chain-insights 0.74.1 → 0.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +3 -2
  2. package/dist/{action-log-D49Par9P.mjs → action-log-Byv9Ln_6.mjs} +4 -10
  3. package/dist/{action-log-D49Par9P.mjs.map → action-log-Byv9Ln_6.mjs.map} +1 -1
  4. package/dist/{action-log-HniMMF7f.cjs → action-log-WMW6xFMx.cjs} +3 -9
  5. package/dist/{active-Dkf8AB1R.mjs → active-D2aabYRF.mjs} +3 -4
  6. package/dist/{active-Dkf8AB1R.mjs.map → active-D2aabYRF.mjs.map} +1 -1
  7. package/dist/{active-Bc13hJIm.cjs → active-q3yViZhc.cjs} +2 -3
  8. package/dist/answer-hint-BlYEBq_Y.cjs +57 -0
  9. package/dist/answer-hint-vOE1O6Lf.mjs +48 -0
  10. package/dist/answer-hint-vOE1O6Lf.mjs.map +1 -0
  11. package/dist/{buy-_mpdRieG.mjs → buy-B2luUbWF.mjs} +5 -6
  12. package/dist/{buy-_mpdRieG.mjs.map → buy-B2luUbWF.mjs.map} +1 -1
  13. package/dist/{buy-97M6dtEu.cjs → buy-DEoGITbT.cjs} +4 -5
  14. package/dist/{cache-location-CBVzUIxq.cjs → cache-location-C09AE55j.cjs} +2 -3
  15. package/dist/{cache-location-BO2XkfgI.mjs → cache-location-DxTTqBwk.mjs} +2 -3
  16. package/dist/{cache-location-BO2XkfgI.mjs.map → cache-location-DxTTqBwk.mjs.map} +1 -1
  17. package/dist/{call-args-B0oMK1-J.mjs → call-args-CBqbYfOE.mjs} +15 -4
  18. package/dist/{call-args-B0oMK1-J.mjs.map → call-args-CBqbYfOE.mjs.map} +1 -1
  19. package/dist/{call-args-C8Gp5gco.cjs → call-args-DXEmPeE-.cjs} +14 -2
  20. package/dist/{capabilities-DxojbX4D.mjs → capabilities-BRNHcabF.mjs} +5 -11
  21. package/dist/{capabilities-DxojbX4D.mjs.map → capabilities-BRNHcabF.mjs.map} +1 -1
  22. package/dist/{capabilities-Ds3320iS.cjs → capabilities-DalimVY2.cjs} +4 -10
  23. package/dist/{claude-desktop-Jmm4PlBZ.cjs → claude-desktop-3OksQZVE.cjs} +2 -3
  24. package/dist/{claude-desktop-6jwX0Lux.mjs → claude-desktop-C1SDYAP2.mjs} +2 -3
  25. package/dist/{claude-desktop-6jwX0Lux.mjs.map → claude-desktop-C1SDYAP2.mjs.map} +1 -1
  26. package/dist/cli.cjs +95 -76
  27. package/dist/cli.mjs +94 -75
  28. package/dist/cli.mjs.map +1 -1
  29. package/dist/{client-7qOfAdpH.mjs → client-BaHAIidE.mjs} +10 -21
  30. package/dist/{client-7qOfAdpH.mjs.map → client-BaHAIidE.mjs.map} +1 -1
  31. package/dist/{client-C9uwHnBS.cjs → client-Ddk4X9Ko.cjs} +9 -20
  32. package/dist/{config-BxtMoo9c.cjs → config-BdE8LcF-.cjs} +3 -5
  33. package/dist/{config-9MabJh5R.mjs → config-BkLIqOYq.mjs} +4 -6
  34. package/dist/{config-9MabJh5R.mjs.map → config-BkLIqOYq.mjs.map} +1 -1
  35. package/dist/{create-CpfZq2fx.mjs → create-CluDZkuF.mjs} +3 -4
  36. package/dist/{create-CpfZq2fx.mjs.map → create-CluDZkuF.mjs.map} +1 -1
  37. package/dist/{create-DdggkF04.cjs → create-DvBumvHn.cjs} +2 -3
  38. package/dist/{dex-registry-Chs79Ukc.cjs → dex-registry-CZQB2YhU.cjs} +4 -26
  39. package/dist/{dex-registry-rziydXYq.mjs → dex-registry-D6Xxi_vr.mjs} +5 -27
  40. package/dist/{dex-registry-rziydXYq.mjs.map → dex-registry-D6Xxi_vr.mjs.map} +1 -1
  41. package/dist/{dex-tool-DsaAIa-a.mjs → dex-tool-BoAYqhZO.mjs} +13 -67
  42. package/dist/dex-tool-BoAYqhZO.mjs.map +1 -0
  43. package/dist/{dex-tool-DLWnff1n.cjs → dex-tool-DsM-pSku.cjs} +17 -77
  44. package/dist/{format-CSesEBvS.mjs → format-CsnW5M4D.mjs} +2 -3
  45. package/dist/{format-CSesEBvS.mjs.map → format-CsnW5M4D.mjs.map} +1 -1
  46. package/dist/{format-DfhRQq4L.cjs → format-DUzmoeaE.cjs} +1 -2
  47. package/dist/{graph-schema-BGbJumCY.cjs → graph-schema-C8Pi6r7c.cjs} +12 -29
  48. package/dist/{graph-schema-ClqjzgrM.mjs → graph-schema-D4LAefGf.mjs} +13 -30
  49. package/dist/graph-schema-D4LAefGf.mjs.map +1 -0
  50. package/dist/index.cjs +7 -7
  51. package/dist/index.d.cts +0 -16
  52. package/dist/index.d.cts.map +1 -1
  53. package/dist/index.d.mts +0 -16
  54. package/dist/index.d.mts.map +1 -1
  55. package/dist/index.mjs +7 -7
  56. package/dist/{known-keys-B87ZqOgE.mjs → known-keys-BbuzCZOW.mjs} +4 -7
  57. package/dist/{known-keys-B87ZqOgE.mjs.map → known-keys-BbuzCZOW.mjs.map} +1 -1
  58. package/dist/{known-keys-PKZF5GYd.cjs → known-keys-Cy8lKDOA.cjs} +3 -6
  59. package/dist/mcp-proxy.cjs +83 -57
  60. package/dist/mcp-proxy.d.cts +2 -2
  61. package/dist/mcp-proxy.d.cts.map +1 -1
  62. package/dist/mcp-proxy.d.mts +2 -2
  63. package/dist/mcp-proxy.d.mts.map +1 -1
  64. package/dist/mcp-proxy.mjs +81 -56
  65. package/dist/mcp-proxy.mjs.map +1 -1
  66. package/dist/{print-result-Cyqrlx8P.cjs → print-result-BYppJlUi.cjs} +20 -20
  67. package/dist/{print-result-C3YazZBw.mjs → print-result-IFARsMnL.mjs} +10 -22
  68. package/dist/print-result-IFARsMnL.mjs.map +1 -0
  69. package/dist/{public-tools-Bl_l_rKK.cjs → public-tools-Cfc1OPNS.cjs} +16 -21
  70. package/dist/{public-tools-CQjGt7_q.mjs → public-tools-DXlZcanX.mjs} +16 -21
  71. package/dist/public-tools-DXlZcanX.mjs.map +1 -0
  72. package/dist/{quote-DfTut0cx.mjs → quote-41CbMc37.mjs} +2 -3
  73. package/dist/{quote-DfTut0cx.mjs.map → quote-41CbMc37.mjs.map} +1 -1
  74. package/dist/{quote-B9sYNOiv.cjs → quote-pFKcSvMv.cjs} +1 -2
  75. package/dist/{request-timeout-CYmQF8N7.cjs → request-timeout-DxwNijQD.cjs} +1 -2
  76. package/dist/{request-timeout-lBBe0mGf.mjs → request-timeout-K3ljP0pa.mjs} +2 -3
  77. package/dist/{request-timeout-lBBe0mGf.mjs.map → request-timeout-K3ljP0pa.mjs.map} +1 -1
  78. package/dist/{robinhood-CCTMagwM.mjs → robinhood-0NZsA6ZW.mjs} +2 -3
  79. package/dist/robinhood-0NZsA6ZW.mjs.map +1 -0
  80. package/dist/{robinhood-ChiT69sc.cjs → robinhood-DumTxvlA.cjs} +1 -2
  81. package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
  82. package/dist/{rolldown-runtime-C0BPl7ul.cjs → rolldown-runtime-BW-eSwOZ.cjs} +1 -2
  83. package/dist/{rules-BWdbOtHi.mjs → rules-B3w9pCeQ.mjs} +2 -3
  84. package/dist/{rules-BWdbOtHi.mjs.map → rules-B3w9pCeQ.mjs.map} +1 -1
  85. package/dist/{rules-BD-cNHMX.cjs → rules-BKwfmNsJ.cjs} +1 -2
  86. package/dist/{schema-KjZqCHbu.mjs → schema-CKnQsdw9.mjs} +6 -13
  87. package/dist/{schema-KjZqCHbu.mjs.map → schema-CKnQsdw9.mjs.map} +1 -1
  88. package/dist/{schema-tX0U0-VI.cjs → schema-CSESfCvA.cjs} +5 -12
  89. package/dist/{schema-cache-DRObKUvS.mjs → schema-cache-BfKHodDY.mjs} +3 -4
  90. package/dist/{schema-cache-DRObKUvS.mjs.map → schema-cache-BfKHodDY.mjs.map} +1 -1
  91. package/dist/{schema-cache-C7v9ml6S.cjs → schema-cache-NLgJmh4X.cjs} +3 -4
  92. package/dist/{skill-refresh-xYWZ_hua.mjs → skill-refresh-BchIsODN.mjs} +2 -3
  93. package/dist/{skill-refresh-xYWZ_hua.mjs.map → skill-refresh-BchIsODN.mjs.map} +1 -1
  94. package/dist/{skill-refresh-Be2D5FrX.cjs → skill-refresh-DaCTxhhy.cjs} +2 -3
  95. package/dist/{subscription-status-DIuH84fM.mjs → subscription-status-5WfPhSep.mjs} +3 -4
  96. package/dist/{subscription-status-DIuH84fM.mjs.map → subscription-status-5WfPhSep.mjs.map} +1 -1
  97. package/dist/{subscription-status-9tMfD90J.cjs → subscription-status-w4zI2KCK.cjs} +2 -3
  98. package/dist/token-lookup-BJ00JO9A.cjs +342 -0
  99. package/dist/token-lookup-XnyisLQW.mjs +303 -0
  100. package/dist/token-lookup-XnyisLQW.mjs.map +1 -0
  101. package/dist/{tool-visibility-BNwvcuVx.cjs → tool-visibility-DIpgPULN.cjs} +5 -10
  102. package/dist/{tool-visibility-B6983rxo.mjs → tool-visibility-Dy3psowS.mjs} +6 -11
  103. package/dist/tool-visibility-Dy3psowS.mjs.map +1 -0
  104. package/dist/{tools-D9ep9E7Q.mjs → tools-6pZo4h_p.mjs} +6 -21
  105. package/dist/{tools-D9ep9E7Q.mjs.map → tools-6pZo4h_p.mjs.map} +1 -1
  106. package/dist/{tools-Cmnq7yip.cjs → tools-DZLizem9.cjs} +5 -20
  107. package/dist/{topup-B6gZbTmv.mjs → topup--7JTo4UQ.mjs} +6 -7
  108. package/dist/{topup-B6gZbTmv.mjs.map → topup--7JTo4UQ.mjs.map} +1 -1
  109. package/dist/{topup-DVTCU2le.cjs → topup-BgI9OcUd.cjs} +5 -6
  110. package/dist/{topup-server-ShuYSyBY.cjs → topup-server-D9Uk1Th3.cjs} +7 -24
  111. package/dist/{topup-server-KQDviFXG.mjs → topup-server-DR0HaUcR.mjs} +8 -25
  112. package/dist/{topup-server-KQDviFXG.mjs.map → topup-server-DR0HaUcR.mjs.map} +1 -1
  113. package/dist/{topup-server-BcT7DIpd.mjs → topup-server-DlwzFEF1.mjs} +5 -12
  114. package/dist/{topup-server-BcT7DIpd.mjs.map → topup-server-DlwzFEF1.mjs.map} +1 -1
  115. package/dist/{topup-server-f4Gx0vji.cjs → topup-server-H1M_7PJK.cjs} +4 -11
  116. package/dist/{transport-error-D4hmpkqL.mjs → transport-error-68G35VPH.mjs} +3 -4
  117. package/dist/{transport-error-D4hmpkqL.mjs.map → transport-error-68G35VPH.mjs.map} +1 -1
  118. package/dist/{transport-error-CgISST8l.cjs → transport-error-DXy1iTpS.cjs} +2 -3
  119. package/dist/{update-CZDHSi_u.mjs → update-BH8F4cQ2.mjs} +3 -4
  120. package/dist/{update-CZDHSi_u.mjs.map → update-BH8F4cQ2.mjs.map} +1 -1
  121. package/dist/{update-DGyRlm3J.cjs → update-DUDdQSEU.cjs} +2 -3
  122. package/dist/{usage-status-Frot6fPG.mjs → usage-status-BUZgRl4r.mjs} +3 -5
  123. package/dist/{usage-status-Frot6fPG.mjs.map → usage-status-BUZgRl4r.mjs.map} +1 -1
  124. package/dist/{usage-status-DonwoLR3.cjs → usage-status-DnV3I3gX.cjs} +2 -4
  125. package/dist/{wallet-QTo5YCFR.mjs → wallet-B1M0HdQh.mjs} +4 -8
  126. package/dist/{wallet-QTo5YCFR.mjs.map → wallet-B1M0HdQh.mjs.map} +1 -1
  127. package/dist/{wallet-CgIAfdxL.cjs → wallet-BubGd_sG.cjs} +3 -7
  128. package/docs/graph-query-compatibility.md +13 -13
  129. package/docs/graph-tools.md +22 -22
  130. package/docs/mcp-proxy.md +35 -1
  131. package/docs/stability.md +3 -2
  132. package/package.json +1 -1
  133. package/skills/chain-insights-cypher/SKILL.md +30 -27
  134. package/skills/chain-insights-dex/SKILL.md +2 -2
  135. package/skills/chain-insights-dex/reference.md +1 -1
  136. package/skills/chain-insights-dex-gauge/SKILL.md +4 -4
  137. package/skills/chain-insights-dex-launchpad/SKILL.md +2 -2
  138. package/skills/chain-insights-virtuals/reference.md +5 -5
  139. package/dist/dex-tool-DsaAIa-a.mjs.map +0 -1
  140. package/dist/graph-schema-ClqjzgrM.mjs.map +0 -1
  141. package/dist/print-result-C3YazZBw.mjs.map +0 -1
  142. package/dist/public-tools-CQjGt7_q.mjs.map +0 -1
  143. package/dist/robinhood-CCTMagwM.mjs.map +0 -1
  144. package/dist/tool-visibility-B6983rxo.mjs.map +0 -1
