chain-insights 0.75.0 → 0.76.0

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 (135) hide show
  1. package/README.md +1 -0
  2. package/dist/{action-log-D49Par9P.mjs → action-log-Byv9Ln_6.mjs} +4 -10
  3. package/dist/{action-log-D49Par9P.mjs.map → action-log-Byv9Ln_6.mjs.map} +1 -1
  4. package/dist/{action-log-HniMMF7f.cjs → action-log-WMW6xFMx.cjs} +3 -9
  5. package/dist/{active-Dkf8AB1R.mjs → active-D2aabYRF.mjs} +3 -4
  6. package/dist/{active-Dkf8AB1R.mjs.map → active-D2aabYRF.mjs.map} +1 -1
  7. package/dist/{active-Bc13hJIm.cjs → active-q3yViZhc.cjs} +2 -3
  8. package/dist/answer-hint-BlYEBq_Y.cjs +57 -0
  9. package/dist/answer-hint-vOE1O6Lf.mjs +48 -0
  10. package/dist/answer-hint-vOE1O6Lf.mjs.map +1 -0
  11. package/dist/{buy-_mpdRieG.mjs → buy-B2luUbWF.mjs} +5 -6
  12. package/dist/{buy-_mpdRieG.mjs.map → buy-B2luUbWF.mjs.map} +1 -1
  13. package/dist/{buy-97M6dtEu.cjs → buy-DEoGITbT.cjs} +4 -5
  14. package/dist/{cache-location-CBVzUIxq.cjs → cache-location-C09AE55j.cjs} +2 -3
  15. package/dist/{cache-location-BO2XkfgI.mjs → cache-location-DxTTqBwk.mjs} +2 -3
  16. package/dist/{cache-location-BO2XkfgI.mjs.map → cache-location-DxTTqBwk.mjs.map} +1 -1
  17. package/dist/{call-args-B0oMK1-J.mjs → call-args-CBqbYfOE.mjs} +15 -4
  18. package/dist/{call-args-B0oMK1-J.mjs.map → call-args-CBqbYfOE.mjs.map} +1 -1
  19. package/dist/{call-args-C8Gp5gco.cjs → call-args-DXEmPeE-.cjs} +14 -2
  20. package/dist/{capabilities-DxojbX4D.mjs → capabilities-BRNHcabF.mjs} +5 -11
  21. package/dist/{capabilities-DxojbX4D.mjs.map → capabilities-BRNHcabF.mjs.map} +1 -1
  22. package/dist/{capabilities-Ds3320iS.cjs → capabilities-DalimVY2.cjs} +4 -10
  23. package/dist/{claude-desktop-Jmm4PlBZ.cjs → claude-desktop-3OksQZVE.cjs} +2 -3
  24. package/dist/{claude-desktop-6jwX0Lux.mjs → claude-desktop-C1SDYAP2.mjs} +2 -3
  25. package/dist/{claude-desktop-6jwX0Lux.mjs.map → claude-desktop-C1SDYAP2.mjs.map} +1 -1
  26. package/dist/cli.cjs +95 -76
  27. package/dist/cli.mjs +94 -75
  28. package/dist/cli.mjs.map +1 -1
  29. package/dist/{client-7qOfAdpH.mjs → client-BaHAIidE.mjs} +10 -21
  30. package/dist/{client-7qOfAdpH.mjs.map → client-BaHAIidE.mjs.map} +1 -1
  31. package/dist/{client-C9uwHnBS.cjs → client-Ddk4X9Ko.cjs} +9 -20
  32. package/dist/{config-BxtMoo9c.cjs → config-BdE8LcF-.cjs} +3 -5
  33. package/dist/{config-9MabJh5R.mjs → config-BkLIqOYq.mjs} +4 -6
  34. package/dist/{config-9MabJh5R.mjs.map → config-BkLIqOYq.mjs.map} +1 -1
  35. package/dist/{create-CpfZq2fx.mjs → create-CluDZkuF.mjs} +3 -4
  36. package/dist/{create-CpfZq2fx.mjs.map → create-CluDZkuF.mjs.map} +1 -1
  37. package/dist/{create-DdggkF04.cjs → create-DvBumvHn.cjs} +2 -3
  38. package/dist/{dex-registry-Chs79Ukc.cjs → dex-registry-CZQB2YhU.cjs} +4 -26
  39. package/dist/{dex-registry-rziydXYq.mjs → dex-registry-D6Xxi_vr.mjs} +5 -27
  40. package/dist/{dex-registry-rziydXYq.mjs.map → dex-registry-D6Xxi_vr.mjs.map} +1 -1
  41. package/dist/{dex-tool-ib_ICiyV.mjs → dex-tool-BoAYqhZO.mjs} +8 -62
  42. package/dist/dex-tool-BoAYqhZO.mjs.map +1 -0
  43. package/dist/{dex-tool-85_76Q8i.cjs → dex-tool-DsM-pSku.cjs} +12 -72
  44. package/dist/{format-CSesEBvS.mjs → format-CsnW5M4D.mjs} +2 -3
  45. package/dist/{format-CSesEBvS.mjs.map → format-CsnW5M4D.mjs.map} +1 -1
  46. package/dist/{format-DfhRQq4L.cjs → format-DUzmoeaE.cjs} +1 -2
  47. package/dist/{graph-schema-DNJXDaTn.cjs → graph-schema-C8Pi6r7c.cjs} +8 -25
  48. package/dist/{graph-schema-Bxqwukqu.mjs → graph-schema-D4LAefGf.mjs} +9 -26
  49. package/dist/{graph-schema-Bxqwukqu.mjs.map → graph-schema-D4LAefGf.mjs.map} +1 -1
  50. package/dist/index.cjs +7 -7
  51. package/dist/index.d.cts +0 -16
  52. package/dist/index.d.cts.map +1 -1
  53. package/dist/index.d.mts +0 -16
  54. package/dist/index.d.mts.map +1 -1
  55. package/dist/index.mjs +7 -7
  56. package/dist/{known-keys-B87ZqOgE.mjs → known-keys-BbuzCZOW.mjs} +4 -7
  57. package/dist/{known-keys-B87ZqOgE.mjs.map → known-keys-BbuzCZOW.mjs.map} +1 -1
  58. package/dist/{known-keys-PKZF5GYd.cjs → known-keys-Cy8lKDOA.cjs} +3 -6
  59. package/dist/mcp-proxy.cjs +65 -39
  60. package/dist/mcp-proxy.d.cts +2 -2
  61. package/dist/mcp-proxy.d.cts.map +1 -1
  62. package/dist/mcp-proxy.d.mts +2 -2
  63. package/dist/mcp-proxy.d.mts.map +1 -1
  64. package/dist/mcp-proxy.mjs +63 -38
  65. package/dist/mcp-proxy.mjs.map +1 -1
  66. package/dist/{print-result-if-AbNLY.cjs → print-result-BYppJlUi.cjs} +19 -19
  67. package/dist/{print-result-BtEAn2Wl.mjs → print-result-IFARsMnL.mjs} +9 -21
  68. package/dist/print-result-IFARsMnL.mjs.map +1 -0
  69. package/dist/{public-tools-COG3pCpD.cjs → public-tools-Cfc1OPNS.cjs} +8 -13
  70. package/dist/{public-tools-DIJs4SHz.mjs → public-tools-DXlZcanX.mjs} +8 -13
  71. package/dist/{public-tools-DIJs4SHz.mjs.map → public-tools-DXlZcanX.mjs.map} +1 -1
  72. package/dist/{quote-DfTut0cx.mjs → quote-41CbMc37.mjs} +2 -3
  73. package/dist/{quote-DfTut0cx.mjs.map → quote-41CbMc37.mjs.map} +1 -1
  74. package/dist/{quote-B9sYNOiv.cjs → quote-pFKcSvMv.cjs} +1 -2
  75. package/dist/{request-timeout-CYmQF8N7.cjs → request-timeout-DxwNijQD.cjs} +1 -2
  76. package/dist/{request-timeout-lBBe0mGf.mjs → request-timeout-K3ljP0pa.mjs} +2 -3
  77. package/dist/{request-timeout-lBBe0mGf.mjs.map → request-timeout-K3ljP0pa.mjs.map} +1 -1
  78. package/dist/{robinhood-CCTMagwM.mjs → robinhood-0NZsA6ZW.mjs} +2 -3
  79. package/dist/robinhood-0NZsA6ZW.mjs.map +1 -0
  80. package/dist/{robinhood-ChiT69sc.cjs → robinhood-DumTxvlA.cjs} +1 -2
  81. package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
  82. package/dist/{rolldown-runtime-C0BPl7ul.cjs → rolldown-runtime-BW-eSwOZ.cjs} +1 -2
  83. package/dist/{rules-BWdbOtHi.mjs → rules-B3w9pCeQ.mjs} +2 -3
  84. package/dist/{rules-BWdbOtHi.mjs.map → rules-B3w9pCeQ.mjs.map} +1 -1
  85. package/dist/{rules-BD-cNHMX.cjs → rules-BKwfmNsJ.cjs} +1 -2
  86. package/dist/{schema-KjZqCHbu.mjs → schema-CKnQsdw9.mjs} +6 -13
  87. package/dist/{schema-KjZqCHbu.mjs.map → schema-CKnQsdw9.mjs.map} +1 -1
  88. package/dist/{schema-tX0U0-VI.cjs → schema-CSESfCvA.cjs} +5 -12
  89. package/dist/{schema-cache-DRObKUvS.mjs → schema-cache-BfKHodDY.mjs} +3 -4
  90. package/dist/{schema-cache-DRObKUvS.mjs.map → schema-cache-BfKHodDY.mjs.map} +1 -1
  91. package/dist/{schema-cache-C7v9ml6S.cjs → schema-cache-NLgJmh4X.cjs} +3 -4
  92. package/dist/{skill-refresh-xYWZ_hua.mjs → skill-refresh-BchIsODN.mjs} +2 -3
  93. package/dist/{skill-refresh-xYWZ_hua.mjs.map → skill-refresh-BchIsODN.mjs.map} +1 -1
  94. package/dist/{skill-refresh-Be2D5FrX.cjs → skill-refresh-DaCTxhhy.cjs} +2 -3
  95. package/dist/{subscription-status-DIuH84fM.mjs → subscription-status-5WfPhSep.mjs} +3 -4
  96. package/dist/{subscription-status-DIuH84fM.mjs.map → subscription-status-5WfPhSep.mjs.map} +1 -1
  97. package/dist/{subscription-status-9tMfD90J.cjs → subscription-status-w4zI2KCK.cjs} +2 -3
  98. package/dist/token-lookup-BJ00JO9A.cjs +342 -0
  99. package/dist/token-lookup-XnyisLQW.mjs +303 -0
  100. package/dist/token-lookup-XnyisLQW.mjs.map +1 -0
  101. package/dist/{tool-visibility-DTAYvE9E.cjs → tool-visibility-DIpgPULN.cjs} +5 -10
  102. package/dist/{tool-visibility-zcmwMSbn.mjs → tool-visibility-Dy3psowS.mjs} +6 -11
  103. package/dist/tool-visibility-Dy3psowS.mjs.map +1 -0
  104. package/dist/{tools-D9ep9E7Q.mjs → tools-6pZo4h_p.mjs} +6 -21
  105. package/dist/{tools-D9ep9E7Q.mjs.map → tools-6pZo4h_p.mjs.map} +1 -1
  106. package/dist/{tools-Cmnq7yip.cjs → tools-DZLizem9.cjs} +5 -20
  107. package/dist/{topup-B6gZbTmv.mjs → topup--7JTo4UQ.mjs} +6 -7
  108. package/dist/{topup-B6gZbTmv.mjs.map → topup--7JTo4UQ.mjs.map} +1 -1
  109. package/dist/{topup-DVTCU2le.cjs → topup-BgI9OcUd.cjs} +5 -6
  110. package/dist/{topup-server-ShuYSyBY.cjs → topup-server-D9Uk1Th3.cjs} +7 -24
  111. package/dist/{topup-server-KQDviFXG.mjs → topup-server-DR0HaUcR.mjs} +8 -25
  112. package/dist/{topup-server-KQDviFXG.mjs.map → topup-server-DR0HaUcR.mjs.map} +1 -1
  113. package/dist/{topup-server-BcT7DIpd.mjs → topup-server-DlwzFEF1.mjs} +5 -12
  114. package/dist/{topup-server-BcT7DIpd.mjs.map → topup-server-DlwzFEF1.mjs.map} +1 -1
  115. package/dist/{topup-server-f4Gx0vji.cjs → topup-server-H1M_7PJK.cjs} +4 -11
  116. package/dist/{transport-error-C7OQjmC7.mjs → transport-error-68G35VPH.mjs} +3 -4
  117. package/dist/{transport-error-C7OQjmC7.mjs.map → transport-error-68G35VPH.mjs.map} +1 -1
  118. package/dist/{transport-error-qDWQn8hb.cjs → transport-error-DXy1iTpS.cjs} +2 -3
  119. package/dist/{update-DqBhBXFs.mjs → update-BH8F4cQ2.mjs} +3 -4
  120. package/dist/{update-DqBhBXFs.mjs.map → update-BH8F4cQ2.mjs.map} +1 -1
  121. package/dist/{update-NowrCmjR.cjs → update-DUDdQSEU.cjs} +2 -3
  122. package/dist/{usage-status-Frot6fPG.mjs → usage-status-BUZgRl4r.mjs} +3 -5
  123. package/dist/{usage-status-Frot6fPG.mjs.map → usage-status-BUZgRl4r.mjs.map} +1 -1
  124. package/dist/{usage-status-DonwoLR3.cjs → usage-status-DnV3I3gX.cjs} +2 -4
  125. package/dist/{wallet-QTo5YCFR.mjs → wallet-B1M0HdQh.mjs} +4 -8
  126. package/dist/{wallet-QTo5YCFR.mjs.map → wallet-B1M0HdQh.mjs.map} +1 -1
  127. package/dist/{wallet-CgIAfdxL.cjs → wallet-BubGd_sG.cjs} +3 -7
  128. package/docs/mcp-proxy.md +34 -0
  129. package/docs/stability.md +3 -2
  130. package/package.json +1 -1
  131. package/skills/chain-insights-cypher/SKILL.md +3 -0
  132. package/dist/dex-tool-ib_ICiyV.mjs.map +0 -1
  133. package/dist/print-result-BtEAn2Wl.mjs.map +0 -1
  134. package/dist/robinhood-CCTMagwM.mjs.map +0 -1
  135. package/dist/tool-visibility-zcmwMSbn.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"update-DqBhBXFs.mjs","names":[],"sources":["../src/update.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process'\nimport type { Readable, Writable } from 'node:stream'\nimport { createInterface } from 'node:readline/promises'\nimport { stdin, stdout } from 'node:process'\nimport { PACKAGE_INFO, PACKAGE_VERSION } from './version.js'\n\nconst DEFAULT_REGISTRY_URL = 'https://registry.npmjs.org'\nconst DEFAULT_TIMEOUT_MS = 3000\n\nexport interface UpdateCheckOptions {\n packageName?: string\n currentVersion?: string\n registryUrl?: string\n timeoutMs?: number\n fetchImpl?: typeof fetch\n}\n\nexport interface UpdateCheckResult {\n packageName: string\n currentVersion: string\n latestVersion?: string\n updateAvailable: boolean\n updateCommand: string\n error?: string\n}\n\nexport interface NpmInvocation {\n command: string\n args: string[]\n displayCommand: string\n}\n\nexport interface UpdatePromptOptions extends UpdateCheckOptions {\n input?: NodeJS.ReadStream & Readable\n output?: NodeJS.WriteStream & Writable\n env?: NodeJS.ProcessEnv\n}\n\nexport function compareSemverVersions(a: string, b: string): number {\n const left = parseSemverCore(a)\n const right = parseSemverCore(b)\n for (let i = 0; i < 3; i += 1) {\n if (left[i] > right[i]) return 1\n if (left[i] < right[i]) return -1\n }\n return 0\n}\n\nexport function resolveUpdateRegistryUrl(env: NodeJS.ProcessEnv = process.env): string {\n return env['CHAIN_INSIGHTS_NPM_REGISTRY_URL']?.trim() || DEFAULT_REGISTRY_URL\n}\n\nexport function buildPackageLatestUrl(\n packageName: string,\n registryUrl = DEFAULT_REGISTRY_URL\n): string {\n const base = registryUrl.endsWith('/') ? registryUrl.slice(0, -1) : registryUrl\n return `${base}/${encodeURIComponent(packageName)}/latest`\n}\n\nexport function resolveNpmUpdateInvocation(\n packageName = PACKAGE_INFO.name,\n env: NodeJS.ProcessEnv = process.env\n): NpmInvocation {\n const packageSpec = `${packageName}@latest`\n const displayCommand = `npm install -g ${packageSpec}`\n const npmExecPath = env['npm_execpath']?.trim()\n if (npmExecPath) {\n return {\n command: process.execPath,\n args: [npmExecPath, 'install', '-g', packageSpec],\n displayCommand,\n }\n }\n return {\n command: process.platform === 'win32' ? 'npm.cmd' : 'npm',\n args: ['install', '-g', packageSpec],\n displayCommand,\n }\n}\n\nexport async function fetchLatestPackageVersion(options: UpdateCheckOptions = {}): Promise<string> {\n const packageName = options.packageName ?? PACKAGE_INFO.name\n const registryUrl = options.registryUrl ?? resolveUpdateRegistryUrl()\n const fetchImpl = options.fetchImpl ?? fetch\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_TIMEOUT_MS)\n\n try {\n const response = await fetchImpl(buildPackageLatestUrl(packageName, registryUrl), {\n headers: {\n accept: 'application/json',\n 'user-agent': `chain-insights/${PACKAGE_VERSION}`,\n },\n signal: controller.signal,\n })\n if (!response.ok) {\n throw new Error(`npmjs registry returned ${response.status}`)\n }\n const body = (await response.json()) as { version?: unknown }\n if (typeof body.version !== 'string' || !body.version.trim()) {\n throw new Error('npmjs registry response did not include a version')\n }\n return body.version.trim()\n } finally {\n clearTimeout(timeout)\n }\n}\n\nexport async function checkForUpdate(options: UpdateCheckOptions = {}): Promise<UpdateCheckResult> {\n const packageName = options.packageName ?? PACKAGE_INFO.name\n const currentVersion = options.currentVersion ?? PACKAGE_VERSION\n const updateCommand = resolveNpmUpdateInvocation(packageName).displayCommand\n try {\n const latestVersion = await fetchLatestPackageVersion(options)\n return {\n packageName,\n currentVersion,\n latestVersion,\n updateAvailable: compareSemverVersions(latestVersion, currentVersion) > 0,\n updateCommand,\n }\n } catch (err) {\n return {\n packageName,\n currentVersion,\n updateAvailable: false,\n updateCommand,\n error: (err as Error).message,\n }\n }\n}\n\nexport function runPackageUpdate(packageName = PACKAGE_INFO.name): void {\n const invocation = resolveNpmUpdateInvocation(packageName)\n const result = spawnSync(invocation.command, invocation.args, { stdio: 'inherit' })\n if (result.error) {\n throw result.error\n }\n if (result.status !== 0) {\n const detail = result.signal\n ? `signal ${result.signal}`\n : `exit code ${result.status ?? 'unknown'}`\n throw new Error(`Update failed with ${detail}`)\n }\n}\n\nexport function shouldPromptForUpdate(options: UpdatePromptOptions = {}): boolean {\n const env = options.env ?? process.env\n if (env['CHAIN_INSIGHTS_SKIP_UPDATE_CHECK'] === '1') return false\n if (env['CI'] === 'true') return false\n const input = options.input ?? stdin\n const output = options.output ?? stdout\n return input.isTTY === true && output.isTTY === true\n}\n\nexport async function maybePromptForUpdate(options: UpdatePromptOptions = {}): Promise<void> {\n if (!shouldPromptForUpdate(options)) return\n\n const check = await checkForUpdate(options)\n if (check.error || !check.updateAvailable || !check.latestVersion) return\n\n const output = options.output ?? stdout\n output.write(\n `\\nChain Insights ${check.latestVersion} is available (current ${check.currentVersion}).\\n`\n )\n output.write(`Update command: ${check.updateCommand}\\n`)\n\n const rl = createInterface({\n input: options.input ?? stdin,\n output,\n })\n try {\n const answer = await rl.question('Update now? [Y/n] ')\n if (!answer.trim() || answer.trim().toLowerCase().startsWith('y')) {\n try {\n runPackageUpdate(check.packageName)\n } catch (err) {\n output.write(`Update failed: ${(err as Error).message}\\n`)\n output.write('Workspace initialization is complete. Run `cia update` when ready.\\n')\n }\n } else {\n output.write('Skipped update. Run `cia update` when ready.\\n')\n }\n } finally {\n rl.close()\n }\n}\n\nfunction parseSemverCore(version: string): [number, number, number] {\n const match = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:[-+].*)?$/.exec(version)\n if (!match) throw new Error(`Invalid semver version: ${version}`)\n return [Number(match[1]), Number(match[2]), Number(match[3])]\n}\n"],"mappings":";;;AAMA,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AA+B3B,SAAgB,sBAAsB,GAAW,GAAmB;CAClE,MAAM,OAAO,gBAAgB,CAAC;CAC9B,MAAM,QAAQ,gBAAgB,CAAC;CAC/B,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG;EAC7B,IAAI,KAAK,KAAK,MAAM,IAAI,OAAO;EAC/B,IAAI,KAAK,KAAK,MAAM,IAAI,OAAO;CACjC;CACA,OAAO;AACT;AAEA,SAAgB,yBAAyB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ACtB;AACF;AAEA,eAAsB,eAAe,UAA8B,CAAC,GAA+B;CACjG,MAAM,cAAc,QAAQ,eAAe,aAAa;CACxD,MAAM,iBAAiB,QAAQ,kBAAkB;CACjD,MAAM,gBAAgB,2BAA2B,WAAW,CAAC,CAAC;CAC9D,IAAI;EACF,MAAM,gBAAgB,MAAM,0BAA0B,OAAO;EAC7D,OAAO;GACL;GACA;GACA;GACA,iBAAiB,sBAAsB,eAAe,cAAc,IAAI;GACxE;EACF;CACF,SAAS,KAAK;EACZ,OAAO;GACL;GACA;GACA,iBAAiB;GACjB;GACA,OAAQ,IAAc;EACxB;CACF;AACF;AAEA,SAAgB,iBAAiB,cAAc,aAAa,MAAY;CACtE,MAAM,aAAa,2BAA2B,WAAW;CACzD,MAAM,SAAS,UAAU,WAAW,SAAS,WAAW,MAAM,EAAE,OAAO,UAAU,CAAC;CAClF,IAAI,OAAO,OACT,MAAM,OAAO;CAEf,IAAI,OAAO,WAAW,GAAG;EACvB,MAAM,SAAS,OAAO,SAClB,UAAU,OAAO,WACjB,aAAa,OAAO,UAAU;EAClC,MAAM,IAAI,MAAM,sBAAsB,QAAQ;CAChD;AACF;AA4CA,SAAS,gBAAgB,SAA2C;CAClE,MAAM,QAAQ,wDAAwD,KAAK,OAAO;CAClF,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,2BAA2B,SAAS;CAChE,OAAO;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;AAC9D"}
