dexbot 1.4.19 → 1.4.21

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 (302) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +22 -12
  3. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +2 -2
  4. package/analysis/ama_fitting/calibrate_convergence_er.ts +1 -1
  5. package/analysis/ama_fitting/optimizer_high_resolution.ts +2 -1
  6. package/analysis/ama_fitting/package.json +1 -1
  7. package/analysis/analyze_derivatives.ts +4 -2
  8. package/analysis/analyze_dynamic_weight.ts +3 -1
  9. package/analysis/analyze_kalman.ts +3 -1
  10. package/analysis/analyze_regime.ts +3 -1
  11. package/analysis/analyze_regime_windows.ts +3 -1
  12. package/analysis/analyze_volatility.ts +2 -2
  13. package/analysis/bot_fitting/backtest_ama_sweep.ts +2 -1
  14. package/analysis/bot_fitting/backtest_bot_fitting.ts +17 -12
  15. package/analysis/bot_fitting/shared_utils.ts +1 -1
  16. package/analysis/bot_key_utils.ts +1 -5
  17. package/analysis/bot_usage/kibana_bot_queries.ts +1 -256
  18. package/analysis/chart_css.ts +1 -1
  19. package/analysis/chart_utils.ts +24 -0
  20. package/analysis/derivative_chart_generator.ts +3 -2
  21. package/analysis/math_utils.ts +1 -8
  22. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  23. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +91 -55
  24. package/analysis/trend_detection/package.json +1 -1
  25. package/claw/ecosystem.config.cjs +2 -3
  26. package/claw/examples/claw_profiles_example.ts +4 -1
  27. package/claw/examples/memu_integration_example.ts +17 -17
  28. package/claw/modules/chain_actions.ts +51 -54
  29. package/claw/modules/chain_broadcast.ts +66 -104
  30. package/claw/modules/claw_bridge.ts +60 -80
  31. package/claw/modules/claw_catalog.ts +48 -17
  32. package/claw/modules/claw_infra.ts +1 -5
  33. package/claw/modules/claw_launcher.ts +47 -49
  34. package/claw/modules/claw_skill_md.ts +14 -16
  35. package/claw/modules/credit_runtime_adapter.ts +2 -18
  36. package/claw/modules/decision_loop.ts +4 -0
  37. package/claw/modules/dexbot_bridge.ts +1 -1
  38. package/claw/modules/dexbot_profiles.ts +8 -22
  39. package/claw/modules/honest_ecosystem.ts +24 -8
  40. package/claw/modules/launcher_paths.ts +4 -2
  41. package/claw/modules/liquidity_pools.ts +10 -3
  42. package/claw/modules/mcp_utils.ts +109 -0
  43. package/claw/modules/memu_bridge.ts +76 -54
  44. package/claw/modules/mpa_utils.ts +26 -3
  45. package/claw/modules/position_discovery.ts +16 -27
  46. package/claw/modules/position_manager.ts +32 -41
  47. package/claw/modules/position_manager_watch.ts +3 -2
  48. package/claw/modules/short_mpa_strategy.ts +1 -9
  49. package/claw/modules/skill_utils.ts +5 -3
  50. package/claw/modules/utils.ts +9 -1
  51. package/claw/package.json +1 -1
  52. package/claw/runtimes/openclaw-plugin/index.ts +27 -10
  53. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  54. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  55. package/claw/scripts/claw_bridge.ts +1 -1
  56. package/claw/scripts/claw_mcp_server.ts +19 -78
  57. package/claw/scripts/honest_assets_report.ts +19 -84
  58. package/claw/scripts/memu_mcp_server.ts +57 -155
  59. package/claw/tests/test_claw_bridge.ts +6 -2
  60. package/claw/tests/test_claw_mcp_transport.ts +2 -2
  61. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -2
  62. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +1 -1
  63. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +1 -1
  64. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +1 -1
  65. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +1 -1
  66. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +2 -1
  67. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +1 -1
  68. package/dist/analysis/analyze_derivatives.d.ts.map +1 -1
  69. package/dist/analysis/analyze_derivatives.js +4 -2
  70. package/dist/analysis/analyze_derivatives.js.map +1 -1
  71. package/dist/analysis/analyze_dynamic_weight.js +3 -1
  72. package/dist/analysis/analyze_dynamic_weight.js.map +1 -1
  73. package/dist/analysis/analyze_kalman.js +3 -1
  74. package/dist/analysis/analyze_kalman.js.map +1 -1
  75. package/dist/analysis/analyze_regime.js +3 -1
  76. package/dist/analysis/analyze_regime.js.map +1 -1
  77. package/dist/analysis/analyze_regime_windows.js +3 -1
  78. package/dist/analysis/analyze_regime_windows.js.map +1 -1
  79. package/dist/analysis/analyze_volatility.js +2 -2
  80. package/dist/analysis/analyze_volatility.js.map +1 -1
  81. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +1 -1
  82. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +2 -1
  83. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +1 -1
  84. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +18 -13
  85. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +1 -1
  86. package/dist/analysis/bot_fitting/shared_utils.d.ts +1 -12
  87. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +1 -1
  88. package/dist/analysis/bot_fitting/shared_utils.js +1 -1
  89. package/dist/analysis/bot_fitting/shared_utils.js.map +1 -1
  90. package/dist/analysis/bot_key_utils.d.ts +1 -1
  91. package/dist/analysis/bot_key_utils.d.ts.map +1 -1
  92. package/dist/analysis/bot_key_utils.js +1 -5
  93. package/dist/analysis/bot_key_utils.js.map +1 -1
  94. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -337
  95. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +1 -1
  96. package/dist/analysis/bot_usage/kibana_bot_queries.js +1 -241
  97. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +1 -1
  98. package/dist/analysis/chart_css.d.ts +1 -15
  99. package/dist/analysis/chart_css.d.ts.map +1 -1
  100. package/dist/analysis/chart_css.js +1 -1
  101. package/dist/analysis/chart_css.js.map +1 -1
  102. package/dist/analysis/chart_utils.d.ts +0 -3
  103. package/dist/analysis/chart_utils.d.ts.map +1 -1
  104. package/dist/analysis/chart_utils.js +25 -0
  105. package/dist/analysis/chart_utils.js.map +1 -1
  106. package/dist/analysis/derivative_chart_generator.d.ts.map +1 -1
  107. package/dist/analysis/derivative_chart_generator.js +3 -2
  108. package/dist/analysis/derivative_chart_generator.js.map +1 -1
  109. package/dist/analysis/math_utils.d.ts +3 -5
  110. package/dist/analysis/math_utils.d.ts.map +1 -1
  111. package/dist/analysis/math_utils.js +3 -5
  112. package/dist/analysis/math_utils.js.map +1 -1
  113. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +1 -1
  114. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +82 -50
  115. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +1 -1
  116. package/dist/bot.js +2 -2
  117. package/dist/bot.js.map +1 -1
  118. package/dist/credential-daemon.js +1 -1
  119. package/dist/credential-daemon.js.map +1 -1
  120. package/dist/dexbot.d.ts.map +1 -1
  121. package/dist/dexbot.js +20 -17
  122. package/dist/dexbot.js.map +1 -1
  123. package/dist/market_adapter/ama_signal_runner.js +3 -3
  124. package/dist/market_adapter/core/kibana_client.d.ts +1 -3
  125. package/dist/market_adapter/core/kibana_client.d.ts.map +1 -1
  126. package/dist/market_adapter/core/kibana_client.js +1 -1
  127. package/dist/market_adapter/core/kibana_client.js.map +1 -1
  128. package/dist/market_adapter/core/market_adapter_service.d.ts +1 -2
  129. package/dist/market_adapter/core/market_adapter_service.d.ts.map +1 -1
  130. package/dist/market_adapter/core/market_adapter_service.js +9 -4
  131. package/dist/market_adapter/core/market_adapter_service.js.map +1 -1
  132. package/dist/market_adapter/core/strategies/regime_gate.d.ts +1 -2
  133. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +1 -1
  134. package/dist/market_adapter/core/strategies/regime_gate.js +1 -1
  135. package/dist/market_adapter/core/strategies/regime_gate.js.map +1 -1
  136. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -2
  137. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +1 -1
  138. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +5 -5
  139. package/dist/market_adapter/inputs/fetch_lp_data.js +5 -5
  140. package/dist/market_adapter/inputs/kibana_source.d.ts +1 -2
  141. package/dist/market_adapter/inputs/kibana_source.d.ts.map +1 -1
  142. package/dist/market_adapter/inputs/kibana_source.js +1 -1
  143. package/dist/market_adapter/inputs/kibana_source.js.map +1 -1
  144. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +1 -2
  145. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +1 -1
  146. package/dist/market_adapter/lp_chart_strategy_loader.js +4 -4
  147. package/dist/market_adapter/lp_chart_strategy_loader.js.map +1 -1
  148. package/dist/market_adapter/market_adapter.d.ts.map +1 -1
  149. package/dist/market_adapter/market_adapter.js +2 -1
  150. package/dist/market_adapter/market_adapter.js.map +1 -1
  151. package/dist/modules/account_bots.d.ts +3 -0
  152. package/dist/modules/account_bots.d.ts.map +1 -1
  153. package/dist/modules/account_bots.js +156 -46
  154. package/dist/modules/account_bots.js.map +1 -1
  155. package/dist/modules/account_orders.d.ts +1 -7
  156. package/dist/modules/account_orders.d.ts.map +1 -1
  157. package/dist/modules/account_orders.js +9 -17
  158. package/dist/modules/account_orders.js.map +1 -1
  159. package/dist/modules/bitshares_client.d.ts +2 -14
  160. package/dist/modules/bitshares_client.d.ts.map +1 -1
  161. package/dist/modules/bitshares_client.js +22 -31
  162. package/dist/modules/bitshares_client.js.map +1 -1
  163. package/dist/modules/bot_settings.js +1 -1
  164. package/dist/modules/bot_settings.js.map +1 -1
  165. package/dist/modules/chain_keys.js +2 -2
  166. package/dist/modules/chain_keys.js.map +1 -1
  167. package/dist/modules/chain_orders.d.ts +2 -3
  168. package/dist/modules/chain_orders.d.ts.map +1 -1
  169. package/dist/modules/chain_orders.js +8 -25
  170. package/dist/modules/chain_orders.js.map +1 -1
  171. package/dist/modules/config.d.ts +2 -0
  172. package/dist/modules/config.d.ts.map +1 -1
  173. package/dist/modules/config.js +6 -1
  174. package/dist/modules/config.js.map +1 -1
  175. package/dist/modules/constants.d.ts +0 -1
  176. package/dist/modules/constants.d.ts.map +1 -1
  177. package/dist/modules/constants.js +1 -5
  178. package/dist/modules/constants.js.map +1 -1
  179. package/dist/modules/credential_policy.js +1 -1
  180. package/dist/modules/credential_policy.js.map +1 -1
  181. package/dist/modules/dexbot_class.d.ts.map +1 -1
  182. package/dist/modules/dexbot_class.js +3 -2
  183. package/dist/modules/dexbot_class.js.map +1 -1
  184. package/dist/modules/dexbot_cow_runtime.d.ts +0 -7
  185. package/dist/modules/dexbot_cow_runtime.d.ts.map +1 -1
  186. package/dist/modules/dexbot_cow_runtime.js +95 -0
  187. package/dist/modules/dexbot_cow_runtime.js.map +1 -1
  188. package/dist/modules/dexbot_state_recovery.d.ts.map +1 -1
  189. package/dist/modules/dexbot_state_recovery.js +22 -2
  190. package/dist/modules/dexbot_state_recovery.js.map +1 -1
  191. package/dist/modules/fund_registry.d.ts.map +1 -1
  192. package/dist/modules/fund_registry.js +5 -2
  193. package/dist/modules/fund_registry.js.map +1 -1
  194. package/dist/modules/launcher/bot_supervisor.d.ts.map +1 -1
  195. package/dist/modules/launcher/bot_supervisor.js +6 -7
  196. package/dist/modules/launcher/bot_supervisor.js.map +1 -1
  197. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +1 -1
  198. package/dist/modules/launcher/foreign_cred_daemon.js +6 -0
  199. package/dist/modules/launcher/foreign_cred_daemon.js.map +1 -1
  200. package/dist/modules/launcher/market_adapter_runtime.d.ts +2 -3
  201. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +1 -1
  202. package/dist/modules/launcher/market_adapter_runtime.js +7 -15
  203. package/dist/modules/launcher/market_adapter_runtime.js.map +1 -1
  204. package/dist/modules/launcher/monolithic_runtime.d.ts.map +1 -1
  205. package/dist/modules/launcher/monolithic_runtime.js +1 -0
  206. package/dist/modules/launcher/monolithic_runtime.js.map +1 -1
  207. package/dist/modules/launcher/status_reporting.d.ts +1 -2
  208. package/dist/modules/launcher/status_reporting.d.ts.map +1 -1
  209. package/dist/modules/launcher/status_reporting.js +1 -4
  210. package/dist/modules/launcher/status_reporting.js.map +1 -1
  211. package/dist/modules/order/accounting.js +2 -2
  212. package/dist/modules/order/accounting.js.map +1 -1
  213. package/dist/modules/order/format.d.ts +0 -8
  214. package/dist/modules/order/format.d.ts.map +1 -1
  215. package/dist/modules/order/format.js +0 -8
  216. package/dist/modules/order/format.js.map +1 -1
  217. package/dist/modules/order/grid.d.ts.map +1 -1
  218. package/dist/modules/order/grid.js +146 -32
  219. package/dist/modules/order/grid.js.map +1 -1
  220. package/dist/modules/order/logger.js +1 -1
  221. package/dist/modules/order/logger.js.map +1 -1
  222. package/dist/modules/order/logger_state.d.ts +1 -13
  223. package/dist/modules/order/logger_state.d.ts.map +1 -1
  224. package/dist/modules/order/logger_state.js +1 -11
  225. package/dist/modules/order/logger_state.js.map +1 -1
  226. package/dist/modules/order/manager.d.ts +13 -0
  227. package/dist/modules/order/manager.d.ts.map +1 -1
  228. package/dist/modules/order/manager.js +75 -2
  229. package/dist/modules/order/manager.js.map +1 -1
  230. package/dist/modules/order/processed_fill_store.d.ts +0 -5
  231. package/dist/modules/order/processed_fill_store.d.ts.map +1 -1
  232. package/dist/modules/order/processed_fill_store.js +1 -12
  233. package/dist/modules/order/processed_fill_store.js.map +1 -1
  234. package/dist/modules/order/sync_engine.d.ts.map +1 -1
  235. package/dist/modules/order/sync_engine.js +10 -3
  236. package/dist/modules/order/sync_engine.js.map +1 -1
  237. package/dist/modules/order/utils/math.d.ts +80 -1
  238. package/dist/modules/order/utils/math.d.ts.map +1 -1
  239. package/dist/modules/order/utils/math.js +138 -2
  240. package/dist/modules/order/utils/math.js.map +1 -1
  241. package/dist/modules/order/utils/order.d.ts.map +1 -1
  242. package/dist/modules/order/utils/order.js +10 -2
  243. package/dist/modules/order/utils/order.js.map +1 -1
  244. package/dist/modules/paths.d.ts +26 -1
  245. package/dist/modules/paths.d.ts.map +1 -1
  246. package/dist/modules/paths.js +39 -6
  247. package/dist/modules/paths.js.map +1 -1
  248. package/dist/modules/runtime_settings.js +3 -1
  249. package/dist/modules/runtime_settings.js.map +1 -1
  250. package/dist/modules/settings_merge.d.ts.map +1 -1
  251. package/dist/modules/settings_merge.js +3 -1
  252. package/dist/modules/settings_merge.js.map +1 -1
  253. package/dist/modules/storage/browser_adapter.d.ts +8 -3
  254. package/dist/modules/storage/browser_adapter.d.ts.map +1 -1
  255. package/dist/modules/storage/browser_adapter.js +53 -4
  256. package/dist/modules/storage/browser_adapter.js.map +1 -1
  257. package/dist/modules/utils/sanitize_key.d.ts +7 -0
  258. package/dist/modules/utils/sanitize_key.d.ts.map +1 -0
  259. package/dist/modules/utils/sanitize_key.js +15 -0
  260. package/dist/modules/utils/sanitize_key.js.map +1 -0
  261. package/dist/pm2.js +6 -6
  262. package/dist/pm2.js.map +1 -1
  263. package/dist/scripts/analyze-git.js +2 -1
  264. package/dist/scripts/analyze-git.js.map +1 -1
  265. package/dist/scripts/analyze-orders.d.ts +2 -2
  266. package/dist/scripts/analyze-orders.d.ts.map +1 -1
  267. package/dist/scripts/analyze-orders.js +6 -14
  268. package/dist/scripts/analyze-orders.js.map +1 -1
  269. package/dist/scripts/runner.js +1 -1
  270. package/dist/scripts/runner.js.map +1 -1
  271. package/dist/scripts/update.js +1 -1
  272. package/dist/scripts/update.js.map +1 -1
  273. package/docs/BITSHARES_ONBOARDING.md +63 -18
  274. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +5 -14
  275. package/docs/COW_INVARIANTS.md +4 -4
  276. package/docs/CREDENTIAL_SECURITY.md +0 -11
  277. package/docs/DEXBOT_COMPARISON.md +11 -11
  278. package/docs/EVOLUTION.md +12 -10
  279. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +27 -83
  280. package/docs/GRID_RECALCULATION.md +1 -13
  281. package/docs/GRID_RECONCILE.md +24 -24
  282. package/docs/LIFECYCLE.md +4 -4
  283. package/docs/LOGGING.md +1 -1
  284. package/docs/MPA_CREDIT_USAGE.md +3 -3
  285. package/docs/README.md +2 -2
  286. package/docs/WORKFLOW.md +2 -2
  287. package/docs/architecture.md +43 -38
  288. package/docs/developer_guide.md +16 -18
  289. package/market_adapter/README.md +0 -2
  290. package/modules/README.md +2 -1
  291. package/package.json +2 -3
  292. package/scripts/README.md +1 -1
  293. package/scripts/lib/dexbot-paths.sh +20 -11
  294. package/claw/openclaw.plugin.json +0 -13
  295. package/dist/market_adapter/merge_lp_data.d.ts +0 -3
  296. package/dist/market_adapter/merge_lp_data.d.ts.map +0 -1
  297. package/dist/market_adapter/merge_lp_data.js +0 -125
  298. package/dist/market_adapter/merge_lp_data.js.map +0 -1
  299. package/dist/market_adapter/utils/paths.d.ts +0 -3
  300. package/dist/market_adapter/utils/paths.d.ts.map +0 -1
  301. package/dist/market_adapter/utils/paths.js +0 -5
  302. package/dist/market_adapter/utils/paths.js.map +0 -1
