chain-insights 0.78.0 → 0.80.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.
- package/README.md +3 -0
- package/dist/cli.cjs +72 -18
- package/dist/cli.mjs +72 -18
- package/dist/cli.mjs.map +1 -1
- package/dist/deployer-screen-BomgSBcq.cjs +446 -0
- package/dist/deployer-screen-ByQBZEsg.mjs +413 -0
- package/dist/deployer-screen-ByQBZEsg.mjs.map +1 -0
- package/dist/{dex-registry-sPTFuCrP.mjs → dex-registry-BY67f4Ul.mjs} +2 -2
- package/dist/{dex-registry-sPTFuCrP.mjs.map → dex-registry-BY67f4Ul.mjs.map} +1 -1
- package/dist/{dex-registry-DdXOg5On.cjs → dex-registry-BhGJUG9_.cjs} +36 -0
- package/dist/{dex-tool-CDmhhXfk.cjs → dex-tool-B6AymECb.cjs} +2 -2
- package/dist/{dex-tool-D61sIjpq.mjs → dex-tool-CjUZY19i.mjs} +3 -3
- package/dist/dex-tool-CjUZY19i.mjs.map +1 -0
- package/dist/exchange-deposit-check-CMGTPv-T.mjs +209 -0
- package/dist/exchange-deposit-check-CMGTPv-T.mjs.map +1 -0
- package/dist/exchange-deposit-check-hJGDHLz1.cjs +242 -0
- package/dist/exchange-registry-CT0rRW__.cjs +347 -0
- package/dist/exchange-registry-CoLgHw6d.mjs +319 -0
- package/dist/exchange-registry-CoLgHw6d.mjs.map +1 -0
- package/dist/exchange-tool-B2SMeC5f.cjs +218 -0
- package/dist/exchange-tool-Dc46SJ49.mjs +179 -0
- package/dist/exchange-tool-Dc46SJ49.mjs.map +1 -0
- package/dist/{graph-schema-D4LAefGf.mjs → graph-schema-B8KMeX75.mjs} +19 -3
- package/dist/{graph-schema-D4LAefGf.mjs.map → graph-schema-B8KMeX75.mjs.map} +1 -1
- package/dist/{graph-schema-C8Pi6r7c.cjs → graph-schema-D8rHCsBJ.cjs} +23 -1
- package/dist/mcp-proxy.cjs +78 -12
- package/dist/mcp-proxy.d.cts +1 -0
- package/dist/mcp-proxy.d.cts.map +1 -1
- package/dist/mcp-proxy.d.mts +1 -0
- package/dist/mcp-proxy.d.mts.map +1 -1
- package/dist/mcp-proxy.mjs +78 -13
- package/dist/mcp-proxy.mjs.map +1 -1
- package/dist/{public-tools-DXlZcanX.mjs → public-tools-CU1nukHW.mjs} +171 -10
- package/dist/public-tools-CU1nukHW.mjs.map +1 -0
- package/dist/{public-tools-Cfc1OPNS.cjs → public-tools-yvRiFSry.cjs} +170 -9
- package/dist/{token-lookup-DvgEyqcC.cjs → token-lookup-D-5GBEwF.cjs} +15 -2
- package/dist/{token-lookup-sH2DesLS.mjs → token-lookup-QpIv77P2.mjs} +5 -4
- package/dist/token-lookup-QpIv77P2.mjs.map +1 -0
- package/dist/{tool-visibility-DIpgPULN.cjs → tool-visibility-D8Up081E.cjs} +8 -1
- package/dist/{tool-visibility-Dy3psowS.mjs → tool-visibility-DuTds7V4.mjs} +9 -2
- package/dist/tool-visibility-DuTds7V4.mjs.map +1 -0
- package/docs/contributing.md +5 -2
- package/docs/development.md +5 -2
- package/docs/graph-query-compatibility.md +20 -4
- package/docs/graph-tools.md +22 -8
- package/docs/mcp-proxy.md +111 -5
- package/docs/stability.md +5 -2
- package/package.json +2 -2
- package/registry/README.md +42 -5
- package/registry/exchanges/ethereum.json +920 -0
- package/registry/exchanges/robinhood.json +87 -0
- package/registry/robinhood.json +7 -4
- package/registry/robinhood.md +9 -5
- package/skills/chain-insights-aml-exchange/SKILL.md +134 -0
- package/skills/chain-insights-aml-exchange/agents/openai.yaml +4 -0
- package/skills/chain-insights-cypher/SKILL.md +41 -11
- package/skills/chain-insights-dex/SKILL.md +3 -3
- package/skills/chain-insights-dex-gauge/SKILL.md +2 -0
- package/skills/chain-insights-dex-launchpad/SKILL.md +9 -10
- package/skills/chain-insights-dex-vault/SKILL.md +2 -0
- package/skills/chain-insights-virtuals/SKILL.md +1 -1
- package/dist/dex-tool-D61sIjpq.mjs.map +0 -1
- package/dist/public-tools-DXlZcanX.mjs.map +0 -1
- package/dist/token-lookup-sH2DesLS.mjs.map +0 -1
- package/dist/tool-visibility-Dy3psowS.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dex-tool-D61sIjpq.mjs","names":[],"sources":["../src/mcp/dex-recipes.ts","../src/mcp/dex-tool.ts"],"sourcesContent":["/**\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 =\n typeof rawAddress === 'string' && rawAddress.trim() !== '' ? rawAddress.trim() : null\n if (name !== null && addressText !== null)\n 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(\n (row) => address in row.roles || row.helpers?.includes(address)\n )\n match = {\n matched: holder ?? null,\n ...(holder ? { took_for: `${holder.roles[address] ?? 'helper'}, 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":";;;;;AAsBA,MAAa,eAA0C;CACrD,OAAO;CACP,OAAO;CACP,OAAO;CACP,WAAW;AACb;AAEA,MAAM,SAAS;AACf,MAAM,MAAM;AACZ,MAAM,KAAK;AACX,MAAM,QAAQ;;AAGd,SAAgB,oBAAoB,SAAiB,QAAQ,IAAY;CACvE,OACE,4CAA4C,QAAQ,8QAEV;AAE9C;;AAGA,SAAS,qBAAqB,MAAsB;CAClD,OACE,uEAAuE,KAAK;AAIhF;;AAGA,SAAS,yBAAyB,UAA0B;CAC1D,OACE,sEAAsE,SAAS;AAInF;;AAGA,SAAS,mBAA2B;CAClC,OACE,4CAA4C,OAAO;AAIvD;;AAGA,SAAS,cAAc,WAA2B;CAChD,OACE,yCAAyC,OAAO,sCAAsC,UAAU,4BAA4B,IAAI;AAGpI;;AAGA,SAAS,kBAAkB,QAAwB;CACjD,OACE,yCAAyC,OAAO,sDAAsD,IAAI,mBAAmB,GAAG;AAGpI;AAEA,MAAM,UAAsB;CAC1B,MAAM;CACN,KAAK;CACL,OACE;AACJ;;;;;AAMA,SAAS,UAAU,OAAiB,SAAuC;CACzE,OAAO,WAAW,MAAM,gBAAgB;AAC1C;AAEA,SAAS,UAAU,OAAoC;CACrD,MAAM,UAAU,MAAM,UAAU,MAAM,YAAY,MAAM,MAAM,aAAa,SAAS;CACpF,IAAI,CAAC,SAAS,OAAO;CACrB,OAAO;EACL,MAAM;EACN,KAAK,aAAa,MAAM,QAAQ,+DAA+D,MAAM,UAAU,QAAQ,MAAM,MAAM,MAAM,OAAO,SAAS,CAAC,CAAC,KAAK,IAAI,EAAE;EACtK,OAAO,oBAAoB,OAAO;CACpC;AACF;;AAGA,SAAgB,UAAU,OAAiB,SAAsC;CAC/E,MAAM,OAAO,UAAU,OAAO,OAA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AAK;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":"public-tools-DXlZcanX.mjs","names":["isRecord","numberValue"],"sources":["../src/investigation/graph-normalizer.ts","../src/investigation/risk-level.ts","../src/workspace/output-root.ts","../src/lib/usage-accumulator.ts","../src/investigation/public-tools.ts"],"sourcesContent":["const GRAPH_TYPE_LABELS = new Set([\n 'Address',\n 'Exchange',\n 'Miner',\n 'Validator',\n 'Hotkey',\n 'Subnet',\n 'IPAddress',\n])\nconst FLOW_EDGE_TYPES = new Set(['flowed_to', 'transfer', 'transfer_to', 'transfers_to'])\n\ntype GraphRecord = Record<string, unknown>\n\nexport type NormalizedGraphPayload = {\n schema: 'chain-insights.graph.v1'\n nodes: GraphRecord[]\n edges: GraphRecord[]\n flows: unknown[]\n edge_anchors: unknown[]\n [key: string]: unknown\n}\n\nfunction isRecord(value: unknown): value is GraphRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.map(String).filter(Boolean) : []\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values)]\n}\n\nfunction lowerSnake(value: string): string {\n return value\n .trim()\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .replace(/^_+|_+$/g, '')\n .toLowerCase()\n}\n\nfunction isGraphTypeLabel(label: string): boolean {\n return GRAPH_TYPE_LABELS.has(label)\n}\n\nfunction displayLabels(node: GraphRecord): string[] {\n return unique(stringArray(node['labels'])).filter((label) => !isGraphTypeLabel(label))\n}\n\nfunction systemLabels(node: GraphRecord): string[] {\n return unique([\n ...stringArray(node['system_labels']),\n ...stringArray(node['graph_labels']),\n ...stringArray(node['raw_labels']),\n ...stringArray(node['labels']).filter(isGraphTypeLabel),\n ])\n}\n\nfunction normalizeRoles(node: GraphRecord): string[] {\n const roles = stringArray(node['roles'])\n const role = typeof node['role'] === 'string' ? node['role'] : ''\n if (role === 'source_exchange') roles.push('exchange')\n else if (role) roles.push(role)\n\n const display = stringArray(node['labels']).map(lowerSnake)\n if (\n systemLabels(node).some((label) => lowerSnake(label) === 'exchange') ||\n display.includes('exchange')\n ) {\n roles.push('exchange')\n }\n\n return unique(roles.map(lowerSnake).filter(Boolean))\n}\n\nfunction normalizeNodeType(node: GraphRecord): string {\n if (typeof node['node_type'] === 'string' && node['node_type'].trim()) {\n return lowerSnake(node['node_type'])\n }\n if (typeof node['address'] === 'string' || typeof node['id'] === 'string') return 'address'\n const labels = systemLabels(node)\n if (labels.length > 0) return lowerSnake(labels[0]!)\n return 'unknown'\n}\n\nfunction normalizeNode(node: unknown): GraphRecord {\n if (!isRecord(node)) return {}\n\n const normalized: GraphRecord = {}\n for (const [key, value] of Object.entries(node)) {\n if (\n [\n 'address_subtypes',\n 'entity_kind',\n 'graph_labels',\n 'labels',\n 'node_type',\n 'pattern_flags',\n 'raw_labels',\n 'role',\n 'roles',\n 'system_labels',\n 'type',\n ].includes(key)\n ) {\n continue\n }\n normalized[key] = value\n }\n\n const id =\n typeof node['id'] === 'string'\n ? node['id']\n : typeof node['address'] === 'string'\n ? node['address']\n : undefined\n if (id) normalized['id'] = id\n\n const address = typeof node['address'] === 'string' ? node['address'] : id\n if (address) normalized['address'] = address\n\n normalized['node_type'] = normalizeNodeType(node)\n normalized['labels'] = displayLabels(node)\n\n const addressSubtypes = unique(stringArray(node['address_subtypes']))\n if (addressSubtypes.length > 0) normalized['address_subtypes'] = addressSubtypes\n\n const roles = normalizeRoles(node)\n if (roles.length > 0) normalized['roles'] = roles\n\n if (\n !Array.isArray(node['flags']) &&\n Array.isArray(node['pattern_flags']) &&\n node['pattern_flags'].length > 0\n ) {\n normalized['flags'] = node['pattern_flags'].map(String)\n }\n\n return normalized\n}\n\nfunction normalizeEdgeType(edge: GraphRecord): string {\n const rawType =\n typeof edge['edge_type'] === 'string' && edge['edge_type'].trim()\n ? edge['edge_type']\n : typeof edge['type'] === 'string' && edge['type'].trim()\n ? edge['type']\n : typeof edge['relationship_type'] === 'string' && edge['relationship_type'].trim()\n ? edge['relationship_type']\n : 'related_to'\n const edgeType = lowerSnake(rawType)\n return FLOW_EDGE_TYPES.has(edgeType) ? 'flowed_to' : edgeType\n}\n\nfunction normalizeEdge(edge: unknown): GraphRecord {\n if (!isRecord(edge)) return {}\n\n const normalized: GraphRecord = {}\n for (const [key, value] of Object.entries(edge)) {\n if (['edge_type', 'from_address', 'relationship_type', 'to_address', 'type'].includes(key))\n continue\n normalized[key] = value\n }\n\n if (typeof normalized['source'] !== 'string' && typeof edge['from_address'] === 'string') {\n normalized['source'] = edge['from_address']\n }\n if (typeof normalized['target'] !== 'string' && typeof edge['to_address'] === 'string') {\n normalized['target'] = edge['to_address']\n }\n normalized['edge_type'] = normalizeEdgeType(edge)\n\n return normalized\n}\n\nexport function normalizeGraphPayload(payload: unknown): NormalizedGraphPayload {\n if (!isRecord(payload) || payload['schema'] !== 'chain-insights.graph.v1') {\n throw new Error('Unsupported graph payload schema')\n }\n\n return {\n ...payload,\n schema: 'chain-insights.graph.v1',\n nodes: Array.isArray(payload['nodes']) ? payload['nodes'].map(normalizeNode) : [],\n edges: Array.isArray(payload['edges']) ? payload['edges'].map(normalizeEdge) : [],\n flows: Array.isArray(payload['flows']) ? payload['flows'] : [],\n edge_anchors: Array.isArray(payload['edge_anchors']) ? payload['edge_anchors'] : [],\n }\n}\n","/**\n * Risk-level normalization shared by the AML tools and graph payload builders.\n *\n * The Chain Insights Graph serves the ML verdict verbatim, which historically\n * mixed cases (HIGH vs high) and — since the calibrated-scoring release —\n * includes an explicit abstention band: risk_level = UNSCORED means the model\n * had too little labeled graph context to stand behind a band. UNSCORED is a\n * \"no stance\" state and must never be rendered or reasoned about as low risk.\n */\n\nexport const RISK_SEVERITIES = ['low', 'medium', 'high', 'critical'] as const\nexport const UNSCORED_RISK_LEVEL = 'unscored'\n\n/** Lowercased, trimmed risk level; undefined for empty/unrecognized values. */\nexport function normalizeRiskLevel(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const normalized = value.trim().toLowerCase()\n if (!normalized) return undefined\n if (normalized === UNSCORED_RISK_LEVEL) return UNSCORED_RISK_LEVEL\n if ((RISK_SEVERITIES as readonly string[]).includes(normalized)) return normalized\n return undefined\n}\n\n/** True when the ML verdict explicitly abstained (no stance, not low). */\nexport function isUnscoredRiskLevel(value: unknown): boolean {\n return normalizeRiskLevel(value) === UNSCORED_RISK_LEVEL\n}\n\n/**\n * Severity ordering for comparisons: low(0) < medium(1) < high(2) <\n * critical(3). Unknown/unscored values rank -1 — they never win a\n * severity comparison, they abstain from it.\n */\nexport function riskSeverityRank(value: unknown): number {\n const normalized = normalizeRiskLevel(value)\n if (!normalized || normalized === UNSCORED_RISK_LEVEL) return -1\n return (RISK_SEVERITIES as readonly string[]).indexOf(normalized)\n}\n","import path from 'node:path'\nimport { findActiveWorkspace } from './active.js'\n\nexport const NO_WORKSPACE_ERROR = 'No Chain Insights workspace found. Run: cia init .'\n\nexport interface WorkspaceOutputPaths {\n root: string\n metadataDir: string\n schemaDir: string\n runtimeDir: string\n artifactsRoot: string\n entitiesRoot: string\n sessionsRoot: string\n publishedRoot: string\n reportsRoot: string\n reportGraphsRoot: string\n reportTablesRoot: string\n logsRoot: string\n}\n\nexport function requireWorkspaceRoot(startDir = process.cwd()): string {\n const workspace = findActiveWorkspace(startDir)\n if (!workspace) throw new Error(NO_WORKSPACE_ERROR)\n return workspace.root\n}\n\nexport function workspaceOutputPaths(workspaceRoot = requireWorkspaceRoot()): WorkspaceOutputPaths {\n const root = path.resolve(workspaceRoot)\n return {\n root,\n metadataDir: path.join(root, '.chain-insights'),\n schemaDir: path.join(root, '.chain-insights', 'schema'),\n runtimeDir: path.join(root, '.chain-insights', 'runtime'),\n artifactsRoot: path.join(root, 'artifacts'),\n entitiesRoot: path.join(root, 'entities'),\n sessionsRoot: path.join(root, 'sessions'),\n publishedRoot: path.join(root, 'published'),\n reportsRoot: path.join(root, 'reports'),\n reportGraphsRoot: path.join(root, 'reports', 'graphs'),\n reportTablesRoot: path.join(root, 'reports', 'tables'),\n logsRoot: path.join(root, '.chain-insights', 'runtime', 'logs'),\n }\n}\n","/**\n * Per-workflow billable-units accounting for the aml_* tools (internal feature:\n * usage-units-propagation). The `aml_*` workflow tools make MANY internal\n * graph_query_batch round trips to answer one high-level question; this\n * module totals what those round trips billed so the workflow response can\n * report a single `usage` block instead of exposing nothing at all.\n *\n * Capture point: aml_address_risk (and internal graph_query_batch helper\n * calls feeding its enrichment) wraps its `remoteClient` once via\n * `wrapClientForUsageTracking` before making any internal calls, then reads\n * the shared `UsageTotals` back out when building its response. Every\n * internal helper (callGraphBatch, probeSeedAddresses, ...) keeps calling\n * `client.callTool(...)` exactly as before -- the wrapper observes\n * graph_query_batch/graph_query responses in transit and never changes their\n * return value.\n *\n * Defensive by design: a backend that does not yet emit billing fields (or\n * an unparsable response) contributes 0 units but the call still counts\n * toward `query_count` -- this must never throw and never block a workflow.\n */\n\ninterface CallToolLike {\n callTool(...args: unknown[]): Promise<unknown>\n}\n\nexport interface UsageTotals {\n billable_units: number\n query_count: number\n truncated_queries: number\n}\n\nexport function createUsageAccumulator(): UsageTotals {\n return { billable_units: 0, query_count: 0, truncated_queries: 0 }\n}\n\n// Snapshot as a plain object for embedding in a response -- callers should\n// not hand out the live mutable accumulator.\nexport function usageBlock(totals: UsageTotals): UsageTotals {\n return {\n billable_units: totals.billable_units,\n query_count: totals.query_count,\n truncated_queries: totals.truncated_queries,\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction numberValue(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim()) {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n}\n\nfunction textOfToolResult(result: unknown): string {\n if (!isRecord(result)) return ''\n const content = result['content']\n if (!Array.isArray(content)) return ''\n return content\n .filter(\n (item): item is { type: 'text'; text: string } =>\n isRecord(item) && item['type'] === 'text' && typeof item['text'] === 'string'\n )\n .map((item) => item.text)\n .join('\\n')\n}\n\n// facts.query.* is the single-query shape (graph_query). facts.batch.* /\n// facts.queries[] is the batch shape (graph_query_batch). Both are read\n// defensively -- missing/malformed fields never throw, they just contribute\n// nothing to the total.\nfunction accumulateFacts(totals: UsageTotals, facts: unknown): void {\n if (!isRecord(facts)) return\n\n const query = facts['query']\n if (isRecord(query)) {\n const units = numberValue(query['billable_units'])\n if (units !== undefined) totals.billable_units += units\n if (query['truncated'] === true) totals.truncated_queries += 1\n }\n\n const batch = facts['batch']\n const batchUnits = isRecord(batch) ? numberValue(batch['billable_units']) : undefined\n const queries = Array.isArray(facts['queries'])\n ? (facts['queries'] as unknown[]).filter(isRecord)\n : undefined\n\n if (batchUnits !== undefined) {\n totals.billable_units += batchUnits\n } else if (queries) {\n // No batch-level total (older/mocked backend): fall back to summing\n // whatever per-query billable_units are present. Entries with no field\n // contribute 0, same as the single-query defensive path.\n for (const entry of queries) {\n const units = numberValue(entry['billable_units'])\n if (units !== undefined) totals.billable_units += units\n }\n }\n\n if (queries) {\n for (const entry of queries) {\n if (entry['truncated'] === true) totals.truncated_queries += 1\n }\n } else if (isRecord(batch) && batch['truncated'] === true) {\n totals.truncated_queries += 1\n }\n}\n\n// One graph_query_batch round trip is one query_count unit per Cypher\n// statement it carried (facts.queries.length) -- that is what \"one internal\n// graph query\" means for this tool. A round trip whose response could not be\n// attributed to individual statements (parse failure, missing facts.queries)\n// still represents one internal graph query having been issued, so it counts\n// as 1 rather than 0.\nfunction recordGraphQueryBatchResult(totals: UsageTotals, rawResult: unknown): void {\n let facts: unknown\n try {\n const text = textOfToolResult(rawResult).trim()\n if (text) facts = (JSON.parse(text) as { facts?: unknown }).facts\n else if (\n isRecord(rawResult) &&\n isRecord((rawResult as Record<string, unknown>)['structuredContent'])\n ) {\n facts = (\n (rawResult as Record<string, unknown>)['structuredContent'] as Record<string, unknown>\n )['facts']\n }\n } catch {\n facts = undefined\n }\n\n const queries =\n isRecord(facts) && Array.isArray(facts['queries']) ? (facts['queries'] as unknown[]) : undefined\n totals.query_count += queries ? queries.length : 1\n accumulateFacts(totals, facts)\n}\n\n// One graph_query round trip is exactly one internal graph query.\nfunction recordGraphQueryResult(totals: UsageTotals, rawResult: unknown): void {\n totals.query_count += 1\n let facts: unknown\n try {\n if (\n isRecord(rawResult) &&\n isRecord((rawResult as Record<string, unknown>)['structuredContent'])\n ) {\n facts = (\n (rawResult as Record<string, unknown>)['structuredContent'] as Record<string, unknown>\n )['facts']\n } else {\n const text = textOfToolResult(rawResult).trim()\n if (text) facts = (JSON.parse(text) as { facts?: unknown }).facts\n }\n } catch {\n facts = undefined\n }\n accumulateFacts(totals, facts)\n}\n\n// Wraps a Client-shaped object (real MCP SDK Client or a test double) so\n// every graph_query_batch/graph_query call it makes is observed and totaled\n// into `totals`, without changing what the call returns. Any other method\n// or property passes through untouched.\nexport function wrapClientForUsageTracking<T extends CallToolLike>(\n client: T,\n totals: UsageTotals\n): T {\n return new Proxy(client as object, {\n get(target, prop, receiver) {\n if (prop === 'callTool') {\n return async (...args: unknown[]) => {\n const result = await (target as CallToolLike).callTool(...args)\n const request = args[0]\n const toolName =\n isRecord(request) && typeof request['name'] === 'string' ? request['name'] : undefined\n if (toolName === 'graph_query_batch') {\n recordGraphQueryBatchResult(totals, result)\n } else if (toolName === 'graph_query') {\n recordGraphQueryResult(totals, result)\n }\n return result\n }\n }\n const value = Reflect.get(target, prop, target)\n return typeof value === 'function' ? value.bind(target) : value\n },\n }) as T\n}\n","import { mkdir, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport type { ContentBlock } from '@modelcontextprotocol/sdk/types.js'\nimport { normalizeGraphPayload } from './graph-normalizer.js'\nimport { isUnscoredRiskLevel, normalizeRiskLevel, riskSeverityRank } from './risk-level.js'\nimport { workspaceOutputPaths } from '../workspace/output-root.js'\nimport { GRAPH_TOOL_REQUEST_TIMEOUT_MS } from '../mcp/request-timeout.js'\nimport {\n createUsageAccumulator,\n usageBlock,\n wrapClientForUsageTracking,\n} from '../lib/usage-accumulator.js'\n\nexport { buildTruthProposal, resolveTruthIngressTlsPaths } from './truth-proposal.js'\nexport type { TruthProposalCommand } from './truth-proposal.js'\n\ntype RemoteToolResult = {\n content?: ContentBlock[]\n isError?: boolean\n}\n\ninterface ParsedGraphBatch {\n facts?: {\n queries?: Array<{\n id?: string\n ok?: boolean\n results?: Array<Record<string, unknown>>\n error?: string\n }>\n }\n}\n\ntype QueryFailure = {\n id: string\n error: string\n}\n\nexport interface AddressRiskOptions {\n address: string\n network: string\n compareAddress?: string\n writeArtifacts?: boolean\n}\n\nconst AML_ADDRESS_RISK_SUPPORTED_VERSIONS = ['v1'] as const\nexport type AmlAddressRiskVersion = (typeof AML_ADDRESS_RISK_SUPPORTED_VERSIONS)[number]\nexport const LATEST_AML_ADDRESS_RISK_VERSION: AmlAddressRiskVersion = 'v1'\n\nexport function resolveAmlAddressRiskVersion(requested?: string): AmlAddressRiskVersion {\n const normalized = requested?.trim().toLowerCase()\n if (!normalized) return LATEST_AML_ADDRESS_RISK_VERSION\n if (\n AML_ADDRESS_RISK_SUPPORTED_VERSIONS.includes(\n normalized as (typeof AML_ADDRESS_RISK_SUPPORTED_VERSIONS)[number]\n )\n ) {\n return normalized as AmlAddressRiskVersion\n }\n throw new Error(\n `Unsupported aml_address_risk version \"${requested?.trim() ?? ''}\". Supported versions: ${AML_ADDRESS_RISK_SUPPORTED_VERSIONS.join(', ')}.`\n )\n}\n\nfunction escapeCypherString(value: string): string {\n return value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')\n}\n\nfunction textFromToolResult(result: RemoteToolResult): string {\n return (result.content ?? [])\n .filter((item): item is Extract<ContentBlock, { type: 'text' }> => item.type === 'text')\n .map((item) => item.text)\n .join('\\n')\n}\n\nfunction parseGraphBatchResult(result: RemoteToolResult): ParsedGraphBatch {\n const text = textFromToolResult(result).trim()\n if (!text) throw new Error('graph_query_batch returned no text content')\n const parsed = JSON.parse(text) as ParsedGraphBatch\n if (!parsed.facts?.queries)\n throw new Error('graph_query_batch response did not include facts.queries')\n return parsed\n}\n\nfunction topologyGraphQuery(query: string): string {\n const trimmed = query.trim()\n if (/^USE\\s+/i.test(trimmed)) return trimmed\n return `USE topology ${trimmed}`\n}\n\nfunction collectQueryFailure(\n failures: QueryFailure[],\n id: string,\n error: string | undefined\n): void {\n failures.push({ id, error: error || 'unknown error' })\n}\n\nfunction optionalResultsFor(\n batch: ParsedGraphBatch,\n id: string,\n failures: QueryFailure[]\n): Array<Record<string, unknown>> {\n const query = batch.facts?.queries?.find((entry) => entry.id === id)\n if (!query) return []\n if (query.ok === false) {\n collectQueryFailure(failures, id, query.error)\n return []\n }\n return query.results ?? []\n}\n\nfunction optionalResultsWithPrefix(\n batch: ParsedGraphBatch,\n prefix: string,\n failures: QueryFailure[]\n): Array<Record<string, unknown>> {\n return (batch.facts?.queries ?? [])\n .filter((entry) => entry.id?.startsWith(prefix))\n .flatMap((entry) => {\n if (entry.ok === false) {\n collectQueryFailure(failures, entry.id ?? prefix, entry.error)\n return []\n }\n return entry.results ?? []\n })\n}\n\nasync function callGraphBatch(\n remoteClient: Client,\n network: string,\n queries: Array<{ id: string; query: string }>\n): Promise<ParsedGraphBatch> {\n const result = (await remoteClient.callTool(\n {\n name: 'graph_query_batch',\n arguments: {\n network,\n queries: queries.map((query) => ({\n ...query,\n query: topologyGraphQuery(query.query),\n })),\n },\n },\n undefined,\n {\n timeout: GRAPH_TOOL_REQUEST_TIMEOUT_MS,\n maxTotalTimeout: GRAPH_TOOL_REQUEST_TIMEOUT_MS,\n }\n )) as RemoteToolResult\n if (result.isError) throw new Error(textFromToolResult(result) || 'graph_query_batch failed')\n return parseGraphBatchResult(result)\n}\n\nfunction addressProfileQuery(address: string): { id: string; query: string } {\n // risk_score/risk_level are always projected: topology is now the only ML\n // risk source (the retired facts_risk_scores_view never had a risk_level\n // column, so UNSCORED abstention was invisible until this move).\n const riskFields = ', a.risk_score AS live_risk_score, a.risk_level AS live_risk_level'\n // Per-label risk is the overlay graphsync materializes on the node, one\n // entry per current label row. DozerDB properties cannot hold a list of\n // maps, so it is three parallel lists: label_risk_labels, label_risk_levels\n // and label_risk_updated_timestamps. deriveLabelRows zips them back.\n // Missing/empty is \"no label-risk signal,\" never an error.\n const labelRiskFields =\n ', a.label_risk_labels AS label_risk_labels, a.label_risk_levels AS label_risk_levels, a.label_risk_updated_timestamps AS label_risk_updated_timestamps'\n return {\n id: 'address_profile',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})`,\n `RETURN a.address AS address, a.network AS network, a.labels AS display_labels, a.labels AS system_labels, a.is_exchange AS is_exchange${riskFields}${labelRiskFields}`,\n 'LIMIT 1',\n ].join(' '),\n }\n}\n\n// Lifetime address features are materialized on the one USE topology node.\nfunction addressFeatureQuery(address: string): { id: string; query: string } {\n return {\n id: 'address_feature',\n query: [\n 'USE topology',\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})`,\n 'RETURN a.degree_in AS degree_in, a.degree_out AS degree_out, a.degree_total AS degree_total, a.tx_in_count AS tx_in_count, a.tx_out_count AS tx_out_count, a.tx_total_count AS tx_total_count, a.total_volume_usd AS total_volume_usd, a.total_in_usd AS total_in_usd, a.total_out_usd AS total_out_usd, a.net_flow_usd AS net_flow_usd, a.first_activity_timestamp AS first_activity_timestamp, a.last_activity_timestamp AS last_activity_timestamp, a.activity_span_days AS activity_span_days',\n 'LIMIT 1',\n ].join(' '),\n }\n}\n\nfunction flowEdgeMap(variableName: string): string {\n return `{amount_usd_sum: ${variableName}.amount_usd_sum, tx_count: ${variableName}.tx_count, first_seen_timestamp: ${variableName}.first_seen_timestamp, last_seen_timestamp: ${variableName}.last_seen_timestamp}`\n}\n\nfunction pathNodeMap(variableName: string): string {\n // risk_score/risk_level are always projected on topology nodes.\n const riskFields = `, risk_score: ${variableName}.risk_score, risk_level: ${variableName}.risk_level`\n return `{address: ${variableName}.address, network: ${variableName}.network, labels: ${variableName}.labels, system_labels: ${variableName}.labels, is_exchange: ${variableName}.is_exchange${riskFields}}`\n}\n\n// money-trail enrichment: incident MONEY_TRAIL edges on the subject address\n// (either direction), and the TRAIL_ENDS_AT fan-out of whichever seed\n// generated the trail -- both are optional-results reads, so a graph with no\n// money-trail layer (or a failed query) never fails aml_address_risk itself.\nexport function moneyTrailIncidentQuery(address: string): string {\n return [\n 'USE topology',\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[r:MONEY_TRAIL]-()`,\n 'RETURN r.edge_class AS edge_class, r.value AS value, r.min_hop AS min_hop, r.seed_count AS seed_count, r.primary_seed AS primary_seed, r.generation AS generation, r.network AS network, r.first_ts AS first_ts, r.last_ts AS last_ts',\n 'LIMIT 200',\n ].join(' ')\n}\n\nexport function moneyTrailEndsQuery(seed: string): string {\n return [\n 'USE topology',\n `MATCH (s:Address {address: \"${escapeCypherString(seed)}\"})-[r:TRAIL_ENDS_AT]->(t:Address)`,\n 'RETURN t.address AS address, r.fact_type AS fact_type, r.direction AS direction, r.terminal_role AS terminal_role, r.hop AS hop, r.value AS value, r.generation AS generation',\n 'LIMIT 200',\n ].join(' ')\n}\n\n// Task 2 (trace fast path): a resolved trace target IS a money-trail seed\n// when it has outgoing TRAIL_ENDS_AT edges -- same shape as\n// moneyTrailEndsQuery, reused here under a probe-specific name so the\n// trace-tool call site reads as \"check whether this address is a seed\"\n// rather than \"fetch the ends fan of a known seed\" (they happen to be the\n// same read).\nexport function moneyTrailSeedProbeQuery(address: string): string {\n return moneyTrailEndsQuery(address)\n}\n\n// Precomputed MONEY_TRAIL corridor from a confirmed seed: bounded to 6 hops\n// (min_hop is a property baked onto the edge by the walk engine, not a\n// variable-length path depth) and excludes peripheral-only continuation --\n// peripheral is the \"touched funds\" floor (see MONEY_TRAIL_CLASS_RANK), not\n// a real trail hop, so it never extends the fast-path corridor.\nexport function moneyTrailCorridorQuery(seed: string): string {\n return [\n 'USE topology',\n `MATCH (s:Address {address: \"${escapeCypherString(seed)}\"})-[r:MONEY_TRAIL]->(t:Address)`,\n 'WHERE r.min_hop <= 6 AND r.edge_class <> \"peripheral\"',\n 'RETURN t.address AS address, r.edge_class AS edge_class, r.value AS value, r.min_hop AS min_hop, r.seed_count AS seed_count, r.primary_seed AS primary_seed, r.generation AS generation, r.network AS network',\n 'ORDER BY r.min_hop ASC',\n 'LIMIT 200',\n ].join(' ')\n}\n\nexport interface MoneyTrailBlock {\n on_trail: true\n class: string\n min_hop: number\n primary_seed: string\n generation: number\n nearest_trail_end?: { address: string; fact_type: string; value: string }\n}\n\nconst MONEY_TRAIL_CLASS_RANK: Record<string, number> = { transport: 3, holding: 2, peripheral: 1 }\n\nexport function buildMoneyTrailBlock(\n incidentRows: Array<Record<string, unknown>>,\n endRows: Array<Record<string, unknown>>\n): MoneyTrailBlock | undefined {\n if (incidentRows.length === 0) return undefined\n\n const winningClassRank = Math.max(\n ...incidentRows.map((row) => MONEY_TRAIL_CLASS_RANK[firstString(row['edge_class']) ?? ''] ?? 0)\n )\n const winningClass =\n Object.entries(MONEY_TRAIL_CLASS_RANK).find(([, rank]) => rank === winningClassRank)?.[0] ??\n firstString(incidentRows[0]?.['edge_class']) ??\n 'peripheral'\n const rowsOfWinningClass = incidentRows.filter(\n (row) => firstString(row['edge_class']) === winningClass\n )\n const bestRow = rowsOfWinningClass.reduce((best, row) => {\n const rowHop = numberValue(row['min_hop']) ?? Number.POSITIVE_INFINITY\n const bestHop = numberValue(best['min_hop']) ?? Number.POSITIVE_INFINITY\n return rowHop < bestHop ? row : best\n }, rowsOfWinningClass[0]!)\n\n const nearestEnd = endRows.reduce<Record<string, unknown> | undefined>((best, row) => {\n const rowValue = numberValue(row['value']) ?? Number.NEGATIVE_INFINITY\n const bestValue = best\n ? (numberValue(best['value']) ?? Number.NEGATIVE_INFINITY)\n : Number.NEGATIVE_INFINITY\n return !best || rowValue > bestValue ? row : best\n }, undefined)\n\n return {\n on_trail: true,\n class: winningClass,\n min_hop: numberValue(bestRow['min_hop']) ?? 0,\n primary_seed: firstString(bestRow['primary_seed']) ?? '',\n generation: numberValue(bestRow['generation']) ?? 0,\n ...(nearestEnd\n ? {\n nearest_trail_end: {\n address: firstString(nearestEnd['address']) ?? '',\n fact_type: firstString(nearestEnd['fact_type']) ?? '',\n value: String(nearestEnd['value'] ?? ''),\n },\n }\n : {}),\n }\n}\n\nexport function moneyTrailSummarySentence(block: MoneyTrailBlock): string {\n return block.class === 'peripheral'\n ? `This address touched money-trail funds (${block.class}, min hop ${block.min_hop}).`\n : `This address sits on a money trail (${block.class}, min hop ${block.min_hop}).`\n}\n\n// Pool guard (cypher skill, \"Pool trace rule\"): a FLOWED_TO walk never starts\n// at a :Pool and never passes through one, and each guard is its own AND term\n// (inside an OR it would guard nothing). Fixed-hop form of\n// skills/chain-insights-cypher: `WHERE NOT src:Pool AND NOT mid:Pool`.\nfunction poolGuardTerms(nodeVariables: string[]): string {\n return nodeVariables.map((nodeVariable) => `NOT ${nodeVariable}:Pool`).join(' AND ')\n}\n\n// System guard (cypher skill, \"Pool trace rule\"): a walk of two or more hops\n// also never starts at, and never passes through, a :Protocol contract (such\n// as a PoolManager) or a system address. Each links millions of unrelated\n// wallets, so a route through one connects nothing. One hop needs no guard:\n// the links of such an address are facts.\nexport const SYSTEM_ADDRESSES = [\n '0x0000000000000000000000000000000000000000',\n '0x000000000000000000000000000000000000dead',\n] as const\nconst SYSTEM_ADDRESS_LIST = `[${SYSTEM_ADDRESSES.map((address) => `\"${address}\"`).join(', ')}]`\n\nfunction systemGuardTerms(nodeVariables: string[]): string {\n return nodeVariables\n .map(\n (nodeVariable) =>\n `NOT ${nodeVariable}:Protocol AND NOT ${nodeVariable}:System AND NOT ${nodeVariable}.address IN ${SYSTEM_ADDRESS_LIST}`\n )\n .join(' AND ')\n}\n\n// The guard of every address a walk leaves: the pool guard, and on a walk of\n// two or more hops the system guard after it.\nfunction walkGuardTerms(nodeVariables: string[], hops: number): string {\n return hops > 1\n ? nodeVariables\n .map(\n (nodeVariable) =>\n `${poolGuardTerms([nodeVariable])} AND ${systemGuardTerms([nodeVariable])}`\n )\n .join(' AND ')\n : poolGuardTerms(nodeVariables)\n}\n\nfunction exchangeOutflowQueries(address: string): Array<{ id: string; query: string }> {\n return Array.from({ length: 3 }, (_, index) => exchangeOutflowQueryAtDepth(address, index + 1))\n}\n\nfunction exchangeOutflowQueryAtDepth(\n address: string,\n depth: number\n): { id: string; query: string } {\n const intermediateVariables = Array.from(\n { length: Math.max(depth - 1, 0) },\n (_, index) => `n${index + 1}`\n )\n const nodeVariables = ['a', ...intermediateVariables, 'exchange']\n const edgeVariables = Array.from({ length: depth }, (_, index) => `r${index + 1}`)\n const relationshipChain = edgeVariables\n .map((edgeVariable, index) => {\n const targetVariable =\n index === edgeVariables.length - 1 ? 'exchange' : intermediateVariables[index]!\n return `-[${edgeVariable}:FLOWED_TO]->(${targetVariable}:Address)`\n })\n .join('')\n const intermediatePredicates = intermediateVariables.map(\n (nodeVariable) => `${nodeVariable}.is_exchange IS NULL`\n )\n // Pool trace rule: the walk starts at the screened address and passes\n // through the intermediates, so none of them may be a :Pool, and on two or\n // more hops none a :Protocol or a system address. The exchange end is the\n // target, which may be one.\n const poolGuards = walkGuardTerms(['a', ...intermediateVariables], depth)\n const depositVariable = nodeVariables[nodeVariables.length - 2]!\n const terminalEdgeVariable = edgeVariables[edgeVariables.length - 1]!\n return {\n id: `exchange_outflows_${depth}`,\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})${relationshipChain}`,\n `WHERE a.address <> exchange.address AND exchange.is_exchange IS NOT NULL${intermediatePredicates.length > 0 ? ` AND ${intermediatePredicates.join(' AND ')}` : ''} AND ${poolGuards}`,\n `RETURN \"outflow\" AS direction, exchange.address AS exchange_address, exchange.labels AS exchange_display_labels, exchange.labels AS exchange_system_labels, ${depositVariable}.address AS deposit_address, ${depth} AS hops, ${terminalEdgeVariable}.amount_usd_sum AS amount_usd_sum, ${terminalEdgeVariable}.tx_count AS tx_count, ${terminalEdgeVariable}.first_seen_timestamp AS first_seen_timestamp, ${terminalEdgeVariable}.last_seen_timestamp AS last_seen_timestamp, [${nodeVariables.map((nodeVariable) => `${nodeVariable}.address`).join(', ')}] AS addresses, [${nodeVariables.map((nodeVariable) => pathNodeMap(nodeVariable)).join(', ')}] AS path_nodes, [${edgeVariables.map(flowEdgeMap).join(', ')}] AS edge_props`,\n 'ORDER BY hops ASC',\n 'LIMIT 200',\n ].join(' '),\n }\n}\n\nfunction exchangeInflowQueries(address: string): Array<{ id: string; query: string }> {\n return Array.from({ length: 3 }, (_, index) => exchangeInflowQueryAtDepth(address, index + 1))\n}\n\nfunction exchangeInflowQueryAtDepth(address: string, depth: number): { id: string; query: string } {\n const intermediateVariables = Array.from(\n { length: Math.max(depth - 1, 0) },\n (_, index) => `n${index + 1}`\n )\n const nodeVariables = ['exchange', ...intermediateVariables, 'a']\n const edgeVariables = Array.from({ length: depth }, (_, index) => `r${index + 1}`)\n const relationshipChain = edgeVariables\n .map((edgeVariable, index) => {\n const targetVariable =\n index === edgeVariables.length - 1 ? 'a' : intermediateVariables[index]!\n return `-[${edgeVariable}:FLOWED_TO]->(${targetVariable}:Address)`\n })\n .join('')\n const intermediatePredicates = intermediateVariables.map(\n (nodeVariable) => `${nodeVariable}.is_exchange IS NULL`\n )\n // Pool trace rule: the trace starts at the screened address `a` and walks\n // back through the intermediates, so none of them may be a :Pool, and on\n // two or more hops none a :Protocol or a system address. The exchange end\n // is the target, which may be one.\n const poolGuards = walkGuardTerms(['a', ...intermediateVariables], depth)\n const withdrawalVariable = nodeVariables[1]!\n const terminalEdgeVariable = edgeVariables[edgeVariables.length - 1]!\n return {\n id: `exchange_inflows_${depth}`,\n query: [\n `MATCH (exchange:Address)${relationshipChain}`,\n `WHERE a.address = \"${escapeCypherString(address)}\" AND a.address <> exchange.address AND exchange.is_exchange IS NOT NULL${intermediatePredicates.length > 0 ? ` AND ${intermediatePredicates.join(' AND ')}` : ''} AND ${poolGuards}`,\n `RETURN \"inflow\" AS direction, exchange.address AS exchange_address, exchange.labels AS exchange_display_labels, exchange.labels AS exchange_system_labels, ${withdrawalVariable}.address AS withdrawal_address, ${depth} AS hops, ${terminalEdgeVariable}.amount_usd_sum AS amount_usd_sum, ${terminalEdgeVariable}.tx_count AS tx_count, ${terminalEdgeVariable}.first_seen_timestamp AS first_seen_timestamp, ${terminalEdgeVariable}.last_seen_timestamp AS last_seen_timestamp, [${nodeVariables.map((nodeVariable) => `${nodeVariable}.address`).join(', ')}] AS addresses, [${nodeVariables.map((nodeVariable) => pathNodeMap(nodeVariable)).join(', ')}] AS path_nodes, [${edgeVariables.map(flowEdgeMap).join(', ')}] AS edge_props`,\n 'ORDER BY hops ASC',\n 'LIMIT 200',\n ].join(' '),\n }\n}\n\nfunction connectionProbeQuery(\n address: string,\n compareAddress: string\n): { id: string; query: string } {\n return {\n id: 'connection_probe',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[r:FLOWED_TO]-(b:Address {address: \"${escapeCypherString(compareAddress)}\"})`,\n 'RETURN [a.address, b.address] AS addresses, 1 AS hops',\n 'LIMIT 5',\n ].join(' '),\n }\n}\n\n// Address-grain has no separate identity-resolution lookup: existence of the\n// compare_address is checked directly against :Address, distinct from the\n// primary address_profile query so both existence checks can run in one batch.\nfunction compareAddressExistsQuery(address: string): { id: string; query: string } {\n return {\n id: 'compare_address_exists',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})`,\n 'RETURN a.address AS address',\n 'LIMIT 1',\n ].join(' '),\n }\n}\n\n// Pool trace rule: the via_linked read is a two-hop walk through `owned`, so\n// `a` and `owned` carry the pool and the system guard and the target `b` may\n// be a pool. The direct\n// read is a counterparty listing of one address, not a trace, and stays\n// unguarded (ruling: a pool's own counterparty list is a listing).\n// AC11: FLOWED_TO reachability UNIONed over one -[:LINKED]- hop, so an\n// investigator surveying an address's exposure also sees exposure carried by\n// an address that is only ownership-LINKED to it (LINKED is undirected).\nfunction linkedExposureQueries(address: string): Array<{ id: string; query: string }> {\n return [\n {\n id: 'linked_exposure_direct',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[r:FLOWED_TO]-(b:Address)`,\n 'WHERE a.address <> b.address',\n `RETURN a.address AS subject_address, b.address AS counterparty_address, b.network AS counterparty_network, \"direct\" AS exposure_basis, r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count`,\n 'LIMIT 200',\n ].join(' '),\n },\n {\n id: 'linked_exposure_via_linked',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[l:LINKED]-(owned:Address)-[r:FLOWED_TO]-(b:Address)`,\n `WHERE ${walkGuardTerms(['a', 'owned'], 2)} AND owned.address <> b.address AND a.address <> b.address`,\n `RETURN a.address AS subject_address, b.address AS counterparty_address, b.network AS counterparty_network, \"via_linked\" AS exposure_basis, owned.address AS linked_via_address, l.basis AS link_basis, l.confidence AS link_confidence, r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count`,\n 'LIMIT 200',\n ].join(' '),\n },\n ]\n}\n\n// AC5: LINKED ownership-overlay probe. On the single public robinhood graph,\n// `network` is the query's network on every node, never stored, so both ends of\n// a LINKED edge read the same value and never a second query network: LINKED is\n// the ownership edge within that one space, served on the topology graph only,\n// with no network switch.\nfunction crossSpaceLinkedQuery(address: string): { id: string; query: string } {\n return {\n id: 'cross_space_linked',\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[l:LINKED]-(b:Address)`,\n 'WHERE a.network <> b.network',\n 'RETURN a.address AS address, a.network AS network, b.address AS linked_address, b.network AS linked_network, l.basis AS basis, l.confidence AS confidence, l.source_event AS source_event, l.declared_owner AS declared_owner',\n 'LIMIT 50',\n ].join(' '),\n }\n}\n\n// ── Pairwise route evidence ──\n// Undirected shortest route between two KNOWN identity endpoints. The\n// topology graph speaks ISO GQL, so both routes use one shortest path.\n// Exchange intermediates on a returned route are DISCLOSED in the evidence,\n// never silently filtered out.\n//\n// Pool trace rule (cypher skill, \"Pool trace rule\"): a route never starts at\n// a :Pool and never passes through one, and it may end at one. It follows\n// FLOWED_TO and SWAPPED, so it crosses a swap from payer to recipient. The\n// guard sits inside the path pattern, so the search finds the shortest route\n// that avoids pools instead of dropping a shortest route that crosses one.\n//\n// The text is the guarded route contract (ruled 2026-09-28), served word for\n// word by skills/chain-insights-cypher, and graphrag-mcp rewrites exactly this\n// shape onto DozerDB's fast shortest-path search (data-pipeline\n// route_rewrite.go). Change the addresses and the RETURN only. The quantifier\n// bound covers the guarded middle; the last hop is the unguarded target end,\n// so a route is 1 to CONNECTION_ROUTE_DEPTH_BOUND + 1 hops. The `{0,...}`\n// lower bound keeps DozerDB off the slow undirected search.\n\nexport const CONNECTION_ROUTE_DEPTH_BOUND = 4\n// A route is the guarded middle plus the last hop to the target end.\nexport const CONNECTION_ROUTE_MAX_HOPS = CONNECTION_ROUTE_DEPTH_BOUND + 1\n\nexport function shouldIncludeRouteQueries(compareAddress: string | undefined): boolean {\n // GQL shortest-path traversal always fires when a compare address is given.\n return Boolean(compareAddress)\n}\n\nexport function connectionRouteQueries(\n address: string,\n compareAddress: string\n): Array<{ id: string; query: string }> {\n const routeQuery = (fromAddress: string, toAddress: string): string =>\n [\n `MATCH p = SHORTEST 1 (a:Address {address: \"${escapeCypherString(fromAddress)}\"} WHERE ${walkGuardTerms(['a'], 2)})`,\n ` (()-[:FLOWED_TO|SWAPPED]-(via:Address) WHERE ${walkGuardTerms(['via'], 2)}){0,${CONNECTION_ROUTE_DEPTH_BOUND}}`,\n ` ()-[:FLOWED_TO|SWAPPED]-(b:Address {address: \"${escapeCypherString(toAddress)}\"}) RETURN p LIMIT 1`,\n ].join('')\n return [\n { id: 'connection_route_outbound', query: routeQuery(address, compareAddress) },\n { id: 'connection_route_inbound', query: routeQuery(compareAddress, address) },\n ]\n}\n\nexport interface RouteEvidenceSide {\n hops: number\n identities: string[]\n exchange_intermediates: string[]\n amount_usd_sum_total: number\n}\n\nfunction collectOrdered(\n value: unknown,\n matches: (candidate: Record<string, unknown>) => boolean\n): Array<Record<string, unknown>> {\n const collected: Array<Record<string, unknown>> = []\n const walk = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const entry of node) walk(entry)\n return\n }\n if (node && typeof node === 'object') {\n const candidate = node as Record<string, unknown>\n if (matches(candidate)) collected.push(candidate)\n for (const nested of Object.values(candidate)) walk(nested)\n }\n }\n walk(value)\n return collected\n}\n\n// is_exchange on topology nodes is a MARKER, not a boolean: it usually\n// carries the exchange name (e.g. \"binance\"). Treat explicit falsy\n// encodings as not-exchange (a bare non-null check would falsely disclose\n// nodes serialized as false/\"false\"/0), and any other non-empty value as\n// exchange. isExchangeFlag() is NOT reused here — it is boolean-only and\n// would miss name-valued markers.\nexport function isExchangeMarker(value: unknown): boolean {\n if (value === null || value === undefined || value === false) return false\n if (typeof value === 'number') return value !== 0\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase()\n return (\n normalized !== '' && normalized !== 'false' && normalized !== '0' && normalized !== 'null'\n )\n }\n return value === true\n}\n\n// Shape-tolerant hydrated-path reader: walks the returned path value for\n// ordered address nodes and FLOWED_TO edge amounts without pinning the\n// backend's exact path envelope.\nexport function routeFromPathValue(value: unknown): RouteEvidenceSide | null {\n if (!value || typeof value !== 'object') return null\n const nodes = collectOrdered(value, (candidate) => typeof candidate['address'] === 'string')\n if (nodes.length < 2) return null\n const edges = collectOrdered(\n value,\n (candidate) => typeof candidate['amount_usd_sum'] === 'number' && !('address' in candidate)\n )\n const identities = nodes.map((node) => String(node['address']))\n const exchangeIntermediates = nodes\n .slice(1, -1)\n .filter((node) => isExchangeMarker(node['is_exchange']))\n .map((node) => String(node['address']))\n return {\n // Hop count is a structural property of the node sequence — never\n // derived from edge-object detection, which keys on numeric\n // amount_usd_sum and would under-report on partially hydrated edges.\n hops: nodes.length - 1,\n identities,\n exchange_intermediates: exchangeIntermediates,\n amount_usd_sum_total: edges.reduce((total, edge) => total + Number(edge['amount_usd_sum']), 0),\n }\n}\n\nexport interface RouteEvidence {\n search_strategy: 'any_shortest'\n route_rank_basis: 'hop_count'\n depth_bound: number\n route_found: boolean\n outbound: RouteEvidenceSide | null\n inbound: RouteEvidenceSide | null\n}\n\nexport function buildRouteEvidence(\n outboundRows: Array<Record<string, unknown>>,\n inboundRows: Array<Record<string, unknown>>\n): RouteEvidence {\n const sideFrom = (rows: Array<Record<string, unknown>>): RouteEvidenceSide | null => {\n const first = rows[0]\n if (!first) return null\n const pathValue = 'p' in first ? first['p'] : Object.values(first)[0]\n return routeFromPathValue(pathValue)\n }\n const outbound = sideFrom(outboundRows)\n const inbound = sideFrom(inboundRows)\n return {\n search_strategy: 'any_shortest',\n route_rank_basis: 'hop_count',\n depth_bound: CONNECTION_ROUTE_MAX_HOPS,\n route_found: outbound !== null || inbound !== null,\n outbound,\n inbound,\n }\n}\n\nfunction formatExchangeRows(rows: Array<Record<string, unknown>>): string[] {\n return rows.map((row) => {\n const direction = String(row['direction'] ?? 'flow')\n const exchange = String(row['exchange_address'] ?? '')\n const amount = row['amount_usd_sum'] ?? ''\n const hops = row['hops'] ?? ''\n return `- ${direction}: ${exchange} (${hops} hop(s), amount_usd_sum ${amount})`\n })\n}\n\nfunction numberValue(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim()) {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n }\n return undefined\n}\n\nfunction firstNumber(...values: unknown[]): number | undefined {\n for (const value of values) {\n const parsed = numberValue(value)\n if (parsed !== undefined) return parsed\n }\n return undefined\n}\n\nfunction firstString(...values: unknown[]): string | undefined {\n for (const value of values) {\n if (typeof value === 'string' && value.trim()) return value.trim()\n }\n return undefined\n}\n\nfunction riskLevelFromScore(score: number): string {\n if (score >= 0.85) return 'critical'\n if (score >= 0.7) return 'high'\n if (score >= 0.4) return 'medium'\n return 'low'\n}\n\nfunction riskRecommendation(level: string): string {\n if (level === 'critical' || level === 'high') return 'Escalate for manual review.'\n if (level === 'medium') return 'Review exchange exposure and counterparties before clearing.'\n return 'No stored risk signal found; continue with normal monitoring.'\n}\n\nfunction riskDrivers(\n profile: Record<string, unknown>,\n labelRows: Array<Record<string, unknown>>,\n exchangeRows: Array<Record<string, unknown>>\n): string[] {\n const drivers: string[] = []\n\n const riskLabels = labelRows\n .map((row) => firstString(row['label']))\n .filter((label): label is string => Boolean(label))\n if (riskLabels.length > 0) drivers.push(`Labels: ${[...new Set(riskLabels)].join('; ')}`)\n\n const outflowCount = exchangeRows.filter((row) => row['direction'] === 'outflow').length\n const inflowCount = exchangeRows.filter((row) => row['direction'] === 'inflow').length\n if (outflowCount > 0)\n drivers.push(`Forward bounded search reached ${outflowCount} exchange path(s).`)\n if (inflowCount > 0)\n drivers.push(`Backward bounded search found ${inflowCount} source exchange path(s).`)\n\n return [...new Set(drivers)]\n}\n\n// Derives the deterministic labelRows subset from the profile row's three\n// label_risk_* lists (topology), reproducing the retired\n// addressLabelRiskQuery's `ORDER BY label.updated_timestamp DESC LIMIT 10`\n// subset byte-for-byte: same sort, same cap. The lists are parallel: entry i\n// of each one describes the same label row. Missing/empty lists -> empty\n// array, same as \"no labels\" behaved under the old facts read.\nfunction deriveLabelRows(profile: Record<string, unknown>): Array<Record<string, unknown>> {\n // Dozer/Neo4j properties cannot store lists of maps. Sync therefore\n // materializes the three map fields as parallel primitive arrays.\n const labels = Array.isArray(profile['label_risk_labels'])\n ? (profile['label_risk_labels'] as unknown[]).map((value) => String(value))\n : []\n const riskLevels = Array.isArray(profile['label_risk_levels'])\n ? (profile['label_risk_levels'] as unknown[]).map((value) => String(value))\n : []\n const timestamps = Array.isArray(profile['label_risk_updated_timestamps'])\n ? (profile['label_risk_updated_timestamps'] as unknown[]).map((value) => numberValue(value))\n : []\n const rows = labels.map((label, index) => ({\n label,\n risk_level: riskLevels[index] ?? '',\n updated_timestamp: timestamps[index] ?? 0,\n }))\n return [...rows]\n .sort(\n (a, b) =>\n (numberValue(b['updated_timestamp']) ?? 0) - (numberValue(a['updated_timestamp']) ?? 0)\n )\n .slice(0, 10)\n}\n\nconst RISK_LEVEL_ORDER = ['critical', 'high', 'medium', 'low'] as const\n\nfunction strongestLabelRiskLevel(labelRows: Array<Record<string, unknown>>): string | undefined {\n const levels = labelRows\n .map((row) => firstString(row['risk_level'])?.toLowerCase())\n .filter((level): level is string =>\n Boolean(level && (RISK_LEVEL_ORDER as readonly string[]).includes(level))\n )\n if (levels.length === 0) return undefined\n return RISK_LEVEL_ORDER.find((candidate) => levels.includes(candidate))\n}\n\nfunction riskScoreSources(\n profile: Record<string, unknown>,\n labelRows: Array<Record<string, unknown>>\n): Array<Record<string, unknown>> {\n const sources: Array<Record<string, unknown>> = []\n if (numberValue(profile['live_risk_score']) !== undefined) {\n sources.push({\n family: 'ml_risk_score',\n layer: 'topology',\n source: 'address_node',\n fields: ['risk_score', 'risk_level'],\n })\n }\n if (labelRows.length > 0) {\n sources.push({\n family: 'label_risk',\n layer: 'topology',\n source: 'address_node',\n labels: labelRows.map((row) => ({\n label: row['label'],\n risk_level: row['risk_level'],\n })),\n })\n }\n return sources\n}\n\nfunction terminalEdgeProperties(row: Record<string, unknown>): Record<string, unknown> | undefined {\n const edgeProps = Array.isArray(row['edge_props'])\n ? (row['edge_props'] as Array<Record<string, unknown>>)\n : []\n return edgeProps[edgeProps.length - 1]\n}\n\nfunction enrichExchangeRows(rows: Array<Record<string, unknown>>): Array<Record<string, unknown>> {\n return rows.map((row) => {\n const terminal = terminalEdgeProperties(row)\n if (!terminal) return row\n return {\n ...row,\n amount_usd_sum: row['amount_usd_sum'] ?? terminal['amount_usd_sum'],\n tx_count: row['tx_count'] ?? terminal['tx_count'],\n first_seen_timestamp: row['first_seen_timestamp'] ?? terminal['first_seen_timestamp'],\n last_seen_timestamp: row['last_seen_timestamp'] ?? terminal['last_seen_timestamp'],\n }\n })\n}\n\nconst FALLBACK_SHARED_TX_COUNT = 1000\nconst FALLBACK_SHARED_USD_SUM = 5_000_000\nconst FALLBACK_SHARED_DAMPING = 0.1\nconst FALLBACK_VALUE_SATURATION_USD = 1_000_000\nconst FALLBACK_BASE_SCORE = 0.1\nconst FALLBACK_MAX_SCORE = 0.6\n\n/**\n * Score exchange exposure when no ML risk score exists. Topology-grain:\n * log-scaled USD volume across exchange rows, with shared/omnibus edges\n * (high tx_count or USD throughput) dampened, bounded in (0, 0.6] so a\n * fallback can never impersonate a high ML score band.\n */\nexport function exchangeExposureFallbackScore(\n exchangeRows: Array<Record<string, unknown>>\n): number {\n if (exchangeRows.length === 0) return 0\n let weightedUsd = 0\n for (const row of exchangeRows) {\n const usd = numberValue(row['amount_usd_sum']) ?? 0\n const txCount = numberValue(row['tx_count']) ?? 0\n const shared = txCount >= FALLBACK_SHARED_TX_COUNT || usd >= FALLBACK_SHARED_USD_SUM\n weightedUsd += shared ? usd * FALLBACK_SHARED_DAMPING : usd\n }\n const capped = Math.min(weightedUsd, FALLBACK_VALUE_SATURATION_USD)\n const factor = Math.log10(1 + capped) / Math.log10(1 + FALLBACK_VALUE_SATURATION_USD)\n return Math.min(\n FALLBACK_MAX_SCORE,\n FALLBACK_BASE_SCORE + (FALLBACK_MAX_SCORE - FALLBACK_BASE_SCORE) * factor\n )\n}\n\nexport function riskAssessment(\n profile: Record<string, unknown>,\n labelRows: Array<Record<string, unknown>>,\n exchangeRows: Array<Record<string, unknown>>\n): Record<string, unknown> {\n const mlRiskScore = firstNumber(profile['live_risk_score'])\n // UNSCORED is the model's explicit abstention (calibrated-scoring release):\n // the score exists for transparency but carries no stance — deriving a\n // severity band from it would silently launder an abstention into a\n // confident verdict (typically \"low\"). Fall back to labels/exchange\n // exposure and say so.\n const mlAbstained = isUnscoredRiskLevel(profile['live_risk_level'])\n const labelRiskLevel = strongestLabelRiskLevel(labelRows)\n const usableMlScore = mlAbstained ? undefined : mlRiskScore\n const score = usableMlScore ?? exchangeExposureFallbackScore(exchangeRows)\n let level =\n labelRiskLevel ??\n (mlAbstained && exchangeRows.length === 0 ? 'unscored' : riskLevelFromScore(score))\n const drivers = riskDrivers(profile, labelRows, exchangeRows)\n if (mlAbstained)\n drivers.push(\n 'ml_abstained: ML verdict is UNSCORED (insufficient labeled graph context); level derived from labels/exchange exposure only'\n )\n // Labels are curated truth and stay first — but a lower-severity label\n // must never SUPPRESS a more severe usable ML band. Failing toward\n // \"looks safe\" is the one direction an AML triage tool may not fail.\n const usableMlBand = usableMlScore !== undefined ? riskLevelFromScore(usableMlScore) : undefined\n if (\n labelRiskLevel &&\n usableMlBand &&\n riskSeverityRank(usableMlBand) > riskSeverityRank(labelRiskLevel)\n ) {\n level = usableMlBand\n drivers.push(\n `ml_label_divergence: usable ML band ${usableMlBand} exceeds strongest label level ${labelRiskLevel}; reporting the more severe band — review the label`\n )\n }\n return {\n level,\n score,\n ...(mlRiskScore !== undefined ? { ml_risk_score: mlRiskScore } : {}),\n ...(mlAbstained ? { ml_verdict: 'unscored' } : {}),\n confidence:\n usableMlScore !== undefined || labelRiskLevel\n ? 'high'\n : exchangeRows.length > 0\n ? 'medium'\n : 'low',\n recommendation:\n level === 'unscored'\n ? 'Model abstained and no label/exchange signal found; gather more context before clearing.'\n : riskRecommendation(level),\n drivers,\n sources: riskScoreSources(profile, labelRows),\n }\n}\n\nfunction formatRiskScore(score: unknown): string {\n const parsed = numberValue(score)\n if (parsed === undefined) return String(score ?? 'unknown')\n return Number.isInteger(parsed) ? parsed.toString() : parsed.toFixed(2)\n}\n\nfunction stringArrayValue(value: unknown): string[] | undefined {\n if (Array.isArray(value)) return value.map(String)\n if (typeof value === 'string' && value.trim()) return [value]\n return undefined\n}\n\nfunction restoreSystemLabels(\n graph: Record<string, unknown>,\n rawNodes: Array<Record<string, unknown>>\n): Record<string, unknown> {\n if (!Array.isArray(graph['nodes'])) return graph\n const labelsByAddress = new Map(\n rawNodes\n .map(\n (node) =>\n [\n typeof node['address'] === 'string'\n ? node['address']\n : typeof node['id'] === 'string'\n ? node['id']\n : '',\n stringArrayValue(node['system_labels']),\n ] as const\n )\n .filter(\n (entry): entry is readonly [string, string[]] =>\n Boolean(entry[0]) && Array.isArray(entry[1]) && entry[1].length > 0\n )\n )\n return {\n ...graph,\n nodes: graph['nodes'].map((node) => {\n if (typeof node !== 'object' || node === null || Array.isArray(node)) return node\n const record = node as Record<string, unknown>\n const address =\n typeof record['address'] === 'string'\n ? record['address']\n : typeof record['id'] === 'string'\n ? record['id']\n : ''\n const systemLabels = labelsByAddress.get(address)\n return systemLabels ? { ...record, system_labels: systemLabels } : record\n }),\n }\n}\n\nfunction buildRiskGraph(\n address: string,\n profile: Record<string, unknown>,\n rows: Array<Record<string, unknown>>,\n network: string\n): Record<string, unknown> {\n const nodes = new Map<string, Record<string, unknown>>()\n nodes.set(address, {\n id: address,\n address,\n node_type: 'address',\n labels: stringArrayValue(profile['display_labels']) ?? [],\n ...(stringArrayValue(profile['system_labels'])\n ? { system_labels: stringArrayValue(profile['system_labels']) }\n : {}),\n ...(stringArrayValue(profile['member_addresses'])?.length\n ? { member_addresses: stringArrayValue(profile['member_addresses']) }\n : {}),\n ...(numberValue(profile['live_risk_score']) !== undefined\n ? { risk_score: numberValue(profile['live_risk_score']) }\n : {}),\n ...(firstString(profile['live_risk_level'])\n ? { risk_level: firstString(profile['live_risk_level']) }\n : {}),\n roles: ['subject'],\n })\n const edges: Array<Record<string, unknown>> = []\n const mergeNode = (entry: string, metadata?: Record<string, unknown>) => {\n const existing = nodes.get(entry) ?? {\n id: entry,\n address: entry,\n node_type: 'address',\n labels: [],\n }\n const labels = stringArrayValue(metadata?.['labels']) ?? existing['labels']\n const systemLabels = stringArrayValue(metadata?.['system_labels']) ?? existing['system_labels']\n const memberAddresses =\n stringArrayValue(metadata?.['member_addresses']) ?? existing['member_addresses']\n const riskScore = numberValue(metadata?.['risk_score']) ?? existing['risk_score']\n const riskLevel =\n normalizeRiskLevel(firstString(metadata?.['risk_level'])) ?? existing['risk_level']\n nodes.set(entry, {\n ...existing,\n labels,\n ...(systemLabels ? { system_labels: systemLabels } : {}),\n ...(Array.isArray(memberAddresses) && memberAddresses.length > 0\n ? { member_addresses: memberAddresses }\n : {}),\n ...(riskScore !== undefined ? { risk_score: riskScore } : {}),\n ...(riskLevel ? { risk_level: riskLevel } : {}),\n })\n }\n for (const row of rows) {\n const rawPath = Array.isArray(row['path']) ? row['path'] : row['addresses']\n const path = Array.isArray(rawPath) ? rawPath.map(String) : []\n const pathNodes = Array.isArray(row['path_nodes'])\n ? (row['path_nodes'] as Array<Record<string, unknown>>)\n : []\n for (let index = 0; index < path.length; index += 1) {\n const entry = path[index]!\n mergeNode(entry, pathNodes[index])\n }\n const exchange = typeof row['exchange_address'] === 'string' ? row['exchange_address'] : ''\n if (exchange) {\n const displayLabels = stringArrayValue(row['exchange_display_labels']) ?? []\n const systemLabels =\n stringArrayValue(row['exchange_system_labels']) ??\n stringArrayValue(row['exchange_labels']) ??\n []\n nodes.set(exchange, {\n id: exchange,\n address: exchange,\n node_type: 'address',\n labels: displayLabels,\n ...(systemLabels.length > 0 ? { system_labels: systemLabels } : {}),\n roles: ['exchange'],\n })\n }\n for (let index = 0; index < path.length - 1; index += 1) {\n const edgeProps = Array.isArray(row['edge_props'])\n ? (row['edge_props'] as Array<Record<string, unknown>>)\n : []\n const edge = edgeProps[index] ?? row\n edges.push({\n source: path[index],\n target: path[index + 1],\n edge_type: 'flowed_to',\n usd_amount: edge['amount_usd_sum'] ?? 0,\n amount_usd_sum: edge['amount_usd_sum'] ?? 0,\n tx_count: edge['tx_count'] ?? 0,\n direction: row['direction'],\n })\n }\n }\n const rawNodes = [...nodes.values()]\n return restoreSystemLabels(\n normalizeGraphPayload({\n schema: 'chain-insights.graph.v1',\n nodes: rawNodes,\n edges,\n flows: [],\n edge_anchors: [],\n metadata: { address, network, generated_at: new Date().toISOString() },\n }),\n rawNodes\n )\n}\n\nexport async function addressRisk(\n remoteClient: Client,\n options: AddressRiskOptions\n): Promise<{\n summaryText: string\n structuredContent: Record<string, unknown>\n graphData: Record<string, unknown>\n}> {\n const address = options.address.trim()\n const network = options.network.trim()\n const compareInput = options.compareAddress?.trim() ?? ''\n if (!address) throw new Error('address is required')\n if (!network) throw new Error('network is required')\n\n // Every internal graph_query_batch round trip this workflow makes is\n // observed here and totaled into a usage block on the response (never\n // blocks/throws on a backend that doesn't emit billing fields yet).\n const usage = createUsageAccumulator()\n const trackedClient = wrapClientForUsageTracking(remoteClient, usage)\n\n // Address-grain has no separate resolution step for the SUBJECT address:\n // the input address IS the graph node key. Its existence is inferred\n // post-hoc from the address_profile row (below) instead of the pre-revert\n // pre-flight lookup -- deliberate: it saves a round trip on the hot path.\n // The COMPARE address keeps a pre-flight existence probe, because the\n // connection probe and shortest-path route queries must be SUPPRESSED (not\n // ignored) when the compare address does not exist -- pre-revert behavior\n // never issued route probes for an unresolved compare input.\n let compareUnresolved = false\n if (compareInput) {\n const compareBatch = await callGraphBatch(trackedClient, network, [\n compareAddressExistsQuery(compareInput),\n ])\n const compareRows = optionalResultsFor(compareBatch, 'compare_address_exists', [])\n compareUnresolved = !firstString(compareRows[0]?.['address'])\n }\n const compareAddress = compareInput && !compareUnresolved ? compareInput : ''\n\n const queries = [\n addressProfileQuery(address),\n addressFeatureQuery(address),\n { id: 'money_trail_incident', query: moneyTrailIncidentQuery(address) },\n ...exchangeOutflowQueries(address),\n ...exchangeInflowQueries(address),\n ...(compareAddress\n ? [connectionProbeQuery(address, compareAddress)]\n : [\n {\n id: 'connection_probe',\n query:\n 'MATCH (n:Address {address: \"__chain_insights_noop__\"}) RETURN n.address AS noop LIMIT 0',\n },\n ]),\n // Route evidence is additive: ISO GQL shortest-path traversal always\n // fires for a compare address whose existence probe succeeded (the\n // 1-hop probe above always runs).\n ...(shouldIncludeRouteQueries(compareAddress)\n ? connectionRouteQueries(address, compareAddress)\n : []),\n ]\n const batch = await callGraphBatch(trackedClient, network, queries)\n const partialQueryFailures: QueryFailure[] = []\n // Deliberate post-hoc existence inference (address grain): an empty\n // address_profile result means the subject :Address does not exist ->\n // report unresolved; this replaces the pre-revert identity pre-flight.\n const addressProfileRows = optionalResultsFor(batch, 'address_profile', partialQueryFailures)\n if (addressProfileRows.length === 0) {\n return {\n summaryText: `Address risk for ${network}:${address}\\n\\nUnresolved: no Address found for \"${address}\". The address may not have on-chain activity in this network.`,\n structuredContent: {\n schema: 'chain-insights.result.v1',\n tool: 'aml_address_risk',\n facts: {\n subject: { network, addresses: [address] },\n unresolved: [address],\n usage: usageBlock(usage),\n },\n },\n graphData: {\n schema: 'chain-insights.graph.v1',\n nodes: [],\n edges: [],\n flows: [],\n edge_anchors: [],\n metadata: { address, network, generated_at: new Date().toISOString() },\n },\n }\n }\n const profile: Record<string, unknown> = {\n address,\n ...(addressProfileRows[0] ?? {}),\n ...(optionalResultsFor(batch, 'address_feature', partialQueryFailures)[0] ?? {}),\n }\n const labelRows = deriveLabelRows(profile)\n const outflows = enrichExchangeRows(\n optionalResultsWithPrefix(batch, 'exchange_outflows_', partialQueryFailures)\n )\n const inflows = enrichExchangeRows(\n optionalResultsWithPrefix(batch, 'exchange_inflows_', partialQueryFailures)\n )\n const connections = compareAddress\n ? optionalResultsFor(batch, 'connection_probe', partialQueryFailures)\n : []\n const routeEvidence = shouldIncludeRouteQueries(compareAddress)\n ? buildRouteEvidence(\n optionalResultsFor(batch, 'connection_route_outbound', partialQueryFailures),\n optionalResultsFor(batch, 'connection_route_inbound', partialQueryFailures)\n )\n : undefined\n const exchangeRows = [...outflows, ...inflows]\n // A hop-depth exchange_outflows_N/exchange_inflows_N query can fail\n // independently (e.g. the archive-tier query-memory limit on a deep\n // multi-hop search) while other hop depths succeed with zero rows. An\n // empty exchangeRows result must then read as \"search incomplete,\" not\n // \"no exchange exposure\" -- the two are not the same claim, and an AML\n // tool that silently reports a false-clean verdict on a partial search\n // failure is a real risk (found during MoA review, 2026-07-05).\n const exchangeSearchFailures = partialQueryFailures.filter(\n (failure) =>\n failure.id.startsWith('exchange_outflows_') || failure.id.startsWith('exchange_inflows_')\n )\n const exchangeSearchComplete = exchangeSearchFailures.length === 0\n // money-trail enrichment (optional): a preliminary block resolves the\n // primary_seed off the incident-only rows, then a second batch call fans\n // out TRAIL_ENDS_AT for that seed so the block can pick the highest-value\n // terminal fact. Both reads are optional-results -- a graph with no\n // money-trail layer never fails the tool.\n const moneyTrailIncidentRows = optionalResultsFor(\n batch,\n 'money_trail_incident',\n partialQueryFailures\n )\n const preliminaryMoneyTrail = buildMoneyTrailBlock(moneyTrailIncidentRows, [])\n let moneyTrailEndRows: Array<Record<string, unknown>> = []\n if (preliminaryMoneyTrail?.primary_seed) {\n try {\n const endsBatch = await callGraphBatch(trackedClient, network, [\n { id: 'money_trail_ends', query: moneyTrailEndsQuery(preliminaryMoneyTrail.primary_seed) },\n ])\n moneyTrailEndRows = optionalResultsFor(endsBatch, 'money_trail_ends', partialQueryFailures)\n } catch (error) {\n // Degrade, don't fail: a transport/parse error on the second batch call\n // (unlike a query-level ok:false, which optionalResultsFor already\n // absorbs) must not blow up the whole tool -- the incident rows are\n // already in hand, so the block still reports on_trail without\n // nearest_trail_end.\n collectQueryFailure(\n partialQueryFailures,\n 'money_trail_ends',\n error instanceof Error ? error.message : String(error)\n )\n }\n }\n const moneyTrail = buildMoneyTrailBlock(moneyTrailIncidentRows, moneyTrailEndRows)\n const graphData = buildRiskGraph(address, profile, exchangeRows, network)\n const risk = riskAssessment(profile, labelRows, exchangeRows)\n const liveRiskScore = numberValue(profile['live_risk_score'])\n const liveRiskLevel = firstString(profile['live_risk_level'])\n const liveNodeVerdict =\n liveRiskScore !== undefined || liveRiskLevel\n ? {\n ...(liveRiskScore !== undefined ? { risk_score: liveRiskScore } : {}),\n ...(liveRiskLevel ? { risk_level: liveRiskLevel } : {}),\n source: 'topology_node',\n }\n : undefined\n\n const lines = [\n `Address risk for ${network}:${address}`,\n '',\n `Risk: ${risk['level']} (${formatRiskScore(risk['score'])})`,\n `Confidence: ${risk['confidence']}`,\n `Recommendation: ${risk['recommendation']}`,\n ...(liveNodeVerdict\n ? [`Live node triage: ${liveRiskLevel ?? 'unknown'} (${formatRiskScore(liveRiskScore)})`]\n : []),\n `Graph degree: in ${profile['degree_in'] ?? 'unknown'}, out ${profile['degree_out'] ?? 'unknown'}.`,\n '',\n 'Exchange behavior',\n ...(exchangeRows.length > 0\n ? [\n formatExchangeRows(exchangeRows).join('\\n'),\n ...(exchangeSearchComplete\n ? []\n : [\n `(incomplete: ${exchangeSearchFailures.length} other hop-depth quer${exchangeSearchFailures.length === 1 ? 'y' : 'ies'} failed -- there may be more exchange exposure than shown here)`,\n ]),\n ]\n : [\n exchangeSearchComplete\n ? '- No exchange inflow/outflow paths found in bounded search.'\n : `- Exchange search incomplete: ${exchangeSearchFailures.length} hop-depth quer${exchangeSearchFailures.length === 1 ? 'y' : 'ies'} failed before returning a result. This is NOT a clean finding -- retry or narrow the search (see Partial query failures below).`,\n ]),\n ]\n if (Array.isArray(risk['drivers']) && risk['drivers'].length > 0) {\n lines.push('', 'Risk drivers', risk['drivers'].map((driver) => `- ${driver}`).join('\\n'))\n }\n if (moneyTrail) {\n lines.push('', moneyTrailSummarySentence(moneyTrail))\n }\n if (compareAddress) {\n lines.push(\n '',\n `Connection compare target: ${compareAddress}`,\n connections.length > 0\n ? `Connection paths found: ${connections.length}`\n : 'Connection paths found: 0'\n )\n }\n if (compareUnresolved) {\n lines.push(\n '',\n `Unresolved compare_address: no Address found for \"${compareInput}\"; comparison skipped.`\n )\n }\n if (partialQueryFailures.length > 0) {\n lines.push(\n '',\n 'Partial query failures',\n partialQueryFailures.map((failure) => `- ${failure.id}: ${failure.error}`).join('\\n')\n )\n }\n const summaryText = lines.join('\\n')\n const structuredContent = {\n schema: 'chain-insights.result.v1',\n tool: 'aml_address_risk',\n facts: {\n subject: {\n network,\n addresses: compareAddress ? [address, compareAddress] : [address],\n },\n risk: {\n ...risk,\n ...(liveNodeVerdict ? { live_node: liveNodeVerdict } : {}),\n },\n exchange_behavior: {\n outflows,\n inflows,\n search_status: exchangeSearchComplete ? 'complete' : 'incomplete',\n ...(exchangeSearchComplete\n ? {}\n : { failed_query_ids: exchangeSearchFailures.map((failure) => failure.id) }),\n },\n connection: compareAddress\n ? {\n compare_address: compareAddress,\n paths: connections,\n ...(routeEvidence ? { route_evidence: routeEvidence } : {}),\n }\n : undefined,\n money_trail: moneyTrail,\n unresolved: compareUnresolved ? [compareInput] : undefined,\n partial_query_errors: partialQueryFailures.length > 0 ? partialQueryFailures : undefined,\n usage: usageBlock(usage),\n },\n }\n const artifacts = options.writeArtifacts\n ? await writeAddressRiskArtifacts(\n network,\n address,\n compareAddress,\n graphData,\n exchangeRows,\n summaryText\n )\n : statelessArtifacts()\n const evidence = artifactEvidence(artifacts)\n\n return {\n summaryText,\n structuredContent: {\n ...structuredContent,\n artifacts,\n evidence: [\n ...evidence,\n {\n evidence_type: 'tool_summary',\n summary: `aml_address_risk ${address} completed for ${network}`,\n },\n ],\n },\n graphData,\n }\n}\n\n/**\n * Routes the public AML tool contract to the requested implementation. An\n * omitted version always follows the latest supported contract.\n */\nexport async function runAmlAddressRisk(\n remoteClient: Client,\n options: AddressRiskOptions,\n requestedVersion?: string\n) {\n const version = resolveAmlAddressRiskVersion(requestedVersion)\n switch (version) {\n case 'v1': {\n const result = await addressRisk(remoteClient, options)\n return {\n ...result,\n structuredContent: {\n ...result.structuredContent,\n tool_version: version,\n },\n }\n }\n }\n}\n\nfunction toCsvValue(value: unknown): string {\n return value === undefined || value === null ? '' : String(value)\n}\n\nfunction subjectNodeForExchangeRow(row: Record<string, unknown>, fallbackAddress: string): string {\n return String(\n row['direction'] === 'inflow'\n ? (row['withdrawal_address'] ?? row['deposit_address'] ?? fallbackAddress)\n : (row['deposit_address'] ?? row['withdrawal_address'] ?? fallbackAddress)\n )\n}\n\nfunction buildAddressRiskTableHtml(\n tool: string,\n network: string,\n rows: Array<Record<string, unknown>>,\n subject: string\n): string {\n const headers = [\n 'direction',\n 'exchange_address',\n 'subject_path_node',\n 'hops',\n 'amount_usd_sum',\n 'tx_count',\n ] as const\n const body = rows\n .map((row) => {\n const exchangeAddress = String(row['exchange_address'] ?? '')\n const subjectNode = subjectNodeForExchangeRow(row, subject)\n const rowValues = [\n row['direction'] ?? '',\n exchangeAddress,\n subjectNode,\n row['hops'] ?? '',\n row['amount_usd_sum'] ?? '',\n row['tx_count'] ?? '',\n ]\n return `<tr>${rowValues.map((value) => `<td>${htmlEscape(toCsvValue(value))}</td>`).join('')}</tr>`\n })\n .join('\\n')\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${htmlEscape(tool)} Risk Table</title>\n<style>\n :root { color-scheme: dark; font-family: Inter, ui-sans-serif, system-ui; background: #0b0d12; color: #f4f2ea; }\n body { margin: 0; background: #0b0d12; color: #f4f2ea; }\n main { padding: 24px; }\n h1 { font-size: 20px; margin: 0 0 8px; font-weight: 650; }\n table { border-collapse: collapse; width: 100%; min-width: 900px; }\n th, td { border-bottom: 1px solid rgba(255,255,255,.08); padding: 8px 10px; text-align: left; }\n th { position: sticky; top: 0; background: #161a24; color: #f2dda6; font-weight: 600; }\n</style>\n</head>\n<body>\n<main>\n <h1>${htmlEscape(tool)} Table</h1>\n <div>Network: <strong>${htmlEscape(network)}</strong></div>\n <div>Generated: <strong>${htmlEscape(new Date().toISOString())}</strong></div>\n <table>\n <thead><tr>${headers.map((header) => `<th>${htmlEscape(header)}</th>`).join('')}</tr></thead>\n <tbody>${body}</tbody>\n </table>\n</main>\n</body>\n</html>\n`\n}\n\nasync function writeAddressRiskArtifacts(\n network: string,\n address: string,\n compareAddress: string | undefined,\n graphData: Record<string, unknown>,\n exchangeRows: Array<Record<string, unknown>>,\n summaryText: string\n): Promise<Record<string, string>> {\n const paths = workspaceOutputPaths()\n await Promise.all([\n mkdir(paths.reportsRoot, { recursive: true }),\n mkdir(paths.reportGraphsRoot, { recursive: true }),\n mkdir(paths.reportTablesRoot, { recursive: true }),\n ])\n const safeNetwork = network.replace(/[^A-Za-z0-9._-]+/g, '_')\n const safeAddress = address.replace(/[^A-Za-z0-9._-]+/g, '_')\n const slug = `${new Date()\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.\\d{3}Z$/, 'Z')}_aml_address_risk_${safeNetwork}_${safeAddress}`\n const graphPath = path.join(paths.reportGraphsRoot, `${slug}.graph.json`)\n const tableJsonPath = path.join(paths.reportTablesRoot, `${slug}.compact-evidence.json`)\n const csvPath = path.join(paths.reportTablesRoot, `${slug}.flows.csv`)\n const tableHtmlPath = path.join(paths.reportsRoot, `${slug}.table.html`)\n const reportPath = path.join(paths.reportsRoot, `${slug}.aml-address-report.md`)\n const header = [\n 'direction',\n 'exchange_address',\n 'subject_path_node',\n 'hops',\n 'amount_usd_sum',\n 'tx_count',\n ]\n const csv =\n [\n header.join(','),\n ...exchangeRows.map((row) => {\n const exchangeAddress = String(row['exchange_address'] ?? '')\n const subjectPathNode = subjectNodeForExchangeRow(row, address)\n return [\n row['direction'] ?? '',\n exchangeAddress,\n subjectPathNode,\n row['hops'] ?? '',\n row['amount_usd_sum'] ?? '',\n row['tx_count'] ?? '',\n ]\n .map((value) => JSON.stringify(String(value)))\n .join(',')\n }),\n ].join('\\n') + '\\n'\n const evidence = {\n schema: 'chain-insights.trace.v1',\n tool: 'aml_address_risk',\n network,\n input: {\n address,\n ...(compareAddress ? { compare_address: compareAddress } : {}),\n },\n profile: {\n exchange_rows: exchangeRows.map((row) => ({\n direction: row['direction'],\n exchange_address: row['exchange_address'],\n subject_node: subjectNodeForExchangeRow(row, address),\n hops: row['hops'],\n amount_usd_sum: row['amount_usd_sum'],\n tx_count: row['tx_count'],\n })),\n report_summary: summaryText,\n },\n }\n await writeFile(graphPath, JSON.stringify(graphData, null, 2) + '\\n', { mode: 0o600 })\n await writeFile(tableJsonPath, JSON.stringify(evidence, null, 2) + '\\n', { mode: 0o600 })\n await writeFile(csvPath, csv, { mode: 0o600 })\n await writeFile(\n tableHtmlPath,\n buildAddressRiskTableHtml('aml_address_risk', network, exchangeRows, address),\n { mode: 0o600 }\n )\n await writeFile(\n reportPath,\n [\n `# Address Risk Report (${network}:${address})`,\n `- Graph JSON: ${graphPath}`,\n `- Table JSON: ${tableJsonPath}`,\n `- CSV: ${csvPath}`,\n `- Report HTML: ${tableHtmlPath}`,\n '',\n summaryText,\n ].join('\\n'),\n { mode: 0o600 }\n )\n\n return {\n graph_json: graphPath,\n table_json: tableJsonPath,\n flows_csv: csvPath,\n table_html: tableHtmlPath,\n report_md: reportPath,\n }\n}\n\nfunction statelessArtifacts(): Record<string, unknown> {\n return {\n artifacts_written: false,\n artifact_mode: 'stateless',\n }\n}\n\nfunction artifactEvidence(artifacts: Record<string, unknown>): Array<Record<string, unknown>> {\n return Object.entries(artifacts)\n .filter(\n (entry): entry is [string, string] =>\n entry[0] !== 'artifact_mode' && typeof entry[1] === 'string' && entry[1].length > 0\n )\n .map(([kind, filePath]) => ({\n evidence_type: 'artifact_pointer',\n path: filePath,\n summary: `${kind} artifact`,\n }))\n}\n\nfunction htmlEscape(value: unknown): string {\n return String(value ?? '')\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''')\n}\n\n// Deterministic query-builder surface for the committed corpus and\n// query-with-a-documented-call-contract tests. Reflects the retained\n// aml_address_risk/graph query builders after the aml_trace_* cut.\n\n// pairAnchorQuery resolves a transaction id of a pair through the facts lane\n// (openspec dozerdb-flows-to-slim-schema: the topology edge carries no tx\n// anchors). A facts read names an address pair with one day, or one\n// transaction hash, and takes no ORDER BY, so the read names the UTC day (take\n// it from the link's first_seen_timestamp or last_seen_timestamp) and returns\n// one transfer of the pair on that day. Bounded: LIMIT 1 on the pair and the\n// day. TRANSFER lists every transfer the link counts, internal native transfers\n// included (kind internal), so the anchor query finds a row for a pair that only\n// internal transfers move.\nexport function pairAnchorQuery(from: string, to: string, day: string): string {\n return [\n 'USE facts',\n `MATCH (a:Address {address: \"${escapeCypherString(from)}\"})-[t:TRANSFER]->(b:Address {address: \"${escapeCypherString(to)}\"})`,\n `WHERE t.block_date = \"${escapeCypherString(day)}\"`,\n 'RETURN t.tx_id AS tx_id, t.block_timestamp AS block_timestamp',\n 'LIMIT 1',\n ].join(' ')\n}\n\n// inlineAverageFlowQuery is the documented recipe for the retired\n// avg_tx_size_usd edge property: compute the average at read time from the\n// two fields the slim edge carries.\nexport function inlineAverageFlowQuery(address: string, limit = 25): { query: string } {\n return {\n query: [\n `MATCH (a:Address {address: \"${escapeCypherString(address)}\"})-[r:FLOWED_TO]->(b:Address)`,\n 'RETURN b.address AS neighbor, r.amount_usd_sum AS amount_usd_sum, r.tx_count AS tx_count,',\n ' r.amount_usd_sum / toFloat(r.tx_count) AS avg_tx_size_usd',\n `ORDER BY r.amount_usd_sum DESC LIMIT ${limit}`,\n ].join(' '),\n }\n}\n\nexport const queryBuilderContract = {\n topologyGraphQuery,\n pairAnchorQuery,\n inlineAverageFlowQuery,\n addressProfileQuery,\n compareAddressExistsQuery,\n addressFeatureQuery,\n exchangeOutflowQueries,\n exchangeInflowQueries,\n connectionProbeQuery,\n connectionRouteQueries,\n linkedExposureQueries,\n crossSpaceLinkedQuery,\n}\n"],"mappings":";;;;;AAAA,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAAa;CAAY;CAAe;AAAc,CAAC;AAaxF,SAASA,WAAS,OAAsC;CACtD,OAAO,OAAO,UAAU,YAAY,UAAU,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AkB;EAClB;EACA;CACF,CAAC,CAAC,KAAK,IAAI,GACX,EAAE,MAAM,IAAM,CAChB;CAEA,OAAO;EACL,YAAY;EACZ,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,WAAW;CACb;AACF;AAEA,SAAS,qBAA8C;CACrD,OAAO;EACL,mBAAmB;EACnB,eAAe;CACjB;AACF;AAEA,SAAS,iBAAiB,WAAoE;CAC5F,OAAO,OAAO,QAAQ,SAAS,CAAC,CAC7B,QACE,UACC,MAAM,OAAO,mBAAmB,OAAO,MAAM,OAAO,YAAY,MAAM,EAAE,CAAC,SAAS,CACtF,CAAC,CACA,KAAK,CAAC,MAAM,eAAe;EAC1B,eAAe;EACf,MAAM;EACN,SAAS,GAAG,KAAK;CACnB,EAAE;AACN;AAEA,SAAS,WAAW,OAAwB;CAC1C,OAAO,OAAO,SAAS,EAAE,CAAC,CACvB,WAAW,KAAK,OAAO,CAAC,CACxB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,MAAK,QAAQ,CAAC,CACzB,WAAW,KAAK,OAAO;AAC5B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"token-lookup-sH2DesLS.mjs","names":[],"sources":["../src/mcp/token-lookup.ts"],"sourcesContent":["/**\n * meta_token_lookup: a ticker or a token name becomes its contracts.\n *\n * A local tool of the proxy. It sends one anchored facts read of the Asset\n * lookup by symbol, the same read by name when the symbol answers nothing, and\n * then the creator and the factory of each candidate from topology, one batch\n * member per candidate. Nothing is matched here: the graph server matches the\n * symbol or the name, case-insensitively and exactly, and orders the rows\n * verified first, then oldest first. The proxy keeps that order.\n *\n * Tickers collide on purpose: clones reuse a symbol to borrow its trust. The\n * tool never picks one. The description below is the contract with every\n * host, Claude Desktop chat included, which reads no skill.\n */\n\nimport { ANSWER_HINT } from './answer-hint.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport { isEpochMs, utcText } from './timestamp-text.js'\n\nexport const META_TOKEN_LOOKUP_TOOL = 'meta_token_lookup'\nexport const META_TOKEN_LOOKUP_SCHEMA = 'chain-insights.meta-token-lookup.v1' as const\nexport const META_TOKEN_LOOKUP_TITLE = 'Token by ticker or name'\nexport const META_TOKEN_LOOKUP_DESCRIPTION =\n 'Call this first when a question names a token by its ticker or name and gives no contract ' +\n '(TCITY, USDG, SPCX). It returns every contract on the network that carries that symbol, ' +\n 'verified first, then oldest first. Tickers collide: never treat the first row as the token. ' +\n 'When several match, name them and ask, or pick by the evidence the user gave. Zero candidates ' +\n 'means no contract carries the symbol: say so, and do not search the web.'\nexport const META_TOKEN_LOOKUP_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const META_TOKEN_LOOKUP_ARGS = ['network', 'symbol'] as const\n\n/** The candidates returned. The read asks for one more, so a full page says there are more. */\nexport const CANDIDATES_MAX = 25\nexport const ROWS_READ = CANDIDATES_MAX + 1\n/** The graph server admits at most 20 members in one graph_query_batch. */\nexport const CREATOR_BATCH_MAX = 20\nexport const SYMBOL_MAX = 64\n\nexport const ADDRESS_INPUT_HINT = 'an address is already an anchor: read it on USE topology'\n\nexport interface TokenCandidate {\n contract: string\n symbol: string | null\n name: string | null\n token_standard: string | null\n decimals: number | null\n verified: boolean\n verification_source: string | null\n first_seen_timestamp: number | null\n first_seen_timestamp_utc: string | null\n creator: string | null\n factory: string | null\n}\n\nexport interface MetaTokenLookupResult {\n schema: typeof META_TOKEN_LOOKUP_SCHEMA\n network: string\n query: string\n matched_on: 'symbol' | 'name' | null\n candidates: TokenCandidate[]\n /** The rows the server sent, at most 26: 26 means there are more than the 25 returned. */\n total: number\n truncated: boolean\n hint: string\n}\n\n/** One graph_query or graph_query_batch reply as the remote client returns it. */\nexport type GraphAnswer = {\n content?: unknown[]\n structuredContent?: unknown\n isError?: boolean\n}\n\nexport interface TokenToolDependencies {\n /** One graph_query through the proxy's remote client, billed as any read. */\n graphQuery: (args: { network: string; query: string }) => Promise<GraphAnswer>\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<GraphAnswer>\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 MetaTokenLookupToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\nconst ADDRESS_FORM = /^0x[0-9a-fA-F]{40}$/\nconst CONTRACT_FORM = /^0x[0-9a-f]{40}$/\n// A string literal of the read holds no double quote, no backslash and no\n// control character: the symbol is refused rather than escaped, so the read the\n// server receives is always the read written here.\nfunction unsafeLiteral(text: string): boolean {\n for (const char of text) {\n const code = char.codePointAt(0)!\n if (char === '\"' || char === '\\\\' || code < 0x20 || code === 0x7f) return true\n }\n return false\n}\nconst CODE_PREFIX = /^([a-z][a-z0-9_]*):\\s*/\n// Codes of a read that was stopped, not refused: the same read may answer later.\nconst TRANSIENT_CODE =\n /(timeout|memory_limit|cpu_limit|busy|_failed$|rate_limited|unavailable|too_large|node_error)/\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): MetaTokenLookupToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: MetaTokenLookupResult): MetaTokenLookupToolResult {\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/** The facts Asset read by symbol or by name, in the one shape the graph server admits. */\nexport function assetQuery(key: 'symbol' | 'name', value: string): string {\n return (\n `USE facts MATCH (t:Asset {${key}: \"${value}\"}) ` +\n 'RETURN t.asset_contract AS contract, t.asset_symbol AS symbol, t.name AS name, ' +\n 't.token_standard AS token_standard, t.decimals AS decimals, t.verified AS verified, ' +\n 't.verification_source AS verification_source, t.first_seen_timestamp AS first_seen_timestamp ' +\n `LIMIT ${ROWS_READ}`\n )\n}\n\n/** The topology read of who deployed one contract: the deploying address and the transaction's sender. */\nexport function creatorQuery(contract: string): string {\n return (\n `USE topology MATCH (f:Address)-[d:DEPLOYED_CONTRACT]->(t:Address {address: \"${contract}\"}) ` +\n 'RETURN f.address AS factory, d.tx_origin AS creator LIMIT 1'\n )\n}\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value : null\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 addressOrNull = (value: unknown): string | null =>\n typeof value === 'string' && ADDRESS_FORM.test(value.trim()) ? value.trim().toLowerCase() : null\n\nfunction verifiedOf(value: unknown): boolean {\n if (typeof value === 'boolean') return value\n if (typeof value === 'number') return value === 1\n if (typeof value === 'string') return ['true', '1'].includes(value.trim().toLowerCase())\n return false\n}\n\nfunction answerText(answer: GraphAnswer): string {\n return (Array.isArray(answer.content) ? answer.content : [])\n .map((block) => (isRecord(block) && typeof block.text === 'string' ? block.text : ''))\n .filter(Boolean)\n .join('\\n')\n .trim()\n}\n\ntype Refusal = { code: string; text: string; transient: boolean }\n\n/** A graph_query answer that did not answer: its code, its text, and whether the same read may answer later. */\nfunction refusalOf(answer: GraphAnswer): Refusal {\n const text = answerText(answer)\n const detail = isRecord(answer.structuredContent)\n ? answer.structuredContent.error_detail\n : undefined\n const detailCode = isRecord(detail) && typeof detail.code === 'string' ? detail.code : ''\n const detailClass = isRecord(detail) && typeof detail.class === 'string' ? detail.class : ''\n const named = detailCode || CODE_PREFIX.exec(text)?.[1] || ''\n // A refusal that names no class is a stop only when its code says so; a\n // refusal in plain words (\"unknown label Asset\") is a server that lacks the read.\n const transient = detailClass ? detailClass !== 'refused' : TRANSIENT_CODE.test(named)\n const code = named || 'not_served'\n return { code, text: text || `${code}: the graph endpoint refused the read`, transient }\n}\n\n/** The result rows of a graph_query answer, or null when it holds none. */\nfunction rowsOf(answer: GraphAnswer): Array<Record<string, unknown>> | null {\n const facts = isRecord(answer.structuredContent) ? answer.structuredContent.facts : undefined\n const query = isRecord(facts) ? facts.query : undefined\n const results = isRecord(query) ? query.results : undefined\n return Array.isArray(results) ? results.filter(isRecord) : null\n}\n\ntype Member = { id?: unknown; ok?: unknown; results?: unknown; error?: unknown }\n\nfunction membersOf(answer: GraphAnswer): 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\nfunction candidateOf(row: Record<string, unknown>): TokenCandidate | null {\n const contract = textOrNull(row.contract)?.trim().toLowerCase()\n if (!contract) return null\n const firstSeen = numberOrNull(row.first_seen_timestamp)\n return {\n contract,\n symbol: textOrNull(row.symbol),\n name: textOrNull(row.name),\n token_standard: textOrNull(row.token_standard),\n decimals: numberOrNull(row.decimals),\n verified: verifiedOf(row.verified),\n verification_source: textOrNull(row.verification_source),\n first_seen_timestamp: firstSeen,\n first_seen_timestamp_utc: isEpochMs(firstSeen) ? utcText(firstSeen) : null,\n creator: null,\n factory: null,\n }\n}\n\ntype Read =\n | { kind: 'rows'; rows: Array<Record<string, unknown>> }\n | { kind: 'not_served'; refusal: Refusal }\n | { kind: 'failed'; text: string }\n\nasync function readAssets(\n deps: TokenToolDependencies,\n network: string,\n key: 'symbol' | 'name',\n value: string\n): Promise<Read> {\n let answer: GraphAnswer\n try {\n answer = await deps.graphQuery({ network, query: assetQuery(key, value) })\n } catch (err) {\n return { kind: 'failed', text: deps.describeFailure(err) }\n }\n const rows = rowsOf(answer)\n if (answer.isError !== true && rows !== null) return { kind: 'rows', rows }\n const refusal = refusalOf(answer)\n if (answer.isError === true && refusal.transient) return { kind: 'failed', text: refusal.text }\n return { kind: 'not_served', refusal }\n}\n\n/**\n * The creator and the factory of each candidate, written in place. Returns why\n * some creators were not read, or null when every read answered. A read that\n * answered with no row leaves the candidate's creator empty with no note: the\n * graph holds no deployment for it.\n */\nasync function readCreators(\n deps: TokenToolDependencies,\n network: string,\n candidates: TokenCandidate[]\n): Promise<string | null> {\n const contracts = [\n ...new Set(candidates.map((c) => c.contract).filter((c) => CONTRACT_FORM.test(c))),\n ]\n const found = new Map<string, { creator: string | null; factory: string | null }>()\n const reasons: string[] = []\n let unread = candidates.length - candidates.filter((c) => CONTRACT_FORM.test(c.contract)).length\n for (let at = 0; at < contracts.length; at += CREATOR_BATCH_MAX) {\n const chunk = contracts.slice(at, at + CREATOR_BATCH_MAX)\n const queries = chunk.map((contract) => ({\n id: `creator:${contract}`,\n query: creatorQuery(contract),\n }))\n let members = new Map<string, Member>()\n try {\n const answer = await deps.graphQueryBatch({ network, queries })\n members = membersOf(answer)\n if (members.size === 0) {\n reasons.push(\n answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n )\n }\n } catch (err) {\n reasons.push(deps.describeFailure(err))\n }\n for (const contract of chunk) {\n const member = members.get(`creator:${contract}`)\n if (member?.ok === true && Array.isArray(member.results)) {\n const row = member.results.find(isRecord)\n found.set(contract, {\n creator: row ? addressOrNull(row.creator) : null,\n factory: row ? addressOrNull(row.factory) : null,\n })\n continue\n }\n unread += 1\n if (member && typeof member.error === 'string' && !reasons.includes(member.error))\n reasons.push(member.error)\n }\n }\n for (const candidate of candidates) {\n const read = found.get(candidate.contract)\n if (read) Object.assign(candidate, read)\n }\n if (unread === 0) return null\n return `${unread} of ${candidates.length}${reasons.length > 0 ? `: ${reasons.join('; ')}` : ''}`\n}\n\nconst NO_WEB =\n 'Do not search the web and do not guess a contract: a web page is not a contract on this network.'\n\nfunction hintFor(\n result: Omit<MetaTokenLookupResult, 'hint'>,\n creatorsNotRead: string | null\n): string {\n const { network, query, candidates, matched_on, truncated } = result\n const parts: string[] = [ANSWER_HINT]\n if (candidates.length === 0) {\n parts.push(\n `No contract on ${network} carries the symbol or the name \"${query}\". Say so in one line. ${NO_WEB} ` +\n 'Ask the user for the contract if they have one.'\n )\n return parts.join(' ')\n }\n if (matched_on === 'name') {\n parts.push(`No contract carries \"${query}\" as its symbol; these carry it as their name.`)\n }\n if (candidates.length === 1) {\n parts.push(\n `One contract on ${network} carries \"${query}\": ${candidates[0]!.contract}. ` +\n 'Say it is the only one on this network, then read it by this full contract on USE topology.'\n )\n } else {\n parts.push(\n `${candidates.length} contracts on ${network} carry \"${query}\"` +\n `${truncated ? `, and more exist than the ${CANDIDATES_MAX} listed` : ''}. ` +\n 'Tickers collide: never treat the first row as the token. Name them, each contract in full, ' +\n 'with its creator and first seen time, and ask which one the user means, or pick one by the evidence the user gave ' +\n '(a creator, a launch date, a price move) and say why.'\n )\n }\n if (creatorsNotRead) {\n parts.push(\n `The creators were not read for ${creatorsNotRead}. creator and factory are empty there because the read failed, ` +\n 'not because the chain holds none.'\n )\n }\n parts.push('Write every contract and creator in full, 0x plus 40 hex characters.')\n return parts.join(' ')\n}\n\n/** meta_token_lookup, {network, symbol}. Every argument is checked before a read is sent. */\nexport async function handleMetaTokenLookup(\n args: unknown,\n deps: TokenToolDependencies\n): Promise<MetaTokenLookupToolResult> {\n const record = isRecord(args) ? args : {}\n let network: string\n try {\n network = normalizeDexNetwork(record.network)\n } catch (err) {\n return errorResult(\n err instanceof DexRegistryError ? err.message : `invalid_network: ${(err as Error).message}`\n )\n }\n if (typeof record.symbol !== 'string' || record.symbol.trim() === '') {\n return errorResult(\n 'invalid_symbol: symbol is required: the ticker or the name as the user wrote it, for example TCITY'\n )\n }\n const symbol = record.symbol.trim()\n if (symbol.length > SYMBOL_MAX) {\n return errorResult(`invalid_symbol: symbol holds at most ${SYMBOL_MAX} characters`)\n }\n const base = {\n schema: META_TOKEN_LOOKUP_SCHEMA,\n network,\n query: symbol,\n }\n\n if (ADDRESS_FORM.test(symbol)) {\n const address = symbol.toLowerCase()\n return textResult({\n ...base,\n matched_on: null,\n candidates: [],\n total: 0,\n truncated: false,\n hint: `${ANSWER_HINT} ${address} is a contract address, not a ticker: ${ADDRESS_INPUT_HINT}. Send no token lookup for it.`,\n })\n }\n if (unsafeLiteral(symbol)) {\n return errorResult(\n 'invalid_symbol: a symbol holds no double quote, backslash or control character. Send the ticker or the name as plain text.'\n )\n }\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No token read was sent: ${unavailable} The lookup has no answer yet, which is not \"no contract\": try again later, or ask the user for the contract. ${NO_WEB}`\n )\n }\n\n let matchedOn: 'symbol' | 'name' = 'symbol'\n let read = await readAssets(deps, network, 'symbol', symbol)\n if (read.kind === 'rows' && read.rows.length === 0) {\n matchedOn = 'name'\n read = await readAssets(deps, network, 'name', symbol)\n }\n if (read.kind === 'failed') {\n return errorResult(\n `The token read failed: ${read.text} This is not \"no contract\": send the same lookup again once, or ask the user for the contract. ${NO_WEB}`\n )\n }\n if (read.kind === 'not_served') {\n return textResult({\n ...base,\n matched_on: null,\n candidates: [],\n total: 0,\n truncated: false,\n hint:\n `${ANSWER_HINT} This Chain Insights server does not serve the token lookup yet (${read.refusal.code}). ` +\n `That is not \"no contract carries ${symbol}\": ask the user for the token's contract, 0x plus 40 hex characters. ${NO_WEB}`,\n })\n }\n\n const total = read.rows.length\n const candidates = read.rows\n .slice(0, CANDIDATES_MAX)\n .map(candidateOf)\n .filter((candidate): candidate is TokenCandidate => candidate !== null)\n const creatorsNotRead =\n candidates.length > 0 ? await readCreators(deps, network, candidates) : null\n const result = {\n ...base,\n matched_on: candidates.length > 0 ? matchedOn : null,\n candidates,\n total,\n truncated: total > CANDIDATES_MAX,\n }\n return textResult({ ...result, hint: hintFor(result, creatorsNotRead) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAa,yBAAyB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,KAAK,QAAQ,KAAK,sCAChE,OAAO,uEAAuE;CACtH,CAAC;CAGH,MAAM,QAAQ,KAAK,KAAK;CACxB,MAAM,aAAa,KAAK,KACrB,MAAM,GAAG,cAAc,CAAC,CACxB,IAAI,WAAW,CAAC,CAChB,QAAQ,cAA2C,cAAc,IAAI;CACxE,MAAM,kBACJ,WAAW,SAAS,IAAI,MAAM,aAAa,MAAM,SAAS,UAAU,IAAI;CAC1E,MAAM,SAAS;EACb,GAAG;EACH,YAAY,WAAW,SAAS,IAAI,YAAY;EAChD;EACA;EACA,WAAW,QAAQ;CACrB;CACA,OAAO,WAAW;EAAE,GAAG;EAAQ,MAAM,QAAQ,QAAQ,eAAe;CAAE,CAAC;AACzE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tool-visibility-Dy3psowS.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 // A local tool of the proxy (src/mcp/token-lookup.ts): the contracts of a ticker.\n meta_token_lookup: ['network', 'symbol'],\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;EAA6B;CAAY;CAEnF,iBAAiB;EAA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