dexbot 1.6.11 → 1.6.13

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 (398) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +11 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/analysis/tradingview/README.md +1 -1
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  7. package/claw/README.md +1 -0
  8. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  9. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  10. package/claw/modules/chain_broadcast.ts +7 -1
  11. package/claw/modules/claw_bridge.ts +0 -3
  12. package/claw/modules/claw_launcher.ts +1 -1
  13. package/claw/modules/claw_skill_md.ts +1 -0
  14. package/claw/modules/launcher_mode_detector.ts +9 -2
  15. package/claw/package.json +3 -3
  16. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  17. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/account_resolver.d.ts +1 -1
  20. package/dist/analysis/account_resolver.js +2 -1
  21. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  22. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +3 -21
  23. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  24. package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
  25. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
  26. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
  27. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
  28. package/dist/analysis/analyze_args.d.ts +43 -0
  29. package/dist/analysis/analyze_args.js +61 -0
  30. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  31. package/dist/analysis/analyze_kalman.js +7 -17
  32. package/dist/analysis/analyze_regime.js +7 -17
  33. package/dist/analysis/analyze_regime_windows.js +8 -18
  34. package/dist/analysis/analyze_risk_profile.js +8 -18
  35. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  36. package/dist/analysis/analyze_volatility.js +7 -17
  37. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +221 -28
  38. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
  39. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  40. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
  41. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  42. package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
  43. package/dist/analysis/bot_fitting/shared_utils.js +125 -9
  44. package/dist/analysis/bot_key_utils.d.ts +18 -10
  45. package/dist/analysis/bot_key_utils.js +7 -4
  46. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  47. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  48. package/dist/analysis/chain_pool.d.ts +3 -1
  49. package/dist/analysis/chart_ui.d.ts +35 -3
  50. package/dist/analysis/chart_ui.js +43 -4
  51. package/dist/analysis/chart_utils.d.ts +5 -5
  52. package/dist/analysis/chart_utils.js +9 -0
  53. package/dist/analysis/fills_cache.d.ts +4 -24
  54. package/dist/analysis/fills_cache.js +3 -84
  55. package/dist/analysis/fills_source.d.ts +33 -3
  56. package/dist/analysis/fills_source.js +83 -13
  57. package/dist/analysis/grid_correction_check.d.ts +2 -24
  58. package/dist/analysis/grid_correction_check.js +27 -69
  59. package/dist/analysis/math_utils.d.ts +91 -6
  60. package/dist/analysis/math_utils.js +119 -7
  61. package/dist/analysis/pnl_report.js +29 -29
  62. package/dist/analysis/price_sources.d.ts +30 -9
  63. package/dist/analysis/price_sources.js +28 -4
  64. package/dist/analysis/resolve_bot_accounts.js +2 -2
  65. package/dist/analysis/resolve_source.d.ts +1 -1
  66. package/dist/analysis/resolve_source.js +31 -10
  67. package/dist/analysis/trade_profitability.d.ts +29 -2
  68. package/dist/analysis/trade_profitability.js +73 -147
  69. package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
  70. package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
  71. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  72. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  73. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  74. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  75. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  76. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -34
  77. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  78. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
  79. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  80. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
  81. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  82. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  83. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  84. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  85. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  86. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  87. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  88. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  89. package/dist/analysis/worker_pool.d.ts +38 -0
  90. package/dist/analysis/worker_pool.js +67 -0
  91. package/dist/credential-daemon.js +34 -20
  92. package/dist/dexbot.js +78 -59
  93. package/dist/market_adapter/ama_signal_runner.js +21 -54
  94. package/dist/market_adapter/candle_utils.d.ts +29 -19
  95. package/dist/market_adapter/candle_utils.js +35 -21
  96. package/dist/market_adapter/cli_args.d.ts +22 -0
  97. package/dist/market_adapter/cli_args.js +30 -0
  98. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  99. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  100. package/dist/market_adapter/core/config_normalizers.js +11 -6
  101. package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
  102. package/dist/market_adapter/core/kibana_candles.js +12 -9
  103. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  104. package/dist/market_adapter/core/kibana_client.js +8 -7
  105. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  106. package/dist/market_adapter/core/market_adapter_service.d.ts +320 -153
  107. package/dist/market_adapter/core/market_adapter_service.js +228 -269
  108. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  109. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  110. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  111. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  112. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  113. package/dist/market_adapter/core/strategies/ama.js +2 -4
  114. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  115. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  116. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  117. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  118. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  119. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  120. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  121. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  122. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  123. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  124. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  125. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  126. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  127. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  128. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  129. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  130. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  131. package/dist/market_adapter/inputs/fetch_book_data.js +3 -2
  132. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
  133. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
  134. package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
  135. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  136. package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
  137. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  138. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  139. package/dist/market_adapter/inputs/window_cache.d.ts +93 -156
  140. package/dist/market_adapter/inputs/window_cache.js +59 -184
  141. package/dist/market_adapter/interval_utils.d.ts +15 -5
  142. package/dist/market_adapter/interval_utils.js +16 -1
  143. package/dist/market_adapter/log_format.d.ts +6 -6
  144. package/dist/market_adapter/log_format.js +28 -21
  145. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  146. package/dist/market_adapter/lp_chart_core.js +26 -192
  147. package/dist/market_adapter/lp_chart_runner.d.ts +10 -7
  148. package/dist/market_adapter/lp_chart_runner.js +37 -19
  149. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  150. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  151. package/dist/market_adapter/market_adapter.d.ts +94 -32
  152. package/dist/market_adapter/market_adapter.js +94 -120
  153. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  154. package/dist/market_adapter/utils/adapter_client.js +2 -2
  155. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  156. package/dist/market_adapter/utils/chain.d.ts +50 -41
  157. package/dist/market_adapter/utils/chain.js +40 -46
  158. package/dist/market_adapter/utils/data_discovery.d.ts +49 -2
  159. package/dist/market_adapter/utils/data_discovery.js +220 -27
  160. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  161. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  162. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  163. package/dist/market_adapter/utils/file_lock.js +36 -32
  164. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  165. package/dist/market_adapter/utils/month_shards.js +237 -0
  166. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  167. package/dist/market_adapter/utils/native_history.js +35 -28
  168. package/dist/modules/account_bots.d.ts +578 -21
  169. package/dist/modules/account_bots.js +272 -267
  170. package/dist/modules/account_orders.d.ts +79 -30
  171. package/dist/modules/account_orders.js +60 -64
  172. package/dist/modules/authority_resolver.d.ts +12 -2
  173. package/dist/modules/authority_resolver.js +15 -8
  174. package/dist/modules/bitshares-native/chain_client.d.ts +39 -4
  175. package/dist/modules/bitshares-native/chain_client.js +59 -59
  176. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  177. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  178. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  179. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  180. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  181. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  182. package/dist/modules/bitshares-native/index.d.ts +1 -1
  183. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  184. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  185. package/dist/modules/bitshares-native/resolvers.js +22 -25
  186. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  187. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  188. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  189. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  190. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  191. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  192. package/dist/modules/bitshares-native/serial/types.js +73 -108
  193. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  194. package/dist/modules/bitshares-native/signing_client.js +19 -14
  195. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  196. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  197. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  198. package/dist/modules/bitshares-native/transport.js +5 -4
  199. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  200. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  201. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  202. package/dist/modules/bitshares_client.d.ts +45 -13
  203. package/dist/modules/bitshares_client.js +28 -19
  204. package/dist/modules/bot_defaults.d.ts +8 -16
  205. package/dist/modules/bot_defaults.js +1 -5
  206. package/dist/modules/bot_settings.d.ts +44 -10
  207. package/dist/modules/bot_settings.js +11 -8
  208. package/dist/modules/bots_file_lock.d.ts +6 -6
  209. package/dist/modules/bots_file_lock.js +16 -12
  210. package/dist/modules/broadcast_failure.d.ts +4 -3
  211. package/dist/modules/broadcast_failure.js +5 -4
  212. package/dist/modules/chain_keys.d.ts +42 -40
  213. package/dist/modules/chain_keys.js +53 -45
  214. package/dist/modules/chain_orders.d.ts +94 -60
  215. package/dist/modules/chain_orders.js +81 -118
  216. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  217. package/dist/modules/constants.d.ts +534 -32
  218. package/dist/modules/constants.js +35 -48
  219. package/dist/modules/cr_planner.d.ts +41 -3
  220. package/dist/modules/cr_planner.js +1 -5
  221. package/dist/modules/credential_policy.d.ts +68 -8
  222. package/dist/modules/credential_policy.js +37 -31
  223. package/dist/modules/credential_session_cache.d.ts +2 -2
  224. package/dist/modules/credit_pricing.d.ts +43 -6
  225. package/dist/modules/credit_pricing.js +70 -60
  226. package/dist/modules/credit_runtime.d.ts +283 -118
  227. package/dist/modules/credit_runtime.js +500 -231
  228. package/dist/modules/crypto/browser_provider.js +6 -4
  229. package/dist/modules/crypto/node_provider.js +1 -1
  230. package/dist/modules/crypto/pure_scrypt.js +35 -4
  231. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  232. package/dist/modules/crypto/sync.d.ts +9 -9
  233. package/dist/modules/crypto/sync.js +16 -9
  234. package/dist/modules/daemon_node_health.d.ts +4 -3
  235. package/dist/modules/dexbot_class.d.ts +213 -146
  236. package/dist/modules/dexbot_class.js +183 -86
  237. package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
  238. package/dist/modules/dexbot_cow_runtime.js +302 -234
  239. package/dist/modules/dexbot_credential_client.d.ts +19 -18
  240. package/dist/modules/dexbot_credential_client.js +1 -2
  241. package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
  242. package/dist/modules/dexbot_fill_runtime.js +53 -47
  243. package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
  244. package/dist/modules/dexbot_maintenance_runtime.js +187 -147
  245. package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
  246. package/dist/modules/dexbot_startup_runtime.js +56 -57
  247. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  248. package/dist/modules/dexbot_state_recovery.js +18 -13
  249. package/dist/modules/fund_registry.d.ts +4 -2
  250. package/dist/modules/fund_registry.js +10 -10
  251. package/dist/modules/general_settings.d.ts +30 -4
  252. package/dist/modules/graceful_shutdown.d.ts +3 -3
  253. package/dist/modules/graceful_shutdown.js +19 -13
  254. package/dist/modules/grid_price_source.d.ts +1 -1
  255. package/dist/modules/key_store.d.ts +14 -8
  256. package/dist/modules/key_store.js +7 -7
  257. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  258. package/dist/modules/launcher/adapter_requirement.js +5 -5
  259. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  260. package/dist/modules/launcher/bot_supervisor.js +12 -11
  261. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  262. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  263. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  264. package/dist/modules/launcher/credential_daemon.js +2 -2
  265. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  266. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  267. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  268. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  269. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  270. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  271. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  272. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  273. package/dist/modules/launcher/supervisor_control.js +4 -2
  274. package/dist/modules/lazy_shim.d.ts +11 -0
  275. package/dist/modules/lazy_shim.js +16 -0
  276. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  277. package/dist/modules/market_adapter_whitelist.js +15 -3
  278. package/dist/modules/node_connect_policy.d.ts +3 -2
  279. package/dist/modules/node_failure_ledger.d.ts +6 -5
  280. package/dist/modules/node_manager.d.ts +41 -11
  281. package/dist/modules/node_manager.js +5 -4
  282. package/dist/modules/order/accounting.d.ts +53 -24
  283. package/dist/modules/order/accounting.js +16 -15
  284. package/dist/modules/order/async_lock.d.ts +5 -2
  285. package/dist/modules/order/async_lock.js +1 -1
  286. package/dist/modules/order/export.d.ts +7 -6
  287. package/dist/modules/order/export.js +1 -7
  288. package/dist/modules/order/format.d.ts +16 -7
  289. package/dist/modules/order/format.js +15 -3
  290. package/dist/modules/order/genesis_policy.d.ts +24 -21
  291. package/dist/modules/order/genesis_policy.js +17 -10
  292. package/dist/modules/order/grid.d.ts +144 -36
  293. package/dist/modules/order/grid.js +226 -145
  294. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  295. package/dist/modules/order/grid_reconcile.js +13 -12
  296. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  297. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  298. package/dist/modules/order/index.d.ts +264 -1
  299. package/dist/modules/order/logger.d.ts +46 -19
  300. package/dist/modules/order/logger.js +38 -49
  301. package/dist/modules/order/logger_state.d.ts +4 -4
  302. package/dist/modules/order/manager.d.ts +232 -191
  303. package/dist/modules/order/manager.js +110 -130
  304. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  305. package/dist/modules/order/processed_fill_store.js +16 -27
  306. package/dist/modules/order/strategy.d.ts +21 -13
  307. package/dist/modules/order/strategy.js +5 -6
  308. package/dist/modules/order/sync_engine.d.ts +91 -33
  309. package/dist/modules/order/sync_engine.js +84 -53
  310. package/dist/modules/order/utils/math.d.ts +157 -102
  311. package/dist/modules/order/utils/math.js +77 -38
  312. package/dist/modules/order/utils/order.d.ts +310 -110
  313. package/dist/modules/order/utils/order.js +153 -126
  314. package/dist/modules/order/utils/slot.d.ts +1 -1
  315. package/dist/modules/order/utils/system.d.ts +156 -26
  316. package/dist/modules/order/utils/system.js +103 -71
  317. package/dist/modules/order/utils/validate.d.ts +89 -41
  318. package/dist/modules/order/utils/validate.js +26 -24
  319. package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
  320. package/dist/modules/order/utils/withPoolRef.js +18 -12
  321. package/dist/modules/order/working_grid.d.ts +14 -13
  322. package/dist/modules/paths.d.ts +1 -4
  323. package/dist/modules/paths.js +33 -61
  324. package/dist/modules/process_discovery.d.ts +1 -1
  325. package/dist/modules/process_discovery.js +2 -1
  326. package/dist/modules/runtime.d.ts +7 -3
  327. package/dist/modules/runtime.js +4 -3
  328. package/dist/modules/runtime_settings.d.ts +14 -11
  329. package/dist/modules/runtime_settings.js +30 -24
  330. package/dist/modules/settings_merge.d.ts +29 -3
  331. package/dist/modules/settings_merge.js +56 -78
  332. package/dist/modules/socket_json_client.d.ts +9 -5
  333. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  334. package/dist/modules/storage/browser_adapter.js +7 -30
  335. package/dist/modules/storage/index.d.ts +1 -1
  336. package/dist/modules/storage/node_adapter.d.ts +45 -27
  337. package/dist/modules/storage/node_adapter.js +9 -9
  338. package/dist/modules/storage/types.d.ts +5 -4
  339. package/dist/modules/types.d.ts +1090 -6
  340. package/dist/modules/types.js +4 -1
  341. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  342. package/dist/modules/utils/asset_symbols.js +2 -1
  343. package/dist/modules/utils/errors.d.ts +9 -0
  344. package/dist/modules/utils/errors.js +24 -4
  345. package/dist/modules/utils/time_range.d.ts +1 -12
  346. package/dist/modules/utils/time_range.js +1 -1
  347. package/dist/modules/validate_profiles.js +53 -43
  348. package/dist/modules/version_notice.d.ts +23 -11
  349. package/dist/modules/version_notice.js +6 -4
  350. package/dist/pm2.d.ts +28 -27
  351. package/dist/pm2.js +61 -40
  352. package/dist/scripts/analyze-credit.d.ts +2 -1
  353. package/dist/scripts/analyze-credit.js +23 -24
  354. package/dist/scripts/analyze-git.js +2 -15
  355. package/dist/scripts/analyze-orders.d.ts +77 -9
  356. package/dist/scripts/analyze-orders.js +65 -40
  357. package/dist/scripts/chart_command.d.ts +27 -18
  358. package/dist/scripts/chart_command.js +15 -13
  359. package/dist/scripts/check_any.d.ts +22 -0
  360. package/dist/scripts/check_any.js +158 -0
  361. package/dist/scripts/diagnose-pool-history.js +13 -13
  362. package/dist/scripts/print_grid.js +0 -1
  363. package/dist/scripts/run-tests.js +39 -8
  364. package/dist/scripts/runner.js +1 -1
  365. package/dist/scripts/sync-version.js +0 -10
  366. package/dist/scripts/test-credit-renewal.js +30 -21
  367. package/dist/scripts/update.d.ts +10 -5
  368. package/dist/scripts/update.js +168 -103
  369. package/dist/scripts/update_dist_freshness.js +1 -0
  370. package/dist/scripts/update_layout.d.ts +61 -0
  371. package/dist/scripts/update_layout.js +180 -0
  372. package/dist/scripts/validate_bots.js +2 -1
  373. package/dist/scripts/verify-browser-bundle.js +8 -0
  374. package/dist/unlock.d.ts +28 -3
  375. package/dist/unlock.js +63 -35
  376. package/docs/BITSHARES_ONBOARDING.md +10 -12
  377. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
  378. package/docs/COW_INVARIANTS.md +13 -6
  379. package/docs/DEXBOT_COMPARISON.md +8 -8
  380. package/docs/EVOLUTION.md +10 -8
  381. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  382. package/docs/GRID_RECALCULATION.md +4 -2
  383. package/docs/GRID_RECONCILE.md +14 -3
  384. package/docs/LIFECYCLE.md +11 -11
  385. package/docs/MPA_CREDIT_USAGE.md +22 -3
  386. package/docs/README.md +14 -3
  387. package/docs/WORKFLOW.md +1 -0
  388. package/docs/architecture.md +31 -19
  389. package/docs/developer_guide.md +6 -6
  390. package/market_adapter/README.md +12 -5
  391. package/modules/README.md +4 -1
  392. package/package.json +9 -9
  393. package/scripts/README.md +43 -38
  394. package/tests/README.md +25 -10
  395. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  396. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  397. package/scripts/git-viewer.sh +0 -489
  398. package/scripts/postinstall.js +0 -16