@@ -56,6 +56,40 @@ function getSpawn(): any {
56
56
  return _spawn;
57
57
  }
58
58
 
59
+ /**
60
+ * Spawn a detached background child and wait for the spawn itself to succeed.
61
+ * Spawn failures (missing script, ENOENT, EACCES) are reported asynchronously
62
+ * via the child's 'error' event; waiting one macrotask lets those surface as a
63
+ * thrown error instead of callers receiving a false { started: true } result.
64
+ * A permanent 'error' handler remains attached so late errors are logged
65
+ * rather than crashing the host with an unhandled 'error' event.
66
+ */
67
+ function spawnDetached(scriptPath: string, args: string[], cwd: string): Promise<any> {
68
+ const child = getSpawn()('node', [scriptPath, ...args], {
69
+ detached: true,
70
+ stdio: 'ignore',
71
+ cwd
72
+ });
73
+
74
+ return new Promise((resolve, reject) => {
75
+ let settled = false;
76
+ child.on('error', (err: any) => {
77
+ if (!settled) {
78
+ settled = true;
79
+ reject(new Error(`Failed to spawn ${scriptPath}: ${getErrorMessage(err)}`));
80
+ return;
81
+ }
82
+ console.error(`[LAUNCHER] Child process error (${scriptPath}): ${getErrorMessage(err)}`);
83
+ });
84
+ setImmediate(() => {
85
+ if (!settled) {
86
+ settled = true;
87
+ resolve(child);
88
+ }
89
+ });
90
+ });
91
+ }
92
+
59
93
  let _pm2: any;