1
+ {"version":3,"file":"update-BH8F4cQ2.mjs","names":[],"sources":["../src/update.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process'\nimport type { Readable, Writable } from 'node:stream'\nimport { createInterface } from 'node:readline/promises'\nimport { stdin, stdout } from 'node:process'\nimport { PACKAGE_INFO, PACKAGE_VERSION } from './version.js'\n\nconst DEFAULT_REGISTRY_URL = 'https://registry.npmjs.org'\nconst DEFAULT_TIMEOUT_MS = 3000\n\nexport interface UpdateCheckOptions {\n packageName?: string\n currentVersion?: string\n registryUrl?: string\n timeoutMs?: number\n fetchImpl?: typeof fetch\n}\n\nexport interface UpdateCheckResult {\n packageName: string\n currentVersion: string\n latestVersion?: string\n updateAvailable: boolean\n updateCommand: string\n error?: string\n}\n\nexport interface NpmInvocation {\n command: string\n args: string[]\n displayCommand: string\n}\n\nexport interface UpdatePromptOptions extends UpdateCheckOptions {\n input?: NodeJS.ReadStream & Readable\n output?: NodeJS.WriteStream & Writable\n env?: NodeJS.ProcessEnv\n}\n\nexport function compareSemverVersions(a: string, b: string): number {\n const left = parseSemverCore(a)\n const right = parseSemverCore(b)\n for (let i = 0; i < 3; i += 1) {\n if (left[i] > right[i]) return 1\n if (left[i] < right[i]) return -1\n }\n return 0\n}\n\nexport function resolveUpdateRegistryUrl(env: NodeJS.ProcessEnv = process.env): string {\n return env['CHAIN_INSIGHTS_NPM_REGISTRY_URL']?.trim() || DEFAULT_REGISTRY_URL\n}\n\nexport function buildPackageLatestUrl(\n packageName: string,\n registryUrl = DEFAULT_REGISTRY_URL\n): string {\n const base = registryUrl.endsWith('/') ? registryUrl.slice(0, -1) : registryUrl\n return `${base}/${encodeURIComponent(packageName)}/latest`\n}\n\nexport function resolveNpmUpdateInvocation(\n packageName = PACKAGE_INFO.name,\n env: NodeJS.ProcessEnv = process.env\n): NpmInvocation {\n const packageSpec = `${packageName}@latest`\n const displayCommand = `npm install -g ${packageSpec}`\n const npmExecPath = env['npm_execpath']?.trim()\n if (npmExecPath) {\n return {\n command: process.execPath,\n args: [npmExecPath, 'install', '-g', packageSpec],\n displayCommand,\n }\n }\n return {\n command: process.platform === 'win32' ? 'npm.cmd' : 'npm',\n args: ['install', '-g', packageSpec],\n displayCommand,\n }\n}\n\nexport async function fetchLatestPackageVersion(options: UpdateCheckOptions = {}): Promise<string> {\n const packageName = options.packageName ?? PACKAGE_INFO.name\n const registryUrl = options.registryUrl ?? resolveUpdateRegistryUrl()\n const fetchImpl = options.fetchImpl ?? fetch\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_TIMEOUT_MS)\n\n try {\n const response = await fetchImpl(buildPackageLatestUrl(packageName, registryUrl), {\n headers: {\n accept: 'application/json',\n 'user-agent': `chain-insights/${PACKAGE_VERSION}`,\n },\n signal: controller.signal,\n })\n if (!response.ok) {\n throw new Error(`npmjs registry returned ${response.status}`)\n }\n const body = (await response.json()) as { version?: unknown }\n if (typeof body.version !== 'string' || !body.version.trim()) {\n throw new Error('npmjs registry response did not include a version')\n }\n return body.version.trim()\n } finally {\n clearTimeout(timeout)\n }\n}\n\nexport async function checkForUpdate(options: UpdateCheckOptions = {}): Promise<UpdateCheckResult> {\n const packageName = options.packageName ?? PACKAGE_INFO.name\n const currentVersion = options.currentVersion ?? PACKAGE_VERSION\n const updateCommand = resolveNpmUpdateInvocation(packageName).displayCommand\n try {\n const latestVersion = await fetchLatestPackageVersion(options)\n return {\n packageName,\n currentVersion,\n latestVersion,\n updateAvailable: compareSemverVersions(latestVersion, currentVersion) > 0,\n updateCommand,\n }\n } catch (err) {\n return {\n packageName,\n currentVersion,\n updateAvailable: false,\n updateCommand,\n error: (err as Error).message,\n }\n }\n}\n\nexport function runPackageUpdate(packageName = PACKAGE_INFO.name): void {\n const invocation = resolveNpmUpdateInvocation(packageName)\n const result = spawnSync(invocation.command, invocation.args, { stdio: 'inherit' })\n if (result.error) {\n throw result.error\n }\n if (result.status !== 0) {\n const detail = result.signal\n ? `signal ${result.signal}`\n : `exit code ${result.status ?? 'unknown'}`\n throw new Error(`Update failed with ${detail}`)\n }\n}\n\nexport function shouldPromptForUpdate(options: UpdatePromptOptions = {}): boolean {\n const env = options.env ?? process.env\n if (env['CHAIN_INSIGHTS_SKIP_UPDATE_CHECK'] === '1') return false\n if (env['CI'] === 'true') return false\n const input = options.input ?? stdin\n const output = options.output ?? stdout\n return input.isTTY === true && output.isTTY === true\n}\n\nexport async function maybePromptForUpdate(options: UpdatePromptOptions = {}): Promise<void> {\n if (!shouldPromptForUpdate(options)) return\n\n const check = await checkForUpdate(options)\n if (check.error || !check.updateAvailable || !check.latestVersion) return\n\n const output = options.output ?? stdout\n output.write(\n `\\nChain Insights ${check.latestVersion} is available (current ${check.currentVersion}).\\n`\n )\n output.write(`Update command: ${check.updateCommand}\\n`)\n\n const rl = createInterface({\n input: options.input ?? stdin,\n output,\n })\n try {\n const answer = await rl.question('Update now? [Y/n] ')\n if (!answer.trim() || answer.trim().toLowerCase().startsWith('y')) {\n try {\n runPackageUpdate(check.packageName)\n } catch (err) {\n output.write(`Update failed: ${(err as Error).message}\\n`)\n output.write('Workspace initialization is complete. Run `cia update` when ready.\\n')\n }\n } else {\n output.write('Skipped update. Run `cia update` when ready.\\n')\n }\n } finally {\n rl.close()\n }\n}\n\nfunction parseSemverCore(version: string): [number, number, number] {\n const match = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:[-+].*)?$/.exec(version)\n if (!match) throw new Error(`Invalid semver version: ${version}`)\n return [Number(match[1]), Number(match[2]), Number(match[3])]\n}\n"],"mappings":";;;AAMA,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AA+B3B,SAAgB,sBAAsB,GAAW,GAAmB;CAClE,MAAM,OAAO,gBAAgB,CAAC;CAC9B,MAAM,QAAQ,gBAAgB,CAAC;CAC/B,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG;EAC7B,IAAI,KAAK,KAAK,MAAM,IAAI,OAAO;EAC/B,IAAI,KAAK,KAAK,MAAM,IAAI,OAAO;CACjC;CACA,OAAO;AACT;AAEA,SAAgB,yBAAyB,MAAyB,QAAQ,KAAa;CACrF,OAAO,IAAI,kCAAkC,EAAE,KAAK,KAAK;AAC3D;AAEA,SAAgB,sBACd,aACA,cAAc,sBACN;CAER,OAAO,GADM,YAAY,SAAS,GAAG,IAAI,YAAY,MAAM,GAAG,EAAE,IAAI,YACrD,GAAG,mBAAmB,WAAW,E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,0BAA0B,OAAO;EAC7D,OAAO;GACL;GACA;GACA;GACA,iBAAiB,sBAAsB,eAAe,cAAc,IAAI;GACxE;EACF;CACF,SAAS,KAAK;EACZ,OAAO;GACL;GACA;GACA,iBAAiB;GACjB;GACA,OAAQ,IAAc;EACxB;CACF;AACF;AAEA,SAAgB,iBAAiB,cAAc,aAAa,MAAY;CACtE,MAAM,aAAa,2BAA2B,WAAW;CACzD,MAAM,SAAS,UAAU,WAAW,SAAS,WAAW,MAAM,EAAE,OAAO,UAAU,CAAC;CAClF,IAAI,OAAO,OACT,MAAM,OAAO;CAEf,IAAI,OAAO,WAAW,GAAG;EACvB,MAAM,SAAS,OAAO,SAClB,UAAU,OAAO,WACjB,aAAa,OAAO,UAAU;EAClC,MAAM,IAAI,MAAM,sBAAsB,QAAQ;CAChD;AACF;AA4CA,SAAS,gBAAgB,SAA2C;CAClE,MAAM,QAAQ,wDAAwD,KAAK,OAAO;CAClF,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,2BAA2B,SAAS;CAChE,OAAO;EAAC,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;EAAG,OAAO,MAAM,EAAE;CAAC;AAC9D"}
@@ -1,6 +1,6 @@
1
- const require_print_result = require("./print-result-if-AbNLY.cjs");
1
+ const require_print_result = require("./print-result-BYppJlUi.cjs");
2
2
  let node_child_process = require("node:child_process");
3
- //#region src/update.ts
3
+ // src/update.ts
4
4
  const DEFAULT_REGISTRY_URL = "https://registry.npmjs.org";
5
5
  const DEFAULT_TIMEOUT_MS = 3e3;
6
6
  function compareSemverVersions(a, b) {
@@ -105,6 +105,5 @@ function parseSemverCore(version) {
105
105
  Number(match[3])
106
106
  ];
107
107
  }
108
- //#endregion
109
108
  exports.checkForUpdate = checkForUpdate;
110
109
  exports.runPackageUpdate = runPackageUpdate;