@@ -10,13 +10,18 @@
10
10
  * - Handles branch switching if needed
11
11
  * - Reinstalls npm dependencies and rebuilds TypeScript sources
12
12
  *
13
- * 2. npm package install (e.g. `npm install -g dexbot`):
13
+ * 2. Package install (npm / pnpm / yarn):
14
+ * - Classifies the exact layout via scripts/update_layout.ts
14
15
  * - Compares the installed version against the npm registry
15
- * - Runs `npm install -g <pkg>@<latest>` to fetch the newest release
16
+ * - npm global: runs `npm install -g <pkg>@<latest>` in place (its package
17
+ * directory is stable across reinstalls), then verifies version + dist/
18
+ * - local / linked / pnpm / yarn: NOT replaced in place (the parent
19
+ * lockfile owns a local dep; pnpm/yarn global trees are
20
+ * content-addressed and version-hashed). Update is refused with the exact
21
+ * command to run instead.
16
22
  * - Skips the git and local build steps (published packages are pre-built)
17
- * - Requires the npm CLI and registry access; only global installs can be
18
- * updated in place (local `node_modules` deps must be updated from the
19
- * parent project with `npm update`)
23
+ * - Resolves the manager CLI next to the running Node (process.execPath) so
24
+ * a version-manager (nvm/fnm/volta) PATH mismatch is not a false failure
20
25
  *