60
94
  function getPM2Module(): any {
61
95
  if (_pm2 === undefined) {
@@ -88,16 +122,7 @@ async function launcherStart(botName: string | null, options: Record<string, any
88
122
  args.push(botName);
89
123
  }
90
124
 
91
- const child = getSpawn()('node', [dexbotPath, ...args], {
92
- detached: true,
93
- stdio: 'ignore',
94
- cwd: ROOT
95
- });
96
-
97
- child.on('error', (err: any) => {
98
- console.error(`[LAUNCHER] Failed to spawn ${dexbotPath}: ${getErrorMessage(err)}`);
99
- });
100
-
125
+ const child = await spawnDetached(dexbotPath, args, ROOT);
101
126
  child.unref();
102
127
 
103
128
  return {
@@ -124,16 +149,7 @@ async function launcherDrystart(botName: string | null, options: Record<string,
124
149
  args.push(botName);
125
150
  }
126
151
 
127
- const child = getSpawn()('node', [dexbotPath, ...args], {
128
- detached: true,
129
- stdio: 'ignore',
130
- cwd: ROOT
131
- });
132
-
133
- child.on('error', (err: any) => {
134
- console.error(`[LAUNCHER] Failed to spawn ${dexbotPath}: ${getErrorMessage(err)}`);
135
- });
136
-
152
+ const child = await spawnDetached(dexbotPath, args, ROOT);
137
153
  child.unref();
138
154
 
139
155
  return {
@@ -158,10 +174,10 @@ async function launcherReset(botName: string | null, options: Record<string, any
158
174
  const { config } = loadSettingsFile(PROFILES_BOTS_FILE);
159
175
  const entries = normalizeBotEntries(resolveRawBotEntries(config));
160
176
 
161
- const targets = botName ? entries.filter((b: any) => b.name === botName) : entries.filter((b: any) => b.active);
177
+ const targets = botName ? entries.filter((b: any) => b.name === botName) : entries.filter((b: any) => b.active !== false);
162
178
 
163
179
  if (botName && targets.length === 0) {
164
- throw new Error(`Bot '${botName}' not found in profiles/bots.json`);
180
+ throw new Error(`Bot '${botName}' not found in ${PROFILES_BOTS_FILE}`);
165
181
  }
166
182
 
167
183
  const triggered: Array<Record<string, any>> = [];
@@ -221,7 +237,7 @@ async function launcherDisable(botName: string | null, options: Record<string, a
221
237
 
222
238
  const match = entries.find((b: any) => b.name === botName);
223
239
  if (!match) {
224
- throw new Error(`Bot '${botName}' not found in profiles/bots.json`);
240
+ throw new Error(`Bot '${botName}' not found in ${PROFILES_BOTS_FILE}`);
225
241
  }
226
242
 
227
243
  if (match.active === false) {
@@ -252,10 +268,10 @@ async function launcherPm2Start(botName: string | null, options: Record<string,
252
268
  const { config } = loadSettingsFile(PROFILES_BOTS_FILE);
253
269
  const entries = normalizeBotEntries(resolveRawBotEntries(config));
254
270
 
255
- const targets = botName ? entries.filter((b: any) => b.name === botName) : entries.filter((b: any) => b.active);
271
+ const targets = botName ? entries.filter((b: any) => b.name === botName) : entries.filter((b: any) => b.active !== false);
256
272
 
257
273
  if (botName && targets.length === 0) {
258
- throw new Error(`Bot '${botName}' not found or not active in profiles/bots.json`);
274
+ throw new Error(`Bot '${botName}' not found or not active in ${PROFILES_BOTS_FILE}`);
259
275
  }
260
276
 
261
277
  // Then check if daemon is ready
@@ -292,7 +308,7 @@ async function launcherPm2Start(botName: string | null, options: Record<string,
292
308
  * @param {Object} [options={}] - Options
293
309
  * @returns {Promise<Object>} { stopped: true, target }
294
310
  */
295
- async function launcherPm2Stop(target: string, options: Record<string, any> = {}) {
311
+ async function launcherPm2Stop(target: string, _options: Record<string, any> = {}) {
296
312
  await getPM2Module().stopPM2Processes(target || 'all');
297
313
  return {
298
314
  stopped: true,
@@ -306,7 +322,7 @@ async function launcherPm2Stop(target: string, options: Record<string, any> = {}
306
322
  * @param {Object} [options={}] - Options
307
323
  * @returns {Promise<Object>} { deleted: true, target }
308
324
  */
309
- async function launcherPm2Delete(target: string, options: Record<string, any> = {}) {
325
+ async function launcherPm2Delete(target: string, _options: Record<string, any> = {}) {
310
326
  await getPM2Module().deletePM2Processes(target || 'all');
311
327
  return {
312
328
  deleted: true,
@@ -320,7 +336,7 @@ async function launcherPm2Delete(target: string, options: Record<string, any> =
320
336
  * @param {Object} [options={}] - Options
321
337
  * @returns {Promise<Object>} { restarted: true, target }
322
338
  */
323
- async function launcherPm2Restart(target: string, options: Record<string, any> = {}) {
339
+ async function launcherPm2Restart(target: string, _options: Record<string, any> = {}) {
324
340
  await getPM2Module().restartPM2Processes(target || 'all');
325
341
  return {
326
342
  restarted: true,
@@ -422,16 +438,7 @@ async function launcherClawOnly(options: Record<string, any> = {}) {
422
438
  const ROOT = normalizeRoot(options);
423
439
  const pm2ScriptPath = resolveRuntimeScript(ROOT, 'pm2.js');
424
440
 
425
- const child = getSpawn()('node', [pm2ScriptPath, 'claw-only'], {
426
- detached: true,
427
- stdio: 'ignore',
428
- cwd: ROOT
429
- });
430
-
431
- child.on('error', (err: any) => {
432
- console.error(`[LAUNCHER] Failed to spawn ${pm2ScriptPath}: ${getErrorMessage(err)}`);
433
- });
434
-
441
+ const child = await spawnDetached(pm2ScriptPath, ['claw-only'], ROOT);
435
442
  child.unref();
436
443
 
437
444
  return {
@@ -459,16 +466,7 @@ async function launcherUnlockStart(botName: string | null, options: Record<strin
459
466
  args.push(botName);
460
467
  }
461
468
 
462
- const child = getSpawn()('node', [unlockPath, ...args], {
463
- detached: true,
464
- stdio: 'ignore',
465
- cwd: ROOT
466
- });
467
-
468
- child.on('error', (err: any) => {
469
- console.error(`[LAUNCHER] Failed to spawn ${unlockPath}: ${getErrorMessage(err)}`);
470
- });
471
-
469
+ const child = await spawnDetached(unlockPath, args, ROOT);
472
470
  child.unref();
473
471
 
474
472
  return {
@@ -481,5 +479,5 @@ async function launcherUnlockStart(botName: string | null, options: Record<strin
481
479
  };
482
480
  }
483
481
 
484
- export { launcherRun, launcherStart, launcherDrystart, launcherReset, launcherDisable, launcherPm2Start, launcherPm2Stop, launcherPm2Delete, launcherPm2Restart }
482
+ export { launcherRun, launcherDrystart, launcherReset, launcherDisable, launcherPm2Start, launcherPm2Stop, launcherPm2Delete, launcherPm2Restart }
485
483
 
@@ -11,14 +11,15 @@ function normalizeClawRepoRoot(repoRoot: string) {
11
11
  return normalizeRepoRoot(repoRoot);
12
12
  }
13
13
 
14
- // Generated docs must reference scripts that actually exist. Prefer the built
15
- // .js (dist layout); fall back to the .ts source run through tsx.
14
+ // Generated docs must reference scripts that actually exist. Claw tooling
15
+ // lives in claw/scripts/ (shipped as source); prefer a compiled sibling when
16
+ // present, otherwise fall back to the .ts source run through tsx.
16
17
  function resolveScriptInvocation(repoRoot: string, name: string) {
17
- const jsPath = path.join(repoRoot, 'scripts', `${name}.js`);
18
+ const jsPath = path.join(repoRoot, 'claw', 'scripts', `${name}.js`);
18
19
  if (storage.exists(jsPath)) {
19
20
  return { command: 'node', script: jsPath };
20
21
  }
21
- return { command: 'npx tsx', script: path.join(repoRoot, 'scripts', `${name}.ts`) };
22
+ return { command: 'npx tsx', script: path.join(repoRoot, 'claw', 'scripts', `${name}.ts`) };
22
23
  }
23
24
 
24
25
  function buildBridgeInvocation(repoRoot: string, profileRoot: string, command: string, extraArgs: any[] = []) {
@@ -208,7 +209,7 @@ function buildRuntimeSetup(runtime: any, repoRoot: string, profileRoot: string)
208
209
  'Start the memU MCP server:',
209
210
  '',
210
211
  '```bash',
211
- `tsx ${path.join(repoRoot, 'scripts', 'memu_mcp_server.ts').replace(/\\/g, '/')} --memu-dir ${PATHS.CLAW.MEMU_DIR.replace(/\\/g, '/')}`,
212
+ `tsx ${path.join(repoRoot, 'claw', 'scripts', 'memu_mcp_server.ts').replace(/\\/g, '/')} --memu-dir ${PATHS.CLAW.MEMU_DIR.replace(/\\/g, '/')}`,
212
213
  '```',
213
214
  '',
214
215
  'Or use the npm script:',
@@ -236,20 +237,17 @@ function buildRuntimeSetup(runtime: any, repoRoot: string, profileRoot: string)
236
237
  }
237
238
 
238
239
  function buildRuntimeWorkflow(runtime: any) {
239
- if (runtime.runtime === 'hermes') {
240
- return [
241
- '- Start with `claw_manifest`, `claw_runtime`, `claw_profile_context`, `claw_market_snapshot`, `claw_account_snapshot`, or `claw_open_orders`.',
242
- '- For MPA and short workflows, use `claw_build_open_short_plan`, `claw_build_take_profit_plan`, or `claw_build_close_short_plan` before executing trades.',
243
- '- Use `claw_honest_context`, `claw_honest_pair`, and `claw_honest_price` when the task involves HONEST assets or discovery.',
244
- '- The shared Claw MCP server registers raw tool ids such as `claw_manifest`; if Hermes shows a namespaced label in its UI, follow the label shown there.'
245
- ].join('\n');
246
- }
247
-
248
- return [
240
+ const baseLines = [
249
241
  '- Start with `claw_manifest`, `claw_runtime`, `claw_profile_context`, `claw_market_snapshot`, `claw_account_snapshot`, or `claw_open_orders`.',
250
242
  '- For MPA and short workflows, use `claw_build_open_short_plan`, `claw_build_take_profit_plan`, or `claw_build_close_short_plan` before executing trades.',
251
243
  '- Use `claw_honest_context`, `claw_honest_pair`, and `claw_honest_price` when the task involves HONEST assets or discovery.'
252
- ].join('\n');
244
+ ];
245
+
246
+ if (runtime.runtime === 'hermes') {
247
+ baseLines.push('- The shared Claw MCP server registers raw tool ids such as `claw_manifest`; if Hermes shows a namespaced label in its UI, follow the label shown there.');
248
+ }
249
+
250
+ return baseLines.join('\n');
253
251
  }
254
252
 
255
253
  function buildRuntimeSkillToml(runtime: any, repoRoot: string, profileRoot: string) {
@@ -24,7 +24,7 @@ function createCreditRuntimeAdapter(infra: any, options: Record<string, any> = {
24
24
  assetA: botEntry.assetA,
25
25
  assetB: botEntry.assetB,
26
26
  },
27
- _log: (msg: string, level?: string) => {
27
+ _log: (msg: string) => {
28
28
  const logger = infra.runtime?.logger || console;
29
29
  if (typeof logger.info === 'function') logger.info(`[credit-runtime] ${msg}`);
30
30
  else logger.log(`[credit-runtime] ${msg}`);
@@ -100,10 +100,7 @@ function createCreditRuntimeAdapter(infra: any, options: Record<string, any> = {
100
100
  const rt = await _getRuntime(botRef);
101
101
  if (!rt) {
102
102
  try {
103
- const bundle = await infra.profiles.loadBundle();
104
- const bot = bundle.bots.find(
105
- (b: Record<string, any>) => b.botKey === botRef || b.name === botRef,
106
- );
103
+ const bot = await _resolveBotEntry(botRef);
107
104
  if (!bot) return { error: `bot not found: ${botRef}` };
108
105
  if (!bot.debtPolicy) return { error: `bot ${botRef} has no debtPolicy configured` };
109
106
  return { error: `unable to initialize credit runtime for ${botRef}` };
@@ -142,19 +139,6 @@ function createCreditRuntimeAdapter(infra: any, options: Record<string, any> = {
142
139
  _ensureSigningKey(rt, privateKey);
143
140
  return rt.processPendingReborrows();
144
141
  },
145
-
146
- listRuntimes(): any[] {
147
- return Array.from(_runtimes.entries())
148
- .filter(([_, rt]) => rt.isEnabled())
149
- .map(([key, rt]) => ({
150
- botKey: key,
151
- enabled: rt.isEnabled(),
152
- }));
153
- },
154
-
155
- getRuntime(botRef: string): any | null {
156
- return _runtimes.get(botRef) || null;
157
- },
158
142
  };
159
143
  }
160
144
 
@@ -186,6 +186,10 @@ function buildSummary(assessments: Array<Record<string, any>>) {
186
186
  function resetAnalyzers() {
187
187
  analyzers.clear();
188
188
  analyzerConfigs.clear();
189
+ // Premiums belong to the analyzer generation that produced them; keeping
190
+ // them across a reset would let the reuse path report a stale value from
191
+ // discarded config.
192
+ marketPremiums.clear();
189
193
  }
190
194
 
191
195
  export { evaluate, getOrCreateAnalyzer, resetAnalyzers }
@@ -78,5 +78,5 @@ function loadDexbotOrderSystemUtils() {
78
78
  return requireDexbot2Module('modules/order/utils/system');
79
79
  }
80
80
 
81
- export { getDexbot2Root, loadDexbotOrderConstants, loadDexbotOrderSubsystem, loadDexbotOrderSystemUtils, loadDexbotOrderUtils, requireDexbot2Module, resolveDexbot2Path }
81
+ export { getDexbot2Root, loadDexbotOrderConstants, loadDexbotOrderSubsystem, loadDexbotOrderSystemUtils, loadDexbotOrderUtils, requireDexbot2Module }
82
82
 
@@ -12,7 +12,7 @@ import { clone } from './utils.js';
12
12
  import { createBotKey, sanitizeKey } from '../../modules/account_orders.js';
13
13
  const storage = getStorage();
14
14
 
15
- import type { BotSettings, ProfileOptions, Logger, ClawProfileBundle } from './types.js';
15
+ import type { BotSettings, ProfileOptions, ClawProfileBundle } from './types.js';
16
16
  import { getErrorMessage } from '../../modules/utils/errors.js';
17
17
 
18
18
  const DEFAULT_MANIFEST_FILE = 'config.json';
@@ -661,7 +661,7 @@ async function normalizeBotEntries(rawEntries: Record<string, any>[], options: P
661
661
  if (logger) {
662
662
  validateBotEntry(entry, index, logger);
663
663
  }
664
- const normalized = { active: entry.active === undefined ? true : !!entry.active, ...entry };
664
+ const normalized = { ...entry, active: entry.active === undefined ? true : !!entry.active };
665
665
  results.push({ ...normalized, botIndex: index, botKey: createBotKey(normalized, index) });
666
666
  }
667
667
  return results;
@@ -706,7 +706,9 @@ function resolveProfilesDir(profileRoot: any) {
706
706
  candidates.push(path.join(envRoot, 'profiles'));
707
707
  }
708
708
 
709
- if (Config.CWD) candidates.push(path.resolve(Config.CWD, 'profiles'));
709
+ // No bare CWD/profiles candidate here: an existing home config is
710
+ // authoritative (matching modules/paths.ts), and legacy cwd profiles are
711
+ // handled by the central resolver's migration logic below.
710
712
 
711
713
  for (const candidate of candidates) {
712
714
  if (isFileLike(candidate)) {
@@ -1006,8 +1008,8 @@ async function loadDexbotProfileBundle(profileRoot: string | null, options: Part
1006
1008
  * The adapter wraps bundle loading, settings validation, and atomic writes behind
1007
1009
  * per-file locks so concurrent updates do not clobber each other.
1008
1010
  *
1009
- * @returns {Object} Adapter with loadBundle, listBots, findBot, getBotBundle,
1010
- * getBotSettings, previewBotSettingsUpdate, applyBotSettingsPatch, getProfilesDir
1011
+ * @returns {Object} Adapter with loadBundle, getBotSettings,
1012
+ * previewBotSettingsUpdate, applyBotSettingsPatch, updateBotSettings, getClawProfileContext
1011
1013
  */
1012
1014
  function createDexbotProfileAdapter(profileRoot: string | null, options: Partial<ProfileOptions> = {}) {
1013
1015
  let cachedBundle: any = null;
@@ -1023,16 +1025,6 @@ function createDexbotProfileAdapter(profileRoot: string | null, options: Partial
1023
1025
  return resolveProfilesDir(profileRoot || options.profileRoot);
1024
1026
  }
1025
1027
 
1026
- async function listBots({ activeOnly = false, forceReload = false } = {}) {
1027
- const bundle = await loadBundle(forceReload);
1028
- return activeOnly ? bundle.activeBots : bundle.bots;
1029
- }
1030
-
1031
- async function findBot(identifier: any, forceReload = false) {
1032
- const bundle = await loadBundle(forceReload);
1033
- return bundle.bots.find((bot: any) => matchBotIdentifier(bot, identifier)) || null;
1034
- }
1035
-
1036
1028
  async function getBotBundle(identifier: any, forceReload = false) {
1037
1029
  const bundle = await loadBundle(forceReload);
1038
1030
  const bot = bundle.bots.find((entry: any) => matchBotIdentifier(entry, identifier)) || null;
@@ -1270,20 +1262,14 @@ function createDexbotProfileAdapter(profileRoot: string | null, options: Partial
1270
1262
  }
1271
1263
 
1272
1264
  return {
1273
- buildClawProfileContext: (bundle: any, contextOptions = {}) => buildClawProfileContext(bundle, contextOptions),
1274
1265
  applyBotSettingsPatch,
1275
- findBot,
1276
- getBotBundle,
1277
1266
  getBotSettings,
1278
1267
  getClawProfileContext,
1279
- getProfilesDir,
1280
- listBots,
1281
1268
  loadBundle,
1282
1269
  previewBotSettingsUpdate,
1283
- resolveProfilesDir: () => resolveProfilesDir(profileRoot || options.profileRoot),
1284
1270
  updateBotSettings
1285
1271
  };
1286
1272
  }
1287
1273
 
1288
- export { buildBotSettingsView, createBotKey, createDexbotProfileAdapter, buildClawProfileContext, describeBotSettingMutability, loadDexbotProfileBundle, matchBotIdentifier, normalizeBotSettings, normalizeBotEntries, readTriggerFile, resolveProfilesDir, resolveRawBotEntries, sanitizeKey, validateBotEntry, validateBotSettingsPatch, validateBotSettingsState, writeJsonFileAtomic }
1274
+ export { createBotKey, createDexbotProfileAdapter, matchBotIdentifier, normalizeBotEntries, resolveProfilesDir, resolveRawBotEntries, validateBotEntry, writeJsonFileAtomic }
1289
1275
 
@@ -88,7 +88,11 @@ async function fetchLivePoolReserves(poolId: string = HARDCODED_POOL_ID) {
88
88
  };
89
89
  _poolReservesCache = { poolId, ts: Date.now(), value: result };
90
90
  return result;
91
- } catch {
91
+ } catch (err: any) {
92
+ // Never cache failures, but surface them: silently serving the hardcoded
93
+ // fallback snapshot hides a degraded node and produces confidently-wrong
94
+ // bridge prices with no telemetry trail.
95
+ console.warn(`[honest-ecosystem] live pool reserves fetch failed for ${poolId}, using hardcoded fallback: ${err?.message || err}`);
92
96
  return null;
93
97
  }
94
98
  }
@@ -217,10 +221,15 @@ async function resolveHonestPairContext(assetA: any, assetB: any, options: Recor
217
221
  };
218
222
  }
219
223
 
220
- async function loadHonestAssets({ prefix = DEFAULT_PREFIX, batchSize = 100, maxPages = 100, startSymbol = DEFAULT_PREFIX }: Record<string, any> = {}) {
221
- const all = [];
224
+ /**
225
+ * Paginate list_assets with the shared dedup/boundary rules used across the
226
+ * HONEST tooling. `onPage` receives each de-duplicated page and accumulates
227
+ * whatever it needs; returning `false` stops pagination early (e.g. crossing
228
+ * a prefix boundary).
229
+ */
230
+ async function paginateListAssets({ batchSize = 100, maxPages = 100, startSymbol = '' }: Record<string, any> = {}, onPage: (pageItems: any[], batch: any[]) => boolean | void) {
222
231
  let lowerBound = startSymbol;
223
- let previousLastSymbol = null;
232
+ let previousLastSymbol: string | null = null;
224
233
 
225
234
  for (let page = 0; page < maxPages; page += 1) {
226
235
  const batch = await listAssets(lowerBound, batchSize);
@@ -237,17 +246,24 @@ async function loadHonestAssets({ prefix = DEFAULT_PREFIX, batchSize = 100, maxP
237
246
  break;
238
247
  }
239
248
 
240
- const matching = pageItems.filter((asset) => isHonestAsset(asset) && asset.symbol.startsWith(prefix));
241
- all.push(...matching);
249
+ const keepGoing = await onPage(pageItems, batch);
242
250
 
243
251
  previousLastSymbol = pageItems[pageItems.length - 1].symbol;
244
252
  lowerBound = previousLastSymbol;
245
253
 
246
- if (batch.length < batchSize) {
254
+ if (keepGoing === false || batch.length < batchSize) {
247
255
  break;
248
256
  }
249
257
  }
258
+ }
250
259
 
260
+ async function loadHonestAssets({ prefix = DEFAULT_PREFIX, batchSize = 100, maxPages = 100, startSymbol = DEFAULT_PREFIX }: Record<string, any> = {}) {
261
+ const all: any[] = [];
262
+
263
+ await paginateListAssets({ batchSize, maxPages, startSymbol }, (pageItems) => {
264
+ const matching = pageItems.filter((asset) => isHonestAsset(asset) && asset.symbol.startsWith(prefix));
265
+ all.push(...matching);
266
+ });
251
267
  const mpas = [];
252
268
  for (const asset of all) {
253
269
  if (!isMpa(asset)) {
@@ -357,5 +373,5 @@ function createHonestEcosystemAdapter(options: Record<string, any> = {}) {
357
373
  };
358
374
  }
359
375
 
360
- export { CORE_SYMBOL, DEFAULT_PREFIX, REFERENCE_SYMBOL, buildHonestEcosystemContext, createHonestEcosystemAdapter, getHardcodedHonestMoneyBridge, loadHonestAssets, isHardcodedHonestMoneyBtsPair, resolveHardcodedHonestMoneyPrice, resolveHonestPairContext, resolveHonestPairPrice }
376
+ export { buildHonestEcosystemContext, createHonestEcosystemAdapter, getHardcodedHonestMoneyBridge, getHonestMoneyBridge, isMpa, loadHonestAssets, paginateListAssets, resolveHardcodedHonestMoneyPrice, resolveHonestPairContext, resolveHonestPairPrice }
361
377
 
@@ -44,8 +44,10 @@ function normalizeRoot(options: Record<string, any> = {}) {
44
44
  if (parent === candidate) break;
45
45
  candidate = parent;
46
46
  }
47
- // Fall back to one level up (original behavior)
48
- return path.dirname(resolved);
47
+ // No code root found above the profile dir (e.g. a home config like
48
+ // ~/.config/dexbot2/profiles). Spawn from the code location actually
49
+ // running this launcher instead of guessing an unrelated ancestor.
50
+ return DEFAULT_ROOT;
49
51
  }
50
52
  return DEFAULT_ROOT;
51
53
  }
@@ -1,7 +1,7 @@
1
1
 
2
2
 
3
3
  import * as client from './bitshares_client.js';
4
- import { getDexbot2Root, loadDexbotOrderSystemUtils, requireDexbot2Module } from './dexbot_bridge.js';
4
+ import { loadDexbotOrderSystemUtils, requireDexbot2Module } from './dexbot_bridge.js';
5
5
  function getDexbotSystem() {
6
6
  return loadDexbotOrderSystemUtils();
7
7
  }
@@ -13,9 +13,16 @@ function derivePoolPrice(assetA: any, assetB: any, poolRef?: string | null | Rec
13
13
  try {
14
14
  const { withPoolRef: wrapWithPoolRef } = requireDexbot2Module('modules/order/utils/withPoolRef') as any;
15
15
  const override = wrapWithPoolRef(client.BitShares, resolvedPoolRef);
16
- if (override) return override.derivePoolPrice(assetA, assetB);
16
+ // The caller pinned a specific pool: honoring the pin or failing is
17
+ // correct, silently deriving from a different auto-selected pool is not.
18
+ if (!override) {
19
+ console.warn(`[liquidity-pools] derivePoolPrice could not pin pool ${resolvedPoolRef}`);
20
+ return null;
21
+ }
22
+ return override.derivePoolPrice(assetA, assetB);
17
23
  } catch (e: any) {
18
24
  console.warn(`[liquidity-pools] derivePoolPrice with poolRef failed: ${e?.message || e}`);
25
+ return null;
19
26
  }
20
27
  }
21
28
  return system.derivePoolPrice(client.BitShares, assetA, assetB);
@@ -47,5 +54,5 @@ function createDexbotPoolHelper() {
47
54
  };
48
55
  }
49
56
 
50
- export { derivePoolPrice, derivePrice, createDexbotPoolHelper, getDexbot2Root, requireDexbot2Module }
57
+ export { derivePoolPrice, derivePrice, createDexbotPoolHelper }
51
58
 
@@ -43,6 +43,106 @@ export function failure(id: any, code: any, message: any, data = undefined) {
43
43
  });
44
44
  }
45
45
 
46
+ /**
47
+ * Build an Error that createJsonRpcToolsHandler maps to a JSON-RPC error
48
+ * response with the given code instead of the isError:true result convention.
49
+ * Use -32602 for caller-input problems (invalid params, unknown tool).
50
+ */
51
+ export function jsonRpcError(code: number, message: string): Error & { statusCode: number } {
52
+ const err = new Error(message) as Error & { statusCode: number };
53
+ err.statusCode = code;
54
+ return err;
55
+ }
56
+
57
+ /**
58
+ * Shared JSON-RPC request shell for the claw/memu stdio servers: initialize
59
+ * handshake (echoing the client's protocolVersion), notifications/initialized,
60
+ * ping, tools/list (internal failures map to -32603), tools/call delegation,
61
+ * and method-not-found. `callTool(params, defaults)` returns the result value
62
+ * for a successful call; thrown Errors carrying a numeric `statusCode`
63
+ * become JSON-RPC errors, everything else becomes an isError:true result.
64
+ */
65
+ export function createJsonRpcToolsHandler(options: {
66
+ serverName: string;
67
+ serverVersion?: string;
68
+ listTools: () => any[] | Promise<any[]>;
69
+ callTool: (params: any, defaults: any) => Promise<any>;
70
+ }) {
71
+ const { serverName, listTools, callTool } = options;
72
+ const serverVersion = options.serverVersion || '0.1.0';
73
+
74
+ return async function handleRequest(message: any, defaults: any) {
75
+ const { id, method, params } = message;
76
+
77
+ switch (method) {
78
+ case 'initialize':
79
+ return success(id, {
80
+ // Echo the client's requested protocol version when provided, so a
81
+ // JSONL-speaking client can negotiate its own version.
82
+ protocolVersion: params?.protocolVersion || '2024-11-05',
83
+ capabilities: {
84
+ tools: {
85
+ listChanged: false
86
+ }
87
+ },
88
+ serverInfo: {
89
+ name: serverName,
90
+ version: serverVersion
91
+ }
92
+ });
93
+
94
+ case 'notifications/initialized':
95
+ return;
96
+
97
+ case 'ping':
98
+ return success(id, {});
99
+
100
+ case 'tools/list':
101
+ try {
102
+ return success(id, {
103
+ tools: await listTools()
104
+ });
105
+ } catch (error: any) {
106
+ // Catalog load failure is a server-side problem, not bad input.
107
+ return failure(id, -32603, `Failed to load tool catalog: ${error && error.message ? error.message : String(error)}`);
108
+ }
109
+
110
+ case 'tools/call': {
111
+ try {
112
+ const result = await callTool(params, defaults);
113
+ return success(id, {
114
+ content: [
115
+ {
116
+ type: 'text',
117
+ text: JSON.stringify(result, null, 2)
118
+ }
119
+ ],
120
+ structuredContent: result
121
+ });
122
+ } catch (error: any) {
123
+ if (error && typeof error.statusCode === 'number') {
124
+ return failure(id, error.statusCode, error.message);
125
+ }
126
+ return success(id, {
127
+ content: [
128
+ {
129
+ type: 'text',
130
+ text: error && error.stack ? error.stack : String(error)
131
+ }
132
+ ],
133
+ isError: true
134
+ });
135
+ }
136
+ }
137
+
138
+ default:
139
+ if (id !== undefined) {
140
+ return failure(id, -32601, `Method not found: ${method}`);
141
+ }
142
+ }
143
+ };
144
+ }
145
+
46
146
  export function createMessageParser(onMessage: any, onDrain?: () => void) {
47
147
  if (!hasProcess()) {
48
148
  throw new Error('MCP stdio transport not available in this environment');
@@ -128,6 +228,7 @@ export async function runMcpServer(parseArgs: (argv: string[]) => Record<string,
128
228
  }
129
229
  });
130
230
  let lastQueue = Promise.resolve();
231
+ let finishInput: () => void = () => {};
131
232
 
132
233
  runtime.stdin!.on('data', (chunk) => {
133
234
  lastQueue = parser.push(chunk);
@@ -138,10 +239,18 @@ export async function runMcpServer(parseArgs: (argv: string[]) => Record<string,
138
239
  runtime.stdin!.pause();
139
240
  }
140
241
  });
242
+ // Without an 'error' listener an EPIPE/EIO on stdin emits an unhandled
243
+ // 'error' event and crashes the MCP server mid-session. Treat it as EOF.
244
+ runtime.stdin!.on('error', (err: any) => {
245
+ runtime.stderr.write(`[mcp] stdin error: ${err && err.stack ? err.stack : String(err)}\n`);
246
+ // The 'end' event never fires after a stream error; unblock the wait.
247
+ finishInput();
248
+ });
141
249
  runtime.stdin!.resume();
142
250
 
143
251
  await new Promise<void>((resolve) => {
144
252
  runtime.stdin!.on('end', () => resolve());
253
+ finishInput = resolve;
145
254
  });
146
255
  await lastQueue;
147
256
  }