@@ -1,7 +1,6 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
- //#region src/mcp/usage-status.ts
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
+ // src/mcp/usage-status.ts
3
3
  var usage_status_exports = /* @__PURE__ */ __exportAll({
4
- freeTierSpentText: () => freeTierSpentText,
5
4
  isMissingUsageStatusToolError: () => isMissingUsageStatusToolError,
6
5
  primitiveBackendUsageStatus: () => primitiveBackendUsageStatus,
7
6
  usageStatusText: () => usageStatusText
@@ -59,7 +58,6 @@ function resetAtText(iso) {
59
58
  const pad = (n) => String(n).padStart(2, "0");
60
59
  return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())} UTC`;
61
60
  }
62
- //#endregion
63
61
  export { primitiveBackendUsageStatus as n, usage_status_exports as r, freeTierSpentText as t };
64
62
 
65
- //# sourceMappingURL=usage-status-Frot6fPG.mjs.map
63
+ //# sourceMappingURL=usage-status-BUZgRl4r.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"usage-status-Frot6fPG.mjs","names":[],"sources":["../src/mcp/usage-status.ts"],"sourcesContent":["export type UsageStatusResult = {\n schema: 'chain-insights.result.v1'\n tool: 'meta_usage_status'\n facts: {\n usage: {\n mode: 'primitive_graph_backend'\n quota_enforced: false\n usage_status_tool: 'unavailable'\n }\n backend: {\n endpoint: string\n reason: string\n }\n }\n hint: string\n}\n\nexport function primitiveBackendUsageStatus(endpoint: string): UsageStatusResult {\n return {\n schema: 'chain-insights.result.v1',\n tool: 'meta_usage_status',\n facts: {\n usage: {\n mode: 'primitive_graph_backend',\n quota_enforced: false,\n usage_status_tool: 'unavailable',\n },\n backend: {\n endpoint,\n reason: 'The graph backend exposes primitive graph tools but no usage_status quota tool.',\n },\n },\n hint: 'This backend does not expose Chain Insights quota telemetry; calls against it are treated as unmetered by Chain Insights.',\n }\n}\n\nexport function usageStatusText(result: UsageStatusResult): string {\n return JSON.stringify(result, null, 2)\n}\n\nexport function isMissingUsageStatusToolError(err: unknown): boolean {\n const message = String((err as Error).message ?? err).toLowerCase()\n return (\n message.includes('unknown tool') ||\n message.includes('tool not found') ||\n message.includes('method not found') ||\n message.includes('usage_status')\n )\n}\n\n/**\n * The first sentence of a payment failure when the caller's free tier for the\n * day is spent. The server gives every caller 5,000 free units a day before\n * it answers 402, so a payment failure right after that is a used-up free\n * tier, not a service that must be paid for to try. `usage` is the\n * `facts.usage` object a `usage_status` read answers with. Undefined when the\n * quota is not spent, or the object is not a free-tier quota.\n */\nexport function freeTierSpentText(usage: unknown): string | undefined {\n if (typeof usage !== 'object' || usage === null) return undefined\n const u = usage as Record<string, unknown>\n if (u['access_mode'] !== 'public_free') return undefined\n const remaining = Number(u['remaining_units'])\n if (!Number.isFinite(remaining) || remaining > 0) return undefined\n const used = Number(u['daily_units_used'])\n const limit = Number(u['daily_units_limit'])\n const units =\n Number.isFinite(used) && Number.isFinite(limit)\n ? `${used.toLocaleString('en-US')} of ${limit.toLocaleString('en-US')} free units`\n : 'every free unit'\n const resetAt = typeof u['reset_at'] === 'string' ? u['reset_at'] : undefined\n const reset = resetAt ? resetAtText(resetAt) : 'midnight UTC'\n const who = u['identifier_kind'] === 'ip' ? 'this network address' : 'this caller'\n return (\n `The free tier for today is used up: ${who} spent ${units}, and the quota resets at ${reset}. ` +\n 'Until then every graph call is paid per call.'\n )\n}\n\nfunction resetAtText(iso: string): string {\n const ms = Date.parse(iso)\n if (!Number.isFinite(ms)) return iso\n const d = new Date(ms)\n const pad = (n: number) => String(n).padStart(2, '0')\n return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())} UTC`\n}\n"],"mappings":";;;;;;;;AAiBA,SAAgB,4BAA4B,UAAqC;CAC/E,OAAO;EACL,QAAQ;EACR,MAAM;EACN,OAAO;GACL,OAAO;IACL,MAAM;IACN,gBAAgB;IAChB,mBAAmB;GACrB;GACA,SAAS;IACP;IACA,QAAQ;GACV;EACF;EACA,MAAM;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AY,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,WAAW,CAAC,EAAE,GAAG,IAAI,EAAE,YAAY,CAAC,EAAE,GAAG,IAAI,EAAE,cAAc,CAAC,EAAE;AACpI"}
1
+ {"version":3,"file":"usage-status-BUZgRl4r.mjs","names":[],"sources":["../src/mcp/usage-status.ts"],"sourcesContent":["export type UsageStatusResult = {\n schema: 'chain-insights.result.v1'\n tool: 'meta_usage_status'\n facts: {\n usage: {\n mode: 'primitive_graph_backend'\n quota_enforced: false\n usage_status_tool: 'unavailable'\n }\n backend: {\n endpoint: string\n reason: string\n }\n }\n hint: string\n}\n\nexport function primitiveBackendUsageStatus(endpoint: string): UsageStatusResult {\n return {\n schema: 'chain-insights.result.v1',\n tool: 'meta_usage_status',\n facts: {\n usage: {\n mode: 'primitive_graph_backend',\n quota_enforced: false,\n usage_status_tool: 'unavailable',\n },\n backend: {\n endpoint,\n reason: 'The graph backend exposes primitive graph tools but no usage_status quota tool.',\n },\n },\n hint: 'This backend does not expose Chain Insights quota telemetry; calls against it are treated as unmetered by Chain Insights.',\n }\n}\n\nexport function usageStatusText(result: UsageStatusResult): string {\n return JSON.stringify(result, null, 2)\n}\n\nexport function isMissingUsageStatusToolError(err: unknown): boolean {\n const message = String((err as Error).message ?? err).toLowerCase()\n return (\n message.includes('unknown tool') ||\n message.includes('tool not found') ||\n message.includes('method not found') ||\n message.includes('usage_status')\n )\n}\n\n/**\n * The first sentence of a payment failure when the caller's free tier for the\n * day is spent. The server gives every caller 5,000 free units a day before\n * it answers 402, so a payment failure right after that is a used-up free\n * tier, not a service that must be paid for to try. `usage` is the\n * `facts.usage` object a `usage_status` read answers with. Undefined when the\n * quota is not spent, or the object is not a free-tier quota.\n */\nexport function freeTierSpentText(usage: unknown): string | undefined {\n if (typeof usage !== 'object' || usage === null) return undefined\n const u = usage as Record<string, unknown>\n if (u['access_mode'] !== 'public_free') return undefined\n const remaining = Number(u['remaining_units'])\n if (!Number.isFinite(remaining) || remaining > 0) return undefined\n const used = Number(u['daily_units_used'])\n const limit = Number(u['daily_units_limit'])\n const units =\n Number.isFinite(used) && Number.isFinite(limit)\n ? `${used.toLocaleString('en-US')} of ${limit.toLocaleString('en-US')} free units`\n : 'every free unit'\n const resetAt = typeof u['reset_at'] === 'string' ? u['reset_at'] : undefined\n const reset = resetAt ? resetAtText(resetAt) : 'midnight UTC'\n const who = u['identifier_kind'] === 'ip' ? 'this network address' : 'this caller'\n return (\n `The free tier for today is used up: ${who} spent ${units}, and the quota resets at ${reset}. ` +\n 'Until then every graph call is paid per call.'\n )\n}\n\nfunction resetAtText(iso: string): string {\n const ms = Date.parse(iso)\n if (!Number.isFinite(ms)) return iso\n const d = new Date(ms)\n const pad = (n: number) => String(n).padStart(2, '0')\n return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())} UTC`\n}\n"],"mappings":";;;;;;;AAiBA,SAAgB,4BAA4B,UAAqC;CAC/E,OAAO;EACL,QAAQ;EACR,MAAM;EACN,OAAO;GACL,OAAO;IACL,MAAM;IACN,gBAAgB;IAChB,mBAAmB;GACrB;GACA,SAAS;IACP;IACA,QAAQ;GACV;EACF;EACA,MAAM;CACR;AACF;AAEA,SAAgB,gBAAgB,QAAmC;CACjE,OAAO,KAAK,UAAU,QAAQ,MAAM,CAAC;AACvC;AAEA,SAAgB,8BAA8B,KAAuB;CACnE,MAAM,UAAU,OAAQ,IAAc,WAAW,GAAG,CAAC,CAAC,YAAY;CAClE,OACE,QAAQ,SAAS,cAAc,KAC/B,QAAQ,SAAS,gBAAgB,KACjC,QAAQ,SAAS,kBAAkB,KACnC,QAAQ,SAAS,cAAc;AAEnC;;;;;;;;;AAUA,SAAgB,kBAAkB,OAAoC;CACpE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CACxD,MAAM,IAAI;CACV,IAAI,EAAE,mBAAmB,eAAe,OAAO,KAAA;CAC/C,MAAM,YAAY,OAAO,EAAE,kBAAkB;CAC7C,IAAI,CAAC,OAAO,SAAS,SAAS,KAAK,YAAY,GAAG,OAAO,KAAA;CACzD,MAAM,OAAO,OAAO,EAAE,mBAAmB;CACzC,MAAM,QAAQ,OAAO,EAAE,oBAAoB;CAC3C,MAAM,QACJ,OAAO,SAAS,IAAI,KAAK,OAAO,SAAS,KAAK,IAC1C,GAAG,KAAK,eAAe,OAAO,EAAE,MAAM,MAAM,eAAe,OAAO,EAAE,eACpE;CACN,MAAM,UAAU,OAAO,EAAE,gBAAgB,WAAW,EAAE,cAAc,KAAA;CACpE,MAAM,QAAQ,UAAU,YAAY,OAAO,IAAI;CAE/C,OACE,uCAFU,EAAE,uBAAuB,OAAO,yBAAyB,cAExB,SAAS,MAAM,4BAA4B,MAAM;AAGhG;AAEA,SAAS,YAAY,KAAqB;CACxC,MAAM,KAAK,KAAK,MAAM,GAAG;CACzB,IAAI,CAAC,OAAO,SAAS,EAAE,GAAG,OAAO;CACjC,MAAM,IAAI,IAAI,KAAK,EAAE;CACrB,MAAM,OAAO,MAAc,OAAO,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;CACpD,OAAO,GAAG,EAAE,eAAe,EAAE,GAAG,IAAI,EAAE,YAAY,IAAI,CAAC,EAAE,GAAG,IAAI,EAAE,WAAW,CAAC,EAAE,GAAG,IAAI,EAAE,YAAY,CAAC,EAAE,GAAG,IAAI,EAAE,cAAc,CAAC,EAAE;AACpI"}
@@ -1,6 +1,5 @@
1
- //#region src/mcp/usage-status.ts
2
- var usage_status_exports = /* @__PURE__ */ require("./rolldown-runtime-C0BPl7ul.cjs").__exportAll({
3
- freeTierSpentText: () => freeTierSpentText,
1
+ // src/mcp/usage-status.ts
2
+ var usage_status_exports = /* @__PURE__ */ require("./rolldown-runtime-BW-eSwOZ.cjs").__exportAll({
4
3
  isMissingUsageStatusToolError: () => isMissingUsageStatusToolError,
5
4
  primitiveBackendUsageStatus: () => primitiveBackendUsageStatus,
6
5
  usageStatusText: () => usageStatusText
@@ -58,7 +57,6 @@ function resetAtText(iso) {
58
57
  const pad = (n) => String(n).padStart(2, "0");
59
58
  return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())} UTC`;
60
59
  }
61
- //#endregion
62
60
  Object.defineProperty(exports, "freeTierSpentText", {
63
61
  enumerable: true,
64
62
  get: function() {
@@ -1,21 +1,18 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
- import { n as assertPrivateKeyNotPublic, r as isPrivateKeyPublic } from "./known-keys-B87ZqOgE.mjs";
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
+ import { n as assertPrivateKeyNotPublic, r as isPrivateKeyPublic } from "./known-keys-BbuzCZOW.mjs";
3
3
  import path from "node:path";
4
4
  import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
5
5
  import os from "node:os";
6
6
  import crypto from "node:crypto";
7
7
  import { privateKeyToAccount } from "viem/accounts";
8
- //#region src/wallet/index.ts
8
+ // src/wallet/index.ts
9
9
  var wallet_exports = /* @__PURE__ */ __exportAll({
10
10
  assertStoredWalletReplaceable: () => assertStoredWalletReplaceable,
11
11
  decryptKey: () => decryptKey,
12
- encryptKey: () => encryptKey,
13
12
  isWalletConfigured: () => isWalletConfigured,
14
- normalizeWalletPrivateKey: () => normalizeWalletPrivateKey,
15
13
  replacePublicWallet: () => replacePublicWallet,
16
14
  setWalletPrivateKey: () => setWalletPrivateKey,
17
15
  storedWalletKeyIsPublic: () => storedWalletKeyIsPublic,
18
- walletAddressFromPrivateKey: () => walletAddressFromPrivateKey,
19
16
  walletPath: () => walletPath
20
17
  });
21
18
  function walletPath() {
@@ -174,7 +171,6 @@ async function isWalletConfigured() {
174
171
  throw err;
175
172
  }
176
173
  }
177
- //#endregion
178
174
  export { setWalletPrivateKey as a, normalizeWalletPrivateKey as i, encryptKey as n, walletAddressFromPrivateKey as o, isWalletConfigured as r, wallet_exports as s, decryptKey as t };
179
175
 
180
- //# sourceMappingURL=wallet-QTo5YCFR.mjs.map
176
+ //# sourceMappingURL=wallet-B1M0HdQh.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"wallet-QTo5YCFR.mjs","names":["nodeErr"],"sources":["../src/wallet/index.ts"],"sourcesContent":["import crypto from 'node:crypto'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { readFile, writeFile, mkdir, stat } from 'node:fs/promises'\nimport type { Address, Hex } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { assertPrivateKeyNotPublic, isPrivateKeyPublic } from './known-keys.js'\n\n// Path derived at call time so tests can override HOME.\nexport function walletPath(): string {\n return path.join(os.homedir(), '.chain-insights', 'wallet.json')\n}\n\n// Derive a 32-byte key from the machine identity (hostname + username) and a\n// random per-wallet salt. The salt prevents precomputation attacks across wallets.\nfunction deriveKey(salt: Buffer): Buffer {\n return crypto.scryptSync(`${os.hostname()}:${os.userInfo().username}`, salt, 32)\n}\n\ninterface WalletData {\n salt: string\n iv: string\n tag: string\n data: string\n}\n\nexport function normalizeWalletPrivateKey(value: string): Hex {\n if (!/^0x[0-9a-fA-F]{64}$/.test(value)) {\n throw new Error('Stored wallet private key is not a valid 0x-prefixed EVM private key')\n }\n return value as Hex\n}\n\nexport function walletAddressFromPrivateKey(privateKey: string): Address {\n return privateKeyToAccount(normalizeWalletPrivateKey(privateKey)).address\n}\n\n/**\n * Encrypts a private key and writes it to ~/.chain-insights/wallet.json.\n * Uses AES-256-GCM with a machine-identity-derived key and a random per-wallet salt.\n * File is written with 0o600 permissions (owner read/write only).\n *\n * @param privateKey - The EVM private key to encrypt (0x-prefixed)\n */\nexport async function encryptKey(privateKey: string): Promise<void> {\n const normalizedPrivateKey = normalizeWalletPrivateKey(privateKey)\n const salt = crypto.randomBytes(16)\n const key = deriveKey(salt)\n const iv = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)\n\n const encrypted = Buffer.concat([cipher.update(normalizedPrivateKey, 'utf8'), cipher.final()])\n\n // getAuthTag() MUST be called after final()\n const tag = cipher.getAuthTag()\n\n const walletData: WalletData = {\n salt: salt.toString('hex'),\n iv: iv.toString('hex'),\n tag: tag.toString('hex'),\n data: encrypted.toString('hex'),\n }\n\n const p = walletPath()\n await mkdir(path.dirname(p), { recursive: true })\n await writeFile(p, JSON.stringify(walletData, null, 2) + '\\n', { mode: 0o600 })\n}\n\nexport interface SetWalletPrivateKeyOptions {\n /** Overwrite an existing wallet. The previous ciphertext is backed up first. */\n force?: boolean\n}\n\n/**\n * Best-effort address of the currently stored wallet, for overwrite messaging.\n * Returns null when the wallet can't be decrypted (e.g. hostname/username\n * changed) — the overwrite is still refused, just without naming the address.\n */\nasync function existingWalletAddress(): Promise<Address | null> {\n try {\n return walletAddressFromPrivateKey(await decryptKey())\n } catch {\n return null\n }\n}\n\n/**\n * Copies the existing wallet.json to a timestamped `.bak-*` sibling before it\n * is overwritten, preserving the 0o600 permission. No-op when absent.\n */\nasync function backupExistingWallet(): Promise<void> {\n const p = walletPath()\n let raw: string\n try {\n raw = await readFile(p, 'utf8')\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return\n throw err\n }\n const stamp = new Date().toISOString().replace(/[:.]/g, '-')\n await writeFile(`${p}.bak-${stamp}`, raw, { mode: 0o600 })\n}\n\n/**\n * Encrypts and stores a private key, refusing to overwrite an existing wallet\n * unless `force` is set. Importing a new key over a funded wallet discards the\n * only local copy of the old key, so the overwrite is guarded and the previous\n * ciphertext is backed up.\n */\nexport async function setWalletPrivateKey(\n privateKey: string,\n options: SetWalletPrivateKeyOptions = {}\n): Promise<Address> {\n const normalizedPrivateKey = normalizeWalletPrivateKey(privateKey)\n // import, create and `config set walletPrivateKey` all land here: a public\n // key is never stored.\n assertPrivateKeyNotPublic(normalizedPrivateKey)\n const address = walletAddressFromPrivateKey(normalizedPrivateKey)\n\n if (await isWalletConfigured()) {\n if (!options.force) {\n const existing = await existingWalletAddress()\n const which = existing ? ` (${existing})` : ''\n throw new Error(\n `A payment wallet already exists${which}. Importing a new key overwrites it and permanently ` +\n `discards the old key. Re-run \\`cia wallet import <key> --force\\` to replace it; ` +\n `the previous encrypted key is backed up next to wallet.json first.`\n )\n }\n await backupExistingWallet()\n }\n\n await encryptKey(normalizedPrivateKey)\n return address\n}\n\n/**\n * True when the stored wallet's key is public (src/wallet/known-keys.ts),\n * false when it is not, null when no wallet exists or it cannot be read.\n */\nexport async function storedWalletKeyIsPublic(): Promise<boolean | null> {\n if (!(await isWalletConfigured())) return null\n try {\n return isPrivateKeyPublic(normalizeWalletPrivateKey(await decryptKey()))\n } catch {\n return null\n }\n}\n\n/**\n * Refuses unless a wallet exists and its key is public: `--replace` never\n * replaces a private key.\n */\nexport async function assertStoredWalletReplaceable(): Promise<void> {\n const stored = await storedWalletKeyIsPublic()\n if (stored === true) return\n throw new Error(\n stored === null\n ? '`--replace` replaces a wallet whose key is public, and no readable wallet exists. Run `cia wallet create`.'\n : \"`--replace` works only for a wallet whose key is public. This wallet's key is private; keep it, or use `cia wallet import <key> --force`.\"\n )\n}\n\n/**\n * Replaces a wallet whose key is public with `privateKey`. The old file is\n * backed up next to wallet.json first.\n */\nexport async function replacePublicWallet(privateKey: string): Promise<Address> {\n await assertStoredWalletReplaceable()\n return setWalletPrivateKey(privateKey, { force: true })\n}\n\n/**\n * Reads and decrypts the private key from ~/.chain-insights/wallet.json.\n * Throws a human-readable error if wallet is absent or decryption fails.\n *\n * @returns The decrypted EVM private key string\n */\nexport async function decryptKey(): Promise<string> {\n let raw: string\n try {\n raw = await readFile(walletPath(), 'utf8')\n } catch (err: unknown) {\n const nodeErr = err as NodeJS.ErrnoException\n if (nodeErr.code === 'ENOENT') {\n throw new Error(\n 'Wallet not configured. Run `cia wallet create` to generate one, or `cia wallet import <private-key>` to use an existing key. Then run `cia wallet ready`.'\n )\n }\n throw err\n }\n\n try {\n const stored = JSON.parse(raw) as WalletData\n const salt = Buffer.from(stored.salt, 'hex')\n const key = deriveKey(salt)\n const iv = Buffer.from(stored.iv, 'hex')\n const tag = Buffer.from(stored.tag, 'hex')\n const encrypted = Buffer.from(stored.data, 'hex')\n\n const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv)\n // setAuthTag() MUST be called before update()\n decipher.setAuthTag(tag)\n\n const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])\n\n return decrypted.toString('utf8')\n } catch {\n throw new Error(\n 'Wallet decryption failed. If you changed your hostname or username, re-import it with `cia wallet import <private-key>`.'\n )\n }\n}\n\n/**\n * Returns true if wallet.json exists, false if absent.\n * Does not validate the wallet contents.\n */\nexport async function isWalletConfigured(): Promise<boolean> {\n try {\n await stat(walletPath())\n return true\n } catch (err: unknown) {\n const nodeErr = err as NodeJS.ErrnoException\n if (nodeErr.code === 'ENOENT') return false\n throw err\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AASA,SAAgB,aAAqB;CACnC,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,mBAAmB,aAAa;AACjE;AAIA,SAAS,UAAU,MAAsB;CACvC,OAAO,OAAO,WAAW,GAAG,GAAG,SAAS,EAAE,GAAG,GAAG,SAAS,CAAC,CAAC,YAAY,MAAM,EAAE;AACjF;AASA,SAAgB,0BAA0B,OAAoB;CAC5D,IAAI,CAAC,sBAAsB,KAAK,KAAK,GACnC,MAAM,IAAI,MAAM,sEAAsE;CAExF,OAAO;AACT;AAEA,SAAgB,4BAA4B,YAA6B;CACvE,OAAO,oBAAoB,0BAA0B,UAAU,CAAC,CAAC,CAAC;AACpE;;;;;;;;AASA,eAAsB,WAAW,YAAmC;CAClE,MAAM,uBAAuB,0BAA0B,UAAU;CACjE,MAAM,OAAO,OAAO,YAAY,EAAE;CAClC,MAAM,MAAM,UAAU,IAAI;CAC1B,MAAM,KAAK,OAAO,YAAY,EAAE;CAChC,MAAM,SAAS,OAAO,eAAe,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F,MAAM,KAAK,WAAW,CAAC;EACvB,OAAO;CACT,SAAS,KAAc;EAErB,IAAIA,IAAQ,SAAS,UAAU,OAAO;EACtC,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"wallet-B1M0HdQh.mjs","names":["nodeErr"],"sources":["../src/wallet/index.ts"],"sourcesContent":["import crypto from 'node:crypto'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { readFile, writeFile, mkdir, stat } from 'node:fs/promises'\nimport type { Address, Hex } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { assertPrivateKeyNotPublic, isPrivateKeyPublic } from './known-keys.js'\n\n// Path derived at call time so tests can override HOME.\nexport function walletPath(): string {\n return path.join(os.homedir(), '.chain-insights', 'wallet.json')\n}\n\n// Derive a 32-byte key from the machine identity (hostname + username) and a\n// random per-wallet salt. The salt prevents precomputation attacks across wallets.\nfunction deriveKey(salt: Buffer): Buffer {\n return crypto.scryptSync(`${os.hostname()}:${os.userInfo().username}`, salt, 32)\n}\n\ninterface WalletData {\n salt: string\n iv: string\n tag: string\n data: string\n}\n\nexport function normalizeWalletPrivateKey(value: string): Hex {\n if (!/^0x[0-9a-fA-F]{64}$/.test(value)) {\n throw new Error('Stored wallet private key is not a valid 0x-prefixed EVM private key')\n }\n return value as Hex\n}\n\nexport function walletAddressFromPrivateKey(privateKey: string): Address {\n return privateKeyToAccount(normalizeWalletPrivateKey(privateKey)).address\n}\n\n/**\n * Encrypts a private key and writes it to ~/.chain-insights/wallet.json.\n * Uses AES-256-GCM with a machine-identity-derived key and a random per-wallet salt.\n * File is written with 0o600 permissions (owner read/write only).\n *\n * @param privateKey - The EVM private key to encrypt (0x-prefixed)\n */\nexport async function encryptKey(privateKey: string): Promise<void> {\n const normalizedPrivateKey = normalizeWalletPrivateKey(privateKey)\n const salt = crypto.randomBytes(16)\n const key = deriveKey(salt)\n const iv = crypto.randomBytes(12)\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv)\n\n const encrypted = Buffer.concat([cipher.update(normalizedPrivateKey, 'utf8'), cipher.final()])\n\n // getAuthTag() MUST be called after final()\n const tag = cipher.getAuthTag()\n\n const walletData: WalletData = {\n salt: salt.toString('hex'),\n iv: iv.toString('hex'),\n tag: tag.toString('hex'),\n data: encrypted.toString('hex'),\n }\n\n const p = walletPath()\n await mkdir(path.dirname(p), { recursive: true })\n await writeFile(p, JSON.stringify(walletData, null, 2) + '\\n', { mode: 0o600 })\n}\n\nexport interface SetWalletPrivateKeyOptions {\n /** Overwrite an existing wallet. The previous ciphertext is backed up first. */\n force?: boolean\n}\n\n/**\n * Best-effort address of the currently stored wallet, for overwrite messaging.\n * Returns null when the wallet can't be decrypted (e.g. hostname/username\n * changed) — the overwrite is still refused, just without naming the address.\n */\nasync function existingWalletAddress(): Promise<Address | null> {\n try {\n return walletAddressFromPrivateKey(await decryptKey())\n } catch {\n return null\n }\n}\n\n/**\n * Copies the existing wallet.json to a timestamped `.bak-*` sibling before it\n * is overwritten, preserving the 0o600 permission. No-op when absent.\n */\nasync function backupExistingWallet(): Promise<void> {\n const p = walletPath()\n let raw: string\n try {\n raw = await readFile(p, 'utf8')\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return\n throw err\n }\n const stamp = new Date().toISOString().replace(/[:.]/g, '-')\n await writeFile(`${p}.bak-${stamp}`, raw, { mode: 0o600 })\n}\n\n/**\n * Encrypts and stores a private key, refusing to overwrite an existing wallet\n * unless `force` is set. Importing a new key over a funded wallet discards the\n * only local copy of the old key, so the overwrite is guarded and the previous\n * ciphertext is backed up.\n */\nexport async function setWalletPrivateKey(\n privateKey: string,\n options: SetWalletPrivateKeyOptions = {}\n): Promise<Address> {\n const normalizedPrivateKey = normalizeWalletPrivateKey(privateKey)\n // import, create and `config set walletPrivateKey` all land here: a public\n // key is never stored.\n assertPrivateKeyNotPublic(normalizedPrivateKey)\n const address = walletAddressFromPrivateKey(normalizedPrivateKey)\n\n if (await isWalletConfigured()) {\n if (!options.force) {\n const existing = await existingWalletAddress()\n const which = existing ? ` (${existing})` : ''\n throw new Error(\n `A payment wallet already exists${which}. Importing a new key overwrites it and permanently ` +\n `discards the old key. Re-run \\`cia wallet import <key> --force\\` to replace it; ` +\n `the previous encrypted key is backed up next to wallet.json first.`\n )\n }\n await backupExistingWallet()\n }\n\n await encryptKey(normalizedPrivateKey)\n return address\n}\n\n/**\n * True when the stored wallet's key is public (src/wallet/known-keys.ts),\n * false when it is not, null when no wallet exists or it cannot be read.\n */\nexport async function storedWalletKeyIsPublic(): Promise<boolean | null> {\n if (!(await isWalletConfigured())) return null\n try {\n return isPrivateKeyPublic(normalizeWalletPrivateKey(await decryptKey()))\n } catch {\n return null\n }\n}\n\n/**\n * Refuses unless a wallet exists and its key is public: `--replace` never\n * replaces a private key.\n */\nexport async function assertStoredWalletReplaceable(): Promise<void> {\n const stored = await storedWalletKeyIsPublic()\n if (stored === true) return\n throw new Error(\n stored === null\n ? '`--replace` replaces a wallet whose key is public, and no readable wallet exists. Run `cia wallet create`.'\n : \"`--replace` works only for a wallet whose key is public. This wallet's key is private; keep it, or use `cia wallet import <key> --force`.\"\n )\n}\n\n/**\n * Replaces a wallet whose key is public with `privateKey`. The old file is\n * backed up next to wallet.json first.\n */\nexport async function replacePublicWallet(privateKey: string): Promise<Address> {\n await assertStoredWalletReplaceable()\n return setWalletPrivateKey(privateKey, { force: true })\n}\n\n/**\n * Reads and decrypts the private key from ~/.chain-insights/wallet.json.\n * Throws a human-readable error if wallet is absent or decryption fails.\n *\n * @returns The decrypted EVM private key string\n */\nexport async function decryptKey(): Promise<string> {\n let raw: string\n try {\n raw = await readFile(walletPath(), 'utf8')\n } catch (err: unknown) {\n const nodeErr = err as NodeJS.ErrnoException\n if (nodeErr.code === 'ENOENT') {\n throw new Error(\n 'Wallet not configured. Run `cia wallet create` to generate one, or `cia wallet import <private-key>` to use an existing key. Then run `cia wallet ready`.'\n )\n }\n throw err\n }\n\n try {\n const stored = JSON.parse(raw) as WalletData\n const salt = Buffer.from(stored.salt, 'hex')\n const key = deriveKey(salt)\n const iv = Buffer.from(stored.iv, 'hex')\n const tag = Buffer.from(stored.tag, 'hex')\n const encrypted = Buffer.from(stored.data, 'hex')\n\n const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv)\n // setAuthTag() MUST be called before update()\n decipher.setAuthTag(tag)\n\n const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])\n\n return decrypted.toString('utf8')\n } catch {\n throw new Error(\n 'Wallet decryption failed. If you changed your hostname or username, re-import it with `cia wallet import <private-key>`.'\n )\n }\n}\n\n/**\n * Returns true if wallet.json exists, false if absent.\n * Does not validate the wallet contents.\n */\nexport async function isWalletConfigured(): Promise<boolean> {\n try {\n await stat(walletPath())\n return true\n } catch (err: unknown) {\n const nodeErr = err as NodeJS.ErrnoException\n if (nodeErr.code === 'ENOENT') return false\n throw err\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AASA,SAAgB,aAAqB;CACnC,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,mBAAmB,aAAa;AACjE;AAIA,SAAS,UAAU,MAAsB;CACvC,OAAO,OAAO,WAAW,GAAG,GAAG,SAAS,EAAE,GAAG,GAAG,SAAS,CAAC,CAAC,YAAY,MAAM,EAAE;AACjF;AASA,SAAgB,0BAA0B,OAAoB;CAC5D,IAAI,CAAC,sBAAsB,KAAK,KAAK,GACnC,MAAM,IAAI,MAAM,sEAAsE;CAExF,OAAO;AACT;AAEA,SAAgB,4BAA4B,YAA6B;CACvE,OAAO,oBAAoB,0BAA0B,UAAU,CAAC,CAAC,CAAC;AACpE;;;;;;;;AASA,eAAsB,WAAW,YAAmC;CAClE,MAAM,uBAAuB,0BAA0B,UAAU;CACjE,MAAM,OAAO,OAAO,YAAY,EAAE;CAClC,MAAM,MAAM,UAAU,IAAI;CAC1B,MAAM,KAAK,OAAO,YAAY,EAAE;CAChC,MAAM,SAAS,OAAO,eAAe,eAAe,KAAK,EAAE;CAE3D,MAAM,YAAY,OAA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T,SAAS,KAAc;EAErB,IAAIA,IAAQ,SAAS,UAAU,OAAO;EACtC,MAAM;CACR;AACF"}
@@ -1,5 +1,5 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
- const require_known_keys = require("./known-keys-PKZF5GYd.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
+ const require_known_keys = require("./known-keys-Cy8lKDOA.cjs");
3
3
  let node_path = require("node:path");
4
4
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
5
5
  let node_fs_promises = require("node:fs/promises");
@@ -8,17 +8,14 @@ node_os = require_rolldown_runtime.__toESM(node_os, 1);
8
8
  let node_crypto = require("node:crypto");
9
9
  node_crypto = require_rolldown_runtime.__toESM(node_crypto, 1);
10
10
  let viem_accounts = require("viem/accounts");
11
- //#region src/wallet/index.ts
11
+ // src/wallet/index.ts
12
12
  var wallet_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
13
13
  assertStoredWalletReplaceable: () => assertStoredWalletReplaceable,
14
14
  decryptKey: () => decryptKey,
15
- encryptKey: () => encryptKey,
16
15
  isWalletConfigured: () => isWalletConfigured,
17
- normalizeWalletPrivateKey: () => normalizeWalletPrivateKey,
18
16
  replacePublicWallet: () => replacePublicWallet,
19
17
  setWalletPrivateKey: () => setWalletPrivateKey,
20
18
  storedWalletKeyIsPublic: () => storedWalletKeyIsPublic,
21
- walletAddressFromPrivateKey: () => walletAddressFromPrivateKey,
22
19
  walletPath: () => walletPath
23
20
  });
24
21
  function walletPath() {
@@ -177,7 +174,6 @@ async function isWalletConfigured() {
177
174
  throw err;
178
175
  }
179
176
  }
180
- //#endregion
181
177
  Object.defineProperty(exports, "decryptKey", {
182
178
  enumerable: true,
183
179
  get: function() {
package/docs/mcp-proxy.md CHANGED
@@ -82,6 +82,7 @@ The proxy:
82
82
  | `meta_network_capabilities` | Show the current Chain Insights network/tool support matrix |
83
83
  | `meta_schema` | Show the live graph schema of a network: labels, link types, fields, indexes |
84
84
  | `meta_dex_lookup` | Turn an exchange name into its factories, routers or manager, pools and first reads |
85
+ | `meta_token_lookup` | Turn a ticker or a token name into every contract that carries it, with its creator |
85
86
  | `meta_rules` | Read the answer rules when the `chain-insights-cypher` skill is not loaded |
86
87
  | `meta_help` | Show Chain Insights tool and workflow guidance |
87
88
  | `meta_usage_status` | Check the caller's daily free-tier graph query allowance |
@@ -132,6 +133,32 @@ cache. `registry_source` in the answer says which copy answered: `fetched`,
132
133
  `cached` or `packaged`. `CHAIN_INSIGHTS_DEX_REGISTRY_URL` points the fetch
133
134
  somewhere else, for tests and the lab; `{network}` in it is filled in.
134
135
 
136
+ `meta_token_lookup` turns a ticker or a token name into the contracts that
137
+ carry it. It takes `network` and `symbol` (both required, `symbol` 1 to 64
138
+ characters). Tickers collide: a clone reuses a symbol on purpose, so the tool
139
+ never picks one.
140
+
141
+ 1. One `graph_query` reads the `Asset` lookup on `USE facts` by symbol. When
142
+ no contract carries the symbol, the same read runs by name. The server
143
+ matches exactly, in any case, and orders the rows verified first, then
144
+ oldest first. The proxy keeps that order.
145
+ 2. One `graph_query_batch` reads, for each candidate, the address that
146
+ deployed it (`factory`) and the sender of that transaction (`creator`) on
147
+ `USE topology`. A batch holds at most 20 reads, so 25 candidates take two.
148
+ A failed or refused creator read keeps the candidate, with `creator` and
149
+ `factory` empty, and the `hint` says the creators were not read.
150
+ 3. The answer carries at most 25 `candidates`, `total` (the rows the server
151
+ sent, at most 26) and `truncated` (true when there are more than 25).
152
+ Each candidate has `first_seen_timestamp_utc` beside the milliseconds.
153
+
154
+ Zero candidates is an answer: no contract on the network carries the symbol
155
+ or the name. A contract address sent as `symbol` sends no read: an address is
156
+ already an anchor, read it on `USE topology`. A server that does not serve the
157
+ `Asset` read yet answers with no candidates and a `hint` to ask the user for
158
+ the contract. Both reads are billed as any read.
159
+ `cia mcp call meta_token_lookup network=robinhood symbol=TCITY` runs the same
160
+ lookup in a terminal.
161
+
135
162
  ## Host parity
136
163
 
137
164
  **A rule a host never loads does not exist for that host.** Each host loads a
@@ -145,6 +172,7 @@ different part of what this package ships:
145
172
  | tool descriptions | yes | yes | yes | yes | yes | yes |
146
173
  | result `hint` | yes | yes | yes | yes | yes | yes |
147
174
  | protocol tool doors | yes | yes | yes | yes | yes | yes |
175
+ | token door `meta_token_lookup` | yes | yes | yes | yes | yes | yes |
148
176
 
149
177
  The scout agent pins the CLI by version in its image and copies only
150
178
  `chain-insights-cypher` and `chain-insights-virtuals` into its project, yet asks
@@ -172,6 +200,12 @@ buying is `cia subscription buy` in a terminal, an agent never buys, and $CIA
172
200
  sent by hand to any other address is not credited. The core skill repeats them
173
201
  as its rule 12. `tests/subscription-rules.test.ts` holds both.
174
202
 
203
+ A token named by its ticker takes the same path. The `meta_token_lookup`
204
+ description carries the rule (tickers collide, zero candidates is an answer,
205
+ never search the web), the `graph_query` description sends a named token to
206
+ it, and the core skill `chain-insights-cypher` repeats it as a row of its
207
+ question table.
208
+
175
209
  A host that loads skills gets both. A host that loads none gets the door.
176
210
  `tests/host-parity.test.ts` checks it: every
177
211
  `skills/chain-insights-<protocol>/SKILL.md` has a door, the door is in
package/docs/stability.md CHANGED
@@ -18,13 +18,14 @@ Exit codes are contract. Scripts and agent harnesses may rely on them.
18
18
 
19
19
  ### MCP tool names
20
20
 
21
- The public MCP surface is these twelve tools:
21
+ The public MCP surface is these thirteen tools:
22
22
 
23
23
  - `graph_query`
24
24
  - `graph_query_batch`
25
25
  - `meta_network_capabilities`
26
26
  - `meta_schema`
27
27
  - `meta_dex_lookup`
28
+ - `meta_token_lookup`
28
29
  - `meta_rules`
29
30
  - `meta_help`
30
31
  - `meta_usage_status`
@@ -33,7 +34,7 @@ The public MCP surface is these twelve tools:
33
34
  - `wallet_topup`
34
35
  - `subscription_topup`
35
36
 
36
- `graph_expand` is the thirteenth tool the proxy registers. The view calls it
37
+ `graph_expand` is the fourteenth tool the proxy registers. The view calls it
37
38
  when you click in a picture; hosts keep it out of the model's tool list. It
38
39
  is not part of the public surface.
39
40
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chain-insights",
3
- "version": "0.75.0",
3
+ "version": "0.76.0",
4
4
  "description": "AML investigation CLI and MCP proxy for blockchain risk screening and Chain Insights Graph access",
5
5
  "homepage": "https://chain-insights.ai",
6
6
  "repository": {
@@ -156,6 +156,7 @@ Find the question in this table. Send its first query, once, with the addresses
156
156
  | Which tokens moved between two addresses? | `topology` | `TRANSFERRED` of the pair, one link per token (see Tokens) |
157
157
  | Where did one token go, or come from, in N hops? | `topology` | The guarded walk on `TRANSFERRED` with one `asset` (see Tokens) |
158
158
  | The biggest receivers of one token in a window | `topology` | `TRANSFERRED` with one `asset` and `last_seen_timestamp` (see Tokens) |
159
+ | The user names a token by its ticker or name, no contract | none | Call `meta_token_lookup {network, symbol}` first; several candidates are clones, name them and ask |
159
160
  | What fields does an Address have? | none | Call `meta_schema {network}`. Send no query. |
160
161
  | Recent addresses, biggest senders, any top list of the chain | topology | A search bounded by `f.last_seen_timestamp`, then sort and LIMIT (below). |
161
162
 
@@ -474,6 +475,8 @@ A `TRANSFERRED` search over the whole chain, with no address anchor, must name o
474
475
 
475
476
  An `asset` that names no token of the graph, or a symbol such as `USDC`, is refused with `anchor_missing` whose fix names the contract: the graph holds no token at that address. That refusal is not a family behind and not a missing anchor: do not ask for an address. Check the contract, all 42 characters in lowercase, and send the same query again with the right one.
476
477
 
478
+ A token named by its ticker or its name, with no contract (TCITY, USDG): call `meta_token_lookup {network, symbol}` first, before any read. It returns every contract on the network that carries that symbol, verified first, then oldest first, each with its creator. Tickers collide: a clone copies a symbol on purpose, so never treat the first row as the token. When several come back, name each contract in full with its creator and first seen time, and ask which one the user means, or pick one by the evidence the user gave and say why. Zero candidates is an answer: say no contract on the network carries the symbol, and do not search the web. Then read the chosen contract as the `asset` of the reads above.
479
+
477
480
  How to answer from these rows:
478
481
 
479
482
  - Tokens are not dollars. Say "tokens worth about 183 USD", never "sent 183 USD". Head the column "Tokens worth (USD)".
@@ -1 +0,0 @@
1
- {"version":3,"file":"dex-tool-ib_ICiyV.mjs","names":["isRecord"],"sources":["../src/mcp/answer-hint.ts","../src/mcp/dex-recipes.ts","../src/mcp/dex-tool.ts"],"sourcesContent":["/**\n * The two answer rules that still slip in long answers, carried on every\n * graph reply in the result's `hint` field. Claude Code has a Stop hook that\n * reads the answer; Codex and Claude Desktop have no such hook, and in the\n * loop's third prompt set they broke one of these two rules in three of\n * thirteen conversations. The reply is the one thing every host hands the\n * model right before it writes, so the rules ride on it. A `hint` the\n * server already set is kept.\n */\n\nexport const ANSWER_HINT =\n 'Answer: write every address in full (0x plus 40 characters), also when it repeats one named earlier and also when the user asks for shorter ones (name them instead); ' +\n 'a transfer moves tokens, so write \"tokens worth about N USD\", never \"sent N USD\" or a $ figure; ' +\n 'never draw the flows in text, ASCII or Mermaid, the host draws them.'\n\ntype TextBlock = { type: string; text?: string }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The structured content with the hint set when the server left it empty. */\nexport function withAnswerHint(structuredContent: unknown): unknown {\n if (!isRecord(structuredContent) || !isRecord(structuredContent.facts)) return structuredContent\n if (typeof structuredContent.hint === 'string' && structuredContent.hint.trim()) return structuredContent\n return { ...structuredContent, hint: ANSWER_HINT }\n}\n\n/** A graph tool result whose structured content and single JSON text block both carry the hint. */\nexport function withAnswerHintResult<T extends { content?: TextBlock[]; structuredContent?: unknown }>(result: T): T {\n const structured = withAnswerHint(result.structuredContent)\n if (structured === result.structuredContent) return result\n const content = result.content ?? []\n const only = content.length === 1 && content[0]?.type === 'text' ? content[0] : null\n let parsed: unknown = undefined\n try {\n parsed = only?.text ? JSON.parse(only.text) : undefined\n } catch {\n parsed = undefined\n }\n const textIsStructured = parsed !== undefined && JSON.stringify(parsed) === JSON.stringify(result.structuredContent)\n return { ...result, structuredContent: structured, content: textIsStructured ? [{ ...only, text: JSON.stringify(structured) }] : content }\n}\n","/**\n * The first reads of each trail type, filled with the addresses of one\n * exchange. meta_dex_lookup returns them, so a host that loads no skill\n * (Claude Desktop chat) still gets the tested reads of\n * skills/chain-insights-dex*. The shapes are the skills' own: R3 and R4 of\n * chain-insights-dex, G1, G4 and G5 of the gauge trail, V1, V3 and V4 of the\n * vault trail, L1 to L3 of the launchpad trail.\n *\n * A value the lookup cannot know (a seller, a day, a transaction) is written\n * as a placeholder in angle brackets, and the step's `why` says where it comes\n * from. Every address the lookup knows is written in full.\n */\n\nimport type { DexEntry, TrailType } from './dex-registry.js'\n\nexport interface RecipeStep {\n step: string\n why: string\n query: string\n}\n\n/** The trail-type skill of each trail, for hosts that load skills. */\nexport const TRAIL_SKILLS: Record<TrailType, string> = {\n plain: 'chain-insights-dex',\n gauge: 'chain-insights-dex-gauge',\n vault: 'chain-insights-dex-vault',\n launchpad: 'chain-insights-dex-launchpad',\n}\n\nconst SELLER = '<seller address>'\nconst DAY = '<YYYY-MM-DD>'\nconst TX = '<tx_id>'\nconst TOKEN = '<launched token address>'\n\n/** The pools one factory deployed, by lifetime volume (R3). */\nexport function poolsByFactoryQuery(factory: string, limit = 10): string {\n return (\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[:DEPLOYED_CONTRACT]->(p:Pool) WHERE p.total_volume_usd IS NOT NULL ` +\n 'RETURN f.address AS from_address, p.address AS to_address, p.labels AS to_labels, p.total_volume_usd AS total_volume_usd, p.tx_total_count AS tx_total_count ' +\n `ORDER BY p.total_volume_usd DESC LIMIT ${limit}`\n )\n}\n\n/** The senders of one pool on FLOWED_TO, by lifetime volume (R4, G1). */\nfunction sellersIntoPoolQuery(pool: string): string {\n return (\n `USE topology MATCH (s:Address)-[f:FLOWED_TO]->(p:Address {address: \"${pool}\"}) WHERE NOT s:Pool ` +\n 'RETURN s.address AS from_address, p.address AS to_address, labels(s) AS from_node_labels, f.amount_usd_sum AS amount_usd_sum, f.tx_count AS tx_count, f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp, s.labels AS from_labels, p.labels AS to_labels, s.is_exchange AS from_is_exchange, p.is_exchange AS to_is_exchange ' +\n 'ORDER BY f.amount_usd_sum DESC LIMIT 25'\n )\n}\n\n/** The payers whose swaps name one contract as the recipient, by sold volume (V4 shape). */\nfunction sellersIntoContractQuery(contract: string): string {\n return (\n `USE topology MATCH (s:Address)-[sw:SWAPPED]->(r:Address {address: \"${contract}\"}) WHERE NOT s:Pool ` +\n 'RETURN s.address AS from_address, r.address AS to_address, labels(s) AS from_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.pools AS pools, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.sold_usd DESC LIMIT 25'\n )\n}\n\n/** One seller's swaps (R5, G2, V1). */\nfunction sellerSwapsQuery(): string {\n return (\n `USE topology MATCH (s:Address {address: \"${SELLER}\"})-[sw:SWAPPED]->(r:Address) ` +\n 'RETURN s.address AS from_address, r.address AS to_address, labels(r) AS to_node_labels, sw.sold_asset AS sold_asset, sw.bought_asset AS bought_asset, sw.sold_usd AS sold_usd, sw.bought_usd AS bought_usd, sw.swap_count AS swap_count, sw.pools AS pools, sw.last_seen_height AS last_seen_height ' +\n 'ORDER BY sw.swap_count DESC LIMIT 25'\n )\n}\n\n/** The facts SWAP rows of a seller and one recipient on one day (R6, G4, V3). */\nfunction swapRowsQuery(recipient: string): string {\n return (\n `USE facts MATCH (s:Address {address: \"${SELLER}\"})-[x:SWAP]->(r:Address {address: \"${recipient}\"}) WHERE x.block_date = \"${DAY}\" ` +\n 'RETURN x.tx_id AS tx_id, x.block_timestamp AS block_timestamp, x.payer AS payer, x.recipient AS recipient, x.sold_asset_symbol AS sold_asset_symbol, x.sold_usd AS sold_usd, x.bought_asset_symbol AS bought_asset_symbol, x.bought_usd AS bought_usd LIMIT 50'\n )\n}\n\n/** The transfers one router made in one transaction (G5). */\nfunction routerPayoutQuery(router: string): string {\n return (\n `USE facts MATCH (r:Address {address: \"${router}\"})-[t:TRANSFER]->(b:Address) WHERE t.block_date = \"${DAY}\" AND t.tx_id = \"${TX}\" ` +\n 'RETURN r.address AS from_address, b.address AS to_address, t.amount_usd AS amount_usd, t.asset_symbol AS asset_symbol, t.kind AS kind, t.tx_id AS tx_id LIMIT 10'\n )\n}\n\nconst dayStep: RecipeStep = {\n step: 'The day of a swap link',\n why: 'A SWAPPED link carries heights, not times: read the block of its last_seen_height for the day the facts reads need.',\n query:\n 'USE chain MATCH (b:Block {block_height: <last_seen_height>}) RETURN b.block_date, b.block_timestamp',\n}\n\n/**\n * The pool a trail starts from: the busiest pool read, else the registry's\n * example pool, else none.\n */\nfunction startPool(entry: DexEntry, topPool: string | null): string | null {\n return topPool ?? entry.example_pool ?? null\n}\n\nfunction poolsStep(entry: DexEntry): RecipeStep | null {\n const factory = entry.factories.find((address) => entry.roles[address] === 'factory')\n if (!factory) return null\n return {\n step: 'Pools of the exchange, by factory',\n why: `The pools ${entry.display} deployed, by lifetime volume. One batch member per factory: ${entry.factories.filter((a) => entry.roles[a] === 'factory').join(', ')}.`,\n query: poolsByFactoryQuery(factory),\n }\n}\n\n/** The first reads of the exchange's trail type, with its addresses filled in. */\nexport function recipeFor(entry: DexEntry, topPool: string | null): RecipeStep[] {\n const pool = startPool(entry, topPool)\n const steps: RecipeStep[] = []\n switch (entry.trail_type) {\n case 'gauge': {\n const router = entry.routers[0]\n if (router) {\n steps.push({\n step: 'Sellers into the router',\n why: `On ${entry.display} a swap pays the router, and the router pays on. These are the payers whose swaps name the router ${router}; the router is never the buyer.`,\n query: sellersIntoContractQuery(router),\n })\n }\n if (pool) {\n steps.push({\n step: 'Sellers into the busiest pool',\n why: `The senders of ${pool} on FLOWED_TO. A sender that also adds liquidity is a liquidity provider, not a seller.`,\n query: sellersIntoPoolQuery(pool),\n })\n } else {\n const pools = poolsStep(entry)\n if (pools) steps.push(pools)\n }\n if (router) {\n steps.push(dayStep)\n steps.push({\n step: \"A seller's swaps through the router on one day\",\n why: 'Fill the seller from the first step and the day from the block read: each row gives the tx_id of one swap.',\n query: swapRowsQuery(router),\n })\n steps.push({\n step: 'Who the router paid in that transaction',\n why: 'Fill the day and the tx_id: the receiver of the bought asset is the buyer. A pool or a pool manager there is the next leg, not the buyer.',\n query: routerPayoutQuery(router),\n })\n }\n break\n }\n case 'vault': {\n const manager = entry.factories[0]!\n steps.push({\n step: 'The swaps the pool manager settles',\n why: `${entry.display} keeps every pool in one manager, ${manager}. A manager deploys nothing: its pools are the pools of the swaps it settles.`,\n query: sellersIntoContractQuery(manager),\n })\n steps.push({\n step: \"One seller's swaps\",\n why: 'Fill a seller from the first step. A recipient that is the manager is never the buyer: read the facts row past it.',\n query: sellerSwapsQuery(),\n })\n steps.push(dayStep)\n steps.push({\n step: 'The facts SWAP row past the manager',\n why: 'Fill the seller and the day: the recipient column names who the manager paid.',\n query: swapRowsQuery(manager),\n })\n break\n }\n case 'launchpad': {\n const factory = entry.factories[0]!\n steps.push({\n step: 'Launches of the launchpad, newest first',\n why: `The contracts ${factory} created, with the creator of each.`,\n query:\n `USE topology MATCH (f:Address {address: \"${factory}\"})-[d:DEPLOYED_CONTRACT]->(t:Address) ` +\n 'RETURN f.address AS from_address, t.address AS to_address, labels(t) AS to_node_labels, t.labels AS to_labels, d.tx_origin AS creator, d.tx_id AS tx_id, d.block_height AS block_height, d.block_timestamp AS created_timestamp ORDER BY d.block_height DESC LIMIT 25',\n })\n steps.push({\n step: 'Traders on the curve of one launched token',\n why: 'Fill a launched token from the first step.',\n query:\n `USE topology MATCH (t:Address {address: \"${TOKEN}\"})-[f:FLOWED_TO]-(b:Address) WHERE NOT t:Pool ` +\n 'RETURN startNode(f).address AS from_address, endNode(f).address AS to_address, labels(b) AS node_labels, f.tx_count AS tx_count, f.amount_usd_sum AS amount_usd_sum, f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp ORDER BY f.tx_count DESC LIMIT 25',\n })\n steps.push({\n step: 'The first pool of one launched token',\n why: 'The oldest ADDED_LIQUIDITY into a :Pool is the graduation. None means it has not graduated in the graph yet.',\n query:\n `USE topology MATCH (t:Address {address: \"${TOKEN}\"})-[l:ADDED_LIQUIDITY]->(p:Pool) ` +\n 'RETURN t.address AS from_address, p.address AS to_address, p.labels AS to_labels, l.asset AS asset, l.usd AS usd, l.first_seen_height AS first_seen_height ORDER BY l.first_seen_height ASC LIMIT 5',\n })\n break\n }\n case 'plain': {\n if (pool) {\n steps.push({\n step: 'Sellers into the busiest pool',\n why: `The senders of ${pool} on FLOWED_TO, by lifetime volume. A seller that is a contract is often an aggregator or a router: say \"a contract\".`,\n query: sellersIntoPoolQuery(pool),\n })\n } else {\n const pools = poolsStep(entry)\n if (pools) steps.push(pools)\n }\n steps.push({\n step: \"Who a seller's swaps paid\",\n why: 'Fill a seller from the first step. Keep the rows whose pools hold the pool: the recipient is the buyer.',\n query: sellerSwapsQuery(),\n })\n steps.push(dayStep)\n steps.push({\n step: 'The swaps of a seller and a recipient on one day',\n why: 'Fill the seller, the recipient and the day.',\n query: swapRowsQuery('<recipient address>'),\n })\n break\n }\n }\n return steps\n}\n","/**\n * meta_dex_lookup: an exchange's name becomes its addresses.\n *\n * A local tool of the proxy. It matches the name against the exchange registry\n * (src/mcp/dex-registry.ts) at no cost, then sends one graph_query_batch of\n * anchored reads: Head for the family lag, each factory, manager and router by\n * its address, and the pools each factory deployed. Nothing is read by name and\n * nothing is gated on a family lag: a factory deployed months ago is not stale\n * because the swap family is behind. A name that is not covered sends no read.\n *\n * The description below is the contract with every host, Claude Desktop chat\n * included, which reads no skill: it carries the rule the exchange skills open\n * with. tests/host-parity.test.ts holds it to the skills' trigger words.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { recipeFor, TRAIL_SKILLS, type RecipeStep, poolsByFactoryQuery } from './dex-recipes.js'\nimport {\n DexRegistryError,\n matchDex,\n normalizeDexNetwork,\n type DexCandidate,\n type DexEntry,\n type DexMatchResult,\n type LoadedRegistry,\n type RegistrySource,\n type Role,\n type TrailType,\n} from './dex-registry.js'\n\nexport const META_DEX_LOOKUP_TOOL = 'meta_dex_lookup'\nexport const META_DEX_LOOKUP_SCHEMA = 'chain-insights.meta-dex-lookup.v1' as const\nexport const META_DEX_LOOKUP_TITLE = 'Exchange by name or address'\nexport const META_DEX_LOOKUP_DESCRIPTION =\n 'Call this first when a question names a decentralized exchange, a launchpad or a vault ' +\n '(Aero, Aerodrome, Velodrome, up., Raphael, Topaz, Uniswap, PancakeSwap, Balancer, Curve, ' +\n \"Penguin, Virtuals, ...) and gives no address. It turns the name into the exchange's \" +\n 'factories, routers or pool manager, its biggest pools, and the first reads to send, ' +\n 'with every address in full. A misspelling within two letters is taken and named in ' +\n 'took_for. When matched is null the name is not covered: say so, list covered, and send ' +\n 'no graph query for the name. Never ask the user for a pool, factory or router address. ' +\n 'When the user gives a contract address instead of a name, send it as address (0x plus 40 hex, ' +\n 'any case, with no name): the answer is the exchange whose factory, router or manager it is, ' +\n 'and took_for names the role it holds. When matched is null no exchange row holds the address: ' +\n 'send no read for it. Give a name or an address, not both.'\nexport const META_DEX_LOOKUP_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const META_DEX_LOOKUP_ARGS = ['network', 'name', 'address', 'pools'] as const\n\n/** The pools returned per exchange, and per factory read. */\nexport const POOLS_LIMIT = 10\n/** A batch holds at most 20 members; Head and the pool reads take their share. */\nconst CONTRACT_MEMBERS_MAX = 12\n\nexport interface ContractRow {\n address: string\n role: Role\n confirmed: boolean\n confirmed_by?: string\n}\n\nexport interface PoolRow {\n address: string\n labels: string[]\n total_volume_usd: number\n tx_total_count: number\n}\n\nexport interface FamilyLag {\n behind_money: number | null\n behind_dex: number | null\n behind_transfers: number | null\n}\n\nexport interface DexMatch {\n dex: string\n display: string\n trail_type: TrailType\n /** The skill a host with skills loads next. */\n skill: string\n factories: ContractRow[]\n routers: ContractRow[]\n manager: ContractRow | null\n pools: PoolRow[]\n recipe: RecipeStep[]\n}\n\nexport interface CoveredExchange {\n dex: string\n display: string\n trail_type: TrailType\n factories: string[]\n routers: string[]\n}\n\nexport interface MetaDexLookupResult {\n schema: typeof META_DEX_LOOKUP_SCHEMA\n network: string\n registry_version: number\n registry_source: RegistrySource\n matched: DexMatch | null\n /** A near name hit: the name as typed. An address hit: the role it holds and the verification cell. */\n took_for?: string\n candidates: DexCandidate[]\n covered: string[]\n /** With no name: every covered exchange, with its key, trail type and contracts. */\n exchanges?: CoveredExchange[]\n families: FamilyLag | null\n /** What a read could not do: a lane that is not reachable, a member that was refused. */\n notes?: string[]\n hint: string\n}\n\n/** The batch reply as the remote client returns it. */\nexport type BatchAnswer = {\n content?: unknown[]\n structuredContent?: unknown\n isError?: boolean\n}\n\nexport interface DexToolDependencies {\n loadRegistry: (network: string) => Promise<LoadedRegistry>\n /** One graph_query_batch through the proxy's remote client, billed as any read. */\n graphQueryBatch: (args: {\n network: string\n queries: Array<{ id: string; query: string }>\n }) => Promise<BatchAnswer>\n /** The reason no read can be sent now, or undefined when the graph is reachable. */\n unavailable?: () => Promise<string | undefined> | string | undefined\n /** The text of a call that threw: payment required, transport. */\n describeFailure: (err: unknown) => string\n}\n\nexport type MetaDexLookupToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction errorResult(text: string): MetaDexLookupToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\ntype Member = { id?: unknown; ok?: unknown; results?: unknown; error?: unknown }\n\nfunction membersOf(answer: BatchAnswer): Map<string, Member> {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const queries = isRecord(facts) ? facts.queries : undefined\n const members = new Map<string, Member>()\n if (Array.isArray(queries)) {\n for (const member of queries)\n if (isRecord(member) && typeof member.id === 'string') members.set(member.id, member)\n }\n return members\n}\n\nconst rowsOf = (member: Member | undefined): Array<Record<string, unknown>> =>\n member?.ok === true && Array.isArray(member.results) ? member.results.filter(isRecord) : []\n\nconst numberOrNull = (value: unknown): number | null => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value)))\n return Number(value)\n return null\n}\n\nconst stringList = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n\n/** A column of a row, read under its alias or as the query wrote it (h.behind_dex). */\nfunction column(row: Record<string, unknown>, name: string, variable: string): unknown {\n return name in row ? row[name] : row[`${variable}.${name}`]\n}\n\nexport const HEAD_QUERY =\n 'USE chain MATCH (h:Head) RETURN h.behind_money, h.behind_dex, h.behind_transfers'\n\nexport function contractQuery(address: string): string {\n return (\n `USE topology MATCH (a:Address {address: \"${address}\"}) ` +\n 'RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.is_contract AS is_contract LIMIT 1'\n )\n}\n\nexport function contractListQuery(addresses: string[]): string {\n return (\n `USE topology MATCH (a:Address) WHERE a.address IN [${addresses.map((a) => `\"${a}\"`).join(', ')}] ` +\n `RETURN a.address AS address, labels(a) AS node_labels, a.labels AS labels, a.is_contract AS is_contract LIMIT ${addresses.length}`\n )\n}\n\n/** The anchored reads of one exchange: Head, each contract, and the pools of each factory. */\nexport function lookupQueries(\n entry: DexEntry,\n pools: boolean\n): Array<{ id: string; query: string }> {\n const contracts = Object.keys(entry.roles)\n const queries: Array<{ id: string; query: string }> = [{ id: 'head', query: HEAD_QUERY }]\n if (contracts.length <= CONTRACT_MEMBERS_MAX) {\n for (const address of contracts)\n queries.push({ id: `contract:${address}`, query: contractQuery(address) })\n } else {\n queries.push({ id: 'contracts', query: contractListQuery(contracts) })\n }\n if (pools) {\n for (const factory of entry.factories.filter((address) => entry.roles[address] === 'factory')) {\n queries.push({ id: `pools:${factory}`, query: poolsByFactoryQuery(factory, POOLS_LIMIT) })\n }\n }\n return queries\n}\n\nfunction confirmation(\n row: Record<string, unknown> | undefined\n): Pick<ContractRow, 'confirmed' | 'confirmed_by'> {\n if (!row) return { confirmed: false }\n if (row.is_contract === true) return { confirmed: true, confirmed_by: 'is_contract' }\n if (stringList(row.node_labels).includes('Contract'))\n return { confirmed: true, confirmed_by: ':Contract' }\n return { confirmed: false }\n}\n\nfunction readMatch(\n entry: DexEntry,\n members: Map<string, Member>,\n read: boolean\n): {\n contracts: Map<string, ContractRow>\n pools: PoolRow[]\n families: FamilyLag | null\n notes: string[]\n} {\n const notes: string[] = []\n const contracts = new Map<string, ContractRow>()\n const listed = new Map(rowsOf(members.get('contracts')).map((row) => [String(row.address), row]))\n for (const [address, role] of Object.entries(entry.roles)) {\n const row = members.has(`contract:${address}`)\n ? rowsOf(members.get(`contract:${address}`))[0]\n : listed.get(address)\n contracts.set(address, { address, role, ...confirmation(row) })\n }\n const byAddress = new Map<string, PoolRow>()\n for (const [id, member] of members) {\n if (!id.startsWith('pools:')) continue\n for (const row of rowsOf(member)) {\n const address = typeof row.to_address === 'string' ? row.to_address : null\n const volume = numberOrNull(row.total_volume_usd)\n if (!address || volume === null || byAddress.has(address)) continue\n byAddress.set(address, {\n address,\n labels: stringList(row.to_labels),\n total_volume_usd: volume,\n tx_total_count: numberOrNull(row.tx_total_count) ?? 0,\n })\n }\n }\n const pools = [...byAddress.values()]\n .sort((a, b) => b.total_volume_usd - a.total_volume_usd)\n .slice(0, POOLS_LIMIT)\n const head = rowsOf(members.get('head'))[0]\n const families: FamilyLag | null = head\n ? {\n behind_money: numberOrNull(column(head, 'behind_money', 'h')),\n behind_dex: numberOrNull(column(head, 'behind_dex', 'h')),\n behind_transfers: numberOrNull(column(head, 'behind_transfers', 'h')),\n }\n : null\n if (read) {\n for (const [id, member] of members) {\n if (member.ok !== true)\n notes.push(\n `${id}: ${typeof member.error === 'string' ? member.error : 'the read was not served'}`\n )\n }\n }\n return { contracts, pools, families, notes }\n}\n\nconst ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/\n\nfunction hintFor(\n result: Omit<MetaDexLookupResult, 'hint'>,\n name: string | null,\n address: string | null = null\n): string {\n if (address !== null && !result.matched) {\n return `${ANSWER_HINT} No exchange row holds ${address}: it is not a registered exchange contract. Send no exchange read for it; read the graph for what the address did.`\n }\n if (address !== null && result.matched) {\n const { matched } = result\n return (\n `${ANSWER_HINT} Say in one line: \"${address} is a ${result.took_for} row of ${matched.display}.\" Ask nothing. ` +\n `Exchange ${matched.display}, trail ${matched.trail_type}: send the first reads of recipe, ` +\n `anchored on the addresses above, and load ${matched.skill} when this host has skills. ` +\n 'Read families before a SWAPPED search: it is sent when behind_dex is at most 100000. Never ask the user for an address.'\n )\n }\n if (name === null) {\n return `${ANSWER_HINT} These are the exchanges the registry covers. Call meta_dex_lookup with a name for its addresses and first reads.`\n }\n if (result.matched) {\n const { matched } = result\n const took = result.took_for\n ? `Say in one line: \"I took ${matched.display} for ${result.took_for}.\" Ask nothing. `\n : ''\n return (\n `${ANSWER_HINT} ${took}Exchange ${matched.display}, trail ${matched.trail_type}: send the first reads of recipe, ` +\n `anchored on the addresses above, and load ${matched.skill} when this host has skills. ` +\n 'Read families before a SWAPPED search: it is sent when behind_dex is at most 100000. Never ask the user for an address.'\n )\n }\n if (result.candidates.length > 0) {\n const names = result.candidates\n .map((candidate) => `${candidate.display} (${candidate.dex})`)\n .join(', ')\n return `${ANSWER_HINT} ${result.candidates.length} rows fit \"${name}\": ${names}. Name both or pick one: call meta_dex_lookup with each key. Never guess one, never ask the user for an address.`\n }\n return `${ANSWER_HINT} ${name} is not covered. Send no query for the name: say so in one line and list the covered exchanges by name.`\n}\n\nfunction textResult(structured: MetaDexLookupResult): MetaDexLookupToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],\n structuredContent: structured as unknown as Record<string, unknown>,\n isError: false,\n }\n}\n\n/** meta_dex_lookup, {network, name?, address?, pools?}. Every argument is checked before the registry is read. */\nexport async function handleMetaDexLookup(\n args: unknown,\n deps: DexToolDependencies\n): Promise<MetaDexLookupToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult((err as Error).message)\n }\n const rawName = record.name\n if (rawName !== undefined && rawName !== null && typeof rawName !== 'string') {\n return errorResult('invalid_name: name must be the exchange name as text')\n }\n const name = typeof rawName === 'string' && rawName.trim() !== '' ? rawName.trim() : null\n const rawAddress = record.address\n if (rawAddress !== undefined && rawAddress !== null && typeof rawAddress !== 'string') {\n return errorResult('invalid_address: address must be 0x plus 40 hex characters')\n }\n const addressText = typeof rawAddress === 'string' && rawAddress.trim() !== '' ? rawAddress.trim() : null\n if (name !== null && addressText !== null) return errorResult('Give a name or an address, not both.')\n if (addressText !== null && !ADDRESS_FORM.test(addressText)) {\n return errorResult('invalid_address: address must be 0x plus 40 hex characters')\n }\n const address = addressText === null ? null : addressText.toLowerCase()\n const rawPools = record.pools\n if (rawPools !== undefined && rawPools !== null && typeof rawPools !== 'boolean') {\n return errorResult('invalid_pools: pools must be true or false')\n }\n const pools = rawPools !== false\n\n let loaded: LoadedRegistry\n try {\n loaded = await deps.loadRegistry(network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError\n ? err.message\n : `exchange registry unavailable: ${(err as Error).message}`\n )\n }\n const { document } = loaded\n const base = {\n schema: META_DEX_LOOKUP_SCHEMA,\n network,\n registry_version: document.registry_version,\n registry_source: loaded.source,\n }\n\n if (name === null && address === null) {\n const result = {\n ...base,\n matched: null,\n candidates: [],\n covered: document.rows.map((row) => row.display),\n exchanges: document.rows.map((row) => ({\n dex: row.dex,\n display: row.display,\n trail_type: row.trail_type,\n factories: row.factories,\n routers: row.routers,\n })),\n families: null,\n }\n return textResult({ ...result, hint: hintFor(result, null) })\n }\n\n let match: DexMatchResult\n if (address !== null) {\n const holder = document.rows.find((row) => address in row.roles)\n match = {\n matched: holder ?? null,\n ...(holder ? { took_for: `${holder.roles[address]}, served` } : {}),\n candidates: [],\n covered: document.rows.map((row) => row.display),\n }\n } else {\n match = matchDex(name as string, document.rows)\n }\n if (!match.matched) {\n const result = {\n ...base,\n matched: null,\n candidates: match.candidates,\n covered: match.covered,\n families: null,\n }\n return textResult({ ...result, hint: hintFor(result, name, address) })\n }\n\n const entry = match.matched\n const queries = lookupQueries(entry, pools)\n let members = new Map<string, Member>()\n const notes: string[] = []\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n notes.push(\n `No graph read was sent: ${unavailable} The contracts are the reviewed registry rows, not yet confirmed on the graph.`\n )\n } else {\n try {\n const answer = await deps.graphQueryBatch({ network, queries })\n members = membersOf(answer)\n if (answer.isError === true && members.size === 0) {\n const first = Array.isArray(answer.content) ? answer.content[0] : undefined\n notes.push(\n `The graph refused the reads: ${isRecord(first) && typeof first.text === 'string' ? first.text : 'no reason given'}`\n )\n }\n } catch (err) {\n notes.push(`The graph reads failed: ${deps.describeFailure(err)}`)\n }\n }\n const read = readMatch(entry, members, members.size > 0)\n notes.push(...read.notes)\n const contractsOf = (role: Role): ContractRow[] =>\n [...read.contracts.values()].filter((contract) => contract.role === role)\n const topPool = read.pools[0]?.address ?? null\n const matched: DexMatch = {\n dex: entry.dex,\n display: entry.display,\n trail_type: entry.trail_type,\n skill: TRAIL_SKILLS[entry.trail_type],\n factories: contractsOf('factory'),\n routers: contractsOf('router'),\n manager: contractsOf('manager')[0] ?? null,\n pools: read.pools,\n recipe: recipeFor(entry, topPool),\n }\n const result = {\n ...base,\n matched,\n ...(match.took_for ? { took_for: match.took_for } : {}),\n candidates: [],\n covered: match.covered,\n families: read.families,\n ...(notes.length > 0 ? { notes } : {}),\n }\n return textResult({ ...result, hint: hintFor(result, name, address) })\n}\n"],"mappings":";;;;;;;;;;;;AAUA,MAAa,cACX;AAMF,SAASA,WAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAA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2B,KAAK,gBAAgB,GAAG,GAAG;CACnE;CAEF,MAAM,OAAO,UAAU,OAAO,SAAS,QAAQ,OAAO,CAAC;CACvD,MAAM,KAAK,GAAG,KAAK,KAAK;CACxB,MAAM,eAAe,SACnB,CAAC,GAAG,KAAK,UAAU,OAAO,CAAC,CAAC,CAAC,QAAQ,aAAa,SAAS,SAAS,IAAI;CAC1E,MAAM,UAAU,KAAK,MAAM,EAAE,EAAE,WAAW;CAC1C,MAAM,UAAoB;EACxB,KAAK,MAAM;EACX,SAAS,MAAM;EACf,YAAY,MAAM;EAClB,OAAO,aAAa,MAAM;EAC1B,WAAW,YAAY,SAAS;EAChC,SAAS,YAAY,QAAQ;EAC7B,SAAS,YAAY,SAAS,CAAC,CAAC,MAAM;EACtC,OAAO,KAAK;EACZ,QAAQ,UAAU,OAAO,OAAO;CAClC;CACA,MAAM,SAAS;EACb,GAAG;EACH;EACA,GAAI,MAAM,WAAW,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;EACrD,YAAY,CAAC;EACb,SAAS,MAAM;EACf,UAAU,KAAK;EACf,GAAI,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;CACtC;CACA,OAAO,WAAW;EAAE,GAAG;EAAQ,MAAM,QAAQ,QAAQ,MAAM,OAAO;CAAE,CAAC;AACvE"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"print-result-BtEAn2Wl.mjs","names":["isRecord"],"sources":["../src/version.ts","../src/mcp/balance-text.ts","../src/mcp/label-case.ts","../src/mcp/timestamp-text.ts","../src/mcp/print-result.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\n\nexport const PACKAGE_INFO = JSON.parse(\n readFileSync(new URL('../package.json', import.meta.url), 'utf8')\n) as { name: string; version: string }\n\nexport const PACKAGE_VERSION = PACKAGE_INFO.version\n","/**\n * An ETH text twin beside every native balance column of a chain answer.\n *\n * `USE chain` serves `balance` as wei in decimal text, exact and 16 to 22\n * digits long. A host without a shell (Claude Desktop, 2026-10-21) printed\n * `10003752747799400` to the user as the balance. A model that divides by\n * 10^18 by head misplaces the point, so the proxy writes `<column>_eth`\n * next to each one, the same way `<column>_utc` sits beside a timestamp.\n */\n\nconst BALANCE_KEY = /(^|_)balance$/\nconst WEI_TEXT = /^[0-9]{1,78}$/\nconst WEI_PER_ETH = 10n ** 18n\n\n/** `0.0100037527477994` for `10003752747799400` wei: exact, no exponent, no trailing zeros. */\nexport function ethText(wei: string): string {\n const value = BigInt(wei)\n const whole = value / WEI_PER_ETH\n const frac = (value % WEI_PER_ETH).toString().padStart(18, '0').replace(/0+$/, '')\n return frac === '' ? whole.toString() : `${whole}.${frac}`\n}\n\nfunction isWeiText(value: unknown): value is string {\n return typeof value === 'string' && WEI_TEXT.test(value)\n}\n\n/**\n * One row with a `<key>_eth` string after every wei balance column that has\n * no twin yet. A column the model itself named `*_eth` (an alias such as\n * `a.balance_eth AS held_eth`, see stripEthProperties) arrives as wei and is\n * rendered as ETH text in place: the model gets the column it asked for.\n */\nexport function addBalanceText(row: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(row)) {\n out[key] = key.endsWith('_eth') && isWeiText(value) ? ethText(value) : value\n if (BALANCE_KEY.test(key) && isWeiText(value) && !(`${key}_eth` in row)) out[`${key}_eth`] = ethText(value)\n }\n return out\n}\n\n/**\n * The `_eth` twin is added by the proxy; it is no chain property. A query\n * that names `a.balance_eth` is rewritten to `a.balance`, so the row comes\n * back and the twin is written beside it. An alias after AS stays as written.\n */\nexport function stripEthProperties(query: string): string {\n return query.replace(/\\.((?:[A-Za-z_][A-Za-z0-9_]*_)?balance)_eth\\b/g, '.$1')\n}\n","/**\n * A node label or link type written in the wrong case is spelled the graph's way.\n *\n * Labels and link types are case sensitive. `(a:address {address: \"0x…\"})`\n * matches nothing and the read answers zero rows with no error, so the model\n * tells the user the address has no activity. Claude Desktop did exactly that\n * for the basket router on 2026-10-21 (skill loop, basket round 8): its links\n * were there under `:Address`.\n *\n * Only a name that is a known label or link type, in another case, after the\n * `:` (or `|`) of a node or link pattern is rewritten. Text inside quotes and a\n * map value such as `{address: address}` stay as written.\n */\n\nconst NAMES = [\n // topology node labels\n 'Account', 'Address', 'Bridge', 'Bundler', 'Chain', 'Contract', 'EntryPoint', 'Exchange', 'IssuerFrozen', 'Launchpad',\n 'Mixer', 'NFT', 'OnMoneyTrail', 'Paymaster', 'Poisoned', 'Pool', 'Protocol', 'Sanctioned', 'Scam', 'SmartAccount',\n 'Targeted', 'Token', 'Victim',\n // chain lookups\n 'Transaction', 'Block', 'Head',\n // topology link types\n 'ADDED_LIQUIDITY', 'APPROVED', 'BRIDGED', 'BUNDLED', 'DEPLOYED_CONTRACT', 'FLOWED_TO', 'LINKED', 'OPERATED_BY',\n 'REMOVED_LIQUIDITY', 'SIGNED_AUTHORIZATION', 'SIGNED_FOR', 'SPONSORED', 'SWAPPED', 'TRANSFERRED',\n // facts link types\n 'TRANSFER', 'BRIDGE_CROSSING', 'SWAP', 'LIQUIDITY_ADD', 'LIQUIDITY_REMOVE',\n]\n\nconst CANONICAL = new Map(NAMES.map((name) => [name.toLowerCase(), name]))\nconst IDENT = /[A-Za-z0-9_]/\n\nfunction prevNonSpace(text: string, from: number): number {\n let i = from\n while (i >= 0 && /\\s/.test(text[i])) i--\n return i\n}\n\n/** True when the `:` or `|` at `at` opens a label or link type, not a map value. */\nfunction opensLabel(text: string, at: number): boolean {\n let i = prevNonSpace(text, at - 1)\n if (i < 0) return false\n // `[:TRANSFER|swap]`: a `|` counts only after a link type of its own.\n if (text[at] !== '|' && (text[i] === '(' || text[i] === '[')) return true\n if (!IDENT.test(text[i])) return false\n while (i >= 0 && IDENT.test(text[i])) i--\n const before = prevNonSpace(text, i)\n // `(a:Address:contract)`: the name before this `:` is itself a label.\n if (before >= 0 && (text[before] === ':' || text[before] === '|')) return opensLabel(text, before)\n return text[at] === ':' && before >= 0 && (text[before] === '(' || text[before] === '[')\n}\n\nfunction fixSegment(segment: string): string {\n return segment.replace(/([:|])(\\s*)([A-Za-z_][A-Za-z0-9_]*)/g, (whole, mark: string, space: string, name: string, at: number) => {\n const canonical = CANONICAL.get(name.toLowerCase())\n if (!canonical || canonical === name || !opensLabel(segment, at)) return whole\n return `${mark}${space}${canonical}`\n })\n}\n\n/** The query with every known label and link type in the graph's case; quoted text is untouched. */\nexport function fixLabelCase(query: string): string {\n return query\n .split(/(\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|`[^`]*`)/)\n .map((part, index) => (index % 2 === 1 ? part : fixSegment(part)))\n .join('')\n}\n","/**\n * A UTC text twin beside every timestamp column of a graph answer.\n *\n * The graph serves integer milliseconds. A model that converts them by head\n * gets the time of day wrong about one time in three (loop 3, 2026-10-10:\n * four of twelve answers about one block named 00:15, 09:35, 06:35 or 09:15\n * for 23:55:43 UTC). Hosts without a shell (Claude Desktop) have no other\n * way to convert, so the proxy writes `<column>_utc` next to each one.\n */\n\nimport { addBalanceText, stripEthProperties } from './balance-text.js'\nimport { fixLabelCase } from './label-case.js'\n\nconst TIMESTAMP_KEY = /(_timestamp|_time|_at|_seen|_active)$/\nconst MIN_MS = 1_000_000_000_000 // 2001-09-09\nconst MAX_MS = 4_000_000_000_000 // 2096-10-02\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** `2026-08-05 23:55:43 UTC` for epoch milliseconds. */\nexport function utcText(ms: number): string {\n return `${new Date(ms).toISOString().slice(0, 19).replace('T', ' ')} UTC`\n}\n\nfunction isEpochMs(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value >= MIN_MS && value <= MAX_MS\n}\n\n/**\n * One row with a `<key>_utc` string after every epoch-millisecond timestamp\n * column. A column the model itself named `*_utc` (its query asked for the\n * twin as a property, see stripUtcProperties) arrives as milliseconds and is\n * rendered as UTC text in place: the model gets the column it asked for.\n */\nexport function addTimestampText(row: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(row)) {\n out[key] = key.endsWith('_utc') && isEpochMs(value) ? utcText(value) : value\n if (TIMESTAMP_KEY.test(key) && isEpochMs(value) && !(`${key}_utc` in row)) out[`${key}_utc`] = utcText(value)\n }\n return out\n}\n\n/**\n * The `_utc` twin is added to a reply by the proxy; it is no graph property.\n * Thirteen of 48 loop-5 rounds wrote `f.first_seen_timestamp_utc` into a\n * query anyway: topology answers null, a SWAP read is refused. The property\n * reference is rewritten to its millisecond column, `x.<column>_utc` to\n * `x.<column>`; an alias after AS is not a property and stays as written, so\n * `f.first_seen_timestamp_utc AS first_seen_utc` yields a `first_seen_utc`\n * column that addTimestampText renders as text. A label or link type in the\n * wrong case is spelled the graph's way (label-case.ts).\n */\nexport function stripUtcProperties(query: string): string {\n return fixLabelCase(stripEthProperties(query.replace(/\\.([A-Za-z_][A-Za-z0-9_]*?)_utc\\b/g, '.$1')))\n}\n\n/** graph_query and graph_query_batch arguments with stripUtcProperties applied to every query. */\nexport function withoutUtcProperties(toolName: string, args: Record<string, unknown>): Record<string, unknown> {\n if (toolName === 'graph_query' && typeof args.query === 'string') return { ...args, query: stripUtcProperties(args.query) }\n if (toolName === 'graph_query_batch' && Array.isArray(args.queries)) {\n return {\n ...args,\n queries: args.queries.map((entry) =>\n isRecord(entry) && typeof entry.query === 'string' ? { ...entry, query: stripUtcProperties(entry.query) } : entry\n ),\n }\n }\n return args\n}\n\nfunction mapResults(holder: unknown): unknown {\n if (!isRecord(holder) || !Array.isArray(holder.results)) return holder\n return {\n ...holder,\n results: holder.results.map((row) => (isRecord(row) ? addBalanceText(addTimestampText(row)) : row)),\n }\n}\n\n/**\n * The structured content of graph_query (facts.query.results) or\n * graph_query_batch (facts.queries[].results) with the UTC twins and the\n * ETH twins (balance-text.ts) added.\n * Anything else comes back as it was.\n */\nexport function withTimestampText(structuredContent: unknown): unknown {\n if (!isRecord(structuredContent) || !isRecord(structuredContent.facts)) return structuredContent\n const facts = structuredContent.facts\n if (!isRecord(facts.query) && !Array.isArray(facts.queries)) return structuredContent\n const next: Record<string, unknown> = { ...facts }\n if (isRecord(facts.query)) next.query = mapResults(facts.query)\n if (Array.isArray(facts.queries)) next.queries = facts.queries.map(mapResults)\n return { ...structuredContent, facts: next }\n}\n\ntype TextBlock = { type: string; text?: string }\n\n/**\n * A tool result whose structured content and single JSON text block both carry\n * the UTC twins. A text block that is not the JSON of the structured content\n * is left alone.\n */\nexport function withTimestampTextResult<T extends { content?: TextBlock[]; structuredContent?: unknown }>(result: T): T {\n const structured = withTimestampText(result.structuredContent)\n if (structured === result.structuredContent) return result\n const content = result.content ?? []\n const only = content.length === 1 && content[0]?.type === 'text' ? content[0] : null\n let parsed: unknown = undefined\n try {\n parsed = only?.text ? JSON.parse(only.text) : undefined\n } catch {\n parsed = undefined\n }\n const textIsStructured =\n parsed !== undefined && JSON.stringify(parsed) === JSON.stringify(result.structuredContent)\n return {\n ...result,\n structuredContent: structured,\n content: textIsStructured ? [{ ...only, text: JSON.stringify(structured) }] : content,\n }\n}\n","import { withTimestampTextResult } from './timestamp-text.js'\n\nexport interface McpTextResult {\n content?: Array<{ type: string; text?: string }>\n structuredContent?: unknown\n isError?: boolean\n}\n\n/**\n * The refusal envelope of the graph server, as the reply carries it in\n * `structuredContent.error_detail`. `class` is one of `refused`, `killed`,\n * `capacity` or `failed`, and it decides the caller's next move.\n */\nexport interface McpErrorDetail {\n code?: string\n rule?: string\n class?: string\n fix?: string\n example?: string\n}\n\nconst ERROR_DETAIL_FIELDS = ['code', 'rule', 'class', 'fix', 'example'] as const\n\n/**\n * A tool reply flagged `isError`: the server answered, and its answer is an\n * error. It is never a failure of the connection, so no caller may report it\n * as an unreachable endpoint. `message` is the server's own text and\n * `errorDetail` is the envelope of the reply, absent when the reply has none.\n */\nexport class McpToolError extends Error {\n readonly errorDetail?: McpErrorDetail\n\n constructor(message: string, errorDetail?: McpErrorDetail) {\n super(message)\n this.name = 'McpToolError'\n if (errorDetail) this.errorDetail = errorDetail\n }\n}\n\nexport interface McpPrintOptions {\n tool?: string\n json?: boolean\n}\n\n// What a switched-off or lagging chain layer means for the caller, in the line\n// under the server's text. The endpoint answered, so the endpoint is up, and\n// the other two layers do not depend on the chain node.\nconst CHAIN_UNAVAILABLE_MEANING =\n 'the chain layer is off or behind. The endpoint is up. USE topology and USE facts still work.'\n\n/**\n * How `cia mcp call` shows an McpToolError: the server's own text, then one\n * line built from its error_detail, `code <code> · class <class> · <fix>`. A\n * reply with no error_detail is the server text alone. For `chain_unavailable`\n * the line also says what the code means for the caller.\n */\nexport function formatMcpToolError(err: McpToolError): string {\n const detail = err.errorDetail\n if (!detail) return err.message\n const parts: string[] = []\n if (detail.code) parts.push(`code ${detail.code}`)\n if (detail.class) parts.push(`class ${detail.class}`)\n if (detail.fix) parts.push(detail.fix)\n if (detail.code === 'chain_unavailable') parts.push(CHAIN_UNAVAILABLE_MEANING)\n if (parts.length === 0) return err.message\n return `${err.message}\\n ${parts.join(' · ')}`\n}\n\ntype JsonRecord = Record<string, unknown>\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** The text fields of `structuredContent.error_detail`, or undefined when it has none. */\nfunction errorDetailOf(structuredContent: unknown): McpErrorDetail | undefined {\n if (!isRecord(structuredContent) || !isRecord(structuredContent.error_detail)) return undefined\n const detail: McpErrorDetail = {}\n for (const field of ERROR_DETAIL_FIELDS) {\n const value = structuredContent.error_detail[field]\n if (typeof value === 'string') detail[field] = value\n }\n return Object.keys(detail).length > 0 ? detail : undefined\n}\n\nfunction displayValue(value: unknown): string {\n if (value === null || value === undefined) return ''\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\nfunction formatTable(rows: Array<JsonRecord>): string[] {\n if (rows.length === 0) return []\n const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))]\n const values = rows.map((row) => columns.map((column) => displayValue(row[column])))\n const widths = columns.map((column, index) =>\n Math.max(column.length, ...values.map((row) => row[index]?.length ?? 0))\n )\n const line = (row: string[]): string =>\n row\n .map((value, index) => (index === row.length - 1 ? value : value.padEnd(widths[index] ?? 0)))\n .join(' | ')\n return [line(columns), widths.map((width) => '-'.repeat(width)).join('-+-'), ...values.map(line)]\n}\n\nfunction formatGraphResult(value: JsonRecord, fallbackTool?: string): string | null {\n const facts = isRecord(value.facts) ? value.facts : undefined\n const query = facts && isRecord(facts.query) ? facts.query : undefined\n const queries = facts && Array.isArray(facts.queries) ? facts.queries : undefined\n if (!query && !queries) return null\n\n const lines = [`Tool: ${displayValue(value.tool) || fallbackTool || 'MCP result'}`]\n const subject = isRecord(value.subject)\n ? value.subject\n : facts && isRecord(facts.subject)\n ? facts.subject\n : undefined\n if (subject?.network !== undefined) lines.push(`Network: ${displayValue(subject.network)}`)\n\n if (query) {\n const results = Array.isArray(query.results) ? query.results.filter(isRecord) : []\n if (query.count !== undefined) lines.push(`Rows: ${displayValue(query.count)}`)\n else lines.push(`Rows: ${results.length}`)\n if (query.billable_units !== undefined) {\n lines.push(`Billed units: ${displayValue(query.billable_units)}`)\n }\n if (query.elapsed_ms !== undefined) lines.push(`Elapsed: ${displayValue(query.elapsed_ms)} ms`)\n if (query.truncated !== undefined) lines.push(`Truncated: ${displayValue(query.truncated)}`)\n if (query.error !== undefined) lines.push(`Error: ${displayValue(query.error)}`)\n if (results.length > 0) lines.push('', 'Results:', ...formatTable(results))\n else lines.push('', 'Results: none')\n }\n\n if (queries) {\n lines.push(`Queries: ${queries.length}`)\n for (const entry of queries) {\n if (!isRecord(entry)) continue\n const id = displayValue(entry.id) || 'query'\n const results = Array.isArray(entry.results) ? entry.results.filter(isRecord) : []\n lines.push('', `[${id}]`)\n if (entry.error !== undefined) lines.push(`Error: ${displayValue(entry.error)}`)\n lines.push(`Rows: ${displayValue(entry.count ?? results.length)}`)\n if (results.length > 0) lines.push(...formatTable(results))\n else lines.push('Results: none')\n }\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Formats one MCP text block for terminal output. JSON is indented when the\n * caller requests `--json`; graph query envelopes are rendered as a compact\n * result summary and table by default.\n */\nexport function formatMcpTextContent(\n text: string,\n tool?: string,\n options: Pick<McpPrintOptions, 'json'> = {}\n): string {\n let parsed: unknown\n try {\n parsed = JSON.parse(text) as unknown\n } catch {\n return text\n }\n\n if (options.json) {\n try {\n return JSON.stringify(parsed, null, 2)\n } catch {\n return text\n }\n }\n\n if (isRecord(parsed)) {\n return formatGraphResult(parsed, tool) ?? JSON.stringify(parsed, null, 2)\n }\n return displayValue(parsed)\n}\n\n/**\n * Prints the text blocks of an MCP tool result to stdout. When the result is\n * flagged `isError`, throws an McpToolError with the tool's error text instead\n * — MCP `callTool` returns tool errors as ordinary results (it does not\n * reject), so callers must surface them as failures (non-zero exit) rather than\n * printing to stdout and exiting 0. The error keeps the `error_detail` of the\n * reply, so a caller can tell a refused query from a dead endpoint.\n */\n/** The tools whose rows carry the `_utc` and `_eth` twins, the same two the proxy adds (src/mcp/proxy.ts). */\nfunction isGraphReadTool(tool?: string): boolean {\n return tool === 'graph_query' || tool === 'graph_query_batch'\n}\n\n/**\n * A graph reply with the twins the proxy writes for a host: `<column>_utc`\n * beside every timestamp and `<column>_eth` beside every wei balance. The\n * shell path printed the server row as it arrived (chain-insights #509), so a\n * person reading `cia mcp call` got the raw milliseconds and the raw wei.\n * The text block the server sends is the JSON of its structured content, so\n * both are rewritten together; a result with no structured content is read\n * from its text block first.\n */\nexport function withGraphTwins(result: McpTextResult, tool?: string): McpTextResult {\n if (!isGraphReadTool(tool) || result.isError) return result\n const only = (result.content ?? []).length === 1 && result.content?.[0]?.type === 'text' ? result.content[0] : null\n let structured = result.structuredContent\n if (structured === undefined && only?.text) {\n try {\n structured = JSON.parse(only.text) as unknown\n } catch {\n return result\n }\n }\n const twinned = withTimestampTextResult({ ...result, structuredContent: structured })\n return twinned.structuredContent === structured && result.structuredContent !== undefined ? result : twinned\n}\n\nexport function printMcpTextContent(result: McpTextResult, options: McpPrintOptions = {}): void {\n result = withGraphTwins(result, options.tool)\n const texts = (result.content ?? [])\n .filter((item) => item.type === 'text')\n .map((item) => item.text ?? '')\n\n if (result.isError) {\n throw new McpToolError(\n texts.join('\\n').trim() || 'MCP tool returned an error',\n errorDetailOf(result.structuredContent)\n )\n }\n\n for (const text of texts) console.log(formatMcpTextContent(text, options.tool, options))\n}\n"],"mappings":";;;AAEA,MAAa,eAAe,KAAK,MAC/B,aAAa,IAAI,IAAI,mBAAmB,YAAY,GAAG,GAAG,MAAM,CAClE;AAEA,MAAa,kBAAkB,aAAa;;;;;;;;;;;;ACI5C,MAAM,cAAc;AACpB,MAAM,WAAW;AACjB,MAAM,cAAc,OAAO;;AAG3B,SAAgB,QAAQ,KAAqB;CAC3C,MAAM,QAAQ,OAAO,GAAG;CACxB,MAAM,QAAQ,QAAQ;CACtB,MAAM,QAAQ,QAAQ,YAAA,CAAa,SAAS,CAAC,CAAC,SAAS,IAAI,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;CACjF,OAAO,SAAS,KAAK,MAAM,SAAS,IAAI,GAAG,MAAM,GAAG;AACtD;AAEA,SAAS,UAAU,OAAiC;CAClD,OAAO,OAAO,UAAU,YAAY,SAAS,KAAK,KAAK;AACzD;;;;;;;AAQA,SAAgB,eAAe,KAAuD;CACpF,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAAG;EAC9C,IAAI,OAAO,IAAI,SAAS,MAAM,KAAK,UAAU,KAAK,IAAI,QAAQ,KAAK,IAAI;EACvE,IAAI,YAAY,KAAK,GAAG,KAAK,UAAU,KAAK,KAAK,EAAE,GAAG,IAAI,SAAS,MAAM,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;CAC5G;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,mBAAmB,OAAuB;CACxD,OAAO,MAAM,QA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IAAI;CACnC,QAAQ;EACN,OAAO;CACT;CAEF,MAAM,UAAU,wBAAwB;EAAE,GAAG;EAAQ,mBAAmB;CAAW,CAAC;CACpF,OAAO,QAAQ,sBAAsB,cAAc,OAAO,sBAAsB,KAAA,IAAY,SAAS;AACvG;AAEA,SAAgB,oBAAoB,QAAuB,UAA2B,CAAC,GAAS;CAC9F,SAAS,eAAe,QAAQ,QAAQ,IAAI;CAC5C,MAAM,SAAS,OAAO,WAAW,CAAC,EAAA,CAC/B,QAAQ,SAAS,KAAK,SAAS,MAAM,CAAC,CACtC,KAAK,SAAS,KAAK,QAAQ,EAAE;CAEhC,IAAI,OAAO,SACT,MAAM,IAAI,aACR,MAAM,KAAK,IAAI,CAAC,CAAC,KAAK,KAAK,8BAC3B,cAAc,OAAO,iBAAiB,CACxC;CAGF,KAAK,MAAM,QAAQ,OAAO,QAAQ,IAAI,qBAAqB,MAAM,QAAQ,MAAM,OAAO,CAAC;AACzF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"robinhood-CCTMagwM.mjs","names":[],"sources":["../src/wallet/robinhood.ts"],"sourcesContent":["import {\n createPublicClient,\n createWalletClient,\n decodeEventLog,\n defineChain,\n formatEther,\n formatUnits,\n http,\n type Address,\n type Hex,\n} from 'viem'\nimport { robinhood } from 'viem/chains'\nimport { privateKeyToAccount } from 'viem/accounts'\n\n// Robinhood Chain: the network of the $CIA token and of the subscription\n// payment. Also the second EVM network accepted for x402 Permit2 payments\n// beside Base (src/mcp/client.ts).\nexport const ROBINHOOD_CHAIN_ID = 4663\nexport const ROBINHOOD_NETWORK = 'eip155:4663'\nexport const ROBINHOOD_NETWORK_DISPLAY = 'Robinhood Chain'\nexport const ROBINHOOD_RPC_URL = 'https://rpc.mainnet.chain.robinhood.com'\nexport const PUBLIC_ROBINHOOD_RPC_URLS = [ROBINHOOD_RPC_URL, 'https://rpc.ordofi.network'] as const\nexport const ROBINHOOD_EXPLORER_URL = 'https://robin.etherscan.io'\n\n// $CIA, the Chain Insights token on Robinhood Chain.\nexport const CIA_TOKEN_ADDRESS = '0x766bd6598182586beda76414dc5f8deb1530a213' as const\nexport const CIA_DECIMALS = 18\nexport const CIA_SYMBOL = '$CIA'\n\n// The subscription sink. Module-private on purpose: only the buy below sends\n// to it, and no text a user reads names it. $CIA sent to it by hand is not\n// credited to a subscription.\nconst SUBSCRIPTION_SINK = '0x67a8c068cc762e371706ea6c399178171f92810d' as const\n\n// viem's chain entry links Blockscout; Chain Insights links Etherscan.\nexport const robinhoodChain = defineChain({\n ...robinhood,\n blockExplorers: {\n default: { name: 'Robinhood Chain Etherscan', url: ROBINHOOD_EXPLORER_URL },\n },\n})\n\nconst ERC20_ABI = [\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: '', type: 'uint256' }],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ name: '', type: 'uint256' }],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n] as const\n\nconst SINK_ABI = [\n {\n type: 'function',\n name: 'deposit',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'token', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [],\n },\n {\n type: 'event',\n name: 'Received',\n inputs: [\n { name: 'from', type: 'address', indexed: true },\n { name: 'token', type: 'address', indexed: true },\n { name: 'amount', type: 'uint256', indexed: false },\n ],\n },\n] as const\n\n/**\n * The Robinhood Chain RPC list: ROBINHOOD_RPC_URL from the environment first,\n * then the public endpoints, without duplicates.\n */\nexport function robinhoodRpcUrls(env: NodeJS.ProcessEnv = process.env): string[] {\n const override = env['ROBINHOOD_RPC_URL']?.trim()\n const urls = [...(override ? [override] : []), ...PUBLIC_ROBINHOOD_RPC_URLS]\n return [...new Set(urls)]\n}\n\nexport function explorerTxUrl(hash: string): string {\n return `${ROBINHOOD_EXPLORER_URL}/tx/${hash}`\n}\n\nexport function explorerAddressUrl(address: string): string {\n return `${ROBINHOOD_EXPLORER_URL}/address/${address}`\n}\n\n/** A $CIA amount in token units (18 decimals) as a decimal string. */\nexport function formatCia(amount: bigint): string {\n return formatUnits(amount, CIA_DECIMALS)\n}\n\nfunction publicClient(url: string) {\n return createPublicClient({ chain: robinhoodChain, transport: http(url) })\n}\n\n/** Walks the RPC list; null when every endpoint fails. */\nasync function readFirst<T>(env: NodeJS.ProcessEnv, read: (url: string) => Promise<T>): Promise<T | null> {\n for (const url of robinhoodRpcUrls(env)) {\n try {\n return await read(url)\n } catch {\n // Try the next Robinhood Chain RPC endpoint.\n }\n }\n return null\n}\n\nexport function readCiaBalance(address: string, env: NodeJS.ProcessEnv = process.env): Promise<bigint | null> {\n return readFirst(env, (url) =>\n publicClient(url).readContract({\n address: CIA_TOKEN_ADDRESS,\n abi: ERC20_ABI,\n functionName: 'balanceOf',\n args: [address as Address],\n })\n )\n}\n\nexport function readRobinhoodEthBalance(address: string, env: NodeJS.ProcessEnv = process.env): Promise<bigint | null> {\n return readFirst(env, (url) => publicClient(url).getBalance({ address: address as Address }))\n}\n\n/** The $CIA the subscription sink may take from `owner`. */\nexport function readCiaAllowance(owner: string, env: NodeJS.ProcessEnv = process.env): Promise<bigint | null> {\n return readFirst(env, (url) =>\n publicClient(url).readContract({\n address: CIA_TOKEN_ADDRESS,\n abi: ERC20_ABI,\n functionName: 'allowance',\n args: [owner as Address, SUBSCRIPTION_SINK],\n })\n )\n}\n\n/** The $CIA balance as a decimal string, or 'unknown' when every RPC fails. */\nexport async function getCiaBalance(address: string, env: NodeJS.ProcessEnv = process.env): Promise<string> {\n const value = await readCiaBalance(address, env)\n return value === null ? 'unknown' : formatCia(value)\n}\n\n/** The ETH balance on Robinhood Chain, or 'unknown' when every RPC fails. */\nexport async function getRobinhoodEthBalance(address: string, env: NodeJS.ProcessEnv = process.env): Promise<string> {\n const value = await readRobinhoodEthBalance(address, env)\n return value === null ? 'unknown' : formatEther(value)\n}\n\n/** The allowance of the subscription sink, or 'unknown' when every RPC fails. */\nexport async function getCiaAllowance(owner: string, env: NodeJS.ProcessEnv = process.env): Promise<string> {\n const value = await readCiaAllowance(owner, env)\n return value === null ? 'unknown' : formatCia(value)\n}\n\nexport interface SentTransaction {\n txHash: Hex\n status: 'success' | 'reverted'\n}\n\nexport interface DepositTransaction extends SentTransaction {\n /** The sink's Received log of this deposit, or null when it has none. */\n received: { from: string; token: string; amount: bigint } | null\n}\n\n/**\n * A transaction is sent once, through the first RPC of the list, and never\n * resent through another: a send that failed half-way may still land.\n */\nfunction writeClients(privateKey: Hex, env: NodeJS.ProcessEnv) {\n const url = robinhoodRpcUrls(env)[0]\n const account = privateKeyToAccount(privateKey)\n return {\n account,\n publicClient: publicClient(url),\n walletClient: createWalletClient({ account, chain: robinhoodChain, transport: http(url) }),\n }\n}\n\n/** Approves exactly `amount` $CIA to the subscription sink, never more. */\nexport async function approveCiaForSubscription(\n privateKey: Hex,\n amount: bigint,\n env: NodeJS.ProcessEnv = process.env\n): Promise<SentTransaction> {\n const { publicClient: reader, walletClient } = writeClients(privateKey, env)\n const txHash = await walletClient.writeContract({\n address: CIA_TOKEN_ADDRESS,\n abi: ERC20_ABI,\n functionName: 'approve',\n args: [SUBSCRIPTION_SINK, amount],\n })\n const receipt = await reader.waitForTransactionReceipt({ hash: txHash })\n return { txHash, status: receipt.status }\n}\n\n/** Deposits `amount` $CIA into the subscription sink and reads its Received log. */\nexport async function depositCiaForSubscription(\n privateKey: Hex,\n amount: bigint,\n env: NodeJS.ProcessEnv = process.env\n): Promise<DepositTransaction> {\n const { publicClient: reader, walletClient } = writeClients(privateKey, env)\n const txHash = await walletClient.writeContract({\n address: SUBSCRIPTION_SINK,\n abi: SINK_ABI,\n functionName: 'deposit',\n args: [CIA_TOKEN_ADDRESS, amount],\n })\n const receipt = await reader.waitForTransactionReceipt({ hash: txHash })\n let received: DepositTransaction['received'] = null\n for (const log of receipt.logs) {\n if (log.address.toLowerCase() !== SUBSCRIPTION_SINK) continue\n try {\n const event = decodeEventLog({ abi: SINK_ABI, data: log.data, topics: log.topics })\n if (event.eventName === 'Received') {\n received = { from: event.args.from, token: event.args.token, amount: event.args.amount }\n }\n } catch {\n // Not the Received event.\n }\n }\n return { txHash, status: receipt.status, received }\n}\n"],"mappings":";;;;AAiBA,MAAa,qBAAqB;AAClC,MAAa,oBAAoB;AACjC,MAAa,4BAA4B;AAEzC,MAAa,4BAA4B,CAAC,2CAAmB,4BAA4B;AACzF,MAAa,yBAAyB;AAGtC,MAAa,oBAAoB;AACjC,MAAa,eAAe;AAC5B,MAAa,aAAa;AAK1B,MAAM,oBAAoB;AAG1B,MAAa,iBAAiB,YAAY;CACxC,GAAG;CACH,gBAAgB,EACd,SAAS;EAAE,MAAM;EAA6B,KAAK;CAAuB,EAC5E;AACF,CAAC;AAED,MAAM,YAAY;CAChB;EACE,MAAM;EACN,MAAM;EACN,iBAAiB;EACjB,QAAQ,CAAC;GAAE,MAAM;GAAW,MAAM;EAAU,CAAC;EAC7C,SAAS,CAAC;GAAE,MAAM;GAAI,MAAM;EAAU,CAAC;CACzC;CACA;EACE,MAAM;EACN,MAAM;EACN,iBAAiB;EACjB,QAAQ,CACN;GAAE,MAAM;GAAS,MAAM;EAAU,GACjC;GAAE,MAAM;GAAW,MAAM;EAAU,CACrC;EACA,SAAS,CAAC;GAAE,MAAM;GAAI,MAAM;EAAU,CAAC;CACzC;CACA;EACE,MAAM;EACN,MAAM;EACN,iBAAiB;EACjB,QAAQ,CACN;GAAE,MAAM;GAAW,MAAM;EAAU,GACnC;GAAE,MAAM;GAAU,MAAM;EAAU,CACpC;EACA,SAAS,CAAC;GAAE,MAAM;GAAI,MAAM;EAAO,CAAC;CACtC;AACF;AAEA,MAAM,WAAW,CACf;CACE,MAAM;CACN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,SAAS,MAAM,aAAa,cAAc;EAC9C,SAAS;EACT,KAAK;EACL,cAAc;EACd,MAAM,CAAC,mBAAmB,MAAM;CAClC,CAAC;CACD,MAAM,UAAU,MAAM,OAAO,0BAA0B,EAAE,MAAM,OAAO,CAAC;CACvE,IAAI,WAA2C;CAC/C,KAAK,MAAM,OAAO,QAAQ,MAAM;EAC9B,IAAI,IAAI,QAAQ,YAAY,MAAM,mBAAmB;EACrD,IAAI;GACF,MAAM,QAAQ,eAAe;IAAE,KAAK;IAAU,MAAM,IAAI;IAAM,QAAQ,IAAI;GAAO,CAAC;GAClF,IAAI,MAAM,cAAc,YACtB,WAAW;IAAE,MAAM,MAAM,KAAK;IAAM,OAAO,MAAM,KAAK;IAAO,QAAQ,MAAM,KAAK;GAAO;EAE3F,QAAQ,CAER;CACF;CACA,OAAO;EAAE;EAAQ,QAAQ,QAAQ;EAAQ;CAAS;AACpD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tool-visibility-zcmwMSbn.mjs","names":[],"sources":["../src/mcp/tool-visibility.ts"],"sourcesContent":["import { McpToolError, formatMcpToolError } from './print-result.js'\n\nexport const HIDDEN_REMOTE_TOOL_NAMES = new Set([\n 'topup',\n 'address_risk',\n // Hidden until its verdict is fixed: never listed, never registered, never\n // called through the proxy. The remote graph endpoint does not serve it.\n 'aml_address_risk',\n 'trace_victim_funds',\n 'trace_suspect_funds',\n 'trace_deposit_sources',\n 'trace_funds',\n 'track_funds',\n // Retired tools: never exposed publicly. Built by concatenation so the\n // retired names do not appear as literals in this file.\n ['aml_trace_victim', '_funds'].join(''),\n ['aml_trace_suspect', '_funds'].join(''),\n ['aml_trace_deposit', '_sources'].join(''),\n 'network_capabilities',\n 'usage_status',\n 'subscription_status',\n 'balance',\n 'help',\n ['money', '_flows_between_exchanges'].join(''),\n 'address_connection_risk',\n])\n\nexport const PUBLIC_MCP_TOOL_REQUIRED_ARGS: Record<string, string[]> = {\n graph_query: ['query', 'network'],\n graph_query_batch: ['network', 'queries'],\n}\n\n// normalizeRemoteToolArguments FILTERS pass-through arguments to this list, so\n// an argument that is missing here is silently STRIPPED and the caller gets a\n// default-bounded result with no error and no warning. `time_scope` shipped\n// broken for exactly this reason. Every tunable search bound below\n// (per_address_limit, row_limit) must therefore be listed the moment it\n// appears on a tool schema, and is covered end-to-end through the proxy in\n// tests/mcp-proxy.test.ts.\nexport const PUBLIC_MCP_TOOL_ALLOWED_ARGS: Record<string, string[]> = {\n // `time_scope` narrows a `USE topology` query to a temporal-shard subset\n graph_query: ['query', 'network', 'time_scope'],\n graph_query_batch: ['network', 'queries', 'per_query_timeout_seconds', 'time_scope'],\n // A local tool of the proxy (src/mcp/dex-tool.ts): the exchange by name.\n meta_dex_lookup: ['network', 'name', 'address', 'pools'],\n}\n\nexport function isHiddenRemoteToolName(name: string): boolean {\n return HIDDEN_REMOTE_TOOL_NAMES.has(name)\n}\n\n/**\n * True for an MCP Apps tool only a view may call: `_meta.ui.visibility` is set\n * and does not include \"model\" (for example graph_expand, visibility [\"app\"]).\n * Such a tool never appears in a tool list built for the model or the CLI.\n */\nexport function isAppOnlyTool(tool: { _meta?: Record<string, unknown> }): boolean {\n const ui = tool._meta?.ui\n if (!ui || typeof ui !== 'object' || Array.isArray(ui)) return false\n const visibility = (ui as Record<string, unknown>).visibility\n return Array.isArray(visibility) && !visibility.includes('model')\n}\n\nexport function visibleRemoteTools<T extends { name: string; _meta?: Record<string, unknown> }>(\n tools: T[]\n): T[] {\n return tools.filter((tool) => !isHiddenRemoteToolName(tool.name) && !isAppOnlyTool(tool))\n}\n\nexport function assertPublicMcpToolName(name: string): void {\n if (!isHiddenRemoteToolName(name)) return\n const replacement =\n name === 'network_capabilities'\n ? ' Use meta_network_capabilities instead.'\n : name === 'usage_status'\n ? ' Use meta_usage_status instead.'\n : name === 'subscription_status'\n ? ' Use meta_subscription_status instead.'\n : name === 'balance'\n ? ' Use wallet_balance instead.'\n : name === 'help'\n ? ' Use meta_help instead.'\n : ''\n throw new Error(`MCP tool '${name}' is not exposed by Chain Insights.${replacement}`)\n}\n\nexport function formatMcpCallError(tool: string, err: unknown): string {\n // A tool error with an envelope is the server's own answer: its text, then the\n // line of its error_detail. It is never matched against the unknown-tool\n // pattern below. A tool error with no envelope keeps the old reading, because\n // a server can answer an unknown tool as an error reply.\n if (err instanceof McpToolError && err.errorDetail) return formatMcpToolError(err)\n const message = err instanceof Error ? err.message : String(err)\n if (/\\bunknown tool\\b|\\btool\\b.*\\bnot found\\b/i.test(message)) {\n return `Unknown MCP tool \"${tool}\". Run \\`cia mcp tools --refresh\\` to list available tools.`\n }\n return message\n}\n\nexport function validatePublicMcpToolArguments(name: string, args: Record<string, unknown>): void {\n const allowedArgs = PUBLIC_MCP_TOOL_ALLOWED_ARGS[name]\n if (!allowedArgs) return\n\n const unsupportedArgs = Object.keys(args).filter((argName) => !allowedArgs.includes(argName))\n if (unsupportedArgs.length === 0) return\n\n throw new Error(\n [\n `Unsupported argument${unsupportedArgs.length === 1 ? '' : 's'} for ${name}: ${unsupportedArgs.join(', ')}.`,\n `Allowed arguments: ${allowedArgs.join(', ')}.`,\n ].join(' ')\n )\n}\n"],"mappings":";;;;;;;;;;;;;;AAEA,MAAa,2CAA2B,IAAI,IAAI;CAC9C;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CAGA,CAAC,oBAAoB,QAAQ,CAAC,CAAC,KAAK,EAAE;CACtC,CAAC,qBAAqB,QAAQ,CAAC,CAAC,KAAK,EAAE;CACvC,CAAC,qBAAqB,UAAU,CAAC,CAAC,KAAK,EAAE;CACzC;CACA;CACA;CACA;CACA;CACA,CAAC,SAAS,0BAA0B,CAAC,CAAC,KAAK,EAAE;CAC7C;AACF,CAAC;AAED,MAAa,gCAA0D;CACrE,aAAa,CAAC,SAAS,SAAS;CAChC,mBAAmB,CAAC,WAAW,SAAS;AAC1C;AASA,MAAa,+BAAyD;CAEpE,aAAa;EAAC;EAAS;EAAW;CAAY;CAC9C,mBAAmB;EAAC;EAAW;EAAW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