package/README.md CHANGED
@@ -107,6 +107,7 @@ Never touches:
107
107
  | `meta_network_capabilities` | Check supported Chain Insights networks and graph tools |
108
108
  | `meta_schema` | Read the live graph schema of a network: labels, link types, fields, indexes |
109
109
  | `meta_dex_lookup` | Turn an exchange name (Aero, Uniswap, Virtuals) into its contracts, pools, reads |
110
+ | `meta_token_lookup` | Turn a ticker or a token name (TCITY, USDG) into every contract that carries it |
110
111
  | `meta_usage_status` | Check the caller's daily free-tier graph query allowance |
111
112
  | `meta_subscription_status` | Check your wallet's subscription: days left, today's allowance, payments pending |
112
113
  | `meta_rules` | Read the answer rules when the `chain-insights-cypher` skill is not loaded |
@@ -173,7 +174,7 @@ Graph queries choose the read graph explicitly:
173
174
 
174
175
  | Graph | Use it for |
175
176
  | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
176
- | `topology` | The unified address / FLOWS_TO / OPERATED_BY / LINKED graph — recent and full historical fund-flow traversal, and swap, liquidity-pool and bridge totals (see [Graph tools](docs/graph-tools.md#swaps-liquidity-pools-and-bridges)) |
177
+ | `topology` | The unified address / FLOWED_TO / OPERATED_BY / LINKED graph — recent and full historical fund-flow traversal, and swap, liquidity-pool and bridge totals (see [Graph tools](docs/graph-tools.md#swaps-liquidity-pools-and-bridges)) |
177
178
  | `facts` | Bounded individual `TRANSFER` rows with amount, `amount_usd`, asset, transaction, and block facts, plus single `SWAP`, `LIQUIDITY_ADD`, `LIQUIDITY_REMOVE` and `BRIDGE_CROSSING` rows |
178
179
  | `chain` | One keyed lookup on the chain node: a transaction by `tx_id`, a block by `block_height` or `block_hash`, an address at one block (balance, nonce, kind), or the head |
179
180
 
@@ -315,7 +316,7 @@ Batch across graph views:
315
316
  ```bash
316
317
  cia mcp call graph_query_batch \
317
318
  network=robinhood \
318
- 'queries=[{"id":"count","query":"USE topology MATCH (a:Address) RETURN count(a) AS count LIMIT 1"},{"id":"flows","query":"USE topology MATCH (src:Address)-[f:FLOWS_TO]->(dst:Address) RETURN src.address AS source, dst.address AS target, f.amount_usd_sum AS amount_usd_sum, f.tx_count AS tx_count LIMIT 3"},{"id":"linked","query":"USE topology MATCH (a:Address)-[l:LINKED]-(b:Address) RETURN a.address AS address, b.address AS linked_address, l.basis AS basis, l.confidence AS confidence LIMIT 3"},{"id":"node_metrics","query":"USE topology MATCH (a:Address {address:\"FULL_ADDRESS\"}) RETURN a.address AS address, a.tx_out_count AS tx_out_count, a.tx_in_count AS tx_in_count LIMIT 1"}]'
319
+ 'queries=[{"id":"count","query":"USE topology MATCH (a:Address) RETURN count(a) AS count LIMIT 1"},{"id":"flows","query":"USE topology MATCH (src:Address)-[f:FLOWED_TO]->(dst:Address) RETURN src.address AS source, dst.address AS target, f.amount_usd_sum AS amount_usd_sum, f.tx_count AS tx_count LIMIT 3"},{"id":"linked","query":"USE topology MATCH (a:Address)-[l:LINKED]-(b:Address) RETURN a.address AS address, b.address AS linked_address, l.basis AS basis, l.confidence AS confidence LIMIT 3"},{"id":"node_metrics","query":"USE topology MATCH (a:Address {address:\"FULL_ADDRESS\"}) RETURN a.address AS address, a.tx_out_count AS tx_out_count, a.tx_in_count AS tx_in_count LIMIT 1"}]'
319
320
  ```
320
321
 
321
322
  More query examples (manual fund-flow reads, pagination):
@@ -1,13 +1,8 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
2
  import path from "node:path";
3
3
  import { appendFile, mkdir } from "node:fs/promises";
4
- //#region src/mcp/action-log.ts
5
- var action_log_exports = /* @__PURE__ */ __exportAll({
6
- actionLogPath: () => actionLogPath,
7
- actionLogSignalsFromResult: () => actionLogSignalsFromResult,
8
- appendActionLog: () => appendActionLog,
9
- installActionLogging: () => installActionLogging
10
- });
4
+ // src/mcp/action-log.ts
5
+ var action_log_exports = /* @__PURE__ */ __exportAll({ installActionLogging: () => installActionLogging });
11
6
  function actionLogPath() {
12
7
  const configured = process.env.CIA_ACTION_LOG?.trim();
13
8
  return configured ? configured : void 0;
@@ -87,7 +82,6 @@ function installActionLogging(client) {
87
82
  client.callTool = wrapped;
88
83
  return client;
89
84
  }
90
- //#endregion
91
85
  export { action_log_exports as n, appendActionLog as r, actionLogSignalsFromResult as t };
92
86
 
93
- //# sourceMappingURL=action-log-D49Par9P.mjs.map
87
+ //# sourceMappingURL=action-log-Byv9Ln_6.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"action-log-D49Par9P.mjs","names":[],"sources":["../src/mcp/action-log.ts"],"sourcesContent":["// src/mcp/action-log.ts\n// Optional append-only record of every MCP tool invocation, for operators\n// running cia unattended who need to audit what ran and why a result looked\n// the way it did. Off unless CIA_ACTION_LOG names a path.\n//\n// `warnings` and `search_limits` are captured deliberately: they are how a\n// reader tells \"found nothing\" from \"hit a cap\", which is invisible in the\n// result alone.\nimport { appendFile, mkdir } from 'node:fs/promises'\nimport path from 'node:path'\n\nexport interface ActionLogEntry {\n timestamp: number\n tool: string\n args: Record<string, unknown>\n outcome: 'ok' | 'error'\n duration_ms: number\n result_counts?: Record<string, number>\n warnings?: string[]\n search_limits?: Record<string, unknown>\n error?: string\n}\n\nexport function actionLogPath(): string | undefined {\n const configured = process.env.CIA_ACTION_LOG?.trim()\n return configured ? configured : undefined\n}\n\n// Some special filesystems (notably /proc) answer mkdir on a child with\n// ENOENT even though the parent visibly exists. Node's fs.mkdir(dir,\n// {recursive: true}) treats that as a transient race and retries with no\n// cap, which spins forever rather than rejecting — confirmed via strace\n// (an unbounded, rapid mkdir/statx loop; the event loop stays live and the\n// process never blocks, it just never stops). Walking the path ourselves,\n// one plain mkdir per component with no retry, makes every case settle in\n// a bounded number of syscalls: EEXIST is expected and skipped, anything\n// else (including that ENOENT-on-existing-parent case) fails once instead\n// of retrying.\nasync function ensureDir(dir: string): Promise<void> {\n const segments = dir.split(path.sep).filter(Boolean)\n let current = path.isAbsolute(dir) ? path.sep : ''\n for (const segment of segments) {\n current = current ? path.join(current, segment) : segment\n try {\n await mkdir(current)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') continue\n throw err\n }\n }\n}\n\n// A residual, undemonstrated risk remains distinct from the mkdir retry loop\n// above: a single mkdir/appendFile syscall genuinely wedged on a stalled\n// filesystem (e.g. a hung network mount) blocks like any normal blocking I/O\n// would. Node's fs promises do not support cancelling an in-flight mkdir, so\n// a bounded wait here only frees the *caller* — the wedged operation itself\n// keeps running in the background until the OS/filesystem gives up on its\n// own. That is an accepted, documented limitation, not a bug this module can\n// fix from userland; it is unrelated to (and much rarer than) the retry-loop\n// case ensureDir() eliminates above.\nconst WRITE_TIMEOUT_MS = 2000\n\nasync function writeEntry(file: string, entry: ActionLogEntry): Promise<void> {\n await ensureDir(path.dirname(file))\n await appendFile(file, JSON.stringify(entry) + '\\n', 'utf8')\n}\n\n// Never throws, and never hangs beyond WRITE_TIMEOUT_MS. A failure (or a\n// stall) recording an action must not fail (or stall) the action:\n// observability that can break the thing it observes is worse than none.\nexport async function appendActionLog(entry: ActionLogEntry): Promise<void> {\n const file = actionLogPath()\n if (!file) return\n try {\n await Promise.race([\n writeEntry(file, entry),\n new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, WRITE_TIMEOUT_MS)\n timer.unref?.()\n }),\n ])\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// Exported so BOTH client paths log identically: the MCP proxy's remote client\n// and the CLI's own client. They are separate clients, and wiring only one is how\n// an unattended instance ends up with an empty log while the mechanism 'works'.\nexport function actionLogSignalsFromResult(result: unknown): {\n warnings?: string[]\n search_limits?: Record<string, unknown>\n} {\n const structuredContent = isRecord(result) ? result['structuredContent'] : undefined\n if (!isRecord(structuredContent)) return {}\n const warnings = Array.isArray(structuredContent['warnings'])\n ? (structuredContent['warnings'] as string[])\n : undefined\n const input = structuredContent['input']\n const search_limits =\n isRecord(input) && isRecord(input['search_limits'])\n ? (input['search_limits'] as Record<string, unknown>)\n : undefined\n return { warnings, search_limits }\n}\n\ntype CallToolFn = (...args: never[]) => Promise<unknown>\n\n// Wrap a client's callTool so every invocation is recorded. Returns the client.\n// Idempotent-unsafe: call once per client.\nexport function installActionLogging<T extends { callTool: CallToolFn }>(client: T): T {\n const original = client.callTool.bind(client) as CallToolFn\n const wrapped = (async (...args: never[]) => {\n const startedAt = Date.now()\n const input = (args[0] ?? {}) as { name?: unknown; arguments?: Record<string, unknown> }\n const tool = String(input.name ?? 'unknown')\n const toolArgs = input.arguments ?? {}\n try {\n const result = await original(...args)\n const { warnings, search_limits } = actionLogSignalsFromResult(result)\n await appendActionLog({\n timestamp: startedAt,\n tool,\n args: toolArgs,\n outcome: 'ok',\n duration_ms: Date.now() - startedAt,\n warnings,\n search_limits,\n })\n return result\n } catch (err) {\n await appendActionLog({\n timestamp: startedAt,\n tool,\n args: toolArgs,\n outcome: 'error',\n duration_ms: Date.now() - startedAt,\n error: (err as Error).message,\n })\n throw err\n }\n }) as CallToolFn\n client.callTool = wrapped as T['callTool']\n return client\n}\n"],"mappings":";;;;;;;;;;AAuBA,SAAgB,gBAAoC;CAClD,MAAM,aAAa,QAAQ,IAAI,gBAAgB,KAAK;CACpD,OAAO,aAAa,aAAa,KAAA;AACnC;AAYA,eAAe,UAAU,KAA4B;CACnD,MAAM,WAAW,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,OAAO,OAAO;CACnD,IAAI,UAAU,KAAK,WAAW,GAAG,IAAI,KAAK,MAAM;CAChD,KAAK,MAAM,WAAW,UAAU;EAC9B,UAAU,UAAU,KAAK,KAAK,SAAS,OAAO,IAAI;EAClD,IAAI;GACF,MAAM,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MAAM,SAAS,MAAM,SAAS,GAAG,IAAI;GACrC,MAAM,EAAE,UAAU,kBAAkB,2BAA2B,MAAM;GACrE,MAAM,gBAAgB;IACpB,WAAW;IACX;IACA,MAAM;IACN,SAAS;IACT,aAAa,KAAK,IAAI,IAAI;IAC1B;IACA;GACF,CAAC;GACD,OAAO;EACT,SAAS,KAAK;GACZ,MAAM,gBAAgB;IACpB,WAAW;IACX;IACA,MAAM;IACN,SAAS;IACT,aAAa,KAAK,IAAI,IAAI;IAC1B,OAAQ,IAAc;GACxB,CAAC;GACD,MAAM;EACR;CACF;CACA,OAAO,WAAW;CAClB,OAAO;AACT"}
1
+ {"version":3,"file":"action-log-Byv9Ln_6.mjs","names":[],"sources":["../src/mcp/action-log.ts"],"sourcesContent":["// src/mcp/action-log.ts\n// Optional append-only record of every MCP tool invocation, for operators\n// running cia unattended who need to audit what ran and why a result looked\n// the way it did. Off unless CIA_ACTION_LOG names a path.\n//\n// `warnings` and `search_limits` are captured deliberately: they are how a\n// reader tells \"found nothing\" from \"hit a cap\", which is invisible in the\n// result alone.\nimport { appendFile, mkdir } from 'node:fs/promises'\nimport path from 'node:path'\n\nexport interface ActionLogEntry {\n timestamp: number\n tool: string\n args: Record<string, unknown>\n outcome: 'ok' | 'error'\n duration_ms: number\n result_counts?: Record<string, number>\n warnings?: string[]\n search_limits?: Record<string, unknown>\n error?: string\n}\n\nexport function actionLogPath(): string | undefined {\n const configured = process.env.CIA_ACTION_LOG?.trim()\n return configured ? configured : undefined\n}\n\n// Some special filesystems (notably /proc) answer mkdir on a child with\n// ENOENT even though the parent visibly exists. Node's fs.mkdir(dir,\n// {recursive: true}) treats that as a transient race and retries with no\n// cap, which spins forever rather than rejecting — confirmed via strace\n// (an unbounded, rapid mkdir/statx loop; the event loop stays live and the\n// process never blocks, it just never stops). Walking the path ourselves,\n// one plain mkdir per component with no retry, makes every case settle in\n// a bounded number of syscalls: EEXIST is expected and skipped, anything\n// else (including that ENOENT-on-existing-parent case) fails once instead\n// of retrying.\nasync function ensureDir(dir: string): Promise<void> {\n const segments = dir.split(path.sep).filter(Boolean)\n let current = path.isAbsolute(dir) ? path.sep : ''\n for (const segment of segments) {\n current = current ? path.join(current, segment) : segment\n try {\n await mkdir(current)\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') continue\n throw err\n }\n }\n}\n\n// A residual, undemonstrated risk remains distinct from the mkdir retry loop\n// above: a single mkdir/appendFile syscall genuinely wedged on a stalled\n// filesystem (e.g. a hung network mount) blocks like any normal blocking I/O\n// would. Node's fs promises do not support cancelling an in-flight mkdir, so\n// a bounded wait here only frees the *caller* — the wedged operation itself\n// keeps running in the background until the OS/filesystem gives up on its\n// own. That is an accepted, documented limitation, not a bug this module can\n// fix from userland; it is unrelated to (and much rarer than) the retry-loop\n// case ensureDir() eliminates above.\nconst WRITE_TIMEOUT_MS = 2000\n\nasync function writeEntry(file: string, entry: ActionLogEntry): Promise<void> {\n await ensureDir(path.dirname(file))\n await appendFile(file, JSON.stringify(entry) + '\\n', 'utf8')\n}\n\n// Never throws, and never hangs beyond WRITE_TIMEOUT_MS. A failure (or a\n// stall) recording an action must not fail (or stall) the action:\n// observability that can break the thing it observes is worse than none.\nexport async function appendActionLog(entry: ActionLogEntry): Promise<void> {\n const file = actionLogPath()\n if (!file) return\n try {\n await Promise.race([\n writeEntry(file, entry),\n new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, WRITE_TIMEOUT_MS)\n timer.unref?.()\n }),\n ])\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// Exported so BOTH client paths log identically: the MCP proxy's remote client\n// and the CLI's own client. They are separate clients, and wiring only one is how\n// an unattended instance ends up with an empty log while the mechanism 'works'.\nexport function actionLogSignalsFromResult(result: unknown): {\n warnings?: string[]\n search_limits?: Record<string, unknown>\n} {\n const structuredContent = isRecord(result) ? result['structuredContent'] : undefined\n if (!isRecord(structuredContent)) return {}\n const warnings = Array.isArray(structuredContent['warnings'])\n ? (structuredContent['warnings'] as string[])\n : undefined\n const input = structuredContent['input']\n const search_limits =\n isRecord(input) && isRecord(input['search_limits'])\n ? (input['search_limits'] as Record<string, unknown>)\n : undefined\n return { warnings, search_limits }\n}\n\ntype CallToolFn = (...args: never[]) => Promise<unknown>\n\n// Wrap a client's callTool so every invocation is recorded. Returns the client.\n// Idempotent-unsafe: call once per client.\nexport function installActionLogging<T extends { callTool: CallToolFn }>(client: T): T {\n const original = client.callTool.bind(client) as CallToolFn\n const wrapped = (async (...args: never[]) => {\n const startedAt = Date.now()\n const input = (args[0] ?? {}) as { name?: unknown; arguments?: Record<string, unknown> }\n const tool = String(input.name ?? 'unknown')\n const toolArgs = input.arguments ?? {}\n try {\n const result = await original(...args)\n const { warnings, search_limits } = actionLogSignalsFromResult(result)\n await appendActionLog({\n timestamp: startedAt,\n tool,\n args: toolArgs,\n outcome: 'ok',\n duration_ms: Date.now() - startedAt,\n warnings,\n search_limits,\n })\n return result\n } catch (err) {\n await appendActionLog({\n timestamp: startedAt,\n tool,\n args: toolArgs,\n outcome: 'error',\n duration_ms: Date.now() - startedAt,\n error: (err as Error).message,\n })\n throw err\n }\n }) as CallToolFn\n client.callTool = wrapped as T['callTool']\n return client\n}\n"],"mappings":";;;;;AAuBA,SAAgB,gBAAoC;CAClD,MAAM,aAAa,QAAQ,IAAI,gBAAgB,KAAK;CACpD,OAAO,aAAa,aAAa,KAAA;AACnC;AAYA,eAAe,UAAU,KAA4B;CACnD,MAAM,WAAW,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,OAAO,OAAO;CACnD,IAAI,UAAU,KAAK,WAAW,GAAG,IAAI,KAAK,MAAM;CAChD,KAAK,MAAM,WAAW,UAAU;EAC9B,UAAU,UAAU,KAAK,KAAK,SAAS,OAAO,IAAI;EAClD,IAAI;GACF,MAAM,MAAM,OAAO;EACrB,SAAS,KAAK;GACZ,IAAK,IAA8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,EAAE,UAAU,kBAAkB,2BAA2B,MAAM;GACrE,MAAM,gBAAgB;IACpB,WAAW;IACX;IACA,MAAM;IACN,SAAS;IACT,aAAa,KAAK,IAAI,IAAI;IAC1B;IACA;GACF,CAAC;GACD,OAAO;EACT,SAAS,KAAK;GACZ,MAAM,gBAAgB;IACpB,WAAW;IACX;IACA,MAAM;IACN,SAAS;IACT,aAAa,KAAK,IAAI,IAAI;IAC1B,OAAQ,IAAc;GACxB,CAAC;GACD,MAAM;EACR;CACF;CACA,OAAO,WAAW;CAClB,OAAO;AACT"}
@@ -1,14 +1,9 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
2
  let node_path = require("node:path");
3
3
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
4
4
  let node_fs_promises = require("node:fs/promises");
5
- //#region src/mcp/action-log.ts
6
- var action_log_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
7
- actionLogPath: () => actionLogPath,
8
- actionLogSignalsFromResult: () => actionLogSignalsFromResult,
9
- appendActionLog: () => appendActionLog,
10
- installActionLogging: () => installActionLogging
11
- });
5
+ // src/mcp/action-log.ts
6
+ var action_log_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({ installActionLogging: () => installActionLogging });
12
7
  function actionLogPath() {
13
8
  const configured = process.env.CIA_ACTION_LOG?.trim();
14
9
  return configured ? configured : void 0;
@@ -88,7 +83,6 @@ function installActionLogging(client) {
88
83
  client.callTool = wrapped;
89
84
  return client;
90
85
  }
91
- //#endregion
92
86
  Object.defineProperty(exports, "actionLogSignalsFromResult", {
93
87
  enumerable: true,
94
88
  get: function() {
@@ -1,8 +1,8 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
2
  import path from "node:path";
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
5
- //#region src/workspace/active.ts
5
+ // src/workspace/active.ts
6
6
  var active_exports = /* @__PURE__ */ __exportAll({
7
7
  activeDataDir: () => activeDataDir,
8
8
  findActiveWorkspace: () => findActiveWorkspace
@@ -42,7 +42,6 @@ function findActiveWorkspace(startDir = process.cwd()) {
42
42
  function activeDataDir(fallbackDataDir) {
43
43
  return findActiveWorkspace()?.root ?? fallbackDataDir ?? path.join(os.homedir(), ".chain-insights");
44
44
  }
45
- //#endregion
46
45
  export { findActiveWorkspace as n, active_exports as t };
47
46
 
48
- //# sourceMappingURL=active-Dkf8AB1R.mjs.map
47
+ //# sourceMappingURL=active-D2aabYRF.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"active-Dkf8AB1R.mjs","names":[],"sources":["../src/workspace/active.ts"],"sourcesContent":["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\ninterface WorkspaceConfig {\n schema?: string\n workspace_root?: string\n artifacts_dir?: string\n domain_hints?: unknown\n}\n\nexport interface ActiveWorkspace {\n root: string\n metadataDir: string\n artifactsRoot: string\n domainHints: string[]\n}\n\nfunction workspaceFromRoot(rootCandidate: string): ActiveWorkspace | null {\n const root = path.resolve(rootCandidate)\n const metadataDir = path.join(root, '.chain-insights')\n const markerPath = path.join(metadataDir, 'workspace.json')\n if (!fs.existsSync(markerPath)) return null\n\n const parsed = JSON.parse(fs.readFileSync(markerPath, 'utf8')) as WorkspaceConfig\n if (parsed.schema !== 'chain-insights.workspace.v1') return null\n\n const workspaceRoot = path.resolve(parsed.workspace_root ?? root)\n const artifactsDir = parsed.artifacts_dir ?? 'artifacts'\n const domainHints = Array.isArray(parsed.domain_hints)\n ? parsed.domain_hints.filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0\n )\n : []\n return {\n root: workspaceRoot,\n metadataDir: path.join(workspaceRoot, '.chain-insights'),\n artifactsRoot: path.resolve(workspaceRoot, artifactsDir),\n domainHints,\n }\n}\n\nexport function findActiveWorkspace(startDir = process.cwd()): ActiveWorkspace | null {\n const envWorkspace = process.env['CHAIN_INSIGHTS_WORKSPACE']?.trim()\n if (envWorkspace) {\n const active = workspaceFromRoot(envWorkspace)\n if (active) return active\n }\n\n let current = path.resolve(startDir)\n while (true) {\n const active = workspaceFromRoot(current)\n if (active) return active\n\n const parent = path.dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\nexport function activeMetadataDir(): string {\n return findActiveWorkspace()?.metadataDir ?? path.join(os.homedir(), '.chain-insights')\n}\n\nexport function activeArtifactsRoot(): string {\n return (\n findActiveWorkspace()?.artifactsRoot ?? path.join(os.homedir(), '.chain-insights', 'artifacts')\n )\n}\n\nexport function activeDataDir(fallbackDataDir?: string): string {\n return (\n findActiveWorkspace()?.root ?? fallbackDataDir ?? path.join(os.homedir(), '.chain-insights')\n )\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAS,kBAAkB,eAA+C;CACxE,MAAM,OAAO,KAAK,QAAQ,aAAa;CACvC,MAAM,cAAc,KAAK,KAAK,MAAM,iBAAiB;CACrD,MAAM,aAAa,KAAK,KAAK,aAAa,gBAAgB;CAC1D,IAAI,CAAC,GAAG,WAAW,UAAU,GAAG,OAAO;CAEvC,MAAM,SAAS,KAAK,MAAM,GAAG,aAAa,YAAY,MAAM,CAAC;CAC7D,IAAI,OAAO,WAAW,+BAA+B,OAAO;CAE5D,MAAM,gBAAgB,KAAK,QAAQ,OAAO,kBAAkB,IAAI;CAChE,MAAM,eAAe,OAAO,iBAAiB;CAC7C,MAAM,cAAc,MAAM,QAAQ,OAAO,YAAY,IACjD,OAAO,aAAa,QACjB,UAA2B,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS,CACjF,IACA,CAAC;CACL,OAAO;EACL,MAAM;EACN,aAAa,KAAK,KAAK,eAAe,iBAAiB;EACvD,eAAe,KAAK,QAAQ,eAAe,YAAY;EACvD;CACF;AACF;AAEA,SAAgB,oBAAoB,WAAW,QAAQ,IAAI,GAA2B;CACpF,MAAM,eAAe,QAAQ,IAAI,2BAA2B,EAAE,KAAK;CACnE,IAAI,cAAc;EAChB,MAAM,SAAS,kBAAkB,YAAY;EAC7C,IAAI,QAAQ,OAAO;CACrB;CAEA,IAAI,UAAU,KAAK,QAAQ,QAAQ;CACnC,OAAO,MAAM;EACX,MAAM,SAAS,kBAAkB,OAAO;EACxC,IAAI,QAAQ,OAAO;EAEnB,MAAM,SAAS,KAAK,QAAQ,OAAO;EACnC,IAAI,WAAW,SAAS,OAAO;EAC/B,UAAU;CACZ;AACF;AAYA,SAAgB,cAAc,iBAAkC;CAC9D,OACE,oBAAoB,CAAC,EAAE,QAAQ,mBAAmB,KAAK,KAAK,GAAG,QAAQ,GAAG,iBAAiB;AAE/F"}
1
+ {"version":3,"file":"active-D2aabYRF.mjs","names":[],"sources":["../src/workspace/active.ts"],"sourcesContent":["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\n\ninterface WorkspaceConfig {\n schema?: string\n workspace_root?: string\n artifacts_dir?: string\n domain_hints?: unknown\n}\n\nexport interface ActiveWorkspace {\n root: string\n metadataDir: string\n artifactsRoot: string\n domainHints: string[]\n}\n\nfunction workspaceFromRoot(rootCandidate: string): ActiveWorkspace | null {\n const root = path.resolve(rootCandidate)\n const metadataDir = path.join(root, '.chain-insights')\n const markerPath = path.join(metadataDir, 'workspace.json')\n if (!fs.existsSync(markerPath)) return null\n\n const parsed = JSON.parse(fs.readFileSync(markerPath, 'utf8')) as WorkspaceConfig\n if (parsed.schema !== 'chain-insights.workspace.v1') return null\n\n const workspaceRoot = path.resolve(parsed.workspace_root ?? root)\n const artifactsDir = parsed.artifacts_dir ?? 'artifacts'\n const domainHints = Array.isArray(parsed.domain_hints)\n ? parsed.domain_hints.filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0\n )\n : []\n return {\n root: workspaceRoot,\n metadataDir: path.join(workspaceRoot, '.chain-insights'),\n artifactsRoot: path.resolve(workspaceRoot, artifactsDir),\n domainHints,\n }\n}\n\nexport function findActiveWorkspace(startDir = process.cwd()): ActiveWorkspace | null {\n const envWorkspace = process.env['CHAIN_INSIGHTS_WORKSPACE']?.trim()\n if (envWorkspace) {\n const active = workspaceFromRoot(envWorkspace)\n if (active) return active\n }\n\n let current = path.resolve(startDir)\n while (true) {\n const active = workspaceFromRoot(current)\n if (active) return active\n\n const parent = path.dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\nexport function activeMetadataDir(): string {\n return findActiveWorkspace()?.metadataDir ?? path.join(os.homedir(), '.chain-insights')\n}\n\nexport function activeArtifactsRoot(): string {\n return (\n findActiveWorkspace()?.artifactsRoot ?? path.join(os.homedir(), '.chain-insights', 'artifacts')\n )\n}\n\nexport function activeDataDir(fallbackDataDir?: string): string {\n return (\n findActiveWorkspace()?.root ?? fallbackDataDir ?? path.join(os.homedir(), '.chain-insights')\n )\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAS,kBAAkB,eAA+C;CACxE,MAAM,OAAO,KAAK,QAAQ,aAAa;CACvC,MAAM,cAAc,KAAK,KAAK,MAAM,iBAAiB;CACrD,MAAM,aAAa,KAAK,KAAK,aAAa,gBAAgB;CAC1D,IAAI,CAAC,GAAG,WAAW,UAAU,GAAG,OAAO;CAEvC,MAAM,SAAS,KAAK,MAAM,GAAG,aAAa,YAAY,MAAM,CAAC;CAC7D,IAAI,OAAO,WAAW,+BAA+B,OAAO;CAE5D,MAAM,gBAAgB,KAAK,QAAQ,OAAO,kBAAkB,IAAI;CAChE,MAAM,eAAe,OAAO,iBAAiB;CAC7C,MAAM,cAAc,MAAM,QAAQ,OAAO,YAAY,IACjD,OAAO,aAAa,QACjB,UAA2B,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS,CACjF,IACA,CAAC;CACL,OAAO;EACL,MAAM;EACN,aAAa,KAAK,KAAK,eAAe,iBAAiB;EACvD,eAAe,KAAK,QAAQ,eAAe,YAAY;EACvD;CACF;AACF;AAEA,SAAgB,oBAAoB,WAAW,QAAQ,IAAI,GAA2B;CACpF,MAAM,eAAe,QAAQ,IAAI,2BAA2B,EAAE,KAAK;CACnE,IAAI,cAAc;EAChB,MAAM,SAAS,kBAAkB,YAAY;EAC7C,IAAI,QAAQ,OAAO;CACrB;CAEA,IAAI,UAAU,KAAK,QAAQ,QAAQ;CACnC,OAAO,MAAM;EACX,MAAM,SAAS,kBAAkB,OAAO;EACxC,IAAI,QAAQ,OAAO;EAEnB,MAAM,SAAS,KAAK,QAAQ,OAAO;EACnC,IAAI,WAAW,SAAS,OAAO;EAC/B,UAAU;CACZ;AACF;AAYA,SAAgB,cAAc,iBAAkC;CAC9D,OACE,oBAAoB,CAAC,EAAE,QAAQ,mBAAmB,KAAK,KAAK,GAAG,QAAQ,GAAG,iBAAiB;AAE/F"}
@@ -1,11 +1,11 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
2
  let node_path = require("node:path");
3
3
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
4
4
  let node_fs = require("node:fs");
5
5
  node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
6
6
  let node_os = require("node:os");
7
7
  node_os = require_rolldown_runtime.__toESM(node_os, 1);
8
- //#region src/workspace/active.ts
8
+ // src/workspace/active.ts
9
9
  var active_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
10
10
  activeDataDir: () => activeDataDir,
11
11
  findActiveWorkspace: () => findActiveWorkspace
@@ -45,7 +45,6 @@ function findActiveWorkspace(startDir = process.cwd()) {
45
45
  function activeDataDir(fallbackDataDir) {
46
46
  return findActiveWorkspace()?.root ?? fallbackDataDir ?? node_path.default.join(node_os.default.homedir(), ".chain-insights");
47
47
  }
48
- //#endregion
49
48
  Object.defineProperty(exports, "active_exports", {
50
49
  enumerable: true,
51
50
  get: function() {
@@ -0,0 +1,57 @@
1
+ // src/mcp/answer-hint.ts
2
+ /**
3
+ * The two answer rules that still slip in long answers, carried on every
4
+ * graph reply in the result's `hint` field. Claude Code has a Stop hook that
5
+ * reads the answer; Codex and Claude Desktop have no such hook, and in the
6
+ * loop's third prompt set they broke one of these two rules in three of
7
+ * thirteen conversations. The reply is the one thing every host hands the
8
+ * model right before it writes, so the rules ride on it. A `hint` the
9
+ * server already set is kept.
10
+ */
11
+ const ANSWER_HINT = "Answer: write every address in full (0x plus 40 characters), also when it repeats one named earlier and also when the user asks for shorter ones (name them instead); a transfer moves tokens, so write \"tokens worth about N USD\", never \"sent N USD\" or a $ figure; never draw the flows in text, ASCII or Mermaid, the host draws them.";
12
+ function isRecord(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ /** The structured content with the hint set when the server left it empty. */
16
+ function withAnswerHint(structuredContent) {
17
+ if (!isRecord(structuredContent) || !isRecord(structuredContent.facts)) return structuredContent;
18
+ if (typeof structuredContent.hint === "string" && structuredContent.hint.trim()) return structuredContent;
19
+ return {
20
+ ...structuredContent,
21
+ hint: ANSWER_HINT
22
+ };
23
+ }
24
+ /** A graph tool result whose structured content and single JSON text block both carry the hint. */
25
+ function withAnswerHintResult(result) {
26
+ const structured = withAnswerHint(result.structuredContent);
27
+ if (structured === result.structuredContent) return result;
28
+ const content = result.content ?? [];
29
+ const only = content.length === 1 && content[0]?.type === "text" ? content[0] : null;
30
+ let parsed = void 0;
31
+ try {
32
+ parsed = only?.text ? JSON.parse(only.text) : void 0;
33
+ } catch {
34
+ parsed = void 0;
35
+ }
36
+ const textIsStructured = parsed !== void 0 && JSON.stringify(parsed) === JSON.stringify(result.structuredContent);
37
+ return {
38
+ ...result,
39
+ structuredContent: structured,
40
+ content: textIsStructured ? [{
41
+ ...only,
42
+ text: JSON.stringify(structured)
43
+ }] : content
44
+ };
45
+ }
46
+ Object.defineProperty(exports, "ANSWER_HINT", {
47
+ enumerable: true,
48
+ get: function() {
49
+ return ANSWER_HINT;
50
+ }
51
+ });
52
+ Object.defineProperty(exports, "withAnswerHintResult", {
53
+ enumerable: true,
54
+ get: function() {
55
+ return withAnswerHintResult;
56
+ }
57
+ });
@@ -0,0 +1,48 @@
1
+ // src/mcp/answer-hint.ts
2
+ /**
3
+ * The two answer rules that still slip in long answers, carried on every
4
+ * graph reply in the result's `hint` field. Claude Code has a Stop hook that
5
+ * reads the answer; Codex and Claude Desktop have no such hook, and in the
6
+ * loop's third prompt set they broke one of these two rules in three of
7
+ * thirteen conversations. The reply is the one thing every host hands the
8
+ * model right before it writes, so the rules ride on it. A `hint` the
9
+ * server already set is kept.
10
+ */
11
+ const ANSWER_HINT = "Answer: write every address in full (0x plus 40 characters), also when it repeats one named earlier and also when the user asks for shorter ones (name them instead); a transfer moves tokens, so write \"tokens worth about N USD\", never \"sent N USD\" or a $ figure; never draw the flows in text, ASCII or Mermaid, the host draws them.";
12
+ function isRecord(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ /** The structured content with the hint set when the server left it empty. */
16
+ function withAnswerHint(structuredContent) {
17
+ if (!isRecord(structuredContent) || !isRecord(structuredContent.facts)) return structuredContent;
18
+ if (typeof structuredContent.hint === "string" && structuredContent.hint.trim()) return structuredContent;
19
+ return {
20
+ ...structuredContent,
21
+ hint: ANSWER_HINT
22
+ };
23
+ }
24
+ /** A graph tool result whose structured content and single JSON text block both carry the hint. */
25
+ function withAnswerHintResult(result) {
26
+ const structured = withAnswerHint(result.structuredContent);
27
+ if (structured === result.structuredContent) return result;
28
+ const content = result.content ?? [];
29
+ const only = content.length === 1 && content[0]?.type === "text" ? content[0] : null;
30
+ let parsed = void 0;
31
+ try {
32
+ parsed = only?.text ? JSON.parse(only.text) : void 0;
33
+ } catch {
34
+ parsed = void 0;
35
+ }
36
+ const textIsStructured = parsed !== void 0 && JSON.stringify(parsed) === JSON.stringify(result.structuredContent);
37
+ return {
38
+ ...result,
39
+ structuredContent: structured,
40
+ content: textIsStructured ? [{
41
+ ...only,
42
+ text: JSON.stringify(structured)
43
+ }] : content
44
+ };
45
+ }
46
+ export { withAnswerHintResult as n, ANSWER_HINT as t };
47
+
48
+ //# sourceMappingURL=answer-hint-vOE1O6Lf.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"answer-hint-vOE1O6Lf.mjs","names":[],"sources":["../src/mcp/answer-hint.ts"],"sourcesContent":["/**\n * The two answer rules that still slip in long answers, carried on every\n * graph reply in the result's `hint` field. Claude Code has a Stop hook that\n * reads the answer; Codex and Claude Desktop have no such hook, and in the\n * loop's third prompt set they broke one of these two rules in three of\n * thirteen conversations. The reply is the one thing every host hands the\n * model right before it writes, so the rules ride on it. A `hint` the\n * server already set is kept.\n */\n\nexport const ANSWER_HINT =\n 'Answer: write every address in full (0x plus 40 characters), also when it repeats one named earlier and also when the user asks for shorter ones (name them instead); ' +\n 'a transfer moves tokens, so write \"tokens worth about N USD\", never \"sent N USD\" or a $ figure; ' +\n 'never draw the flows in text, ASCII or Mermaid, the host draws them.'\n\ntype TextBlock = { type: string; text?: string }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The structured content with the hint set when the server left it empty. */\nexport function withAnswerHint(structuredContent: unknown): unknown {\n if (!isRecord(structuredContent) || !isRecord(structuredContent.facts)) return structuredContent\n if (typeof structuredContent.hint === 'string' && structuredContent.hint.trim()) return structuredContent\n return { ...structuredContent, hint: ANSWER_HINT }\n}\n\n/** A graph tool result whose structured content and single JSON text block both carry the hint. */\nexport function withAnswerHintResult<T extends { content?: TextBlock[]; structuredContent?: unknown }>(result: T): T {\n const structured = withAnswerHint(result.structuredContent)\n if (structured === result.structuredContent) return result\n const content = result.content ?? []\n const only = content.length === 1 && content[0]?.type === 'text' ? content[0] : null\n let parsed: unknown = undefined\n try {\n parsed = only?.text ? JSON.parse(only.text) : undefined\n } catch {\n parsed = undefined\n }\n const textIsStructured = parsed !== undefined && JSON.stringify(parsed) === JSON.stringify(result.structuredContent)\n return { ...result, structuredContent: structured, content: textIsStructured ? [{ ...only, text: JSON.stringify(structured) }] : content }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,cACX;AAMF,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;AAGA,SAAgB,eAAe,mBAAqC;CAClE,IAAI,CAAC,SAAS,iBAAiB,KAAK,CAAC,SAAS,kBAAkB,KAAK,GAAG,OAAO;CAC/E,IAAI,OAAO,kBAAkB,SAAS,YAAY,kBAAkB,KAAK,KAAK,GAAG,OAAO;CACxF,OAAO;EAAE,GAAG;EAAmB,MAAM;CAAY;AACnD;;AAGA,SAAgB,qBAAuF,QAAc;CACnH,MAAM,aAAa,eAAe,OAAO,iBAAiB;CAC1D,IAAI,eAAe,OAAO,mBAAmB,OAAO;CACpD,MAAM,UAAU,OAAO,WAAW,CAAC;CACnC,MAAM,OAAO,QAAQ,WAAW,KAAK,QAAQ,EAAE,EAAE,SAAS,SAAS,QAAQ,KAAK;CAChF,IAAI,SAAkB,KAAA;CACtB,IAAI;EACF,SAAS,MAAM,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,KAAA;CAChD,QAAQ;EACN,SAAS,KAAA;CACX;CACA,MAAM,mBAAmB,WAAW,KAAA,KAAa,KAAK,UAAU,MAAM,MAAM,KAAK,UAAU,OAAO,iBAAiB;CACnH,OAAO;EAAE,GAAG;EAAQ,mBAAmB;EAAY,SAAS,mBAAmB,CAAC;GAAE,GAAG;GAAM,MAAM,KAAK,UAAU,UAAU;EAAE,CAAC,IAAI;CAAQ;AAC3I"}
@@ -1,7 +1,7 @@
1
- import { t as PUBLIC_KEY_WALLET_TEXT } from "./known-keys-B87ZqOgE.mjs";
2
- import { c as explorerTxUrl, f as readCiaAllowance, l as formatCia, m as readRobinhoodEthBalance, n as CIA_TOKEN_ADDRESS, o as approveCiaForSubscription, p as readCiaBalance, s as depositCiaForSubscription } from "./robinhood-CCTMagwM.mjs";
3
- import { MAX_DAYS_HELD, SUBSCRIPTION_DAY_USD, quoteForDays } from "./quote-DfTut0cx.mjs";
4
- //#region src/subscription/buy.ts
1
+ import { t as PUBLIC_KEY_WALLET_TEXT } from "./known-keys-BbuzCZOW.mjs";
2
+ import { c as explorerTxUrl, f as readCiaAllowance, l as formatCia, m as readRobinhoodEthBalance, n as CIA_TOKEN_ADDRESS, o as approveCiaForSubscription, p as readCiaBalance, s as depositCiaForSubscription } from "./robinhood-0NZsA6ZW.mjs";
3
+ import { MAX_DAYS_HELD, SUBSCRIPTION_DAY_USD, quoteForDays } from "./quote-41CbMc37.mjs";
4
+ // src/subscription/buy.ts
5
5
  const GRANT_WAIT_MS = 12e4;
6
6
  const GRANT_POLL_MS = 5e3;
7
7
  const STATUS_COMMAND = "cia subscription status";
@@ -189,7 +189,6 @@ function formatBuyResult(result) {
189
189
  else lines.push("The server has not credited the payment yet.", grant.next);
190
190
  return lines.join("\n");
191
191
  }
192
- //#endregion
193
192
  export { assertConfirmable, executeBuy, formatBuyResult };
194
193
 
195
- //# sourceMappingURL=buy-_mpdRieG.mjs.map
194
+ //# sourceMappingURL=buy-B2luUbWF.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"buy-_mpdRieG.mjs","names":[],"sources":["../src/subscription/buy.ts"],"sourcesContent":["import type { Hex } from 'viem'\nimport type { SubscriptionStatusFacts } from '../mcp/subscription-status.js'\nimport { PUBLIC_KEY_WALLET_TEXT } from '../wallet/known-keys.js'\nimport {\n CIA_TOKEN_ADDRESS,\n approveCiaForSubscription,\n depositCiaForSubscription,\n explorerTxUrl,\n formatCia,\n readCiaAllowance,\n readCiaBalance,\n readRobinhoodEthBalance,\n} from '../wallet/robinhood.js'\nimport { MAX_DAYS_HELD, SUBSCRIPTION_DAY_USD, quoteForDays, type CiaPrice, type Quote } from './quote.js'\n\n// `cia subscription buy --days N`: the one way to pay for a subscription. It\n// is a terminal command and never an MCP tool: an agent cannot buy. Order:\n// wallet, status, quote, balances, the user's yes, approve, deposit, wait.\n\nexport const GRANT_WAIT_MS = 120_000\nexport const GRANT_POLL_MS = 5_000\nexport const STATUS_COMMAND = 'cia subscription status'\nexport const TOPUP_COMMAND = 'cia subscription topup'\n\nexport interface BuyState {\n wallet: { address: string; keyIsPublic?: boolean }\n /** null when the server's subscription status could not be read. */\n status: SubscriptionStatusFacts | null\n quote: Quote\n ciaBalance: bigint | null\n ethBalance: bigint | null\n allowance: bigint | null\n}\n\nexport type BuyPlan = { ok: true; approve: boolean; quote: Quote } | { ok: false; reason: string }\n\n/** Decides the buy from what was read. Pure: no I/O. */\nexport function planBuy(state: BuyState): BuyPlan {\n const { quote } = state\n if (state.wallet.keyIsPublic === true) return { ok: false, reason: PUBLIC_KEY_WALLET_TEXT }\n if (!state.status) {\n return {\n ok: false,\n reason: `The subscription status could not be read, so a payment cannot be checked. Nothing was sent. Run \\`${STATUS_COMMAND}\\` and try again.`,\n }\n }\n const pending = state.status.pending_payments[0]\n if (pending) {\n return {\n ok: false,\n reason: `A payment is still being credited: ${explorerTxUrl(pending.tx_hash)}. Nothing was sent. Wait a few minutes and run \\`${STATUS_COMMAND}\\`.`,\n }\n }\n const held = state.status.active ? Math.max(0, state.status.days_left) : 0\n const room = Math.floor(MAX_DAYS_HELD - held)\n if (quote.days > room) {\n return {\n ok: false,\n reason:\n room < 1\n ? `The wallet already holds ${held.toFixed(1)} days, and a wallet may hold at most ${MAX_DAYS_HELD}. Nothing was sent. Buy again after a day has passed.`\n : `The wallet already holds ${held.toFixed(1)} days, and a wallet may hold at most ${MAX_DAYS_HELD}. Buy at most ${room} ${room === 1 ? 'day' : 'days'} now. Nothing was sent.`,\n }\n }\n if (state.ciaBalance === null || state.ethBalance === null) {\n return {\n ok: false,\n reason:\n 'The wallet balance on Robinhood Chain could not be read. Nothing was sent. Try again, or set ROBINHOOD_RPC_URL to a working Robinhood Chain RPC.',\n }\n }\n if (state.ciaBalance < quote.amount) {\n const short = quote.amount - state.ciaBalance\n return {\n ok: false,\n reason: `Not enough $CIA: the buy needs ${formatCia(quote.amount)} $CIA and the wallet holds ${formatCia(state.ciaBalance)}, ${formatCia(short)} short. Run \\`${TOPUP_COMMAND}\\` to fund it.`,\n }\n }\n if (state.ethBalance === 0n) {\n return {\n ok: false,\n reason: `The wallet holds no ETH on Robinhood Chain to pay the gas. Run \\`${TOPUP_COMMAND}\\` and send a little ETH.`,\n }\n }\n return { ok: true, approve: (state.allowance ?? 0n) < quote.amount, quote }\n}\n\nfunction utcMinute(date: Date): string {\n return `${date.toISOString().slice(0, 16).replace('T', ' ')} UTC`\n}\n\n/** The text the user says yes to. It never names the sink address. */\nexport function confirmText(quote: Quote, approve: boolean): string {\n const transactions = approve\n ? `It signs up to two transactions on Robinhood Chain: approve exactly ${formatCia(quote.amount)} $CIA, then pay.`\n : 'It signs up to two transactions on Robinhood Chain; this time one is enough: the payment.'\n return [\n `Buy about ${quote.days} ${quote.days === 1 ? 'day' : 'days'} of the Chain Insights subscription.`,\n `Price: ${quote.days} x ${SUBSCRIPTION_DAY_USD} USD = ${quote.usd} USD.`,\n `Pay: ${formatCia(quote.amount)} $CIA at ${quote.price.usd} USD per $CIA (CoinGecko, ${utcMinute(quote.price.updatedAt)}).`,\n 'The server prices the payment again when it credits it, so the days can differ by a few minutes.',\n transactions,\n ].join('\\n')\n}\n\n/** A buy needs a typed yes on a terminal, or --yes. */\nexport function assertConfirmable(options: { stdinIsTTY: boolean; yes: boolean }): void {\n if (options.yes || options.stdinIsTTY) return\n throw new Error(\n '`cia subscription buy` needs a typed yes, and stdin is not a terminal. Run it in a terminal, or pass --yes.'\n )\n}\n\nexport type GrantOutcome =\n | { outcome: 'granted'; tx_hash: string; window_end: string | null; days_left: number }\n | { outcome: 'pending'; tx_hash: string; next: string }\n | { outcome: 'timeout'; tx_hash: string; next: string }\n\nexport interface WaitForGrantOptions {\n txHash: string\n /** The status read before the payment. */\n before: SubscriptionStatusFacts | null\n readStatus: () => Promise<SubscriptionStatusFacts | null>\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n timeoutMs?: number\n intervalMs?: number\n}\n\n/**\n * Polls the status every 5 s for at most 120 s. granted: the window moved\n * and the payment is no longer pending. pending: the server saw the payment\n * and has not priced it yet. timeout: the server has not seen it. Never resends.\n */\nexport async function waitForGrant(options: WaitForGrantOptions): Promise<GrantOutcome> {\n const now = options.now ?? (() => Date.now())\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n const timeoutMs = options.timeoutMs ?? GRANT_WAIT_MS\n const intervalMs = options.intervalMs ?? GRANT_POLL_MS\n const tx = options.txHash.toLowerCase()\n const before = options.before\n const deadline = now() + timeoutMs\n let seen = false\n while (now() < deadline) {\n await sleep(Math.min(intervalMs, deadline - now()))\n let status: SubscriptionStatusFacts | null = null\n try {\n status = await options.readStatus()\n } catch {\n status = null\n }\n if (!status) continue\n if (status.pending_payments.some((payment) => payment.tx_hash.toLowerCase() === tx)) {\n seen = true\n continue\n }\n const moved = !before || !before.active || status.window_end !== before.window_end\n if (status.active && moved) {\n return { outcome: 'granted', tx_hash: options.txHash, window_end: status.window_end, days_left: status.days_left }\n }\n }\n const next = `Run \\`${STATUS_COMMAND}\\` in a few minutes. Do not pay again.`\n return seen\n ? { outcome: 'pending', tx_hash: options.txHash, next }\n : { outcome: 'timeout', tx_hash: options.txHash, next }\n}\n\nexport interface BuyChain {\n readCiaBalance(address: string): Promise<bigint | null>\n readEthBalance(address: string): Promise<bigint | null>\n readAllowance(owner: string): Promise<bigint | null>\n approve: typeof approveCiaForSubscription\n deposit: typeof depositCiaForSubscription\n}\n\n/** The Robinhood Chain, through ROBINHOOD_RPC_URL or the public endpoints. */\nexport function robinhoodBuyChain(env: NodeJS.ProcessEnv = process.env): BuyChain {\n return {\n readCiaBalance: (address) => readCiaBalance(address, env),\n readEthBalance: (address) => readRobinhoodEthBalance(address, env),\n readAllowance: (owner) => readCiaAllowance(owner, env),\n approve: (key, amount) => approveCiaForSubscription(key, amount, env),\n deposit: (key, amount) => depositCiaForSubscription(key, amount, env),\n }\n}\n\nexport interface BuyDependencies {\n account: { address: string; privateKey: Hex; keyIsPublic?: boolean }\n days: number\n readStatus: () => Promise<SubscriptionStatusFacts | null>\n fetchPrice: () => Promise<CiaPrice>\n /** Shows the text and resolves true on the user's yes. */\n confirm: (text: string) => Promise<boolean>\n chain?: BuyChain\n log?: (line: string) => void\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n timeoutMs?: number\n}\n\nexport interface BuyResult {\n days: number\n usd: number\n amount_cia: string\n price_usd: string\n price_time: string\n approve_tx: string | null\n deposit_tx: string\n deposit_url: string\n grant: GrantOutcome\n}\n\n/** Runs one buy. Throws, with nothing sent, on every refusal before the yes. */\nexport async function executeBuy(deps: BuyDependencies): Promise<BuyResult> {\n const chain = deps.chain ?? robinhoodBuyChain()\n const log = deps.log ?? (() => {})\n const { account } = deps\n if (account.keyIsPublic === true) throw new Error(PUBLIC_KEY_WALLET_TEXT)\n\n const status = await deps.readStatus()\n const price = await deps.fetchPrice()\n const quote = quoteForDays(deps.days, price)\n const [ciaBalance, ethBalance, allowance] = await Promise.all([\n chain.readCiaBalance(account.address),\n chain.readEthBalance(account.address),\n chain.readAllowance(account.address),\n ])\n const plan = planBuy({ wallet: account, status, quote, ciaBalance, ethBalance, allowance })\n if (!plan.ok) throw new Error(plan.reason)\n if (!(await deps.confirm(confirmText(quote, plan.approve)))) {\n throw new Error('Buy cancelled. Nothing was sent.')\n }\n\n let approveTx: string | null = null\n if (plan.approve) {\n const approval = await chain.approve(account.privateKey, quote.amount)\n approveTx = approval.txHash\n log(`Approve: ${explorerTxUrl(approval.txHash)}`)\n if (approval.status !== 'success') {\n throw new Error(`The approval failed on chain: ${explorerTxUrl(approval.txHash)}. No $CIA was paid.`)\n }\n }\n const deposit = await chain.deposit(account.privateKey, quote.amount)\n log(`Payment: ${explorerTxUrl(deposit.txHash)}`)\n if (deposit.status !== 'success') {\n throw new Error(`The payment failed on chain: ${explorerTxUrl(deposit.txHash)}. No $CIA was paid.`)\n }\n const received = deposit.received\n if (\n !received ||\n received.from.toLowerCase() !== account.address.toLowerCase() ||\n received.token.toLowerCase() !== CIA_TOKEN_ADDRESS ||\n received.amount !== quote.amount\n ) {\n throw new Error(\n `The payment landed, but its receipt does not show ${formatCia(quote.amount)} $CIA from this wallet: ${explorerTxUrl(deposit.txHash)}. Do not pay again. Run \\`${STATUS_COMMAND}\\`.`\n )\n }\n\n const grant = await waitForGrant({\n txHash: deposit.txHash,\n before: status,\n readStatus: deps.readStatus,\n now: deps.now,\n sleep: deps.sleep,\n timeoutMs: deps.timeoutMs,\n })\n return {\n days: quote.days,\n usd: quote.usd,\n amount_cia: formatCia(quote.amount),\n price_usd: price.usd,\n price_time: price.updatedAt.toISOString(),\n approve_tx: approveTx,\n deposit_tx: deposit.txHash,\n deposit_url: explorerTxUrl(deposit.txHash),\n grant,\n }\n}\n\n/** The outcome in plain lines. */\nexport function formatBuyResult(result: BuyResult): string {\n const lines = [`Paid ${result.amount_cia} $CIA for about ${result.days} ${result.days === 1 ? 'day' : 'days'}: ${result.deposit_url}`]\n const grant = result.grant\n if (grant.outcome === 'granted') {\n lines.push(`Subscription active until ${grant.window_end ?? 'unknown'} (about ${grant.days_left.toFixed(1)} days left).`)\n } else if (grant.outcome === 'pending') {\n lines.push('The server has seen the payment and is pricing it.', grant.next)\n } else {\n lines.push('The server has not credited the payment yet.', grant.next)\n }\n return lines.join('\\n')\n}\n"],"mappings":";;;;AAmBA,MAAa,gBAAgB;AAC7B,MAAa,gBAAgB;AAC7B,MAAa,iBAAiB;AAC9B,MAAa,gBAAgB;;AAe7B,SAAgB,QAAQ,OAA0B;CAChD,MAAM,EAAE,UAAU;CAClB,IAAI,MAAM,OAAO,gBAAgB,MAAM,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAuB;CAC1F,IAAI,CAAC,MAAM,QACT,OAAO;EACL,IAAI;EACJ,QAAQ,sGAAsG,eAAe;CAC/H;CAEF,MAAM,UAAU,MAAM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;MAE3E,MAAM,KAAK,gDAAgD,MAAM,IAAI;CAEvE,OAAO,MAAM,KAAK,IAAI;AACxB"}
1
+ {"version":3,"file":"buy-B2luUbWF.mjs","names":[],"sources":["../src/subscription/buy.ts"],"sourcesContent":["import type { Hex } from 'viem'\nimport type { SubscriptionStatusFacts } from '../mcp/subscription-status.js'\nimport { PUBLIC_KEY_WALLET_TEXT } from '../wallet/known-keys.js'\nimport {\n CIA_TOKEN_ADDRESS,\n approveCiaForSubscription,\n depositCiaForSubscription,\n explorerTxUrl,\n formatCia,\n readCiaAllowance,\n readCiaBalance,\n readRobinhoodEthBalance,\n} from '../wallet/robinhood.js'\nimport { MAX_DAYS_HELD, SUBSCRIPTION_DAY_USD, quoteForDays, type CiaPrice, type Quote } from './quote.js'\n\n// `cia subscription buy --days N`: the one way to pay for a subscription. It\n// is a terminal command and never an MCP tool: an agent cannot buy. Order:\n// wallet, status, quote, balances, the user's yes, approve, deposit, wait.\n\nexport const GRANT_WAIT_MS = 120_000\nexport const GRANT_POLL_MS = 5_000\nexport const STATUS_COMMAND = 'cia subscription status'\nexport const TOPUP_COMMAND = 'cia subscription topup'\n\nexport interface BuyState {\n wallet: { address: string; keyIsPublic?: boolean }\n /** null when the server's subscription status could not be read. */\n status: SubscriptionStatusFacts | null\n quote: Quote\n ciaBalance: bigint | null\n ethBalance: bigint | null\n allowance: bigint | null\n}\n\nexport type BuyPlan = { ok: true; approve: boolean; quote: Quote } | { ok: false; reason: string }\n\n/** Decides the buy from what was read. Pure: no I/O. */\nexport function planBuy(state: BuyState): BuyPlan {\n const { quote } = state\n if (state.wallet.keyIsPublic === true) return { ok: false, reason: PUBLIC_KEY_WALLET_TEXT }\n if (!state.status) {\n return {\n ok: false,\n reason: `The subscription status could not be read, so a payment cannot be checked. Nothing was sent. Run \\`${STATUS_COMMAND}\\` and try again.`,\n }\n }\n const pending = state.status.pending_payments[0]\n if (pending) {\n return {\n ok: false,\n reason: `A payment is still being credited: ${explorerTxUrl(pending.tx_hash)}. Nothing was sent. Wait a few minutes and run \\`${STATUS_COMMAND}\\`.`,\n }\n }\n const held = state.status.active ? Math.max(0, state.status.days_left) : 0\n const room = Math.floor(MAX_DAYS_HELD - held)\n if (quote.days > room) {\n return {\n ok: false,\n reason:\n room < 1\n ? `The wallet already holds ${held.toFixed(1)} days, and a wallet may hold at most ${MAX_DAYS_HELD}. Nothing was sent. Buy again after a day has passed.`\n : `The wallet already holds ${held.toFixed(1)} days, and a wallet may hold at most ${MAX_DAYS_HELD}. Buy at most ${room} ${room === 1 ? 'day' : 'days'} now. Nothing was sent.`,\n }\n }\n if (state.ciaBalance === null || state.ethBalance === null) {\n return {\n ok: false,\n reason:\n 'The wallet balance on Robinhood Chain could not be read. Nothing was sent. Try again, or set ROBINHOOD_RPC_URL to a working Robinhood Chain RPC.',\n }\n }\n if (state.ciaBalance < quote.amount) {\n const short = quote.amount - state.ciaBalance\n return {\n ok: false,\n reason: `Not enough $CIA: the buy needs ${formatCia(quote.amount)} $CIA and the wallet holds ${formatCia(state.ciaBalance)}, ${formatCia(short)} short. Run \\`${TOPUP_COMMAND}\\` to fund it.`,\n }\n }\n if (state.ethBalance === 0n) {\n return {\n ok: false,\n reason: `The wallet holds no ETH on Robinhood Chain to pay the gas. Run \\`${TOPUP_COMMAND}\\` and send a little ETH.`,\n }\n }\n return { ok: true, approve: (state.allowance ?? 0n) < quote.amount, quote }\n}\n\nfunction utcMinute(date: Date): string {\n return `${date.toISOString().slice(0, 16).replace('T', ' ')} UTC`\n}\n\n/** The text the user says yes to. It never names the sink address. */\nexport function confirmText(quote: Quote, approve: boolean): string {\n const transactions = approve\n ? `It signs up to two transactions on Robinhood Chain: approve exactly ${formatCia(quote.amount)} $CIA, then pay.`\n : 'It signs up to two transactions on Robinhood Chain; this time one is enough: the payment.'\n return [\n `Buy about ${quote.days} ${quote.days === 1 ? 'day' : 'days'} of the Chain Insights subscription.`,\n `Price: ${quote.days} x ${SUBSCRIPTION_DAY_USD} USD = ${quote.usd} USD.`,\n `Pay: ${formatCia(quote.amount)} $CIA at ${quote.price.usd} USD per $CIA (CoinGecko, ${utcMinute(quote.price.updatedAt)}).`,\n 'The server prices the payment again when it credits it, so the days can differ by a few minutes.',\n transactions,\n ].join('\\n')\n}\n\n/** A buy needs a typed yes on a terminal, or --yes. */\nexport function assertConfirmable(options: { stdinIsTTY: boolean; yes: boolean }): void {\n if (options.yes || options.stdinIsTTY) return\n throw new Error(\n '`cia subscription buy` needs a typed yes, and stdin is not a terminal. Run it in a terminal, or pass --yes.'\n )\n}\n\nexport type GrantOutcome =\n | { outcome: 'granted'; tx_hash: string; window_end: string | null; days_left: number }\n | { outcome: 'pending'; tx_hash: string; next: string }\n | { outcome: 'timeout'; tx_hash: string; next: string }\n\nexport interface WaitForGrantOptions {\n txHash: string\n /** The status read before the payment. */\n before: SubscriptionStatusFacts | null\n readStatus: () => Promise<SubscriptionStatusFacts | null>\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n timeoutMs?: number\n intervalMs?: number\n}\n\n/**\n * Polls the status every 5 s for at most 120 s. granted: the window moved\n * and the payment is no longer pending. pending: the server saw the payment\n * and has not priced it yet. timeout: the server has not seen it. Never resends.\n */\nexport async function waitForGrant(options: WaitForGrantOptions): Promise<GrantOutcome> {\n const now = options.now ?? (() => Date.now())\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))\n const timeoutMs = options.timeoutMs ?? GRANT_WAIT_MS\n const intervalMs = options.intervalMs ?? GRANT_POLL_MS\n const tx = options.txHash.toLowerCase()\n const before = options.before\n const deadline = now() + timeoutMs\n let seen = false\n while (now() < deadline) {\n await sleep(Math.min(intervalMs, deadline - now()))\n let status: SubscriptionStatusFacts | null = null\n try {\n status = await options.readStatus()\n } catch {\n status = null\n }\n if (!status) continue\n if (status.pending_payments.some((payment) => payment.tx_hash.toLowerCase() === tx)) {\n seen = true\n continue\n }\n const moved = !before || !before.active || status.window_end !== before.window_end\n if (status.active && moved) {\n return { outcome: 'granted', tx_hash: options.txHash, window_end: status.window_end, days_left: status.days_left }\n }\n }\n const next = `Run \\`${STATUS_COMMAND}\\` in a few minutes. Do not pay again.`\n return seen\n ? { outcome: 'pending', tx_hash: options.txHash, next }\n : { outcome: 'timeout', tx_hash: options.txHash, next }\n}\n\nexport interface BuyChain {\n readCiaBalance(address: string): Promise<bigint | null>\n readEthBalance(address: string): Promise<bigint | null>\n readAllowance(owner: string): Promise<bigint | null>\n approve: typeof approveCiaForSubscription\n deposit: typeof depositCiaForSubscription\n}\n\n/** The Robinhood Chain, through ROBINHOOD_RPC_URL or the public endpoints. */\nexport function robinhoodBuyChain(env: NodeJS.ProcessEnv = process.env): BuyChain {\n return {\n readCiaBalance: (address) => readCiaBalance(address, env),\n readEthBalance: (address) => readRobinhoodEthBalance(address, env),\n readAllowance: (owner) => readCiaAllowance(owner, env),\n approve: (key, amount) => approveCiaForSubscription(key, amount, env),\n deposit: (key, amount) => depositCiaForSubscription(key, amount, env),\n }\n}\n\nexport interface BuyDependencies {\n account: { address: string; privateKey: Hex; keyIsPublic?: boolean }\n days: number\n readStatus: () => Promise<SubscriptionStatusFacts | null>\n fetchPrice: () => Promise<CiaPrice>\n /** Shows the text and resolves true on the user's yes. */\n confirm: (text: string) => Promise<boolean>\n chain?: BuyChain\n log?: (line: string) => void\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n timeoutMs?: number\n}\n\nexport interface BuyResult {\n days: number\n usd: number\n amount_cia: string\n price_usd: string\n price_time: string\n approve_tx: string | null\n deposit_tx: string\n deposit_url: string\n grant: GrantOutcome\n}\n\n/** Runs one buy. Throws, with nothing sent, on every refusal before the yes. */\nexport async function executeBuy(deps: BuyDependencies): Promise<BuyResult> {\n const chain = deps.chain ?? robinhoodBuyChain()\n const log = deps.log ?? (() => {})\n const { account } = deps\n if (account.keyIsPublic === true) throw new Error(PUBLIC_KEY_WALLET_TEXT)\n\n const status = await deps.readStatus()\n const price = await deps.fetchPrice()\n const quote = quoteForDays(deps.days, price)\n const [ciaBalance, ethBalance, allowance] = await Promise.all([\n chain.readCiaBalance(account.address),\n chain.readEthBalance(account.address),\n chain.readAllowance(account.address),\n ])\n const plan = planBuy({ wallet: account, status, quote, ciaBalance, ethBalance, allowance })\n if (!plan.ok) throw new Error(plan.reason)\n if (!(await deps.confirm(confirmText(quote, plan.approve)))) {\n throw new Error('Buy cancelled. Nothing was sent.')\n }\n\n let approveTx: string | null = null\n if (plan.approve) {\n const approval = await chain.approve(account.privateKey, quote.amount)\n approveTx = approval.txHash\n log(`Approve: ${explorerTxUrl(approval.txHash)}`)\n if (approval.status !== 'success') {\n throw new Error(`The approval failed on chain: ${explorerTxUrl(approval.txHash)}. No $CIA was paid.`)\n }\n }\n const deposit = await chain.deposit(account.privateKey, quote.amount)\n log(`Payment: ${explorerTxUrl(deposit.txHash)}`)\n if (deposit.status !== 'success') {\n throw new Error(`The payment failed on chain: ${explorerTxUrl(deposit.txHash)}. No $CIA was paid.`)\n }\n const received = deposit.received\n if (\n !received ||\n received.from.toLowerCase() !== account.address.toLowerCase() ||\n received.token.toLowerCase() !== CIA_TOKEN_ADDRESS ||\n received.amount !== quote.amount\n ) {\n throw new Error(\n `The payment landed, but its receipt does not show ${formatCia(quote.amount)} $CIA from this wallet: ${explorerTxUrl(deposit.txHash)}. Do not pay again. Run \\`${STATUS_COMMAND}\\`.`\n )\n }\n\n const grant = await waitForGrant({\n txHash: deposit.txHash,\n before: status,\n readStatus: deps.readStatus,\n now: deps.now,\n sleep: deps.sleep,\n timeoutMs: deps.timeoutMs,\n })\n return {\n days: quote.days,\n usd: quote.usd,\n amount_cia: formatCia(quote.amount),\n price_usd: price.usd,\n price_time: price.updatedAt.toISOString(),\n approve_tx: approveTx,\n deposit_tx: deposit.txHash,\n deposit_url: explorerTxUrl(deposit.txHash),\n grant,\n }\n}\n\n/** The outcome in plain lines. */\nexport function formatBuyResult(result: BuyResult): string {\n const lines = [`Paid ${result.amount_cia} $CIA for about ${result.days} ${result.days === 1 ? 'day' : 'days'}: ${result.deposit_url}`]\n const grant = result.grant\n if (grant.outcome === 'granted') {\n lines.push(`Subscription active until ${grant.window_end ?? 'unknown'} (about ${grant.days_left.toFixed(1)} days left).`)\n } else if (grant.outcome === 'pending') {\n lines.push('The server has seen the payment and is pricing it.', grant.next)\n } else {\n lines.push('The server has not credited the payment yet.', grant.next)\n }\n return lines.join('\\n')\n}\n"],"mappings":";;;;AAmBA,MAAa,gBAAgB;AAC7B,MAAa,gBAAgB;AAC7B,MAAa,iBAAiB;AAC9B,MAAa,gBAAgB;;AAe7B,SAAgB,QAAQ,OAA0B;CAChD,MAAM,EAAE,UAAU;CAClB,IAAI,MAAM,OAAO,gBAAgB,MAAM,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAuB;CAC1F,IAAI,CAAC,MAAM,QACT,OAAO;EACL,IAAI;EACJ,QAAQ,sGAAsG,eAAe;CAC/H;CAEF,MAAM,UAAU,MAAM,OAAO,iBAAiB;CAC9C,IAAI,SACF,OAAO;EACL,IAAI;EACJ,QAAQ,sCAAsC,cAAc,QAAQ,OAAO,EAAE,mDAAmD,eAAe;CACjJ;CAEF,MAAM,OAAO,MAAM,OAAO,SAAS,KAAK,IAAI,GAAG,MAAM,OAAO,SAAS,IAAI;CACzE,MAAM,OAAO,KAAK,MAAM,gBAAgB,IAAI;CAC5C,IAAI,MAAM,OAAO,MACf,OAAO;EACL,IAAI;EACJ,QACE,OAAO,IACH,4BAA4B,KAAK,QAAQ,CAAC,EAAE,uCAAuC,cAAc,yDACjG,4BAA4B,KAAK,QAAQ,CAAC,EAAE,uCAAuC,cAAc,gBAAgB,KAAK,GAAG,SAAS,IAAI,QAAQ,OAAO;CAC7J;CAEF,IAAI,MAAM,eAAe,QAAQ,MAAM,eAAe,MACpD,OAAO;EACL,IAAI;EACJ,QACE;CACJ;CAEF,IAAI,MAAM,aAAa,MAAM,QAAQ;EACnC,MAAM,QAAQ,MAAM,SAAS,MAAM;EACnC,OAAO;GACL,IAAI;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AK;EACZ,WAAW,KAAK;CAClB,CAAC;CACD,OAAO;EACL,MAAM,MAAM;EACZ,KAAK,MAAM;EACX,YAAY,UAAU,MAAM,MAAM;EAClC,WAAW,MAAM;EACjB,YAAY,MAAM,UAAU,YAAY;EACxC,YAAY;EACZ,YAAY,QAAQ;EACpB,aAAa,cAAc,QAAQ,MAAM;EACzC;CACF;AACF;;AAGA,SAAgB,gBAAgB,QAA2B;CACzD,MAAM,QAAQ,CAAC,QAAQ,OAAO,WAAW,kBAAkB,OAAO,KAAK,GAAG,OAAO,SAAS,IAAI,QAAQ,OAAO,IAAI,OAAO,aAAa;CACrI,MAAM,QAAQ,OAAO;CACrB,IAAI,MAAM,YAAY,WACpB,MAAM,KAAK,6BAA6B,MAAM,cAAc,UAAU,UAAU,MAAM,UAAU,QAAQ,CAAC,EAAE,aAAa;MACnH,IAAI,MAAM,YAAY,WAC3B,MAAM,KAAK,sDAAsD,MAAM,IAAI;MAE3E,MAAM,KAAK,gDAAgD,MAAM,IAAI;CAEvE,OAAO,MAAM,KAAK,IAAI;AACxB"}
@@ -1,7 +1,7 @@
1
- const require_known_keys = require("./known-keys-PKZF5GYd.cjs");
2
- const require_robinhood = require("./robinhood-ChiT69sc.cjs");
3
- const require_quote = require("./quote-B9sYNOiv.cjs");
4
- //#region src/subscription/buy.ts
1
+ const require_known_keys = require("./known-keys-Cy8lKDOA.cjs");
2
+ const require_robinhood = require("./robinhood-DumTxvlA.cjs");
3
+ const require_quote = require("./quote-pFKcSvMv.cjs");
4
+ // src/subscription/buy.ts
5
5
  const GRANT_WAIT_MS = 12e4;
6
6
  const GRANT_POLL_MS = 5e3;
7
7
  const STATUS_COMMAND = "cia subscription status";
@@ -189,7 +189,6 @@ function formatBuyResult(result) {
189
189
  else lines.push("The server has not credited the payment yet.", grant.next);
190
190
  return lines.join("\n");
191
191
  }
192
- //#endregion
193
192
  exports.assertConfirmable = assertConfirmable;
194
193
  exports.executeBuy = executeBuy;
195
194
  exports.formatBuyResult = formatBuyResult;
@@ -1,14 +1,13 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-BW-eSwOZ.cjs");
2
2
  let node_path = require("node:path");
3
3
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
4
4
  let node_os = require("node:os");
5
5
  node_os = require_rolldown_runtime.__toESM(node_os, 1);
6
- //#region src/mcp/cache-location.ts
6
+ // src/mcp/cache-location.ts
7
7
  const CACHE_TTL_MS = 864e5;
8
8
  function chainInsightsHome() {
9
9
  return node_path.default.join(node_os.default.homedir(), ".chain-insights");
10
10
  }
11
- //#endregion
12
11
  Object.defineProperty(exports, "CACHE_TTL_MS", {
13
12
  enumerable: true,
14
13
  get: function() {
@@ -1,11 +1,10 @@
1
1
  import path from "node:path";
2
2
  import os from "node:os";
3
- //#region src/mcp/cache-location.ts
3
+ // src/mcp/cache-location.ts
4
4
  const CACHE_TTL_MS = 864e5;
5
5
  function chainInsightsHome() {
6
6
  return path.join(os.homedir(), ".chain-insights");
7
7
  }
8
- //#endregion
9
8
  export { chainInsightsHome as n, CACHE_TTL_MS as t };
10
9
 
11
- //# sourceMappingURL=cache-location-BO2XkfgI.mjs.map
10
+ //# sourceMappingURL=cache-location-DxTTqBwk.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache-location-BO2XkfgI.mjs","names":[],"sources":["../src/mcp/cache-location.ts"],"sourcesContent":["import path from 'node:path'\nimport os from 'node:os'\n\n// One home and one lifetime for every file cache of the package: the tool list\n// (mcp-schema.json) and the graph schema (cache/schema-<network>-<endpoint>.json).\n// The home is read at call time so a test can point HOME at a temporary\n// directory.\n\nexport const CACHE_TTL_MS = 24 * 60 * 60 * 1000 // 24 hours\n\nexport function chainInsightsHome(): string {\n return path.join(os.homedir(), '.chain-insights')\n}\n"],"mappings":";;;AAQA,MAAa,eAAe;AAE5B,SAAgB,oBAA4B;CAC1C,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,iBAAiB;AAClD"}
1
+ {"version":3,"file":"cache-location-DxTTqBwk.mjs","names":[],"sources":["../src/mcp/cache-location.ts"],"sourcesContent":["import path from 'node:path'\nimport os from 'node:os'\n\n// One home and one lifetime for every file cache of the package: the tool list\n// (mcp-schema.json) and the graph schema (cache/schema-<network>-<endpoint>.json).\n// The home is read at call time so a test can point HOME at a temporary\n// directory.\n\nexport const CACHE_TTL_MS = 24 * 60 * 60 * 1000 // 24 hours\n\nexport function chainInsightsHome(): string {\n return path.join(os.homedir(), '.chain-insights')\n}\n"],"mappings":";;;AAQA,MAAa,eAAe;AAE5B,SAAgB,oBAA4B;CAC1C,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,iBAAiB;AAClD"}
@@ -1,4 +1,4 @@
1
- //#region src/mcp/call-args.ts
1
+ // src/mcp/call-args.ts
2
2
  const NUMERIC_ARG_KEYS = /* @__PURE__ */ new Set([
3
3
  "in_offset",
4
4
  "out_offset",
@@ -42,7 +42,18 @@ function metaDexLookupArgs(args) {
42
42
  ...pools === void 0 ? {} : { pools }
43
43
  };
44
44
  }
45
- //#endregion
46
- export { metaDexLookupArgs, parseMcpCallArgs };
45
+ /**
46
+ * The arguments `cia mcp call meta_token_lookup` hands the lookup: network and
47
+ * symbol as typed. A symbol that looks like a number (a ticker such as 42) stays
48
+ * text, because the tool reads the ticker as the user wrote it.
49
+ */
50
+ function metaTokenLookupArgs(args) {
51
+ const symbol = args["symbol"];
52
+ return {
53
+ network: args["network"],
54
+ ...symbol === void 0 ? {} : { symbol: typeof symbol === "number" ? String(symbol) : symbol }
55
+ };
56
+ }
57
+ export { metaDexLookupArgs, metaTokenLookupArgs, parseMcpCallArgs };
47
58
 
48
- //# sourceMappingURL=call-args-B0oMK1-J.mjs.map
59
+ //# sourceMappingURL=call-args-CBqbYfOE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"call-args-B0oMK1-J.mjs","names":[],"sources":["../src/mcp/call-args.ts"],"sourcesContent":["// `cia mcp call tool key=value` yields strings. A key listed here is coerced\n// to a number; anything else stays a string and is rejected by the tool's\n// numeric zod schema. Every tunable search bound must therefore appear here,\n// or passing it from the CLI fails with a confusing type error.\nconst NUMERIC_ARG_KEYS = new Set([\n 'in_offset',\n 'out_offset',\n 'limit',\n 'skip',\n 'per_query_timeout_seconds',\n 'incident_timestamp',\n 'max_hops',\n 'per_address_limit',\n 'row_limit',\n])\n\nfunction parseMcpArgValue(key: string, value: string): unknown {\n const trimmed = value.trim()\n if (!trimmed) return value\n\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n return JSON.parse(trimmed) as unknown\n }\n\n if (NUMERIC_ARG_KEYS.has(key) && /^-?\\d+(?:\\.\\d+)?$/.test(trimmed)) {\n return Number(trimmed)\n }\n\n return value\n}\n\nexport function parseMcpCallArgs(rawArgs: string[]): Record<string, unknown> {\n const args: Record<string, unknown> = {}\n for (const pair of rawArgs) {\n const eqIdx = pair.indexOf('=')\n if (eqIdx === -1) {\n throw new Error(`Invalid arg format: ${pair} (expected key=value)`)\n }\n const key = pair.slice(0, eqIdx)\n args[key] = parseMcpArgValue(key, pair.slice(eqIdx + 1))\n }\n return args\n}\n\n/**\n * The arguments `cia mcp call meta_dex_lookup` hands the lookup: network, name\n * and address as typed, pools as a boolean when given. The CLI builds this call\n * itself, so every argument the tool admits must be carried here; 0.71.3\n * admitted `address` at the gate and dropped it here (AP1000 #1716).\n */\nexport function metaDexLookupArgs(args: Record<string, unknown>): {\n network: unknown\n name?: unknown\n address?: unknown\n pools?: boolean\n} {\n const pools = args['pools'] === undefined ? undefined : String(args['pools']).toLowerCase() !== 'false'\n return {\n network: args['network'],\n ...(args['name'] === undefined ? {} : { name: args['name'] }),\n ...(args['address'] === undefined ? {} : { address: args['address'] }),\n ...(pools === undefined ? {} : { pools }),\n }\n}\n"],"mappings":";AAIA,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,iBAAiB,KAAa,OAAwB;CAC7D,MAAM,UAAU,MAAM,KAAK;CAC3B,IAAI,CAAC,SAAS,OAAO;CAErB,IAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,WAAW,GAAG,GACnD,OAAO,KAAK,MAAM,OAAO;CAG3B,IAAI,iBAAiB,IAAI,GAAG,KAAK,oBAAoB,KAAK,OAAO,GAC/D,OAAO,OAAO,OAAO;CAGvB,OAAO;AACT;AAEA,SAAgB,iBAAiB,SAA4C;CAC3E,MAAM,OAAgC,CAAC;CACvC,KAAK,MAAM,QAAQ,SAAS;EAC1B,MAAM,QAAQ,KAAK,QAAQ,GAAG;EAC9B,IAAI,UAAU,IACZ,MAAM,IAAI,MAAM,uBAAuB,KAAK,sBAAsB;EAEpE,MAAM,MAAM,KAAK,MAAM,GAAG,KAAK;EAC/B,KAAK,OAAO,iBAAiB,KAAK,KAAK,MAAM,QAAQ,CAAC,CAAC;CACzD;CACA,OAAO;AACT;;;;;;;AAQA,SAAgB,kBAAkB,MAKhC;CACA,MAAM,QAAQ,KAAK,aAAa,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK,QAAQ,CAAC,CAAC,YAAY,MAAM;CAChG,OAAO;EACL,SAAS,KAAK;EACd,GAAI,KAAK,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,KAAK,QAAQ;EAC3D,GAAI,KAAK,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,KAAK,WAAW;EACpE,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;CACzC;AACF"}
1
+ {"version":3,"file":"call-args-CBqbYfOE.mjs","names":[],"sources":["../src/mcp/call-args.ts"],"sourcesContent":["// `cia mcp call tool key=value` yields strings. A key listed here is coerced\n// to a number; anything else stays a string and is rejected by the tool's\n// numeric zod schema. Every tunable search bound must therefore appear here,\n// or passing it from the CLI fails with a confusing type error.\nconst NUMERIC_ARG_KEYS = new Set([\n 'in_offset',\n 'out_offset',\n 'limit',\n 'skip',\n 'per_query_timeout_seconds',\n 'incident_timestamp',\n 'max_hops',\n 'per_address_limit',\n 'row_limit',\n])\n\nfunction parseMcpArgValue(key: string, value: string): unknown {\n const trimmed = value.trim()\n if (!trimmed) return value\n\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n return JSON.parse(trimmed) as unknown\n }\n\n if (NUMERIC_ARG_KEYS.has(key) && /^-?\\d+(?:\\.\\d+)?$/.test(trimmed)) {\n return Number(trimmed)\n }\n\n return value\n}\n\nexport function parseMcpCallArgs(rawArgs: string[]): Record<string, unknown> {\n const args: Record<string, unknown> = {}\n for (const pair of rawArgs) {\n const eqIdx = pair.indexOf('=')\n if (eqIdx === -1) {\n throw new Error(`Invalid arg format: ${pair} (expected key=value)`)\n }\n const key = pair.slice(0, eqIdx)\n args[key] = parseMcpArgValue(key, pair.slice(eqIdx + 1))\n }\n return args\n}\n\n/**\n * The arguments `cia mcp call meta_dex_lookup` hands the lookup: network, name\n * and address as typed, pools as a boolean when given. The CLI builds this call\n * itself, so every argument the tool admits must be carried here; 0.71.3\n * admitted `address` at the gate and dropped it here (AP1000 #1716).\n */\nexport function metaDexLookupArgs(args: Record<string, unknown>): {\n network: unknown\n name?: unknown\n address?: unknown\n pools?: boolean\n} {\n const pools = args['pools'] === undefined ? undefined : String(args['pools']).toLowerCase() !== 'false'\n return {\n network: args['network'],\n ...(args['name'] === undefined ? {} : { name: args['name'] }),\n ...(args['address'] === undefined ? {} : { address: args['address'] }),\n ...(pools === undefined ? {} : { pools }),\n }\n}\n\n/**\n * The arguments `cia mcp call meta_token_lookup` hands the lookup: network and\n * symbol as typed. A symbol that looks like a number (a ticker such as 42) stays\n * text, because the tool reads the ticker as the user wrote it.\n */\nexport function metaTokenLookupArgs(args: Record<string, unknown>): {\n network: unknown\n symbol?: unknown\n} {\n const symbol = args['symbol']\n return {\n network: args['network'],\n ...(symbol === undefined ? {} : { symbol: typeof symbol === 'number' ? String(symbol) : symbol }),\n }\n}\n"],"mapp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OAAO,MAAM,IAAI,OAAO;CACjG;AACF"}
@@ -1,4 +1,4 @@
1
- //#region src/mcp/call-args.ts
1
+ // src/mcp/call-args.ts
2
2
  const NUMERIC_ARG_KEYS = /* @__PURE__ */ new Set([
3
3
  "in_offset",
4
4
  "out_offset",
@@ -42,6 +42,18 @@ function metaDexLookupArgs(args) {
42
42
  ...pools === void 0 ? {} : { pools }
43
43
  };
44
44
  }
45
- //#endregion
45
+ /**
46
+ * The arguments `cia mcp call meta_token_lookup` hands the lookup: network and
47
+ * symbol as typed. A symbol that looks like a number (a ticker such as 42) stays
48
+ * text, because the tool reads the ticker as the user wrote it.
49
+ */
50
+ function metaTokenLookupArgs(args) {
51
+ const symbol = args["symbol"];
52
+ return {
53
+ network: args["network"],
54
+ ...symbol === void 0 ? {} : { symbol: typeof symbol === "number" ? String(symbol) : symbol }
55
+ };
56
+ }
46
57
  exports.metaDexLookupArgs = metaDexLookupArgs;
58
+ exports.metaTokenLookupArgs = metaTokenLookupArgs;
47
59
  exports.parseMcpCallArgs = parseMcpCallArgs;
@@ -1,17 +1,12 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
- import { a as resolveGraphMcpEndpoint, n as applyMcpAuthHeaders } from "./client-7qOfAdpH.mjs";
3
- //#region src/mcp/capabilities.ts
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
+ import { a as resolveGraphMcpEndpoint, n as applyMcpAuthHeaders } from "./client-BaHAIidE.mjs";
3
+ // src/mcp/capabilities.ts
4
4
  var capabilities_exports = /* @__PURE__ */ __exportAll({
5
- familyDisplayName: () => familyDisplayName,
6
5
  fetchNetworkCapabilities: () => fetchNetworkCapabilities,
7
6
  findNetworkCapability: () => findNetworkCapability,
8
7
  formatNetworkCapabilities: () => formatNetworkCapabilities,
9
8
  formatNetworkCapability: () => formatNetworkCapability,
10
- formatNetworkOverview: () => formatNetworkOverview,
11
- groupThousands: () => groupThousands,
12
- laneDisplayName: () => laneDisplayName,
13
- layerDisplayName: () => layerDisplayName,
14
- mirrorGraphNetworkCapabilities: () => mirrorGraphNetworkCapabilities
9
+ formatNetworkOverview: () => formatNetworkOverview
15
10
  });
16
11
  const AVAILABLE_TOOLS_PER_LINE = 3;
17
12
  function isRecord(value) {
@@ -380,7 +375,6 @@ function formatNetworkCapability(network) {
380
375
  ...formatProgressTables(tables, head !== void 0)
381
376
  ].join("\n");
382
377
  }
383
- //#endregion
384
378
  export { findNetworkCapability as n, mirrorGraphNetworkCapabilities as r, capabilities_exports as t };
385
379
 
386
- //# sourceMappingURL=capabilities-DxojbX4D.mjs.map
380
+ //# sourceMappingURL=capabilities-BRNHcabF.mjs.map