chain-insights 0.71.4 → 0.73.2

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 (88) hide show
  1. package/README.md +38 -3
  2. package/dist/buy-97M6dtEu.cjs +195 -0
  3. package/dist/buy-_mpdRieG.mjs +195 -0
  4. package/dist/buy-_mpdRieG.mjs.map +1 -0
  5. package/dist/{capabilities-DGavTSoW.cjs → capabilities-Ds3320iS.cjs} +1 -1
  6. package/dist/{capabilities-BBVDIECk.mjs → capabilities-DxojbX4D.mjs} +2 -2
  7. package/dist/{capabilities-BBVDIECk.mjs.map → capabilities-DxojbX4D.mjs.map} +1 -1
  8. package/dist/{claude-desktop-CTaBCUIm.mjs → claude-desktop-6jwX0Lux.mjs} +18 -3
  9. package/dist/{claude-desktop-CTaBCUIm.mjs.map → claude-desktop-6jwX0Lux.mjs.map} +1 -1
  10. package/dist/{claude-desktop-BI_mGkZ6.cjs → claude-desktop-Jmm4PlBZ.cjs} +17 -2
  11. package/dist/cli.cjs +163 -31
  12. package/dist/cli.mjs +163 -31
  13. package/dist/cli.mjs.map +1 -1
  14. package/dist/{client-gsLi528K.mjs → client-7qOfAdpH.mjs} +31 -12
  15. package/dist/client-7qOfAdpH.mjs.map +1 -0
  16. package/dist/{client-Ypw9BNbn.cjs → client-C9uwHnBS.cjs} +33 -14
  17. package/dist/{dex-registry-KOTJhAQf.cjs → dex-registry-Chs79Ukc.cjs} +11 -8
  18. package/dist/{dex-registry-05wAhSa0.mjs → dex-registry-rziydXYq.mjs} +12 -9
  19. package/dist/{dex-registry-05wAhSa0.mjs.map → dex-registry-rziydXYq.mjs.map} +1 -1
  20. package/dist/{dex-tool-B4T8Czhm.cjs → dex-tool-DLWnff1n.cjs} +6 -4
  21. package/dist/{dex-tool-B5Qwz1Zd.mjs → dex-tool-DsaAIa-a.mjs} +7 -5
  22. package/dist/{dex-tool-B5Qwz1Zd.mjs.map → dex-tool-DsaAIa-a.mjs.map} +1 -1
  23. package/dist/{graph-schema-BoUMa03H.cjs → graph-schema-BGbJumCY.cjs} +63 -25
  24. package/dist/{graph-schema-DqZUTnP0.mjs → graph-schema-ClqjzgrM.mjs} +59 -27
  25. package/dist/{graph-schema-DqZUTnP0.mjs.map → graph-schema-ClqjzgrM.mjs.map} +1 -1
  26. package/dist/index.cjs +5 -5
  27. package/dist/index.d.cts +7 -0
  28. package/dist/index.d.cts.map +1 -1
  29. package/dist/index.d.mts +7 -0
  30. package/dist/index.d.mts.map +1 -1
  31. package/dist/index.mjs +5 -5
  32. package/dist/known-keys-B87ZqOgE.mjs +78 -0
  33. package/dist/known-keys-B87ZqOgE.mjs.map +1 -0
  34. package/dist/known-keys-PKZF5GYd.cjs +99 -0
  35. package/dist/mcp-proxy.cjs +86 -39
  36. package/dist/mcp-proxy.d.cts.map +1 -1
  37. package/dist/mcp-proxy.d.mts.map +1 -1
  38. package/dist/mcp-proxy.mjs +86 -39
  39. package/dist/mcp-proxy.mjs.map +1 -1
  40. package/dist/{public-tools-Dj130EuJ.cjs → public-tools-Bl_l_rKK.cjs} +8 -5
  41. package/dist/{public-tools-B77ZT0jt.mjs → public-tools-CQjGt7_q.mjs} +9 -6
  42. package/dist/{public-tools-B77ZT0jt.mjs.map → public-tools-CQjGt7_q.mjs.map} +1 -1
  43. package/dist/quote-B9sYNOiv.cjs +70 -0
  44. package/dist/quote-DfTut0cx.mjs +68 -0
  45. package/dist/quote-DfTut0cx.mjs.map +1 -0
  46. package/dist/robinhood-CCTMagwM.mjs +226 -0
  47. package/dist/robinhood-CCTMagwM.mjs.map +1 -0
  48. package/dist/robinhood-ChiT69sc.cjs +313 -0
  49. package/dist/rules-BD-cNHMX.cjs +31 -0
  50. package/dist/rules-BWdbOtHi.mjs +10 -0
  51. package/dist/rules-BWdbOtHi.mjs.map +1 -0
  52. package/dist/{schema-cache-DwddPLcY.cjs → schema-cache-C7v9ml6S.cjs} +1 -1
  53. package/dist/{schema-cache-BT-kHy_r.mjs → schema-cache-DRObKUvS.mjs} +3 -3
  54. package/dist/{schema-cache-BT-kHy_r.mjs.map → schema-cache-DRObKUvS.mjs.map} +1 -1
  55. package/dist/{skill-refresh-FXhQpW94.cjs → skill-refresh-Be2D5FrX.cjs} +2 -2
  56. package/dist/{skill-refresh-I5MSULwP.mjs → skill-refresh-xYWZ_hua.mjs} +3 -3
  57. package/dist/{skill-refresh-I5MSULwP.mjs.map → skill-refresh-xYWZ_hua.mjs.map} +1 -1
  58. package/dist/subscription-status-9tMfD90J.cjs +168 -0
  59. package/dist/subscription-status-DIuH84fM.mjs +148 -0
  60. package/dist/subscription-status-DIuH84fM.mjs.map +1 -0
  61. package/dist/{tools-BHfphgy9.cjs → tools-Cmnq7yip.cjs} +21 -4
  62. package/dist/{tools-BnThuvE2.mjs → tools-D9ep9E7Q.mjs} +22 -5
  63. package/dist/tools-D9ep9E7Q.mjs.map +1 -0
  64. package/dist/topup--nWtDnWP.cjs +43 -0
  65. package/dist/topup-CfFe1bGS.mjs +45 -0
  66. package/dist/topup-CfFe1bGS.mjs.map +1 -0
  67. package/dist/{topup-server-DzeM_YAt.mjs → topup-server-B0VKHslr.mjs} +2 -2
  68. package/dist/{topup-server-DzeM_YAt.mjs.map → topup-server-B0VKHslr.mjs.map} +1 -1
  69. package/dist/{topup-server-BIbSfvX5.cjs → topup-server-BkGM8P99.cjs} +1 -1
  70. package/dist/{topup-server-Bh7MlzRt.cjs → topup-server-C58eWflv.cjs} +284 -69
  71. package/dist/{topup-server-BrkPhqJG.mjs → topup-server-RQ6-c92F.mjs} +274 -71
  72. package/dist/topup-server-RQ6-c92F.mjs.map +1 -0
  73. package/dist/{wallet-B3hAr70M.cjs → wallet-CgIAfdxL.cjs} +34 -0
  74. package/dist/{wallet-GNDl3FkR.mjs → wallet-QTo5YCFR.mjs} +35 -1
  75. package/dist/wallet-QTo5YCFR.mjs.map +1 -0
  76. package/docs/development.md +1 -1
  77. package/docs/graph-tools.md +2 -1
  78. package/docs/mcp-proxy.md +30 -4
  79. package/docs/stability.md +3 -2
  80. package/package.json +1 -1
  81. package/skills/chain-insights-cypher/SKILL.md +9 -0
  82. package/dist/client-gsLi528K.mjs.map +0 -1
  83. package/dist/subscription-status-DA9DCFrC.mjs +0 -32
  84. package/dist/subscription-status-DA9DCFrC.mjs.map +0 -1
  85. package/dist/subscription-status-ru99UCPZ.cjs +0 -40
  86. package/dist/tools-BnThuvE2.mjs.map +0 -1
  87. package/dist/topup-server-BrkPhqJG.mjs.map +0 -1
  88. package/dist/wallet-GNDl3FkR.mjs.map +0 -1
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":[],"sources":["../src/investigation/workflows.ts","../src/cli.ts"],"sourcesContent":["export interface CiaWorkflow {\n name: string\n tool: string\n network: string\n description: string\n command: string\n}\n\nexport const CIA_WORKFLOWS: readonly CiaWorkflow[] = [\n {\n name: 'aml-address-risk',\n tool: 'aml_address_risk',\n network: 'robinhood',\n description: 'Screen one address for AML risk, behavior, and exchange exposure.',\n command: 'cia workflow aml-address-risk',\n },\n]\n\nconst NAME_WIDTH = 22\nconst NETWORK_WIDTH = 12\nconst COMMAND_WIDTH = 34\n\nfunction formatRow(values: string[]): string {\n return [\n values[0]?.padEnd(NAME_WIDTH),\n values[1]?.padEnd(NETWORK_WIDTH),\n values[2]?.padEnd(COMMAND_WIDTH),\n ].join(' ')\n}\n\nexport function formatCiaWorkflows(workflows: readonly CiaWorkflow[]): string {\n if (workflows.length === 0) return 'No CIA workflow tools available.'\n\n const rows = workflows.flatMap((workflow) => [\n formatRow([workflow.name, workflow.network, workflow.command]),\n ` ${workflow.description}`,\n ])\n\n return [\n 'CIA workflow tools',\n '',\n formatRow(['Workflow', 'Network', 'Run with']),\n formatRow(['-'.repeat(NAME_WIDTH), '-'.repeat(NETWORK_WIDTH), '-'.repeat(COMMAND_WIDTH)]),\n ...rows,\n ].join('\\n')\n}\n","import { Command, Option } from 'commander'\nimport { execFileSync } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport path from 'node:path'\nimport { PACKAGE_INFO, PACKAGE_VERSION } from './version.js'\nimport { CIA_WORKFLOWS, formatCiaWorkflows } from './investigation/workflows.js'\nimport { printMcpTextContent } from './mcp/print-result.js'\n\n// Resolve bin/install.cjs relative to this file's location in dist/\nconst __dirname = path.dirname(fileURLToPath(import.meta.url))\nconst installerPath = path.resolve(__dirname, '..', 'bin', 'install.cjs')\n\nconst program = new Command()\n\nfunction createCliCommand(name: string): Command {\n return new Command(name).showHelpAfterError()\n}\n\nprogram\n .name('cia')\n .description('AML investigation toolkit for blockchain analysis')\n .version(PACKAGE_INFO.version)\n .showHelpAfterError()\n .option('--claude', 'Install Claude Code skills globally to ~/.claude/skills/')\n .option('--claude-desktop', 'Register the MCP proxy in Claude Desktop')\n .option('--codex', 'Install Codex skills globally to ~/.codex/skills/ and register MCP')\n .option(\n '--hermes',\n 'Install Hermes skills globally to ~/.hermes/skills/chain-insights/ and register MCP'\n )\n\n// Handle installer flags when invoked with no subcommand (bare `chain-insights --claude`)\nconst rawArgs = process.argv.slice(2)\nconst installerFlags = rawArgs.filter(\n (a) => a === '--claude' || a === '--claude-desktop' || a === '--codex' || a === '--hermes'\n)\n\n// Commander treats the root package `--version` option as global, so it would\n// consume the same flag on the AML workflow command before the child can route\n// a tool contract. Rewrite only the child-command form to a hidden alias. The\n// visible child help still documents `--version`, while root `cia --version`\n// remains the package version.\nfunction normalizeAmlToolVersionArgv(argv: string[]): string[] {\n const commandIndex = rawArgs.findIndex(\n (arg, index) => arg === 'aml-address-risk' && index === 1 && rawArgs[0] === 'workflow'\n )\n if (commandIndex === -1) return argv\n\n return argv.map((arg, index) => {\n const userArgIndex = index - 2\n if (userArgIndex <= commandIndex) return arg\n if (arg === '--version') return '--tool-version'\n if (arg.startsWith('--version=')) return `--tool-version=${arg.slice('--version='.length)}`\n return arg\n })\n}\n// A help/version request must never trigger a global install side effect — let\n// commander handle it and print help/version instead.\nconst wantsHelpOrVersion = rawArgs.some(\n (a) => a === '--help' || a === '-h' || a === '--version' || a === '-V'\n)\nif (installerFlags.length > 0 && !wantsHelpOrVersion && !rawArgs.some((a) => !a.startsWith('-'))) {\n try {\n execFileSync(process.execPath, [installerPath, ...installerFlags], { stdio: 'inherit' })\n } catch (err) {\n console.error('Installation failed:', (err as Error).message)\n process.exit(1)\n }\n process.exit(0)\n}\n\n// Legacy mcp aliases for retired graph tools are not commands; reject them\n// before Commander can mis-parse them. Members are built by concatenation so\n// retired names never appear as literal source strings.\nconst retiredMcpAliases = new Set([['trace', '-funds'].join(''), ['track', '-funds'].join('')])\nif (rawArgs[0] === 'mcp' && retiredMcpAliases.has(rawArgs[1] ?? '')) {\n console.error(`error: unknown command '${rawArgs[1]}'`)\n process.exit(1)\n}\n\nfunction runInstaller(flag: '--claude' | '--claude-desktop' | '--codex' | '--hermes'): void {\n try {\n execFileSync(process.execPath, [installerPath, flag], { stdio: 'inherit' })\n } catch (err) {\n console.error('Installation failed:', (err as Error).message)\n process.exit(1)\n }\n}\n\nasync function withGraphMcpClient<T>(\n name: string,\n fn: (\n client: import('@modelcontextprotocol/sdk/client/index.js').Client,\n config: Awaited<ReturnType<typeof import('./config/index.js').loadConfig>>\n ) => Promise<T>\n): Promise<T> {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n // A dead or wrong endpoint (e.g. a stale `debug` config pointing at a stopped\n // local server) otherwise surfaces as a bare \"fetch failed\"; toGraphMcpEndpointError\n // names the endpoint and the cause, and passes real backend errors through.\n const { toGraphMcpEndpointError } = await import('./mcp/transport-error.js')\n const endpoint = resolveGraphMcpEndpoint(config)\n const paymentFetch = await createConfiguredGraphMcpFetch(config)\n const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')\n const { StreamableHTTPClientTransport } =\n await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name, version: PACKAGE_VERSION })\n try {\n await client.connect(\n new StreamableHTTPClientTransport(new URL(endpoint), {\n fetch: paymentFetch,\n })\n )\n } catch (err) {\n throw toGraphMcpEndpointError(err, endpoint)\n }\n // Every CLI command builds its own client, separate from the MCP proxy's\n // one, so unattended scheduled CLI runs also write to the action log.\n const { installActionLogging } = await import('./mcp/action-log.js')\n installActionLogging(client)\n try {\n return await fn(client, config)\n } catch (err) {\n throw toGraphMcpEndpointError(err, endpoint)\n } finally {\n await client.close()\n }\n}\n\nasync function printNetworkCapabilities(opts: { json?: boolean }): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { fetchNetworkCapabilities, formatNetworkCapabilities } =\n await import('./mcp/capabilities.js')\n const document = await fetchNetworkCapabilities(await loadConfig())\n if (opts.json) {\n console.log(JSON.stringify(document, null, 2))\n } else {\n console.log(formatNetworkCapabilities(document))\n }\n}\n\nasync function printNetworkOverview(opts: { json?: boolean }): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { fetchNetworkCapabilities, formatNetworkOverview } = await import('./mcp/capabilities.js')\n const document = await fetchNetworkCapabilities(await loadConfig())\n if (opts.json) {\n console.log(JSON.stringify(document, null, 2))\n } else {\n console.log(formatNetworkOverview(document))\n }\n}\n\nasync function printNetworkCapability(name: string, opts: { json?: boolean }): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { fetchNetworkCapabilities, findNetworkCapability, formatNetworkCapability } =\n await import('./mcp/capabilities.js')\n const document = await fetchNetworkCapabilities(await loadConfig())\n const network = findNetworkCapability(document, name)\n if (!network) {\n const available = document.networks.map((candidate) => candidate.network).join(', ')\n const suffix = available ? ` Available networks: ${available}.` : ''\n throw new Error(\n `Network \"${name}\" is not supported.${suffix} Run \\`cia networks\\` to list supported networks.`\n )\n }\n if (opts.json) {\n console.log(JSON.stringify(network, null, 2))\n } else {\n console.log(formatNetworkCapability(network))\n }\n}\n\n/**\n * The live graph schema of one network (meta_schema). A fresh cache answers with\n * no request; a build opens one session and reads through it.\n */\nasync function printNetworkSchema(\n name: string,\n opts: { json?: boolean; refresh?: boolean }\n): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n const { formatGraphSchemaText, getGraphSchema } = await import('./mcp/graph-schema.js')\n const config = await loadConfig()\n const schema = await getGraphSchema({\n network: name,\n refresh: opts.refresh === true,\n endpoint: resolveGraphMcpEndpoint(config),\n withClient: (fn) => withGraphMcpClient('chain-insights-cli-schema', (client) => fn(client)),\n })\n console.log(opts.json ? JSON.stringify(schema, null, 2) : formatGraphSchemaText(schema))\n}\n\nfunction addAmlAddressRiskCommand(parent: Command, networksCommand: string): void {\n parent.addCommand(\n createCliCommand('aml-address-risk')\n .description(\n 'CIA workflow: screen an address for AML risk, exchange behavior, and optional comparison with another address'\n )\n .requiredOption('--address <address>', 'Full blockchain address to screen')\n .requiredOption(\n '--network <network>',\n `Network to query. Run \\`${networksCommand}\\` for supported networks.`\n )\n .option(\n '--compare-address <address>',\n 'Optional second address to compare against the screened address'\n )\n .option('--json', 'Print machine-readable JSON output')\n .option(\n '--version <version>',\n 'AML tool contract version. Omit to use the latest version (currently v1)'\n )\n .addOption(\n new Option('--tool-version <version>', 'Internal alias for the AML tool version').hideHelp()\n )\n .action(\n async (opts: {\n address: string\n network: string\n compareAddress?: string\n json?: boolean\n version?: string\n toolVersion?: string\n }) => {\n try {\n const { resolveAmlAddressRiskVersion } = await import('./investigation/public-tools.js')\n const requestedVersion = opts.toolVersion ?? opts.version\n resolveAmlAddressRiskVersion(requestedVersion)\n await withGraphMcpClient('chain-insights-cli-aml-address-risk', async (client) => {\n const { runAmlAddressRisk } = await import('./investigation/public-tools.js')\n const result = await runAmlAddressRisk(\n client,\n {\n address: opts.address,\n network: opts.network,\n compareAddress: opts.compareAddress,\n },\n requestedVersion\n )\n console.log(\n opts.json ? JSON.stringify(result.structuredContent, null, 2) : result.summaryText\n )\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n }\n )\n )\n}\n\nprogram\n .command('networks')\n .description('Show supported network status and dataset overview')\n .option('--json', 'Print raw capability JSON')\n .action(async (opts: { json?: boolean }) => {\n try {\n await printNetworkOverview(opts)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram\n .command('network')\n .description('Show details for one supported graph network')\n .argument('<name>', 'Network identifier or display name (for example: robinhood)')\n .option('--json', 'Print raw capability JSON for this network (with --schema: the schema JSON)')\n .option(\n '--schema',\n 'Show the live graph schema: labels, link types, fields and indexes (cached for 24 hours)'\n )\n .option('--refresh', 'With --schema: rebuild the schema now instead of reading the cache')\n .action(async (name: string, opts: { json?: boolean; schema?: boolean; refresh?: boolean }) => {\n try {\n if (opts.refresh && !opts.schema) {\n throw new Error('--refresh needs --schema: run `cia network <name> --schema --refresh`.')\n }\n if (opts.schema) {\n await printNetworkSchema(name, opts)\n } else {\n await printNetworkCapability(name, opts)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram\n .command('workflows')\n .description('List CIA workflow tools')\n .option('--json', 'Print the workflow catalog as JSON')\n .action((opts: { json?: boolean }) => {\n if (opts.json) {\n console.log(JSON.stringify(CIA_WORKFLOWS, null, 2))\n return\n }\n console.log(formatCiaWorkflows(CIA_WORKFLOWS))\n })\n\nconst workflowCommand = program.command('workflow').description('Run a high-level CIA workflow')\n\naddAmlAddressRiskCommand(workflowCommand, 'cia networks')\n\nprogram\n .command('status')\n .description('Show toolkit status and configuration')\n .action(async () => {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n const graphMcpStatus =\n config.graphMcpMode === 'debug' && config.graphMcpAuthToken?.trim()\n ? 'bearer access mode'\n : `${config.graphMcpMode} mode`\n console.log('Config: ', config.dataDir)\n console.log('Chain Insights Graph:', graphMcpStatus)\n console.log('Graph endpoint:', config.graphMcpEndpoint)\n })\n\nprogram\n .command('update')\n .description('Check npmjs for a newer Chain Insights release and update this CLI')\n .option('--check', 'Only check for a newer release')\n .option('--dry-run', 'Print the update command without running it')\n .action(async (opts: { check?: boolean; dryRun?: boolean }) => {\n try {\n const { checkForUpdate, runPackageUpdate } = await import('./update.js')\n const result = await checkForUpdate()\n if (result.error) {\n throw new Error(`Could not check npmjs for updates: ${result.error}`)\n }\n if (!result.updateAvailable || !result.latestVersion) {\n console.log(`Chain Insights is up to date (${result.currentVersion}).`)\n return\n }\n\n console.log(\n `Chain Insights ${result.latestVersion} is available (current ${result.currentVersion}).`\n )\n if (opts.check) {\n console.log(`Run: ${result.updateCommand}`)\n return\n }\n if (opts.dryRun) {\n console.log(`Would run: ${result.updateCommand}`)\n return\n }\n\n console.log(`Running: ${result.updateCommand}`)\n runPackageUpdate(result.packageName)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram\n .command('debug')\n .description('Configure Chain Insights Graph debug mode')\n .addCommand(\n createCliCommand('on')\n .description('Enable Chain Insights Graph debug mode without x402 payments')\n .requiredOption('--token <token>', 'Debug bearer token')\n .option('--endpoint <url>', 'Chain Insights Graph endpoint')\n .action(async (opts: { token: string; endpoint?: string }) => {\n try {\n const { saveConfig } = await import('./config/index.js')\n await saveConfig({\n graphMcpMode: 'debug',\n graphMcpAuthToken: opts.token,\n ...(opts.endpoint ? { graphMcpEndpoint: opts.endpoint } : {}),\n })\n console.log('Chain Insights Graph debug mode enabled')\n if (opts.endpoint) console.log(`Graph endpoint: ${opts.endpoint}`)\n console.log('Payments: disabled for Chain Insights Graph calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('off')\n .description('Disable Chain Insights Graph debug mode and use paid x402 calls')\n .action(async () => {\n try {\n const { saveConfig } = await import('./config/index.js')\n await saveConfig({ graphMcpMode: 'paid', graphMcpAuthToken: '' })\n console.log('Chain Insights Graph debug mode disabled')\n console.log('Payments: enabled for Chain Insights Graph calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('status')\n .description('Show Chain Insights Graph payment/debug mode')\n .action(async () => {\n try {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n console.log(`Chain Insights Graph mode: ${config.graphMcpMode}`)\n console.log(`Graph endpoint: ${config.graphMcpEndpoint}`)\n console.log(\n `Debug token: ${config.graphMcpAuthToken?.trim() ? 'configured' : 'not configured'}`\n )\n console.log(`Payments: ${config.graphMcpMode === 'debug' ? 'disabled' : 'enabled'}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('access-key')\n .description('Configure Chain Insights Graph test access key mode')\n .addCommand(\n createCliCommand('set')\n .description('Use a Chain Insights Graph test access key without x402 payments')\n .argument('<key>', 'Test access key')\n .option('--endpoint <url>', 'Chain Insights Graph endpoint')\n .action(async (key: string, opts: { endpoint?: string }) => {\n try {\n const normalizedKey = key.trim()\n if (!normalizedKey) throw new Error('Test access key is required')\n const { saveConfig } = await import('./config/index.js')\n await saveConfig({\n graphMcpMode: 'debug',\n graphMcpAuthToken: normalizedKey,\n ...(opts.endpoint ? { graphMcpEndpoint: opts.endpoint } : {}),\n })\n console.log('Chain Insights Graph test access key configured')\n if (opts.endpoint) console.log(`Graph endpoint: ${opts.endpoint}`)\n console.log('Payments: disabled when the server accepts this key')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('clear')\n .description('Remove the Chain Insights Graph test access key and use paid x402 calls')\n .action(async () => {\n try {\n const { saveConfig } = await import('./config/index.js')\n await saveConfig({ graphMcpMode: 'paid', graphMcpAuthToken: '' })\n console.log('Chain Insights Graph test access key cleared')\n console.log('Payments: enabled for Chain Insights Graph calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('status')\n .description('Show Chain Insights Graph test access key status')\n .action(async () => {\n try {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n console.log(`Graph endpoint: ${config.graphMcpEndpoint}`)\n console.log(\n `Access key: ${config.graphMcpAuthToken?.trim() ? 'configured' : 'not configured'}`\n )\n console.log(\n `Payments: ${config.graphMcpAuthToken?.trim() ? 'disabled when accepted by server' : 'enabled'}`\n )\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('setup')\n .description('Configure external MCP clients')\n .addCommand(\n createCliCommand('claude-code')\n .alias('claude')\n .description('Install Claude Code skills and register the MCP proxy')\n .action(() => {\n runInstaller('--claude')\n })\n )\n .addCommand(\n createCliCommand('claude-desktop')\n .description('Register the MCP proxy in Claude Desktop, which draws the money-flow views')\n .action(() => {\n runInstaller('--claude-desktop')\n })\n )\n .addCommand(\n createCliCommand('codex')\n .description('Install Codex skills and register the MCP proxy')\n .action(() => {\n runInstaller('--codex')\n })\n )\n .addCommand(\n createCliCommand('chatgpt')\n .description('Set up the ChatGPT desktop app: its Codex chats run Chain Insights')\n .action(() => {\n runInstaller('--codex')\n // The ChatGPT chat itself runs in the cloud and cannot reach a server on\n // this computer. Only the app's Codex chats can.\n console.log(\n '\\n In the ChatGPT app, ask in a Codex chat (Codex in the sidebar), not in a ChatGPT chat.\\n'\n )\n })\n )\n .addCommand(\n createCliCommand('hermes')\n .description('Install Hermes skills and register the MCP proxy')\n .action(() => {\n runInstaller('--hermes')\n })\n )\n\nprogram\n .command('config')\n .description('Read or write configuration values')\n .addCommand(\n createCliCommand('get')\n .description('Read one Chain Insights configuration value')\n .argument('<key>', 'Config key to read')\n .action(async (key: string) => {\n const { loadConfig } = await import('./config/index.js')\n const { CONFIG_KEYS } = await import('./config/schema.js')\n if (!CONFIG_KEYS.includes(key as (typeof CONFIG_KEYS)[number])) {\n console.error(`Unknown config key: ${key}`)\n process.exit(1)\n }\n const config = await loadConfig()\n const value = (config as Record<string, unknown>)[key]\n console.log(value ?? '')\n })\n )\n .addCommand(\n createCliCommand('reset')\n .description(\n 'Put every setting back to its default (production endpoint, paid mode, no test key); the wallet stays'\n )\n .action(async () => {\n try {\n const { resetConfig, loadConfig } = await import('./config/index.js')\n const { backupPath } = await resetConfig()\n const config = await loadConfig()\n if (backupPath) console.log(`Previous settings saved to ${backupPath}`)\n console.log('Settings reset to defaults.')\n console.log(`Graph endpoint: ${config.graphMcpEndpoint}`)\n console.log(`Mode: ${config.graphMcpMode}`)\n console.log('Test access: off')\n console.log('Wallet: unchanged (~/.chain-insights/wallet.json)')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('set')\n .description('Write one Chain Insights configuration value')\n .argument('<key>', 'Config key to write')\n .argument('<value>', 'Value to set')\n .action(async (key: string, value: string) => {\n // D-01: walletPrivateKey is intercepted before saveConfig — the raw private key\n // must NEVER be written to config.json.\n if (key === 'walletPrivateKey') {\n try {\n const { setWalletPrivateKey } = await import('./wallet/index.js')\n const address = await setWalletPrivateKey(value)\n console.log('Wallet private key encrypted and stored in ~/.chain-insights/wallet.json')\n console.log(`Wallet address: ${address}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n return // MUST return — walletPrivateKey must never reach saveConfig or config.json\n }\n const { loadConfig, saveConfig } = await import('./config/index.js')\n const { CONFIG_KEYS, DEFAULT_CONFIG } = await import('./config/schema.js')\n const current = await loadConfig()\n if (!CONFIG_KEYS.includes(key as (typeof CONFIG_KEYS)[number])) {\n console.error(`Unknown config key: ${key}`)\n process.exit(1)\n }\n const existing = (current as Record<string, unknown>)[key]\n const defaultValue = (DEFAULT_CONFIG as Record<string, unknown>)[key]\n const coerced =\n typeof existing === 'number' || typeof defaultValue === 'number' ? Number(value) : value\n await saveConfig({ [key]: coerced } as Parameters<typeof saveConfig>[0])\n const displayed = key.toLowerCase().includes('token') ? '[redacted]' : coerced\n console.log(`Set ${key} = ${displayed}`)\n })\n )\n\nprogram\n .command('wallet')\n .description('Manage the local Base USDC payment wallet')\n .addCommand(\n createCliCommand('create')\n .description('Generate a new local Base payment wallet')\n .action(async () => {\n try {\n const { isWalletConfigured, setWalletPrivateKey, walletPath } =\n await import('./wallet/index.js')\n const { createInterface } = await import('node:readline/promises')\n const { formatWalletBackupWarning, generateWalletPrivateKey, isWalletBackupConfirmed } =\n await import('./wallet/create.js')\n\n if (await isWalletConfigured()) {\n throw new Error(\n 'A payment wallet already exists. Run `cia wallet address` to view it or use `cia wallet import <private-key> --force` to replace it.'\n )\n }\n\n const privateKey = generateWalletPrivateKey()\n const color = process.stderr.isTTY === true && process.env['NO_COLOR'] === undefined\n process.stderr.write(`${formatWalletBackupWarning(privateKey, { color })}\\n`)\n const prompt = createInterface({ input: process.stdin, output: process.stderr })\n let answer: string\n try {\n answer = await prompt.question('> ')\n } finally {\n prompt.close()\n }\n process.stderr.write('\\n')\n if (!isWalletBackupConfirmed(answer)) {\n throw new Error('Wallet creation cancelled. The wallet was not saved.')\n }\n\n const address = await setWalletPrivateKey(privateKey)\n console.log(`Wallet created: ${address}`)\n console.log(`Encrypted local copy: ${walletPath()}`)\n console.log('Next: cia wallet ready')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('import')\n .description('Import a Base payment wallet')\n .argument('<private-key>', '0x-prefixed EVM private key')\n .option(\n '--force',\n 'Replace an existing wallet (the previous key is backed up next to wallet.json)'\n )\n .action(async (privateKey: string, opts: { force?: boolean }) => {\n try {\n const { setWalletPrivateKey, isWalletConfigured } = await import('./wallet/index.js')\n const replacing = opts.force === true && (await isWalletConfigured())\n const address = await setWalletPrivateKey(privateKey, { force: opts.force })\n if (replacing) {\n console.log('Previous wallet key backed up next to ~/.chain-insights/wallet.json')\n }\n console.log(`Wallet imported: ${address}`)\n console.log(\n 'Keep your original private key backed up securely; it cannot be recovered from the encrypted local copy.'\n )\n console.log('Encrypted local copy: ~/.chain-insights/wallet.json')\n console.log('Next: cia wallet ready')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('address')\n .description('Print the local payment wallet address')\n .action(async () => {\n try {\n const { getWalletAccount } = await import('./wallet/tools.js')\n const account = await getWalletAccount()\n console.log(account.address)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('balance')\n .description('Show the local payment wallet Base USDC balance')\n .action(async () => {\n try {\n const { getWalletBalanceText } = await import('./wallet/tools.js')\n console.log(await getWalletBalanceText())\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('ready')\n .description('Check and prepare the wallet for paid Chain Insights Graph calls')\n .option('--check-only', 'Only check readiness; do not submit the one-time payment setup')\n .addOption(new Option('--no-approve', 'Deprecated alias for --check-only').hideHelp())\n .option('--payment-usdc <amount>', 'USDC setup cap to prepare for paid calls', '1')\n .addOption(\n new Option('--approval-usdc <amount>', 'Deprecated alias for --payment-usdc').hideHelp()\n )\n .option('--json', 'Print machine-readable readiness metadata')\n .action(\n async (opts: {\n checkOnly?: boolean\n approve?: boolean\n paymentUsdc?: string\n approvalUsdc?: string\n json?: boolean\n }) => {\n try {\n const { formatWalletReadiness, parsePaymentApprovalUnits, prepareWalletForPaidCalls } =\n await import('./wallet/tools.js')\n const minimumApprovalUnits = parsePaymentApprovalUnits(\n opts.paymentUsdc ?? opts.approvalUsdc ?? '1'\n )\n const result = await prepareWalletForPaidCalls({\n minimumApprovalUnits,\n approve: opts.checkOnly ? false : opts.approve !== false,\n })\n\n if (opts.json) {\n console.log(\n JSON.stringify(\n result,\n (_key, value) => (typeof value === 'bigint' ? value.toString() : value),\n 2\n )\n )\n return\n }\n\n console.log(formatWalletReadiness(result.readiness, result.approval))\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n }\n )\n )\n .addCommand(\n createCliCommand('topup')\n .description('Open a local browser page to top up the payment wallet')\n .option('--no-open', 'Print the top-up URL without opening a browser')\n .option('--json', 'Print machine-readable top-up metadata')\n .action(async (opts: { open?: boolean; json?: boolean }) => {\n try {\n const { buildTopupInfo, getWalletAccount } = await import('./wallet/tools.js')\n const { startTopupServer } = await import('./wallet/topup-server.js')\n const account = await getWalletAccount()\n const url = await startTopupServer(account)\n const info = buildTopupInfo(account.address, url)\n\n if (opts.json) {\n console.log(JSON.stringify(info, null, 2))\n } else {\n console.log(`Top-up URL: ${url}`)\n console.log(`Wallet: ${account.address}`)\n console.log('Network: Base')\n console.log('Token: USDC')\n console.log('Press Ctrl+C to stop the top-up server.')\n }\n\n if (opts.open !== false) {\n const open = (await import('open')).default\n await open(url)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nconst mcpCommand = program\n .command('mcp')\n .description('Low-level access to the Chain Insights MCP endpoint')\n .allowExcessArguments(false)\n .addCommand(\n createCliCommand('networks')\n .description('List the detailed Chain Insights capability matrix and tool support')\n .option('--json', 'Print raw capability JSON')\n .action(async (opts: { json?: boolean }) => {\n try {\n await printNetworkCapabilities(opts)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('tools')\n .description('List the remote GraphRAG MCP tools (cached for 24 hours)')\n .option('--refresh', 'Force refresh schema cache')\n .action(async (opts: { refresh?: boolean }) => {\n try {\n const { loadSchema, saveSchema } = await import('./mcp/schema-cache.js')\n const { formatToolsTable } = await import('./mcp/format.js')\n const { visibleRemoteTools } = await import('./mcp/tool-visibility.js')\n const { loadConfig } = await import('./config/index.js')\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } =\n await import('./mcp/client.js')\n const config = await loadConfig()\n const graphMcpEndpoint = resolveGraphMcpEndpoint(config)\n let tools = opts.refresh ? null : await loadSchema(graphMcpEndpoint)\n if (!tools) {\n const paymentFetch = await createConfiguredGraphMcpFetch(config)\n const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')\n const { StreamableHTTPClientTransport } =\n await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name: 'chain-insights-cli', version: PACKAGE_VERSION })\n await client.connect(\n new StreamableHTTPClientTransport(new URL(graphMcpEndpoint), { fetch: paymentFetch })\n )\n try {\n const result = await client.listTools()\n tools = result.tools as Array<{ name: string; description?: string }>\n await saveSchema(tools, graphMcpEndpoint)\n } finally {\n await client.close()\n }\n }\n console.log(formatToolsTable(visibleRemoteTools(tools)))\n // The local tool doors the proxy serves beside the remote tools.\n const { META_DEX_LOOKUP_DESCRIPTION, META_DEX_LOOKUP_TITLE, META_DEX_LOOKUP_TOOL } =\n await import('./mcp/dex-tool.js')\n console.log('')\n console.log(\n formatToolsTable(\n [{ name: META_DEX_LOOKUP_TOOL, description: `${META_DEX_LOOKUP_TITLE}. ${META_DEX_LOOKUP_DESCRIPTION}` }],\n 'Local proxy tool'\n )\n )\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nmcpCommand.addCommand(\n createCliCommand('call')\n .description('Call a low-level MCP tool directly (advanced)')\n .option('--json', 'Print machine-readable JSON output')\n .argument('<tool>', 'Tool name to call')\n .argument('[args...]', 'Key=value arguments (e.g. address=0x1234... network=robinhood)')\n .action(async (tool: string, rawArgs: string[], opts: { json?: boolean }) => {\n try {\n const { parseMcpCallArgs } = await import('./mcp/call-args.js')\n const { assertPublicMcpToolName, validatePublicMcpToolArguments } =\n await import('./mcp/tool-visibility.js')\n let args = parseMcpCallArgs(rawArgs)\n assertPublicMcpToolName(tool)\n validatePublicMcpToolArguments(tool, args)\n\n if (tool === 'wallet_balance') {\n const { getWalletBalanceText } = await import('./wallet/tools.js')\n console.log(await getWalletBalanceText())\n return\n }\n\n if (tool === 'meta_network_capabilities') {\n await printNetworkCapabilities({ json: opts.json })\n return\n }\n\n if (tool === 'meta_schema') {\n await printNetworkSchema(String(args['network'] ?? ''), {\n json: opts.json,\n refresh: String(args['refresh'] ?? '').toLowerCase() === 'true',\n })\n return\n }\n\n if (tool === 'meta_dex_lookup') {\n // The proxy's local tool, run here with the CLI's own graph session.\n const { handleMetaDexLookup } = await import('./mcp/dex-tool.js')\n const { loadRegistry } = await import('./mcp/dex-registry.js')\n const { metaDexLookupArgs } = await import('./mcp/call-args.js')\n const result = await withGraphMcpClient('chain-insights-cli-dex-lookup', (client) =>\n handleMetaDexLookup(\n metaDexLookupArgs(args),\n {\n loadRegistry: (network) => loadRegistry(network),\n graphQueryBatch: async (batchArgs) =>\n (await client.callTool({ name: 'graph_query_batch', arguments: batchArgs })) as {\n content?: unknown[]\n structuredContent?: unknown\n isError?: boolean\n },\n describeFailure: (err) => (err as Error).message,\n }\n )\n )\n console.log(result.content[0]?.text ?? '')\n if (result.isError) process.exitCode = 1\n return\n }\n\n if (tool === 'graph_expand') {\n throw new Error(\n 'graph_expand is used only by the Chain Insights view in Claude. Run `cia mcp call graph_query` with your own query instead.'\n )\n }\n\n if (tool === 'meta_help') {\n console.log(\n 'Graph tools: graph_query and graph_query_batch. Metadata and payment tools: meta_* and wallet_balance.'\n )\n return\n }\n\n await withGraphMcpClient('chain-insights-cli-call', async (client, config) => {\n if (tool === 'meta_usage_status') {\n try {\n const result = await client.callTool({ name: 'usage_status', arguments: {} })\n printMcpTextContent(\n result as { content?: Array<{ type: string; text?: string }>; isError?: boolean },\n { tool, json: opts.json }\n )\n } catch (err) {\n const {\n isMissingUsageStatusToolError,\n primitiveBackendUsageStatus,\n usageStatusText,\n } = await import('./mcp/usage-status.js')\n if (!isMissingUsageStatusToolError(err)) throw err\n const { resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n console.log(\n usageStatusText(primitiveBackendUsageStatus(resolveGraphMcpEndpoint(config)))\n )\n }\n return\n }\n if (tool === 'meta_subscription_status') {\n try {\n const { getWalletAccount } = await import('./wallet/tools.js')\n const account = await getWalletAccount()\n const result = await client.callTool({\n name: 'subscription_status',\n arguments: { wallet: account.address },\n })\n printMcpTextContent(\n result as { content?: Array<{ type: string; text?: string }>; isError?: boolean },\n { tool, json: opts.json }\n )\n } catch (err) {\n const {\n isMissingSubscriptionStatusToolError,\n unavailableSubscriptionStatus,\n subscriptionStatusText,\n } = await import('./mcp/subscription-status.js')\n if (!isMissingSubscriptionStatusToolError(err)) throw err\n const { resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n console.log(\n subscriptionStatusText(\n unavailableSubscriptionStatus(\n resolveGraphMcpEndpoint(config),\n `subscription_status failed: ${(err as Error).message}`\n )\n )\n )\n }\n return\n }\n // graph_query and graph_query_batch can run past the SDK's 60 s default\n // while the server is still answering. Other tools keep that default.\n const { graphToolRequestOptions } = await import('./mcp/request-timeout.js')\n const requestOptions = graphToolRequestOptions(tool)\n // A query that names a twin as a property (a.balance_eth, f.last_seen_timestamp_utc)\n // is rewritten to the column the server has, as the proxy does (src/mcp/timestamp-text.ts).\n const { withoutUtcProperties } = await import('./mcp/timestamp-text.js')\n args = withoutUtcProperties(tool, args)\n const result = requestOptions\n ? await client.callTool({ name: tool, arguments: args }, undefined, requestOptions)\n : await client.callTool({ name: tool, arguments: args })\n printMcpTextContent(\n result as { content?: Array<{ type: string; text?: string }>; isError?: boolean },\n { tool, json: opts.json }\n )\n })\n } catch (err) {\n const { formatMcpCallError } = await import('./mcp/tool-visibility.js')\n console.error(formatMcpCallError(tool, err))\n process.exit(1)\n }\n })\n)\n\n// parseAsync (not parse) so a rejected async action surfaces as a clean\n// one-line error and a non-zero exit, instead of an unhandled-rejection stack\n// trace. Commands with their own try/catch still exit(1) before this fires.\nprogram.parseAsync(normalizeAmlToolVersionArgv(process.argv)).catch((err) => {\n console.error((err as Error).message)\n process.exit(1)\n})\n"],"mappings":";;;;;;AAQA,MAAa,gBAAwC,CACnD;CACE,MAAM;CACN,MAAM;CACN,SAAS;CACT,aAAa;CACb,SAAS;AACX,CACF;AAEA,MAAM,aAAa;AACnB,MAAM,gBAAgB;AACtB,MAAM,gBAAgB;AAEtB,SAAS,UAAU,QAA0B;CAC3C,OAAO;EACL,OAAO,EAAE,EAAE,OAAO,UAAU;EAC5B,OAAO,EAAE,EAAE,OAAO,aAAa;EAC/B,OAAO,EAAE,EAAE,OAAO,a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IACF,SAAS,KAAK;KACZ,MAAM,EACJ,sCACA,+BACA,2BACE,MAAM,OAAO,qCAA+B,CAAA,MAAA,MAAA,EAAA,CAAA;KAChD,IAAI,CAAC,qCAAqC,GAAG,GAAG,MAAM;KACtD,MAAM,EAAE,4BAA4B,MAAM,OAAO,wBAAkB,CAAA,MAAA,MAAA,EAAA,CAAA;KACnE,QAAQ,IACN,uBACE,8BACE,wBAAwB,MAAM,GAC9B,+BAAgC,IAAc,SAChD,CACF,CACF;IACF;IACA;GACF;GAGA,MAAM,EAAE,4BAA4B,MAAM,OAAO;GACjD,MAAM,iBAAiB,wBAAwB,IAAI;GAGnD,MAAM,EAAE,yBAAyB,MAAM,OAAO,8BAA0B,CAAA,MAAA,MAAA,EAAA,CAAA;GACxE,OAAO,qBAAqB,MAAM,IAAI;GACtC,MAAM,SAAS,iBACX,MAAM,OAAO,SAAS;IAAE,MAAM;IAAM,WAAW;GAAK,GAAG,KAAA,GAAW,cAAc,IAChF,MAAM,OAAO,SAAS;IAAE,MAAM;IAAM,WAAW;GAAK,CAAC;GACzD,oBACE,QACA;IAAE;IAAM,MAAM,KAAK;GAAK,CAC1B;EACF,CAAC;CACH,SAAS,KAAK;EACZ,MAAM,EAAE,uBAAuB,MAAM,OAAO,iCAA2B,CAAA,MAAA,MAAA,EAAA,CAAA;EACvE,QAAQ,MAAM,mBAAmB,MAAM,GAAG,CAAC;EAC3C,QAAQ,KAAK,CAAC;CAChB;AACF,CAAC,CACL;AAKA,QAAQ,WAAW,4BAA4B,QAAQ,IAAI,CAAC,CAAC,CAAC,OAAO,QAAQ;CAC3E,QAAQ,MAAO,IAAc,OAAO;CACpC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"cli.mjs","names":[],"sources":["../src/investigation/workflows.ts","../src/subscription/cli.ts","../src/cli.ts"],"sourcesContent":["export interface CiaWorkflow {\n name: string\n tool: string\n network: string\n description: string\n command: string\n}\n\nexport const CIA_WORKFLOWS: readonly CiaWorkflow[] = [\n {\n name: 'aml-address-risk',\n tool: 'aml_address_risk',\n network: 'robinhood',\n description: 'Screen one address for AML risk, behavior, and exchange exposure.',\n command: 'cia workflow aml-address-risk',\n },\n]\n\nconst NAME_WIDTH = 22\nconst NETWORK_WIDTH = 12\nconst COMMAND_WIDTH = 34\n\nfunction formatRow(values: string[]): string {\n return [\n values[0]?.padEnd(NAME_WIDTH),\n values[1]?.padEnd(NETWORK_WIDTH),\n values[2]?.padEnd(COMMAND_WIDTH),\n ].join(' ')\n}\n\nexport function formatCiaWorkflows(workflows: readonly CiaWorkflow[]): string {\n if (workflows.length === 0) return 'No CIA workflow tools available.'\n\n const rows = workflows.flatMap((workflow) => [\n formatRow([workflow.name, workflow.network, workflow.command]),\n ` ${workflow.description}`,\n ])\n\n return [\n 'CIA workflow tools',\n '',\n formatRow(['Workflow', 'Network', 'Run with']),\n formatRow(['-'.repeat(NAME_WIDTH), '-'.repeat(NETWORK_WIDTH), '-'.repeat(COMMAND_WIDTH)]),\n ...rows,\n ].join('\\n')\n}\n","import type { Command } from 'commander'\nimport { PACKAGE_VERSION } from '../version.js'\nimport type { SubscriptionStatusFacts } from '../mcp/subscription-status.js'\n\n// `cia subscription topup | buy --days N | status`. Registered by src/cli.ts.\n// buy is a terminal command only: no MCP tool can buy.\n\ntype CommandFactory = (name: string) => Command\n\ninterface StatusReader {\n /** The status of the proven wallet, or null when it cannot be read. */\n read(): Promise<SubscriptionStatusFacts | null>\n /** The server's own words when the last read failed. */\n lastError(): string | null\n}\n\n/** One MCP session to the configured graph endpoint, for the status reads. */\nasync function withStatusReader<T>(fn: (reader: StatusReader) => Promise<T>): Promise<T> {\n const { loadConfig } = await import('../config/index.js')\n const config = await loadConfig()\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } = await import('../mcp/client.js')\n const { toGraphMcpEndpointError } = await import('../mcp/transport-error.js')\n const endpoint = resolveGraphMcpEndpoint(config)\n const fetchImpl = await createConfiguredGraphMcpFetch(config)\n const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')\n const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name: 'chain-insights-cli-subscription', version: PACKAGE_VERSION })\n try {\n await client.connect(new StreamableHTTPClientTransport(new URL(endpoint), { fetch: fetchImpl }))\n } catch (err) {\n throw toGraphMcpEndpointError(err, endpoint)\n }\n try {\n const { parseSubscriptionStatusToolResult, subscriptionStatusArguments, subscriptionStatusNeedsWallet } =\n await import('../mcp/subscription-status.js')\n const remote = (await client.listTools()).tools.find((tool) => tool.name === 'subscription_status')\n let wallet: string | null = null\n if (remote && subscriptionStatusNeedsWallet(remote)) {\n const { getWalletAccount } = await import('../wallet/tools.js')\n wallet = (await getWalletAccount()).address\n }\n let lastError: string | null = remote ? null : `${endpoint} serves no subscription_status tool.`\n return await fn({\n async read() {\n if (!remote) return null\n try {\n const result = await client.callTool({\n name: 'subscription_status',\n arguments: subscriptionStatusArguments(remote, wallet),\n })\n const facts = parseSubscriptionStatusToolResult(result)\n if (facts) {\n lastError = null\n return facts\n }\n const text = (result.content as Array<{ type: string; text?: string }> | undefined)?.find(\n (block) => block.type === 'text'\n )?.text\n lastError = text ?? 'The server sent a subscription status this version cannot read.'\n return null\n } catch (err) {\n lastError = (err as Error).message\n return null\n }\n },\n lastError: () => lastError,\n })\n } finally {\n await client.close()\n }\n}\n\nasync function askYes(text: string): Promise<boolean> {\n const { createInterface } = await import('node:readline/promises')\n process.stderr.write(`${text}\\n`)\n const prompt = createInterface({ input: process.stdin, output: process.stderr })\n try {\n return (await prompt.question('Type yes to continue: ')).trim().toLowerCase() === 'yes'\n } finally {\n prompt.close()\n }\n}\n\nfunction fail(err: unknown): never {\n console.error((err as Error).message)\n process.exit(1)\n}\n\nexport function registerSubscriptionCommands(program: Command, command: CommandFactory): void {\n program\n .command('subscription')\n .description('Buy and check the Chain Insights subscription, paid in $CIA on Robinhood Chain')\n .addCommand(\n command('topup')\n .description('Show the wallet address and QR code to fund with $CIA and ETH on Robinhood Chain')\n .option('--no-open', 'Print the top-up page URL without opening a browser')\n .option('--json', 'Print machine-readable top-up facts')\n .action(async (opts: { open?: boolean; json?: boolean }) => {\n try {\n const { runSubscriptionTopup } = await import('./topup.js')\n await runSubscriptionTopup(opts)\n } catch (err) {\n fail(err)\n }\n })\n )\n .addCommand(\n command('buy')\n .description('Buy subscription days: approve and pay $CIA on Robinhood Chain, after your yes')\n .requiredOption('--days <n>', 'Days to buy, a whole number; a wallet holds at most 90 days')\n .option('--yes', 'Skip the typed yes (for a run with no terminal)')\n .option('--json', 'Print the outcome as JSON')\n .action(async (opts: { days: string; yes?: boolean; json?: boolean }) => {\n try {\n const { assertDays, fetchCiaUsdPrice } = await import('./quote.js')\n const { assertConfirmable, executeBuy, formatBuyResult } = await import('./buy.js')\n const days = Number(opts.days)\n assertDays(days)\n assertConfirmable({ stdinIsTTY: process.stdin.isTTY === true, yes: opts.yes === true })\n const { assertWalletKeyNotPublic, getWalletAccount } = await import('../wallet/tools.js')\n const account = await getWalletAccount()\n assertWalletKeyNotPublic(account)\n const result = await withStatusReader((reader) =>\n executeBuy({\n account,\n days,\n readStatus: () => reader.read(),\n fetchPrice: () => fetchCiaUsdPrice(),\n confirm: async (text) => {\n if (opts.yes !== true) return askYes(text)\n process.stderr.write(`${text}\\nConfirmed by --yes.\\n`)\n return true\n },\n log: (line) => process.stderr.write(`${line}\\n`),\n })\n )\n console.log(opts.json ? JSON.stringify(result, null, 2) : formatBuyResult(result))\n } catch (err) {\n fail(err)\n }\n })\n )\n .addCommand(\n command('status')\n .description(\"Show the subscription of this wallet, read by the wallet's proof\")\n .option('--json', 'Print the status facts as JSON')\n .action(async (opts: { json?: boolean }) => {\n try {\n const { formatSubscriptionStatus } = await import('../mcp/subscription-status.js')\n await withStatusReader(async (reader) => {\n const facts = await reader.read()\n if (!facts) throw new Error(`Subscription status unavailable: ${reader.lastError() ?? 'no answer'}`)\n console.log(opts.json ? JSON.stringify(facts, null, 2) : formatSubscriptionStatus(facts))\n })\n } catch (err) {\n fail(err)\n }\n })\n )\n}\n","import { Command, Option } from 'commander'\nimport { execFileSync } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport path from 'node:path'\nimport { PACKAGE_INFO, PACKAGE_VERSION } from './version.js'\nimport { CIA_WORKFLOWS, formatCiaWorkflows } from './investigation/workflows.js'\nimport { printMcpTextContent } from './mcp/print-result.js'\nimport { registerSubscriptionCommands } from './subscription/cli.js'\n\n// Resolve bin/install.cjs relative to this file's location in dist/\nconst __dirname = path.dirname(fileURLToPath(import.meta.url))\nconst installerPath = path.resolve(__dirname, '..', 'bin', 'install.cjs')\n\nconst program = new Command()\n\nfunction createCliCommand(name: string): Command {\n return new Command(name).showHelpAfterError()\n}\n\nprogram\n .name('cia')\n .description('AML investigation toolkit for blockchain analysis')\n .version(PACKAGE_INFO.version)\n .showHelpAfterError()\n .option('--claude', 'Install Claude Code skills globally to ~/.claude/skills/')\n .option('--claude-desktop', 'Register the MCP proxy in Claude Desktop')\n .option('--codex', 'Install Codex skills globally to ~/.codex/skills/ and register MCP')\n .option(\n '--hermes',\n 'Install Hermes skills globally to ~/.hermes/skills/chain-insights/ and register MCP'\n )\n\n// Handle installer flags when invoked with no subcommand (bare `chain-insights --claude`)\nconst rawArgs = process.argv.slice(2)\nconst installerFlags = rawArgs.filter(\n (a) => a === '--claude' || a === '--claude-desktop' || a === '--codex' || a === '--hermes'\n)\n\n// Commander treats the root package `--version` option as global, so it would\n// consume the same flag on the AML workflow command before the child can route\n// a tool contract. Rewrite only the child-command form to a hidden alias. The\n// visible child help still documents `--version`, while root `cia --version`\n// remains the package version.\nfunction normalizeAmlToolVersionArgv(argv: string[]): string[] {\n const commandIndex = rawArgs.findIndex(\n (arg, index) => arg === 'aml-address-risk' && index === 1 && rawArgs[0] === 'workflow'\n )\n if (commandIndex === -1) return argv\n\n return argv.map((arg, index) => {\n const userArgIndex = index - 2\n if (userArgIndex <= commandIndex) return arg\n if (arg === '--version') return '--tool-version'\n if (arg.startsWith('--version=')) return `--tool-version=${arg.slice('--version='.length)}`\n return arg\n })\n}\n// A help/version request must never trigger a global install side effect — let\n// commander handle it and print help/version instead.\nconst wantsHelpOrVersion = rawArgs.some(\n (a) => a === '--help' || a === '-h' || a === '--version' || a === '-V'\n)\nif (installerFlags.length > 0 && !wantsHelpOrVersion && !rawArgs.some((a) => !a.startsWith('-'))) {\n try {\n execFileSync(process.execPath, [installerPath, ...installerFlags], { stdio: 'inherit' })\n } catch (err) {\n console.error('Installation failed:', (err as Error).message)\n process.exit(1)\n }\n process.exit(0)\n}\n\n// Legacy mcp aliases for retired graph tools are not commands; reject them\n// before Commander can mis-parse them. Members are built by concatenation so\n// retired names never appear as literal source strings.\nconst retiredMcpAliases = new Set([['trace', '-funds'].join(''), ['track', '-funds'].join('')])\nif (rawArgs[0] === 'mcp' && retiredMcpAliases.has(rawArgs[1] ?? '')) {\n console.error(`error: unknown command '${rawArgs[1]}'`)\n process.exit(1)\n}\n\nfunction runInstaller(flag: '--claude' | '--claude-desktop' | '--codex' | '--hermes'): void {\n try {\n execFileSync(process.execPath, [installerPath, flag], { stdio: 'inherit' })\n } catch (err) {\n console.error('Installation failed:', (err as Error).message)\n process.exit(1)\n }\n}\n\nasync function withGraphMcpClient<T>(\n name: string,\n fn: (\n client: import('@modelcontextprotocol/sdk/client/index.js').Client,\n config: Awaited<ReturnType<typeof import('./config/index.js').loadConfig>>\n ) => Promise<T>\n): Promise<T> {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n // A dead or wrong endpoint (e.g. a stale `debug` config pointing at a stopped\n // local server) otherwise surfaces as a bare \"fetch failed\"; toGraphMcpEndpointError\n // names the endpoint and the cause, and passes real backend errors through.\n const { toGraphMcpEndpointError } = await import('./mcp/transport-error.js')\n const endpoint = resolveGraphMcpEndpoint(config)\n const paymentFetch = await createConfiguredGraphMcpFetch(config)\n const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')\n const { StreamableHTTPClientTransport } =\n await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name, version: PACKAGE_VERSION })\n try {\n await client.connect(\n new StreamableHTTPClientTransport(new URL(endpoint), {\n fetch: paymentFetch,\n })\n )\n } catch (err) {\n throw toGraphMcpEndpointError(err, endpoint)\n }\n // Every CLI command builds its own client, separate from the MCP proxy's\n // one, so unattended scheduled CLI runs also write to the action log.\n const { installActionLogging } = await import('./mcp/action-log.js')\n installActionLogging(client)\n try {\n return await fn(client, config)\n } catch (err) {\n throw toGraphMcpEndpointError(err, endpoint)\n } finally {\n await client.close()\n }\n}\n\nasync function printNetworkCapabilities(opts: { json?: boolean }): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { fetchNetworkCapabilities, formatNetworkCapabilities } =\n await import('./mcp/capabilities.js')\n const document = await fetchNetworkCapabilities(await loadConfig())\n if (opts.json) {\n console.log(JSON.stringify(document, null, 2))\n } else {\n console.log(formatNetworkCapabilities(document))\n }\n}\n\nasync function printNetworkOverview(opts: { json?: boolean }): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { fetchNetworkCapabilities, formatNetworkOverview } = await import('./mcp/capabilities.js')\n const document = await fetchNetworkCapabilities(await loadConfig())\n if (opts.json) {\n console.log(JSON.stringify(document, null, 2))\n } else {\n console.log(formatNetworkOverview(document))\n }\n}\n\nasync function printNetworkCapability(name: string, opts: { json?: boolean }): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { fetchNetworkCapabilities, findNetworkCapability, formatNetworkCapability } =\n await import('./mcp/capabilities.js')\n const document = await fetchNetworkCapabilities(await loadConfig())\n const network = findNetworkCapability(document, name)\n if (!network) {\n const available = document.networks.map((candidate) => candidate.network).join(', ')\n const suffix = available ? ` Available networks: ${available}.` : ''\n throw new Error(\n `Network \"${name}\" is not supported.${suffix} Run \\`cia networks\\` to list supported networks.`\n )\n }\n if (opts.json) {\n console.log(JSON.stringify(network, null, 2))\n } else {\n console.log(formatNetworkCapability(network))\n }\n}\n\n/**\n * The live graph schema of one network (meta_schema). A fresh cache answers with\n * no request; a build opens one session and reads through it.\n */\nasync function printNetworkSchema(\n name: string,\n opts: { json?: boolean; refresh?: boolean }\n): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n const { formatGraphSchemaText, getGraphSchema } = await import('./mcp/graph-schema.js')\n const config = await loadConfig()\n const schema = await getGraphSchema({\n network: name,\n refresh: opts.refresh === true,\n endpoint: resolveGraphMcpEndpoint(config),\n withClient: (fn) => withGraphMcpClient('chain-insights-cli-schema', (client) => fn(client)),\n })\n console.log(opts.json ? JSON.stringify(schema, null, 2) : formatGraphSchemaText(schema))\n}\n\nfunction addAmlAddressRiskCommand(parent: Command, networksCommand: string): void {\n parent.addCommand(\n createCliCommand('aml-address-risk')\n .description(\n 'CIA workflow: screen an address for AML risk, exchange behavior, and optional comparison with another address'\n )\n .requiredOption('--address <address>', 'Full blockchain address to screen')\n .requiredOption(\n '--network <network>',\n `Network to query. Run \\`${networksCommand}\\` for supported networks.`\n )\n .option(\n '--compare-address <address>',\n 'Optional second address to compare against the screened address'\n )\n .option('--json', 'Print machine-readable JSON output')\n .option(\n '--version <version>',\n 'AML tool contract version. Omit to use the latest version (currently v1)'\n )\n .addOption(\n new Option('--tool-version <version>', 'Internal alias for the AML tool version').hideHelp()\n )\n .action(\n async (opts: {\n address: string\n network: string\n compareAddress?: string\n json?: boolean\n version?: string\n toolVersion?: string\n }) => {\n try {\n const { resolveAmlAddressRiskVersion } = await import('./investigation/public-tools.js')\n const requestedVersion = opts.toolVersion ?? opts.version\n resolveAmlAddressRiskVersion(requestedVersion)\n await withGraphMcpClient('chain-insights-cli-aml-address-risk', async (client) => {\n const { runAmlAddressRisk } = await import('./investigation/public-tools.js')\n const result = await runAmlAddressRisk(\n client,\n {\n address: opts.address,\n network: opts.network,\n compareAddress: opts.compareAddress,\n },\n requestedVersion\n )\n console.log(\n opts.json ? JSON.stringify(result.structuredContent, null, 2) : result.summaryText\n )\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n }\n )\n )\n}\n\nprogram\n .command('networks')\n .description('Show supported network status and dataset overview')\n .option('--json', 'Print raw capability JSON')\n .action(async (opts: { json?: boolean }) => {\n try {\n await printNetworkOverview(opts)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram\n .command('network')\n .description('Show details for one supported graph network')\n .argument('<name>', 'Network identifier or display name (for example: robinhood)')\n .option('--json', 'Print raw capability JSON for this network (with --schema: the schema JSON)')\n .option(\n '--schema',\n 'Show the live graph schema: labels, link types, fields and indexes (cached for 24 hours)'\n )\n .option('--refresh', 'With --schema: rebuild the schema now instead of reading the cache')\n .action(async (name: string, opts: { json?: boolean; schema?: boolean; refresh?: boolean }) => {\n try {\n if (opts.refresh && !opts.schema) {\n throw new Error('--refresh needs --schema: run `cia network <name> --schema --refresh`.')\n }\n if (opts.schema) {\n await printNetworkSchema(name, opts)\n } else {\n await printNetworkCapability(name, opts)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram\n .command('workflows')\n .description('List CIA workflow tools')\n .option('--json', 'Print the workflow catalog as JSON')\n .action((opts: { json?: boolean }) => {\n if (opts.json) {\n console.log(JSON.stringify(CIA_WORKFLOWS, null, 2))\n return\n }\n console.log(formatCiaWorkflows(CIA_WORKFLOWS))\n })\n\nconst workflowCommand = program.command('workflow').description('Run a high-level CIA workflow')\n\naddAmlAddressRiskCommand(workflowCommand, 'cia networks')\n\nprogram\n .command('status')\n .description('Show toolkit status and configuration')\n .action(async () => {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n const graphMcpStatus =\n config.graphMcpMode === 'debug' && config.graphMcpAuthToken?.trim()\n ? 'bearer access mode'\n : `${config.graphMcpMode} mode`\n console.log('Config: ', config.dataDir)\n console.log('Chain Insights Graph:', graphMcpStatus)\n console.log('Graph endpoint:', config.graphMcpEndpoint)\n })\n\nprogram\n .command('update')\n .description('Check npmjs for a newer Chain Insights release and update this CLI')\n .option('--check', 'Only check for a newer release')\n .option('--dry-run', 'Print the update command without running it')\n .action(async (opts: { check?: boolean; dryRun?: boolean }) => {\n try {\n const { checkForUpdate, runPackageUpdate } = await import('./update.js')\n const result = await checkForUpdate()\n if (result.error) {\n throw new Error(`Could not check npmjs for updates: ${result.error}`)\n }\n if (!result.updateAvailable || !result.latestVersion) {\n console.log(`Chain Insights is up to date (${result.currentVersion}).`)\n return\n }\n\n console.log(\n `Chain Insights ${result.latestVersion} is available (current ${result.currentVersion}).`\n )\n if (opts.check) {\n console.log(`Run: ${result.updateCommand}`)\n return\n }\n if (opts.dryRun) {\n console.log(`Would run: ${result.updateCommand}`)\n return\n }\n\n console.log(`Running: ${result.updateCommand}`)\n runPackageUpdate(result.packageName)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram\n .command('debug')\n .description('Configure Chain Insights Graph debug mode')\n .addCommand(\n createCliCommand('on')\n .description('Enable Chain Insights Graph debug mode without x402 payments')\n .requiredOption('--token <token>', 'Debug bearer token')\n .option('--endpoint <url>', 'Chain Insights Graph endpoint')\n .action(async (opts: { token: string; endpoint?: string }) => {\n try {\n const { saveConfig } = await import('./config/index.js')\n await saveConfig({\n graphMcpMode: 'debug',\n graphMcpAuthToken: opts.token,\n ...(opts.endpoint ? { graphMcpEndpoint: opts.endpoint } : {}),\n })\n console.log('Chain Insights Graph debug mode enabled')\n if (opts.endpoint) console.log(`Graph endpoint: ${opts.endpoint}`)\n console.log('Payments: disabled for Chain Insights Graph calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('off')\n .description('Disable Chain Insights Graph debug mode and use paid x402 calls')\n .action(async () => {\n try {\n const { saveConfig } = await import('./config/index.js')\n await saveConfig({ graphMcpMode: 'paid', graphMcpAuthToken: '' })\n console.log('Chain Insights Graph debug mode disabled')\n console.log('Payments: enabled for Chain Insights Graph calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('status')\n .description('Show Chain Insights Graph payment/debug mode')\n .action(async () => {\n try {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n console.log(`Chain Insights Graph mode: ${config.graphMcpMode}`)\n console.log(`Graph endpoint: ${config.graphMcpEndpoint}`)\n console.log(\n `Debug token: ${config.graphMcpAuthToken?.trim() ? 'configured' : 'not configured'}`\n )\n console.log(`Payments: ${config.graphMcpMode === 'debug' ? 'disabled' : 'enabled'}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('access-key')\n .description('Configure Chain Insights Graph test access key mode')\n .addCommand(\n createCliCommand('set')\n .description('Use a Chain Insights Graph test access key without x402 payments')\n .argument('<key>', 'Test access key')\n .option('--endpoint <url>', 'Chain Insights Graph endpoint')\n .action(async (key: string, opts: { endpoint?: string }) => {\n try {\n const normalizedKey = key.trim()\n if (!normalizedKey) throw new Error('Test access key is required')\n const { saveConfig } = await import('./config/index.js')\n await saveConfig({\n graphMcpMode: 'debug',\n graphMcpAuthToken: normalizedKey,\n ...(opts.endpoint ? { graphMcpEndpoint: opts.endpoint } : {}),\n })\n console.log('Chain Insights Graph test access key configured')\n if (opts.endpoint) console.log(`Graph endpoint: ${opts.endpoint}`)\n console.log('Payments: disabled when the server accepts this key')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('clear')\n .description('Remove the Chain Insights Graph test access key and use paid x402 calls')\n .action(async () => {\n try {\n const { saveConfig } = await import('./config/index.js')\n await saveConfig({ graphMcpMode: 'paid', graphMcpAuthToken: '' })\n console.log('Chain Insights Graph test access key cleared')\n console.log('Payments: enabled for Chain Insights Graph calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('status')\n .description('Show Chain Insights Graph test access key status')\n .action(async () => {\n try {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n console.log(`Graph endpoint: ${config.graphMcpEndpoint}`)\n console.log(\n `Access key: ${config.graphMcpAuthToken?.trim() ? 'configured' : 'not configured'}`\n )\n console.log(\n `Payments: ${config.graphMcpAuthToken?.trim() ? 'disabled when accepted by server' : 'enabled'}`\n )\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('setup')\n .description('Configure external MCP clients')\n .addCommand(\n createCliCommand('claude-code')\n .alias('claude')\n .description('Install Claude Code skills and register the MCP proxy')\n .action(() => {\n runInstaller('--claude')\n })\n )\n .addCommand(\n createCliCommand('claude-desktop')\n .description('Register the MCP proxy in Claude Desktop, which draws the money-flow views')\n .action(() => {\n runInstaller('--claude-desktop')\n })\n )\n .addCommand(\n createCliCommand('codex')\n .description('Install Codex skills and register the MCP proxy')\n .action(() => {\n runInstaller('--codex')\n })\n )\n .addCommand(\n createCliCommand('chatgpt')\n .description('Set up the ChatGPT desktop app: its Codex chats run Chain Insights')\n .action(() => {\n runInstaller('--codex')\n // The ChatGPT chat itself runs in the cloud and cannot reach a server on\n // this computer. Only the app's Codex chats can.\n console.log(\n '\\n In the ChatGPT app, ask in a Codex chat (Codex in the sidebar), not in a ChatGPT chat.\\n'\n )\n })\n )\n .addCommand(\n createCliCommand('hermes')\n .description('Install Hermes skills and register the MCP proxy')\n .action(() => {\n runInstaller('--hermes')\n })\n )\n\nprogram\n .command('config')\n .description('Read or write configuration values')\n .addCommand(\n createCliCommand('get')\n .description('Read one Chain Insights configuration value')\n .argument('<key>', 'Config key to read')\n .action(async (key: string) => {\n const { loadConfig } = await import('./config/index.js')\n const { CONFIG_KEYS } = await import('./config/schema.js')\n if (!CONFIG_KEYS.includes(key as (typeof CONFIG_KEYS)[number])) {\n console.error(`Unknown config key: ${key}`)\n process.exit(1)\n }\n const config = await loadConfig()\n const value = (config as Record<string, unknown>)[key]\n console.log(value ?? '')\n })\n )\n .addCommand(\n createCliCommand('reset')\n .description(\n 'Put every setting back to its default (production endpoint, paid mode, no test key); the wallet stays'\n )\n .action(async () => {\n try {\n const { resetConfig, loadConfig } = await import('./config/index.js')\n const { backupPath } = await resetConfig()\n const config = await loadConfig()\n if (backupPath) console.log(`Previous settings saved to ${backupPath}`)\n console.log('Settings reset to defaults.')\n console.log(`Graph endpoint: ${config.graphMcpEndpoint}`)\n console.log(`Mode: ${config.graphMcpMode}`)\n console.log('Test access: off')\n console.log('Wallet: unchanged (~/.chain-insights/wallet.json)')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('set')\n .description('Write one Chain Insights configuration value')\n .argument('<key>', 'Config key to write')\n .argument('<value>', 'Value to set')\n .action(async (key: string, value: string) => {\n // D-01: walletPrivateKey is intercepted before saveConfig — the raw private key\n // must NEVER be written to config.json.\n if (key === 'walletPrivateKey') {\n try {\n const { setWalletPrivateKey } = await import('./wallet/index.js')\n const address = await setWalletPrivateKey(value)\n console.log('Wallet private key encrypted and stored in ~/.chain-insights/wallet.json')\n console.log(`Wallet address: ${address}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n return // MUST return — walletPrivateKey must never reach saveConfig or config.json\n }\n const { loadConfig, saveConfig } = await import('./config/index.js')\n const { CONFIG_KEYS, DEFAULT_CONFIG } = await import('./config/schema.js')\n const current = await loadConfig()\n if (!CONFIG_KEYS.includes(key as (typeof CONFIG_KEYS)[number])) {\n console.error(`Unknown config key: ${key}`)\n process.exit(1)\n }\n const existing = (current as Record<string, unknown>)[key]\n const defaultValue = (DEFAULT_CONFIG as Record<string, unknown>)[key]\n const coerced =\n typeof existing === 'number' || typeof defaultValue === 'number' ? Number(value) : value\n await saveConfig({ [key]: coerced } as Parameters<typeof saveConfig>[0])\n const displayed = key.toLowerCase().includes('token') ? '[redacted]' : coerced\n console.log(`Set ${key} = ${displayed}`)\n })\n )\n\nprogram\n .command('wallet')\n .description('Manage the local Base USDC payment wallet')\n .addCommand(\n createCliCommand('create')\n .description('Generate a new local Base payment wallet')\n .option(\n '--replace',\n 'Replace a wallet whose key is public (the old file is backed up next to wallet.json)'\n )\n .action(async (opts: { replace?: boolean }) => {\n try {\n const {\n assertStoredWalletReplaceable,\n isWalletConfigured,\n replacePublicWallet,\n setWalletPrivateKey,\n storedWalletKeyIsPublic,\n walletPath,\n } = await import('./wallet/index.js')\n const { createInterface } = await import('node:readline/promises')\n const { formatWalletBackupWarning, generateWalletPrivateKey, isWalletBackupConfirmed } =\n await import('./wallet/create.js')\n\n if (opts.replace === true) {\n await assertStoredWalletReplaceable()\n } else if (await isWalletConfigured()) {\n throw new Error(\n (await storedWalletKeyIsPublic()) === true\n ? \"A payment wallet already exists, and its key is public: anything sent to it is taken within seconds. Run `cia wallet create --replace`.\"\n : 'A payment wallet already exists. Run `cia wallet address` to view it or use `cia wallet import <private-key> --force` to replace it.'\n )\n }\n\n const privateKey = generateWalletPrivateKey()\n const color = process.stderr.isTTY === true && process.env['NO_COLOR'] === undefined\n process.stderr.write(`${formatWalletBackupWarning(privateKey, { color })}\\n`)\n const prompt = createInterface({ input: process.stdin, output: process.stderr })\n let answer: string\n try {\n answer = await prompt.question('> ')\n } finally {\n prompt.close()\n }\n process.stderr.write('\\n')\n if (!isWalletBackupConfirmed(answer)) {\n throw new Error('Wallet creation cancelled. The wallet was not saved.')\n }\n\n const address =\n opts.replace === true\n ? await replacePublicWallet(privateKey)\n : await setWalletPrivateKey(privateKey)\n if (opts.replace === true) {\n console.log('The old wallet file is backed up next to ~/.chain-insights/wallet.json')\n }\n console.log(`Wallet created: ${address}`)\n console.log(`Encrypted local copy: ${walletPath()}`)\n console.log('Next: cia wallet ready')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('import')\n .description('Import a Base payment wallet')\n .argument('<private-key>', '0x-prefixed EVM private key')\n .option(\n '--force',\n 'Replace an existing wallet (the previous key is backed up next to wallet.json)'\n )\n .action(async (privateKey: string, opts: { force?: boolean }) => {\n try {\n const { setWalletPrivateKey, isWalletConfigured } = await import('./wallet/index.js')\n const replacing = opts.force === true && (await isWalletConfigured())\n const address = await setWalletPrivateKey(privateKey, { force: opts.force })\n if (replacing) {\n console.log('Previous wallet key backed up next to ~/.chain-insights/wallet.json')\n }\n console.log(`Wallet imported: ${address}`)\n console.log(\n 'Keep your original private key backed up securely; it cannot be recovered from the encrypted local copy.'\n )\n console.log('Encrypted local copy: ~/.chain-insights/wallet.json')\n console.log('Next: cia wallet ready')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('address')\n .description('Print the local payment wallet address')\n .action(async () => {\n try {\n const { getWalletAccount } = await import('./wallet/tools.js')\n const account = await getWalletAccount()\n console.log(account.address)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('balance')\n .description('Show the local payment wallet Base USDC balance')\n .action(async () => {\n try {\n const { getWalletBalanceText } = await import('./wallet/tools.js')\n console.log(await getWalletBalanceText())\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('ready')\n .description('Check and prepare the wallet for paid Chain Insights Graph calls')\n .option('--check-only', 'Only check readiness; do not submit the one-time payment setup')\n .addOption(new Option('--no-approve', 'Deprecated alias for --check-only').hideHelp())\n .option('--payment-usdc <amount>', 'USDC setup cap to prepare for paid calls', '1')\n .addOption(\n new Option('--approval-usdc <amount>', 'Deprecated alias for --payment-usdc').hideHelp()\n )\n .option('--json', 'Print machine-readable readiness metadata')\n .action(\n async (opts: {\n checkOnly?: boolean\n approve?: boolean\n paymentUsdc?: string\n approvalUsdc?: string\n json?: boolean\n }) => {\n try {\n const { formatWalletReadiness, parsePaymentApprovalUnits, prepareWalletForPaidCalls } =\n await import('./wallet/tools.js')\n const minimumApprovalUnits = parsePaymentApprovalUnits(\n opts.paymentUsdc ?? opts.approvalUsdc ?? '1'\n )\n const result = await prepareWalletForPaidCalls({\n minimumApprovalUnits,\n approve: opts.checkOnly ? false : opts.approve !== false,\n })\n\n if (opts.json) {\n console.log(\n JSON.stringify(\n result,\n (_key, value) => (typeof value === 'bigint' ? value.toString() : value),\n 2\n )\n )\n return\n }\n\n console.log(formatWalletReadiness(result.readiness, result.approval))\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n }\n )\n )\n .addCommand(\n createCliCommand('topup')\n .description('Open a local browser page to top up the payment wallet')\n .option('--no-open', 'Print the top-up URL without opening a browser')\n .option('--json', 'Print machine-readable top-up metadata')\n .action(async (opts: { open?: boolean; json?: boolean }) => {\n try {\n const { assertWalletKeyNotPublic, buildTopupInfo, getWalletAccount } =\n await import('./wallet/tools.js')\n const { startTopupServer } = await import('./wallet/topup-server.js')\n const account = await getWalletAccount()\n assertWalletKeyNotPublic(account)\n const url = await startTopupServer(account)\n const info = buildTopupInfo(account.address, url)\n\n if (opts.json) {\n console.log(JSON.stringify(info, null, 2))\n } else {\n console.log(`Top-up URL: ${url}`)\n console.log(`Wallet: ${account.address}`)\n console.log('Network: Base')\n console.log('Token: USDC')\n console.log('Press Ctrl+C to stop the top-up server.')\n }\n\n if (opts.open !== false) {\n const open = (await import('open')).default\n await open(url)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nregisterSubscriptionCommands(program, createCliCommand)\n\nconst mcpCommand = program\n .command('mcp')\n .description('Low-level access to the Chain Insights MCP endpoint')\n .allowExcessArguments(false)\n .addCommand(\n createCliCommand('networks')\n .description('List the detailed Chain Insights capability matrix and tool support')\n .option('--json', 'Print raw capability JSON')\n .action(async (opts: { json?: boolean }) => {\n try {\n await printNetworkCapabilities(opts)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('tools')\n .description('List the remote GraphRAG MCP tools (cached for 24 hours)')\n .option('--refresh', 'Force refresh schema cache')\n .action(async (opts: { refresh?: boolean }) => {\n try {\n const { loadSchema, saveSchema } = await import('./mcp/schema-cache.js')\n const { formatToolsTable } = await import('./mcp/format.js')\n const { visibleRemoteTools } = await import('./mcp/tool-visibility.js')\n const { loadConfig } = await import('./config/index.js')\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } =\n await import('./mcp/client.js')\n const config = await loadConfig()\n const graphMcpEndpoint = resolveGraphMcpEndpoint(config)\n let tools = opts.refresh ? null : await loadSchema(graphMcpEndpoint)\n if (!tools) {\n const paymentFetch = await createConfiguredGraphMcpFetch(config)\n const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')\n const { StreamableHTTPClientTransport } =\n await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name: 'chain-insights-cli', version: PACKAGE_VERSION })\n await client.connect(\n new StreamableHTTPClientTransport(new URL(graphMcpEndpoint), { fetch: paymentFetch })\n )\n try {\n const result = await client.listTools()\n tools = result.tools as Array<{ name: string; description?: string }>\n await saveSchema(tools, graphMcpEndpoint)\n } finally {\n await client.close()\n }\n }\n console.log(formatToolsTable(visibleRemoteTools(tools)))\n // The local tool doors the proxy serves beside the remote tools.\n const { META_DEX_LOOKUP_DESCRIPTION, META_DEX_LOOKUP_TITLE, META_DEX_LOOKUP_TOOL } =\n await import('./mcp/dex-tool.js')\n console.log('')\n console.log(\n formatToolsTable(\n [{ name: META_DEX_LOOKUP_TOOL, description: `${META_DEX_LOOKUP_TITLE}. ${META_DEX_LOOKUP_DESCRIPTION}` }],\n 'Local proxy tool'\n )\n )\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nmcpCommand.addCommand(\n createCliCommand('call')\n .description('Call a low-level MCP tool directly (advanced)')\n .option('--json', 'Print machine-readable JSON output')\n .argument('<tool>', 'Tool name to call')\n .argument('[args...]', 'Key=value arguments (e.g. address=0x1234... network=robinhood)')\n .action(async (tool: string, rawArgs: string[], opts: { json?: boolean }) => {\n try {\n const { parseMcpCallArgs } = await import('./mcp/call-args.js')\n const { assertPublicMcpToolName, validatePublicMcpToolArguments } =\n await import('./mcp/tool-visibility.js')\n let args = parseMcpCallArgs(rawArgs)\n assertPublicMcpToolName(tool)\n validatePublicMcpToolArguments(tool, args)\n\n if (tool === 'wallet_balance') {\n const { getWalletBalanceText } = await import('./wallet/tools.js')\n console.log(await getWalletBalanceText())\n return\n }\n\n if (tool === 'meta_network_capabilities') {\n await printNetworkCapabilities({ json: opts.json })\n return\n }\n\n if (tool === 'meta_schema') {\n await printNetworkSchema(String(args['network'] ?? ''), {\n json: opts.json,\n refresh: String(args['refresh'] ?? '').toLowerCase() === 'true',\n })\n return\n }\n\n if (tool === 'meta_dex_lookup') {\n // The proxy's local tool, run here with the CLI's own graph session.\n const { handleMetaDexLookup } = await import('./mcp/dex-tool.js')\n const { loadRegistry } = await import('./mcp/dex-registry.js')\n const { metaDexLookupArgs } = await import('./mcp/call-args.js')\n const result = await withGraphMcpClient('chain-insights-cli-dex-lookup', (client) =>\n handleMetaDexLookup(\n metaDexLookupArgs(args),\n {\n loadRegistry: (network) => loadRegistry(network),\n graphQueryBatch: async (batchArgs) =>\n (await client.callTool({ name: 'graph_query_batch', arguments: batchArgs })) as {\n content?: unknown[]\n structuredContent?: unknown\n isError?: boolean\n },\n describeFailure: (err) => (err as Error).message,\n }\n )\n )\n console.log(result.content[0]?.text ?? '')\n if (result.isError) process.exitCode = 1\n return\n }\n\n if (tool === 'graph_expand') {\n throw new Error(\n 'graph_expand is used only by the Chain Insights view in Claude. Run `cia mcp call graph_query` with your own query instead.'\n )\n }\n\n if (tool === 'meta_help') {\n console.log(\n 'Graph tools: graph_query and graph_query_batch. Metadata and payment tools: meta_* and wallet_balance.'\n )\n return\n }\n\n await withGraphMcpClient('chain-insights-cli-call', async (client, config) => {\n if (tool === 'meta_usage_status') {\n try {\n const result = await client.callTool({ name: 'usage_status', arguments: {} })\n printMcpTextContent(\n result as { content?: Array<{ type: string; text?: string }>; isError?: boolean },\n { tool, json: opts.json }\n )\n } catch (err) {\n const {\n isMissingUsageStatusToolError,\n primitiveBackendUsageStatus,\n usageStatusText,\n } = await import('./mcp/usage-status.js')\n if (!isMissingUsageStatusToolError(err)) throw err\n const { resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n console.log(\n usageStatusText(primitiveBackendUsageStatus(resolveGraphMcpEndpoint(config)))\n )\n }\n return\n }\n if (tool === 'meta_subscription_status') {\n try {\n // The server reads the wallet from the proof header; only an\n // older server whose schema requires `wallet` is sent it.\n const { subscriptionStatusArguments, subscriptionStatusNeedsWallet } =\n await import('./mcp/subscription-status.js')\n const remote = (await client.listTools()).tools.find(\n (t) => t.name === 'subscription_status'\n )\n let wallet: string | null = null\n if (subscriptionStatusNeedsWallet(remote)) {\n const { getWalletAccount } = await import('./wallet/tools.js')\n wallet = (await getWalletAccount()).address\n }\n const result = await client.callTool({\n name: 'subscription_status',\n arguments: subscriptionStatusArguments(remote, wallet),\n })\n printMcpTextContent(\n result as { content?: Array<{ type: string; text?: string }>; isError?: boolean },\n { tool, json: opts.json }\n )\n } catch (err) {\n const {\n isMissingSubscriptionStatusToolError,\n unavailableSubscriptionStatus,\n subscriptionStatusText,\n } = await import('./mcp/subscription-status.js')\n if (!isMissingSubscriptionStatusToolError(err)) throw err\n const { resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n console.log(\n subscriptionStatusText(\n unavailableSubscriptionStatus(\n resolveGraphMcpEndpoint(config),\n `subscription_status failed: ${(err as Error).message}`\n )\n )\n )\n }\n return\n }\n // graph_query and graph_query_batch can run past the SDK's 60 s default\n // while the server is still answering. Other tools keep that default.\n const { graphToolRequestOptions } = await import('./mcp/request-timeout.js')\n const requestOptions = graphToolRequestOptions(tool)\n // A query that names a twin as a property (a.balance_eth, f.last_seen_timestamp_utc)\n // is rewritten to the column the server has, as the proxy does (src/mcp/timestamp-text.ts).\n const { withoutUtcProperties } = await import('./mcp/timestamp-text.js')\n args = withoutUtcProperties(tool, args)\n const result = requestOptions\n ? await client.callTool({ name: tool, arguments: args }, undefined, requestOptions)\n : await client.callTool({ name: tool, arguments: args })\n printMcpTextContent(\n result as { content?: Array<{ type: string; text?: string }>; isError?: boolean },\n { tool, json: opts.json }\n )\n })\n } catch (err) {\n const { formatMcpCallError } = await import('./mcp/tool-visibility.js')\n console.error(formatMcpCallError(tool, err))\n process.exit(1)\n }\n })\n)\n\n// parseAsync (not parse) so a rejected async action surfaces as a clean\n// one-line error and a non-zero exit, instead of an unhandled-rejection stack\n// trace. Commands with their own try/catch still exit(1) before this fires.\nprogram.parseAsync(normalizeAmlToolVersionArgv(process.argv)).catch((err) => {\n console.error((err as Error).message)\n process.exit(1)\n})\n"],"mappings":";;;;;;AAQA,MAAa,gBAAwC,CACnD;CACE,MAAM;CACN,MAAM;CACN,SAAS;CACT,aAAa;CACb,SAAS;AACX,CACF;AAEA,MAAM,aAAa;AACnB,MAAM,gBAAgB;AACtB,MAAM,gBAAgB;AAEtB,SAAS,UAAU,QAA0B;CAC3C,OAAO;EACL,OAAO,EAAE,EAAE,OAAO,UAAU;EAC5B,OAAO,EAAE,EAAE,OAAO,aAAa;EAC/B,OAAO,EAAE,EAAE,OAAO,aAAa;CACjC,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAgB,mBAAmB,WAA2C;CAC5E,IAAI,UAAU,WAAW,GAAG,OAAO;CAEnC,MAAM,OAAO,UAAU,SAAS,aAAa,CAC3C,UAAU;EAAC,SAAS;EAAM,SAAS;EAAS,SAAS;CAAO,CAAC,GAC7D,KAAK,SAAS,aAChB,CAAC;CAED,OAAO;EACL;EACA;EACA,UAAU;GAAC;GAAY;GAAW;EAAU,CAAC;EAC7C,UAAU;GAAC,IAAI,OAAO,UAAU;GAAG,IAAI,OAAO,aAAa;GAAG,IAAI,OAAO,aAAa;EAAC,CAAC;EACxF,GAAG;CACL,CAAC,CAAC,KAAK,IAAI;A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Ac,OAAO;CACpC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
- import { d as prepareWalletForPaidCalls, f as resolveMaxAutoApprovalUnits, n as USDC_ADDRESS, t as PERMIT2_ADDRESS } from "./tools-BnThuvE2.mjs";
2
+ import { d as prepareWalletForPaidCalls, f as resolveMaxAutoApprovalUnits, n as USDC_ADDRESS, t as PERMIT2_ADDRESS } from "./tools-D9ep9E7Q.mjs";
3
+ import { h as robinhoodRpcUrls, i as ROBINHOOD_NETWORK, r as ROBINHOOD_CHAIN_ID } from "./robinhood-CCTMagwM.mjs";
3
4
  import { privateKeyToAccount } from "viem/accounts";
