chain-insights 0.85.2 → 0.92.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +2 -0
  2. package/bin/install.cjs +2 -1
  3. package/dist/{active-q3yViZhc.cjs → active-COPA14FA.cjs} +2 -16
  4. package/dist/{active-D2aabYRF.mjs → active-CyC4jFka.mjs} +2 -7
  5. package/dist/{active-D2aabYRF.mjs.map → active-CyC4jFka.mjs.map} +1 -1
  6. package/dist/address-card-C-NB03XP.cjs +218 -0
  7. package/dist/address-card-LYaT5yz0.mjs +190 -0
  8. package/dist/address-card-LYaT5yz0.mjs.map +1 -0
  9. package/dist/address-risk-DPuXBsvH.cjs +806 -0
  10. package/dist/address-risk-Da6FsfGx.mjs +653 -0
  11. package/dist/address-risk-Da6FsfGx.mjs.map +1 -0
  12. package/dist/{capabilities-Mxa4oQdd.cjs → capabilities-DkNreyv7.cjs} +1 -1
  13. package/dist/{capabilities-bZOr5Ads.mjs → capabilities-w5bNR7F9.mjs} +2 -2
  14. package/dist/{capabilities-bZOr5Ads.mjs.map → capabilities-w5bNR7F9.mjs.map} +1 -1
  15. package/dist/cli.cjs +138 -46
  16. package/dist/cli.mjs +138 -46
  17. package/dist/cli.mjs.map +1 -1
  18. package/dist/{deployer-screen-B5yrXZGo.mjs → deployer-screen-Bkw_sz94.mjs} +3 -3
  19. package/dist/{deployer-screen-B5yrXZGo.mjs.map → deployer-screen-Bkw_sz94.mjs.map} +1 -1
  20. package/dist/{deployer-screen-0SOQ_HFf.cjs → deployer-screen-CFLi7OeH.cjs} +2 -2
  21. package/dist/{dex-registry-BY67f4Ul.mjs → dex-registry-Bkri0--q.mjs} +10 -2
  22. package/dist/{dex-registry-BY67f4Ul.mjs.map → dex-registry-Bkri0--q.mjs.map} +1 -1
  23. package/dist/{dex-registry-BhGJUG9_.cjs → dex-registry-CyR3GyRr.cjs} +20 -0
  24. package/dist/{dex-tool-7BK_gD6H.mjs → dex-tool-D0K_Qx4N.mjs} +4 -4
  25. package/dist/dex-tool-D0K_Qx4N.mjs.map +1 -0
  26. package/dist/{dex-tool-Be9NAuD8.cjs → dex-tool-DQ5Eg0LO.cjs} +3 -3
  27. package/dist/{exchange-deposit-check-C5MseGlZ.cjs → exchange-deposit-check-BNzkwQeW.cjs} +18 -18
  28. package/dist/{exchange-deposit-check-CXHZCHWW.mjs → exchange-deposit-check-DIALj2sm.mjs} +19 -19
  29. package/dist/exchange-deposit-check-DIALj2sm.mjs.map +1 -0
  30. package/dist/{exchange-registry-CT0rRW__.cjs → exchange-registry-CEgkeQV1.cjs} +16 -93
  31. package/dist/{exchange-registry-CoLgHw6d.mjs → exchange-registry-Dr5UtcT5.mjs} +17 -94
  32. package/dist/exchange-registry-Dr5UtcT5.mjs.map +1 -0
  33. package/dist/{exchange-tool-Dc46SJ49.mjs → exchange-tool-B7E29YoQ.mjs} +4 -4
  34. package/dist/exchange-tool-B7E29YoQ.mjs.map +1 -0
  35. package/dist/{exchange-tool-B2SMeC5f.cjs → exchange-tool-CXaUBAd2.cjs} +3 -3
  36. package/dist/{graph-schema-CcrYPpSv.cjs → graph-schema-Bn3txQCj.cjs} +115 -12
  37. package/dist/{graph-schema-CRQuKya1.mjs → graph-schema-DvABR1yl.mjs} +97 -12
  38. package/dist/graph-schema-DvABR1yl.mjs.map +1 -0
  39. package/dist/{layer-routing-YDj-ynG9.cjs → layer-routing-j48SQ8Wk.cjs} +2 -2
  40. package/dist/{layer-routing-DCJVNN6O.mjs → layer-routing-r4IbIQSr.mjs} +3 -3
  41. package/dist/layer-routing-r4IbIQSr.mjs.map +1 -0
  42. package/dist/mcp-proxy.cjs +62 -15
  43. package/dist/mcp-proxy.d.cts.map +1 -1
  44. package/dist/mcp-proxy.d.mts.map +1 -1
  45. package/dist/mcp-proxy.mjs +62 -15
  46. package/dist/mcp-proxy.mjs.map +1 -1
  47. package/dist/public-file-BISyAesm.mjs +133 -0
  48. package/dist/public-file-BISyAesm.mjs.map +1 -0
  49. package/dist/public-file-DDp2CrUl.cjs +138 -0
  50. package/dist/{request-timeout-DxwNijQD.cjs → request-timeout-BXiIt9Jy.cjs} +0 -1
  51. package/dist/{request-timeout-K3ljP0pa.mjs → request-timeout-DetG2xO4.mjs} +2 -2
  52. package/dist/{request-timeout-K3ljP0pa.mjs.map → request-timeout-DetG2xO4.mjs.map} +1 -1
  53. package/dist/{token-lookup-Cf59VdGe.mjs → token-lookup-Ck0q7crJ.mjs} +2 -2
  54. package/dist/{token-lookup-Cf59VdGe.mjs.map → token-lookup-Ck0q7crJ.mjs.map} +1 -1
  55. package/dist/{token-lookup-DqjSRIxd.cjs → token-lookup-DLe4erP9.cjs} +1 -1
  56. package/dist/token-risk-CpMfFRoY.cjs +1004 -0
  57. package/dist/token-risk-DhnJc2kJ.mjs +971 -0
  58. package/dist/token-risk-DhnJc2kJ.mjs.map +1 -0
  59. package/dist/{tool-visibility-D8Up081E.cjs → tool-visibility-BCa-tmyZ.cjs} +11 -2
  60. package/dist/{tool-visibility-DuTds7V4.mjs → tool-visibility-BstrSl4s.mjs} +12 -3
  61. package/dist/tool-visibility-BstrSl4s.mjs.map +1 -0
  62. package/docs/contributing.md +10 -8
  63. package/docs/development.md +5 -5
  64. package/docs/evals.md +16 -1
  65. package/docs/graph-query-compatibility.md +15 -2
  66. package/docs/graph-tools.md +44 -6
  67. package/docs/mcp-proxy.md +189 -8
  68. package/docs/stability.md +4 -5
  69. package/docs/testing.md +76 -0
  70. package/package.json +1 -1
  71. package/registry/README.md +20 -5
  72. package/registry/address-card.json +680 -0
  73. package/skills/chain-insights-address-risk/SKILL.md +61 -0
  74. package/skills/chain-insights-address-risk/agents/openai.yaml +4 -0
  75. package/skills/chain-insights-aml-exchange/SKILL.md +9 -7
  76. package/skills/chain-insights-cypher/SKILL.md +79 -3
  77. package/skills/chain-insights-token-risk/SKILL.md +81 -0
  78. package/skills/chain-insights-token-risk/agents/openai.yaml +4 -0
  79. package/skills/chain-insights-virtuals/reference.md +1 -1
  80. package/dist/dex-tool-7BK_gD6H.mjs.map +0 -1
  81. package/dist/exchange-deposit-check-CXHZCHWW.mjs.map +0 -1
  82. package/dist/exchange-registry-CoLgHw6d.mjs.map +0 -1
  83. package/dist/exchange-tool-Dc46SJ49.mjs.map +0 -1
  84. package/dist/graph-schema-CRQuKya1.mjs.map +0 -1
  85. package/dist/layer-routing-DCJVNN6O.mjs.map +0 -1
  86. package/dist/public-tools-CBszU2oX.cjs +0 -1334
  87. package/dist/public-tools-DVhUjSDV.mjs +0 -1333
  88. package/dist/public-tools-DVhUjSDV.mjs.map +0 -1
  89. package/dist/tool-visibility-DuTds7V4.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"address-risk-Da6FsfGx.mjs","names":["ADDRESS_INPUT"],"sources":["../src/mcp/risk-word.ts","../src/mcp/row-values.ts","../src/mcp/address-risk.ts"],"sourcesContent":["/**\n * The risk word of an address: the one fixed rule every risk answer applies.\n *\n * Two signals sit on an :Address node of the graph:\n *\n * rules the card's entries (identity, evidence, judgements), each a word the\n * card dictionary (registry/address-card.json, list `words`) gives a\n * level, a standing and a plain sentence;\n * model the risk model's `risk_level` (HIGH, MEDIUM, LOW, or unscored) and\n * its `risk_score`, a number from 0 to 1.\n *\n * The word of the answer is the higher of the two. A label word is never\n * lowered by the model, and only a label gives `critical`. An address no label\n * and no model speaks about is `unscored`, which is neither `low` nor safe.\n *\n * The word is computed here from the entries, never taken from the node's own\n * `risk` property: a card resolved with an older dictionary may still hold the\n * level a word had then. Pure: no read, no clock.\n */\n\nimport type { AddressCardLevel, AddressCardWord } from './address-card.js'\n\n/** The levels, lowest first: critical > high > medium > low > none. */\nexport const RISK_LEVELS = ['none', 'low', 'medium', 'high', 'critical'] as const satisfies readonly AddressCardLevel[]\nexport type RiskLevel = (typeof RISK_LEVELS)[number]\n\n/** The words an answer's risk may carry. */\nexport const RISK_WORDS = ['critical', 'high', 'medium', 'low', 'unscored'] as const\nexport type RiskWord = (typeof RISK_WORDS)[number]\n\n/** The model's word: it never gives critical. */\nexport const MODEL_WORDS = ['high', 'medium', 'low', 'not_scored'] as const\nexport type ModelWord = (typeof MODEL_WORDS)[number]\n\n/** Who set the word: the labels, the model, both at the same level, or nobody (unscored). */\nexport type SetBy = 'rules' | 'model' | 'both' | 'none'\n\n/** The questions whose words give the rules word. A judgement's level is always none today. */\nexport const RULES_QUESTIONS = ['evidence', 'identity', 'judgement'] as const\n\n/**\n * A word whose dictionary item answers the question `judgement` reaches a\n * reader as `pattern`, with its value: a judgement shows a pattern and accuses\n * nobody. That holds for `suspect:FAKE_TOKEN` and for `scam:FAKE_TOKEN` alike.\n */\nexport const JUDGEMENT_WORD_SHOWN = 'pattern'\n\n/** Why the word is what it is: one card entry, or the model. */\nexport interface Reason {\n word: string\n value?: string\n question: string\n standing?: string\n level: RiskLevel\n plain: string\n}\n\nexport interface Risk {\n word: RiskWord\n score: number | null\n rules_word: RiskLevel\n model_word: ModelWord\n set_by: SetBy\n}\n\nexport function levelRank(level: RiskLevel): number {\n return RISK_LEVELS.indexOf(level)\n}\n\n/** The rank of an answer's word: unscored below low, so any spoken word outranks it. */\nexport function riskWordRank(word: RiskWord): number {\n return word === 'unscored' ? -1 : levelRank(word)\n}\n\nconst isLevel = (value: unknown): value is RiskLevel =>\n (RISK_LEVELS as readonly unknown[]).includes(value)\n\n/** One card entry split at its first colon: `word` or `word:VALUE`. A value may hold colons. */\nexport function splitCardEntry(entry: string): { word: string; value: string | null } {\n const text = entry.trim()\n const cut = text.indexOf(':')\n if (cut < 0) return { word: text, value: null }\n const value = text.slice(cut + 1).trim()\n return { word: text.slice(0, cut).trim(), value: value === '' ? null : value }\n}\n\n/**\n * The dictionary item of one card entry, by word and value only, whatever\n * card list the entry came from: the item of the same word and the same value\n * (compared without case), else the item of that word with no value. Null for\n * a word the dictionary does not hold. The item's question is the entry's:\n * the graph writes `scam:FAKE_TOKEN_LP` in `evidence`, and the dictionary\n * says it is a judgement of level none.\n */\nexport function cardWordOf(\n entry: string,\n dictionaryWords: readonly AddressCardWord[]\n): AddressCardWord | null {\n const { word, value } = splitCardEntry(entry)\n if (word === '') return null\n const wanted = word.toLowerCase()\n const items = dictionaryWords.filter((item) => item.word.toLowerCase() === wanted)\n if (value !== null) {\n const exact = items.find((item) => item.value?.toLowerCase() === value.toLowerCase())\n if (exact) return exact\n }\n return items.find((item) => item.value === undefined) ?? null\n}\n\n/**\n * The reason of one card entry, or null for a word the dictionary does not\n * hold. Its question, level, standing and plain sentence are the dictionary\n * item's; the value is the entry's own, as the card wrote it.\n */\nexport function reasonOf(\n entry: string,\n dictionaryWords: readonly AddressCardWord[]\n): Reason | null {\n const item = cardWordOf(entry, dictionaryWords)\n if (!item || !isLevel(item.level)) return null\n const { word, value } = splitCardEntry(entry)\n const shown = item.question === 'judgement' ? JUDGEMENT_WORD_SHOWN : word.toLowerCase()\n return {\n word: shown,\n ...(value !== null ? { value } : {}),\n question: item.question,\n ...(item.standing ? { standing: item.standing } : {}),\n level: item.level,\n plain: item.plain,\n }\n}\n\n/** The highest level among the reasons of the rules questions; none when no reason carries one. */\nexport function rulesWordOf(reasons: readonly Reason[]): RiskLevel {\n let best: RiskLevel = 'none'\n for (const reason of reasons) {\n if (!(RULES_QUESTIONS as readonly string[]).includes(reason.question)) continue\n if (levelRank(reason.level) > levelRank(best)) best = reason.level\n }\n return best\n}\n\n/** The model's word from the node's risk_level: HIGH, MEDIUM, LOW in any case; anything else is not_scored. */\nexport function modelWordOf(riskLevel: unknown): ModelWord {\n const level = typeof riskLevel === 'string' ? riskLevel.trim().toLowerCase() : ''\n return level === 'high' || level === 'medium' || level === 'low' ? level : 'not_scored'\n}\n\n/** The model's number, unchanged: a finite number from 0 to 1, else null. */\nexport function modelScoreOf(riskScore: unknown): number | null {\n const score =\n typeof riskScore === 'number'\n ? riskScore\n : typeof riskScore === 'string' && riskScore.trim() !== ''\n ? Number(riskScore)\n : Number.NaN\n return Number.isFinite(score) && score >= 0 && score <= 1 ? score : null\n}\n\n/** The one sentence of the model's reason per level: the same for every address. */\nexport const MODEL_REASON_PLAIN: Record<Exclude<ModelWord, 'not_scored'>, string> = {\n high: 'The risk model scores this address high.',\n medium: 'The risk model scores this address medium.',\n low: 'The risk model scores this address low.',\n}\n\n/** The reason a model-set word carries: a prediction, and said as one. */\nexport function modelReasonOf(modelWord: Exclude<ModelWord, 'not_scored'>): Reason {\n return {\n word: 'model',\n question: 'model',\n standing: 'predicted',\n level: modelWord,\n plain: MODEL_REASON_PLAIN[modelWord],\n }\n}\n\n/**\n * The word: the higher of the rules word and the model word. `unscored` when\n * neither speaks. The score is the model's, never one made for a label.\n */\nexport function riskOf(input: {\n rulesWord: RiskLevel\n modelWord: ModelWord\n score: number | null\n}): Risk {\n const { rulesWord, modelWord } = input\n const score = modelScoreOf(input.score)\n if (rulesWord === 'none' && modelWord === 'not_scored') {\n return { word: 'unscored', score, rules_word: rulesWord, model_word: modelWord, set_by: 'none' }\n }\n const rules = levelRank(rulesWord)\n const model = modelWord === 'not_scored' ? levelRank('none') : levelRank(modelWord)\n // Either side speaks here, so the top level is above none.\n const setBy: SetBy =\n modelWord === 'not_scored' || rules > model ? 'rules' : model > rules ? 'model' : 'both'\n const top = RISK_LEVELS[Math.max(rules, model)] as Exclude<RiskLevel, 'none'>\n return {\n word: top,\n score,\n rules_word: rulesWord,\n model_word: modelWord,\n set_by: setBy,\n }\n}\n","/**\n * The values of one graph answer row, read the same way by every risk tool:\n * a list of words, a number, a text, a full address, an epoch time as UTC\n * text, and the rows and refusal of one batch member. Pure: no read.\n */\n\nimport { isEpochMs, utcText } from './timestamp-text.js'\nimport { refusalOf, type Member } from './token-lookup.js'\n\nconst ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/\n\n/** The refusal codes a member's text may name anywhere in it. */\nconst NAMED_CODE = /\\b(query_timeout|family_behind|anchor_missing)\\b/\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** The non-empty strings of a list, trimmed; [] for anything else. */\nexport const strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === 'string' && v.trim() !== '').map((v) => v.trim())\n : []\n\n/** A finite number, or a text that holds one; null for anything else. */\nexport const 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\nexport const textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() !== '' ? value.trim() : null\n\n/** A full 0x address in lowercase, or null. */\nexport const addressOrNull = (value: unknown): string | null =>\n typeof value === 'string' && ADDRESS_INPUT.test(value.trim()) ? value.trim().toLowerCase() : null\n\n/** The UTC text of an epoch-millisecond time, or null. */\nexport const utcOrNull = (value: unknown): string | null => {\n const ms = numberOrNull(value)\n return isEpochMs(ms) ? utcText(ms) : null\n}\n\nexport const memberAnswered = (member: Member | undefined): boolean =>\n member?.ok === true && Array.isArray(member.results)\n\nexport const memberRows = (member: Member | undefined): Array<Record<string, unknown>> =>\n memberAnswered(member) ? (member!.results as unknown[]).filter(isRecord) : []\n\n/** Why a member did not answer: its code, as a refusal names it, and its text. */\nexport function memberRefusal(id: string, member: Member | undefined): { code: string; reason: string } {\n if (!member) return { code: 'not_answered', reason: `the ${id} read is missing from the batch answer` }\n const text = typeof member.error === 'string' ? member.error.trim() : ''\n if (text === '') return { code: 'not_answered', reason: `the ${id} read did not answer` }\n const refusal = refusalOf({ content: [{ type: 'text', text }] })\n // A member's text may name its code after a prefix (\"read failed: query_timeout ...\"):\n // the code it names wins over not_served.\n const named = refusal.code === 'not_served' ? NAMED_CODE.exec(text)?.[1] : undefined\n return { code: named ?? refusal.code, reason: refusal.text }\n}\n","/**\n * aml_address_risk: who is this address, and how risky is it?\n *\n * A local tool of the proxy. It sends one graph_query_batch with three reads\n * on USE topology, all anchored on the address:\n *\n * node the address: its node labels and its card (identity, roles,\n * behaviour, evidence, judgements, sources, card_version), the risk\n * model's `risk_level` and `risk_score`, and its exchange role;\n * in its senders: the newest FLOWED_TO links into it worth 1 USD or more,\n * with each sender's own card words (identities included) and model\n * level;\n * out its receivers: the same, out of it.\n *\n * The risk word is the higher of what the labels prove (rules) and what the\n * risk model predicts (model), computed by src/mcp/risk-word.ts from the card\n * entries and the card dictionary. The partners' words are computed by the\n * same rule from their own rows, and never change the address's word.\n *\n * The tool states, the host judges: the answer holds facts and measures, no\n * summary, no advice and no verdict. The only prose is each reason's fixed\n * plain sentence from the card dictionary.\n *\n * `addressRiskQueries` and `addressRiskFromMembers` are the address answer of\n * every risk tool: a tool that names many addresses batches their reads under\n * a prefix each, and builds each answer with the same code.\n */\n\nimport type { AddressCardWord, LoadedAddressCard } from './address-card.js'\nimport { DexRegistryError, normalizeDexNetwork } from './dex-registry.js'\nimport {\n exchangeOfLabels,\n exchangeOfWallet,\n type ExchangeEntry,\n type LoadedExchangeRegistry,\n} from './exchange-registry.js'\nimport { exchangeRoleRead } from './graph-schema.js'\nimport {\n levelRank,\n modelReasonOf,\n modelScoreOf,\n modelWordOf,\n reasonOf,\n riskOf,\n riskWordRank,\n rulesWordOf,\n splitCardEntry,\n type ModelWord,\n type Reason,\n type RiskWord,\n type SetBy,\n} from './risk-word.js'\nimport {\n addressOrNull,\n isRecord,\n memberAnswered,\n memberRefusal,\n memberRows,\n numberOrNull,\n strings,\n textOrNull,\n utcOrNull,\n} from './row-values.js'\nimport { membersOf, refusalOf, type GraphAnswer, type Member } from './token-lookup.js'\n\nexport const AML_ADDRESS_RISK_TOOL = 'aml_address_risk' as const\nexport const AML_ADDRESS_RISK_SCHEMA = 'chain-insights.aml-address-risk.v2' as const\nexport const AML_ADDRESS_RISK_TITLE = 'Address risk'\n\n/** How a host reads the answer: the one text every host reads, in the tool description. */\nexport const ADDRESS_RISK_READING_RULE =\n 'The tool states facts and measures; you write the judgement: say which reasons you rely on, ' +\n 'say when the word comes from the model alone (set_by model) that it is a prediction, never call an address safe, ' +\n 'and name a part listed in not_read as not read.'\n\nexport const AML_ADDRESS_RISK_DESCRIPTION =\n 'Answers who one address is and how risky it is: its identity, wallet roles and behaviour, its risk word with every reason, ' +\n 'the risk model level and score, the partners it exchanged money with (1 USD or more, the 25 newest each way) that carry a risk word of medium or above, ' +\n 'and the exchange wallets its money came from or reached. Three reads anchored on the address, in two calls (the node first), billed as any read. ' +\n 'risk.word is the higher of what labels prove (rules_word) and what the risk model predicts (model_word); critical comes only from a label. ' +\n 'risk.score is the model number from 0 to 1, or null: a label never makes a number. ' +\n 'unscored means neither labels nor the model speak about the address: it is not low and not safe. ' +\n 'A risky partner is listed beside the word and never changes it. ' +\n 'A hub (more than 50,000 links, such as the zero address or a pool manager) has its counterparties not ranked: exposure.hub is true, counterparties_read is 0, and not_read names counterparties; ask about one counterparty, or one token, instead. ' +\n `${ADDRESS_RISK_READING_RULE} ` +\n 'Write every address in full, all 42 characters. Pass surroundings: true for the nodes and money links behind the answer, to draw.'\n\nexport const AML_ADDRESS_RISK_ANNOTATIONS = {\n readOnlyHint: true,\n idempotentHint: true,\n openWorldHint: false,\n} as const\nexport const AML_ADDRESS_RISK_ARGS = ['network', 'address', 'surroundings'] as const\n\n/** The partners kept per direction, the newest first. One more is read to know whether more exist. */\nexport const PARTNER_LIMIT = 25\n/** The money floor of a partner link, in USD: a link under it is dust, filtered by the read. */\nexport const EXPOSURE_FLOOR_USD = 1\n/** The most nodes the surroundings carry. */\nexport const SURROUNDINGS_NODE_LIMIT = 60\n/** The addresses that are never a partner: tokens minted from and burned to them. */\nexport const ZERO_ADDRESSES = [\n '0x0000000000000000000000000000000000000000',\n '0x000000000000000000000000000000000000dead',\n] as const\n\nexport type AddressKind = 'account' | 'contract' | 'token' | 'pool' | 'unknown'\nexport type PartnerDirection = 'sent_to_subject' | 'received_from_subject'\nexport type NotReadPart = 'senders' | 'receivers' | 'counterparties'\n\nexport interface AddressRisk {\n word: RiskWord\n score: number | null\n rules_word: string\n model_word: ModelWord\n set_by: SetBy\n reasons: Reason[]\n /** Card words the dictionary does not hold: listed, they set nothing. */\n unknown_words: string[]\n /** The dictionary version that resolved the card on the graph, or null. */\n card_version: string | null\n}\n\nexport interface ModelScore {\n level: ModelWord\n score: number | null\n scored: boolean\n}\n\nexport interface RiskyPartner {\n address: string\n direction: PartnerDirection\n risk_word: RiskWord\n set_by: SetBy\n reasons: Reason[]\n tokens_worth_usd: number | null\n tx_count: number | null\n first_seen_utc: string | null\n last_seen_utc: string | null\n}\n\nexport interface ExchangeEnd {\n address: string\n direction: PartnerDirection\n /** The exchange id, from the lookup file, else the name on the card. */\n exchange: string | null\n exchange_role: string | null\n tokens_worth_usd: number | null\n first_seen_utc: string | null\n last_seen_utc: string | null\n}\n\nexport interface Exposure {\n floor_usd: typeof EXPOSURE_FLOOR_USD\n /** True for a hub (more than HUB_DEGREE links): its counterparties are not ranked, and none is read. */\n hub: boolean\n /** The address's link count on its node, when the node carries it. */\n degree_total: number | null\n /** Partner links kept: worth 1 USD or more, not a token contract, not a zero address. */\n counterparties_read: number\n /** Partner links read and dropped: a token contract or a zero address. */\n left_out: number\n /** True when a direction had more partners than PARTNER_LIMIT. */\n truncated: boolean\n with_risk: RiskyPartner[]\n /** Kept partners with at least one pattern fact and no word of medium or above. */\n pattern_partners: number\n}\n\nexport interface NotRead {\n part: NotReadPart\n code: string\n reason: string\n}\n\nexport interface SurroundingsNode {\n address: string\n role: 'subject' | 'partner' | 'exchange_end'\n kind: AddressKind\n name: string | null\n risk_word: RiskWord\n model_level: ModelWord\n}\n\nexport interface SurroundingsLink {\n from_address: string\n to_address: string\n link: 'FLOWED_TO'\n tokens_worth_usd: number | null\n first_seen_utc: string | null\n last_seen_utc: string | null\n}\n\nexport interface Surroundings {\n nodes: SurroundingsNode[]\n links: SurroundingsLink[]\n truncated: boolean\n}\n\nexport interface AmlAddressRiskResult {\n schema: typeof AML_ADDRESS_RISK_SCHEMA\n tool: typeof AML_ADDRESS_RISK_TOOL\n network: string\n address: string\n /** false when the graph holds no node for the address. */\n found: boolean\n kind: AddressKind\n identity: { word: string; name: string | null } | null\n roles: string[]\n behaviour: string | null\n risk: AddressRisk\n model: ModelScore\n /** Null when the address is not found. */\n exposure: Exposure | null\n exchange_ends: ExchangeEnd[]\n not_read: NotRead[]\n surroundings?: Surroundings\n}\n\nexport interface AddressRiskDependencies {\n /** The card dictionary: the fresh cache, the public file, or the packaged copy. */\n loadAddressCard: () => Promise<LoadedAddressCard | null>\n loadExchangeRegistry: (network: string) => Promise<LoadedExchangeRegistry>\n graphQueryBatch: (args: {\n network: string\n queries: Array<{ id: string; query: string }>\n }) => Promise<GraphAnswer>\n unavailable?: () => Promise<string | undefined> | string | undefined\n describeFailure: (err: unknown) => string\n}\n\nexport type AmlAddressRiskToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError: boolean\n}\n\n/** A full address as a caller may type it: 0x plus 40 hex characters, any case. */\nexport const ADDRESS_INPUT = /^0x[0-9a-fA-F]{40}$/\nconst ADDRESS_READ = /^0x[0-9a-f]{40}$/\n\nexport function assertReadAddress(address: string): void {\n if (!ADDRESS_READ.test(address)) {\n throw new Error(`address risk: ${JSON.stringify(address)} is not a lowercase 0x address`)\n }\n}\n\n/**\n * The node read: the card, the model's level and score, and the exchange role.\n * `extra` adds columns of the node `a` (a token's standard, a pool's sums).\n */\nexport function addressNodeQuery(address: string, extra: readonly string[] = []): string {\n assertReadAddress(address)\n const more = extra.length > 0 ? `, ${extra.join(', ')}` : ''\n return (\n `USE topology MATCH (a:Address {address: \"${address}\"}) ` +\n 'RETURN labels(a) AS node_labels, a.card_version AS card_version, a.identity AS identity, a.identity_name AS identity_name, ' +\n 'a.identities AS identities, a.address_roles AS address_roles, a.behaviour AS behaviour, a.evidence AS evidence, ' +\n 'a.judgements AS judgements, a.sources AS sources, a.risk_level AS risk_level, a.risk_score AS risk_score, ' +\n `${exchangeRoleRead('a')} AS exchange_role, a.degree_total AS degree_total, a.degree_out AS degree_out${more} LIMIT 1`\n )\n}\n\n/**\n * A hub has more links than this. Ranking a hub's money links by amount is\n * what costs (9 s for the zero address, 17.6 s for a pool manager, against\n * under 3.5 s for every other case measured): a hub's partner reads are not\n * sent, and its counterparties are not ranked.\n */\nexport const HUB_DEGREE = 50_000\n\n/** The link count of a hub node, or null: a node whose degree is missing is not a hub. */\nexport function hubDegreeOf(row: Record<string, unknown> | undefined): number | null {\n const degree = numberOrNull(row?.degree_total)\n return degree !== null && degree > HUB_DEGREE ? degree : null\n}\n\n/** The not-read entry of a hub's counterparties: what to ask instead. */\nexport function hubNotRead(degree: number): NotRead {\n return {\n part: 'counterparties',\n code: 'hub',\n reason: `This address has ${degree} links. Its counterparties are not ranked: ask about one counterparty, or one token.`,\n }\n}\n\n/** A partner read: the newest money links of one direction, one more than kept. */\nexport function addressPartnerQuery(address: string, direction: 'in' | 'out'): string {\n assertReadAddress(address)\n const anchor = `(a:Address {address: \"${address}\"})`\n const match =\n direction === 'in'\n ? `(b:Address)-[f:FLOWED_TO]->${anchor}`\n : `${anchor}-[f:FLOWED_TO]->(b:Address)`\n return (\n `USE topology MATCH ${match} WHERE f.amount_usd_sum >= ${EXPOSURE_FLOOR_USD} ` +\n 'RETURN b.address AS address, labels(b) AS node_labels, b.identity AS identity, b.identity_name AS identity_name, ' +\n 'b.identities AS identities, ' +\n 'b.evidence AS evidence, b.judgements AS judgements, b.risk_level AS risk_level, ' +\n `${exchangeRoleRead('b')} AS exchange_role, ` +\n 'f.amount_usd_sum AS tokens_worth_usd, f.tx_count AS tx_count, ' +\n 'f.first_seen_timestamp AS first_seen_timestamp, f.last_seen_timestamp AS last_seen_timestamp ' +\n `ORDER BY f.last_seen_timestamp DESC LIMIT ${PARTNER_LIMIT + 1}`\n )\n}\n\n/** The three batch members of one address, their ids under `prefix`: `${prefix}node`, `${prefix}in`, `${prefix}out`. */\nexport function addressRiskQueries(\n address: string,\n prefix = ''\n): Array<{ id: string; query: string }> {\n return [\n { id: `${prefix}node`, query: addressNodeQuery(address) },\n { id: `${prefix}in`, query: addressPartnerQuery(address, 'in') },\n { id: `${prefix}out`, query: addressPartnerQuery(address, 'out') },\n ]\n}\n\nconst answered = memberAnswered\nconst rowsOf = memberRows\n\nfunction notReadOf(part: NotReadPart, id: string, member: Member | undefined): NotRead {\n return { part, ...memberRefusal(id, member) }\n}\n\n/** The kind of an address from its node labels: Pool wins over Token over Contract over Account. */\nexport function kindOf(nodeLabels: readonly string[]): AddressKind {\n if (nodeLabels.includes('Pool')) return 'pool'\n if (nodeLabels.includes('Token')) return 'token'\n if (nodeLabels.includes('Contract')) return 'contract'\n if (nodeLabels.includes('Account')) return 'account'\n return 'unknown'\n}\n\n/**\n * The reasons and the word of one row: the top identity, every other identity\n * word that carries a level, the entries of evidence and judgements, and the\n * model level. Each entry is read by the dictionary, whatever list it came from.\n */\nexport function rowRisk(\n row: Record<string, unknown> | undefined,\n dictionary: readonly AddressCardWord[]\n): Omit<AddressRisk, 'card_version'> {\n const reasons: Reason[] = []\n const unknown: string[] = []\n const take = (entry: string, keep: (reason: Reason) => boolean = () => true) => {\n const reason = reasonOf(entry, dictionary)\n if (reason) {\n if (keep(reason)) reasons.push(reason)\n } else {\n const { word } = splitCardEntry(entry)\n if (word !== '' && !unknown.includes(word)) unknown.push(word)\n }\n }\n const identity = textOrNull(row?.identity)\n if (identity) take(identity)\n // A mixer that is not the top identity still raises the word.\n for (const word of strings(row?.identities)) {\n if (word.toLowerCase() === identity?.toLowerCase()) continue\n take(word, (reason) => reason.level !== 'none')\n }\n for (const entry of strings(row?.evidence)) take(entry)\n for (const entry of strings(row?.judgements)) take(entry)\n const modelWord = modelWordOf(row?.risk_level)\n const risk = riskOf({\n rulesWord: rulesWordOf(reasons),\n modelWord,\n score: modelScoreOf(row?.risk_score),\n })\n if (modelWord !== 'not_scored' && (risk.set_by === 'model' || risk.set_by === 'both')) {\n reasons.push(modelReasonOf(modelWord))\n }\n return { ...risk, reasons, unknown_words: unknown }\n}\n\n/** A partner row, as the answer reads it. */\ninterface Partner {\n address: string\n direction: PartnerDirection\n row: Record<string, unknown>\n kind: AddressKind\n risk: Omit<AddressRisk, 'card_version'>\n exchange: { exchange: string | null; exchange_role: string | null } | null\n}\n\nfunction isTokenContract(nodeLabels: readonly string[]): boolean {\n return nodeLabels.includes('Token') && !nodeLabels.includes('Pool')\n}\n\n/** The exchange of a partner that is an exchange wallet, or null when it is none. */\nfunction exchangeOfPartner(\n address: string,\n row: Record<string, unknown>,\n nodeLabels: readonly string[],\n exchangeRows: ExchangeEntry[]\n): Partner['exchange'] {\n const identity = textOrNull(row.identity)?.toLowerCase()\n const role = textOrNull(row.exchange_role)?.toLowerCase() ?? null\n if (identity !== 'exchange' && role === null && !nodeLabels.includes('Exchange')) return null\n const name = textOrNull(row.identity_name)\n const listed =\n exchangeOfWallet(address, exchangeRows)?.entry ??\n (name ? exchangeOfLabels([name], exchangeRows) : null)\n return { exchange: listed?.exchange ?? name, exchange_role: role }\n}\n\n/** The partners of one direction, the token contracts and zero addresses dropped and counted. */\nfunction partnersOf(\n member: Member | undefined,\n direction: PartnerDirection,\n dictionary: readonly AddressCardWord[],\n exchangeRows: ExchangeEntry[]\n): { partners: Partner[]; leftOut: number; truncated: boolean } {\n const rows = rowsOf(member)\n const partners: Partner[] = []\n let leftOut = 0\n for (const row of rows.slice(0, PARTNER_LIMIT)) {\n const address = addressOrNull(row.address)\n if (!address) continue\n const nodeLabels = strings(row.node_labels)\n if (isTokenContract(nodeLabels) || (ZERO_ADDRESSES as readonly string[]).includes(address)) {\n leftOut += 1\n continue\n }\n partners.push({\n address,\n direction,\n row,\n kind: kindOf(nodeLabels),\n risk: rowRisk(row, dictionary),\n exchange: exchangeOfPartner(address, row, nodeLabels, exchangeRows),\n })\n }\n return { partners, leftOut, truncated: rows.length > PARTNER_LIMIT }\n}\n\nfunction riskyPartnerOf(partner: Partner): RiskyPartner {\n return {\n address: partner.address,\n direction: partner.direction,\n risk_word: partner.risk.word,\n set_by: partner.risk.set_by,\n reasons: partner.risk.reasons,\n tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),\n tx_count: numberOrNull(partner.row.tx_count),\n first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),\n last_seen_utc: utcOrNull(partner.row.last_seen_timestamp),\n }\n}\n\nconst MEDIUM_RANK = levelRank('medium')\nconst wordRank = riskWordRank\n\n/** The nodes and money links behind the answer, from the rows already read. */\nfunction surroundingsOf(subject: SurroundingsNode, partners: Partner[], truncated: boolean): Surroundings {\n const nodes: SurroundingsNode[] = [subject]\n const listed = new Set([subject.address])\n let capped = false\n for (const partner of partners) {\n if (listed.has(partner.address)) continue\n if (nodes.length >= SURROUNDINGS_NODE_LIMIT) {\n capped = true\n continue\n }\n listed.add(partner.address)\n nodes.push({\n address: partner.address,\n role: partner.exchange ? 'exchange_end' : 'partner',\n kind: partner.kind,\n name: partner.exchange?.exchange ?? textOrNull(partner.row.identity_name),\n risk_word: partner.risk.word,\n model_level: partner.risk.model_word,\n })\n }\n const links: SurroundingsLink[] = []\n for (const partner of partners) {\n if (!listed.has(partner.address)) continue\n const sent = partner.direction === 'sent_to_subject'\n links.push({\n from_address: sent ? partner.address : subject.address,\n to_address: sent ? subject.address : partner.address,\n link: 'FLOWED_TO',\n tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),\n first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),\n last_seen_utc: utcOrNull(partner.row.last_seen_timestamp),\n })\n }\n return { nodes, links, truncated: truncated || capped }\n}\n\n/**\n * The address answer built from its batch members, or why it cannot be. Only\n * a node read that did not answer is a failure; a partner read that did not\n * answer is named in not_read and the answer still stands.\n */\nexport function addressRiskFromMembers(\n network: string,\n address: string,\n members: Map<string, Member>,\n dictionary: readonly AddressCardWord[],\n exchangeRows: ExchangeEntry[],\n prefix = '',\n options: {\n surroundings?: boolean\n /** The partner reads were not sent for a hub: build the hub answer when the node is one. */\n hubGuard?: boolean\n } = {}\n): { result: AmlAddressRiskResult } | { failure: string } {\n const nodeId = `${prefix}node`\n const node = members.get(nodeId)\n if (!answered(node)) {\n if (!node) return { failure: `the ${nodeId} read is missing from the batch answer` }\n return {\n failure:\n typeof node.error === 'string' && node.error.trim() !== ''\n ? node.error\n : `the ${nodeId} read did not answer`,\n }\n }\n const nodeRow = rowsOf(node)[0]\n const base = {\n schema: AML_ADDRESS_RISK_SCHEMA,\n tool: AML_ADDRESS_RISK_TOOL,\n network,\n address,\n }\n if (!nodeRow) {\n const result: AmlAddressRiskResult = {\n ...base,\n found: false,\n kind: 'unknown',\n identity: null,\n roles: [],\n behaviour: null,\n risk: {\n word: 'unscored',\n score: null,\n rules_word: 'none',\n model_word: 'not_scored',\n set_by: 'none',\n reasons: [],\n unknown_words: [],\n card_version: null,\n },\n model: { level: 'not_scored', score: null, scored: false },\n exposure: null,\n exchange_ends: [],\n not_read: [],\n ...(options.surroundings === true\n ? {\n surroundings: {\n nodes: [\n {\n address,\n role: 'subject' as const,\n kind: 'unknown' as const,\n name: null,\n risk_word: 'unscored' as const,\n model_level: 'not_scored' as const,\n },\n ],\n links: [],\n truncated: false,\n },\n }\n : {}),\n }\n return { result }\n }\n\n const risk = rowRisk(nodeRow, dictionary)\n const kind = kindOf(strings(nodeRow.node_labels))\n const identityWord = textOrNull(nodeRow.identity)\n const identityName = textOrNull(nodeRow.identity_name)\n\n const notRead: NotRead[] = []\n const degree = numberOrNull(nodeRow.degree_total)\n const hub = options.hubGuard === true ? hubDegreeOf(nodeRow) : null\n if (hub !== null) notRead.push(hubNotRead(hub))\n const directions: Array<{ id: string; part: NotReadPart; direction: PartnerDirection }> =\n hub !== null\n ? []\n : [\n { id: `${prefix}in`, part: 'senders', direction: 'sent_to_subject' },\n { id: `${prefix}out`, part: 'receivers', direction: 'received_from_subject' },\n ]\n const partners: Partner[] = []\n let leftOut = 0\n let truncated = false\n for (const { id, part, direction } of directions) {\n const member = members.get(id)\n if (!answered(member)) {\n notRead.push(notReadOf(part, id, member))\n continue\n }\n const read = partnersOf(member, direction, dictionary, exchangeRows)\n partners.push(...read.partners)\n leftOut += read.leftOut\n truncated ||= read.truncated\n }\n\n const exchangeEnds: ExchangeEnd[] = partners\n .filter((partner) => partner.exchange !== null)\n .map((partner) => ({\n address: partner.address,\n direction: partner.direction,\n exchange: partner.exchange!.exchange,\n exchange_role: partner.exchange!.exchange_role,\n tokens_worth_usd: numberOrNull(partner.row.tokens_worth_usd),\n first_seen_utc: utcOrNull(partner.row.first_seen_timestamp),\n last_seen_utc: utcOrNull(partner.row.last_seen_timestamp),\n }))\n\n const result: AmlAddressRiskResult = {\n ...base,\n found: true,\n kind,\n identity: identityWord ? { word: identityWord, name: identityName } : null,\n roles: strings(nodeRow.address_roles),\n behaviour: textOrNull(nodeRow.behaviour),\n risk: { ...risk, card_version: textOrNull(nodeRow.card_version) },\n model: { level: risk.model_word, score: risk.score, scored: risk.model_word !== 'not_scored' },\n exposure: {\n floor_usd: EXPOSURE_FLOOR_USD,\n hub: hub !== null,\n degree_total: degree,\n counterparties_read: partners.length,\n left_out: leftOut,\n truncated,\n with_risk: partners\n .filter((partner) => wordRank(partner.risk.word) >= MEDIUM_RANK)\n .map(riskyPartnerOf),\n pattern_partners: partners.filter(\n (partner) =>\n wordRank(partner.risk.word) < MEDIUM_RANK &&\n partner.risk.reasons.some((reason) => reason.question === 'judgement')\n ).length,\n },\n exchange_ends: exchangeEnds,\n not_read: notRead,\n }\n if (options.surroundings === true) {\n result.surroundings = surroundingsOf(\n {\n address,\n role: 'subject',\n kind,\n name: identityName,\n risk_word: risk.word,\n model_level: risk.model_word,\n },\n partners,\n truncated\n )\n }\n return { result }\n}\n\nfunction errorResult(text: string): AmlAddressRiskToolResult {\n return { content: [{ type: 'text', text }], isError: true }\n}\n\nfunction textResult(structured: AmlAddressRiskResult): AmlAddressRiskToolResult {\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/** aml_address_risk, {network, address, surroundings?}. Every argument is checked before a read is sent. */\nexport async function handleAmlAddressRisk(\n args: unknown,\n deps: AddressRiskDependencies\n): Promise<AmlAddressRiskToolResult> {\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 const raw = typeof record.address === 'string' ? record.address.trim() : ''\n if (!ADDRESS_INPUT.test(raw)) {\n return errorResult(\n 'invalid_address: address is required: 0x plus 40 hex characters. ' +\n 'A name or a ticker is not an address: call meta_token_lookup or meta_exchange_lookup first.'\n )\n }\n if (record.surroundings !== undefined && typeof record.surroundings !== 'boolean') {\n return errorResult('invalid_surroundings: surroundings is true or false.')\n }\n const address = raw.toLowerCase()\n const surroundings = record.surroundings === true\n\n const unavailable = await deps.unavailable?.()\n if (unavailable) {\n return errorResult(\n `No address risk read was sent: ${unavailable} There is no answer yet, which is not \"no risk\": try again later.`\n )\n }\n\n let dictionary: readonly AddressCardWord[]\n try {\n const card = await deps.loadAddressCard()\n if (!card) throw new Error('no copy of the address card dictionary is available')\n dictionary = card.document.words\n } catch (err) {\n return errorResult(\n `No address risk read was sent: the address card dictionary did not load (${(err as Error).message}). ` +\n 'There is no answer yet, which is not \"no risk\".'\n )\n }\n\n let exchangeRows: ExchangeEntry[] = []\n try {\n exchangeRows = (await deps.loadExchangeRegistry(network)).document.rows\n } catch {\n // The lookup only names an exchange; the graph read still answers.\n }\n\n // Call 1: the node alone (about 50 ms). It says whether the address exists and whether it is a hub.\n const read = async (queries: Array<{ id: string; query: string }>) => {\n let answer: GraphAnswer\n try {\n answer = await deps.graphQueryBatch({ network, queries })\n } catch (err) {\n return { failure: `${deps.describeFailure(err)} This is not \"no risk\": send the same call again once.` }\n }\n const members = membersOf(answer)\n if (members.size === 0) {\n const text = answer.isError === true ? refusalOf(answer).text : 'the batch answer held no reads'\n return { failure: `${text} This is not \"no risk\".` }\n }\n return { members }\n }\n const [nodeQuery, ...partnerQueries] = addressRiskQueries(address)\n const first = await read([nodeQuery!])\n if ('failure' in first) return errorResult(`The address risk read failed: ${first.failure}`)\n const members = first.members\n const nodeRow = memberRows(members.get('node'))[0]\n // Call 2: the partner reads, unless the address is not found or is a hub.\n if (nodeRow && hubDegreeOf(nodeRow) === null) {\n const second = await read(partnerQueries)\n if ('failure' in second) {\n for (const { id } of partnerQueries) members.set(id, { id, ok: false, error: second.failure })\n } else {\n for (const [id, member] of second.members) members.set(id, member)\n }\n }\n const built = addressRiskFromMembers(network, address, members, dictionary, exchangeRows, '', {\n surroundings,\n hubGuard: true,\n })\n if ('failure' in built) {\n return errorResult(\n `The address risk read failed: ${built.failure} This is not \"no risk\": send the same call again once.`\n )\n }\n return textResult(built.result)\n}\n"],"mappings":";;;;;;;;AAuBA,MAAa,cAAc;CAAC;CAAQ;CAAO;CAAU;CAAQ;AAAU;;AAevE,MAAa,kBAAkB;CAAC;CAAY;CAAY;AAAW;;;;;;AAOnE,MAAa,uBAAuB;AAoBpC,SAAgB,UAAU,OAA0B;CAClD,OAAO,YAAY,QAAQ,KAAK;AAClC;;AAGA,SAAgB,aAAa,MAAwB;CACnD,OAAO,SAAS,aAAa,KAAK,UAAU,IAAI;AAClD;AAEA,MAAM,WAAW,UACd,YAAmC,SAAS,KAAK;;AAGpD,SAAgB,eAAe,OAAuD;CACpF,MAAM,OAAO,MAAM,KAAK;CACxB,MAAM,MAAM,KAAK,QAAQ,GAAG;CAC5B,IAAI,MAAM,GAAG,OAAO;EAAE,MAAM;EAAM,OAAO;CAAK;CAC9C,MAAM,QAAQ,KAAK,MAAM,MAAM,CAAC,CAAC,CAAC,KAAK;CACvC,OAAO;EAAE,MAAM,KAAK,MAAM,GAAG,GAAG,CAAC,CAAC,KAAK;EAAG,OAAO,UAAU,KAAK,OAAO;CAAM;AAC/E;;;;;;;;;AAUA,SAAgB,WACd,OACA,iBACwB;CACxB,MAAM,EAAE,MAAM,UA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IAAI,IAAI;GAAE;GAAI,IAAI;GAAO,OAAO,OAAO;EAAQ,CAAC;OAE7F,KAAK,MAAM,CAAC,IAAI,WAAW,OAAO,SAAS,QAAQ,IAAI,IAAI,MAAM;CAErE;CACA,MAAM,QAAQ,uBAAuB,SAAS,SAAS,SAAS,YAAY,cAAc,IAAI;EAC5F;EACA,UAAU;CACZ,CAAC;CACD,IAAI,aAAa,OACf,OAAO,YACL,iCAAiC,MAAM,QAAQ,uDACjD;CAEF,OAAO,WAAW,MAAM,MAAM;AAChC"}
