chain-insights 0.2.26 → 0.2.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +3 -0
  2. package/dist/{capabilities-mXm_rCe8.mjs → capabilities-BCm-2oBt.mjs} +2 -2
  3. package/dist/{capabilities-mXm_rCe8.mjs.map → capabilities-BCm-2oBt.mjs.map} +1 -1
  4. package/dist/{capabilities-B4hvro_I.cjs → capabilities-C1-Y-VZx.cjs} +1 -1
  5. package/dist/cli.cjs +13 -13
  6. package/dist/cli.mjs +14 -14
  7. package/dist/cli.mjs.map +1 -1
  8. package/dist/{client-Dl-uHrh1.mjs → client-Bfw9P9uA.mjs} +3 -3
  9. package/dist/client-Bfw9P9uA.mjs.map +1 -0
  10. package/dist/{client-BYnFGA0y.cjs → client-DRJq31u_.cjs} +2 -2
  11. package/dist/index.cjs +3 -3
  12. package/dist/index.mjs +3 -3
  13. package/dist/{init-jhOZ_RvC.cjs → init-CFaUWgjK.cjs} +1 -1
  14. package/dist/{init-CB_ga4_8.mjs → init-DBC9Ml33.mjs} +2 -2
  15. package/dist/{init-CB_ga4_8.mjs.map → init-DBC9Ml33.mjs.map} +1 -1
  16. package/dist/mcp-proxy.cjs +3 -3
  17. package/dist/mcp-proxy.mjs +3 -3
  18. package/dist/{runner-BBH5Ks6q.mjs → runner-C-QgZu-S.mjs} +2 -2
  19. package/dist/{runner-BBH5Ks6q.mjs.map → runner-C-QgZu-S.mjs.map} +1 -1
  20. package/dist/{runner-e9slg6R2.cjs → runner-Ckl96RcN.cjs} +1 -1
  21. package/dist/{tools-D6RBAhSX.mjs → tools-6emZlUwg.mjs} +6 -6
  22. package/dist/tools-6emZlUwg.mjs.map +1 -0
  23. package/dist/{tools-UH5hRXYG.cjs → tools-kqWI7jPU.cjs} +5 -5
  24. package/dist/{topup-server-yAaXYkJP.cjs → topup-server-DhYlOOBM.cjs} +2 -2
  25. package/dist/{topup-server-BJgVw6Jt.mjs → topup-server-R3dNp-p8.mjs} +3 -3
  26. package/dist/topup-server-R3dNp-p8.mjs.map +1 -0
  27. package/docs/mcp-proxy.md +5 -2
  28. package/package.json +1 -1
  29. package/dist/client-Dl-uHrh1.mjs.map +0 -1
  30. package/dist/tools-D6RBAhSX.mjs.map +0 -1
  31. package/dist/topup-server-BJgVw6Jt.mjs.map +0 -1
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { Command } 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'\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\nprogram\n .name('chain-insights')\n .description('AML investigation toolkit for blockchain analysis')\n .version(PACKAGE_INFO.version)\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('--hermes', 'Install Hermes skills globally to ~/.hermes/skills/chain-insights/ and register MCP')\n\n// Handle installer flags when invoked with no subcommand (bare `chain-insights --claude`)\nconst rawArgs = process.argv.slice(2)\nconst installerFlags = rawArgs.filter(a => a === '--claude' || a === '--codex' || a === '--hermes')\nif (installerFlags.length > 0 && !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\nif (rawArgs[0] === 'mcp' && rawArgs[1] === 'trace-funds') {\n console.error(\"error: unknown command 'trace-funds'\")\n process.exit(1)\n}\n\nasync function resolveCaseSelector(input: string): Promise<string> {\n const { resolveCaseSelector } = await import('./cases/selector.js')\n return resolveCaseSelector(input)\n}\n\nasync function scopeCasesToInvocationDir(): Promise<void> {\n if (process.env['CHAIN_INSIGHTS_CASES_ROOT']?.trim()) return\n const { activeCasesRoot } = await import('./workspace/active.js')\n process.env['CHAIN_INSIGHTS_CASES_ROOT'] = activeCasesRoot()\n}\n\nasync function showCaseContext(caseSelector: string): Promise<void> {\n const { CaseStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const ctx = await CaseStore.loadContext(caseId)\n console.log(`\\n=== Case: ${ctx.case.id} ===`)\n console.log(`Name: ${ctx.case.name}`)\n console.log(`Status: ${ctx.case.status}`)\n console.log(`Tags: ${ctx.case.tags.join(', ') || 'none'}`)\n console.log(`Evidence files: ${ctx.evidenceCount}`)\n console.log(`Dossiers: ${ctx.dossierSummaries.length}`)\n if (ctx.lastSession) {\n console.log(`\\n--- Last Session (${ctx.lastSession.sessionId}) ---`)\n console.log(ctx.lastSession.body.slice(0, 500))\n } else {\n console.log('\\nNo previous sessions.')\n }\n if (ctx.dossierSummaries.length > 0) {\n console.log('\\n--- Entity Dossiers ---')\n for (const d of ctx.dossierSummaries) {\n console.log(` ${d.address} [${d.type}] tags: ${d.riskTags || 'none'}`)\n }\n }\n}\n\nfunction optionalNumber(value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const parsed = Number(value)\n if (!Number.isFinite(parsed)) throw new Error(`Invalid number: ${value}`)\n return parsed\n}\n\nfunction optionalNumberArg(value: unknown, name: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') return optionalNumber(value)\n throw new Error(`Invalid number for ${name}: ${String(value)}`)\n}\n\ntype ScamTopologyActivityPolicyModeArg = 'node_relative_only' | 'global_incident_only'\n\nfunction optionalScamTopologyActivityPolicy(value: unknown): ScamTopologyActivityPolicyModeArg | undefined {\n if (value === undefined || value === null || value === '') return undefined\n if (value === 'node_relative_only' || value === 'global_incident_only') return value\n throw new Error('activity_policy must be one of: node_relative_only, global_incident_only')\n}\n\nasync function withGraphMcpClient<T>(name: string, fn: (client: import('@modelcontextprotocol/sdk/client/index.js').Client, config: Awaited<ReturnType<typeof import('./config/index.js').loadConfig>>) => Promise<T>): Promise<T> {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n const paymentFetch = await createConfiguredGraphMcpFetch(config)\n const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')\n const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name, version: PACKAGE_VERSION })\n await client.connect(new StreamableHTTPClientTransport(new URL(resolveGraphMcpEndpoint(config)), { fetch: paymentFetch }))\n try {\n return await fn(client, config)\n } finally {\n await client.close()\n }\n}\n\nfunction printMcpTextContent(result: { content?: Array<{ type: string; text?: string }> }): void {\n for (const item of result.content ?? []) {\n if (item.type === 'text') console.log(item.text)\n }\n}\n\nasync function printNetworkCapabilities(opts: { json?: boolean }): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { fetchNetworkCapabilities, formatNetworkCapabilities } = 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\nprogram\n .command('networks')\n .alias('network')\n .description('List supported graph networks, capability layers, retention, and freshness')\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\nprogram\n .command('serve')\n .description('Start local visualization server')\n .option('-p, --port <number>', 'Port to bind (default: 4321)', '4321')\n .action(async (opts: { port: string }) => {\n try {\n const { requireWorkspaceRoot } = await import('./workspace/output-root.js')\n const workspaceRoot = requireWorkspaceRoot()\n const { startServer } = await import('./server/index.js')\n console.log(`Workspace: ${workspaceRoot}`)\n startServer(parseInt(opts.port, 10))\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\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 { findActiveWorkspace, activeDataDir } = await import('./workspace/active.js')\n const config = await loadConfig()\n const workspace = findActiveWorkspace()\n const graphMcpStatus = config.graphMcpMode === 'debug' && config.graphMcpAuthToken?.trim()\n ? 'bearer access mode'\n : `${config.graphMcpMode} mode`\n console.log('Config: ', activeDataDir(config.dataDir))\n if (workspace) console.log('Workspace:', workspace.root)\n console.log('Server: ', `http://127.0.0.1:${config.serverPort}`)\n console.log('Graph MCP:', graphMcpStatus)\n console.log('Graph endpoint:', config.graphMcpEndpoint)\n })\n\nprogram\n .command('debug')\n .description('Configure Graph MCP debug mode')\n .addCommand(\n new Command('on')\n .description('Enable Graph MCP debug mode without x402 payments')\n .requiredOption('--token <token>', 'Debug bearer token')\n .option('--endpoint <url>', 'Graph MCP 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('Graph MCP debug mode enabled')\n if (opts.endpoint) console.log(`Graph endpoint: ${opts.endpoint}`)\n console.log('Payments: disabled for Graph MCP calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('off')\n .description('Disable Graph MCP 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('Graph MCP debug mode disabled')\n console.log('Payments: enabled for Graph MCP calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('status')\n .description('Show Graph MCP payment/debug mode')\n .action(async () => {\n try {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n console.log(`Graph MCP mode: ${config.graphMcpMode}`)\n console.log(`Graph endpoint: ${config.graphMcpEndpoint}`)\n console.log(`Debug token: ${config.graphMcpAuthToken?.trim() ? 'configured' : 'not configured'}`)\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 Graph MCP test access key mode')\n .addCommand(\n new Command('set')\n .description('Use a Graph MCP test access key without x402 payments')\n .argument('<key>', 'Test access key')\n .option('--endpoint <url>', 'Graph MCP 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('Graph MCP 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 new Command('clear')\n .description('Remove the Graph MCP 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('Graph MCP test access key cleared')\n console.log('Payments: enabled for Graph MCP calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('status')\n .description('Show Graph MCP 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(`Access key: ${config.graphMcpAuthToken?.trim() ? 'configured' : 'not configured'}`)\n console.log(`Payments: ${config.graphMcpAuthToken?.trim() ? 'disabled when accepted by server' : 'enabled'}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('init')\n .description('Initialize an investigation workspace')\n .argument('[dir]', 'Workspace directory to initialize', '.')\n .option('--force', 'Overwrite existing workspace files')\n .action(async (dir: string, opts: { force?: boolean }) => {\n try {\n const { initWorkspace } = await import('./workspace/init.js')\n const result = await initWorkspace({ targetDir: dir, force: opts.force })\n console.log(`Workspace initialized: ${result.workspaceRoot}`)\n console.log(`Files written: ${result.filesWritten.length}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram\n .command('setup')\n .description('Configure external MCP clients')\n .addCommand(\n new Command('claude-desktop')\n .alias('claude')\n .description('Install or update the Claude Desktop MCP server entry')\n .option('--config <path>', 'Path to claude_desktop_config.json')\n .option('--dry-run', 'Print the intended change without writing files')\n .action(async (opts: { config?: string; dryRun?: boolean }) => {\n try {\n const { setupClaudeDesktop } = await import('./claude-desktop/setup.js')\n const result = await setupClaudeDesktop({\n configPath: opts.config,\n dryRun: opts.dryRun,\n })\n\n console.log(`Claude Desktop config: ${result.configPath}`)\n console.log('MCP server: chain-insights')\n console.log(`Command: ${result.command}`)\n console.log(`Args: ${result.args.join(' ')}`)\n if (result.dryRun) {\n console.log(`Dry run: ${result.changed ? 'would update config' : 'already up to date'}`)\n } else if (result.changed) {\n console.log(`Updated: yes`)\n if (result.backupPath) console.log(`Backup: ${result.backupPath}`)\n } else {\n console.log('Updated: already up to date')\n }\n console.log('Reload required: quit and reopen Claude Desktop; it does not hot-reload MCP config.')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('config')\n .description('Read or write configuration values')\n .addCommand(\n new Command('get')\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 new Command('set')\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 = 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 new Command('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 new Command('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 new Command('ready')\n .description('Check and prepare the wallet for paid GraphRAG MCP calls')\n .option('--no-approve', 'Only check readiness; do not submit the one-time payment approval')\n .option('--approval-usdc <amount>', 'USDC approval cap to prepare for paid calls', '1')\n .option('--json', 'Print machine-readable readiness metadata')\n .action(async (opts: { approve?: boolean; approvalUsdc?: string; json?: boolean }) => {\n try {\n const { formatWalletReadiness, parsePaymentApprovalUnits, prepareWalletForPaidCalls } = await import('./wallet/tools.js')\n const minimumApprovalUnits = parsePaymentApprovalUnits(opts.approvalUsdc ?? '1')\n const result = await prepareWalletForPaidCalls({\n minimumApprovalUnits,\n approve: opts.approve !== false,\n })\n\n if (opts.json) {\n console.log(JSON.stringify(result, (_key, value) => (\n typeof value === 'bigint' ? value.toString() : value\n ), 2))\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 .addCommand(\n new Command('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('mcp')\n .description('Interact with the Chain Insights MCP endpoint')\n .allowExcessArguments(false)\n .addCommand(\n new Command('networks')\n .description('List supported graph networks, capability layers, retention, and freshness')\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 new Command('tools')\n .description('List available MCP tools (cached 24h)')\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 } = 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 } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name: 'chain-insights-cli', version: PACKAGE_VERSION })\n await client.connect(new StreamableHTTPClientTransport(new URL(graphMcpEndpoint), { fetch: paymentFetch }))\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 .addCommand(\n new Command('address-risk')\n .description('Screen an address for risk, exchange behavior, and optional compare_address connection risk')\n .requiredOption('--address <address>', 'Full blockchain address to screen')\n .requiredOption('--network <network>', 'Network to query. Run `cia mcp networks` for supported networks.')\n .option('--compare-address <address>', 'Optional second address for connection-risk compare mode')\n .option('--remote', 'Force remote MCP tool call instead of local Chain Insights recipe')\n .action(async (opts: { address: string; network: string; compareAddress?: string; remote?: boolean }) => {\n try {\n await withGraphMcpClient('chain-insights-cli-address-risk', async (client) => {\n if (opts.remote) {\n const result = await client.callTool({\n name: 'address_risk',\n arguments: {\n address: opts.address,\n network: opts.network,\n ...(opts.compareAddress ? { compare_address: opts.compareAddress } : {}),\n },\n })\n printMcpTextContent(result as { content?: Array<{ type: string; text?: string }> })\n return\n }\n const { addressRisk } = await import('./investigation/public-tools.js')\n const result = await addressRisk(client, {\n address: opts.address,\n network: opts.network,\n compareAddress: opts.compareAddress,\n })\n console.log(result.summaryText)\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('track-funds')\n .description('Trace trusted/victim addresses and optional known untrusted/scammer addresses')\n .requiredOption('--trusted-addresses <addresses>', 'Comma-separated full trusted/victim addresses, max 5')\n .requiredOption('--network <network>', 'Network to query. Run `cia mcp networks` for supported networks.')\n .option('--untrusted-addresses <addresses>', 'Comma-separated full known untrusted/scammer addresses, max 5')\n .option('--case <id>', 'Case ID to attach compact evidence pointers')\n .option('--max-hops <number>', 'Maximum trace hops, 1-5')\n .option('--per-address-limit <number>', 'Maximum exchange paths/results per address, 1-10')\n .option('--min-amount-sum <number>', 'Minimum r.amount_sum for traced edges')\n .option('--remote', 'Force remote MCP tool call instead of local Chain Insights recipe')\n .action(async (opts: {\n trustedAddresses: string\n network: string\n untrustedAddresses?: string\n case?: string\n maxHops?: string\n perAddressLimit?: string\n minAmountSum?: string\n remote?: boolean\n }) => {\n try {\n const { requireWorkspaceRoot } = await import('./workspace/output-root.js')\n requireWorkspaceRoot()\n await withGraphMcpClient('chain-insights-cli-track-funds', async (client, config) => {\n if (opts.remote) {\n const result = await client.callTool({\n name: 'track_funds',\n arguments: {\n trusted_addresses: opts.trustedAddresses,\n network: opts.network,\n ...(opts.untrustedAddresses ? { untrusted_addresses: opts.untrustedAddresses } : {}),\n },\n })\n printMcpTextContent(result as { content?: Array<{ type: string; text?: string }> })\n return\n }\n const { trackFunds } = await import('./investigation/public-tools.js')\n const caseId = opts.case ? await resolveCaseSelector(opts.case) : undefined\n const result = await trackFunds(client, config, {\n trustedAddresses: opts.trustedAddresses,\n untrustedAddresses: opts.untrustedAddresses,\n network: opts.network,\n caseId,\n maxHops: optionalNumber(opts.maxHops),\n perAddressLimit: optionalNumber(opts.perAddressLimit),\n minAmountSum: optionalNumber(opts.minAmountSum),\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('scam-topology')\n .description('Build victim-incident scam topology and ML-ready scam labels')\n .requiredOption('--network <network>', 'Network to query. Run `cia mcp networks` for supported networks.')\n .requiredOption('--victim-address <address>', 'Full victim/source address that anchors the incident')\n .requiredOption('--incident-timestamp-ms <milliseconds>', 'Earliest known incident transfer timestamp in milliseconds')\n .option('--max-hops <number>', 'Maximum trace hops, default 16, max 64')\n .option('--activity-policy <mode>', 'Traversal activity policy: node_relative_only or global_incident_only', 'node_relative_only')\n .option('--case <id>', 'Case ID to attach compact evidence pointers')\n .action(async (opts: {\n network: string\n victimAddress: string\n incidentTimestampMs: string\n maxHops?: string\n activityPolicy?: string\n case?: string\n }) => {\n try {\n const { requireWorkspaceRoot } = await import('./workspace/output-root.js')\n requireWorkspaceRoot()\n await withGraphMcpClient('chain-insights-cli-scam-topology', async (client, config) => {\n const { scamTopology } = await import('./investigation/public-tools.js')\n const incidentTimestampMs = optionalNumber(opts.incidentTimestampMs)\n if (incidentTimestampMs === undefined) throw new Error('incident-timestamp-ms is required')\n const caseId = opts.case ? await resolveCaseSelector(opts.case) : undefined\n const result = await scamTopology(client, config, {\n victimAddress: opts.victimAddress,\n network: opts.network,\n maxHops: optionalNumber(opts.maxHops),\n incidentTimestampMs,\n activityPolicyMode: optionalScamTopologyActivityPolicy(opts.activityPolicy),\n caseId,\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('stake-insights')\n .description('Explain Bittensor staking behavior around an address, coldkey, or hotkey')\n .requiredOption('--network <network>', 'Network to query. Run `cia mcp networks` for supported networks.')\n .option('--address <address>', 'Full Bittensor address to inspect as either coldkey or hotkey')\n .option('--coldkey <address>', 'Full Bittensor coldkey address to inspect')\n .option('--hotkey <address>', 'Full Bittensor hotkey address to inspect')\n .option('--netuid <number>', 'Optional subnet netuid filter')\n .option('--start-timestamp-ms <milliseconds>', 'Optional inclusive lower activity timestamp bound')\n .option('--end-timestamp-ms <milliseconds>', 'Optional inclusive upper activity timestamp bound')\n .option('--start-block <number>', 'Optional start block. Current stake graph parity may require timestamp windows instead.')\n .option('--end-block <number>', 'Optional end block. Current stake graph parity may require timestamp windows instead.')\n .option('--depth <number>', 'Optional expansion depth limit, default 1, max 3')\n .action(async (opts: {\n network: string\n address?: string\n coldkey?: string\n hotkey?: string\n netuid?: string\n startTimestampMs?: string\n endTimestampMs?: string\n startBlock?: string\n endBlock?: string\n depth?: string\n }) => {\n try {\n await withGraphMcpClient('chain-insights-cli-stake-insights', async (client) => {\n const { stakeInsights } = await import('./investigation/public-tools.js')\n const result = await stakeInsights(client, {\n network: opts.network,\n address: opts.address,\n coldkey: opts.coldkey,\n hotkey: opts.hotkey,\n netuid: optionalNumber(opts.netuid),\n startTimestampMs: optionalNumber(opts.startTimestampMs),\n endTimestampMs: optionalNumber(opts.endTimestampMs),\n startBlock: optionalNumber(opts.startBlock),\n endBlock: optionalNumber(opts.endBlock),\n depth: optionalNumber(opts.depth),\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('call')\n .description('Call an MCP tool directly (debug)')\n .argument('<tool>', 'Tool name to call')\n .argument('[args...]', 'Key=value arguments (e.g. address=0x1234 chain=ethereum)')\n .action(async (tool: string, rawArgs: string[]) => {\n try {\n const { parseMcpCallArgs } = await import('./mcp/call-args.js')\n const { assertPublicMcpToolName } = await import('./mcp/tool-visibility.js')\n const args = parseMcpCallArgs(rawArgs)\n assertPublicMcpToolName(tool)\n await withGraphMcpClient('chain-insights-cli-call', async (client, config) => {\n if (tool === 'address_risk') {\n const { addressRisk } = await import('./investigation/public-tools.js')\n const result = await addressRisk(client, {\n address: String(args['address'] ?? ''),\n network: String(args['network'] ?? ''),\n compareAddress: args['compare_address'] === undefined ? undefined : String(args['compare_address']),\n })\n console.log(result.summaryText)\n return\n }\n if (tool === 'track_funds') {\n const { trackFunds } = await import('./investigation/public-tools.js')\n const result = await trackFunds(client, config, {\n trustedAddresses: args['trusted_addresses'] as string | string[] | undefined ?? '',\n untrustedAddresses: args['untrusted_addresses'] as string | string[] | undefined,\n network: String(args['network'] ?? ''),\n caseId: args['case_id'] === undefined ? undefined : String(args['case_id']),\n maxHops: typeof args['max_hops'] === 'number' ? args['max_hops'] : undefined,\n perAddressLimit: typeof args['per_address_limit'] === 'number' ? args['per_address_limit'] : undefined,\n minAmountSum: typeof args['min_amount_sum'] === 'number' ? args['min_amount_sum'] : undefined,\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n return\n }\n if (tool === 'scam_topology') {\n const { scamTopology } = await import('./investigation/public-tools.js')\n const victimAddress = String(args['victim_address'] ?? '').trim()\n if (!victimAddress) throw new Error('victim_address is required')\n const incidentTimestampMs = optionalNumberArg(args['incident_timestamp_ms'], 'incident_timestamp_ms')\n if (incidentTimestampMs === undefined) throw new Error('incident_timestamp_ms is required')\n const result = await scamTopology(client, config, {\n victimAddress,\n network: String(args['network'] ?? ''),\n caseId: args['case_id'] === undefined ? undefined : String(args['case_id']),\n maxHops: typeof args['max_hops'] === 'number' ? args['max_hops'] : undefined,\n incidentTimestampMs,\n activityPolicyMode: optionalScamTopologyActivityPolicy(args['activity_policy']),\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n return\n }\n if (tool === 'stake_insights') {\n const { stakeInsights } = await import('./investigation/public-tools.js')\n const result = await stakeInsights(client, {\n network: String(args['network'] ?? ''),\n address: args['address'] === undefined ? undefined : String(args['address']),\n coldkey: args['coldkey'] === undefined ? undefined : String(args['coldkey']),\n hotkey: args['hotkey'] === undefined ? undefined : String(args['hotkey']),\n netuid: optionalNumberArg(args['netuid'], 'netuid'),\n startTimestampMs: optionalNumberArg(args['start_timestamp_ms'], 'start_timestamp_ms'),\n endTimestampMs: optionalNumberArg(args['end_timestamp_ms'], 'end_timestamp_ms'),\n startBlock: optionalNumberArg(args['start_block'], 'start_block'),\n endBlock: optionalNumberArg(args['end_block'], 'end_block'),\n depth: optionalNumberArg(args['depth'] ?? args['max_hops'], 'depth'),\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n return\n }\n const result = await client.callTool({ name: tool, arguments: args })\n printMcpTextContent(result as { content?: Array<{ type: string; text?: string }> })\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nconst caseCommand = new Command('case')\n .description('Manage investigation cases')\n .hook('preAction', async () => {\n await scopeCasesToInvocationDir()\n })\n .addCommand(\n new Command('open')\n .description('Open a new investigation case')\n .argument('<name>', 'Case name (e.g. \"Tornado Mixer Investigation\")')\n .option('--tags <tags>', 'Comma-separated tags (e.g. aml,mixer,defi)', '')\n .option('--description <desc>', 'Brief description of the investigation', '')\n .action(async (name: string, opts: { tags: string; description: string }) => {\n try {\n if (/^[1-9]\\d*$/.test(name.trim())) {\n throw new Error('Numeric case names look like list selectors. Use a descriptive case name, e.g. `cia case open \"Tracking stolen funds from <address>\"`.')\n }\n const { CaseStore } = await import('./cases/index.js')\n const tags = opts.tags ? opts.tags.split(',').map(t => t.trim()).filter(Boolean) : []\n const c = await CaseStore.create({ name, tags, description: opts.description })\n const { casesRoot } = await import('./cases/store.js')\n console.log(`Case opened: ${c.id}`)\n console.log(`Directory: ${path.join(casesRoot(), c.id)}/`)\n console.log(`Status: ${c.status}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('activate')\n .description('Activate a case (set status to active)')\n .argument('<case-id>', 'Case ID to activate')\n .action(async (caseSelector: string) => {\n try {\n const { CaseStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const c = await CaseStore.setStatus(caseId, 'active')\n console.log(`Case ${c.id} is now: active`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('suspend')\n .description('Suspend a case (set status to suspended)')\n .argument('<case-id>', 'Case ID to suspend')\n .action(async (caseSelector: string) => {\n try {\n const { CaseStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const c = await CaseStore.setStatus(caseId, 'suspended')\n console.log(`Case ${c.id} is now: suspended`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('close')\n .description('Close a case permanently')\n .argument('<case-id>', 'Case ID to close')\n .action(async (caseSelector: string) => {\n try {\n const { CaseStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const c = await CaseStore.setStatus(caseId, 'closed')\n console.log(`Case ${c.id} is now: closed`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('list')\n .description('List all investigation cases')\n .option('--status <status>', 'Filter by status (open|active|suspended|closed)')\n .action(async (opts: { status?: string }) => {\n try {\n const { CaseStore } = await import('./cases/index.js')\n const cases = await CaseStore.list()\n const filtered = opts.status ? cases.filter(c => c.status === opts.status) : cases\n if (filtered.length === 0) {\n console.log('No cases found.')\n return\n }\n for (const [index, c] of filtered.entries()) {\n console.log(`${index + 1}. ${c.id} [${c.status}] ${c.name}`)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('evidence')\n .description('Manage case evidence')\n .addCommand(\n new Command('add')\n .description('Add evidence to a case from an MCP query result')\n .argument('<case-id>', 'Case ID to add evidence to')\n .option('--source <tool>', 'MCP tool name that produced this evidence', 'manual')\n .option('--content <text>', 'Evidence content (MCP response or notes)', '')\n .option('--query-params <params>', 'Query parameters used (e.g. address=0x1234)', '')\n .action(async (caseSelector: string, opts: { source: string; content: string; queryParams: string }) => {\n try {\n const { EvidenceStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const result = await EvidenceStore.append(caseId, {\n source: opts.source,\n content: opts.content,\n queryParams: opts.queryParams,\n })\n console.log(`Evidence saved: ${result.filename}`)\n console.log(`SHA-256: ${result.sha256}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('verify')\n .description('Verify evidence manifest integrity for a case')\n .argument('<case-id>', 'Case ID to verify')\n .action(async (caseSelector: string) => {\n try {\n const { EvidenceStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const result = await EvidenceStore.verifyManifest(caseId)\n if (result.ok) {\n console.log(`Manifest OK — ${result.count} evidence file(s) verified`)\n } else {\n console.error(`Manifest FAILED — tampered files: ${(result.tampered ?? []).join(', ')}`)\n process.exit(1)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n )\n .addCommand(\n new Command('dossier')\n .description('Manage entity dossiers for a case')\n .addCommand(\n new Command('update')\n .description('Append a finding to an entity dossier')\n .argument('<case-id>', 'Case ID')\n .argument('<address>', 'Entity address or identifier')\n .option('--finding <text>', 'Finding to append to the dossier', '')\n .option('--type <type>', 'Entity type (eoa|contract|exchange|mixer|unknown)', 'unknown')\n .action(async (caseSelector: string, address: string, opts: { finding: string; type: string }) => {\n try {\n const { DossierStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const validTypes = ['eoa', 'contract', 'exchange', 'mixer', 'unknown'] as const\n const entityType = validTypes.includes(opts.type as typeof validTypes[number])\n ? (opts.type as typeof validTypes[number])\n : 'unknown'\n await DossierStore.appendFinding(caseId, address, opts.finding, entityType)\n console.log(`Dossier updated for ${address}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n )\n .addCommand(\n new Command('session')\n .description('Manage investigation sessions')\n .addCommand(\n new Command('start')\n .description('Start a new investigation session for a case')\n .argument('<case-id>', 'Case ID')\n .argument('[title...]', 'Optional session title')\n .action(async (caseSelector: string, titleParts: string[]) => {\n try {\n const { SessionStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const title = titleParts.join(' ').trim()\n const s = await SessionStore.start(caseId, title ? { title } : {})\n console.log(`Session started: ${s.sessionId}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('end')\n .description('End the current session with findings and next steps')\n .argument('<case-id>', 'Case ID')\n .option('--findings <text>', 'Key findings from this session', '')\n .option('--next-steps <text>', 'Next steps for the investigation', '')\n .action(async (caseSelector: string, opts: { findings: string; nextSteps: string }) => {\n try {\n const { SessionStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n await SessionStore.end(caseId, { findings: opts.findings, nextSteps: opts.nextSteps })\n await SessionStore.archiveOldSessions(caseId)\n console.log(`Session ended for case ${caseId}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n )\n .addCommand(\n new Command('show')\n .description('Show saved case context')\n .argument('<case-id>', 'Case ID or case list number to show')\n .action(async (caseSelector: string) => {\n try {\n await showCaseContext(caseSelector)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram.addCommand(caseCommand)\n\nprogram\n .command('playbook')\n .description('Run and manage investigation playbooks')\n .addCommand(\n new Command('run')\n .description('Execute a playbook by name')\n .argument('<name>', 'Playbook name (e.g. trace-funds, risk-check, entity-profile)')\n .option('--case <id>', 'Case ID to attach evidence to (auto-created if omitted)')\n .option('--from <n>', 'Resume from step N (1-based)', '1')\n .option('--dry-run', 'Show steps without executing')\n .option('-p, --param <kv...>', 'Parameters as key=value pairs (repeatable, e.g. -p address=0x1 -p hops=3)')\n .action(async (name: string, opts: { case?: string; from: string; dryRun?: boolean; param?: string[] }) => {\n try {\n // 1. Parse --param key=value pairs into Record<string,string> — split on first '=' only (T-05-06)\n const resolvedParams: Record<string, string> = {}\n for (const kv of (opts.param ?? [])) {\n const eq = kv.indexOf('=')\n if (eq === -1) {\n console.error(`Invalid param format: \"${kv}\". Use key=value`)\n process.exit(1)\n }\n const key = kv.slice(0, eq)\n if (!key) {\n console.error(`Invalid param format: \"${kv}\". Key must be non-empty`)\n process.exit(1)\n }\n resolvedParams[key] = kv.slice(eq + 1)\n }\n // 2. Resolve playbook content (user-dir first, built-in fallback)\n const { resolvePlaybookContent } = await import('./playbooks/resolver.js')\n const markdown = await resolvePlaybookContent(name)\n // 3. Parse markdown → PlaybookDefinition\n const { PlaybookParser } = await import('./playbooks/parser.js')\n const definition = PlaybookParser.parse(markdown, resolvedParams)\n // 4. Validate required params are provided\n for (const spec of definition.params) {\n if (spec.required && !resolvedParams[spec.name] && !spec.default) {\n console.error(`Missing required param: ${spec.name}. Pass with: -p ${spec.name}=<value>`)\n process.exit(1)\n }\n }\n // 5. Validate --from value\n const fromN = parseInt(opts.from, 10)\n if (isNaN(fromN) || fromN < 1) {\n console.error(`Invalid --from value: \"${opts.from}\". Must be a positive integer.`)\n process.exit(1)\n }\n // 6. Run\n const { PlaybookRunner } = await import('./playbooks/runner.js')\n await PlaybookRunner.run(definition, {\n caseId: opts.case,\n from: fromN,\n dryRun: opts.dryRun,\n params: resolvedParams,\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('list')\n .description('List available playbooks (built-in and user-defined)')\n .action(async () => {\n try {\n const { listPlaybooks } = await import('./playbooks/resolver.js')\n const playbooks = await listPlaybooks()\n if (playbooks.length === 0) { console.log('No playbooks found.'); return }\n for (const p of playbooks) {\n console.log(` ${p.name.padEnd(20)} [${p.source}]`)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('show')\n .description('Show steps for a playbook without executing')\n .argument('<name>', 'Playbook name')\n .action(async (name: string) => {\n try {\n const { resolvePlaybookContent } = await import('./playbooks/resolver.js')\n const { PlaybookParser } = await import('./playbooks/parser.js')\n const markdown = await resolvePlaybookContent(name)\n const definition = PlaybookParser.parse(markdown, {})\n console.log(`Playbook: ${definition.name} v${definition.version}`)\n console.log(`${definition.description}\\n`)\n console.log(`Parameters:`)\n for (const p of definition.params) {\n const req = p.required ? '(required)' : `(optional, default: ${p.default ?? 'none'})`\n console.log(` ${p.name}: ${p.type} ${req}`)\n }\n console.log(`\\nSteps:`)\n for (const step of definition.steps) {\n console.log(` ${step.index}. ${step.label} → tool: ${step.tool}`)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('viz')\n .description('Generate money flow visualization')\n .argument('[case-id]', 'Case ID to visualize')\n .option('--data <file>', 'Raw transaction JSON file for ad-hoc visualization')\n .option('-p, --port <number>', 'Server port', '4321')\n .action(async (caseId: string | undefined, opts: { data?: string; port: string }) => {\n try {\n if (!caseId && !opts.data) {\n console.error('Provide either a case ID or --data <file.json>')\n process.exit(1)\n }\n const { generateVisualization } = await import('./viz/index.js')\n const result = await generateVisualization({ caseId, dataFile: opts.data })\n const { startServer } = await import('./server/index.js')\n const port = parseInt(opts.port, 10)\n startServer(port)\n const url = `http://127.0.0.1:${port}/viz/${result.vizId}`\n console.log(`Visualization: ${url}`)\n const open = (await import('open')).default\n await open(url)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram.parse(process.argv)\n"],"mappings":";;;;;;AAOA,MAAM,YAAY,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;AAC7D,MAAM,gBAAgB,KAAK,QAAQ,WAAW,MAAM,OAAO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AAK,OAAO,OAAO;EACnD,QAAQ,IAAI,kBAAkB,KAAK;EACnC,MAAM,QAAQ,MAAM,OAAO,SAAS;EACpC,MAAM,KAAK,GAAG;CAChB,SAAS,KAAK;EACZ,QAAQ,MAAO,IAAc,OAAO;EACpC,QAAQ,KAAK,CAAC;CAChB;AACF,CAAC;AAEH,QAAQ,MAAM,QAAQ,IAAI"}
1
+ {"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli.ts"],"sourcesContent":["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'\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\nprogram\n .name('chain-insights')\n .description('AML investigation toolkit for blockchain analysis')\n .version(PACKAGE_INFO.version)\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('--hermes', 'Install Hermes skills globally to ~/.hermes/skills/chain-insights/ and register MCP')\n\n// Handle installer flags when invoked with no subcommand (bare `chain-insights --claude`)\nconst rawArgs = process.argv.slice(2)\nconst installerFlags = rawArgs.filter(a => a === '--claude' || a === '--codex' || a === '--hermes')\nif (installerFlags.length > 0 && !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\nif (rawArgs[0] === 'mcp' && rawArgs[1] === 'trace-funds') {\n console.error(\"error: unknown command 'trace-funds'\")\n process.exit(1)\n}\n\nasync function resolveCaseSelector(input: string): Promise<string> {\n const { resolveCaseSelector } = await import('./cases/selector.js')\n return resolveCaseSelector(input)\n}\n\nasync function scopeCasesToInvocationDir(): Promise<void> {\n if (process.env['CHAIN_INSIGHTS_CASES_ROOT']?.trim()) return\n const { activeCasesRoot } = await import('./workspace/active.js')\n process.env['CHAIN_INSIGHTS_CASES_ROOT'] = activeCasesRoot()\n}\n\nasync function showCaseContext(caseSelector: string): Promise<void> {\n const { CaseStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const ctx = await CaseStore.loadContext(caseId)\n console.log(`\\n=== Case: ${ctx.case.id} ===`)\n console.log(`Name: ${ctx.case.name}`)\n console.log(`Status: ${ctx.case.status}`)\n console.log(`Tags: ${ctx.case.tags.join(', ') || 'none'}`)\n console.log(`Evidence files: ${ctx.evidenceCount}`)\n console.log(`Dossiers: ${ctx.dossierSummaries.length}`)\n if (ctx.lastSession) {\n console.log(`\\n--- Last Session (${ctx.lastSession.sessionId}) ---`)\n console.log(ctx.lastSession.body.slice(0, 500))\n } else {\n console.log('\\nNo previous sessions.')\n }\n if (ctx.dossierSummaries.length > 0) {\n console.log('\\n--- Entity Dossiers ---')\n for (const d of ctx.dossierSummaries) {\n console.log(` ${d.address} [${d.type}] tags: ${d.riskTags || 'none'}`)\n }\n }\n}\n\nfunction optionalNumber(value: string | undefined): number | undefined {\n if (value === undefined) return undefined\n const parsed = Number(value)\n if (!Number.isFinite(parsed)) throw new Error(`Invalid number: ${value}`)\n return parsed\n}\n\nfunction optionalNumberArg(value: unknown, name: string): number | undefined {\n if (value === undefined) return undefined\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') return optionalNumber(value)\n throw new Error(`Invalid number for ${name}: ${String(value)}`)\n}\n\ntype ScamTopologyActivityPolicyModeArg = 'node_relative_only' | 'global_incident_only'\n\nfunction optionalScamTopologyActivityPolicy(value: unknown): ScamTopologyActivityPolicyModeArg | undefined {\n if (value === undefined || value === null || value === '') return undefined\n if (value === 'node_relative_only' || value === 'global_incident_only') return value\n throw new Error('activity_policy must be one of: node_relative_only, global_incident_only')\n}\n\nasync function withGraphMcpClient<T>(name: string, fn: (client: import('@modelcontextprotocol/sdk/client/index.js').Client, config: Awaited<ReturnType<typeof import('./config/index.js').loadConfig>>) => Promise<T>): Promise<T> {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n const { createConfiguredGraphMcpFetch, resolveGraphMcpEndpoint } = await import('./mcp/client.js')\n const paymentFetch = await createConfiguredGraphMcpFetch(config)\n const { Client } = await import('@modelcontextprotocol/sdk/client/index.js')\n const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name, version: PACKAGE_VERSION })\n await client.connect(new StreamableHTTPClientTransport(new URL(resolveGraphMcpEndpoint(config)), { fetch: paymentFetch }))\n try {\n return await fn(client, config)\n } finally {\n await client.close()\n }\n}\n\nfunction printMcpTextContent(result: { content?: Array<{ type: string; text?: string }> }): void {\n for (const item of result.content ?? []) {\n if (item.type === 'text') console.log(item.text)\n }\n}\n\nasync function printNetworkCapabilities(opts: { json?: boolean }): Promise<void> {\n const { loadConfig } = await import('./config/index.js')\n const { fetchNetworkCapabilities, formatNetworkCapabilities } = 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\nprogram\n .command('networks')\n .alias('network')\n .description('List supported graph networks, capability layers, retention, and freshness')\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\nprogram\n .command('serve')\n .description('Start local visualization server')\n .option('-p, --port <number>', 'Port to bind (default: 4321)', '4321')\n .action(async (opts: { port: string }) => {\n try {\n const { requireWorkspaceRoot } = await import('./workspace/output-root.js')\n const workspaceRoot = requireWorkspaceRoot()\n const { startServer } = await import('./server/index.js')\n console.log(`Workspace: ${workspaceRoot}`)\n startServer(parseInt(opts.port, 10))\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\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 { findActiveWorkspace, activeDataDir } = await import('./workspace/active.js')\n const config = await loadConfig()\n const workspace = findActiveWorkspace()\n const graphMcpStatus = config.graphMcpMode === 'debug' && config.graphMcpAuthToken?.trim()\n ? 'bearer access mode'\n : `${config.graphMcpMode} mode`\n console.log('Config: ', activeDataDir(config.dataDir))\n if (workspace) console.log('Workspace:', workspace.root)\n console.log('Server: ', `http://127.0.0.1:${config.serverPort}`)\n console.log('Graph MCP:', graphMcpStatus)\n console.log('Graph endpoint:', config.graphMcpEndpoint)\n })\n\nprogram\n .command('debug')\n .description('Configure Graph MCP debug mode')\n .addCommand(\n new Command('on')\n .description('Enable Graph MCP debug mode without x402 payments')\n .requiredOption('--token <token>', 'Debug bearer token')\n .option('--endpoint <url>', 'Graph MCP 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('Graph MCP debug mode enabled')\n if (opts.endpoint) console.log(`Graph endpoint: ${opts.endpoint}`)\n console.log('Payments: disabled for Graph MCP calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('off')\n .description('Disable Graph MCP 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('Graph MCP debug mode disabled')\n console.log('Payments: enabled for Graph MCP calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('status')\n .description('Show Graph MCP payment/debug mode')\n .action(async () => {\n try {\n const { loadConfig } = await import('./config/index.js')\n const config = await loadConfig()\n console.log(`Graph MCP mode: ${config.graphMcpMode}`)\n console.log(`Graph endpoint: ${config.graphMcpEndpoint}`)\n console.log(`Debug token: ${config.graphMcpAuthToken?.trim() ? 'configured' : 'not configured'}`)\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 Graph MCP test access key mode')\n .addCommand(\n new Command('set')\n .description('Use a Graph MCP test access key without x402 payments')\n .argument('<key>', 'Test access key')\n .option('--endpoint <url>', 'Graph MCP 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('Graph MCP 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 new Command('clear')\n .description('Remove the Graph MCP 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('Graph MCP test access key cleared')\n console.log('Payments: enabled for Graph MCP calls')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('status')\n .description('Show Graph MCP 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(`Access key: ${config.graphMcpAuthToken?.trim() ? 'configured' : 'not configured'}`)\n console.log(`Payments: ${config.graphMcpAuthToken?.trim() ? 'disabled when accepted by server' : 'enabled'}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('init')\n .description('Initialize an investigation workspace')\n .argument('[dir]', 'Workspace directory to initialize', '.')\n .option('--force', 'Overwrite existing workspace files')\n .action(async (dir: string, opts: { force?: boolean }) => {\n try {\n const { initWorkspace } = await import('./workspace/init.js')\n const result = await initWorkspace({ targetDir: dir, force: opts.force })\n console.log(`Workspace initialized: ${result.workspaceRoot}`)\n console.log(`Files written: ${result.filesWritten.length}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram\n .command('setup')\n .description('Configure external MCP clients')\n .addCommand(\n new Command('claude-desktop')\n .alias('claude')\n .description('Install or update the Claude Desktop MCP server entry')\n .option('--config <path>', 'Path to claude_desktop_config.json')\n .option('--dry-run', 'Print the intended change without writing files')\n .action(async (opts: { config?: string; dryRun?: boolean }) => {\n try {\n const { setupClaudeDesktop } = await import('./claude-desktop/setup.js')\n const result = await setupClaudeDesktop({\n configPath: opts.config,\n dryRun: opts.dryRun,\n })\n\n console.log(`Claude Desktop config: ${result.configPath}`)\n console.log('MCP server: chain-insights')\n console.log(`Command: ${result.command}`)\n console.log(`Args: ${result.args.join(' ')}`)\n if (result.dryRun) {\n console.log(`Dry run: ${result.changed ? 'would update config' : 'already up to date'}`)\n } else if (result.changed) {\n console.log(`Updated: yes`)\n if (result.backupPath) console.log(`Backup: ${result.backupPath}`)\n } else {\n console.log('Updated: already up to date')\n }\n console.log('Reload required: quit and reopen Claude Desktop; it does not hot-reload MCP config.')\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('config')\n .description('Read or write configuration values')\n .addCommand(\n new Command('get')\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 new Command('set')\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 = 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 new Command('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 new Command('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 new Command('ready')\n .description('Check and prepare the wallet for paid GraphRAG MCP 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(new Option('--approval-usdc <amount>', 'Deprecated alias for --payment-usdc').hideHelp())\n .option('--json', 'Print machine-readable readiness metadata')\n .action(async (opts: { checkOnly?: boolean; approve?: boolean; paymentUsdc?: string; approvalUsdc?: string; json?: boolean }) => {\n try {\n const { formatWalletReadiness, parsePaymentApprovalUnits, prepareWalletForPaidCalls } = await import('./wallet/tools.js')\n const minimumApprovalUnits = parsePaymentApprovalUnits(opts.paymentUsdc ?? opts.approvalUsdc ?? '1')\n const result = await prepareWalletForPaidCalls({\n minimumApprovalUnits,\n approve: opts.checkOnly ? false : opts.approve !== false,\n })\n\n if (opts.json) {\n console.log(JSON.stringify(result, (_key, value) => (\n typeof value === 'bigint' ? value.toString() : value\n ), 2))\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 .addCommand(\n new Command('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('mcp')\n .description('Interact with the Chain Insights MCP endpoint')\n .allowExcessArguments(false)\n .addCommand(\n new Command('networks')\n .description('List supported graph networks, capability layers, retention, and freshness')\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 new Command('tools')\n .description('List available MCP tools (cached 24h)')\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 } = 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 } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js')\n const client = new Client({ name: 'chain-insights-cli', version: PACKAGE_VERSION })\n await client.connect(new StreamableHTTPClientTransport(new URL(graphMcpEndpoint), { fetch: paymentFetch }))\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 .addCommand(\n new Command('address-risk')\n .description('Screen an address for risk, exchange behavior, and optional compare_address connection risk')\n .requiredOption('--address <address>', 'Full blockchain address to screen')\n .requiredOption('--network <network>', 'Network to query. Run `cia mcp networks` for supported networks.')\n .option('--compare-address <address>', 'Optional second address for connection-risk compare mode')\n .option('--remote', 'Force remote MCP tool call instead of local Chain Insights recipe')\n .action(async (opts: { address: string; network: string; compareAddress?: string; remote?: boolean }) => {\n try {\n await withGraphMcpClient('chain-insights-cli-address-risk', async (client) => {\n if (opts.remote) {\n const result = await client.callTool({\n name: 'address_risk',\n arguments: {\n address: opts.address,\n network: opts.network,\n ...(opts.compareAddress ? { compare_address: opts.compareAddress } : {}),\n },\n })\n printMcpTextContent(result as { content?: Array<{ type: string; text?: string }> })\n return\n }\n const { addressRisk } = await import('./investigation/public-tools.js')\n const result = await addressRisk(client, {\n address: opts.address,\n network: opts.network,\n compareAddress: opts.compareAddress,\n })\n console.log(result.summaryText)\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('track-funds')\n .description('Trace trusted/victim addresses and optional known untrusted/scammer addresses')\n .requiredOption('--trusted-addresses <addresses>', 'Comma-separated full trusted/victim addresses, max 5')\n .requiredOption('--network <network>', 'Network to query. Run `cia mcp networks` for supported networks.')\n .option('--untrusted-addresses <addresses>', 'Comma-separated full known untrusted/scammer addresses, max 5')\n .option('--case <id>', 'Case ID to attach compact evidence pointers')\n .option('--max-hops <number>', 'Maximum trace hops, 1-5')\n .option('--per-address-limit <number>', 'Maximum exchange paths/results per address, 1-10')\n .option('--min-amount-sum <number>', 'Minimum r.amount_sum for traced edges')\n .option('--remote', 'Force remote MCP tool call instead of local Chain Insights recipe')\n .action(async (opts: {\n trustedAddresses: string\n network: string\n untrustedAddresses?: string\n case?: string\n maxHops?: string\n perAddressLimit?: string\n minAmountSum?: string\n remote?: boolean\n }) => {\n try {\n const { requireWorkspaceRoot } = await import('./workspace/output-root.js')\n requireWorkspaceRoot()\n await withGraphMcpClient('chain-insights-cli-track-funds', async (client, config) => {\n if (opts.remote) {\n const result = await client.callTool({\n name: 'track_funds',\n arguments: {\n trusted_addresses: opts.trustedAddresses,\n network: opts.network,\n ...(opts.untrustedAddresses ? { untrusted_addresses: opts.untrustedAddresses } : {}),\n },\n })\n printMcpTextContent(result as { content?: Array<{ type: string; text?: string }> })\n return\n }\n const { trackFunds } = await import('./investigation/public-tools.js')\n const caseId = opts.case ? await resolveCaseSelector(opts.case) : undefined\n const result = await trackFunds(client, config, {\n trustedAddresses: opts.trustedAddresses,\n untrustedAddresses: opts.untrustedAddresses,\n network: opts.network,\n caseId,\n maxHops: optionalNumber(opts.maxHops),\n perAddressLimit: optionalNumber(opts.perAddressLimit),\n minAmountSum: optionalNumber(opts.minAmountSum),\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('scam-topology')\n .description('Build victim-incident scam topology and ML-ready scam labels')\n .requiredOption('--network <network>', 'Network to query. Run `cia mcp networks` for supported networks.')\n .requiredOption('--victim-address <address>', 'Full victim/source address that anchors the incident')\n .requiredOption('--incident-timestamp-ms <milliseconds>', 'Earliest known incident transfer timestamp in milliseconds')\n .option('--max-hops <number>', 'Maximum trace hops, default 16, max 64')\n .option('--activity-policy <mode>', 'Traversal activity policy: node_relative_only or global_incident_only', 'node_relative_only')\n .option('--case <id>', 'Case ID to attach compact evidence pointers')\n .action(async (opts: {\n network: string\n victimAddress: string\n incidentTimestampMs: string\n maxHops?: string\n activityPolicy?: string\n case?: string\n }) => {\n try {\n const { requireWorkspaceRoot } = await import('./workspace/output-root.js')\n requireWorkspaceRoot()\n await withGraphMcpClient('chain-insights-cli-scam-topology', async (client, config) => {\n const { scamTopology } = await import('./investigation/public-tools.js')\n const incidentTimestampMs = optionalNumber(opts.incidentTimestampMs)\n if (incidentTimestampMs === undefined) throw new Error('incident-timestamp-ms is required')\n const caseId = opts.case ? await resolveCaseSelector(opts.case) : undefined\n const result = await scamTopology(client, config, {\n victimAddress: opts.victimAddress,\n network: opts.network,\n maxHops: optionalNumber(opts.maxHops),\n incidentTimestampMs,\n activityPolicyMode: optionalScamTopologyActivityPolicy(opts.activityPolicy),\n caseId,\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('stake-insights')\n .description('Explain Bittensor staking behavior around an address, coldkey, or hotkey')\n .requiredOption('--network <network>', 'Network to query. Run `cia mcp networks` for supported networks.')\n .option('--address <address>', 'Full Bittensor address to inspect as either coldkey or hotkey')\n .option('--coldkey <address>', 'Full Bittensor coldkey address to inspect')\n .option('--hotkey <address>', 'Full Bittensor hotkey address to inspect')\n .option('--netuid <number>', 'Optional subnet netuid filter')\n .option('--start-timestamp-ms <milliseconds>', 'Optional inclusive lower activity timestamp bound')\n .option('--end-timestamp-ms <milliseconds>', 'Optional inclusive upper activity timestamp bound')\n .option('--start-block <number>', 'Optional start block. Current stake graph parity may require timestamp windows instead.')\n .option('--end-block <number>', 'Optional end block. Current stake graph parity may require timestamp windows instead.')\n .option('--depth <number>', 'Optional expansion depth limit, default 1, max 3')\n .action(async (opts: {\n network: string\n address?: string\n coldkey?: string\n hotkey?: string\n netuid?: string\n startTimestampMs?: string\n endTimestampMs?: string\n startBlock?: string\n endBlock?: string\n depth?: string\n }) => {\n try {\n await withGraphMcpClient('chain-insights-cli-stake-insights', async (client) => {\n const { stakeInsights } = await import('./investigation/public-tools.js')\n const result = await stakeInsights(client, {\n network: opts.network,\n address: opts.address,\n coldkey: opts.coldkey,\n hotkey: opts.hotkey,\n netuid: optionalNumber(opts.netuid),\n startTimestampMs: optionalNumber(opts.startTimestampMs),\n endTimestampMs: optionalNumber(opts.endTimestampMs),\n startBlock: optionalNumber(opts.startBlock),\n endBlock: optionalNumber(opts.endBlock),\n depth: optionalNumber(opts.depth),\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('call')\n .description('Call an MCP tool directly (debug)')\n .argument('<tool>', 'Tool name to call')\n .argument('[args...]', 'Key=value arguments (e.g. address=0x1234 chain=ethereum)')\n .action(async (tool: string, rawArgs: string[]) => {\n try {\n const { parseMcpCallArgs } = await import('./mcp/call-args.js')\n const { assertPublicMcpToolName } = await import('./mcp/tool-visibility.js')\n const args = parseMcpCallArgs(rawArgs)\n assertPublicMcpToolName(tool)\n await withGraphMcpClient('chain-insights-cli-call', async (client, config) => {\n if (tool === 'address_risk') {\n const { addressRisk } = await import('./investigation/public-tools.js')\n const result = await addressRisk(client, {\n address: String(args['address'] ?? ''),\n network: String(args['network'] ?? ''),\n compareAddress: args['compare_address'] === undefined ? undefined : String(args['compare_address']),\n })\n console.log(result.summaryText)\n return\n }\n if (tool === 'track_funds') {\n const { trackFunds } = await import('./investigation/public-tools.js')\n const result = await trackFunds(client, config, {\n trustedAddresses: args['trusted_addresses'] as string | string[] | undefined ?? '',\n untrustedAddresses: args['untrusted_addresses'] as string | string[] | undefined,\n network: String(args['network'] ?? ''),\n caseId: args['case_id'] === undefined ? undefined : String(args['case_id']),\n maxHops: typeof args['max_hops'] === 'number' ? args['max_hops'] : undefined,\n perAddressLimit: typeof args['per_address_limit'] === 'number' ? args['per_address_limit'] : undefined,\n minAmountSum: typeof args['min_amount_sum'] === 'number' ? args['min_amount_sum'] : undefined,\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n return\n }\n if (tool === 'scam_topology') {\n const { scamTopology } = await import('./investigation/public-tools.js')\n const victimAddress = String(args['victim_address'] ?? '').trim()\n if (!victimAddress) throw new Error('victim_address is required')\n const incidentTimestampMs = optionalNumberArg(args['incident_timestamp_ms'], 'incident_timestamp_ms')\n if (incidentTimestampMs === undefined) throw new Error('incident_timestamp_ms is required')\n const result = await scamTopology(client, config, {\n victimAddress,\n network: String(args['network'] ?? ''),\n caseId: args['case_id'] === undefined ? undefined : String(args['case_id']),\n maxHops: typeof args['max_hops'] === 'number' ? args['max_hops'] : undefined,\n incidentTimestampMs,\n activityPolicyMode: optionalScamTopologyActivityPolicy(args['activity_policy']),\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n return\n }\n if (tool === 'stake_insights') {\n const { stakeInsights } = await import('./investigation/public-tools.js')\n const result = await stakeInsights(client, {\n network: String(args['network'] ?? ''),\n address: args['address'] === undefined ? undefined : String(args['address']),\n coldkey: args['coldkey'] === undefined ? undefined : String(args['coldkey']),\n hotkey: args['hotkey'] === undefined ? undefined : String(args['hotkey']),\n netuid: optionalNumberArg(args['netuid'], 'netuid'),\n startTimestampMs: optionalNumberArg(args['start_timestamp_ms'], 'start_timestamp_ms'),\n endTimestampMs: optionalNumberArg(args['end_timestamp_ms'], 'end_timestamp_ms'),\n startBlock: optionalNumberArg(args['start_block'], 'start_block'),\n endBlock: optionalNumberArg(args['end_block'], 'end_block'),\n depth: optionalNumberArg(args['depth'] ?? args['max_hops'], 'depth'),\n })\n console.log(result.summaryText)\n console.log(JSON.stringify(result.structuredContent, null, 2))\n return\n }\n const result = await client.callTool({ name: tool, arguments: args })\n printMcpTextContent(result as { content?: Array<{ type: string; text?: string }> })\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nconst caseCommand = new Command('case')\n .description('Manage investigation cases')\n .hook('preAction', async () => {\n await scopeCasesToInvocationDir()\n })\n .addCommand(\n new Command('open')\n .description('Open a new investigation case')\n .argument('<name>', 'Case name (e.g. \"Tornado Mixer Investigation\")')\n .option('--tags <tags>', 'Comma-separated tags (e.g. aml,mixer,defi)', '')\n .option('--description <desc>', 'Brief description of the investigation', '')\n .action(async (name: string, opts: { tags: string; description: string }) => {\n try {\n if (/^[1-9]\\d*$/.test(name.trim())) {\n throw new Error('Numeric case names look like list selectors. Use a descriptive case name, e.g. `cia case open \"Tracking stolen funds from <address>\"`.')\n }\n const { CaseStore } = await import('./cases/index.js')\n const tags = opts.tags ? opts.tags.split(',').map(t => t.trim()).filter(Boolean) : []\n const c = await CaseStore.create({ name, tags, description: opts.description })\n const { casesRoot } = await import('./cases/store.js')\n console.log(`Case opened: ${c.id}`)\n console.log(`Directory: ${path.join(casesRoot(), c.id)}/`)\n console.log(`Status: ${c.status}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('activate')\n .description('Activate a case (set status to active)')\n .argument('<case-id>', 'Case ID to activate')\n .action(async (caseSelector: string) => {\n try {\n const { CaseStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const c = await CaseStore.setStatus(caseId, 'active')\n console.log(`Case ${c.id} is now: active`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('suspend')\n .description('Suspend a case (set status to suspended)')\n .argument('<case-id>', 'Case ID to suspend')\n .action(async (caseSelector: string) => {\n try {\n const { CaseStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const c = await CaseStore.setStatus(caseId, 'suspended')\n console.log(`Case ${c.id} is now: suspended`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('close')\n .description('Close a case permanently')\n .argument('<case-id>', 'Case ID to close')\n .action(async (caseSelector: string) => {\n try {\n const { CaseStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const c = await CaseStore.setStatus(caseId, 'closed')\n console.log(`Case ${c.id} is now: closed`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('list')\n .description('List all investigation cases')\n .option('--status <status>', 'Filter by status (open|active|suspended|closed)')\n .action(async (opts: { status?: string }) => {\n try {\n const { CaseStore } = await import('./cases/index.js')\n const cases = await CaseStore.list()\n const filtered = opts.status ? cases.filter(c => c.status === opts.status) : cases\n if (filtered.length === 0) {\n console.log('No cases found.')\n return\n }\n for (const [index, c] of filtered.entries()) {\n console.log(`${index + 1}. ${c.id} [${c.status}] ${c.name}`)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('evidence')\n .description('Manage case evidence')\n .addCommand(\n new Command('add')\n .description('Add evidence to a case from an MCP query result')\n .argument('<case-id>', 'Case ID to add evidence to')\n .option('--source <tool>', 'MCP tool name that produced this evidence', 'manual')\n .option('--content <text>', 'Evidence content (MCP response or notes)', '')\n .option('--query-params <params>', 'Query parameters used (e.g. address=0x1234)', '')\n .action(async (caseSelector: string, opts: { source: string; content: string; queryParams: string }) => {\n try {\n const { EvidenceStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const result = await EvidenceStore.append(caseId, {\n source: opts.source,\n content: opts.content,\n queryParams: opts.queryParams,\n })\n console.log(`Evidence saved: ${result.filename}`)\n console.log(`SHA-256: ${result.sha256}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('verify')\n .description('Verify evidence manifest integrity for a case')\n .argument('<case-id>', 'Case ID to verify')\n .action(async (caseSelector: string) => {\n try {\n const { EvidenceStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const result = await EvidenceStore.verifyManifest(caseId)\n if (result.ok) {\n console.log(`Manifest OK — ${result.count} evidence file(s) verified`)\n } else {\n console.error(`Manifest FAILED — tampered files: ${(result.tampered ?? []).join(', ')}`)\n process.exit(1)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n )\n .addCommand(\n new Command('dossier')\n .description('Manage entity dossiers for a case')\n .addCommand(\n new Command('update')\n .description('Append a finding to an entity dossier')\n .argument('<case-id>', 'Case ID')\n .argument('<address>', 'Entity address or identifier')\n .option('--finding <text>', 'Finding to append to the dossier', '')\n .option('--type <type>', 'Entity type (eoa|contract|exchange|mixer|unknown)', 'unknown')\n .action(async (caseSelector: string, address: string, opts: { finding: string; type: string }) => {\n try {\n const { DossierStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const validTypes = ['eoa', 'contract', 'exchange', 'mixer', 'unknown'] as const\n const entityType = validTypes.includes(opts.type as typeof validTypes[number])\n ? (opts.type as typeof validTypes[number])\n : 'unknown'\n await DossierStore.appendFinding(caseId, address, opts.finding, entityType)\n console.log(`Dossier updated for ${address}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n )\n .addCommand(\n new Command('session')\n .description('Manage investigation sessions')\n .addCommand(\n new Command('start')\n .description('Start a new investigation session for a case')\n .argument('<case-id>', 'Case ID')\n .argument('[title...]', 'Optional session title')\n .action(async (caseSelector: string, titleParts: string[]) => {\n try {\n const { SessionStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n const title = titleParts.join(' ').trim()\n const s = await SessionStore.start(caseId, title ? { title } : {})\n console.log(`Session started: ${s.sessionId}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('end')\n .description('End the current session with findings and next steps')\n .argument('<case-id>', 'Case ID')\n .option('--findings <text>', 'Key findings from this session', '')\n .option('--next-steps <text>', 'Next steps for the investigation', '')\n .action(async (caseSelector: string, opts: { findings: string; nextSteps: string }) => {\n try {\n const { SessionStore } = await import('./cases/index.js')\n const caseId = await resolveCaseSelector(caseSelector)\n await SessionStore.end(caseId, { findings: opts.findings, nextSteps: opts.nextSteps })\n await SessionStore.archiveOldSessions(caseId)\n console.log(`Session ended for case ${caseId}`)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n )\n .addCommand(\n new Command('show')\n .description('Show saved case context')\n .argument('<case-id>', 'Case ID or case list number to show')\n .action(async (caseSelector: string) => {\n try {\n await showCaseContext(caseSelector)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram.addCommand(caseCommand)\n\nprogram\n .command('playbook')\n .description('Run and manage investigation playbooks')\n .addCommand(\n new Command('run')\n .description('Execute a playbook by name')\n .argument('<name>', 'Playbook name (e.g. trace-funds, risk-check, entity-profile)')\n .option('--case <id>', 'Case ID to attach evidence to (auto-created if omitted)')\n .option('--from <n>', 'Resume from step N (1-based)', '1')\n .option('--dry-run', 'Show steps without executing')\n .option('-p, --param <kv...>', 'Parameters as key=value pairs (repeatable, e.g. -p address=0x1 -p hops=3)')\n .action(async (name: string, opts: { case?: string; from: string; dryRun?: boolean; param?: string[] }) => {\n try {\n // 1. Parse --param key=value pairs into Record<string,string> — split on first '=' only (T-05-06)\n const resolvedParams: Record<string, string> = {}\n for (const kv of (opts.param ?? [])) {\n const eq = kv.indexOf('=')\n if (eq === -1) {\n console.error(`Invalid param format: \"${kv}\". Use key=value`)\n process.exit(1)\n }\n const key = kv.slice(0, eq)\n if (!key) {\n console.error(`Invalid param format: \"${kv}\". Key must be non-empty`)\n process.exit(1)\n }\n resolvedParams[key] = kv.slice(eq + 1)\n }\n // 2. Resolve playbook content (user-dir first, built-in fallback)\n const { resolvePlaybookContent } = await import('./playbooks/resolver.js')\n const markdown = await resolvePlaybookContent(name)\n // 3. Parse markdown → PlaybookDefinition\n const { PlaybookParser } = await import('./playbooks/parser.js')\n const definition = PlaybookParser.parse(markdown, resolvedParams)\n // 4. Validate required params are provided\n for (const spec of definition.params) {\n if (spec.required && !resolvedParams[spec.name] && !spec.default) {\n console.error(`Missing required param: ${spec.name}. Pass with: -p ${spec.name}=<value>`)\n process.exit(1)\n }\n }\n // 5. Validate --from value\n const fromN = parseInt(opts.from, 10)\n if (isNaN(fromN) || fromN < 1) {\n console.error(`Invalid --from value: \"${opts.from}\". Must be a positive integer.`)\n process.exit(1)\n }\n // 6. Run\n const { PlaybookRunner } = await import('./playbooks/runner.js')\n await PlaybookRunner.run(definition, {\n caseId: opts.case,\n from: fromN,\n dryRun: opts.dryRun,\n params: resolvedParams,\n })\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('list')\n .description('List available playbooks (built-in and user-defined)')\n .action(async () => {\n try {\n const { listPlaybooks } = await import('./playbooks/resolver.js')\n const playbooks = await listPlaybooks()\n if (playbooks.length === 0) { console.log('No playbooks found.'); return }\n for (const p of playbooks) {\n console.log(` ${p.name.padEnd(20)} [${p.source}]`)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n .addCommand(\n new Command('show')\n .description('Show steps for a playbook without executing')\n .argument('<name>', 'Playbook name')\n .action(async (name: string) => {\n try {\n const { resolvePlaybookContent } = await import('./playbooks/resolver.js')\n const { PlaybookParser } = await import('./playbooks/parser.js')\n const markdown = await resolvePlaybookContent(name)\n const definition = PlaybookParser.parse(markdown, {})\n console.log(`Playbook: ${definition.name} v${definition.version}`)\n console.log(`${definition.description}\\n`)\n console.log(`Parameters:`)\n for (const p of definition.params) {\n const req = p.required ? '(required)' : `(optional, default: ${p.default ?? 'none'})`\n console.log(` ${p.name}: ${p.type} ${req}`)\n }\n console.log(`\\nSteps:`)\n for (const step of definition.steps) {\n console.log(` ${step.index}. ${step.label} → tool: ${step.tool}`)\n }\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n )\n\nprogram\n .command('viz')\n .description('Generate money flow visualization')\n .argument('[case-id]', 'Case ID to visualize')\n .option('--data <file>', 'Raw transaction JSON file for ad-hoc visualization')\n .option('-p, --port <number>', 'Server port', '4321')\n .action(async (caseId: string | undefined, opts: { data?: string; port: string }) => {\n try {\n if (!caseId && !opts.data) {\n console.error('Provide either a case ID or --data <file.json>')\n process.exit(1)\n }\n const { generateVisualization } = await import('./viz/index.js')\n const result = await generateVisualization({ caseId, dataFile: opts.data })\n const { startServer } = await import('./server/index.js')\n const port = parseInt(opts.port, 10)\n startServer(port)\n const url = `http://127.0.0.1:${port}/viz/${result.vizId}`\n console.log(`Visualization: ${url}`)\n const open = (await import('open')).default\n await open(url)\n } catch (err) {\n console.error((err as Error).message)\n process.exit(1)\n }\n })\n\nprogram.parse(process.argv)\n"],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,MAAM,OAAO,sBAAA,MAAA,MAAA,EAAA,CAAA;EAC/C,MAAM,SAAS,MAAM,sBAAsB;GAAE;GAAQ,UAAU,KAAK;EAAK,CAAC;EAC1E,MAAM,EAAE,gBAAgB,MAAM,OAAO,yBAAA,MAAA,MAAA,EAAA,CAAA;EACrC,MAAM,OAAO,SAAS,KAAK,MAAM,EAAE;EACnC,YAAY,IAAI;EAChB,MAAM,MAAM,oBAAoB,KAAK,OAAO,OAAO;EACnD,QAAQ,IAAI,kBAAkB,KAAK;EACnC,MAAM,QAAQ,MAAM,OAAO,SAAS;EACpC,MAAM,KAAK,GAAG;CAChB,SAAS,KAAK;EACZ,QAAQ,MAAO,IAAc,OAAO;EACpC,QAAQ,KAAK,CAAC;CAChB;AACF,CAAC;AAEH,QAAQ,MAAM,QAAQ,IAAI"}
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { s as prepareWalletForPaidCalls } from "./tools-D6RBAhSX.mjs";
2
+ import { s as prepareWalletForPaidCalls } from "./tools-6emZlUwg.mjs";
3
3
  import { privateKeyToAccount } from "viem/accounts";
4
4
  import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
5
5
  import { ExactEvmScheme } from "@x402/evm";
@@ -66,7 +66,7 @@ function describePaymentRequiredResponse(response, payerAddress) {
66
66
  requirement.amount ? `amount=${requirement.amount}` : void 0
67
67
  ].filter(Boolean).join(" ");
68
68
  const message = details ? `x402 payment failed: ${reason} (${details})` : `x402 payment failed: ${reason}`;
69
- if (reason.includes("allowance_required")) return `${message}. The payment wallet needs one-time setup before paid MCP calls can settle. Run \`chain-insights wallet ready\`; Base ETH is required for the approval gas.`;
69
+ if (reason.includes("allowance_required")) return `${message}. The payment wallet needs one-time setup before paid MCP calls can settle. Run \`chain-insights wallet ready\`; Base ETH is used for the setup gas.`;
70
70
  if (reason === "payment_required") return `${message}. ${PAYMENT_NEXT_STEPS}`;
71
71
  return `${message}. ${PAYMENT_NEXT_STEPS}`;
72
72
  } catch {
@@ -157,4 +157,4 @@ async function createConfiguredGraphMcpFetch(config) {
157
157
  //#endregion
158
158
  export { resolveGraphMcpEndpoint as a, createMcpFetchClient as i, client_exports as n, createConfiguredMcpFetch as r, PaymentRequiredError as t };
159
159
 
160
- //# sourceMappingURL=client-Dl-uHrh1.mjs.map
160
+ //# sourceMappingURL=client-Bfw9P9uA.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-Bfw9P9uA.mjs","names":[],"sources":["../src/mcp/client.ts"],"sourcesContent":["import { wrapFetchWithPaymentFromConfig } from '@x402/fetch'\nimport { ExactEvmScheme } from '@x402/evm'\nimport { UptoEvmScheme } from '@x402/evm/upto/client'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport type { InvestigatorConfig } from '../config/schema.js'\nimport { prepareWalletForPaidCalls } from '../wallet/tools.js'\n\ntype FetchLike = typeof fetch\ntype FetchInput = Parameters<FetchLike>[0]\ntype FetchInit = Parameters<FetchLike>[1]\n\nexport class PaymentRequiredError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PaymentRequiredError'\n }\n}\n\nfunction createHeaderFetch(authToken: string, baseFetch: FetchLike): FetchLike {\n return (async (input: FetchInput, init?: FetchInit) => {\n const requestHeaders = input instanceof Request ? input.headers : undefined\n const headers = new Headers(init?.headers ?? requestHeaders)\n headers.set('X-MCP-Debug-Token', authToken)\n headers.set('Authorization', `Bearer ${authToken}`)\n\n return baseFetch(input, {\n ...init,\n headers,\n })\n }) as FetchLike\n}\n\nexport const PAYMENT_NEXT_STEPS =\n 'Next steps: run `chain-insights wallet ready` to check funding and finish one-time payment setup, ' +\n 'run `chain-insights wallet topup` if it says the wallet needs USDC, ' +\n 'or `chain-insights access-key set <key>` if you have been given test access.'\n\ninterface PaymentRequirementDetails {\n reason: string\n scheme?: string\n network?: string\n amount?: string\n amountUnits?: bigint\n payTo?: string\n}\n\nfunction paymentRequirementFromResponse(response: Response): PaymentRequirementDetails | null {\n const encoded = response.headers.get('payment-required')\n if (!encoded) return null\n\n try {\n const decoded = Buffer.from(encoded, 'base64').toString('utf8')\n const parsed = JSON.parse(decoded) as {\n error?: unknown\n accepts?: Array<{ scheme?: unknown; network?: unknown; amount?: unknown; payTo?: unknown }>\n }\n const reason = typeof parsed.error === 'string' && parsed.error.trim() ? parsed.error.trim() : 'payment_required'\n const firstRequirement = Array.isArray(parsed.accepts) ? parsed.accepts[0] : undefined\n const amount = typeof firstRequirement?.amount === 'string' ? firstRequirement.amount.trim() : undefined\n return {\n reason,\n scheme: typeof firstRequirement?.scheme === 'string' ? firstRequirement.scheme : undefined,\n network: typeof firstRequirement?.network === 'string' ? firstRequirement.network : undefined,\n amount,\n amountUnits: amount && /^\\d+$/.test(amount) ? BigInt(amount) : undefined,\n payTo: typeof firstRequirement?.payTo === 'string' ? firstRequirement.payTo.trim() : undefined,\n }\n } catch {\n return null\n }\n}\n\nfunction describePaymentRequiredResponse(response: Response, payerAddress?: string): string {\n const requirement = paymentRequirementFromResponse(response)\n if (!requirement) return `Payment required — this tool costs USDC on Base via x402 micropayments. ${PAYMENT_NEXT_STEPS}`\n\n try {\n const { reason, payTo } = requirement\n if (payerAddress && payTo && payerAddress.toLowerCase() === payTo.toLowerCase()) {\n return 'Local payment wallet matches the MCP payTo address. Configure a separate payer wallet with USDC on Base; do not use the service recipient wallet as the client payment wallet.'\n }\n const details = [\n requirement.scheme ? `scheme=${requirement.scheme}` : undefined,\n requirement.network ? `network=${requirement.network}` : undefined,\n requirement.amount ? `amount=${requirement.amount}` : undefined,\n ].filter(Boolean).join(' ')\n const message = details ? `x402 payment failed: ${reason} (${details})` : `x402 payment failed: ${reason}`\n if (reason.includes('allowance_required')) {\n return `${message}. The payment wallet needs one-time setup before paid MCP calls can settle. Run \\`chain-insights wallet ready\\`; Base ETH is used for the setup gas.`\n }\n if (reason === 'payment_required') {\n return `${message}. ${PAYMENT_NEXT_STEPS}`\n }\n return `${message}. ${PAYMENT_NEXT_STEPS}`\n } catch {\n return `Payment required — this tool costs USDC on Base via x402 micropayments. ${PAYMENT_NEXT_STEPS}`\n }\n}\n\nfunction createPaymentFailureReportingFetch(\n baseFetch: FetchLike,\n payerAddress?: string,\n paymentWallet?: { address: `0x${string}`; privateKey: `0x${string}` },\n): FetchLike {\n const reportingFetch = (async (input: FetchInput, init?: FetchInit) => {\n const response = await baseFetch(input, init)\n if (response.status !== 402) return response\n const requirement = paymentRequirementFromResponse(response)\n if (paymentWallet && requirement?.reason.includes('allowance_required')) {\n try {\n await prepareWalletForPaidCalls({\n account: paymentWallet,\n ...(requirement.amountUnits === undefined ? {} : { minimumApprovalUnits: requirement.amountUnits }),\n })\n } catch (err) {\n throw new PaymentRequiredError(\n 'Payment setup is not ready yet. Run `chain-insights wallet ready` and try again. ' +\n `${(err as Error).message}`,\n )\n }\n const retryResponse = await baseFetch(input, init)\n if (retryResponse.status !== 402) return retryResponse\n throw new PaymentRequiredError(describePaymentRequiredResponse(retryResponse, payerAddress))\n }\n throw new PaymentRequiredError(describePaymentRequiredResponse(response, payerAddress))\n }) as FetchLike\n return Object.assign(reportingFetch, baseFetch)\n}\n\n/**\n * Creates an x402-payment-wrapped fetch function for the Chain Insights MCP.\n * Payments are made in USDC on Base Mainnet (eip155:8453).\n *\n * The factory is pure — no side effects, no state, no caching.\n * If called with an invalid private key format, viem throws — the error propagates.\n *\n * @param privateKey - 0x-prefixed EVM private key (decrypted from wallet.json)\n * @returns A fetch-compatible function that auto-handles HTTP 402 payment challenges\n */\nexport function createMcpFetchClient(privateKey: `0x${string}`, authToken?: string) {\n const account = privateKeyToAccount(privateKey)\n const paymentFetch = wrapFetchWithPaymentFromConfig(fetch, {\n schemes: [\n {\n network: 'eip155:8453', // Base Mainnet — dynamic MCP pricing uses the x402 upto scheme\n client: new UptoEvmScheme(account),\n },\n {\n network: 'eip155:8453', // Base Mainnet — only supported chain in v1\n client: new ExactEvmScheme(account),\n },\n ],\n })\n const reportingFetch = createPaymentFailureReportingFetch(\n paymentFetch,\n account.address,\n { address: account.address, privateKey },\n )\n return authToken ? createHeaderFetch(authToken, reportingFetch) : reportingFetch\n}\n\n/**\n * Creates a bearer/debug-token fetch for local Graph MCP testing.\n *\n * The public x402 debug bypass expects X-MCP-Debug-Token.\n * Private endpoints commonly expect Authorization: Bearer <token>.\n * Sending both lets one config value work for public debug and private M2M endpoints.\n *\n * Wraps with 402 interception so that if the server still requires payment\n * (e.g. token not accepted for paid tools), the user sees actionable guidance\n * instead of a generic transport error.\n */\nexport function createMcpAuthFetchClient(authToken: string, baseFetch: FetchLike = fetch): FetchLike {\n const headerFetch = createHeaderFetch(authToken, baseFetch)\n return createPaymentFailureReportingFetch(headerFetch)\n}\n\nexport function resolveGraphMcpEndpoint(config: Pick<InvestigatorConfig, 'graphMcpEndpoint' | 'mcpEndpoint'>): string {\n const graphEndpoint = config.graphMcpEndpoint?.trim()\n return graphEndpoint || config.mcpEndpoint\n}\n\nasync function createConfiguredFetchWithToken(\n authToken: string | undefined,\n missingTokenName: string,\n): Promise<FetchLike> {\n const normalizedAuthToken = authToken?.trim()\n if (normalizedAuthToken) return createMcpAuthFetchClient(normalizedAuthToken)\n\n const { isWalletConfigured, decryptKey } = await import('../wallet/index.js')\n if (!(await isWalletConfigured())) {\n throw new Error(\n `Wallet not configured and ${missingTokenName} is empty. ` +\n `Run \\`chain-insights access-key set <key>\\` for invited test access or \\`chain-insights config set ${missingTokenName} <token>\\` for local MCP debug bypass, ` +\n 'or `chain-insights config set walletPrivateKey <key>` to enable paid x402 MCP calls.',\n )\n }\n\n const privateKey = await decryptKey()\n return createMcpFetchClient(privateKey as `0x${string}`)\n}\n\nexport async function createConfiguredMcpFetch(config: Pick<InvestigatorConfig, 'mcpAuthToken'>): Promise<FetchLike> {\n return createConfiguredFetchWithToken(config.mcpAuthToken, 'mcpAuthToken')\n}\n\nexport async function createConfiguredGraphMcpFetch(\n config: Pick<InvestigatorConfig, 'mcpAuthToken' | 'graphMcpAuthToken' | 'graphMcpMode'>,\n): Promise<FetchLike> {\n if (config.graphMcpMode === 'debug') {\n const authToken = config.graphMcpAuthToken?.trim() || config.mcpAuthToken?.trim()\n if (!authToken) {\n throw new Error('Graph MCP debug mode requires graphMcpAuthToken. Run `cia access-key set <key>` or `cia debug on --token <token>`.')\n }\n return createMcpAuthFetchClient(authToken)\n }\n\n return createConfiguredFetchWithToken(undefined, 'walletPrivateKey')\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAWA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAS,kBAAkB,WAAmB,WAAiC;CAC7E,QAAQ,OAAO,OAAmB,SAAqB;EACrD,MAAM,iBAAiB,iBAAiB,UAAU,MAAM,UAAU,KAAA;EAClE,MAAM,UAAU,IAAI,QAAQ,MAAM,WAAW,cAAc;EAC3D,QAAQ,IAAI,qBAAqB,SAAS;EAC1C,QAAQ,IAAI,iBAAiB,UAAU,WAAW;EAElD,OAAO,UAAU,OAAO;GACtB,GAAG;GACH;EACF,CAAC;CACH;AACF;AAEA,MAAa,qBACX;AAaF,SAAS,+BAA+B,UAAsD;CAC5F,MAAM,UAAU,SAAS,QAAQ,IAAI,kBAAkB;CACvD,IAAI,CAAC,SAAS,OAAO;CAErB,IAAI;EACF,MAAM,UAAU,OAAO,KAAK,SAAS,QAAQ,EAAE,SAAS,MAAM;EAC9D,MAAM,SAAS,KAAK,MAAM,OAAO;EAIjC,MAAM,SAAS,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,KAAK,IAAI,OAAO,MAAM,KAAK,IAAI;EAC/F,MAAM,mBAAmB,MAAM,QAAQ,OAAO,OAAO,IAAI,OAAO,QAAQ,KAAK,KAAA;EAC7E,MAAM,SAAS,OAAO,kBAAkB,WAAW,WAAW,iBAAiB,OAAO,KAAK,IAAI,KAAA;EAC/F,OAAO;GACL;GACA,QAAQ,OAAO,kBAAkB,WAAW,WAAW,iBAA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AAEA,eAAsB,yBAAyB,QAAsE;CACnH,OAAO,+BAA+B,OAAO,cAAc,cAAc;AAC3E;AAEA,eAAsB,8BACpB,QACoB;CACpB,IAAI,OAAO,iBAAiB,SAAS;EACnC,MAAM,YAAY,OAAO,mBAAmB,KAAK,KAAK,OAAO,cAAc,KAAK;EAChF,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,oHAAoH;EAEtI,OAAO,yBAAyB,SAAS;CAC3C;CAEA,OAAO,+BAA+B,KAAA,GAAW,kBAAkB;AACrE"}
@@ -1,5 +1,5 @@
1
1
  const require_chunk = require("./chunk-DakpK96I.cjs");
2
- const require_tools = require("./tools-UH5hRXYG.cjs");
2
+ const require_tools = require("./tools-kqWI7jPU.cjs");
3
3
  let viem_accounts = require("viem/accounts");
4
4
  let _x402_fetch = require("@x402/fetch");
5
5
  let _x402_evm = require("@x402/evm");
@@ -66,7 +66,7 @@ function describePaymentRequiredResponse(response, payerAddress) {
66
66
  requirement.amount ? `amount=${requirement.amount}` : void 0
67
67
  ].filter(Boolean).join(" ");
68
68
  const message = details ? `x402 payment failed: ${reason} (${details})` : `x402 payment failed: ${reason}`;
69
- if (reason.includes("allowance_required")) return `${message}. The payment wallet needs one-time setup before paid MCP calls can settle. Run \`chain-insights wallet ready\`; Base ETH is required for the approval gas.`;
69
+ if (reason.includes("allowance_required")) return `${message}. The payment wallet needs one-time setup before paid MCP calls can settle. Run \`chain-insights wallet ready\`; Base ETH is used for the setup gas.`;
70
70
  if (reason === "payment_required") return `${message}. ${PAYMENT_NEXT_STEPS}`;
71
71
  return `${message}. ${PAYMENT_NEXT_STEPS}`;
72
72
  } catch {
package/dist/index.cjs CHANGED
@@ -3,9 +3,9 @@ const require_config = require("./config-BwVx19Og.cjs");
3
3
  const require_app = require("./app-BxojXjtB.cjs");
4
4
  const require_server = require("./server-BqVdWath.cjs");
5
5
  const require_wallet = require("./wallet-TAlNMvIM.cjs");
6
- const require_tools = require("./tools-UH5hRXYG.cjs");
7
- const require_topup_server = require("./topup-server-yAaXYkJP.cjs");
8
- const require_client = require("./client-BYnFGA0y.cjs");
6
+ const require_tools = require("./tools-kqWI7jPU.cjs");
7
+ const require_topup_server = require("./topup-server-DhYlOOBM.cjs");
8
+ const require_client = require("./client-DRJq31u_.cjs");
9
9
  const require_viz = require("./viz-Da9YWN_I.cjs");
10
10
  exports.buildTopupInfo = require_tools.buildTopupInfo;
11
11
  exports.createApp = require_app.createApp;
package/dist/index.mjs CHANGED
@@ -2,8 +2,8 @@ import { i as saveConfig, n as loadConfig, r as resetConfigCache } from "./confi
2
2
  import { t as createApp } from "./app-CRd39JJ8.mjs";
3
3
  import { n as startServer } from "./server-BXLX2j_A.mjs";
4
4
  import { a as setWalletPrivateKey, i as normalizeWalletPrivateKey, n as encryptKey, o as walletAddressFromPrivateKey, r as isWalletConfigured, t as decryptKey } from "./wallet-D8IqFRKY.mjs";
5
- import { a as getWalletAccount, i as getBalanceUsdc, n as formatWalletBalance, o as getWalletBalanceText, r as getBalanceEth, t as buildTopupInfo } from "./tools-D6RBAhSX.mjs";
6
- import { i as generateArtifactHtml, n as startTopupServer, t as getTopupUrl } from "./topup-server-BJgVw6Jt.mjs";
7
- import { i as createMcpFetchClient } from "./client-Dl-uHrh1.mjs";
5
+ import { a as getWalletAccount, i as getBalanceUsdc, n as formatWalletBalance, o as getWalletBalanceText, r as getBalanceEth, t as buildTopupInfo } from "./tools-6emZlUwg.mjs";
6
+ import { i as generateArtifactHtml, n as startTopupServer, t as getTopupUrl } from "./topup-server-R3dNp-p8.mjs";
7
+ import { i as createMcpFetchClient } from "./client-Bfw9P9uA.mjs";
8
8
  import { t as generateVisualization } from "./viz-DkJyqlUu.mjs";
9
9
  export { buildTopupInfo, createApp, createMcpFetchClient, decryptKey, encryptKey, formatWalletBalance, generateArtifactHtml, generateVisualization, getBalanceEth, getBalanceUsdc, getTopupUrl, getWalletAccount, getWalletBalanceText, isWalletConfigured, loadConfig, normalizeWalletPrivateKey, resetConfigCache, saveConfig, setWalletPrivateKey, startServer, startTopupServer, walletAddressFromPrivateKey };
@@ -42,7 +42,7 @@ This is a workspace for Chain Insights AML investigations.
42
42
 
43
43
  \`\`\`bash
44
44
  chain-insights mcp tools --refresh
45
- chain-insights wallet ready --no-approve
45
+ chain-insights wallet ready --check-only
46
46
  \`\`\`
47
47
 
48
48
  ## Layout
@@ -40,7 +40,7 @@ This is a workspace for Chain Insights AML investigations.
40
40
 
41
41
  \`\`\`bash
42
42
  chain-insights mcp tools --refresh
43
- chain-insights wallet ready --no-approve
43
+ chain-insights wallet ready --check-only
44
44
  \`\`\`
45
45
 
46
46
  ## Layout
@@ -229,4 +229,4 @@ async function initWorkspace(options) {
229
229
  //#endregion
230
230
  export { initWorkspace };
231
231
 
232
- //# sourceMappingURL=init-CB_ga4_8.mjs.map
232
+ //# sourceMappingURL=init-DBC9Ml33.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"init-CB_ga4_8.mjs","names":[],"sources":["../src/workspace/init.ts"],"sourcesContent":["import { access, mkdir, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { LOCAL_GRAPH_MCP_ENDPOINT } from '../config/mcp-endpoint.js'\n\nexport interface InitWorkspaceOptions {\n targetDir: string\n force?: boolean\n}\n\nexport interface InitWorkspaceResult {\n workspaceRoot: string\n filesWritten: string[]\n}\n\nconst WORKSPACE_DIRS = [\n '.chain-insights',\n '.chain-insights/schema',\n '.chain-insights/runtime',\n '.chain-insights/runtime/logs',\n '.chain-insights/runtime-skill',\n 'cases',\n 'imports',\n 'reports',\n 'reports/graphs',\n 'reports/tables',\n 'templates',\n]\n\nfunction todayIso(): string {\n return new Date().toISOString().slice(0, 10)\n}\n\nfunction workspaceJson(workspaceRoot: string): string {\n return JSON.stringify({\n schema: 'chain-insights.workspace.v1',\n name: 'Chain Insights Investigations',\n workspace_root: workspaceRoot,\n default_network: 'bittensor',\n graph_mcp_endpoint: LOCAL_GRAPH_MCP_ENDPOINT,\n cases_dir: 'cases',\n imports_dir: 'imports',\n reports_dir: 'reports',\n templates_dir: 'templates',\n created_at: todayIso(),\n }, null, 2) + '\\n'\n}\n\nconst README = `# Chain Insights Investigations\n\nThis is a workspace for Chain Insights AML investigations.\n\n## Start\n\n\\`\\`\\`bash\nchain-insights mcp tools --refresh\nchain-insights wallet ready --no-approve\n\\`\\`\\`\n\n## Layout\n\n\\`\\`\\`text\n.chain-insights/ Workspace metadata\ncases/ Case exports and notes\nimports/ External reports, CSVs, screenshots, raw notes\nreports/ Final or interim analyst reports\nreports/graphs/ Graph JSON for visualization\nreports/tables/ Compact tabular extracts\ntemplates/ Reusable case/report templates\n.chain-insights/schema/ Runtime graph schema captures\n.chain-insights/runtime/ Workspace-local runtime process state and debug logs\n.chain-insights/runtime-skill/ Workspace-specific agent schema notes\n\\`\\`\\`\n`\n\nconst AGENTS = `# Agent Instructions\n\nYou are operating inside a Chain Insights investigation workspace.\n\n- Read README.md first.\n- If this directory is not initialized, run \\`cia init .\\` before investigation-producing commands.\n- Do not rerun init in an existing workspace unless replacing scaffolding with \\`--force\\`.\n- Read .chain-insights/runtime-skill/SKILL.md before graph queries.\n- Preserve full blockchain addresses exactly.\n- Do not guess the network for graph queries.\n- Capture or refresh graph schema before the first case query.\n- Save compact evidence with original graph field names.\n- Put canonical graph JSON in reports/graphs/ and analyst tables in reports/tables/.\n- Evidence files should summarize and point to graph/table outputs; do not paste large raw JSON blobs into evidence Markdown.\n- Investigation output must stay in this initialized workspace.\n- Never write cases, evidence, reports, graph JSON, HTML, schema captures, or logs to ~/.chain-insights.\n- Keep theories lightweight until evidence supports them.\n`\n\nconst CLAUDE = AGENTS\n\nconst CASE_BRIEF = `# Case Brief\n\n## Summary\n\nStatus:\nNetwork:\nCurrent Assessment:\n\n## Known Addresses\n\n## Claims To Validate\n\n## Evidence\n\n## Next Steps\n`\n\nconst IMPORTS_README = `# External Investigation Inputs\n\nPut user-provided or third-party investigation material here before turning it\ninto case evidence.\n\nExamples:\n\n- Exchange support exports\n- CSV extracts\n- Screenshots\n- Raw notes\n- Partner reports\n\nFiles in this directory are inputs, not verified evidence. When an import\nsupports a claim, summarize it into the case evidence manifest and reference\nthe original file path.\n`\n\nconst TEMPLATES_README = `# Reusable Workspace Templates\n\nStore local report, case, prompt, and evidence templates here.\n\nTemplates are optional workspace helpers. They are not evidence and should not\nbe treated as case state until copied into a case, evidence file, dossier, or\nreport.\n`\n\nconst RUNTIME_SKILL = `---\nname: chain-insights-runtime-schema\ndescription: Workspace-local Chain Insights runtime schema notes. Refresh this after connecting to a graph MCP endpoint.\n---\n\n# Runtime Graph Schema\n\nBefore the first investigation query, capture the live graph schema into:\n\n\\`\\`\\`text\n.chain-insights/schema/<network>.graph-schema.json\n\\`\\`\\`\n\nUse \\`graph_query_batch\\` for schema capture. Prefix current topology reads\nwith \\`USE live_topology\\`, historical topology reads with\n\\`USE archive_topology\\`, and fact reads with \\`USE facts\\`, for example:\n\n\\`\\`\\`bash\ncia mcp call graph_query_batch network=<network> 'queries=[{\"id\":\"node_labels\",\"query\":\"USE live_topology MATCH (n:Address) RETURN \\\"Address\\\" AS node_label, count(n) AS sample_count LIMIT 1\"},{\"id\":\"archive_flow_sample\",\"query\":\"USE archive_topology MATCH (:Address)-[f:FLOWS_TO]->(:Address) RETURN f.period_granularity AS granularity, f.amount_sum AS amount_sum LIMIT 20\"}]'\n\\`\\`\\`\n\nThen update this file with observed labels, relationship types, and allowed\nproperty names for the active network.\n\nRules:\n\n- Prefer \\`graph_query\\` and \\`graph_query_batch\\` for graph-language reads.\n- Use \\`USE live_topology\\` for recent topology, \\`USE archive_topology\\`\n for historical topology, and \\`USE facts\\` for labels, features,\n risk scores, assets, and enrichment. Address facts can be reached through\n relationships such as \\`(:Address)-[:HAS_FEATURE]->(:AddressFeature)\\`.\n Archived money-flow topology is exposed as\n \\`(:Address)-[:FLOWS_TO]->(:Address)\\` with \\`period_granularity\\`,\n \\`period_start_date\\`, and \\`period_end_date\\` on the relationship.\n- Preserve source schema field names in evidence and generated data files.\n- Do not rename, reinterpret, or add unit labels to graph fields unless the\n schema or query result explicitly supports that interpretation.\n- Keep evidence compact: select only the fields needed to support the claim.\n Avoid storing whole node or relationship property blobs in evidence unless\n the purpose of the query is schema discovery or debugging.\n- Keep analysis products separate from evidence: graph JSON belongs under\n \\`reports/graphs/\\`, tabular extracts under \\`reports/tables/\\`, and analyst\n narrative under \\`reports/\\`.\n- Evidence Markdown should be a short provenance record with key facts and\n pointers. Large JSON belongs in \\`reports/tables/\\`, not inline in evidence.\n`\n\nconst SCHEMA_README = `# Runtime Schema Captures\n\nStore graph schema captures here, for example:\n\n\\`\\`\\`text\nbittensor.graph-schema.json\n\\`\\`\\`\n\nSchema captures should be generated before the first case query in a fresh\nworkspace, then referenced by evidence, reports, and runtime skill notes.\n`\n\nfunction workspaceFiles(workspaceRoot: string): Array<[string, string]> {\n return [\n ['.chain-insights/workspace.json', workspaceJson(workspaceRoot)],\n ['README.md', README],\n ['AGENTS.md', AGENTS],\n ['CLAUDE.md', CLAUDE],\n ['imports/README.md', IMPORTS_README],\n ['templates/README.md', TEMPLATES_README],\n ['templates/case-brief.md', CASE_BRIEF],\n ['.chain-insights/runtime-skill/SKILL.md', RUNTIME_SKILL],\n ['.chain-insights/schema/README.md', SCHEMA_README],\n ['.chain-insights/runtime/.keep', ''],\n ['.chain-insights/runtime/logs/.keep', ''],\n ]\n}\n\nasync function assertNoFileCollisions(workspaceRoot: string): Promise<void> {\n for (const [relativePath] of workspaceFiles(workspaceRoot)) {\n const filePath = path.join(workspaceRoot, relativePath)\n try {\n await access(filePath)\n throw new Error(`Refusing to overwrite ${filePath}. Re-run with --force to replace workspace files.`)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n continue\n }\n throw err\n }\n }\n}\n\nexport async function initWorkspace(options: InitWorkspaceOptions): Promise<InitWorkspaceResult> {\n const workspaceRoot = path.resolve(options.targetDir)\n if (!options.force) {\n await assertNoFileCollisions(workspaceRoot)\n }\n\n for (const dir of WORKSPACE_DIRS) {\n await mkdir(path.join(workspaceRoot, dir), { recursive: true })\n }\n\n const filesWritten: string[] = []\n const flag = options.force ? 'w' : 'wx'\n for (const [relativePath, content] of workspaceFiles(workspaceRoot)) {\n const filePath = path.join(workspaceRoot, relativePath)\n try {\n await writeFile(filePath, content, { mode: 0o600, flag })\n filesWritten.push(relativePath)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new Error(`Refusing to overwrite ${filePath}. Re-run with --force to replace workspace files.`)\n }\n throw err\n }\n }\n\n return { workspaceRoot, filesWritten }\n}\n"],"mappings":";;;;AAcA,MAAM,iBAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,WAAmB;CAC1B,wBAAO,IAAI,KAAK,GAAE,YAAY,EAAE,MAAM,GAAG,EAAE;AAC7C;AAEA,SAAS,cAAc,eAA+B;CACpD,OAAO,KAAK,UAAU;EACpB,QAAQ;EACR,MAAM;EACN,gBAAgB;EAChB,iBAAiB;EACjB,oBAAoB;EACpB,WAAW;EACX,aAAa;EACb,aAAa;EACb,eAAe;EACf,YAAY,SAAS;CACvB,GAAG,MAAM,CAAC,IAAI;AAChB;AAEA,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;AA2Bf,MAAM,SAAS;;;;;;;;;;;;;;;;;;AAmBf,MAAM,SAAS;AAEf,MAAM,aAAa;;;;;;;;;;;;;;;;AAiBnB,MAAM,iBAAiB;;;;;;;;;;;;;;;;;AAkBvB,MAAM,mBAAmB;;;;;;;;AASzB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CtB,MAAM,gBAAgB;;;;;;;;;;;AAYtB,SAAS,eAAe,eAAgD;CACtE,OAAO;EACL,CAAC,kCAAkC,cAAc,aAAa,CAAC;EAC/D,CAAC,aAAa,MAAM;EACpB,CAAC,aAAa,MAAM;EACpB,CAAC,aAAa,MAAM;EACpB,CAAC,qBAAqB,cAAc;EACpC,CAAC,uBAAuB,gBAAgB;EACxC,CAAC,2BAA2B,UAAU;EACtC,CAAC,0CAA0C,aAAa;EACxD,CAAC,oCAAoC,aAAa;EAClD,CAAC,iCAAiC,EAAE;EACpC,CAAC,sCAAsC,EAAE;CAC3C;AACF;AAEA,eAAe,uBAAuB,eAAsC;CAC1E,KAAK,MAAM,CAAC,iBAAiB,eAAe,aAAa,GAAG;EAC1D,MAAM,WAAW,KAAK,KAAK,eAAe,YAAY;EACtD,IAAI;GACF,MAAM,OAAO,QAAQ;GACrB,MAAM,IAAI,MAAM,yBAAyB,SAAS,kDAAkD;EACtG,SAAS,KAAK;GACZ,IAAK,IAA8B,SAAS,UAC1C;GAEF,MAAM;EACR;CACF;AACF;AAEA,eAAsB,cAAc,SAA6D;CAC/F,MAAM,gBAAgB,KAAK,QAAQ,QAAQ,SAAS;CACpD,IAAI,CAAC,QAAQ,OACX,MAAM,uBAAuB,aAAa;CAG5C,KAAK,MAAM,OAAO,gBAChB,MAAM,MAAM,KAAK,KAAK,eAAe,GAAG,GAAG,EAAE,WAAW,KAAK,CAAC;CAGhE,MAAM,eAAyB,CAAC;CAChC,MAAM,OAAO,QAAQ,QAAQ,MAAM;CACnC,KAAK,MAAM,CAAC,cAAc,YAAY,eAAe,aAAa,GAAG;EACnE,MAAM,WAAW,KAAK,KAAK,eAAe,YAAY;EACtD,IAAI;GACF,MAAM,UAAU,UAAU,SAAS;IAAE,MAAM;IAAO;GAAK,CAAC;GACxD,aAAa,KAAK,YAAY;EAChC,SAAS,KAAK;GACZ,IAAK,IAA8B,SAAS,UAC1C,MAAM,IAAI,MAAM,yBAAyB,SAAS,kDAAkD;GAEtG,MAAM;EACR;CACF;CAEA,OAAO;EAAE;EAAe;CAAa;AACvC"}
1
+ {"version":3,"file":"init-DBC9Ml33.mjs","names":[],"sources":["../src/workspace/init.ts"],"sourcesContent":["import { access, mkdir, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { LOCAL_GRAPH_MCP_ENDPOINT } from '../config/mcp-endpoint.js'\n\nexport interface InitWorkspaceOptions {\n targetDir: string\n force?: boolean\n}\n\nexport interface InitWorkspaceResult {\n workspaceRoot: string\n filesWritten: string[]\n}\n\nconst WORKSPACE_DIRS = [\n '.chain-insights',\n '.chain-insights/schema',\n '.chain-insights/runtime',\n '.chain-insights/runtime/logs',\n '.chain-insights/runtime-skill',\n 'cases',\n 'imports',\n 'reports',\n 'reports/graphs',\n 'reports/tables',\n 'templates',\n]\n\nfunction todayIso(): string {\n return new Date().toISOString().slice(0, 10)\n}\n\nfunction workspaceJson(workspaceRoot: string): string {\n return JSON.stringify({\n schema: 'chain-insights.workspace.v1',\n name: 'Chain Insights Investigations',\n workspace_root: workspaceRoot,\n default_network: 'bittensor',\n graph_mcp_endpoint: LOCAL_GRAPH_MCP_ENDPOINT,\n cases_dir: 'cases',\n imports_dir: 'imports',\n reports_dir: 'reports',\n templates_dir: 'templates',\n created_at: todayIso(),\n }, null, 2) + '\\n'\n}\n\nconst README = `# Chain Insights Investigations\n\nThis is a workspace for Chain Insights AML investigations.\n\n## Start\n\n\\`\\`\\`bash\nchain-insights mcp tools --refresh\nchain-insights wallet ready --check-only\n\\`\\`\\`\n\n## Layout\n\n\\`\\`\\`text\n.chain-insights/ Workspace metadata\ncases/ Case exports and notes\nimports/ External reports, CSVs, screenshots, raw notes\nreports/ Final or interim analyst reports\nreports/graphs/ Graph JSON for visualization\nreports/tables/ Compact tabular extracts\ntemplates/ Reusable case/report templates\n.chain-insights/schema/ Runtime graph schema captures\n.chain-insights/runtime/ Workspace-local runtime process state and debug logs\n.chain-insights/runtime-skill/ Workspace-specific agent schema notes\n\\`\\`\\`\n`\n\nconst AGENTS = `# Agent Instructions\n\nYou are operating inside a Chain Insights investigation workspace.\n\n- Read README.md first.\n- If this directory is not initialized, run \\`cia init .\\` before investigation-producing commands.\n- Do not rerun init in an existing workspace unless replacing scaffolding with \\`--force\\`.\n- Read .chain-insights/runtime-skill/SKILL.md before graph queries.\n- Preserve full blockchain addresses exactly.\n- Do not guess the network for graph queries.\n- Capture or refresh graph schema before the first case query.\n- Save compact evidence with original graph field names.\n- Put canonical graph JSON in reports/graphs/ and analyst tables in reports/tables/.\n- Evidence files should summarize and point to graph/table outputs; do not paste large raw JSON blobs into evidence Markdown.\n- Investigation output must stay in this initialized workspace.\n- Never write cases, evidence, reports, graph JSON, HTML, schema captures, or logs to ~/.chain-insights.\n- Keep theories lightweight until evidence supports them.\n`\n\nconst CLAUDE = AGENTS\n\nconst CASE_BRIEF = `# Case Brief\n\n## Summary\n\nStatus:\nNetwork:\nCurrent Assessment:\n\n## Known Addresses\n\n## Claims To Validate\n\n## Evidence\n\n## Next Steps\n`\n\nconst IMPORTS_README = `# External Investigation Inputs\n\nPut user-provided or third-party investigation material here before turning it\ninto case evidence.\n\nExamples:\n\n- Exchange support exports\n- CSV extracts\n- Screenshots\n- Raw notes\n- Partner reports\n\nFiles in this directory are inputs, not verified evidence. When an import\nsupports a claim, summarize it into the case evidence manifest and reference\nthe original file path.\n`\n\nconst TEMPLATES_README = `# Reusable Workspace Templates\n\nStore local report, case, prompt, and evidence templates here.\n\nTemplates are optional workspace helpers. They are not evidence and should not\nbe treated as case state until copied into a case, evidence file, dossier, or\nreport.\n`\n\nconst RUNTIME_SKILL = `---\nname: chain-insights-runtime-schema\ndescription: Workspace-local Chain Insights runtime schema notes. Refresh this after connecting to a graph MCP endpoint.\n---\n\n# Runtime Graph Schema\n\nBefore the first investigation query, capture the live graph schema into:\n\n\\`\\`\\`text\n.chain-insights/schema/<network>.graph-schema.json\n\\`\\`\\`\n\nUse \\`graph_query_batch\\` for schema capture. Prefix current topology reads\nwith \\`USE live_topology\\`, historical topology reads with\n\\`USE archive_topology\\`, and fact reads with \\`USE facts\\`, for example:\n\n\\`\\`\\`bash\ncia mcp call graph_query_batch network=<network> 'queries=[{\"id\":\"node_labels\",\"query\":\"USE live_topology MATCH (n:Address) RETURN \\\"Address\\\" AS node_label, count(n) AS sample_count LIMIT 1\"},{\"id\":\"archive_flow_sample\",\"query\":\"USE archive_topology MATCH (:Address)-[f:FLOWS_TO]->(:Address) RETURN f.period_granularity AS granularity, f.amount_sum AS amount_sum LIMIT 20\"}]'\n\\`\\`\\`\n\nThen update this file with observed labels, relationship types, and allowed\nproperty names for the active network.\n\nRules:\n\n- Prefer \\`graph_query\\` and \\`graph_query_batch\\` for graph-language reads.\n- Use \\`USE live_topology\\` for recent topology, \\`USE archive_topology\\`\n for historical topology, and \\`USE facts\\` for labels, features,\n risk scores, assets, and enrichment. Address facts can be reached through\n relationships such as \\`(:Address)-[:HAS_FEATURE]->(:AddressFeature)\\`.\n Archived money-flow topology is exposed as\n \\`(:Address)-[:FLOWS_TO]->(:Address)\\` with \\`period_granularity\\`,\n \\`period_start_date\\`, and \\`period_end_date\\` on the relationship.\n- Preserve source schema field names in evidence and generated data files.\n- Do not rename, reinterpret, or add unit labels to graph fields unless the\n schema or query result explicitly supports that interpretation.\n- Keep evidence compact: select only the fields needed to support the claim.\n Avoid storing whole node or relationship property blobs in evidence unless\n the purpose of the query is schema discovery or debugging.\n- Keep analysis products separate from evidence: graph JSON belongs under\n \\`reports/graphs/\\`, tabular extracts under \\`reports/tables/\\`, and analyst\n narrative under \\`reports/\\`.\n- Evidence Markdown should be a short provenance record with key facts and\n pointers. Large JSON belongs in \\`reports/tables/\\`, not inline in evidence.\n`\n\nconst SCHEMA_README = `# Runtime Schema Captures\n\nStore graph schema captures here, for example:\n\n\\`\\`\\`text\nbittensor.graph-schema.json\n\\`\\`\\`\n\nSchema captures should be generated before the first case query in a fresh\nworkspace, then referenced by evidence, reports, and runtime skill notes.\n`\n\nfunction workspaceFiles(workspaceRoot: string): Array<[string, string]> {\n return [\n ['.chain-insights/workspace.json', workspaceJson(workspaceRoot)],\n ['README.md', README],\n ['AGENTS.md', AGENTS],\n ['CLAUDE.md', CLAUDE],\n ['imports/README.md', IMPORTS_README],\n ['templates/README.md', TEMPLATES_README],\n ['templates/case-brief.md', CASE_BRIEF],\n ['.chain-insights/runtime-skill/SKILL.md', RUNTIME_SKILL],\n ['.chain-insights/schema/README.md', SCHEMA_README],\n ['.chain-insights/runtime/.keep', ''],\n ['.chain-insights/runtime/logs/.keep', ''],\n ]\n}\n\nasync function assertNoFileCollisions(workspaceRoot: string): Promise<void> {\n for (const [relativePath] of workspaceFiles(workspaceRoot)) {\n const filePath = path.join(workspaceRoot, relativePath)\n try {\n await access(filePath)\n throw new Error(`Refusing to overwrite ${filePath}. Re-run with --force to replace workspace files.`)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n continue\n }\n throw err\n }\n }\n}\n\nexport async function initWorkspace(options: InitWorkspaceOptions): Promise<InitWorkspaceResult> {\n const workspaceRoot = path.resolve(options.targetDir)\n if (!options.force) {\n await assertNoFileCollisions(workspaceRoot)\n }\n\n for (const dir of WORKSPACE_DIRS) {\n await mkdir(path.join(workspaceRoot, dir), { recursive: true })\n }\n\n const filesWritten: string[] = []\n const flag = options.force ? 'w' : 'wx'\n for (const [relativePath, content] of workspaceFiles(workspaceRoot)) {\n const filePath = path.join(workspaceRoot, relativePath)\n try {\n await writeFile(filePath, content, { mode: 0o600, flag })\n filesWritten.push(relativePath)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n throw new Error(`Refusing to overwrite ${filePath}. Re-run with --force to replace workspace files.`)\n }\n throw err\n }\n }\n\n return { workspaceRoot, filesWritten }\n}\n"],"mappings":";;;;AAcA,MAAM,iBAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,WAAmB;CAC1B,wBAAO,IAAI,KAAK,GAAE,YAAY,EAAE,MAAM,GAAG,EAAE;AAC7C;AAEA,SAAS,cAAc,eAA+B;CACpD,OAAO,KAAK,UAAU;EACpB,QAAQ;EACR,MAAM;EACN,gBAAgB;EAChB,iBAAiB;EACjB,oBAAoB;E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