4
5
  import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
5
6
  import { ExactEvmScheme } from "@x402/evm";
@@ -76,7 +77,6 @@ var client_exports = /* @__PURE__ */ __exportAll({
76
77
  PaymentRequiredError: () => PaymentRequiredError,
77
78
  ROBINHOOD_CHAIN_ID: () => ROBINHOOD_CHAIN_ID,
78
79
  ROBINHOOD_NETWORK: () => ROBINHOOD_NETWORK,
79
- ROBINHOOD_RPC_URL: () => ROBINHOOD_RPC_URL,
80
80
  applyMcpAuthHeaders: () => applyMcpAuthHeaders,
81
81
  createConfiguredGraphMcpFetch: () => createConfiguredGraphMcpFetch,
82
82
  createMcpAuthFetchClient: () => createMcpAuthFetchClient,
@@ -84,10 +84,9 @@ var client_exports = /* @__PURE__ */ __exportAll({
84
84
  resolveGraphMcpEndpoint: () => resolveGraphMcpEndpoint,
85
85
  resolvePaymentAssetPreference: () => resolvePaymentAssetPreference
86
86
  });
87
- const ROBINHOOD_CHAIN_ID = 4663;
88
- const ROBINHOOD_NETWORK = "eip155:4663";
89
- const ROBINHOOD_RPC_URL = "https://rpc.mainnet.chain.robinhood.com";
90
- const EVM_SCHEME_OPTIONS = { [ROBINHOOD_CHAIN_ID]: { rpcUrl: ROBINHOOD_RPC_URL } };
87
+ function evmSchemeOptions(env = process.env) {
88
+ return { [ROBINHOOD_CHAIN_ID]: { rpcUrl: robinhoodRpcUrls(env)[0] } };
89
+ }
91
90
  /**
92
91
  * Reads the operator's payment-asset preference order (env
93
92
  * CHAIN_INSIGHTS_PAYMENT_ASSET_PREFERENCE, comma-separated symbols or
@@ -258,7 +257,7 @@ function createPaymentFailureReportingFetch(baseFetch, payerAddress, paymentWall
258
257
  */
259
258
  function createMcpFetchClient(privateKey, authToken) {
260
259
  const account = privateKeyToAccount(privateKey);
261
- const uptoScheme = new UptoEvmScheme(account, EVM_SCHEME_OPTIONS);
260
+ const uptoScheme = new UptoEvmScheme(account, evmSchemeOptions());
262
261
  const reportingFetch = createPaymentFailureReportingFetch(wrapFetchWithPaymentFromConfig(createAssetPreferenceReorderingFetch(createWalletProofFetch(account, fetch), resolvePaymentAssetPreference()), { schemes: [
263
262
  {
264
263
  network: "eip155:8453",
@@ -296,20 +295,40 @@ function createMcpAuthFetchClient(authToken, baseFetch = fetch) {
296
295
  function resolveGraphMcpEndpoint(config) {
297
296
  return config.graphMcpEndpoint.trim();
298
297
  }
298
+ /**
299
+ * The stored wallet's key, or null when no wallet exists or its key is public.
300
+ * A public key signs no payment and no wallet proof: anyone could sign as it.
301
+ */
302
+ async function usableWalletPrivateKey() {
303
+ const { isWalletConfigured, decryptKey } = await import("./wallet-QTo5YCFR.mjs").then((n) => n.s);
304
+ if (!await isWalletConfigured()) return null;
305
+ const privateKey = await decryptKey();
306
+ const { isPrivateKeyPublic, PUBLIC_KEY_WALLET_TEXT } = await import("./known-keys-B87ZqOgE.mjs").then((n) => n.i);
307
+ if (isPrivateKeyPublic(privateKey)) {
308
+ if (!publicKeyWarned) {
309
+ publicKeyWarned = true;
310
+ process.stderr.write(`[chain-insights] ${PUBLIC_KEY_WALLET_TEXT} It is not used.\n`);
311
+ }
312
+ return null;
313
+ }
314
+ return privateKey;
315
+ }
316
+ let publicKeyWarned = false;
299
317
  async function createConfiguredGraphPaidOrFreeFetch() {
300
- const { isWalletConfigured, decryptKey } = await import("./wallet-GNDl3FkR.mjs").then((n) => n.s);
301
- if (!await isWalletConfigured()) return createPaymentFailureReportingFetch(fetch);
302
- return createMcpFetchClient(await decryptKey());
318
+ const privateKey = await usableWalletPrivateKey();
319
+ if (!privateKey) return createPaymentFailureReportingFetch(fetch);
320
+ return createMcpFetchClient(privateKey);
303
321
  }
304
322
  async function createConfiguredGraphMcpFetch(config) {
305
323
  if (config.graphMcpMode === "debug") {
306
324
  const authToken = config.graphMcpAuthToken?.trim();
307
325
  if (!authToken) throw new Error("Chain Insights Graph debug mode requires graphMcpAuthToken. Run `cia access-key set <key>` or `cia debug on --token <token>`.");
308
- return createMcpAuthFetchClient(authToken);
326
+ const privateKey = await usableWalletPrivateKey();
327
+ return createMcpAuthFetchClient(authToken, privateKey ? createWalletProofFetch(privateKeyToAccount(privateKey), fetch) : fetch);
309
328
  }
310
329
  return createConfiguredGraphPaidOrFreeFetch();
311
330
  }
312
331
  //#endregion
313
332
  export { resolveGraphMcpEndpoint as a, createMcpFetchClient as i, applyMcpAuthHeaders as n, client_exports as r, PaymentRequiredError as t };
314
333
 
315
- //# sourceMappingURL=client-gsLi528K.mjs.map
334
+ //# sourceMappingURL=client-7qOfAdpH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-7qOfAdpH.mjs","names":[],"sources":["../src/mcp/payment-asset-preference.ts","../src/mcp/wallet-proof.ts","../src/mcp/client.ts"],"sourcesContent":["/**\n * Payment-asset preference ordering for 402 `accepts` offers.\n *\n * Chain Insights Graph can quote a paid MCP call in more than one ERC-20\n * asset across networks (USDC on Base, USDG/CHOICE on Robinhood Chain). The\n * x402 client's default selector always pays with the first `accepts` entry\n * it can pay with, so re-ordering `accepts` by operator preference before\n * the payment scheme picks lets an operator route payments to a preferred\n * asset without any server-side change.\n */\n\nexport interface PaymentOptionLike {\n network: string // CAIP-2, e.g. \"eip155:8453\"\n asset: string // ERC-20 token contract address\n amount: string // base units\n extra?: Record<string, unknown>\n}\n\n/**\n * Known payment asset symbols by lowercase contract address. Extend this map\n * as new payment assets go live; an address not listed here can still be\n * targeted directly by address in CHAIN_INSIGHTS_PAYMENT_ASSET_PREFERENCE.\n */\nexport const KNOWN_PAYMENT_ASSET_SYMBOLS: Record<string, string> = {\n '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': 'USDC', // Base\n '0x5fc5360d0400a0fd4f2af552add042d716f1d168': 'USDG', // Robinhood Chain\n '0x6e30a5f8fc61cd4e8550d2dd3cddea2a0196dc69': 'CHOICE', // Robinhood Chain (test token)\n}\n\n/**\n * Orders 402 `accepts` by the operator preference list (env\n * CHAIN_INSIGHTS_PAYMENT_ASSET_PREFERENCE, comma-separated symbols or\n * addresses, e.g. \"CHOICE,USDG,USDC\"). Unlisted assets keep server order\n * after listed ones. Empty preference -> server order (today's behavior).\n *\n * Pure: does not mutate `accepts`. Matching is case-insensitive for both\n * symbols and addresses, and the sort is stable so ties (unlisted assets,\n * or repeated preference entries) preserve server order.\n */\nexport function orderPaymentOptions(\n accepts: PaymentOptionLike[],\n preference: string,\n assetSymbols: Record<string, string>\n): PaymentOptionLike[] {\n const preferenceList = preference\n .split(',')\n .map((entry) => entry.trim().toLowerCase())\n .filter(Boolean)\n\n if (preferenceList.length === 0) return accepts\n\n const rankOf = (option: PaymentOptionLike): number => {\n const addressLower = option.asset.toLowerCase()\n const symbolLower = assetSymbols[addressLower]?.toLowerCase()\n const rank = preferenceList.findIndex(\n (entry) => entry === symbolLower || entry === addressLower\n )\n return rank === -1 ? preferenceList.length : rank\n }\n\n return [...accepts].sort((a, b) => rankOf(a) - rankOf(b))\n}\n","import type { Account } from 'viem'\n\ntype FetchLike = typeof fetch\ntype FetchInput = Parameters<FetchLike>[0]\ntype FetchInit = Parameters<FetchLike>[1]\n\nexport const CIA_WALLET_PROOF_HEADER = 'X-CIA-Wallet-Proof'\n\nexport function proofMessage(host: string, unix: number): string {\n return `cia-mcp-permit\\n${host}\\n${unix}`\n}\n\nexport function proofHostFromUrl(input: FetchInput): string {\n if (typeof input === 'string') {\n return new URL(input).host\n }\n if (input instanceof URL) {\n return input.host\n }\n return new URL(input.url).host\n}\n\nexport async function buildWalletProof(opts: {\n account: Pick<Account, 'address' | 'signMessage'>\n host: string\n now?: Date\n}): Promise<string> {\n if (!opts.account.signMessage) {\n throw new Error('wallet cannot sign a burnhole proof')\n }\n const unix = Math.floor((opts.now ?? new Date()).getTime() / 1000)\n const signature = await opts.account.signMessage({\n message: proofMessage(opts.host, unix),\n })\n const sigHex = signature.startsWith('0x') ? signature.slice(2) : signature\n return `v1;${opts.account.address.toLowerCase()};${unix};${sigHex}`\n}\n\nexport function createWalletProofFetch(\n account: Pick<Account, 'address' | 'signMessage'>,\n baseFetch: FetchLike,\n now: () => Date = () => new Date()\n): FetchLike {\n return (async (input: FetchInput, init?: FetchInit) => {\n if (!account.signMessage) {\n return baseFetch(input, init)\n }\n const headers = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined)\n )\n headers.set(\n CIA_WALLET_PROOF_HEADER,\n await buildWalletProof({ account, host: proofHostFromUrl(input), now: now() })\n )\n return baseFetch(input, { ...init, headers })\n }) as FetchLike\n}\n","import { wrapFetchWithPaymentFromConfig } from '@x402/fetch'\nimport { ExactEvmScheme } from '@x402/evm'\nimport { UptoEvmScheme, type UptoEvmSchemeConfigByChainId } from '@x402/evm/upto/client'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport type { InvestigatorConfig } from '../config/schema.js'\nimport {\n prepareWalletForPaidCalls,\n resolveMaxAutoApprovalUnits,\n PERMIT2_ADDRESS,\n USDC_ADDRESS,\n} from '../wallet/tools.js'\nimport {\n orderPaymentOptions,\n KNOWN_PAYMENT_ASSET_SYMBOLS,\n type PaymentOptionLike,\n} from './payment-asset-preference.js'\nimport { createWalletProofFetch } from './wallet-proof.js'\nimport {\n ROBINHOOD_CHAIN_ID,\n ROBINHOOD_NETWORK,\n ROBINHOOD_RPC_URL,\n robinhoodRpcUrls,\n} from '../wallet/robinhood.js'\n\ntype FetchLike = typeof fetch\ntype FetchInput = Parameters<FetchLike>[0]\ntype FetchInit = Parameters<FetchLike>[1]\n\n// Robinhood Chain — second EVM network accepted for x402 Permit2 payments\n// alongside Base Mainnet. The x402 SDK builds its own bare RPC client per\n// chain ID from this config (no viem chain-registry entry is needed: it\n// never imports `viem/chains`, it just does `createPublicClient({transport:\n// http(rpcUrl)})` keyed by CAIP-2 chain ID). The constants live in\n// src/wallet/robinhood.ts; ROBINHOOD_RPC_URL in the environment overrides\n// the RPC here too.\nexport { ROBINHOOD_CHAIN_ID, ROBINHOOD_NETWORK, ROBINHOOD_RPC_URL }\n\nfunction evmSchemeOptions(env: NodeJS.ProcessEnv = process.env): UptoEvmSchemeConfigByChainId {\n return { [ROBINHOOD_CHAIN_ID]: { rpcUrl: robinhoodRpcUrls(env)[0] } }\n}\n\n/**\n * Reads the operator's payment-asset preference order (env\n * CHAIN_INSIGHTS_PAYMENT_ASSET_PREFERENCE, comma-separated symbols or\n * addresses). Empty/unset keeps server order.\n */\nexport function resolvePaymentAssetPreference(env: NodeJS.ProcessEnv = process.env): string {\n return env['CHAIN_INSIGHTS_PAYMENT_ASSET_PREFERENCE']?.trim() ?? ''\n}\n\n/**\n * Wraps `fetch` so that a 402 response's `accepts` offers are re-ordered by\n * the operator's payment-asset preference before the x402 client's default\n * selector (which always picks `accepts[0]`) runs. Must wrap the raw\n * transport `fetch` passed into `wrapFetchWithPaymentFromConfig`, not the\n * result of it, since the x402 client parses `accepts` from the first 402\n * response it sees.\n */\nfunction createAssetPreferenceReorderingFetch(baseFetch: FetchLike, preference: string): FetchLike {\n if (!preference) return baseFetch\n return (async (input: FetchInput, init?: FetchInit) => {\n const response = await baseFetch(input, init)\n if (response.status !== 402) return response\n const encoded = response.headers.get('payment-required')\n if (!encoded) return response\n\n let parsed: { accepts?: PaymentOptionLike[] } & Record<string, unknown>\n try {\n parsed = JSON.parse(Buffer.from(encoded, 'base64').toString('utf8'))\n } catch {\n return response\n }\n if (!Array.isArray(parsed.accepts) || parsed.accepts.length === 0) return response\n\n const reordered = orderPaymentOptions(parsed.accepts, preference, KNOWN_PAYMENT_ASSET_SYMBOLS)\n const reencoded = Buffer.from(JSON.stringify({ ...parsed, accepts: reordered })).toString(\n 'base64'\n )\n const headers = new Headers(response.headers)\n headers.set('payment-required', reencoded)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n }) as FetchLike\n}\n\nexport class PaymentRequiredError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PaymentRequiredError'\n }\n}\n\nexport function applyMcpAuthHeaders(headers: Headers, authToken: string): Headers {\n headers.set('X-MCP-Debug-Token', authToken)\n headers.set('X-MCP-Test-Key', authToken)\n headers.set('X-Chain-Insights-Test-Key', authToken)\n headers.set('Authorization', `Bearer ${authToken}`)\n return headers\n}\n\nfunction createHeaderFetch(authToken: string, baseFetch: FetchLike): FetchLike {\n return (async (input: FetchInput, init?: FetchInit) => {\n const requestHeaders = input instanceof Request ? input.headers : undefined\n const headers = new Headers(init?.headers ?? requestHeaders)\n applyMcpAuthHeaders(headers, authToken)\n\n return baseFetch(input, {\n ...init,\n headers,\n })\n }) as FetchLike\n}\n\nexport const PAYMENT_NEXT_STEPS =\n 'Next steps: run `cia wallet ready` to check funding and finish one-time payment setup, ' +\n 'run `cia wallet topup` if it says the wallet needs USDC, ' +\n 'or `cia access-key set <key>` if you have been given test access.'\n\ninterface PaymentRequirementDetails {\n reason: string\n scheme?: string\n network?: string\n amount?: string\n amountUnits?: bigint\n payTo?: string\n asset?: string\n}\n\nfunction paymentRequirementFromResponse(response: Response): PaymentRequirementDetails | null {\n const encoded = response.headers.get('payment-required')\n if (!encoded) return null\n\n try {\n const decoded = Buffer.from(encoded, 'base64').toString('utf8')\n const parsed = JSON.parse(decoded) as {\n error?: unknown\n accepts?: Array<{\n scheme?: unknown\n network?: unknown\n amount?: unknown\n payTo?: unknown\n asset?: unknown\n }>\n }\n const reason =\n typeof parsed.error === 'string' && parsed.error.trim()\n ? parsed.error.trim()\n : 'payment_required'\n const firstRequirement = Array.isArray(parsed.accepts) ? parsed.accepts[0] : undefined\n const amount =\n typeof firstRequirement?.amount === 'string' ? firstRequirement.amount.trim() : undefined\n return {\n reason,\n scheme: typeof firstRequirement?.scheme === 'string' ? firstRequirement.scheme : undefined,\n network: typeof firstRequirement?.network === 'string' ? firstRequirement.network : undefined,\n amount,\n amountUnits: amount && /^\\d+$/.test(amount) ? BigInt(amount) : undefined,\n payTo:\n typeof firstRequirement?.payTo === 'string' ? firstRequirement.payTo.trim() : undefined,\n asset:\n typeof firstRequirement?.asset === 'string' ? firstRequirement.asset.trim() : undefined,\n }\n } catch {\n return null\n }\n}\n\n/**\n * True only for the one combination this client can auto-approve today:\n * USDC on Base, via the existing Base-only `wallet/tools.ts` allowance flow.\n * A requirement with no `asset` at all predates multi-asset 402 offers and\n * is treated as that same legacy USDC-on-Base case.\n */\nfunction isAutoApprovableBaseUsdc(requirement: PaymentRequirementDetails): boolean {\n if (requirement.network !== 'eip155:8453') return false\n if (!requirement.asset) return true\n return requirement.asset.toLowerCase() === USDC_ADDRESS.toLowerCase()\n}\n\n/**\n * Clear, actionable error for the case the auto-approval flow does not cover:\n * a Permit2 allowance is missing for a non-Base-USDC asset (e.g. USDG/CHOICE\n * on Robinhood Chain) and the server did not offer a gas-sponsored approval\n * extension. Names the token, the canonical Permit2 address, and the exact\n * approval call so the operator can run it manually.\n */\nfunction describePermit2ApprovalNeededError(requirement: PaymentRequirementDetails): string {\n const token = requirement.asset ?? 'the payment token'\n const networkSuffix = requirement.network ? ` on ${requirement.network}` : ''\n return (\n `Payment requires a one-time Permit2 approval for token ${token}${networkSuffix} before paid calls can settle, ` +\n 'and gas-sponsored approval is not available for this asset. ' +\n `Approve the canonical Permit2 contract ${PERMIT2_ADDRESS} to spend ${token} by calling ` +\n `approve(${PERMIT2_ADDRESS}, <amount>) on the token contract, then retry the call.`\n )\n}\n\nfunction describePaymentRequiredResponse(response: Response, payerAddress?: string): string {\n const requirement = paymentRequirementFromResponse(response)\n if (!requirement)\n return `Payment required — this tool costs USDC on Base via x402 micropayments. ${PAYMENT_NEXT_STEPS}`\n\n try {\n const { reason, payTo } = requirement\n if (payerAddress && payTo && payerAddress.toLowerCase() === payTo.toLowerCase()) {\n return 'Local payment wallet matches the MCP payTo address. Configure a separate payer wallet with USDC on Base; do not use the service recipient wallet as the client payment wallet.'\n }\n const details = [\n requirement.scheme ? `scheme=${requirement.scheme}` : undefined,\n requirement.network ? `network=${requirement.network}` : undefined,\n requirement.amount ? `amount=${requirement.amount}` : undefined,\n ]\n .filter(Boolean)\n .join(' ')\n const message = details\n ? `x402 payment failed: ${reason} (${details})`\n : `x402 payment failed: ${reason}`\n if (reason.includes('allowance_required')) {\n return `${message}. The payment wallet needs one-time setup before paid MCP calls can settle. Run \\`cia wallet ready\\`; Base ETH is used for the setup gas.`\n }\n if (reason === 'payment_required') {\n return `${message}. ${PAYMENT_NEXT_STEPS}`\n }\n return `${message}. ${PAYMENT_NEXT_STEPS}`\n } catch {\n return `Payment required — this tool costs USDC on Base via x402 micropayments. ${PAYMENT_NEXT_STEPS}`\n }\n}\n\nfunction createPaymentFailureReportingFetch(\n baseFetch: FetchLike,\n payerAddress?: string,\n paymentWallet?: { address: `0x${string}`; privateKey: `0x${string}` }\n): FetchLike {\n const reportingFetch = (async (input: FetchInput, init?: FetchInit) => {\n const response = await baseFetch(input, init)\n if (response.status !== 402) return response\n const requirement = paymentRequirementFromResponse(response)\n if (paymentWallet && requirement?.reason.includes('allowance_required')) {\n if (!isAutoApprovableBaseUsdc(requirement)) {\n throw new PaymentRequiredError(describePermit2ApprovalNeededError(requirement))\n }\n try {\n await prepareWalletForPaidCalls({\n account: paymentWallet,\n // The endpoint dictates requirement.amountUnits; cap it so a hostile\n // endpoint cannot drive an unbounded Permit2 approval / wallet drain.\n maxApprovalUnits: resolveMaxAutoApprovalUnits(),\n ...(requirement.amountUnits === undefined\n ? {}\n : { minimumApprovalUnits: requirement.amountUnits }),\n })\n } catch (err) {\n throw new PaymentRequiredError(\n 'Payment setup is not ready yet. Run `cia wallet ready` and try again. ' +\n `${(err as Error).message}`\n )\n }\n const retryResponse = await baseFetch(input, init)\n if (retryResponse.status !== 402) return retryResponse\n throw new PaymentRequiredError(describePaymentRequiredResponse(retryResponse, payerAddress))\n }\n throw new PaymentRequiredError(describePaymentRequiredResponse(response, payerAddress))\n }) as FetchLike\n return Object.assign(reportingFetch, baseFetch)\n}\n\n/**\n * Creates an x402-payment-wrapped fetch function for the Chain Insights MCP.\n * Payments are made in USDC on Base Mainnet (eip155:8453) or, when the\n * server offers it and the operator prefers it, a Permit2 asset on\n * Robinhood Chain (eip155:4663) — see ROBINHOOD_NETWORK.\n *\n * The factory is pure — no side effects, no state, no caching.\n * If called with an invalid private key format, viem throws — the error propagates.\n *\n * @param privateKey - 0x-prefixed EVM private key (decrypted from wallet.json)\n * @returns A fetch-compatible function that auto-handles HTTP 402 payment challenges\n */\nexport function createMcpFetchClient(privateKey: `0x${string}`, authToken?: string) {\n const account = privateKeyToAccount(privateKey)\n // Shared across both networks: evmSchemeOptions() is keyed by chain ID, so\n // it only supplies an RPC URL for Robinhood Chain (4663) and leaves Base\n // (8453) exactly as before (no RPC configured — gas-sponsored approval\n // stays unavailable there too, unchanged from prior behavior).\n const uptoScheme = new UptoEvmScheme(account, evmSchemeOptions())\n const paymentFetch = wrapFetchWithPaymentFromConfig(\n createAssetPreferenceReorderingFetch(\n createWalletProofFetch(account, fetch),\n resolvePaymentAssetPreference()\n ),\n {\n schemes: [\n {\n network: 'eip155:8453', // Base Mainnet — dynamic MCP pricing uses the x402 upto scheme\n client: uptoScheme,\n },\n {\n network: 'eip155:8453', // Base Mainnet — only supported chain in v1\n client: new ExactEvmScheme(account),\n },\n {\n network: ROBINHOOD_NETWORK, // Robinhood Chain — Permit2-only (upto scheme), same client instance\n client: uptoScheme,\n },\n ],\n }\n )\n const reportingFetch = createPaymentFailureReportingFetch(paymentFetch, account.address, {\n address: account.address,\n privateKey,\n })\n return authToken ? createHeaderFetch(authToken, reportingFetch) : reportingFetch\n}\n\n/**\n * Creates a bearer/debug-token fetch for local Chain Insights Graph testing.\n *\n * Chain Insights Graph deployments accept test access through the public debug header,\n * test-key headers, or Authorization: Bearer depending on the route.\n * Sending all supported auth headers lets one config value work across hosted\n * MCP calls, metadata reads, and private M2M endpoints.\n *\n * Wraps with 402 interception so that if the server still requires payment\n * (e.g. token not accepted for paid tools), the user sees actionable guidance\n * instead of a generic transport error.\n */\nexport function createMcpAuthFetchClient(\n authToken: string,\n baseFetch: FetchLike = fetch\n): FetchLike {\n const headerFetch = createHeaderFetch(authToken, baseFetch)\n return createPaymentFailureReportingFetch(headerFetch)\n}\n\nexport function resolveGraphMcpEndpoint(\n config: Pick<InvestigatorConfig, 'graphMcpEndpoint'>\n): string {\n return config.graphMcpEndpoint.trim()\n}\n\n/**\n * The stored wallet's key, or null when no wallet exists or its key is public.\n * A public key signs no payment and no wallet proof: anyone could sign as it.\n */\nasync function usableWalletPrivateKey(): Promise<`0x${string}` | null> {\n const { isWalletConfigured, decryptKey } = await import('../wallet/index.js')\n if (!(await isWalletConfigured())) return null\n const privateKey = (await decryptKey()) as `0x${string}`\n const { isPrivateKeyPublic, PUBLIC_KEY_WALLET_TEXT } = await import('../wallet/known-keys.js')\n if (isPrivateKeyPublic(privateKey)) {\n if (!publicKeyWarned) {\n publicKeyWarned = true\n process.stderr.write(`[chain-insights] ${PUBLIC_KEY_WALLET_TEXT} It is not used.\\n`)\n }\n return null\n }\n return privateKey\n}\nlet publicKeyWarned = false\n\nasync function createConfiguredGraphPaidOrFreeFetch(): Promise<FetchLike> {\n const privateKey = await usableWalletPrivateKey()\n if (!privateKey) {\n return createPaymentFailureReportingFetch(fetch)\n }\n return createMcpFetchClient(privateKey)\n}\n\nexport async function createConfiguredGraphMcpFetch(\n config: Pick<InvestigatorConfig, 'graphMcpAuthToken' | 'graphMcpMode'>\n): Promise<FetchLike> {\n if (config.graphMcpMode === 'debug') {\n const authToken = config.graphMcpAuthToken?.trim()\n if (!authToken) {\n throw new Error(\n 'Chain Insights Graph debug mode requires graphMcpAuthToken. Run `cia access-key set <key>` or `cia debug on --token <token>`.'\n )\n }\n // Debug mode still proves the wallet, so the server can read the\n // subscription of the caller (subscription_status) from the proof.\n const privateKey = await usableWalletPrivateKey()\n return createMcpAuthFetchClient(\n authToken,\n privateKey ? createWalletProofFetch(privateKeyToAccount(privateKey), fetch) : fetch\n )\n }\n\n return createConfiguredGraphPaidOrFreeFetch()\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,MAAa,8BAAsD;CACjE,8CAA8C;CAC9C,8CAA8C;CAC9C,8CAA8C;AAChD;;;;;;;;;;;AAYA,SAAgB,oBACd,SACA,YACA,cACqB;CACrB,MAAM,iBAAiB,WACpB,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,CAC1C,OAAO,OAAO;CAEjB,IAAI,eAAe,WAAW,GAAG,OAAO;CAExC,MAAM,UAAU,WAAsC;EACpD,MAAM,eAAe,OAAO,MAAM,YAAY;EAC9C,MAAM,cAAc,aAAa,aAAa,EAAE,YAAY;EAC5D,MAAM,OAAO,eAAe,WACzB,UAAU,UAAU,eAAe,UAAU,YAChD;EACA,OAAO,SAAS,KAAK,eAAe,SAAS;CAC/C;CAEA,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,OAAO,CAAC,CAAC;AAC1D;;;ACvDA,MAAa,0BAA0B;AAEvC,SAAgB,aAAa,MAAc,MAAsB;CAC/D,OAAO,mBAAmB,KAAK,IAAI;AACrC;AAEA,SAAgB,iBAAiB,OAA2B;CAC1D,IAAI,OAAO,UAAU,UACnB,OAAO,IAAI,IAAI,KAAK,CAAC,CAAC;CAExB,IAAI,iBAAiB,KACnB,OAAO,MAAM;CAE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uBAAuB,mBAAmB;EACrF;EACA,OAAO;CACT;CACA,OAAO;AACT;AACA,IAAI,kBAAkB;AAEtB,eAAe,uCAA2D;CACxE,MAAM,aAAa,MAAM,uBAAuB;CAChD,IAAI,CAAC,YACH,OAAO,mCAAmC,KAAK;CAEjD,OAAO,qBAAqB,UAAU;AACxC;AAEA,eAAsB,8BACpB,QACoB;CACpB,IAAI,OAAO,iBAAiB,SAAS;EACnC,MAAM,YAAY,OAAO,mBAAmB,KAAK;EACjD,IAAI,CAAC,WACH,MAAM,IAAI,MACR,+HACF;EAIF,MAAM,aAAa,MAAM,uBAAuB;EAChD,OAAO,yBACL,WACA,aAAa,uBAAuB,oBAAoB,UAAU,GAAG,KAAK,IAAI,KAChF;CACF;CAEA,OAAO,qCAAqC;AAC9C"}
@@ -1,5 +1,6 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- const require_tools = require("./tools-BHfphgy9.cjs");
2
+ const require_tools = require("./tools-Cmnq7yip.cjs");
3
+ const require_robinhood = require("./robinhood-ChiT69sc.cjs");
3
4
  let viem_accounts = require("viem/accounts");
4
5
  let _x402_fetch = require("@x402/fetch");
5
6
  let _x402_evm = require("@x402/evm");
@@ -74,9 +75,8 @@ function createWalletProofFetch(account, baseFetch, now = () => /* @__PURE__ */
74
75
  var client_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
75
76
  PAYMENT_NEXT_STEPS: () => PAYMENT_NEXT_STEPS,
76
77
  PaymentRequiredError: () => PaymentRequiredError,
77
- ROBINHOOD_CHAIN_ID: () => ROBINHOOD_CHAIN_ID,
78
- ROBINHOOD_NETWORK: () => ROBINHOOD_NETWORK,
79
- ROBINHOOD_RPC_URL: () => ROBINHOOD_RPC_URL,
78
+ ROBINHOOD_CHAIN_ID: () => require_robinhood.ROBINHOOD_CHAIN_ID,
79
+ ROBINHOOD_NETWORK: () => require_robinhood.ROBINHOOD_NETWORK,
80
80
  applyMcpAuthHeaders: () => applyMcpAuthHeaders,
81
81
  createConfiguredGraphMcpFetch: () => createConfiguredGraphMcpFetch,
82
82
  createMcpAuthFetchClient: () => createMcpAuthFetchClient,
@@ -84,10 +84,9 @@ var client_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
84
84
  resolveGraphMcpEndpoint: () => resolveGraphMcpEndpoint,
85
85
  resolvePaymentAssetPreference: () => resolvePaymentAssetPreference
86
86
  });
87
- const ROBINHOOD_CHAIN_ID = 4663;
88
- const ROBINHOOD_NETWORK = "eip155:4663";
89
- const ROBINHOOD_RPC_URL = "https://rpc.mainnet.chain.robinhood.com";
90
- const EVM_SCHEME_OPTIONS = { [ROBINHOOD_CHAIN_ID]: { rpcUrl: ROBINHOOD_RPC_URL } };
87
+ function evmSchemeOptions(env = process.env) {
88
+ return { [require_robinhood.ROBINHOOD_CHAIN_ID]: { rpcUrl: require_robinhood.robinhoodRpcUrls(env)[0] } };
89
+ }
91
90
  /**
92
91
  * Reads the operator's payment-asset preference order (env
93
92
  * CHAIN_INSIGHTS_PAYMENT_ASSET_PREFERENCE, comma-separated symbols or
@@ -258,7 +257,7 @@ function createPaymentFailureReportingFetch(baseFetch, payerAddress, paymentWall
258
257
  */
259
258
  function createMcpFetchClient(privateKey, authToken) {
260
259
  const account = (0, viem_accounts.privateKeyToAccount)(privateKey);
261
- const uptoScheme = new _x402_evm_upto_client.UptoEvmScheme(account, EVM_SCHEME_OPTIONS);
260
+ const uptoScheme = new _x402_evm_upto_client.UptoEvmScheme(account, evmSchemeOptions());
262
261
  const reportingFetch = createPaymentFailureReportingFetch((0, _x402_fetch.wrapFetchWithPaymentFromConfig)(createAssetPreferenceReorderingFetch(createWalletProofFetch(account, fetch), resolvePaymentAssetPreference()), { schemes: [
263
262
  {
264
263
  network: "eip155:8453",
@@ -269,7 +268,7 @@ function createMcpFetchClient(privateKey, authToken) {
269
268
  client: new _x402_evm.ExactEvmScheme(account)
270
269
  },
271
270
  {
272
- network: ROBINHOOD_NETWORK,
271
+ network: require_robinhood.ROBINHOOD_NETWORK,
273
272
  client: uptoScheme
274
273
  }
275
274
  ] }), account.address, {
@@ -296,16 +295,36 @@ function createMcpAuthFetchClient(authToken, baseFetch = fetch) {
296
295
  function resolveGraphMcpEndpoint(config) {
297
296
  return config.graphMcpEndpoint.trim();
298
297
  }
298
+ /**
299
+ * The stored wallet's key, or null when no wallet exists or its key is public.
300
+ * A public key signs no payment and no wallet proof: anyone could sign as it.
301
+ */
302
+ async function usableWalletPrivateKey() {
303
+ const { isWalletConfigured, decryptKey } = await Promise.resolve().then(() => require("./wallet-CgIAfdxL.cjs")).then((n) => n.wallet_exports);
304
+ if (!await isWalletConfigured()) return null;
305
+ const privateKey = await decryptKey();
306
+ const { isPrivateKeyPublic, PUBLIC_KEY_WALLET_TEXT } = await Promise.resolve().then(() => require("./known-keys-PKZF5GYd.cjs")).then((n) => n.known_keys_exports);
307
+ if (isPrivateKeyPublic(privateKey)) {
308
+ if (!publicKeyWarned) {
309
+ publicKeyWarned = true;
310
+ process.stderr.write(`[chain-insights] ${PUBLIC_KEY_WALLET_TEXT} It is not used.\n`);
311
+ }
312
+ return null;
313
+ }
314
+ return privateKey;
315
+ }
316
+ let publicKeyWarned = false;
299
317
  async function createConfiguredGraphPaidOrFreeFetch() {
300
- const { isWalletConfigured, decryptKey } = await Promise.resolve().then(() => require("./wallet-B3hAr70M.cjs")).then((n) => n.wallet_exports);
301
- if (!await isWalletConfigured()) return createPaymentFailureReportingFetch(fetch);
302
- return createMcpFetchClient(await decryptKey());
318
+ const privateKey = await usableWalletPrivateKey();
319
+ if (!privateKey) return createPaymentFailureReportingFetch(fetch);
320
+ return createMcpFetchClient(privateKey);
303
321
  }
304
322
  async function createConfiguredGraphMcpFetch(config) {
305
323
  if (config.graphMcpMode === "debug") {
306
324
  const authToken = config.graphMcpAuthToken?.trim();
307
325
  if (!authToken) throw new Error("Chain Insights Graph debug mode requires graphMcpAuthToken. Run `cia access-key set <key>` or `cia debug on --token <token>`.");
308
- return createMcpAuthFetchClient(authToken);
326
+ const privateKey = await usableWalletPrivateKey();
327
+ return createMcpAuthFetchClient(authToken, privateKey ? createWalletProofFetch((0, viem_accounts.privateKeyToAccount)(privateKey), fetch) : fetch);
309
328
  }
310
329
  return createConfiguredGraphPaidOrFreeFetch();
311
330
  }