@@ -1,6 +1,6 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
2
  const require_client = require("./client-Ddk4X9Ko.cjs");
3
- const require_layer_routing = require("./layer-routing-YDj-ynG9.cjs");
3
+ const require_layer_routing = require("./layer-routing-j48SQ8Wk.cjs");
4
4
  // src/mcp/capabilities.ts
5
5
  var capabilities_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
6
6
  fetchNetworkCapabilities: () => fetchNetworkCapabilities,
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
2
  import { a as resolveGraphMcpEndpoint, n as applyMcpAuthHeaders } from "./client-BaHAIidE.mjs";
3
- import { o as swapLinkShape } from "./layer-routing-DCJVNN6O.mjs";
3
+ import { o as swapLinkShape } from "./layer-routing-r4IbIQSr.mjs";
4
4
  // src/mcp/capabilities.ts
5
5
  var capabilities_exports = /* @__PURE__ */ __exportAll({
6
6
  fetchNetworkCapabilities: () => fetchNetworkCapabilities,
@@ -422,4 +422,4 @@ function keptSwapLinkShape(read, ttlMs, now = Date.now) {
422
422
  }
423
423
  export { readSwapLinkShape as a, mirrorGraphNetworkCapabilities as i, findNetworkCapability as n, keptSwapLinkShape as r, capabilities_exports as t };
424
424
 
425
- //# sourceMappingURL=capabilities-bZOr5Ads.mjs.map
425
+ //# sourceMappingURL=capabilities-w5bNR7F9.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities-bZOr5Ads.mjs","names":[],"sources":["../src/mcp/capabilities.ts"],"sourcesContent":["import type { InvestigatorConfig } from '../config/schema.js'\nimport { applyMcpAuthHeaders, resolveGraphMcpEndpoint } from './client.js'\nimport { swapLinkShape, type SwapLinkShape } from './layer-routing.js'\n\nexport interface NetworkTopologyLayer {\n enabled: boolean\n coverage?: {\n from_block?: number\n to_block?: number\n from_timestamp?: string\n to_timestamp?: string\n chain_tip_block?: number\n blocks_behind_tip?: number\n /** Lowest height among the raw-data lanes that have started. Above it an empty answer may mean \"not indexed yet\". */\n complete_through_block?: number\n }\n}\n\nexport interface NetworkLayerCapability {\n enabled: boolean\n live?: NetworkTopologyLayer\n archive?: NetworkTopologyLayer\n /** The relationships a facts layer serves, when the server lists them. */\n relationships?: string[]\n}\n\n/**\n * A block the server publishes about one layer's limits. The mirror repeats it\n * exactly as it came: the members named below are the ones known today, and\n * any other member the server adds is kept. Read a limit from the block, never\n * from a number written elsewhere.\n */\nexport type NetworkAdmissionBlock = Record<string, unknown>\n\n/** `USE chain`: the lookups, the ceilings and the slots of the chain layer. */\nexport interface ChainAdmission extends NetworkAdmissionBlock {\n enabled: boolean\n /** ok, or the reason the layer is off or behind. */\n status?: string\n rules_version?: string\n grammar?: string\n /** The labels of `USE chain`, such as Transaction, Block, Head and Address. */\n lookups?: string[]\n ceiling_seconds?: Record<string, number>\n slots?: number\n past_slots?: number\n slots_per_caller?: number\n calls_per_second_per_caller?: number\n batch_max?: number\n call_gas?: number\n head_ttl_ms?: number\n max_head_age_seconds?: number\n /** How many blocks below the tip a past `Address` read (`at_block`) must be. Read it here, never write it down. */\n at_block_min_depth?: number\n}\n\n/** `USE topology`: the shape rules, when the server publishes them. */\nexport interface TopologyAdmission extends NetworkAdmissionBlock {\n rules_version?: string\n max_hops_per_path?: number\n max_limit?: number\n slots?: number\n}\n\n/** `USE facts`: the read contract, when the server publishes it. */\nexport interface FactsAdmission extends NetworkAdmissionBlock {\n rules_version?: string\n window_days?: number\n max_rows?: number\n max_hops?: number\n}\n\nexport interface NetworkCapability {\n network: string\n display_name?: string\n status: string\n default?: boolean\n /** The layers as the server sent them. Absent when the server sent none. */\n layers?: Record<string, NetworkLayerCapability>\n tools: Record<string, string>\n /** The three layer blocks below are repeated exactly as sent, and absent when not sent. */\n chain_admission?: ChainAdmission\n topology_admission?: TopologyAdmission\n facts_admission?: FactsAdmission\n coverage?: {\n from_block?: number\n to_block?: number\n from_timestamp?: string\n to_timestamp?: string\n chain_tip_block?: number\n blocks_behind_tip?: number\n /** Lowest height among the raw-data lanes that have started. Above it an empty answer may mean \"not indexed yet\". */\n complete_through_block?: number\n }\n freshness?: {\n last_processed_at?: string\n last_successful_sync_at?: string\n max_data_age_seconds?: number\n last_processing_duration_seconds?: number\n /** The chain node's own head block, and how old that reading is. */\n chain_head_block?: number\n chain_head_age_seconds?: number\n warehouse_blocks_behind_head?: number\n graph_blocks_behind_head?: number\n }\n lane_progress?: NetworkLaneProgress[]\n graph_progress?: NetworkGraphProgress\n}\n\n/** One writer lane's committed height. null: the lane has not started. */\nexport interface NetworkLaneProgress {\n lane: string\n height: number | null\n}\n\n/**\n * How far each block layer of the topology graph reaches, and how far the\n * money family reaches (`complete_through_block`). `families` is absent on a\n * server that does not group its layers into families.\n */\nexport interface NetworkGraphProgress {\n complete_through_block: number\n layers: { layer: string; position: number }[]\n families?: NetworkGraphFamily[]\n}\n\n/**\n * One layer family as the server reports it. A block family carries the block\n * it is complete through and its lag behind the head (null on a server that\n * knows no head). `annotations` follows runs, not blocks: both numbers are null\n * and `fresh` says whether its last run is current.\n */\nexport interface NetworkGraphFamily {\n name: string\n complete_through_block: number | null\n blocks_behind_head: number | null\n fresh?: boolean\n layers: string[]\n /** The link types the family serves, when the server lists them. */\n link_types?: string[]\n /** The level of each levelled link type of the family, when the server reports it. */\n link_levels?: Record<string, number>\n}\n\nexport interface NetworkCapabilitiesDocument {\n schema: 'chain-insights.network-capabilities.v1'\n networks: NetworkCapability[]\n}\n\nconst AVAILABLE_TOOLS_PER_LINE = 3\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction advertisedTools(raw: unknown): Record<string, string> {\n if (!isRecord(raw)) return {}\n const tools: Record<string, string> = {}\n for (const [name, status] of Object.entries(raw)) {\n if (name.trim() !== '' && typeof status === 'string') tools[name] = status\n }\n return tools\n}\n\nfunction advertisedLaneProgress(raw: unknown): NetworkLaneProgress[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const lanes: NetworkLaneProgress[] = []\n for (const entry of raw) {\n if (!isRecord(entry) || typeof entry.lane !== 'string' || entry.lane.trim() === '') continue\n if (typeof entry.height === 'number') lanes.push({ lane: entry.lane, height: entry.height })\n else if (entry.height === null) lanes.push({ lane: entry.lane, height: null })\n }\n return lanes\n}\n\nfunction isNumberOrNull(value: unknown): value is number | null {\n return value === null || typeof value === 'number'\n}\n\n/** One family entry, or null when any member has the wrong shape. */\nfunction advertisedGraphFamily(entry: unknown): NetworkGraphFamily | null {\n if (!isRecord(entry) || typeof entry.name !== 'string' || entry.name.trim() === '') return null\n if (!isNumberOrNull(entry.complete_through_block)) return null\n const behind = entry.blocks_behind_head === undefined ? null : entry.blocks_behind_head\n if (!isNumberOrNull(behind)) return null\n if (entry.fresh !== undefined && typeof entry.fresh !== 'boolean') return null\n if (!Array.isArray(entry.layers) || !entry.layers.every((layer) => typeof layer === 'string'))\n return null\n const linkTypes =\n Array.isArray(entry.link_types) && entry.link_types.every((type) => typeof type === 'string')\n ? [...(entry.link_types as string[])]\n : undefined\n const linkLevels = isRecord(entry.link_levels)\n ? Object.fromEntries(\n Object.entries(entry.link_levels).filter(\n (pair): pair is [string, number] => typeof pair[1] === 'number'\n )\n )\n : undefined\n return {\n name: entry.name,\n complete_through_block: entry.complete_through_block,\n blocks_behind_head: behind,\n ...(typeof entry.fresh === 'boolean' ? { fresh: entry.fresh } : {}),\n layers: [...(entry.layers as string[])],\n ...(linkTypes ? { link_types: linkTypes } : {}),\n ...(linkLevels ? { link_levels: linkLevels } : {}),\n }\n}\n\n/** The families list, whole or not at all: one entry with a bad shape drops it. */\nfunction advertisedGraphFamilies(raw: unknown): NetworkGraphFamily[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const families: NetworkGraphFamily[] = []\n for (const entry of raw) {\n const family = advertisedGraphFamily(entry)\n if (family === null) return undefined\n families.push(family)\n }\n return families\n}\n\nfunction advertisedGraphProgress(raw: unknown): NetworkGraphProgress | undefined {\n if (!isRecord(raw) || typeof raw.complete_through_block !== 'number') return undefined\n if (!Array.isArray(raw.layers)) return undefined\n const layers: NetworkGraphProgress['layers'] = []\n for (const entry of raw.layers) {\n if (!isRecord(entry) || typeof entry.layer !== 'string' || typeof entry.position !== 'number')\n continue\n layers.push({ layer: entry.layer, position: entry.position })\n }\n const progress: NetworkGraphProgress = {\n complete_through_block: raw.complete_through_block,\n layers,\n }\n const families = advertisedGraphFamilies(raw.families)\n if (families) progress.families = families\n return progress\n}\n\nfunction advertisedNetwork(raw: unknown): NetworkCapability | null {\n if (!isRecord(raw) || typeof raw.network !== 'string' || raw.network.trim() === '') {\n return null\n }\n const network = raw.network.trim()\n const capability: NetworkCapability = {\n network,\n display_name:\n typeof raw.display_name === 'string' && raw.display_name.trim() !== ''\n ? raw.display_name\n : network,\n status: typeof raw.status === 'string' && raw.status.trim() !== '' ? raw.status : 'live',\n tools: advertisedTools(raw.tools),\n }\n // The layer blocks are the server's own words about its limits. They pass\n // through exactly as sent: nothing is added, no default is invented and no\n // member is dropped. A block the server did not send stays absent.\n if (isRecord(raw.layers)) capability.layers = raw.layers as NetworkCapability['layers']\n if (isRecord(raw.chain_admission)) {\n capability.chain_admission = raw.chain_admission as unknown as ChainAdmission\n }\n if (isRecord(raw.topology_admission)) {\n capability.topology_admission = raw.topology_admission as TopologyAdmission\n }\n if (isRecord(raw.facts_admission)) {\n capability.facts_admission = raw.facts_admission as FactsAdmission\n }\n if (raw.default === true) capability.default = true\n if (raw.default === false) capability.default = false\n if (isRecord(raw.coverage)) capability.coverage = raw.coverage as NetworkCapability['coverage']\n if (isRecord(raw.freshness))\n capability.freshness = raw.freshness as NetworkCapability['freshness']\n const laneProgress = advertisedLaneProgress(raw.lane_progress)\n if (laneProgress) capability.lane_progress = laneProgress\n const graphProgress = advertisedGraphProgress(raw.graph_progress)\n if (graphProgress) capability.graph_progress = graphProgress\n return capability\n}\n\n/** Repeat GraphRAG's network list. CIA does not add, drop, or invent names. */\nexport function mirrorGraphNetworkCapabilities(document: {\n networks: unknown[]\n}): NetworkCapabilitiesDocument {\n return {\n schema: 'chain-insights.network-capabilities.v1',\n networks: document.networks\n .map((network) => advertisedNetwork(network))\n .filter((network): network is NetworkCapability => network !== null),\n }\n}\n\nfunction publicNetworkCapabilities(\n document: NetworkCapabilitiesDocument\n): NetworkCapabilitiesDocument {\n return mirrorGraphNetworkCapabilities(document)\n}\n\nfunction metadataNetworksUrl(endpoint: string): URL {\n const url = new URL(endpoint)\n url.pathname = '/metadata/networks'\n url.search = ''\n url.hash = ''\n return url\n}\n\nexport async function fetchNetworkCapabilities(\n config: Pick<InvestigatorConfig, 'graphMcpAuthToken' | 'graphMcpMode' | 'graphMcpEndpoint'>\n): Promise<NetworkCapabilitiesDocument> {\n const endpoint = resolveGraphMcpEndpoint(config)\n const request = metadataNetworksUrl(endpoint)\n const headers = new Headers()\n const token = config.graphMcpAuthToken?.trim()\n if (token) {\n applyMcpAuthHeaders(headers, token)\n }\n let response: Response\n try {\n response = await fetch(request, { headers })\n } catch (err) {\n throw new Error(`network capabilities unavailable at ${request}: ${(err as Error).message}`)\n }\n if (!response.ok) {\n throw new Error(`network capabilities unavailable at ${request}: HTTP ${response.status}`)\n }\n const parsed = (await response.json()) as NetworkCapabilitiesDocument\n if (\n parsed.schema !== 'chain-insights.network-capabilities.v1' ||\n !Array.isArray(parsed.networks)\n ) {\n throw new Error('network capabilities response has unsupported schema')\n }\n return publicNetworkCapabilities(parsed)\n}\n\nfunction availableTools(network: NetworkCapability): string[] {\n const tools = Object.entries(network.tools ?? {})\n .filter(([, status]) => status === 'available')\n .map(([name]) => name)\n return tools.sort()\n}\n\nfunction availableToolLines(network: NetworkCapability): string[] {\n const tools = availableTools(network)\n if (tools.length === 0) return ['none']\n const lines: string[] = []\n for (let index = 0; index < tools.length; index += AVAILABLE_TOOLS_PER_LINE) {\n lines.push(tools.slice(index, index + AVAILABLE_TOOLS_PER_LINE).join(', '))\n }\n return lines\n}\n\nfunction shortDate(value?: string): string {\n if (!value) return ''\n return value.slice(0, 10)\n}\n\nfunction datasetLabel(network: NetworkCapability): string {\n const coverage = network.coverage\n if (!coverage) return 'unknown'\n const blockRange =\n coverage.from_block !== undefined && coverage.to_block !== undefined\n ? `${coverage.from_block}..${coverage.to_block}`\n : 'blocks unknown'\n const dateRange =\n coverage.from_timestamp && coverage.to_timestamp\n ? `${shortDate(coverage.from_timestamp)}..${shortDate(coverage.to_timestamp)}`\n : ''\n if (blockRange === 'blocks unknown' && dateRange === '') return 'unknown'\n if (blockRange === 'blocks unknown') return dateRange\n if (dateRange === '') return blockRange\n return `${blockRange} / ${dateRange}`\n}\n\nfunction displayName(network: NetworkCapability): string {\n return network.display_name || network.network\n}\n\nfunction statusLabel(network: NetworkCapability): string {\n return network.default ? `${network.status} (default)` : network.status\n}\n\nfunction formatTable(headers: string[], rows: string[][], minimumWidths: number[]): string {\n const widths = headers.map((header, index) =>\n Math.max(\n minimumWidths[index] ?? 0,\n header.length,\n ...rows.map((row) => row[index]?.length ?? 0)\n )\n )\n const row = (values: string[]) =>\n values.map((value, index) => value.padEnd(widths[index]!)).join(' ')\n return [row(headers), widths.map((width) => '-'.repeat(width)).join(' '), ...rows.map(row)].join(\n '\\n'\n )\n}\n\nexport function formatNetworkOverview(document: NetworkCapabilitiesDocument): string {\n if (document.networks.length === 0) return 'No supported networks advertised.'\n const rows = document.networks.map((network) => [\n displayName(network),\n statusLabel(network),\n datasetLabel(network),\n ])\n return formatTable(['Network', 'Status', 'Dataset'], rows, [14, 10, 38])\n}\n\nexport function formatNetworkCapabilities(document: NetworkCapabilitiesDocument): string {\n if (document.networks.length === 0) return 'No supported networks advertised.'\n const networkRows = document.networks.flatMap((network) => {\n const toolLines = availableToolLines(network)\n return toolLines.map((toolLine, index) => [\n index === 0 ? displayName(network) : '',\n index === 0 ? datasetLabel(network) : '',\n toolLine,\n ])\n })\n return formatTable(['Network', 'Dataset', 'Chain Insights tools'], networkRows, [14, 38, 64])\n}\n\nexport function findNetworkCapability(\n document: NetworkCapabilitiesDocument,\n name: string\n): NetworkCapability | undefined {\n const normalizedName = name.trim().toLowerCase()\n if (!normalizedName) return undefined\n return document.networks.find((network) =>\n [network.network, network.display_name].some(\n (candidate) => candidate?.trim().toLowerCase() === normalizedName\n )\n )\n}\n\n/** The writer lanes a customer sees, in screen order, by their plain names. */\nconst KNOWN_LANES: readonly (readonly [string, string])[] = [\n ['core_transfers_source_head', 'receipts'],\n ['core_transfers_internal_follow', 'traces'],\n ['core_dex_follow', 'dex'],\n ['core_bridge_follow', 'bridge'],\n ['core_smart_account_follow', 'smart accounts'],\n]\n\n/** The evidence worker's lane. It has its own table and never joins Indexing. */\nconst EVIDENCE_LANE = 'evidence_sync'\n\n/** The plain name a lane prints as. An unknown lane prints as sent. */\nexport function laneDisplayName(lane: string): string {\n if (lane === EVIDENCE_LANE) return 'evidence'\n return KNOWN_LANES.find(([name]) => name === lane)?.[1] ?? lane\n}\n\n/** A graph layer prints as sent: it is the link kind a query names. */\nexport function layerDisplayName(layer: string): string {\n return layer\n}\n\n/** A family prints by its plain name: `smart_accounts` prints as \"smart accounts\". */\nexport function familyDisplayName(family: string): string {\n return family.replace(/_/g, ' ')\n}\n\n/** 87642448 -> \"87,642,448\", the same on every machine (no locale). */\nexport function groupThousands(value: number): string {\n const sign = value < 0 ? '-' : ''\n const digits = String(Math.trunc(Math.abs(value)))\n return sign + digits.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n}\n\n/** One row of a progress table. `behind` is absent with no head or no height. */\ninterface ProgressRow {\n label: string\n height: number | null\n /** Text printed in the height column instead of a number. */\n note?: string\n behind?: number\n}\n\nconst DETAIL_LABEL_WIDTH = 18\nconst TABLE_LABEL_WIDTH = 30\nconst HEIGHT_MIN_WIDTH = 10\nconst LAG_HEADER = 'behind head'\n\nfunction progressRows(\n entries: { label: string; height: number | null }[],\n head: number | undefined\n): ProgressRow[] {\n return entries.map(({ label, height }) => ({\n label,\n height,\n ...(height === null ? { note: 'not started' } : {}),\n ...(height !== null && head !== undefined ? { behind: Math.max(0, head - height) } : {}),\n }))\n}\n\nfunction notReportedRow(label: string): ProgressRow {\n return { label, height: null, note: 'not reported' }\n}\n\n/**\n * The family rows, in the order the server sends them. A block family's lag is\n * the server's `blocks_behind_head`, or head minus height when the server knows\n * no head. A family with no block (annotations) prints \"fresh\" or \"walking\" and\n * no lag.\n */\nfunction familyRows(families: NetworkGraphFamily[], head: number | undefined): ProgressRow[] {\n return families.map((family) => {\n const label = familyDisplayName(family.name)\n const height = family.complete_through_block\n if (height === null) {\n const note = family.fresh === undefined ? 'not started' : family.fresh ? 'fresh' : 'walking'\n return { label, height: null, note }\n }\n if (head === undefined) return { label, height }\n const behind = family.blocks_behind_head ?? Math.max(0, head - height)\n return { label, height, behind }\n })\n}\n\nfunction formatProgressTables(\n tables: { title: string; rows: ProgressRow[] }[],\n withLag: boolean\n): string[] {\n const allRows = tables.flatMap((table) => table.rows)\n const labelWidth = Math.max(\n TABLE_LABEL_WIDTH,\n ...allRows.map((row) => row.label.length + 4),\n ...tables.map((table) => table.title.length + 2)\n )\n const heightWidth = Math.max(\n HEIGHT_MIN_WIDTH,\n ...allRows.map((row) => (row.height === null ? 0 : groupThousands(row.height).length))\n )\n const lagWidth = Math.max(\n LAG_HEADER.length,\n ...allRows.map((row) => (row.behind === undefined ? 0 : groupThousands(row.behind).length))\n )\n const lines: string[] = []\n for (const table of tables) {\n if (lines.length > 0) lines.push('')\n const header = table.title.padEnd(labelWidth) + 'height'\n lines.push(withLag ? header.padEnd(labelWidth + heightWidth + 2) + LAG_HEADER : header)\n for (const row of table.rows) {\n let line = ` ${row.label}`.padEnd(labelWidth)\n if (row.height === null) {\n line += row.note ?? ''\n } else {\n line += groupThousands(row.height).padStart(heightWidth)\n if (withLag && row.behind !== undefined) {\n line += ' ' + groupThousands(row.behind).padStart(lagWidth)\n }\n }\n lines.push(line.trimEnd())\n }\n }\n return lines\n}\n\n/**\n * `cia network <name>`: how far this network is indexed. The chain node's head\n * comes first; every row reads against it. Known lanes print by plain name,\n * unknown lanes as sent after them, the layer families by plain name in the\n * server's order, graph layers as sent, and evidence in its own table. Heights\n * are right-aligned, so a shorter height lines up by its last digit.\n * `--json` never comes through here.\n */\nexport function formatNetworkCapability(network: NetworkCapability): string {\n const headBlock = network.freshness?.chain_head_block\n const head = typeof headBlock === 'number' ? headBlock : undefined\n const detail: [string, string][] = [\n ['Network', displayName(network)],\n ['Identifier', network.network],\n ['Status', statusLabel(network)],\n ]\n if (head !== undefined) {\n const age = network.freshness?.chain_head_age_seconds\n const ageText = typeof age === 'number' ? ` (${groupThousands(age)} s old)` : ''\n detail.push(['Blockchain head', `${groupThousands(head)}${ageText}`])\n }\n\n const lanes = network.lane_progress ?? []\n const known = KNOWN_LANES.flatMap(([name, label]) =>\n lanes.filter((lane) => lane.lane === name).map((lane) => ({ label, height: lane.height }))\n )\n const unknown = lanes\n .filter(\n (lane) => lane.lane !== EVIDENCE_LANE && !KNOWN_LANES.some(([name]) => name === lane.lane)\n )\n .map((lane) => ({ label: laneDisplayName(lane.lane), height: lane.height }))\n const indexing = [...known, ...unknown]\n const layers = (network.graph_progress?.layers ?? []).map((layer) => ({\n label: layerDisplayName(layer.layer),\n height: layer.position,\n }))\n const evidence = lanes\n .filter((lane) => lane.lane === EVIDENCE_LANE)\n .map((lane) => ({ label: laneDisplayName(lane.lane), height: lane.height }))\n\n const families = network.graph_progress?.families\n\n const tables = [\n {\n title: 'Indexing',\n rows: indexing.length > 0 ? progressRows(indexing, head) : [notReportedRow('indexing')],\n },\n // Absent on a server that sends no families: the table is left out, so the\n // screen of such a server stays as it was.\n ...(families ? [{ title: 'Families', rows: familyRows(families, head) }] : []),\n {\n title: 'Graph',\n rows: layers.length > 0 ? progressRows(layers, head) : [notReportedRow('graph')],\n },\n {\n title: 'Evidence',\n rows: evidence.length > 0 ? progressRows(evidence, head) : [notReportedRow('evidence')],\n },\n ]\n\n return [\n ...detail.map(([label, value]) => `${label.padEnd(DETAIL_LABEL_WIDTH)}${value}`),\n '',\n ...formatProgressTables(tables, head !== undefined),\n ].join('\\n')\n}\n\n/**\n * The shape of a lane's swap links, read from its `network_capabilities` reply:\n * `levels` when its money family lists ROUTED_TO, else `route`. A call that\n * fails, or a reply that lists no such network, gives no shape (undefined): the\n * caller uses `route` for that one call and asks again on the next.\n */\nexport async function readSwapLinkShape(\n client: { callTool: (request: { name: string; arguments: Record<string, unknown> }) => Promise<unknown> },\n network: string\n): Promise<SwapLinkShape | undefined> {\n try {\n const answer = await client.callTool({ name: 'network_capabilities', arguments: {} })\n const structured = isRecord(answer) ? answer.structuredContent : undefined\n const facts = isRecord(structured) ? structured.facts : undefined\n const capabilities = isRecord(facts) ? facts.capabilities : undefined\n const networks =\n isRecord(capabilities) && Array.isArray(capabilities.networks) ? capabilities.networks : []\n const capability = findNetworkCapability(mirrorGraphNetworkCapabilities({ networks }), network)\n if (!capability) return undefined\n return swapLinkShape(capability.graph_progress?.families)\n } catch {\n return undefined\n }\n}\n\n/**\n * A lane's shape, kept `ttlMs` per network once a read gives one. A read that\n * gives none is never kept: that call answers `route`, the next reads again.\n */\nexport function keptSwapLinkShape(\n read: (network: string) => Promise<SwapLinkShape | undefined>,\n ttlMs: number,\n now: () => number = Date.now\n): (network: string) => Promise<SwapLinkShape> {\n const kept = new Map<string, { shape: SwapLinkShape; at: number }>()\n return async (network) => {\n const entry = kept.get(network)\n if (entry && now() - entry.at < ttlMs) return entry.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,SAAS;GAAE;GAAO,IAAI,IAAI;EAAE,CAAC;EACtC,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"capabilities-w5bNR7F9.mjs","names":[],"sources":["../src/mcp/capabilities.ts"],"sourcesContent":["import type { InvestigatorConfig } from '../config/schema.js'\nimport { applyMcpAuthHeaders, resolveGraphMcpEndpoint } from './client.js'\nimport { swapLinkShape, type SwapLinkShape } from './layer-routing.js'\n\nexport interface NetworkTopologyLayer {\n enabled: boolean\n coverage?: {\n from_block?: number\n to_block?: number\n from_timestamp?: string\n to_timestamp?: string\n chain_tip_block?: number\n blocks_behind_tip?: number\n /** Lowest height among the raw-data lanes that have started. Above it an empty answer may mean \"not indexed yet\". */\n complete_through_block?: number\n }\n}\n\nexport interface NetworkLayerCapability {\n enabled: boolean\n live?: NetworkTopologyLayer\n archive?: NetworkTopologyLayer\n /** The relationships a facts layer serves, when the server lists them. */\n relationships?: string[]\n}\n\n/**\n * A block the server publishes about one layer's limits. The mirror repeats it\n * exactly as it came: the members named below are the ones known today, and\n * any other member the server adds is kept. Read a limit from the block, never\n * from a number written elsewhere.\n */\nexport type NetworkAdmissionBlock = Record<string, unknown>\n\n/** `USE chain`: the lookups, the ceilings and the slots of the chain layer. */\nexport interface ChainAdmission extends NetworkAdmissionBlock {\n enabled: boolean\n /** ok, or the reason the layer is off or behind. */\n status?: string\n rules_version?: string\n grammar?: string\n /** The labels of `USE chain`, such as Transaction, Block, Head and Address. */\n lookups?: string[]\n ceiling_seconds?: Record<string, number>\n slots?: number\n past_slots?: number\n slots_per_caller?: number\n calls_per_second_per_caller?: number\n batch_max?: number\n call_gas?: number\n head_ttl_ms?: number\n max_head_age_seconds?: number\n /** How many blocks below the tip a past `Address` read (`at_block`) must be. Read it here, never write it down. */\n at_block_min_depth?: number\n}\n\n/** `USE topology`: the shape rules, when the server publishes them. */\nexport interface TopologyAdmission extends NetworkAdmissionBlock {\n rules_version?: string\n max_hops_per_path?: number\n max_limit?: number\n slots?: number\n}\n\n/** `USE facts`: the read contract, when the server publishes it. */\nexport interface FactsAdmission extends NetworkAdmissionBlock {\n rules_version?: string\n window_days?: number\n max_rows?: number\n max_hops?: number\n}\n\nexport interface NetworkCapability {\n network: string\n display_name?: string\n status: string\n default?: boolean\n /** The layers as the server sent them. Absent when the server sent none. */\n layers?: Record<string, NetworkLayerCapability>\n tools: Record<string, string>\n /** The three layer blocks below are repeated exactly as sent, and absent when not sent. */\n chain_admission?: ChainAdmission\n topology_admission?: TopologyAdmission\n facts_admission?: FactsAdmission\n coverage?: {\n from_block?: number\n to_block?: number\n from_timestamp?: string\n to_timestamp?: string\n chain_tip_block?: number\n blocks_behind_tip?: number\n /** Lowest height among the raw-data lanes that have started. Above it an empty answer may mean \"not indexed yet\". */\n complete_through_block?: number\n }\n freshness?: {\n last_processed_at?: string\n last_successful_sync_at?: string\n max_data_age_seconds?: number\n last_processing_duration_seconds?: number\n /** The chain node's own head block, and how old that reading is. */\n chain_head_block?: number\n chain_head_age_seconds?: number\n warehouse_blocks_behind_head?: number\n graph_blocks_behind_head?: number\n }\n lane_progress?: NetworkLaneProgress[]\n graph_progress?: NetworkGraphProgress\n}\n\n/** One writer lane's committed height. null: the lane has not started. */\nexport interface NetworkLaneProgress {\n lane: string\n height: number | null\n}\n\n/**\n * How far each block layer of the topology graph reaches, and how far the\n * money family reaches (`complete_through_block`). `families` is absent on a\n * server that does not group its layers into families.\n */\nexport interface NetworkGraphProgress {\n complete_through_block: number\n layers: { layer: string; position: number }[]\n families?: NetworkGraphFamily[]\n}\n\n/**\n * One layer family as the server reports it. A block family carries the block\n * it is complete through and its lag behind the head (null on a server that\n * knows no head). `annotations` follows runs, not blocks: both numbers are null\n * and `fresh` says whether its last run is current.\n */\nexport interface NetworkGraphFamily {\n name: string\n complete_through_block: number | null\n blocks_behind_head: number | null\n fresh?: boolean\n layers: string[]\n /** The link types the family serves, when the server lists them. */\n link_types?: string[]\n /** The level of each levelled link type of the family, when the server reports it. */\n link_levels?: Record<string, number>\n}\n\nexport interface NetworkCapabilitiesDocument {\n schema: 'chain-insights.network-capabilities.v1'\n networks: NetworkCapability[]\n}\n\nconst AVAILABLE_TOOLS_PER_LINE = 3\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction advertisedTools(raw: unknown): Record<string, string> {\n if (!isRecord(raw)) return {}\n const tools: Record<string, string> = {}\n for (const [name, status] of Object.entries(raw)) {\n if (name.trim() !== '' && typeof status === 'string') tools[name] = status\n }\n return tools\n}\n\nfunction advertisedLaneProgress(raw: unknown): NetworkLaneProgress[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const lanes: NetworkLaneProgress[] = []\n for (const entry of raw) {\n if (!isRecord(entry) || typeof entry.lane !== 'string' || entry.lane.trim() === '') continue\n if (typeof entry.height === 'number') lanes.push({ lane: entry.lane, height: entry.height })\n else if (entry.height === null) lanes.push({ lane: entry.lane, height: null })\n }\n return lanes\n}\n\nfunction isNumberOrNull(value: unknown): value is number | null {\n return value === null || typeof value === 'number'\n}\n\n/** One family entry, or null when any member has the wrong shape. */\nfunction advertisedGraphFamily(entry: unknown): NetworkGraphFamily | null {\n if (!isRecord(entry) || typeof entry.name !== 'string' || entry.name.trim() === '') return null\n if (!isNumberOrNull(entry.complete_through_block)) return null\n const behind = entry.blocks_behind_head === undefined ? null : entry.blocks_behind_head\n if (!isNumberOrNull(behind)) return null\n if (entry.fresh !== undefined && typeof entry.fresh !== 'boolean') return null\n if (!Array.isArray(entry.layers) || !entry.layers.every((layer) => typeof layer === 'string'))\n return null\n const linkTypes =\n Array.isArray(entry.link_types) && entry.link_types.every((type) => typeof type === 'string')\n ? [...(entry.link_types as string[])]\n : undefined\n const linkLevels = isRecord(entry.link_levels)\n ? Object.fromEntries(\n Object.entries(entry.link_levels).filter(\n (pair): pair is [string, number] => typeof pair[1] === 'number'\n )\n )\n : undefined\n return {\n name: entry.name,\n complete_through_block: entry.complete_through_block,\n blocks_behind_head: behind,\n ...(typeof entry.fresh === 'boolean' ? { fresh: entry.fresh } : {}),\n layers: [...(entry.layers as string[])],\n ...(linkTypes ? { link_types: linkTypes } : {}),\n ...(linkLevels ? { link_levels: linkLevels } : {}),\n }\n}\n\n/** The families list, whole or not at all: one entry with a bad shape drops it. */\nfunction advertisedGraphFamilies(raw: unknown): NetworkGraphFamily[] | undefined {\n if (!Array.isArray(raw)) return undefined\n const families: NetworkGraphFamily[] = []\n for (const entry of raw) {\n const family = advertisedGraphFamily(entry)\n if (family === null) return undefined\n families.push(family)\n }\n return families\n}\n\nfunction advertisedGraphProgress(raw: unknown): NetworkGraphProgress | undefined {\n if (!isRecord(raw) || typeof raw.complete_through_block !== 'number') return undefined\n if (!Array.isArray(raw.layers)) return undefined\n const layers: NetworkGraphProgress['layers'] = []\n for (const entry of raw.layers) {\n if (!isRecord(entry) || typeof entry.layer !== 'string' || typeof entry.position !== 'number')\n continue\n layers.push({ layer: entry.layer, position: entry.position })\n }\n const progress: NetworkGraphProgress = {\n complete_through_block: raw.complete_through_block,\n layers,\n }\n const families = advertisedGraphFamilies(raw.families)\n if (families) progress.families = families\n return progress\n}\n\nfunction advertisedNetwork(raw: unknown): NetworkCapability | null {\n if (!isRecord(raw) || typeof raw.network !== 'string' || raw.network.trim() === '') {\n return null\n }\n const network = raw.network.trim()\n const capability: NetworkCapability = {\n network,\n display_name:\n typeof raw.display_name === 'string' && raw.display_name.trim() !== ''\n ? raw.display_name\n : network,\n status: typeof raw.status === 'string' && raw.status.trim() !== '' ? raw.status : 'live',\n tools: advertisedTools(raw.tools),\n }\n // The layer blocks are the server's own words about its limits. They pass\n // through exactly as sent: nothing is added, no default is invented and no\n // member is dropped. A block the server did not send stays absent.\n if (isRecord(raw.layers)) capability.layers = raw.layers as NetworkCapability['layers']\n if (isRecord(raw.chain_admission)) {\n capability.chain_admission = raw.chain_admission as unknown as ChainAdmission\n }\n if (isRecord(raw.topology_admission)) {\n capability.topology_admission = raw.topology_admission as TopologyAdmission\n }\n if (isRecord(raw.facts_admission)) {\n capability.facts_admission = raw.facts_admission as FactsAdmission\n }\n if (raw.default === true) capability.default = true\n if (raw.default === false) capability.default = false\n if (isRecord(raw.coverage)) capability.coverage = raw.coverage as NetworkCapability['coverage']\n if (isRecord(raw.freshness))\n capability.freshness = raw.freshness as NetworkCapability['freshness']\n const laneProgress = advertisedLaneProgress(raw.lane_progress)\n if (laneProgress) capability.lane_progress = laneProgress\n const graphProgress = advertisedGraphProgress(raw.graph_progress)\n if (graphProgress) capability.graph_progress = graphProgress\n return capability\n}\n\n/** Repeat GraphRAG's network list. CIA does not add, drop, or invent names. */\nexport function mirrorGraphNetworkCapabilities(document: {\n networks: unknown[]\n}): NetworkCapabilitiesDocument {\n return {\n schema: 'chain-insights.network-capabilities.v1',\n networks: document.networks\n .map((network) => advertisedNetwork(network))\n .filter((network): network is NetworkCapability => network !== null),\n }\n}\n\nfunction publicNetworkCapabilities(\n document: NetworkCapabilitiesDocument\n): NetworkCapabilitiesDocument {\n return mirrorGraphNetworkCapabilities(document)\n}\n\nfunction metadataNetworksUrl(endpoint: string): URL {\n const url = new URL(endpoint)\n url.pathname = '/metadata/networks'\n url.search = ''\n url.hash = ''\n return url\n}\n\nexport async function fetchNetworkCapabilities(\n config: Pick<InvestigatorConfig, 'graphMcpAuthToken' | 'graphMcpMode' | 'graphMcpEndpoint'>\n): Promise<NetworkCapabilitiesDocument> {\n const endpoint = resolveGraphMcpEndpoint(config)\n const request = metadataNetworksUrl(endpoint)\n const headers = new Headers()\n const token = config.graphMcpAuthToken?.trim()\n if (token) {\n applyMcpAuthHeaders(headers, token)\n }\n let response: Response\n try {\n response = await fetch(request, { headers })\n } catch (err) {\n throw new Error(`network capabilities unavailable at ${request}: ${(err as Error).message}`)\n }\n if (!response.ok) {\n throw new Error(`network capabilities unavailable at ${request}: HTTP ${response.status}`)\n }\n const parsed = (await response.json()) as NetworkCapabilitiesDocument\n if (\n parsed.schema !== 'chain-insights.network-capabilities.v1' ||\n !Array.isArray(parsed.networks)\n ) {\n throw new Error('network capabilities response has unsupported schema')\n }\n return publicNetworkCapabilities(parsed)\n}\n\nfunction availableTools(network: NetworkCapability): string[] {\n const tools = Object.entries(network.tools ?? {})\n .filter(([, status]) => status === 'available')\n .map(([name]) => name)\n return tools.sort()\n}\n\nfunction availableToolLines(network: NetworkCapability): string[] {\n const tools = availableTools(network)\n if (tools.length === 0) return ['none']\n const lines: string[] = []\n for (let index = 0; index < tools.length; index += AVAILABLE_TOOLS_PER_LINE) {\n lines.push(tools.slice(index, index + AVAILABLE_TOOLS_PER_LINE).join(', '))\n }\n return lines\n}\n\nfunction shortDate(value?: string): string {\n if (!value) return ''\n return value.slice(0, 10)\n}\n\nfunction datasetLabel(network: NetworkCapability): string {\n const coverage = network.coverage\n if (!coverage) return 'unknown'\n const blockRange =\n coverage.from_block !== undefined && coverage.to_block !== undefined\n ? `${coverage.from_block}..${coverage.to_block}`\n : 'blocks unknown'\n const dateRange =\n coverage.from_timestamp && coverage.to_timestamp\n ? `${shortDate(coverage.from_timestamp)}..${shortDate(coverage.to_timestamp)}`\n : ''\n if (blockRange === 'blocks unknown' && dateRange === '') return 'unknown'\n if (blockRange === 'blocks unknown') return dateRange\n if (dateRange === '') return blockRange\n return `${blockRange} / ${dateRange}`\n}\n\nfunction displayName(network: NetworkCapability): string {\n return network.display_name || network.network\n}\n\nfunction statusLabel(network: NetworkCapability): string {\n return network.default ? `${network.status} (default)` : network.status\n}\n\nfunction formatTable(headers: string[], rows: string[][], minimumWidths: number[]): string {\n const widths = headers.map((header, index) =>\n Math.max(\n minimumWidths[index] ?? 0,\n header.length,\n ...rows.map((row) => row[index]?.length ?? 0)\n )\n )\n const row = (values: string[]) =>\n values.map((value, index) => value.padEnd(widths[index]!)).join(' ')\n return [row(headers), widths.map((width) => '-'.repeat(width)).join(' '), ...rows.map(row)].join(\n '\\n'\n )\n}\n\nexport function formatNetworkOverview(document: NetworkCapabilitiesDocument): string {\n if (document.networks.length === 0) return 'No supported networks advertised.'\n const rows = document.networks.map((network) => [\n displayName(network),\n statusLabel(network),\n datasetLabel(network),\n ])\n return formatTable(['Network', 'Status', 'Dataset'], rows, [14, 10, 38])\n}\n\nexport function formatNetworkCapabilities(document: NetworkCapabilitiesDocument): string {\n if (document.networks.length === 0) return 'No supported networks advertised.'\n const networkRows = document.networks.flatMap((network) => {\n const toolLines = availableToolLines(network)\n return toolLines.map((toolLine, index) => [\n index === 0 ? displayName(network) : '',\n index === 0 ? datasetLabel(network) : '',\n toolLine,\n ])\n })\n return formatTable(['Network', 'Dataset', 'Chain Insights tools'], networkRows, [14, 38, 64])\n}\n\nexport function findNetworkCapability(\n document: NetworkCapabilitiesDocument,\n name: string\n): NetworkCapability | undefined {\n const normalizedName = name.trim().toLowerCase()\n if (!normalizedName) return undefined\n return document.networks.find((network) =>\n [network.network, network.display_name].some(\n (candidate) => candidate?.trim().toLowerCase() === normalizedName\n )\n )\n}\n\n/** The writer lanes a customer sees, in screen order, by their plain names. */\nconst KNOWN_LANES: readonly (readonly [string, string])[] = [\n ['core_transfers_source_head', 'receipts'],\n ['core_transfers_internal_follow', 'traces'],\n ['core_dex_follow', 'dex'],\n ['core_bridge_follow', 'bridge'],\n ['core_smart_account_follow', 'smart accounts'],\n]\n\n/** The evidence worker's lane. It has its own table and never joins Indexing. */\nconst EVIDENCE_LANE = 'evidence_sync'\n\n/** The plain name a lane prints as. An unknown lane prints as sent. */\nexport function laneDisplayName(lane: string): string {\n if (lane === EVIDENCE_LANE) return 'evidence'\n return KNOWN_LANES.find(([name]) => name === lane)?.[1] ?? lane\n}\n\n/** A graph layer prints as sent: it is the link kind a query names. */\nexport function layerDisplayName(layer: string): string {\n return layer\n}\n\n/** A family prints by its plain name: `smart_accounts` prints as \"smart accounts\". */\nexport function familyDisplayName(family: string): string {\n return family.replace(/_/g, ' ')\n}\n\n/** 87642448 -> \"87,642,448\", the same on every machine (no locale). */\nexport function groupThousands(value: number): string {\n const sign = value < 0 ? '-' : ''\n const digits = String(Math.trunc(Math.abs(value)))\n return sign + digits.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n}\n\n/** One row of a progress table. `behind` is absent with no head or no height. */\ninterface ProgressRow {\n label: string\n height: number | null\n /** Text printed in the height column instead of a number. */\n note?: string\n behind?: number\n}\n\nconst DETAIL_LABEL_WIDTH = 18\nconst TABLE_LABEL_WIDTH = 30\nconst HEIGHT_MIN_WIDTH = 10\nconst LAG_HEADER = 'behind head'\n\nfunction progressRows(\n entries: { label: string; height: number | null }[],\n head: number | undefined\n): ProgressRow[] {\n return entries.map(({ label, height }) => ({\n label,\n height,\n ...(height === null ? { note: 'not started' } : {}),\n ...(height !== null && head !== undefined ? { behind: Math.max(0, head - height) } : {}),\n }))\n}\n\nfunction notReportedRow(label: string): ProgressRow {\n return { label, height: null, note: 'not reported' }\n}\n\n/**\n * The family rows, in the order the server sends them. A block family's lag is\n * the server's `blocks_behind_head`, or head minus height when the server knows\n * no head. A family with no block (annotations) prints \"fresh\" or \"walking\" and\n * no lag.\n */\nfunction familyRows(families: NetworkGraphFamily[], head: number | undefined): ProgressRow[] {\n return families.map((family) => {\n const label = familyDisplayName(family.name)\n const height = family.complete_through_block\n if (height === null) {\n const note = family.fresh === undefined ? 'not started' : family.fresh ? 'fresh' : 'walking'\n return { label, height: null, note }\n }\n if (head === undefined) return { label, height }\n const behind = family.blocks_behind_head ?? Math.max(0, head - height)\n return { label, height, behind }\n })\n}\n\nfunction formatProgressTables(\n tables: { title: string; rows: ProgressRow[] }[],\n withLag: boolean\n): string[] {\n const allRows = tables.flatMap((table) => table.rows)\n const labelWidth = Math.max(\n TABLE_LABEL_WIDTH,\n ...allRows.map((row) => row.label.length + 4),\n ...tables.map((table) => table.title.length + 2)\n )\n const heightWidth = Math.max(\n HEIGHT_MIN_WIDTH,\n ...allRows.map((row) => (row.height === null ? 0 : groupThousands(row.height).length))\n )\n const lagWidth = Math.max(\n LAG_HEADER.length,\n ...allRows.map((row) => (row.behind === undefined ? 0 : groupThousands(row.behind).length))\n )\n const lines: string[] = []\n for (const table of tables) {\n if (lines.length > 0) lines.push('')\n const header = table.title.padEnd(labelWidth) + 'height'\n lines.push(withLag ? header.padEnd(labelWidth + heightWidth + 2) + LAG_HEADER : header)\n for (const row of table.rows) {\n let line = ` ${row.label}`.padEnd(labelWidth)\n if (row.height === null) {\n line += row.note ?? ''\n } else {\n line += groupThousands(row.height).padStart(heightWidth)\n if (withLag && row.behind !== undefined) {\n line += ' ' + groupThousands(row.behind).padStart(lagWidth)\n }\n }\n lines.push(line.trimEnd())\n }\n }\n return lines\n}\n\n/**\n * `cia network <name>`: how far this network is indexed. The chain node's head\n * comes first; every row reads against it. Known lanes print by plain name,\n * unknown lanes as sent after them, the layer families by plain name in the\n * server's order, graph layers as sent, and evidence in its own table. Heights\n * are right-aligned, so a shorter height lines up by its last digit.\n * `--json` never comes through here.\n */\nexport function formatNetworkCapability(network: NetworkCapability): string {\n const headBlock = network.freshness?.chain_head_block\n const head = typeof headBlock === 'number' ? headBlock : undefined\n const detail: [string, string][] = [\n ['Network', displayName(network)],\n ['Identifier', network.network],\n ['Status', statusLabel(network)],\n ]\n if (head !== undefined) {\n const age = network.freshness?.chain_head_age_seconds\n const ageText = typeof age === 'number' ? ` (${groupThousands(age)} s old)` : ''\n detail.push(['Blockchain head', `${groupThousands(head)}${ageText}`])\n }\n\n const lanes = network.lane_progress ?? []\n const known = KNOWN_LANES.flatMap(([name, label]) =>\n lanes.filter((lane) => lane.lane === name).map((lane) => ({ label, height: lane.height }))\n )\n const unknown = lanes\n .filter(\n (lane) => lane.lane !== EVIDENCE_LANE && !KNOWN_LANES.some(([name]) => name === lane.lane)\n )\n .map((lane) => ({ label: laneDisplayName(lane.lane), height: lane.height }))\n const indexing = [...known, ...unknown]\n const layers = (network.graph_progress?.layers ?? []).map((layer) => ({\n label: layerDisplayName(layer.layer),\n height: layer.position,\n }))\n const evidence = lanes\n .filter((lane) => lane.lane === EVIDENCE_LANE)\n .map((lane) => ({ label: laneDisplayName(lane.lane), height: lane.height }))\n\n const families = network.graph_progress?.families\n\n const tables = [\n {\n title: 'Indexing',\n rows: indexing.length > 0 ? progressRows(indexing, head) : [notReportedRow('indexing')],\n },\n // Absent on a server that sends no families: the table is left out, so the\n // screen of such a server stays as it was.\n ...(families ? [{ title: 'Families', rows: familyRows(families, head) }] : []),\n {\n title: 'Graph',\n rows: layers.length > 0 ? progressRows(layers, head) : [notReportedRow('graph')],\n },\n {\n title: 'Evidence',\n rows: evidence.length > 0 ? progressRows(evidence, head) : [notReportedRow('evidence')],\n },\n ]\n\n return [\n ...detail.map(([label, value]) => `${label.padEnd(DETAIL_LABEL_WIDTH)}${value}`),\n '',\n ...formatProgressTables(tables, head !== undefined),\n ].join('\\n')\n}\n\n/**\n * The shape of a lane's swap links, read from its `network_capabilities` reply:\n * `levels` when its money family lists ROUTED_TO, else `route`. A call that\n * fails, or a reply that lists no such network, gives no shape (undefined): the\n * caller uses `route` for that one call and asks again on the next.\n */\nexport async function readSwapLinkShape(\n client: { callTool: (request: { name: string; arguments: Record<string, unknown> }) => Promise<unknown> },\n network: string\n): Promise<SwapLinkShape | undefined> {\n try {\n const answer = await client.callTool({ name: 'network_capabilities', arguments: {} })\n const structured = isRecord(answer) ? answer.structuredContent : undefined\n const facts = isRecord(structured) ? structured.facts : undefined\n const capabilities = isRecord(facts) ? facts.capabilities : undefined\n const networks =\n isRecord(capabilities) && Array.isArray(capabilities.networks) ? capabilities.networks : []\n const capability = findNetworkCapability(mirrorGraphNetworkCapabilities({ networks }), network)\n if (!capability) return undefined\n return swapLinkShape(capability.graph_progress?.families)\n } catch {\n return undefined\n }\n}\n\n/**\n * A lane's shape, kept `ttlMs` per network once a read gives one. A read that\n * gives none is never kept: that call answers `route`, the next reads again.\n */\nexport function keptSwapLinkShape(\n read: (network: string) => Promise<SwapLinkShape | undefined>,\n ttlMs: number,\n now: () => number = Date.now\n): (network: string) => Promise<SwapLinkShape> {\n const kept = new Map<string, { shape: SwapLinkShape; at: number }>()\n return async (network) => {\n const entry = kept.get(network)\n if (entry && now() - entry.at < ttlMs) return entry.shape\n const shape = await read(network)\n if (shape === undefined) return 'route'\n kept.set(network, { shape, at: now() })\n return shape\n }\n}\n"],"mappings":";;;;;;;;;;;AAqJA,MAAM,2BAA2B;AAEjC,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,gBAAgB,KAAsC;CAC7D,IAAI,CAAC,SAAS,GAAG,GAAG,OAAO,CAAC;CAC5B,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,GAAG,GAC7C,IAAI,KAAK,KAAK,MAAM,MAAM,OAAO,WAAW,UAAU,MAAM,QAAQ;CAEtE,OAAO;AACT;AAEA,SAAS,uBAAuB,KAAiD;CAC/E,IAAI,CAAC,MAAM,QAAQ,GAAG,GAAG,OAAO,KAAA;CAChC,MAAM,QAA+B,CAAC;CACtC,KAAK,MAAM,SAAS,KAAK;EACvB,IAAI,CAAC,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,YAAY,MAAM,KAAK,KAAK,MAAM,IAAI;EACpF,IAAI,OAAO,MAAM,WAAW,UAAU,MAAM,KAAK;GAAE,MAAM,MAAM;GAAM,QAAQ,MAAM;EAAO,CAAC;OACtF,IAAI,MAAM,WAAW,MAAM,MAAM,KAAK;GAAE,MAAM,MAAM;GAAM,QAAQ;EAAK,CAAC;CAC/E;CACA,OAAO;AACT;AAEA,SAAS,eAAe,OAAwC;CAC9D,OAAO,UAAU,QAAQ,OAAO,UAAU;AAC5C;;AAGA,SAAS,sBAAsB,OAA2C;CACxE,IAAI,CAAC,SAAS,KAAK,KAAK,OAAO,MAAM,SAAS,YAAY,MAAM,KAAK,KAAK,MAAM,IAAI,OAAO;CAC3F,IAAI,CAAC,eAAe,MAAM,sBAAsB,GAAG,OAAO;CAC1D,MAAM,SAAS,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