21
26
  * Shared tail for both layouts:
22
27
  * - Selectively restarts active runtime processes
@@ -39,10 +44,11 @@ import { homedir } from 'node:os';
39
44
  import { pathToFileURL } from 'node:url';
40
45
  import { sendControlCommand } from '../modules/launcher/supervisor_control.js';
41
46
  import { findMissingDistEntries, inspectDistBundle } from './update_dist_freshness.js';
47
+ import { classifyInstallLayout, globalInstallArgs, globalInstallCommand, parseVersionLine, } from './update_layout.js';
42
48
  // Import update configuration from constants
43
49
  // Contains: REPOSITORY_URL, BRANCH, BUILD_DIR settings
44
50
  import { UPDATER, BUILD_DIR } from '../modules/constants.js';
45
- import { PATHS, isGlobalNpmPackageDir } from '../modules/paths.js';
51
+ import { PATHS } from '../modules/paths.js';
46
52
  import { Config } from '../modules/config.js';
47
53
  import { getStorage } from '../modules/storage/index.js';
48
54
  const { readJSON } = getStorage();
@@ -143,37 +149,39 @@ function compareVersions(a, b) {
143
149
  return 0;
144
150
  }
145
151
  /**
146
- * getNpmLatestVersion: Query the npm registry for the latest published version.
152
+ * spawnCli: spawn a package-manager CLI portably.
147
153
  *
148
- * Throws when the registry is unreachable so the update is treated as failed
149
- * (exit 1) and the scheduler does not restart the daemon for a no-op.
154
+ * On Windows the manager is a `.cmd`/`.bat` shim that CreateProcess cannot
155
+ * launch directly, and Node's `shell: true` joins the file path into the
156
+ * command line without quoting — which breaks the very common
157
+ * `C:\Program Files\nodejs\npm.cmd`. Route through `cmd.exe /c` with every
158
+ * argument explicitly quoted so spaces and the shim both survive.
150
159
  */
