chain-insights 0.37.1 → 0.37.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.
package/dist/cli.cjs CHANGED
@@ -301,11 +301,11 @@ async function printSubscriptionPassGuidance(pass) {
301
301
  function addAmlAddressRiskCommand(parent, networksCommand) {
302
302
  parent.addCommand(createCliCommand("aml-address-risk").description("CIA workflow: screen an address for AML risk, exchange behavior, and optional comparison with another address").requiredOption("--address <address>", "Full blockchain address to screen").requiredOption("--network <network>", `Network to query. Run \`${networksCommand}\` for supported networks.`).option("--compare-address <address>", "Optional second address to compare against the screened address").option("--json", "Print machine-readable JSON output").option("--version <version>", "AML tool contract version. Omit to use the latest version (currently v1)").addOption(new commander.Option("--tool-version <version>", "Internal alias for the AML tool version").hideHelp()).action(async (opts) => {
303
303
  try {
304
- const { resolveAmlAddressRiskVersion } = await Promise.resolve().then(() => require("./public-tools-cRhdWVRY.cjs"));
304
+ const { resolveAmlAddressRiskVersion } = await Promise.resolve().then(() => require("./public-tools-DWONw7kZ.cjs"));
305
305
  const requestedVersion = opts.toolVersion ?? opts.version;
306
306
  resolveAmlAddressRiskVersion(requestedVersion);
307
307
  await withGraphMcpClient("chain-insights-cli-aml-address-risk", async (client) => {
308
- const { runAmlAddressRisk } = await Promise.resolve().then(() => require("./public-tools-cRhdWVRY.cjs"));
308
+ const { runAmlAddressRisk } = await Promise.resolve().then(() => require("./public-tools-DWONw7kZ.cjs"));
309
309
  const result = await runAmlAddressRisk(client, {
310
310
  address: opts.address,
311
311
  network: opts.network,
@@ -713,7 +713,12 @@ program.command("mcp").description("Low-level access to the Chain Insights MCP e
713
713
  }
714
714
  return;
715
715
  }
716
- printMcpTextContent(await client.callTool({
716
+ const { graphToolRequestOptions } = await Promise.resolve().then(() => require("./request-timeout-CYmQF8N7.cjs"));
717
+ const requestOptions = graphToolRequestOptions(tool);
718
+ printMcpTextContent(requestOptions ? await client.callTool({
719
+ name: tool,
720
+ arguments: args
721
+ }, void 0, requestOptions) : await client.callTool({
717
722
  name: tool,
718
723
  arguments: args
719
724
  }), {
package/dist/cli.mjs CHANGED
@@ -299,11 +299,11 @@ async function printSubscriptionPassGuidance(pass) {
299
299
  function addAmlAddressRiskCommand(parent, networksCommand) {
300
300
  parent.addCommand(createCliCommand("aml-address-risk").description("CIA workflow: screen an address for AML risk, exchange behavior, and optional comparison with another address").requiredOption("--address <address>", "Full blockchain address to screen").requiredOption("--network <network>", `Network to query. Run \`${networksCommand}\` for supported networks.`).option("--compare-address <address>", "Optional second address to compare against the screened address").option("--json", "Print machine-readable JSON output").option("--version <version>", "AML tool contract version. Omit to use the latest version (currently v1)").addOption(new Option("--tool-version <version>", "Internal alias for the AML tool version").hideHelp()).action(async (opts) => {
301
301
  try {
302
- const { resolveAmlAddressRiskVersion } = await import("./public-tools-CYNhQm82.mjs");
302
+ const { resolveAmlAddressRiskVersion } = await import("./public-tools-CDpFHbZ8.mjs");
303
303
  const requestedVersion = opts.toolVersion ?? opts.version;
304
304
  resolveAmlAddressRiskVersion(requestedVersion);
305
305
  await withGraphMcpClient("chain-insights-cli-aml-address-risk", async (client) => {
306
- const { runAmlAddressRisk } = await import("./public-tools-CYNhQm82.mjs");
306
+ const { runAmlAddressRisk } = await import("./public-tools-CDpFHbZ8.mjs");
307
307
  const result = await runAmlAddressRisk(client, {
308
308
  address: opts.address,
309
309
  network: opts.network,
@@ -711,7 +711,12 @@ program.command("mcp").description("Low-level access to the Chain Insights MCP e
711
711
  }
712
712
  return;
713
713
  }
714
- printMcpTextContent(await client.callTool({
714
+ const { graphToolRequestOptions } = await import("./request-timeout-lBBe0mGf.mjs");
715
+ const requestOptions = graphToolRequestOptions(tool);
716
+ printMcpTextContent(requestOptions ? await client.callTool({
717
+ name: tool,
718
+ arguments: args
719
+ }, void 0, requestOptions) : await client.callTool({
715
720
  name: tool,
716
721
  arguments: args
717
722
  }), {
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":[],"sources":["../src/investigation/workflows.ts","../src/mcp/print-result.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","export interface McpTextResult {\n content?: Array<{ type: string; text?: string }>\n isError?: boolean\n}\n\nexport interface McpPrintOptions {\n tool?: string\n json?: boolean\n}\n\ntype JsonRecord = Record<string, unknown>\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction displayValue(value: unknown): string {\n if (value === null || value === undefined) return ''\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\nfunction formatTable(rows: Array<JsonRecord>): string[] {\n if (rows.length === 0) return []\n const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))]\n const values = rows.map((row) => columns.map((column) => displayValue(row[column])))\n const widths = columns.map((column, index) =>\n Math.max(column.length, ...values.map((row) => row[index]?.length ?? 0))\n )\n const line = (row: string[]): string =>\n row\n .map((value, index) => (index === row.length - 1 ? value : value.padEnd(widths[index] ?? 0)))\n .join(' | ')\n return [line(columns), widths.map((width) => '-'.repeat(width)).join('-+-'), ...values.map(line)]\n}\n\nfunction formatGraphResult(value: JsonRecord, fallbackTool?: string): string | null {\n const facts = isRecord(value.facts) ? value.facts : undefined\n const query = facts && isRecord(facts.query) ? facts.query : undefined\n const queries = facts && Array.isArray(facts.queries) ? facts.queries : undefined\n if (!query && !queries) return null\n\n const lines = [`Tool: ${displayValue(value.tool) || fallbackTool || 'MCP result'}`]\n const subject = isRecord(value.subject)\n ? value.subject\n : facts && isRecord(facts.subject)\n ? facts.subject\n : undefined\n if (subject?.network !== undefined) lines.push(`Network: ${displayValue(subject.network)}`)\n\n if (query) {\n const results = Array.isArray(query.results) ? query.results.filter(isRecord) : []\n if (query.count !== undefined) lines.push(`Rows: ${displayValue(query.count)}`)\n else lines.push(`Rows: ${results.length}`)\n if (query.billable_units !== undefined) {\n lines.push(`Billed units: ${displayValue(query.billable_units)}`)\n }\n if (query.elapsed_ms !== undefined) lines.push(`Elapsed: ${displayValue(query.elapsed_ms)} ms`)\n if (query.truncated !== undefined) lines.push(`Truncated: ${displayValue(query.truncated)}`)\n if (query.error !== undefined) lines.push(`Error: ${displayValue(query.error)}`)\n if (results.length > 0) lines.push('', 'Results:', ...formatTable(results))\n else lines.push('', 'Results: none')\n }\n\n if (queries) {\n lines.push(`Queries: ${queries.length}`)\n for (const entry of queries) {\n if (!isRecord(entry)) continue\n const id = displayValue(entry.id) || 'query'\n const results = Array.isArray(entry.results) ? entry.results.filter(isRecord) : []\n lines.push('', `[${id}]`)\n if (entry.error !== undefined) lines.push(`Error: ${displayValue(entry.error)}`)\n lines.push(`Rows: ${displayValue(entry.count ?? results.length)}`)\n if (results.length > 0) lines.push(...formatTable(results))\n else lines.push('Results: none')\n }\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Formats one MCP text block for terminal output. JSON is indented when the\n * caller requests `--json`; graph query envelopes are rendered as a compact\n * result summary and table by default.\n */\nexport function formatMcpTextContent(\n text: string,\n tool?: string,\n options: Pick<McpPrintOptions, 'json'> = {}\n): string {\n let parsed: unknown\n try {\n parsed = JSON.parse(text) as unknown\n } catch {\n return text\n }\n\n if (options.json) {\n try {\n return JSON.stringify(parsed, null, 2)\n } catch {\n return text\n }\n }\n\n if (isRecord(parsed)) {\n return formatGraphResult(parsed, tool) ?? JSON.stringify(parsed, null, 2)\n }\n return displayValue(parsed)\n}\n\n/**\n * Prints the text blocks of an MCP tool result to stdout. When the result is\n * flagged `isError`, throws with the tool's error text instead — MCP `callTool`\n * returns tool errors as ordinary results (it does not reject), so callers must\n * surface them as failures (non-zero exit) rather than printing to stdout and\n * exiting 0.\n */\nexport function printMcpTextContent(result: McpTextResult, options: McpPrintOptions = {}): void {\n const texts = (result.content ?? [])\n .filter((item) => item.type === 'text')\n .map((item) => item.text ?? '')\n\n if (result.isError) {\n throw new Error(texts.join('\\n').trim() || 'MCP tool returned an error')\n }\n\n for (const text of texts) console.log(formatMcpTextContent(text, options.tool, options))\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 type { SubscriptionPass, SubscriptionStatusFacts } from './mcp/subscription-status.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('--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 === '--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' | '--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\ntype SubscriptionStatusLookup =\n { kind: 'available'; facts: SubscriptionStatusFacts } | { kind: 'unavailable'; reason: string }\n\n/**\n * Fetches the caller's subscription facts for the deposit pre-sign guard.\n * The extension math is server-authoritative: the printed values come from\n * `subscription_status`. Any failure (no wallet, unreachable endpoint,\n * missing tool, error result) degrades to an unavailable lookup — the guard\n * must never block the flow on a server that lacks the tool.\n */\nasync function fetchSubscriptionStatusForCli(): Promise<SubscriptionStatusLookup> {\n try {\n const { getWalletAccount } = await import('./wallet/tools.js')\n const account = await getWalletAccount()\n return await withGraphMcpClient(\n 'chain-insights-cli-subscription-status',\n async (client): Promise<SubscriptionStatusLookup> => {\n const result = (await client.callTool({\n name: 'subscription_status',\n arguments: { wallet: account.address },\n })) as {\n content?: Array<{ type: string; text?: string }>\n structuredContent?: Record<string, unknown>\n isError?: boolean\n }\n const { parseSubscriptionStatusToolResult } = await import('./mcp/subscription-status.js')\n const facts = parseSubscriptionStatusToolResult(result)\n if (!facts) {\n return {\n kind: 'unavailable',\n reason: 'the graph endpoint returned no subscription facts',\n }\n }\n return { kind: 'available', facts }\n }\n )\n } catch (err) {\n return { kind: 'unavailable', reason: (err as Error).message }\n }\n}\n\nasync function printSubscriptionPassGuidance(pass: SubscriptionPass): Promise<void> {\n const {\n formatDepositGuardLine,\n formatDepositIrreversibilityWarning,\n formatSubscriptionPassHint,\n isDepositConfirmed,\n resolveSubscriptionMonthUsd,\n } = await import('./mcp/subscription-status.js')\n const hint = formatSubscriptionPassHint(pass, resolveSubscriptionMonthUsd())\n const status = await fetchSubscriptionStatusForCli()\n\n if (status.kind === 'available') {\n process.stderr.write(`${formatDepositGuardLine(status.facts, pass)}\\n`)\n process.stderr.write(\n 'The no-admin subscription sink cannot refund deposits. Type DEPOSIT to continue:\\n'\n )\n const { createInterface } = await import('node:readline/promises')\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 (!isDepositConfirmed(answer)) {\n throw new Error('Deposit cancelled. No deposit was made.')\n }\n console.log(hint)\n return\n }\n\n // Server lacks the tool (or is unreachable): generic irreversibility\n // warning, then proceed with the guidance.\n process.stderr.write(`${formatDepositIrreversibilityWarning(status.reason)}\\n`)\n console.log(hint)\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')\n .action(async (name: string, opts: { json?: boolean }) => {\n try {\n await printNetworkCapability(name, opts)\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('codex')\n .description('Install Codex skills and register the MCP proxy')\n .action(() => {\n runInstaller('--codex')\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('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\nprogram\n .command('buy')\n .description('Show CIA subscription pass deposit guidance (the sink cannot refund deposits)')\n .addCommand(\n createCliCommand('day')\n .description('Show day-pass deposit guidance (SUBSCRIPTION_MONTH_USD / 30)')\n .action(async () => {\n try {\n await printSubscriptionPassGuidance('day')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('month')\n .description('Show month-pass deposit guidance at the list price')\n .action(async () => {\n try {\n await printSubscriptionPassGuidance('month')\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 remote GraphRAG MCP tools only (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 } 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 const args = parseMcpCallArgs(rawArgs)\n assertPublicMcpToolName(tool)\n if (tool === 'aml_address_risk') {\n throw new Error(\n 'aml_address_risk is a CIA workflow. Run `cia workflow aml-address-risk` instead.'\n )\n }\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_help') {\n console.log(\n 'Chain Insights workflow tools: aml_address_risk. Low-level GraphRAG 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 const result = 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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/print-result.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","export interface McpTextResult {\n content?: Array<{ type: string; text?: string }>\n isError?: boolean\n}\n\nexport interface McpPrintOptions {\n tool?: string\n json?: boolean\n}\n\ntype JsonRecord = Record<string, unknown>\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction displayValue(value: unknown): string {\n if (value === null || value === undefined) return ''\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\nfunction formatTable(rows: Array<JsonRecord>): string[] {\n if (rows.length === 0) return []\n const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))]\n const values = rows.map((row) => columns.map((column) => displayValue(row[column])))\n const widths = columns.map((column, index) =>\n Math.max(column.length, ...values.map((row) => row[index]?.length ?? 0))\n )\n const line = (row: string[]): string =>\n row\n .map((value, index) => (index === row.length - 1 ? value : value.padEnd(widths[index] ?? 0)))\n .join(' | ')\n return [line(columns), widths.map((width) => '-'.repeat(width)).join('-+-'), ...values.map(line)]\n}\n\nfunction formatGraphResult(value: JsonRecord, fallbackTool?: string): string | null {\n const facts = isRecord(value.facts) ? value.facts : undefined\n const query = facts && isRecord(facts.query) ? facts.query : undefined\n const queries = facts && Array.isArray(facts.queries) ? facts.queries : undefined\n if (!query && !queries) return null\n\n const lines = [`Tool: ${displayValue(value.tool) || fallbackTool || 'MCP result'}`]\n const subject = isRecord(value.subject)\n ? value.subject\n : facts && isRecord(facts.subject)\n ? facts.subject\n : undefined\n if (subject?.network !== undefined) lines.push(`Network: ${displayValue(subject.network)}`)\n\n if (query) {\n const results = Array.isArray(query.results) ? query.results.filter(isRecord) : []\n if (query.count !== undefined) lines.push(`Rows: ${displayValue(query.count)}`)\n else lines.push(`Rows: ${results.length}`)\n if (query.billable_units !== undefined) {\n lines.push(`Billed units: ${displayValue(query.billable_units)}`)\n }\n if (query.elapsed_ms !== undefined) lines.push(`Elapsed: ${displayValue(query.elapsed_ms)} ms`)\n if (query.truncated !== undefined) lines.push(`Truncated: ${displayValue(query.truncated)}`)\n if (query.error !== undefined) lines.push(`Error: ${displayValue(query.error)}`)\n if (results.length > 0) lines.push('', 'Results:', ...formatTable(results))\n else lines.push('', 'Results: none')\n }\n\n if (queries) {\n lines.push(`Queries: ${queries.length}`)\n for (const entry of queries) {\n if (!isRecord(entry)) continue\n const id = displayValue(entry.id) || 'query'\n const results = Array.isArray(entry.results) ? entry.results.filter(isRecord) : []\n lines.push('', `[${id}]`)\n if (entry.error !== undefined) lines.push(`Error: ${displayValue(entry.error)}`)\n lines.push(`Rows: ${displayValue(entry.count ?? results.length)}`)\n if (results.length > 0) lines.push(...formatTable(results))\n else lines.push('Results: none')\n }\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Formats one MCP text block for terminal output. JSON is indented when the\n * caller requests `--json`; graph query envelopes are rendered as a compact\n * result summary and table by default.\n */\nexport function formatMcpTextContent(\n text: string,\n tool?: string,\n options: Pick<McpPrintOptions, 'json'> = {}\n): string {\n let parsed: unknown\n try {\n parsed = JSON.parse(text) as unknown\n } catch {\n return text\n }\n\n if (options.json) {\n try {\n return JSON.stringify(parsed, null, 2)\n } catch {\n return text\n }\n }\n\n if (isRecord(parsed)) {\n return formatGraphResult(parsed, tool) ?? JSON.stringify(parsed, null, 2)\n }\n return displayValue(parsed)\n}\n\n/**\n * Prints the text blocks of an MCP tool result to stdout. When the result is\n * flagged `isError`, throws with the tool's error text instead — MCP `callTool`\n * returns tool errors as ordinary results (it does not reject), so callers must\n * surface them as failures (non-zero exit) rather than printing to stdout and\n * exiting 0.\n */\nexport function printMcpTextContent(result: McpTextResult, options: McpPrintOptions = {}): void {\n const texts = (result.content ?? [])\n .filter((item) => item.type === 'text')\n .map((item) => item.text ?? '')\n\n if (result.isError) {\n throw new Error(texts.join('\\n').trim() || 'MCP tool returned an error')\n }\n\n for (const text of texts) console.log(formatMcpTextContent(text, options.tool, options))\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 type { SubscriptionPass, SubscriptionStatusFacts } from './mcp/subscription-status.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('--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 === '--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' | '--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\ntype SubscriptionStatusLookup =\n { kind: 'available'; facts: SubscriptionStatusFacts } | { kind: 'unavailable'; reason: string }\n\n/**\n * Fetches the caller's subscription facts for the deposit pre-sign guard.\n * The extension math is server-authoritative: the printed values come from\n * `subscription_status`. Any failure (no wallet, unreachable endpoint,\n * missing tool, error result) degrades to an unavailable lookup — the guard\n * must never block the flow on a server that lacks the tool.\n */\nasync function fetchSubscriptionStatusForCli(): Promise<SubscriptionStatusLookup> {\n try {\n const { getWalletAccount } = await import('./wallet/tools.js')\n const account = await getWalletAccount()\n return await withGraphMcpClient(\n 'chain-insights-cli-subscription-status',\n async (client): Promise<SubscriptionStatusLookup> => {\n const result = (await client.callTool({\n name: 'subscription_status',\n arguments: { wallet: account.address },\n })) as {\n content?: Array<{ type: string; text?: string }>\n structuredContent?: Record<string, unknown>\n isError?: boolean\n }\n const { parseSubscriptionStatusToolResult } = await import('./mcp/subscription-status.js')\n const facts = parseSubscriptionStatusToolResult(result)\n if (!facts) {\n return {\n kind: 'unavailable',\n reason: 'the graph endpoint returned no subscription facts',\n }\n }\n return { kind: 'available', facts }\n }\n )\n } catch (err) {\n return { kind: 'unavailable', reason: (err as Error).message }\n }\n}\n\nasync function printSubscriptionPassGuidance(pass: SubscriptionPass): Promise<void> {\n const {\n formatDepositGuardLine,\n formatDepositIrreversibilityWarning,\n formatSubscriptionPassHint,\n isDepositConfirmed,\n resolveSubscriptionMonthUsd,\n } = await import('./mcp/subscription-status.js')\n const hint = formatSubscriptionPassHint(pass, resolveSubscriptionMonthUsd())\n const status = await fetchSubscriptionStatusForCli()\n\n if (status.kind === 'available') {\n process.stderr.write(`${formatDepositGuardLine(status.facts, pass)}\\n`)\n process.stderr.write(\n 'The no-admin subscription sink cannot refund deposits. Type DEPOSIT to continue:\\n'\n )\n const { createInterface } = await import('node:readline/promises')\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 (!isDepositConfirmed(answer)) {\n throw new Error('Deposit cancelled. No deposit was made.')\n }\n console.log(hint)\n return\n }\n\n // Server lacks the tool (or is unreachable): generic irreversibility\n // warning, then proceed with the guidance.\n process.stderr.write(`${formatDepositIrreversibilityWarning(status.reason)}\\n`)\n console.log(hint)\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')\n .action(async (name: string, opts: { json?: boolean }) => {\n try {\n await printNetworkCapability(name, opts)\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('codex')\n .description('Install Codex skills and register the MCP proxy')\n .action(() => {\n runInstaller('--codex')\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('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\nprogram\n .command('buy')\n .description('Show CIA subscription pass deposit guidance (the sink cannot refund deposits)')\n .addCommand(\n createCliCommand('day')\n .description('Show day-pass deposit guidance (SUBSCRIPTION_MONTH_USD / 30)')\n .action(async () => {\n try {\n await printSubscriptionPassGuidance('day')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n createCliCommand('month')\n .description('Show month-pass deposit guidance at the list price')\n .action(async () => {\n try {\n await printSubscriptionPassGuidance('month')\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 remote GraphRAG MCP tools only (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 } 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 const args = parseMcpCallArgs(rawArgs)\n assertPublicMcpToolName(tool)\n if (tool === 'aml_address_risk') {\n throw new Error(\n 'aml_address_risk is a CIA workflow. Run `cia workflow aml-address-risk` instead.'\n )\n }\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_help') {\n console.log(\n 'Chain Insights workflow tools: aml_address_risk. Low-level GraphRAG 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 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,MA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,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"}
@@ -63,17 +63,17 @@ const GRAPH_SCHEMA_HINTS = [
63
63
  "- Call meta_network_capabilities first. Pass network= exactly as GraphRAG advertised it. CIA does not pick a default network.",
64
64
  "- Coverage is per kind of data. coverage.complete_through_block is the floor of USE facts: below it every raw relationship is indexed. graph_progress.complete_through_block is the floor of USE topology, and graph_progress.layers gives each link kind its own height. An empty answer above the floor may mean not indexed yet, not absent on chain. An absent chain_tip_block means the indexers are catching up: read freshness.max_data_age_seconds for the lag.",
65
65
  "- The graph is address-grain. The only topology money node label is Address, keyed by the raw chain-native H160 address on EVM networks, for example 0x1874a43d7c6d888f9eda3d22a3a49704e3cadb24. The network value on Address nodes matches the tool argument. There is no separate identity key.",
66
- "- Address nodes carry address, network, labels, and the role flags is_exchange, is_scam, is_victim and is_sanctioned. (:Address)-[:LINKED]-(:Address) is an undirected ownership-overlay edge (basis derived/associated, plus confidence, source_event, declared_owner) asserting the two addresses are controlled by the same actor. LINKED is served on the topology graph only. Enumerate LINKED neighbors with MATCH (a:Address {address: $addr})-[l:LINKED]-(b:Address) RETURN b.address, b.network, l.basis, l.confidence.",
66
+ "- Address nodes carry address, network, labels, and the role flags is_exchange, is_scam, is_victim and is_sanctioned. (:Address)-[:LINKED]-(:Address) is an undirected ownership-overlay edge (basis derived/associated, plus confidence, source_event, declared_owner, owner_state) asserting the two addresses are controlled by the same actor. LINKED is served on the topology graph only. Enumerate LINKED neighbors with MATCH (a:Address {address: $addr})-[l:LINKED]-(b:Address) RETURN b.address, b.network, l.basis, l.confidence.",
67
67
  "- Labels hold role words, never detector names: Exchange (plus the exchange name), Scam, Victim and Sanctioned (plus the entity name). Each role is also a node label and a flag on the Address: :Exchange and is_exchange follow the exchange label, :Scam and is_scam the risk label, :Victim and is_victim the protection label, :Sanctioned and is_sanctioned the sanctioned label. Each flag is present only when true and absent otherwise, never false: test IS NOT NULL or IS NULL, not = false. A withdrawn label removes its node label and its flag.",
68
- "- Address nodes also carry a risk verdict (risk_score float, risk_level string) plus base activity rollups: degree_in/degree_out/degree_total (distinct counterparty addresses), tx_in_count/tx_out_count/tx_total_count, total_in_usd/total_out_usd/total_volume_usd, net_flow_usd (in minus out; positive = net receiver) — all computed from external flows only — and first_activity_timestamp/last_activity_timestamp/activity_span_days, which include all flows (self-loops included). FLOWS_TO edges carry exactly tx_count, amount_usd_sum (total money flow, token and native value merged), first_seen_timestamp, last_seen_timestamp. Lifetime aggregates are the only serving window. Averages are computed inline (amount_usd_sum / toFloat(tx_count)); transaction anchors resolve through USE facts: MATCH (a:Address {address: $from})-[t:TRANSFER]->(b:Address {address: $to}) RETURN t.tx_id ORDER BY t.block_timestamp ASC LIMIT 1.",
68
+ "- Address nodes also carry a risk verdict (risk_score float, risk_level string) plus base activity rollups: degree_in/degree_out/degree_total (distinct counterparty addresses), tx_in_count/tx_out_count/tx_total_count, total_in_usd/total_out_usd/total_volume_usd, net_flow_usd (in minus out; positive = net receiver) — all computed from external flows only — and first_activity_timestamp/last_activity_timestamp/activity_span_days, which include all flows (self-loops included). FLOWS_TO edges carry exactly tx_count, amount_usd_sum (total money flow, token and native value merged), first_seen_timestamp, last_seen_timestamp. Lifetime aggregates are the only serving window. Averages are computed inline (amount_usd_sum / toFloat(tx_count)). tx_count counts token and native transfers plus internal native transfers (a contract sending ETH during a call), and amount_usd_sum prices them all. USE facts TRANSFER lists the first group only, so a pair can have tx_count above 0 and no TRANSFER row, and no MCP read lists internal transfers yet. An address-only TRANSFER read covers a recent window (90 days today) and a link covers all time: bound the read with block_date to read further back. For a pair with token or native transfers, a transaction anchor resolves through USE facts: MATCH (a:Address {address: $from})-[t:TRANSFER]->(b:Address {address: $to}) RETURN t.tx_id ORDER BY t.block_timestamp ASC LIMIT 1.",
69
69
  "- For actor-level exposure (AC11), UNION FLOWS_TO and SWAPPED reachability over one visible LINKED hop instead of expanding through the LINKED edge itself: MATCH (a:Address {address: $addr})-[:LINKED]-(owned:Address)-[r:FLOWS_TO|SWAPPED]-(b:Address) WHERE NOT a:Pool AND NOT owned:Pool AND owned.address <> b.address AND a.address <> b.address RETURN owned.address, b.address, type(r), coalesce(r.amount_usd_sum, r.bought_usd).",
70
70
  "- The risk verdict lives on topology nodes (risk_score float, risk_level string). An absent risk_score means UNSCORED: the model gave the address no verdict, which is no signal and never low risk. Labels and per-label risk also live on the address node: the labels array plus three parallel lists, label_risk_labels, label_risk_levels and label_risk_updated_timestamps, where entry i of each list is one label row. USE facts serves bounded single-event rows (TRANSFER, SWAP, LIQUIDITY_ADD, LIQUIDITY_REMOVE and BRIDGE_CROSSING edges) only; lifetime address metrics (degrees, totals, activity window) are node properties on USE topology.",
71
71
  "- (from:Address)-[t:TRANSFER]->(to:Address) on USE facts returns individual transfer rows, not aggregates, with properties amount, amount_usd, asset_symbol, asset_contract, tx_id, block_height, block_timestamp, event_index, edge_index, price_usd, and price_missing. Every TRANSFER query — row-select or count()/sum() aggregate — requires an indexed predicate: address equality on either endpoint (for example {address: \"...\"} on from or to), a WHERE t.tx_id = \"...\" equality (on EVM networks tx_id is the 0x transaction hash), or a bare WHERE t.block_date = \"YYYY-MM-DD\" bound, which t.block_timestamp bounds in epoch milliseconds may narrow to a time window; a bare LIMIT with no indexed predicate is rejected, since facts_transfers_view is a full transfer-history table, not a small per-address dimension view.",
72
72
  "- Facts graph labels include Address; the TRANSFER, SWAP, LIQUIDITY_ADD, LIQUIDITY_REMOVE and BRIDGE_CROSSING relationships each connect two Address nodes. Facts address keys match topology address values exactly.",
73
73
  "- Topology relationships include FLOWS_TO, SWAPPED, OPERATED_BY, LINKED, and RISK_PROXIMITY between Address nodes, ADDED_LIQUIDITY and REMOVED_LIQUIDITY to and from Pool nodes, and BRIDGED to and from Chain nodes.",
74
- "- (:Address)-[:OPERATED_BY]->(:Address) is the directed owner-to-operator edge: the transaction sender that moved the owner's tokens (ERC-20/721), or the event operator (ERC-1155); not the approved spender. Aggregate properties: tx_count, amount_usd_sum, first_seen_timestamp, last_seen_timestamp, and optional token_standard (ERC20/ERC721/ERC1155; absent when the pair is mixed-standard). One edge per owner/operator pair; direct transfers with no operator create none; an owner never operates for itself. Topology-only, and a topology fact — not a risk label. Probe: MATCH (owner:Address)-[operation:OPERATED_BY]->(operator:Address {address: $addr}) RETURN owner.address AS owner, operation.tx_count AS tx_count ORDER BY operation.tx_count DESC LIMIT 10.",
75
- "- FLOWS_TO properties are tx_count, amount_usd_sum, first_seen_timestamp, last_seen_timestamp. pair_key and synced_through_height are internal sync bookkeeping, not to be queried. Tx ids, coverage, and averages come from USE facts or inline arithmetic. FLOWS_TO into and out of pools is kept; the pool trace rule below governs a trace that reaches one.",
76
- "- Swaps, liquidity and bridges on USE topology are lifetime totals per pair; single events are USE facts rows. (:Address)-[:SWAPPED]->(:Address) joins a swap payer to a different recipient, one edge per payer, recipient, sold_asset and bought_asset, with swap_count, sold_amount_raw, bought_amount_raw, sold_usd, bought_usd, pools, families, strength, first_seen_height and last_seen_height. strength is swap (the whole route is proven: payer, recipient, assets, exact raw amounts and conservation) or swap_like (the shape is a swap but the pool matches no reviewed family). A self swap makes no edge, and a missing SWAPPED edge is not proof that no swap happened. Swap attribution is read from SWAPPED, the aggregate (strength, pools, families), or from the USE facts SWAP row, one route. FLOWS_TO carries value only.",
74
+ "- (:Address)-[:OPERATED_BY]->(:Address) is the directed owner-to-operator edge: the transaction sender that moved the owner's tokens (ERC-20/721), or the event operator (ERC-1155); not the approved spender. Aggregate properties: tx_count, amount_usd_sum, first_seen_timestamp, last_seen_timestamp, and optional token_standard (ERC20/ERC721/ERC1155; absent when the pair is mixed-standard). Valuation fields: valuation_tracked_count, valued_count and the reason counters missing_valuation_price_count, unknown_quantity_count, unrepresentable_quantity_count and usd_range_count. valuation_complete is true when valued_count equals valuation_tracked_count, valuation_coverage_ratio is valued_count divided by valuation_tracked_count, and amount_usd_sum counts a transfer with no USD value as 0, so it is a floor unless valuation_complete is true. One edge per owner/operator pair; direct transfers with no operator create none; an owner never operates for itself. Topology-only, and a topology fact — not a risk label. Probe: MATCH (owner:Address)-[operation:OPERATED_BY]->(operator:Address {address: $addr}) RETURN owner.address AS owner, operation.tx_count AS tx_count ORDER BY operation.tx_count DESC LIMIT 10.",
75
+ "- FLOWS_TO properties are tx_count, amount_usd_sum, first_seen_timestamp, last_seen_timestamp. pair_key and synced_through_height are internal sync bookkeeping, not to be queried. synced_through_height is also on the other summed links (SWAPPED, OPERATED_BY, ADDED_LIQUIDITY, REMOVED_LIQUIDITY, BRIDGED, APPROVED, SPONSORED, BUNDLED, SIGNED_FOR) and pair_key on SWAPPED: bookkeeping there too. Tx ids of token and native transfers come from USE facts TRANSFER; internal native transfers have none to read yet. Averages come from inline arithmetic. FLOWS_TO into and out of pools is kept; the pool trace rule below governs a trace that reaches one.",
76
+ "- Swaps, liquidity and bridges on USE topology are lifetime totals per pair; single events are USE facts rows. (:Address)-[:SWAPPED]->(:Address) joins a swap payer to a different recipient, one edge per payer, recipient, sold_asset and bought_asset, with swap_count, sold_amount_raw, bought_amount_raw, sold_usd, bought_usd, pools, families, strength, first_seen_height and last_seen_height. sold_usd and bought_usd sum the routes on the edge at the day price: a route side with no price adds 0, so 0 can mean no price. Do not read 0 as worth nothing. The USE facts SWAP row says which side had no price (sold_price_missing, bought_price_missing). strength is swap (the whole route is proven: payer, recipient, assets, exact raw amounts and conservation) or swap_like (the shape is a swap but the pool code is not proven). Today no route is swap: the swap reader reads transaction receipts only, with no execution trace, so every served route is swap_like, with reason unknown_pool_code and families unknown. A Uniswap V2 or V3 swap reads this way, and unknown does not mean the protocol is unsupported. A filter on strength = \"swap\" or on a known family matches nothing. A route that could not be paired (swap_unsplit) is never served: it has no payer, recipient or pool, makes no SWAPPED edge and no SWAP row, and exists in the warehouse only. Every Uniswap v4 swap is swap_unsplit today, by design, so v4 swaps are hidden. A self swap makes no edge, and a missing SWAPPED edge is not proof that no swap happened. Swap attribution is read from SWAPPED, the aggregate (strength, pools, families), or from the USE facts SWAP row, one route. FLOWS_TO carries value only.",
77
77
  "- Pool is a second label on an Address: the pool of a swap route or liquidity event, with liquidity_added_usd, liquidity_removed_usd, liquidity_net_usd, provider_count and receiver_count. (:Address)-[:ADDED_LIQUIDITY]->(:Pool) and (:Pool)-[:REMOVED_LIQUIDITY]->(:Address) join named providers and receivers to the pool, with event_count, totals_raw, usd, unpriced_count, first_seen_height and last_seen_height; REMOVED_LIQUIDITY adds fees_raw, receiver_added_usd (USD the receiver itself added to the same pool) and receiver_provided. A receiver's profit from a pool is usd minus receiver_added_usd: receiver_provided false is a drain by a stranger, true with a large profit is the creator's rug pull.",
78
78
  "- (:Address)-[:BRIDGED]->(:Chain) is outbound bridge use and (:Chain)-[:BRIDGED]->(:Address) inbound, with kinds, events, totals_raw, first_height, last_height and last_bridge_event_id. A Chain node (network, address) is the remote bridge endpoint, never an Address, so no FLOWS_TO walk passes through it.",
79
79
  "- Pool trace rule, for every trace: 1. Enter a `:Pool` on any edge. 2. Leave a `:Pool` only on `REMOVED_LIQUIDITY`, to the address the liquidity was paid to. 3. Never leave a `:Pool` on `FLOWS_TO`. 4. Across a swap, follow `SWAPPED` from payer to recipient, between two different addresses. Do not walk through the pool. Rug-pull probe: MATCH (victim:Address {address: $addr})-[paid:FLOWS_TO]->(pool:Pool)-[removal:REMOVED_LIQUIDITY]->(receiver:Address) WHERE NOT victim:Pool AND receiver.address <> victim.address RETURN pool.address AS pool_address, receiver.address AS receiver_address, removal.usd AS removed_usd, removal.receiver_added_usd AS receiver_added_usd, removal.receiver_provided AS receiver_provided LIMIT 25.",
@@ -82,6 +82,7 @@ const GRAPH_SCHEMA_HINTS = [
82
82
  "- Pool guard: a trace walks FLOWS_TO and SWAPPED, so it crosses a swap from payer to recipient without passing through the pool. A walk may end at a Pool, but never starts at one or passes through one: its start and every address in its middle stay off a Pool. A fixed-hop walk adds WHERE NOT src:Pool AND NOT mid:Pool, each its own AND term, never inside an OR. A quantified or shortest-path walk puts the guards inside the path pattern, on the start and on up to 4 guarded hops before one last hop: MATCH p = SHORTEST 1 (a:Address {address: $from} WHERE NOT a:Pool) (()-[:FLOWS_TO|SWAPPED]-(via:Address) WHERE NOT via:Pool){0,4} ()-[:FLOWS_TO|SWAPPED]-(b:Address {address: $to}) RETURN [n IN nodes(p) | n.address] AS route. ANY SHORTEST and ALL SHORTEST take the same pattern. An open target from one address: MATCH SHORTEST 1 (a:Address {address: $addr} WHERE NOT a:Pool) (()-[:FLOWS_TO|SWAPPED]-(via:Address) WHERE NOT via:Pool){0,4} ()-[:FLOWS_TO|SWAPPED]-(b:Address) RETURN b.address LIMIT 50. Use these shapes as written, changing only the addresses and the RETURN. A WHERE placed after a SHORTEST pattern runs after the shortest route is chosen, so it drops a route that crosses a pool instead of finding the route that avoids it.",
83
83
  "- Start schema discovery with endpoint-safe property reads: MATCH (n:Address) WHERE n.address IS NOT NULL RETURN n.address AS address, n.network AS network, n.labels AS labels, n.risk_score AS risk_score, n.risk_level AS risk_level LIMIT 20",
84
84
  "- Relationship discovery: MATCH (:Address)-[r:FLOWS_TO]->(:Address) RETURN r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count LIMIT 20",
85
+ "- Anchor every topology read that filters on a link property: put an address in its pattern. Without one, a read starts from every link of the type it names, and you should not count on the filter to narrow that: WHERE x.strength = 'swap' on SWAPPED checks every SWAPPED link, LIMIT stops the read only after enough rows match, and a filter that matches few or none can run to the 60 s topology limit and fail with query_timeout. Example: MATCH (a:Address {address: $addr})-[x:SWAPPED]->(b:Address) WHERE x.swap_count >= 2 RETURN b.address, x.swap_count LIMIT 25. Pick an address with few links: degree_out and degree_in are a rough guide, because they count neighbours, not links, and an address with hundreds of thousands of neighbours can fail the same way. Discovery probes with LIMIT and no filter stay valid. The queries of one batch share a 100 s budget; USE facts queries stop at 30 s.",
85
86
  "- graph_query uses the active Chain Insights graph endpoint. Select the graph with USE topology for topology (address/FLOWS_TO/OPERATED_BY/LINKED graph with SWAPPED, ADDED_LIQUIDITY, REMOVED_LIQUIDITY, BRIDGED and the Pool label, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER, SWAP, LIQUIDITY_ADD, LIQUIDITY_REMOVE and BRIDGE_CROSSING rows and enrichment; address is the node grain, not the topology name.",
86
87
  "- All graph_query calls are read-only. Never use CREATE, INSERT, MERGE, SET, DELETE, REMOVE, DROP, DETACH, ADD, CONNECT, DISCONNECT, ALTER, TRUNCATE, GRANT, or REVOKE.",
87
88
  "- Use USE facts graph patterns for fact and enrichment reads. Do not query internal table namespaces directly."
@@ -769,7 +770,7 @@ async function createProxy() {
769
770
  }],
770
771
  isError: true
771
772
  };
772
- const { runAmlAddressRisk } = await Promise.resolve().then(() => require("./public-tools-cRhdWVRY.cjs"));
773
+ const { runAmlAddressRisk } = await Promise.resolve().then(() => require("./public-tools-DWONw7kZ.cjs"));
773
774
  const result = await runAmlAddressRisk(remoteClient, {
774
775
  address,
775
776
  network,
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-proxy.d.cts","names":[],"sources":["../src/mcp/proxy.ts"],"mappings":";;YA+BY;wBAEI,oBAAoB,MAAK,OAAO,aAA2B;KA2BtE,iBAAiB,eAAe,EAAE;wBAsEvB,2BAA2B,mBAAmB;;;;;;;;wBAwlBxC,eAAe"}
1
+ {"version":3,"file":"mcp-proxy.d.cts","names":[],"sources":["../src/mcp/proxy.ts"],"mappings":";;YA+BY;wBAEI,oBAAoB,MAAK,OAAO,aAA2B;KA2BtE,iBAAiB,eAAe,EAAE;wBAuEvB,2BAA2B,mBAAmB;;;;;;;;wBAwlBxC,eAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-proxy.d.mts","names":[],"sources":["../src/mcp/proxy.ts"],"mappings":";;YA+BY;wBAEI,oBAAoB,MAAK,OAAO,aAA2B;KA2BtE,iBAAiB,eAAe,EAAE;wBAsEvB,2BAA2B,mBAAmB;;;;;;;;wBAwlBxC,eAAe"}
1
+ {"version":3,"file":"mcp-proxy.d.mts","names":[],"sources":["../src/mcp/proxy.ts"],"mappings":";;YA+BY;wBAEI,oBAAoB,MAAK,OAAO,aAA2B;KA2BtE,iBAAiB,eAAe,EAAE;wBAuEvB,2BAA2B,mBAAmB;;;;;;;;wBAwlBxC,eAAe"}
@@ -59,17 +59,17 @@ const GRAPH_SCHEMA_HINTS = [
59
59
  "- Call meta_network_capabilities first. Pass network= exactly as GraphRAG advertised it. CIA does not pick a default network.",
60
60
  "- Coverage is per kind of data. coverage.complete_through_block is the floor of USE facts: below it every raw relationship is indexed. graph_progress.complete_through_block is the floor of USE topology, and graph_progress.layers gives each link kind its own height. An empty answer above the floor may mean not indexed yet, not absent on chain. An absent chain_tip_block means the indexers are catching up: read freshness.max_data_age_seconds for the lag.",
61
61
  "- The graph is address-grain. The only topology money node label is Address, keyed by the raw chain-native H160 address on EVM networks, for example 0x1874a43d7c6d888f9eda3d22a3a49704e3cadb24. The network value on Address nodes matches the tool argument. There is no separate identity key.",
62
- "- Address nodes carry address, network, labels, and the role flags is_exchange, is_scam, is_victim and is_sanctioned. (:Address)-[:LINKED]-(:Address) is an undirected ownership-overlay edge (basis derived/associated, plus confidence, source_event, declared_owner) asserting the two addresses are controlled by the same actor. LINKED is served on the topology graph only. Enumerate LINKED neighbors with MATCH (a:Address {address: $addr})-[l:LINKED]-(b:Address) RETURN b.address, b.network, l.basis, l.confidence.",
62
+ "- Address nodes carry address, network, labels, and the role flags is_exchange, is_scam, is_victim and is_sanctioned. (:Address)-[:LINKED]-(:Address) is an undirected ownership-overlay edge (basis derived/associated, plus confidence, source_event, declared_owner, owner_state) asserting the two addresses are controlled by the same actor. LINKED is served on the topology graph only. Enumerate LINKED neighbors with MATCH (a:Address {address: $addr})-[l:LINKED]-(b:Address) RETURN b.address, b.network, l.basis, l.confidence.",
63
63
  "- Labels hold role words, never detector names: Exchange (plus the exchange name), Scam, Victim and Sanctioned (plus the entity name). Each role is also a node label and a flag on the Address: :Exchange and is_exchange follow the exchange label, :Scam and is_scam the risk label, :Victim and is_victim the protection label, :Sanctioned and is_sanctioned the sanctioned label. Each flag is present only when true and absent otherwise, never false: test IS NOT NULL or IS NULL, not = false. A withdrawn label removes its node label and its flag.",
64
- "- Address nodes also carry a risk verdict (risk_score float, risk_level string) plus base activity rollups: degree_in/degree_out/degree_total (distinct counterparty addresses), tx_in_count/tx_out_count/tx_total_count, total_in_usd/total_out_usd/total_volume_usd, net_flow_usd (in minus out; positive = net receiver) — all computed from external flows only — and first_activity_timestamp/last_activity_timestamp/activity_span_days, which include all flows (self-loops included). FLOWS_TO edges carry exactly tx_count, amount_usd_sum (total money flow, token and native value merged), first_seen_timestamp, last_seen_timestamp. Lifetime aggregates are the only serving window. Averages are computed inline (amount_usd_sum / toFloat(tx_count)); transaction anchors resolve through USE facts: MATCH (a:Address {address: $from})-[t:TRANSFER]->(b:Address {address: $to}) RETURN t.tx_id ORDER BY t.block_timestamp ASC LIMIT 1.",
64
+ "- Address nodes also carry a risk verdict (risk_score float, risk_level string) plus base activity rollups: degree_in/degree_out/degree_total (distinct counterparty addresses), tx_in_count/tx_out_count/tx_total_count, total_in_usd/total_out_usd/total_volume_usd, net_flow_usd (in minus out; positive = net receiver) — all computed from external flows only — and first_activity_timestamp/last_activity_timestamp/activity_span_days, which include all flows (self-loops included). FLOWS_TO edges carry exactly tx_count, amount_usd_sum (total money flow, token and native value merged), first_seen_timestamp, last_seen_timestamp. Lifetime aggregates are the only serving window. Averages are computed inline (amount_usd_sum / toFloat(tx_count)). tx_count counts token and native transfers plus internal native transfers (a contract sending ETH during a call), and amount_usd_sum prices them all. USE facts TRANSFER lists the first group only, so a pair can have tx_count above 0 and no TRANSFER row, and no MCP read lists internal transfers yet. An address-only TRANSFER read covers a recent window (90 days today) and a link covers all time: bound the read with block_date to read further back. For a pair with token or native transfers, a transaction anchor resolves through USE facts: MATCH (a:Address {address: $from})-[t:TRANSFER]->(b:Address {address: $to}) RETURN t.tx_id ORDER BY t.block_timestamp ASC LIMIT 1.",
65
65
  "- For actor-level exposure (AC11), UNION FLOWS_TO and SWAPPED reachability over one visible LINKED hop instead of expanding through the LINKED edge itself: MATCH (a:Address {address: $addr})-[:LINKED]-(owned:Address)-[r:FLOWS_TO|SWAPPED]-(b:Address) WHERE NOT a:Pool AND NOT owned:Pool AND owned.address <> b.address AND a.address <> b.address RETURN owned.address, b.address, type(r), coalesce(r.amount_usd_sum, r.bought_usd).",
66
66
  "- The risk verdict lives on topology nodes (risk_score float, risk_level string). An absent risk_score means UNSCORED: the model gave the address no verdict, which is no signal and never low risk. Labels and per-label risk also live on the address node: the labels array plus three parallel lists, label_risk_labels, label_risk_levels and label_risk_updated_timestamps, where entry i of each list is one label row. USE facts serves bounded single-event rows (TRANSFER, SWAP, LIQUIDITY_ADD, LIQUIDITY_REMOVE and BRIDGE_CROSSING edges) only; lifetime address metrics (degrees, totals, activity window) are node properties on USE topology.",
67
67
  "- (from:Address)-[t:TRANSFER]->(to:Address) on USE facts returns individual transfer rows, not aggregates, with properties amount, amount_usd, asset_symbol, asset_contract, tx_id, block_height, block_timestamp, event_index, edge_index, price_usd, and price_missing. Every TRANSFER query — row-select or count()/sum() aggregate — requires an indexed predicate: address equality on either endpoint (for example {address: \"...\"} on from or to), a WHERE t.tx_id = \"...\" equality (on EVM networks tx_id is the 0x transaction hash), or a bare WHERE t.block_date = \"YYYY-MM-DD\" bound, which t.block_timestamp bounds in epoch milliseconds may narrow to a time window; a bare LIMIT with no indexed predicate is rejected, since facts_transfers_view is a full transfer-history table, not a small per-address dimension view.",
68
68
  "- Facts graph labels include Address; the TRANSFER, SWAP, LIQUIDITY_ADD, LIQUIDITY_REMOVE and BRIDGE_CROSSING relationships each connect two Address nodes. Facts address keys match topology address values exactly.",
69
69
  "- Topology relationships include FLOWS_TO, SWAPPED, OPERATED_BY, LINKED, and RISK_PROXIMITY between Address nodes, ADDED_LIQUIDITY and REMOVED_LIQUIDITY to and from Pool nodes, and BRIDGED to and from Chain nodes.",
70
- "- (:Address)-[:OPERATED_BY]->(:Address) is the directed owner-to-operator edge: the transaction sender that moved the owner's tokens (ERC-20/721), or the event operator (ERC-1155); not the approved spender. Aggregate properties: tx_count, amount_usd_sum, first_seen_timestamp, last_seen_timestamp, and optional token_standard (ERC20/ERC721/ERC1155; absent when the pair is mixed-standard). One edge per owner/operator pair; direct transfers with no operator create none; an owner never operates for itself. Topology-only, and a topology fact — not a risk label. Probe: MATCH (owner:Address)-[operation:OPERATED_BY]->(operator:Address {address: $addr}) RETURN owner.address AS owner, operation.tx_count AS tx_count ORDER BY operation.tx_count DESC LIMIT 10.",
71
- "- FLOWS_TO properties are tx_count, amount_usd_sum, first_seen_timestamp, last_seen_timestamp. pair_key and synced_through_height are internal sync bookkeeping, not to be queried. Tx ids, coverage, and averages come from USE facts or inline arithmetic. FLOWS_TO into and out of pools is kept; the pool trace rule below governs a trace that reaches one.",
72
- "- Swaps, liquidity and bridges on USE topology are lifetime totals per pair; single events are USE facts rows. (:Address)-[:SWAPPED]->(:Address) joins a swap payer to a different recipient, one edge per payer, recipient, sold_asset and bought_asset, with swap_count, sold_amount_raw, bought_amount_raw, sold_usd, bought_usd, pools, families, strength, first_seen_height and last_seen_height. strength is swap (the whole route is proven: payer, recipient, assets, exact raw amounts and conservation) or swap_like (the shape is a swap but the pool matches no reviewed family). A self swap makes no edge, and a missing SWAPPED edge is not proof that no swap happened. Swap attribution is read from SWAPPED, the aggregate (strength, pools, families), or from the USE facts SWAP row, one route. FLOWS_TO carries value only.",
70
+ "- (:Address)-[:OPERATED_BY]->(:Address) is the directed owner-to-operator edge: the transaction sender that moved the owner's tokens (ERC-20/721), or the event operator (ERC-1155); not the approved spender. Aggregate properties: tx_count, amount_usd_sum, first_seen_timestamp, last_seen_timestamp, and optional token_standard (ERC20/ERC721/ERC1155; absent when the pair is mixed-standard). Valuation fields: valuation_tracked_count, valued_count and the reason counters missing_valuation_price_count, unknown_quantity_count, unrepresentable_quantity_count and usd_range_count. valuation_complete is true when valued_count equals valuation_tracked_count, valuation_coverage_ratio is valued_count divided by valuation_tracked_count, and amount_usd_sum counts a transfer with no USD value as 0, so it is a floor unless valuation_complete is true. One edge per owner/operator pair; direct transfers with no operator create none; an owner never operates for itself. Topology-only, and a topology fact — not a risk label. Probe: MATCH (owner:Address)-[operation:OPERATED_BY]->(operator:Address {address: $addr}) RETURN owner.address AS owner, operation.tx_count AS tx_count ORDER BY operation.tx_count DESC LIMIT 10.",
71
+ "- FLOWS_TO properties are tx_count, amount_usd_sum, first_seen_timestamp, last_seen_timestamp. pair_key and synced_through_height are internal sync bookkeeping, not to be queried. synced_through_height is also on the other summed links (SWAPPED, OPERATED_BY, ADDED_LIQUIDITY, REMOVED_LIQUIDITY, BRIDGED, APPROVED, SPONSORED, BUNDLED, SIGNED_FOR) and pair_key on SWAPPED: bookkeeping there too. Tx ids of token and native transfers come from USE facts TRANSFER; internal native transfers have none to read yet. Averages come from inline arithmetic. FLOWS_TO into and out of pools is kept; the pool trace rule below governs a trace that reaches one.",
72
+ "- Swaps, liquidity and bridges on USE topology are lifetime totals per pair; single events are USE facts rows. (:Address)-[:SWAPPED]->(:Address) joins a swap payer to a different recipient, one edge per payer, recipient, sold_asset and bought_asset, with swap_count, sold_amount_raw, bought_amount_raw, sold_usd, bought_usd, pools, families, strength, first_seen_height and last_seen_height. sold_usd and bought_usd sum the routes on the edge at the day price: a route side with no price adds 0, so 0 can mean no price. Do not read 0 as worth nothing. The USE facts SWAP row says which side had no price (sold_price_missing, bought_price_missing). strength is swap (the whole route is proven: payer, recipient, assets, exact raw amounts and conservation) or swap_like (the shape is a swap but the pool code is not proven). Today no route is swap: the swap reader reads transaction receipts only, with no execution trace, so every served route is swap_like, with reason unknown_pool_code and families unknown. A Uniswap V2 or V3 swap reads this way, and unknown does not mean the protocol is unsupported. A filter on strength = \"swap\" or on a known family matches nothing. A route that could not be paired (swap_unsplit) is never served: it has no payer, recipient or pool, makes no SWAPPED edge and no SWAP row, and exists in the warehouse only. Every Uniswap v4 swap is swap_unsplit today, by design, so v4 swaps are hidden. A self swap makes no edge, and a missing SWAPPED edge is not proof that no swap happened. Swap attribution is read from SWAPPED, the aggregate (strength, pools, families), or from the USE facts SWAP row, one route. FLOWS_TO carries value only.",
73
73
  "- Pool is a second label on an Address: the pool of a swap route or liquidity event, with liquidity_added_usd, liquidity_removed_usd, liquidity_net_usd, provider_count and receiver_count. (:Address)-[:ADDED_LIQUIDITY]->(:Pool) and (:Pool)-[:REMOVED_LIQUIDITY]->(:Address) join named providers and receivers to the pool, with event_count, totals_raw, usd, unpriced_count, first_seen_height and last_seen_height; REMOVED_LIQUIDITY adds fees_raw, receiver_added_usd (USD the receiver itself added to the same pool) and receiver_provided. A receiver's profit from a pool is usd minus receiver_added_usd: receiver_provided false is a drain by a stranger, true with a large profit is the creator's rug pull.",
74
74
  "- (:Address)-[:BRIDGED]->(:Chain) is outbound bridge use and (:Chain)-[:BRIDGED]->(:Address) inbound, with kinds, events, totals_raw, first_height, last_height and last_bridge_event_id. A Chain node (network, address) is the remote bridge endpoint, never an Address, so no FLOWS_TO walk passes through it.",
75
75
  "- Pool trace rule, for every trace: 1. Enter a `:Pool` on any edge. 2. Leave a `:Pool` only on `REMOVED_LIQUIDITY`, to the address the liquidity was paid to. 3. Never leave a `:Pool` on `FLOWS_TO`. 4. Across a swap, follow `SWAPPED` from payer to recipient, between two different addresses. Do not walk through the pool. Rug-pull probe: MATCH (victim:Address {address: $addr})-[paid:FLOWS_TO]->(pool:Pool)-[removal:REMOVED_LIQUIDITY]->(receiver:Address) WHERE NOT victim:Pool AND receiver.address <> victim.address RETURN pool.address AS pool_address, receiver.address AS receiver_address, removal.usd AS removed_usd, removal.receiver_added_usd AS receiver_added_usd, removal.receiver_provided AS receiver_provided LIMIT 25.",
@@ -78,6 +78,7 @@ const GRAPH_SCHEMA_HINTS = [
78
78
  "- Pool guard: a trace walks FLOWS_TO and SWAPPED, so it crosses a swap from payer to recipient without passing through the pool. A walk may end at a Pool, but never starts at one or passes through one: its start and every address in its middle stay off a Pool. A fixed-hop walk adds WHERE NOT src:Pool AND NOT mid:Pool, each its own AND term, never inside an OR. A quantified or shortest-path walk puts the guards inside the path pattern, on the start and on up to 4 guarded hops before one last hop: MATCH p = SHORTEST 1 (a:Address {address: $from} WHERE NOT a:Pool) (()-[:FLOWS_TO|SWAPPED]-(via:Address) WHERE NOT via:Pool){0,4} ()-[:FLOWS_TO|SWAPPED]-(b:Address {address: $to}) RETURN [n IN nodes(p) | n.address] AS route. ANY SHORTEST and ALL SHORTEST take the same pattern. An open target from one address: MATCH SHORTEST 1 (a:Address {address: $addr} WHERE NOT a:Pool) (()-[:FLOWS_TO|SWAPPED]-(via:Address) WHERE NOT via:Pool){0,4} ()-[:FLOWS_TO|SWAPPED]-(b:Address) RETURN b.address LIMIT 50. Use these shapes as written, changing only the addresses and the RETURN. A WHERE placed after a SHORTEST pattern runs after the shortest route is chosen, so it drops a route that crosses a pool instead of finding the route that avoids it.",
79
79
  "- Start schema discovery with endpoint-safe property reads: MATCH (n:Address) WHERE n.address IS NOT NULL RETURN n.address AS address, n.network AS network, n.labels AS labels, n.risk_score AS risk_score, n.risk_level AS risk_level LIMIT 20",
80
80
  "- Relationship discovery: MATCH (:Address)-[r:FLOWS_TO]->(:Address) RETURN r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count LIMIT 20",
81
+ "- Anchor every topology read that filters on a link property: put an address in its pattern. Without one, a read starts from every link of the type it names, and you should not count on the filter to narrow that: WHERE x.strength = 'swap' on SWAPPED checks every SWAPPED link, LIMIT stops the read only after enough rows match, and a filter that matches few or none can run to the 60 s topology limit and fail with query_timeout. Example: MATCH (a:Address {address: $addr})-[x:SWAPPED]->(b:Address) WHERE x.swap_count >= 2 RETURN b.address, x.swap_count LIMIT 25. Pick an address with few links: degree_out and degree_in are a rough guide, because they count neighbours, not links, and an address with hundreds of thousands of neighbours can fail the same way. Discovery probes with LIMIT and no filter stay valid. The queries of one batch share a 100 s budget; USE facts queries stop at 30 s.",
81
82
  "- graph_query uses the active Chain Insights graph endpoint. Select the graph with USE topology for topology (address/FLOWS_TO/OPERATED_BY/LINKED graph with SWAPPED, ADDED_LIQUIDITY, REMOVED_LIQUIDITY, BRIDGED and the Pool label, unified recent+historical, plus the node risk_score/risk_level verdict) and USE facts for bounded TRANSFER, SWAP, LIQUIDITY_ADD, LIQUIDITY_REMOVE and BRIDGE_CROSSING rows and enrichment; address is the node grain, not the topology name.",
82
83
  "- All graph_query calls are read-only. Never use CREATE, INSERT, MERGE, SET, DELETE, REMOVE, DROP, DETACH, ADD, CONNECT, DISCONNECT, ALTER, TRUNCATE, GRANT, or REVOKE.",
83
84
  "- Use USE facts graph patterns for fact and enrichment reads. Do not query internal table namespaces directly."
@@ -765,7 +766,7 @@ async function createProxy() {
765
766
  }],
766
767
  isError: true
767
768
  };
768
- const { runAmlAddressRisk } = await import("./public-tools-CYNhQm82.mjs");
769
+ const { runAmlAddressRisk } = await import("./public-tools-CDpFHbZ8.mjs");
769
770
  const result = await runAmlAddressRisk(remoteClient, {
770
771
  address,
771
772
  network,