151
- function getNpmLatestVersion(pkgName) {
152
- try {
153
- const version = execSync(`npm view ${pkgName} version`, { stdio: 'pipe' }).toString().trim();
154
- if (!version)
155
- throw new Error('npm returned an empty version.');
156
- return version;
157
- }
158
- catch (err) {
159
- throw new Error(`Could not reach the npm registry to check for updates (${getErrorMessage(err)}).`);
160
+ function spawnCli(bin, args, opts) {
161
+ if (process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(bin)) {
162
+ const quote = (s) => `"${s.replace(/"/g, '""')}"`;
163
+ const line = [quote(bin), ...args.map(quote)].join(' ');
164
+ return spawnSync(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', line], opts);
160
165
  }
166
+ return spawnSync(bin, args, opts);
161
167
  }
162
168
  /**
163
- * getGlobalNpmRoot: Resolve the npm global install root (e.g. <prefix>/lib/node_modules).
164
- * Returns an empty string when npm is unavailable.
169
+ * getLatestVersion: Query npm for the latest published version.
170
+ *
171
+ * Uses the npm CLI that belongs to the *running* Node (resolved next to
172
+ * process.execPath) rather than whatever `npm` is first on PATH. A Node
173
+ * version manager (nvm/fnm/volta) can put a different Node's npm on PATH,
174
+ * whose global root does not contain this package — the mismatch that used to
175
+ * reject perfectly valid global installs.
176
+ *
177
+ * Returns '' when the registry cannot be reached; callers then install
178
+ * `@latest` and verify the result instead of failing the whole update.
165
179
  */
166
- function getGlobalNpmRoot() {
167
- try {
168
- // npm prints only the root to stdout, but notifications can land there
169
- // in some setups — take the LAST non-empty line so a stray leading
170
- // notice cannot produce a garbage path.
171
- const lines = execSync('npm root -g', { stdio: 'pipe' }).toString().split('\n').filter((l) => l.trim());
172
- return lines.length > 0 ? lines[lines.length - 1].trim() : '';
173
- }
174
- catch (_) {
180
+ function getLatestVersion(pkgName) {
181
+ const res = spawnCli(resolveManagerBinary('npm'), ['view', pkgName, 'version'], { encoding: 'utf8' });
182
+ if (res.error || res.status !== 0)
175
183
  return '';
176
- }
184
+ return parseVersionLine(String(res.stdout || ''));
177
185
  }
178
186
  /**
179
187
  * Resolve a path to its real filesystem location, falling back to the
@@ -193,21 +201,84 @@ function realpathSafe(p) {
193
201
  }
194
202
  }
195
203
  /**
196
- * True when the project root is a DIRECT child of the npm global install root
197
- * (e.g. <prefix>/lib/node_modules/dexbot). Comparing the immediate parent —
198
- * rather than a string prefix — rejects nested packages, custom `--prefix`
199
- * layouts where the package lives deeper in the tree, and relative/absolute
200
- * path mismatches. Both sides are realpath'd so a symlinked global prefix
201
- * (e.g. a nvm/system prefix with a symlink component) is not falsely
202
- * rejected: import.meta.url already realpaths PROJECT_ROOT, while `npm
203
- * root -g` returns the un-resolved prefix. Symlinked layouts (e.g. `npm
204
- * link`) resolve to the real package location, which is intentionally not a
205
- * global-root child, so they fall through to the manual-update error below.
204
+ * resolveManagerBinary: Find a package manager CLI.
205
+ *
206
+ * Prefers the binary next to the running Node (process.execPath), which is
207
+ * what makes version-manager installs work: the npm beside the running node
208
+ * necessarily shares its global root. Falls back to the bare name so the PATH
209
+ * is used when the launcher layout is unusual (npx, shims).
210
+ */
211
+ function resolveManagerBinary(manager) {
212
+ const dir = path.dirname(process.execPath);
213
+ const candidates = process.platform === 'win32'
214
+ ? [`${manager}.cmd`, `${manager}.exe`, manager]
215
+ : [manager];
216
+ for (const candidate of candidates) {
217
+ const full = path.join(dir, candidate);
218
+ if (fs.existsSync(full))
219
+ return full;
220
+ }
221
+ return manager;
222
+ }
223
+ /** Last non-empty line of a CLI query, or '' when the command fails. */
224
+ function queryCliLine(bin, args) {
225
+ try {
226
+ const res = spawnCli(bin, args, { encoding: 'utf8' });
227
+ if (res.error || res.status !== 0)
228
+ return '';
229
+ const lines = String(res.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean);
230
+ return lines.length > 0 ? lines[lines.length - 1] : '';
231
+ }
232
+ catch (_) {
233
+ return '';
234
+ }
235
+ }
236
+ /**
237
+ * collectGlobalRoots: Ask each manager where its global tree lives.
238
+ *
239
+ * Any query may fail (CLI missing, pnpm refusing when its bin dir is off
240
+ * PATH) — the classifier falls back to path signatures for those. Roots are
241
+ * realpath'd so a symlinked prefix compares equal to the already-realpath'd
242
+ * PROJECT_ROOT.
243
+ */
244
+ function collectGlobalRoots(npmRootKnown) {
245
+ const npmRoot = npmRootKnown ?? queryCliLine(resolveManagerBinary('npm'), ['root', '-g']);
246
+ const pnpmRoot = queryCliLine(resolveManagerBinary('pnpm'), ['root', '-g']);
247
+ const yarnDir = queryCliLine(resolveManagerBinary('yarn'), ['global', 'dir']);
248
+ return {
249
+ npm: npmRoot ? realpathSafe(npmRoot) : '',
250
+ pnpm: pnpmRoot ? realpathSafe(pnpmRoot) : '',
251
+ yarn: yarnDir ? realpathSafe(path.join(yarnDir, 'node_modules')) : '',
252
+ };
253
+ }
254
+ /**
255
+ * detectInstallLayout: classify the install, probing only what is needed.
256
+ *
257
+ * An npm-global match settles the layout without spawning pnpm/yarn: invoking
258
+ * pnpm can trigger a corepack download or hit a broken shim on first run, and
259
+ * there is no reason to pay for that when npm already matched. Non-npm layouts
260
+ * fall through to the full probe (required for pnpm/yarn root comparison).
261
+ */
262
+ function detectInstallLayout(pkgName) {
263
+ const npmRoot = queryCliLine(resolveManagerBinary('npm'), ['root', '-g']);
264
+ const npmOnly = classifyInstallLayout(PATHS.PROJECT_ROOT, { npm: npmRoot ? realpathSafe(npmRoot) : '', pnpm: '', yarn: '' }, pkgName);
265
+ if (npmOnly.kind === 'npm-global')
266
+ return npmOnly;
267
+ return classifyInstallLayout(PATHS.PROJECT_ROOT, collectGlobalRoots(npmRoot), pkgName);
268
+ }
269
+ /**
270
+ * runProgram: Spawn a CLI with inherited stdio, throwing on failure.
271
+ *
272
+ * An argv array (not a shell string) keeps paths with spaces intact; spawnCli
273
+ * handles the Windows `.cmd` shim case.
206
274
  */
207
- function isDirectGlobalInstall(projectRoot, globalRoot) {
208
- const resolvedRoot = realpathSafe(path.resolve(globalRoot));
209
- const resolvedProject = realpathSafe(path.resolve(projectRoot));
210
- return path.dirname(resolvedProject) === resolvedRoot;
275
+ function runProgram(cwd, bin, args) {
276
+ log(`Executing: ${bin} ${args.join(' ')}`);
277
+ const res = spawnCli(bin, args, { stdio: 'inherit', cwd });
278
+ if (res.error || res.status !== 0) {
279
+ console.error(updateError(`[ERROR] Command failed: ${bin} ${args.join(' ')}`));
280
+ throw res.error ?? new Error(`Command exited with status ${res.status}`);
281
+ }
211
282
  }
212
283
  function readLivePidFile(filePath) {
213
284
  if (!fs.existsSync(filePath))
@@ -265,7 +336,7 @@ function restartMonolithicRuntime(monolithic) {
265
336
  }
266
337
  catch (_) { }
267
338
  try {
268
- process.kill(monolithic.wrapperPid, 'SIGUSR2');
339
+ process.kill(Number(monolithic.wrapperPid), 'SIGUSR2');
269
340
  }
270
341
  catch (_) { }
271
342
  }
@@ -420,7 +491,7 @@ async function restartActiveIsolatedProcesses() {
420
491
  return false;
421
492
  }
422
493
  const runningNames = Object.entries(status)
423
- .filter(([name, info]) => name !== 'dexbot-update' && info && info.status === 'running')
494
+ .filter(([name, info]) => name !== 'dexbot-update' && Boolean(info) && info.status === 'running')
424
495
  .map(([name]) => name);
425
496
  if (runningNames.length === 0) {
426
497
  log('No active isolated processes are currently running. Skipping supervisor restart.');
@@ -566,7 +637,7 @@ async function restartActiveRuntimes({ monolithicWasRunning, hadMonolithicFiles
566
637
  if (jsonStart !== -1) {
567
638
  const jsonPart = output.substring(jsonStart);
568
639
  const parsed = JSON.parse(jsonPart);
569
- runningProcesses = parsed.map((p) => p.name);
640
+ runningProcesses = parsed.map((p) => String(p.name ?? '')).filter(Boolean);
570
641
  }
571
642
  else {
572
643
  log('Warning: PM2 jlist output did not contain JSON array.');
@@ -584,7 +655,7 @@ async function restartActiveRuntimes({ monolithicWasRunning, hadMonolithicFiles
584
655
  if (pm2Usable) {
585
656
  const botsToRestart = activeInConfig.filter((name) => runningProcesses.includes(name));
586
657
  const activeBots = (config.bots || []).filter((b) => b.active !== false);
587
- const runningActiveBots = activeBots.filter((b) => runningProcesses.includes(b.name));
658
+ const runningActiveBots = activeBots.filter((b) => runningProcesses.includes(String(b.name)));
588
659
  const marketAdapterRequired = pm2NeedsMarketAdapter(runningActiveBots);
589
660
  const serviceAppsToRestart = marketAdapterRequired ? ['dexbot-adapter'] : [];
590
661
  const servicesToRestart = serviceAppsToRestart.filter((name) => runningProcesses.includes(name));
@@ -699,72 +770,71 @@ async function buildAndRestartRuntimes({ monolithicWasRunning, hadMonolithicFile
699
770
  }
700
771
  // ── npm-install update flow ──────────────────────────────────────────
701
772
  /**
702
- * Update a globally installed npm package to the latest published version.
773
+ * Update an installed package to the latest published version.
703
774
  *
704
775
  * Steps:
705
- * 1. Compare installed package.json version against the npm registry.
706
- * 2. Exit cleanly (0) when already up to date — no restart needed.
707
- * 3. Verify this is a global install (only that layout can be replaced in place).
708
- * 4. Snapshot runtime state, then run `npm install -g <pkg>@<latest>` from a
709
- * neutral cwd (home dir) so npm can freely swap the package directory the
710
- * currently running process executes from.
776
+ * 1. Classify the install layout (scripts/update_layout.ts).
777
+ * 2. Compare the installed package.json version against the npm registry and
778
+ * exit cleanly (0) when already up to date — no restart needed.
779
+ * 3. In-place update is only safe for an npm global install; local, linked,
780
+ * pnpm and yarn layouts are refused with the exact command to run (the
781
+ * running process cannot safely re-resolve a content-addressed tree).
782
+ * 4. Snapshot runtime state, then run the manager's global install from a
783
+ * neutral cwd (home dir) so it can freely swap the package directory this
784
+ * process executes from.
711
785
  * 5. Regenerate the ecosystem config and restart active runtimes using the
712
786
  * new code — the published package ships a pre-built dist/, so there is
713
787
  * no local TypeScript build step.
714
788
  */
715
- async function runNpmUpdateFlow() {
716
- log('Detected npm package installation. Checking npm registry for updates...');
789
+ async function runPackageUpdateFlow() {
790
+ log('Detected a package install. Checking registry for updates...');
717
791
  const pkgName = readPackageName(PATHS.PROJECT_ROOT);
718
792
  const currentVersion = readPackageVersion(PATHS.PROJECT_ROOT);
719
793
  if (!currentVersion) {
720
794
  throw new Error(`Could not read a version from package.json at ${PATHS.PROJECT_ROOT}.`);
721
795
  }
722
796
  log(`Current installed version: ${currentVersion}`);
723
- // Verify the npm CLI is available and this is a genuine global install
724
- // BEFORE querying the registry. Only a global layout can be replaced in
725
- // place by `npm install -g`; a local (project) dependency must be updated
726
- // from its own package tree instead.
727
- const globalRoot = getGlobalNpmRoot();
728
- if (!globalRoot) {
729
- throw new Error('DEXBot2 auto-update requires the npm CLI with registry access (it runs `npm view` and ' +
730
- '`npm install -g`). npm could not be found on PATH or returned no global root. ' +
731
- 'Install Node.js/npm or update the package manually.');
732
- }
733
- if (!isDirectGlobalInstall(PATHS.PROJECT_ROOT, globalRoot)) {
734
- // A genuine local (non-global) dependency resolves to a different real
735
- // parent; a symlinked prefix or version-manager/pnpm store lands the
736
- // package somewhere `npm root -g` does not point at. Either way the
737
- // package cannot be swapped in place.
738
- throw new Error('DEXBot2 is installed at ' + PATHS.PROJECT_ROOT + ' but `npm root -g` reports ' + globalRoot + '. ' +
739
- 'Auto-update cannot replace the package in place; the install root differs from `npm root -g` ' +
740
- '(a symlinked prefix, pnpm/yarn global store, or a different Node version manager prefix). ' +
741
- 'Run `npm update ' + pkgName + '` in the parent project directory, or fix the mismatch and re-run `dexbot update`.');
742
- }
743
- const latestVersion = getNpmLatestVersion(pkgName);
744
- log(`Latest published version: ${latestVersion}`);
745
- if (compareVersions(currentVersion, latestVersion) >= 0) {
797
+ // Classify where we are INSTALLED before touching anything. Local, linked,
798
+ // pnpm and yarn layouts must not be replaced in place; each gets an exact
799
+ // command instead. Only an npm global install is swapped in place (its
800
+ // package directory is stable across reinstalls).
801
+ const layout = detectInstallLayout(pkgName);
802
+ log(`Install layout: ${layout.kind}${layout.manager ? ` (${layout.manager})` : ''}`);
803
+ // Best-effort: an unreachable registry means we install `@latest` and let
804
+ // the post-install check confirm the result instead of failing outright.
805
+ const latestVersion = getLatestVersion(pkgName);
806
+ log(`Latest published version: ${latestVersion || 'unknown'}`);
807
+ if (latestVersion && compareVersions(currentVersion, latestVersion) >= 0) {
746
808
  log('DEXBot2 is already up to date (installed version matches or exceeds the latest published version).');
747
809
  process.exit(0);
748
810
  }
749
- log(`${currentVersion} -> ${latestVersion} update available. Proceeding with npm update...`);
750
- // Snapshot pre-update runtime state BEFORE npm replaces the package files.
811
+ if (!layout.autoUpdatable) {
812
+ throw new Error(`DEXBot2 is installed at ${PATHS.PROJECT_ROOT} (${layout.kind} layout). ` +
813
+ 'Auto-update cannot replace this installation in place. ' +
814
+ layout.hint);
815
+ }
816
+ const manager = layout.manager ?? 'npm';
817
+ const managerBin = resolveManagerBinary(manager);
818
+ const versionToInstall = latestVersion || 'latest';
819
+ log(`${currentVersion} -> ${versionToInstall} update available. Proceeding with ${manager} update...`);
820
+ // Snapshot pre-update runtime state BEFORE the package files are replaced.
751
821
  const snapshot = snapshotMonolithicState();
752
- // Run from a neutral cwd: npm's reify swaps the package directory this
753
- // process is executing from, so the working directory may briefly not exist.
754
- runIn(homedir(), `npm install -g ${pkgName}@${latestVersion}`);
822
+ // Run from a neutral cwd: the manager swaps the package directory this
823
+ // process is executing from, so the working directory may briefly vanish.
824
+ runProgram(homedir(), managerBin, globalInstallArgs(manager, pkgName, versionToInstall));
755
825
  // Post-install sanity checks: the published package is pre-built, so a
756
- // successful `npm install -g` MUST leave the requested version and a
757
- // usable dist/ bundle behind. Refuse to restart runtimes against a broken
758
- // install (mirrors the git flow's staleness guard).
826
+ // successful install MUST leave the requested version and a usable dist/
827
+ // bundle behind. Refuse to restart runtimes against a broken install
828
+ // (mirrors the git flow's staleness guard).
759
829
  const installedAfter = readPackageVersion(PATHS.PROJECT_ROOT);
760
830
  log(`Installed version after update: ${installedAfter || 'unknown'}`);
761
831
  if (!installedAfter) {
762
832
  throw new Error(`Update completed but the package version could not be read at ${PATHS.PROJECT_ROOT}. ` +
763
833
  `The global install may be broken; inspect it with \`npm ls -g ${pkgName}\`.`);
764
834
  }
765
- if (compareVersions(installedAfter, latestVersion) < 0) {
835
+ if (latestVersion && compareVersions(installedAfter, latestVersion) < 0) {
766
836
  throw new Error(`Update completed but the installed version (${installedAfter}) is older than the requested ` +
767
- `${latestVersion}. Run \`npm install -g ${pkgName}@${latestVersion}\` manually and inspect the npm output.`);
837
+ `${latestVersion}. Run \`${globalInstallCommand(manager, pkgName, latestVersion)}\` manually and inspect the output.`);
768
838
  }
769
839
  // Verify the pre-built bundle is complete. Published packages ship a
770
840
  // pre-built dist/, so a missing file here means the publish is broken and
@@ -788,25 +858,20 @@ async function runNpmUpdateFlow() {
788
858
  /**
789
859
  * STEP 0: Detect Installation Layout
790
860
  *
791
- * Two supported layouts:
792
- * 1. Git checkout (has a .git dir) -> git pull + npm install + build
793
- * 2. Global npm package install (path under a node_modules tree) ->
794
- * `npm install -g <pkg>@<latest>` (pre-built dist, no local build)
861
+ * A git checkout (has a .git dir) -> git pull + npm install + build.
862
+ * Any npm/pnpm/yarn package install -> runPackageUpdateFlow(), which
863
+ * classifies the exact layout and either updates in place (npm global) or
864
+ * reports the precise command to run (local, linked, pnpm, yarn).
795
865
  *
796
- * A git checkout wins over the npm path so a repo that was npm-linked is
797
- * still updated through git. Neither layout -> fail with a clear message.
866
+ * A git checkout wins over the package path so a repo that was npm-linked
867
+ * is still updated through git.
798
868
  */
799
869
  const isGitRepo = fs.existsSync(path.join(PATHS.PROJECT_ROOT, '.git'));
800
- const isNpmInstall = isGlobalNpmPackageDir(PATHS.PROJECT_ROOT);
801
- if (!isGitRepo && isNpmInstall) {
802
- await runNpmUpdateFlow();
870
+ if (!isGitRepo) {
871
+ await runPackageUpdateFlow();
803
872
  logSuccess('DEXBot2 update completed successfully.');
804
873
  process.exit(0);
805
874
  }
806
- if (!isGitRepo) {
807
- throw new Error('DEXBot2 is neither a git checkout nor an npm package install. ' +
808
- 'Auto-update is not available for this installation.');
809
- }
810
875
  // Get configured repository URL and target branch
811
876
  const repoUrl = UPDATER.REPOSITORY_URL;
812
877
  let branch = UPDATER.BRANCH;
@@ -18,6 +18,7 @@ export const REQUIRED_DIST_ENTRIES = [
18
18
  'credential-daemon.js',
19
19
  'modules/dexbot_class.js',
20
20
  'scripts/update.js',
21
+ 'scripts/update_layout.js',
21
22
  ];
22
23
  /** Roots compiled by the root tsconfig.json (`include`), used to map sources to dist. */
23
24
  export const COMPILED_SOURCE_ROOTS = ['modules', 'market_adapter', 'scripts', 'analysis'];
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Install-layout detection for the updater.
3
+ *
4
+ * The updater runs from *inside* the installed package, so the layout it finds
5
+ * itself in decides everything: whether it can replace itself in place, which
6
+ * package manager owns the tree, and which command the operator must run when
7
+ * it cannot. Keeping this pure (no fs, no child_process, roots passed in) makes
8
+ * every branch table-testable without touching a real global install.
9
+ *
10
+ * Supported layouts:
11
+ * - npm global -> in-place `npm install -g` is safe (stable directory)
12
+ * - pnpm global -> detected, but NOT updated in place (content-addressed
13
+ * store: the running process points at a version-hashed
14
+ * directory that the next `pnpm add -g` abandons)
15
+ * - yarn global -> detected, NOT updated in place (same reasoning; the
16
+ * layout also differs across Yarn 1 / Berry)
17
+ * - local dependency-> the parent project's lockfile owns the version
18
+ * - linked/unknown -> `npm link`, custom prefixes, nested packages
19
+ */
20
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn';
21
+ export type LayoutKind = 'npm-global' | 'pnpm-global' | 'yarn-global' | 'local' | 'linked';
22
+ export interface GlobalRoots {
23
+ /** `npm root -g` (e.g. <prefix>/lib/node_modules). '' when unavailable. */
24
+ npm: string;
25
+ /** `pnpm root -g` (e.g. $PNPM_HOME/global/v11). '' when unavailable. */
26
+ pnpm: string;
27
+ /** Yarn global node_modules (e.g. ~/.config/yarn/global/node_modules). */
28
+ yarn: string;
29
+ }
30
+ export interface InstallLayout {
31
+ kind: LayoutKind;
32
+ /** Manager that owns the install, when it can be inferred. */
33
+ manager: PackageManager | null;
34
+ /** True only when the updater may replace the install in place. */
35
+ autoUpdatable: boolean;
36
+ /** Exact, copy-pasteable command for this layout (always present). */
37
+ hint: string;
38
+ }
39
+ /** True when `root` is a direct child of `globalRoot` (both resolved first). */
40
+ export declare function isDirectChildOf(root: string, globalRoot: string): boolean;
41
+ /** True when `root` sits directly under a directory named `node_modules`. */
42
+ export declare function isNodeModulesChild(root: string): boolean;
43
+ /**
44
+ * Manager inferred from install-shape markers in the path. Used when the
45
+ * manager's own `root`/`dir` query is unavailable or does not line up.
46
+ */
47
+ export declare function detectManagerFromPath(root: string): PackageManager | null;
48
+ export declare function globalInstallCommand(manager: PackageManager | null, pkg: string, version?: string): string;
49
+ export declare function localInstallCommand(manager: PackageManager | null, pkg: string, version?: string): string;
50
+ /** argv for spawning the global install with the owning manager. */
51
+ export declare function globalInstallArgs(manager: PackageManager, pkg: string, version?: string): string[];
52
+ export declare function classifyInstallLayout(root: string, roots: GlobalRoots, pkgName: string): InstallLayout;
53
+ /**
54
+ * parseVersionLine: Pick the last semver-looking line from a CLI's stdout.
55
+ *
56
+ * `npm view <pkg> version` is normally a single line, but npm can prepend
57
+ * notices; matching a version shape instead of trusting the last line keeps a
58
+ * notice from being compared as a version.
59
+ */
60
+ export declare function parseVersionLine(stdout: string): string;
61
+ //# sourceMappingURL=update_layout.d.ts.map
@@ -0,0 +1,180 @@
1
+ import path from 'node:path';
2
+ function normalize(p) {
3
+ return path.resolve(p);
4
+ }
5
+ /** Path with forward slashes, for stable segment matching on every platform. */
6
+ function slashPath(p) {
7
+ return normalize(p).split(path.sep).join('/');
8
+ }
9
+ /**
10
+ * Paths are case-insensitive on Windows; compare accordingly so a drive-letter
11
+ * or username casing difference between PROJECT_ROOT and a CLI-reported root
12
+ * does not turn a valid global install into a "local" one.
13
+ */
14
+ function samePath(a, b) {
15
+ const na = normalize(a);
16
+ const nb = normalize(b);
17
+ return process.platform === 'win32'
18
+ ? na.toLowerCase() === nb.toLowerCase()
19
+ : na === nb;
20
+ }
21
+ /** True when `root` is a direct child of `globalRoot` (both resolved first). */
22
+ export function isDirectChildOf(root, globalRoot) {
23
+ if (!globalRoot)
24
+ return false;
25
+ return samePath(path.dirname(normalize(root)), globalRoot);
26
+ }
27
+ /** True when `root` sits directly under a directory named `node_modules`. */
28
+ export function isNodeModulesChild(root) {
29
+ return path.basename(path.dirname(normalize(root))) === 'node_modules';
30
+ }
31
+ /**
32
+ * Manager inferred from install-shape markers in the path. Used when the
33
+ * manager's own `root`/`dir` query is unavailable or does not line up.
34
+ */
35
+ export function detectManagerFromPath(root) {
36
+ const p = slashPath(root);
37
+ if (/(?:^|\/)\.pnpm\//.test(p) || /\/pnpm\/global\//.test(p))
38
+ return 'pnpm';
39
+ if (/\/yarn\/(?:global|berry)\//.test(p) || /\/\.yarn\/(?:global|berry)\//.test(p))
40
+ return 'yarn';
41
+ return null;
42
+ }
43
+ /**
44
+ * pnpm's global tree is `<pnpmRoot>/<hash>/node_modules/<pkg>` (pnpm >= 9) or
45
+ * `<pnpmRoot>/<version>/node_modules/<pkg>` (older). Either way the package is
46
+ * one level below a `node_modules` that is itself one level below `pnpmRoot`.
47
+ */
48
+ function isUnderPnpmRoot(root, pnpmRoot) {
49
+ if (!pnpmRoot)
50
+ return false;
51
+ const rel = path.relative(normalize(pnpmRoot), normalize(root));
52
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
53
+ return false;
54
+ const parts = rel.split(path.sep);
55
+ return parts.length >= 3 && parts[parts.length - 2] === 'node_modules';
56
+ }
57
+ /**
58
+ * Fallback pnpm-global signature when `pnpm root -g` could not be queried.
59
+ *
60
+ * Two shapes occur because Node resolves symlinks by default:
61
+ * - symlink preserved: <pnpmRoot>/<hash>/node_modules/<pkg>
62
+ * - symlink resolved: <pnpmRoot>/<hash>/node_modules/.pnpm/<pkg>@<v>/node_modules/<pkg>
63
+ * Both carry a `global/<version>` segment, which a local dependency never does.
64
+ */
65
+ function looksLikePnpmGlobal(root) {
66
+ const p = slashPath(root);
67
+ if (/\/global\/v?\d+\/[^/]+\/node_modules\/[^/]+$/.test(p))
68
+ return true;
69
+ return /\/global\/v?\d+\//.test(p) && /\/node_modules\/\.pnpm\//.test(p);
70
+ }
71
+ /** Fallback yarn-global signature when `yarn global dir` could not be queried. */
72
+ function looksLikeYarnGlobal(root) {
73
+ return /\/(?:\.?yarn)\/global\/node_modules\/[^/]+$/.test(slashPath(root));
74
+ }
75
+ export function globalInstallCommand(manager, pkg, version = 'latest') {
76
+ switch (manager) {
77
+ case 'pnpm':
78
+ return `pnpm add -g ${pkg}@${version}`;
79
+ case 'yarn':
80
+ return `yarn global add ${pkg}@${version}`;
81
+ default:
82
+ return `npm install -g ${pkg}@${version}`;
83
+ }
84
+ }
85
+ export function localInstallCommand(manager, pkg, version = 'latest') {
86
+ switch (manager) {
87
+ case 'pnpm':
88
+ return `pnpm add ${pkg}@${version}`;
89
+ case 'yarn':
90
+ return `yarn add ${pkg}@${version}`;
91
+ default:
92
+ return `npm install ${pkg}@${version}`;
93
+ }
94
+ }
95
+ /** argv for spawning the global install with the owning manager. */
96
+ export function globalInstallArgs(manager, pkg, version = 'latest') {
97
+ switch (manager) {
98
+ case 'pnpm':
99
+ return ['add', '-g', `${pkg}@${version}`];
100
+ case 'yarn':
101
+ return ['global', 'add', `${pkg}@${version}`];
102
+ default:
103
+ return ['install', '-g', `${pkg}@${version}`];
104
+ }
105
+ }
106
+ export function classifyInstallLayout(root, roots, pkgName) {
107
+ const resolved = normalize(root);
108
+ // ── Global installs ──────────────────────────────────────────────
109
+ // npm is the only layout the updater can swap in place: its package
110
+ // directory is stable across reinstalls.
111
+ if (isDirectChildOf(resolved, roots.npm)) {
112
+ return {
113
+ kind: 'npm-global',
114
+ manager: 'npm',
115
+ autoUpdatable: true,
116
+ hint: globalInstallCommand('npm', pkgName),
117
+ };
118
+ }
119
+ if (isUnderPnpmRoot(resolved, roots.pnpm) || looksLikePnpmGlobal(resolved)) {
120
+ return {
121
+ kind: 'pnpm-global',
122
+ manager: 'pnpm',
123
+ autoUpdatable: false,
124
+ hint: `This is a pnpm global install. Update it with \`${globalInstallCommand('pnpm', pkgName)}\`. ` +
125
+ 'pnpm keeps the running copy in a version-hashed store directory, so dexbot cannot safely ' +
126
+ 'replace it and restart itself in place.',
127
+ };
128
+ }
129
+ if (isDirectChildOf(resolved, roots.yarn) || looksLikeYarnGlobal(resolved)) {
130
+ return {
131
+ kind: 'yarn-global',
132
+ manager: 'yarn',
133
+ autoUpdatable: false,
134
+ hint: `This is a yarn global install. Update it with \`${globalInstallCommand('yarn', pkgName)}\`, ` +
135
+ 'then restart dexbot.',
136
+ };
137
+ }
138
+ // ── Local dependency ─────────────────────────────────────────────
139
+ // The parent project's package.json/lockfile owns the version. An in-place
140
+ // global install would update a *different* copy, and the next `npm ci`
141
+ // would revert it. Note: `npm update` only moves within the declared range
142
+ // — an exact pin needs `install`, which is why the hint uses `install`.
143
+ if (isNodeModulesChild(resolved)) {
144
+ const manager = detectManagerFromPath(resolved);
145
+ return {
146
+ kind: 'local',
147
+ manager,
148
+ autoUpdatable: false,
149
+ hint: `This is a local dependency, not a global install. Run ` +
150
+ `\`${localInstallCommand(manager, pkgName)}\` in the parent project directory ` +
151
+ '(an exact version pin is not moved by `npm update`).',
152
+ };
153
+ }
154
+ // ── Linked / unrecognized ────────────────────────────────────────
155
+ const manager = detectManagerFromPath(resolved);
156
+ return {
157
+ kind: 'linked',
158
+ manager,
159
+ autoUpdatable: false,
160
+ hint: `This install is linked or uses an unrecognized layout (e.g. \`npm link\`, a custom --prefix, ` +
161
+ `or a nested package). Update the linked source checkout, or reinstall globally with ` +
162
+ `\`${globalInstallCommand('npm', pkgName)}\`.`,
163
+ };
164
+ }
165
+ /**
166
+ * parseVersionLine: Pick the last semver-looking line from a CLI's stdout.
167
+ *
168
+ * `npm view <pkg> version` is normally a single line, but npm can prepend
169
+ * notices; matching a version shape instead of trusting the last line keeps a
170
+ * notice from being compared as a version.
171
+ */
172
+ export function parseVersionLine(stdout) {
173
+ const lines = String(stdout || '').split('\n').map((l) => l.trim());
174
+ for (let i = lines.length - 1; i >= 0; i--) {
175
+ if (/^\d+\.\d+\.\d+/.test(lines[i]))
176
+ return lines[i];
177
+ }
178
+ return '';
179
+ }
180
+ //# sourceMappingURL=update_layout.js.map