dexbot 1.6.15 → 1.6.16

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 (102) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +4 -4
  3. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  4. package/claw/modules/chain_queries.ts +3 -3
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  9. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  10. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  11. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  12. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  13. package/dist/analysis/bot_key_utils.js +9 -7
  14. package/dist/analysis/chart_utils.d.ts +9 -2
  15. package/dist/analysis/chart_utils.js +51 -1
  16. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  17. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +19 -5
  18. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +21 -2
  19. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  20. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  21. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  22. package/dist/dexbot.js +89 -138
  23. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  24. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  25. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  26. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  27. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  28. package/dist/market_adapter/inputs/window_cache.js +53 -17
  29. package/dist/market_adapter/lp_chart_core.js +1 -0
  30. package/dist/market_adapter/utils/chain.js +4 -3
  31. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  32. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  33. package/dist/modules/account_bots.d.ts +37 -3
  34. package/dist/modules/account_bots.js +77 -37
  35. package/dist/modules/account_orders.d.ts +4 -1
  36. package/dist/modules/account_orders.js +4 -1
  37. package/dist/modules/bitshares-native/resolvers.js +3 -3
  38. package/dist/modules/bitshares_client.d.ts +12 -10
  39. package/dist/modules/bitshares_client.js +12 -10
  40. package/dist/modules/bot_settings.js +3 -3
  41. package/dist/modules/chain_keys.d.ts +5 -1
  42. package/dist/modules/chain_keys.js +5 -1
  43. package/dist/modules/chain_orders.d.ts +6 -2
  44. package/dist/modules/chain_orders.js +6 -2
  45. package/dist/modules/constants.d.ts +5 -0
  46. package/dist/modules/constants.js +7 -1
  47. package/dist/modules/dexbot_class.d.ts +3 -1
  48. package/dist/modules/dexbot_class.js +3 -1
  49. package/dist/modules/graceful_shutdown.d.ts +6 -2
  50. package/dist/modules/graceful_shutdown.js +6 -2
  51. package/dist/modules/launcher/bot_supervisor.js +4 -0
  52. package/dist/modules/launcher/launch_modes.js +6 -3
  53. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  54. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  55. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  56. package/dist/modules/launcher/runtime_mode.js +223 -0
  57. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  58. package/dist/modules/market_adapter_whitelist.js +8 -0
  59. package/dist/modules/order/accounting.d.ts +15 -1
  60. package/dist/modules/order/accounting.js +15 -1
  61. package/dist/modules/order/async_lock.d.ts +9 -3
  62. package/dist/modules/order/async_lock.js +9 -3
  63. package/dist/modules/order/export.d.ts +0 -5
  64. package/dist/modules/order/export.js +0 -5
  65. package/dist/modules/order/format.d.ts +6 -4
  66. package/dist/modules/order/format.js +6 -4
  67. package/dist/modules/order/grid.d.ts +29 -18
  68. package/dist/modules/order/grid.js +29 -18
  69. package/dist/modules/order/index.d.ts +1 -1
  70. package/dist/modules/order/index.js +1 -1
  71. package/dist/modules/order/logger_state.d.ts +1 -1
  72. package/dist/modules/order/logger_state.js +1 -1
  73. package/dist/modules/order/sync_engine.d.ts +26 -11
  74. package/dist/modules/order/sync_engine.js +26 -11
  75. package/dist/modules/order/utils/math.d.ts +59 -21
  76. package/dist/modules/order/utils/math.js +59 -21
  77. package/dist/modules/order/utils/order.d.ts +64 -20
  78. package/dist/modules/order/utils/order.js +64 -20
  79. package/dist/modules/order/utils/system.d.ts +41 -11
  80. package/dist/modules/order/utils/system.js +41 -11
  81. package/dist/modules/order/utils/validate.d.ts +5 -2
  82. package/dist/modules/order/utils/validate.js +5 -2
  83. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  84. package/dist/modules/utils/asset_symbols.js +5 -5
  85. package/dist/modules/utils/errors.d.ts +2 -1
  86. package/dist/modules/utils/errors.js +2 -1
  87. package/dist/scripts/rich_list.d.ts +32 -0
  88. package/dist/scripts/rich_list.js +16 -8
  89. package/dist/unlock.js +49 -18
  90. package/docs/BITSHARES_ONBOARDING.md +7 -0
  91. package/docs/COW_INVARIANTS.md +1 -1
  92. package/docs/DEXBOT_COMPARISON.md +5 -5
  93. package/docs/EVOLUTION.md +8 -7
  94. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  95. package/docs/GRID_RECALCULATION.md +18 -6
  96. package/docs/LIFECYCLE.md +8 -8
  97. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +4 -4
  98. package/docs/README.md +1 -1
  99. package/docs/WORKFLOW.md +5 -5
  100. package/market_adapter/README.md +10 -3
  101. package/package.json +3 -1
  102. package/tests/README.md +29 -0
@@ -105,6 +105,7 @@
105
105
  * 17. COW_PERFORMANCE - Copy-on-write grid performance settings
106
106
  * 18. REBALANCE_STATES - Rebalance lifecycle state enum
107
107
  * 19. COW_ACTIONS - Copy-on-write action type enum
108
+ * COW_ORIGINS - Copy-on-write action origin/source enum
108
109
  * 20. CR_ZONES - Credit ratio zone constants
109
110
  * 21. DEFAULT_TARGET_CR - Default target collateral ratio
110
111
  * 22. NATIVE_CLIENT - Native blockchain client configuration
@@ -114,6 +115,10 @@
114
115
  * 26. DAEMON_ERRORS - Credential daemon error codes
115
116
  * 27. DAEMON_CODES - Credential daemon codes
116
117
  * 28. CREDENTIAL_PROMPTS - Credential prompt configuration
118
+ * 29. RANGE_QUALITY - Bot-editor pre-entry price-range legend thresholds
119
+ * 30. buildDefaultGeneralSettings() - Build the canonical default
120
+ * general.settings.json document (first-run seed, editor fallback,
121
+ * and local-overrides merge all share it)
117
122
  *
118
123
  * ===============================================================================
119
124
  *
@@ -106,6 +106,7 @@
106
106
  * 17. COW_PERFORMANCE - Copy-on-write grid performance settings
107
107
  * 18. REBALANCE_STATES - Rebalance lifecycle state enum
108
108
  * 19. COW_ACTIONS - Copy-on-write action type enum
109
+ * COW_ORIGINS - Copy-on-write action origin/source enum
109
110
  * 20. CR_ZONES - Credit ratio zone constants
110
111
  * 21. DEFAULT_TARGET_CR - Default target collateral ratio
111
112
  * 22. NATIVE_CLIENT - Native blockchain client configuration
@@ -115,6 +116,10 @@
115
116
  * 26. DAEMON_ERRORS - Credential daemon error codes
116
117
  * 27. DAEMON_CODES - Credential daemon codes
117
118
  * 28. CREDENTIAL_PROMPTS - Credential prompt configuration
119
+ * 29. RANGE_QUALITY - Bot-editor pre-entry price-range legend thresholds
120
+ * 30. buildDefaultGeneralSettings() - Build the canonical default
121
+ * general.settings.json document (first-run seed, editor fallback,
122
+ * and local-overrides merge all share it)
118
123
  *
119
124
  * ===============================================================================
120
125
  *
@@ -1171,7 +1176,8 @@ let MARKET_ADAPTER = {
1171
1176
  // nob: nz% (Neutral Zone %)
1172
1177
  DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT: 0,
1173
1178
  // DYNAMIC_WEIGHT_AMA_HUBER: Single source of truth for the canonical AMA-slope
1174
- // estimator (computeHuberWindowSlopePct in strategy/dynamic_weight_series.ts).
1179
+ // estimator (computeHuberWindowSlopePct in
1180
+ // market_adapter/core/strategies/dynamic_weight_series.ts).
1175
1181
  // Every consumer — live market adapter, grid-reset replay, bot-fitting
1176
1182
  // backtests, both browser-embedded research charts — reads these values:
1177
1183
  // Node callers via the module import, generated HTML via an injected
@@ -45,7 +45,9 @@
45
45
  * ===============================================================================
46
46
  *
47
47
  * HELPER FUNCTIONS (module-level):
48
- * - normalizeBotEntry() - Normalize bot configuration object
48
+ * - shouldCoalesceBacklogReplay(config, managerConfig) - Decide whether a
49
+ * startup backlog should be drained as one coalesced batch
50
+ * (bot-entry normalization lives in bot_settings.ts: normalizeBotEntry)
49
51
  *
50
52
  * ===============================================================================
51
53
  *
@@ -45,7 +45,9 @@
45
45
  * ===============================================================================
46
46
  *
47
47
  * HELPER FUNCTIONS (module-level):
48
- * - normalizeBotEntry() - Normalize bot configuration object
48
+ * - shouldCoalesceBacklogReplay(config, managerConfig) - Decide whether a
49
+ * startup backlog should be drained as one coalesced batch
50
+ * (bot-entry normalization lives in bot_settings.ts: normalizeBotEntry)
49
51
  *
50
52
  * ===============================================================================
51
53
  *
@@ -11,7 +11,7 @@
11
11
  * - Detailed shutdown logging
12
12
  *
13
13
  * ===============================================================================
14
- * EXPORTS (3 functions)
14
+ * EXPORTS (4 functions)
15
15
  * ===============================================================================
16
16
  *
17
17
  * 1. registerCleanup(name, cleanupFn) - Register cleanup function
@@ -21,7 +21,11 @@
21
21
  *
22
22
  * 2. unregisterCleanup(name) - Unregister a previously registered cleanup
23
23
  *
24
- * 3. setupGracefulShutdown() - Install signal and exception handlers
24
+ * 3. registerExitWipe(name, wipeFn) - Register a synchronous wipe callback
25
+ * that runs AFTER all LIFO cleanups, right before process exit (e.g. a
26
+ * best-effort disk wipe); returns an unregister function
27
+ *
28
+ * 4. setupGracefulShutdown() - Install signal and exception handlers
25
29
  * Registers SIGTERM, SIGINT, uncaughtException, unhandledRejection handlers
26
30
  * Should be called once at process startup
27
31
  *
@@ -11,7 +11,7 @@
11
11
  * - Detailed shutdown logging
12
12
  *
13
13
  * ===============================================================================
14
- * EXPORTS (3 functions)
14
+ * EXPORTS (4 functions)
15
15
  * ===============================================================================
16
16
  *
17
17
  * 1. registerCleanup(name, cleanupFn) - Register cleanup function
@@ -21,7 +21,11 @@
21
21
  *
22
22
  * 2. unregisterCleanup(name) - Unregister a previously registered cleanup
23
23
  *
24
- * 3. setupGracefulShutdown() - Install signal and exception handlers
24
+ * 3. registerExitWipe(name, wipeFn) - Register a synchronous wipe callback
25
+ * that runs AFTER all LIFO cleanups, right before process exit (e.g. a
26
+ * best-effort disk wipe); returns an unregister function
27
+ *
28
+ * 4. setupGracefulShutdown() - Install signal and exception handlers
25
29
  * Registers SIGTERM, SIGINT, uncaughtException, unhandledRejection handlers
26
30
  * Should be called once at process startup
27
31
  *
@@ -681,6 +681,10 @@ function createBotSupervisor({ bots = null, buildEnv = buildScopedChildEnv, spaw
681
681
  await restartAll({ logAction: 'reload-all' });
682
682
  return { ok: true };
683
683
  case 'delete':
684
+ // delete tears the supervisor down as a whole; a bot target
685
+ // would silently kill every bot, so refuse it explicitly.
686
+ if (cmd.bot)
687
+ return { error: `'delete' is whole-runtime; use 'stop ${cmd.bot}' to stop one bot` };
684
688
  await shutdown({ preserveSockets: cmd.preserveSockets || [] });
685
689
  return { ok: true };
686
690
  default:
@@ -52,10 +52,13 @@ function parseUnlockArgs(argv = process.argv) {
52
52
  let cmd = positionalArgs[0];
53
53
  const target = positionalArgs[1] || null;
54
54
  // Normalize whole-runtime controls: restart/reload/stop (no target or 'all') → *-all
55
- // reload mirrors restart but skips the credential daemon re-unlock.
56
- const consumedAll = (cmd === 'restart' || cmd === 'reload' || cmd === 'stop') && (!target || target === 'all');
55
+ // and delete (no target or 'all') → delete. reload mirrors restart but
56
+ // skips the credential daemon re-unlock.
57
+ const wholeRuntime = cmd === 'restart' || cmd === 'reload' || cmd === 'stop' || cmd === 'delete';
58
+ const consumedAll = wholeRuntime && (!target || target === 'all');
57
59
  if (consumedAll) {
58
- cmd += '-all';
60
+ if (cmd !== 'delete')
61
+ cmd += '-all';
59
62
  }
60
63
  return {
61
64
  botName: null,
@@ -51,7 +51,45 @@ declare function listConfiguredBots(botsFile?: string): Array<{
51
51
  declare function getActiveAmaBotFingerprint(botsFile?: string): string;
52
52
  declare function getControlBotNames(target: string | null | undefined, wholeRuntime?: boolean): string[];
53
53
  declare function getControlActionLabel(cmd: string): "shutting down" | "restarting" | "reloading" | "stopping";
54
+ /**
55
+ * Decide the effective `(cmd, target)` for a runtime control request.
56
+ *
57
+ * `all` always selects the whole runtime. A per-bot target exists only under
58
+ * the isolated supervisor: a live monolithic runtime runs every active bot in
59
+ * one worker, so a target cannot select a single bot and the request degrades
60
+ * to the whole-runtime command. `delete` is whole-runtime on every surface and
61
+ * rejects a bot target; `status` is whole-runtime and ignores one.
62
+ *
63
+ * Pure, so the routing contract is unit-testable without a live runtime.
64
+ */
65
+ interface ControlRouting {
66
+ /** Canonical command to dispatch. */
67
+ cmd: string;
68
+ /** Target to act on (null for a whole-runtime action). */
69
+ target: string | null;
70
+ /** The normalized target the user asked for, before any fold (for validation). */
71
+ requestedTarget: string | null;
72
+ /** True when a requested target was dropped into a whole-runtime action. */
73
+ folded: boolean;
74
+ /** Informational message to print when a target was folded. */
75
+ notice: string | null;
76
+ /** Error message when the request must be refused. */
77
+ reject: string | null;
78
+ }
79
+ /**
80
+ * Normalize a target selector: `all` (and empty) select the whole runtime;
81
+ * anything else is treated as a bot name. Single source of the alias rule.
82
+ */
83
+ declare function normalizeControlTarget(target?: string | null): string | null;
84
+ declare function botNotFoundMessage(name: string): string;
85
+ declare function statusIgnoresTargetMessage(name: string): string;
86
+ declare function resolveControlRouting({ cmd, target, monolithicLive }: {
87
+ cmd: string;
88
+ target?: string | null;
89
+ monolithicLive: boolean;
90
+ }): ControlRouting;
54
91
  declare function getControlServiceNames(cmd: string, botNames: string[]): string[];
55
92
  declare function printControlActionSummary(action: string, botNames: string[], serviceNames?: string[]): void;
56
- export { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, CREDENTIAL_READY_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, readProcStat, isProcessInDstate, stopCredentialDaemonPid, cleanupCredentialRuntimeFiles, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, readCredentialDaemonStatus, ensureLogDir, buildDexbotStartArgs, createUpdateScheduler, getActiveAmaBotFingerprint, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, printControlActionSummary, formatBotCount };
93
+ export { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, CREDENTIAL_READY_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, readProcStat, isProcessInDstate, stopCredentialDaemonPid, cleanupCredentialRuntimeFiles, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, readCredentialDaemonStatus, ensureLogDir, buildDexbotStartArgs, createUpdateScheduler, getActiveAmaBotFingerprint, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, resolveControlRouting, normalizeControlTarget, botNotFoundMessage, statusIgnoresTargetMessage, printControlActionSummary, formatBotCount };
94
+ export type { ControlRouting };
57
95
  //# sourceMappingURL=monolithic_runtime.d.ts.map
@@ -350,6 +350,65 @@ function getControlActionLabel(cmd) {
350
350
  return 'shutting down';
351
351
  return 'stopping';
352
352
  }
353
+ /**
354
+ * Normalize a target selector: `all` (and empty) select the whole runtime;
355
+ * anything else is treated as a bot name. Single source of the alias rule.
356
+ */
357
+ function normalizeControlTarget(target) {
358
+ return target === 'all' ? null : (target || null);
359
+ }
360
+ // Shared control/status text, built here so the same message cannot drift
361
+ // between the control router, the status validator and the status branch.
362
+ function botNotFoundMessage(name) {
363
+ return `Bot '${name}' not found in bots.json`;
364
+ }
365
+ function statusIgnoresTargetMessage(name) {
366
+ return `'status' is whole-runtime; ignoring target '${name}'.`;
367
+ }
368
+ function resolveControlRouting({ cmd, target, monolithicLive }) {
369
+ const baseCmd = cmd === 'shutdown' ? 'delete' : cmd === 'stat' ? 'status' : cmd;
370
+ const requestedTarget = normalizeControlTarget(target);
371
+ if (!requestedTarget) {
372
+ // Canonicalize the whole-runtime form so a caller that passes a bare
373
+ // `stop`/`restart`/`reload` still gets the `*-all` command the
374
+ // monolithic dispatch expects (the parser usually does this earlier).
375
+ const wholeCmd = (baseCmd === 'stop' || baseCmd === 'restart' || baseCmd === 'reload')
376
+ ? `${baseCmd}-all`
377
+ : baseCmd;
378
+ return { cmd: wholeCmd, target: null, requestedTarget: null, folded: false, notice: null, reject: null };
379
+ }
380
+ if (baseCmd === 'delete') {
381
+ return {
382
+ cmd: baseCmd,
383
+ target: null,
384
+ requestedTarget,
385
+ folded: true,
386
+ notice: null,
387
+ reject: `'delete' is a whole-runtime control and does not accept a bot name; use 'dexbot delete' or 'dexbot stop ${requestedTarget}'.`,
388
+ };
389
+ }
390
+ if (baseCmd === 'status') {
391
+ return {
392
+ cmd: baseCmd,
393
+ target: null,
394
+ requestedTarget,
395
+ folded: true,
396
+ notice: statusIgnoresTargetMessage(requestedTarget),
397
+ reject: null,
398
+ };
399
+ }
400
+ if (monolithicLive) {
401
+ return {
402
+ cmd: `${baseCmd}-all`,
403
+ target: null,
404
+ requestedTarget,
405
+ folded: true,
406
+ notice: `Monolithic runtime runs all active bots in one worker; '${baseCmd} ${requestedTarget}' applies to the whole runtime.`,
407
+ reject: null,
408
+ };
409
+ }
410
+ return { cmd: baseCmd, target: requestedTarget, requestedTarget, folded: false, notice: null, reject: null };
411
+ }
353
412
  function getControlServiceNames(cmd, botNames) {
354
413
  if (!['stop-all', 'restart-all', 'reload-all', 'delete', 'shutdown'].includes(cmd))
355
414
  return [];
@@ -378,5 +437,5 @@ function printControlActionSummary(action, botNames, serviceNames = []) {
378
437
  console.log('='.repeat(50));
379
438
  console.log();
380
439
  }
381
- export { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, CREDENTIAL_READY_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, readProcStat, isProcessInDstate, stopCredentialDaemonPid, cleanupCredentialRuntimeFiles, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, readCredentialDaemonStatus, ensureLogDir, buildDexbotStartArgs, createUpdateScheduler, getActiveAmaBotFingerprint, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, printControlActionSummary, formatBotCount };
440
+ export { MONOLITHIC_PID_FILE, MONOLITHIC_BOT_PID_FILE, MONOLITHIC_BOT_INFO_FILE, MONOLITHIC_CRED_PID_FILE, MONOLITHIC_OUT_LOG, MONOLITHIC_ERROR_LOG, CREDENTIAL_SOCKET_FILE, CREDENTIAL_READY_FILE, cleanupStateFiles, readLiveMonolithicPid, readMonolithicBotInfo, isLikelyCredentialDaemonProcess, isExpectedMonolithicBotPid, readProcStat, isProcessInDstate, stopCredentialDaemonPid, cleanupCredentialRuntimeFiles, stopCredentialDaemon, ensureNoForeignCredentialDaemon, findCredentialSocketOwnerPid, readCredentialDaemonStatus, ensureLogDir, buildDexbotStartArgs, createUpdateScheduler, getActiveAmaBotFingerprint, listConfiguredBots, getControlBotNames, getControlActionLabel, getControlServiceNames, resolveControlRouting, normalizeControlTarget, botNotFoundMessage, statusIgnoresTargetMessage, printControlActionSummary, formatBotCount };
382
441
  //# sourceMappingURL=monolithic_runtime.js.map
@@ -0,0 +1,79 @@
1
+ export type RuntimeMode = 'monolithic' | 'isolated' | 'pm2' | 'none';
2
+ export interface Pm2Proc {
3
+ pid?: number | string;
4
+ name?: string;
5
+ pm2_env?: {
6
+ pm_uptime?: unknown;
7
+ status?: string;
8
+ };
9
+ monit?: {
10
+ memory?: number;
11
+ };
12
+ [key: string]: unknown;
13
+ }
14
+ export interface RuntimeInfo {
15
+ mode: RuntimeMode;
16
+ /** Live monolithic wrapper PID, or 0. */
17
+ monolithicPid: number;
18
+ /** A supervised (isolated) supervisor socket is present. */
19
+ supervisorSocket: boolean;
20
+ /** The credential daemon is still alive (e.g. after a `stop`). */
21
+ credentialDaemonAlive: boolean;
22
+ /** Live credential-daemon PID (unlock mode), or 0. */
23
+ credentialDaemonPid: number;
24
+ /** Any unlock-mode process is up (monolithic, isolated, or cred daemon). */
25
+ unlockRunning: boolean;
26
+ /** DexBot PM2 processes; empty unless the unlock runtime is down. */
27
+ pm2Processes: Pm2Proc[];
28
+ }
29
+ /** True when `name` matches a configured bot (case-insensitive). */
30
+ export declare function isConfiguredBotName(name: string): boolean;
31
+ export interface StatusTargetCheck {
32
+ error: string | null;
33
+ notice: string | null;
34
+ }
35
+ /**
36
+ * Validate the optional bot name on `dexbot status`. status is whole-runtime
37
+ * on every surface, so a real name is announced-then-ignored and an unknown
38
+ * one is rejected — the same contract the unlock control path applies.
39
+ */
40
+ export declare function checkStatusTarget(target?: string | null): StatusTargetCheck;
41
+ export type StatusRoute = 'unlock' | 'pm2' | 'empty';
42
+ /**
43
+ * Which branch `dexbot status` takes. PM2 wins when PM2 bots are running (even
44
+ * if a stray credential daemon lingers) so the report and the help banner name
45
+ * the same runtime; otherwise a live unlock process is shown by delegating to
46
+ * `unlock status`. The cred-daemon-only case stays on the unlock route so the
47
+ * daemon is still reported.
48
+ */
49
+ export declare function resolveStatusRoute(info: RuntimeInfo): StatusRoute;
50
+ /**
51
+ * Parse `pm2 jlist` and keep only DEXBot2's own processes. Returns `[]` on any
52
+ * failure (pm2 missing, daemon down, malformed output) so callers can treat
53
+ * "no PM2" and "pm2 unavailable" the same way.
54
+ */
55
+ export declare function listDexbotPm2Processes(): Pm2Proc[];
56
+ /**
57
+ * Detect the active runtime and the supporting state the callers need.
58
+ * Monolithic wins over isolated if both markers linger; PM2 is probed last.
59
+ */
60
+ export declare function detectRuntimeMode(): RuntimeInfo;
61
+ /** Human label for the active-runtime banner. */
62
+ export declare const RUNTIME_MODE_LABELS: Record<RuntimeMode, string>;
63
+ /**
64
+ * Banner label for a detection result. `none` with a live credential daemon
65
+ * is called out so the banner agrees with `dexbot status` (which reports the
66
+ * daemon that outlived a `stop`).
67
+ */
68
+ export declare function runtimeModeLabel(info: RuntimeInfo): string;
69
+ export interface RuntimeHelpEntry {
70
+ command: string;
71
+ description: string;
72
+ }
73
+ /**
74
+ * The Runtime command group, phrased for the runtime that is actually up.
75
+ * `none` shows the standard monolithic runtime (the `dexbot start` default)
76
+ * so the reference is always complete before anything is running.
77
+ */
78
+ export declare function runtimeControlHelp(mode: RuntimeMode): RuntimeHelpEntry[];
79
+ //# sourceMappingURL=runtime_mode.d.ts.map
@@ -0,0 +1,223 @@
1
+ 'use strict';
2
+ /**
3
+ * Single source of truth for "which DEXBot2 runtime is running?".
4
+ *
5
+ * Used by `dexbot status` (delegate to `unlock status` vs render the PM2
6
+ * table) and by `dexbot help`/usage output (describe controls in terms of the
7
+ * active runtime). Keeping detection plus the mode→instructions mapping here
8
+ * stops the two entry points from drifting.
9
+ *
10
+ * Unlock-mode liveness is read from pid files/socket (cheap). PM2 is only
11
+ * probed when no unlock runtime is up, so a running monolithic/isolated bot
12
+ * never pays for a `pm2` round-trip.
13
+ *
14
+ * Limitation: the isolated verdict is an `exists()` check on the supervisor
15
+ * socket, so a leftover socket from a crashed supervisor still reads as
16
+ * isolated. A live-connect probe would be more accurate but must stay off the
17
+ * help/status hot path.
18
+ */
19
+ import { execSync } from 'node:child_process';
20
+ import { homedir } from 'node:os';
21
+ import { join } from 'node:path';
22
+ import { getStorage } from '../storage/index.js';
23
+ import { PATHS } from '../paths.js';
24
+ import { Config } from '../config.js';
25
+ import { loadSettingsFile, resolveRawBotEntries } from '../bot_settings.js';
26
+ import { isSameBotName } from '../utils/sanitize_key.js';
27
+ import { normalizeControlTarget, readLiveMonolithicPid, botNotFoundMessage, statusIgnoresTargetMessage } from './monolithic_runtime.js';
28
+ const storage = getStorage();
29
+ /** PM2 app names owned by DEXBot2 (bot names are added from bots.json). */
30
+ const PM2_SERVICE_NAMES = new Set(['dexbot-cred', 'dexbot-adapter', 'dexbot-update']);
31
+ function configuredBotNames() {
32
+ const names = new Set();
33
+ try {
34
+ const { config } = loadSettingsFile(PATHS.PROFILES.BOTS_JSON);
35
+ for (const b of resolveRawBotEntries(config)) {
36
+ if (b?.name)
37
+ names.add(String(b.name));
38
+ }
39
+ }
40
+ catch (_) { }
41
+ return names;
42
+ }
43
+ /** True when `name` matches a configured bot (case-insensitive). */
44
+ export function isConfiguredBotName(name) {
45
+ for (const configured of configuredBotNames()) {
46
+ if (isSameBotName(configured, name))
47
+ return true;
48
+ }
49
+ return false;
50
+ }
51
+ /**
52
+ * Validate the optional bot name on `dexbot status`. status is whole-runtime
53
+ * on every surface, so a real name is announced-then-ignored and an unknown
54
+ * one is rejected — the same contract the unlock control path applies.
55
+ */
56
+ export function checkStatusTarget(target) {
57
+ const requested = normalizeControlTarget(target);
58
+ if (!requested)
59
+ return { error: null, notice: null };
60
+ if (!isConfiguredBotName(requested)) {
61
+ return { error: botNotFoundMessage(requested), notice: null };
62
+ }
63
+ return { error: null, notice: statusIgnoresTargetMessage(requested) };
64
+ }
65
+ /**
66
+ * Which branch `dexbot status` takes. PM2 wins when PM2 bots are running (even
67
+ * if a stray credential daemon lingers) so the report and the help banner name
68
+ * the same runtime; otherwise a live unlock process is shown by delegating to
69
+ * `unlock status`. The cred-daemon-only case stays on the unlock route so the
70
+ * daemon is still reported.
71
+ */
72
+ export function resolveStatusRoute(info) {
73
+ if (info.pm2Processes.length > 0)
74
+ return 'pm2';
75
+ if (info.unlockRunning)
76
+ return 'unlock';
77
+ return 'empty';
78
+ }
79
+ function isPidAlive(pid) {
80
+ if (!Number.isInteger(pid) || pid <= 0)
81
+ return false;
82
+ try {
83
+ process.kill(pid, 0);
84
+ return true;
85
+ }
86
+ catch (err) {
87
+ // A live process owned by another user still exists (EACCES).
88
+ return err?.code === 'EACCES';
89
+ }
90
+ }
91
+ /**
92
+ * Whether a PM2 daemon looks alive in this install. PM2 always writes
93
+ * `pm2.pid` under PM2_HOME (default `~/.pm2`), so its presence is a cheap
94
+ * fast-path that avoids spawning `pm2 jlist` at all when PM2 was never run.
95
+ */
96
+ function isPm2DaemonRunning() {
97
+ try {
98
+ const home = Config.PM2_HOME || process.env.PM2_HOME || join(homedir(), '.pm2');
99
+ return storage.exists(join(home, 'pm2.pid'));
100
+ }
101
+ catch (_) {
102
+ return false;
103
+ }
104
+ }
105
+ /**
106
+ * Parse `pm2 jlist` and keep only DEXBot2's own processes. Returns `[]` on any
107
+ * failure (pm2 missing, daemon down, malformed output) so callers can treat
108
+ * "no PM2" and "pm2 unavailable" the same way.
109
+ */
110
+ export function listDexbotPm2Processes() {
111
+ // Fast path: no daemon pid file means pm2 is not running here, so skip the
112
+ // subprocess. Keeps `dexbot help`/typo-usage output free of a pm2 probe.
113
+ if (!isPm2DaemonRunning())
114
+ return [];
115
+ let allProcs;
116
+ try {
117
+ const output = execSync('pm2 jlist 2>/dev/null', { encoding: 'utf8', timeout: 5000 }).toString().trim();
118
+ const jsonStart = output.indexOf('[');
119
+ if (jsonStart === -1)
120
+ return [];
121
+ const parsed = JSON.parse(output.slice(jsonStart));
122
+ if (!Array.isArray(parsed))
123
+ return [];
124
+ allProcs = parsed;
125
+ }
126
+ catch (_) {
127
+ return [];
128
+ }
129
+ const botNames = configuredBotNames();
130
+ return allProcs.filter((p) => {
131
+ const name = String(p?.name || '');
132
+ return PM2_SERVICE_NAMES.has(name) || botNames.has(name);
133
+ });
134
+ }
135
+ /**
136
+ * Detect the active runtime and the supporting state the callers need.
137
+ * Monolithic wins over isolated if both markers linger; PM2 is probed last.
138
+ */
139
+ export function detectRuntimeMode() {
140
+ const monolithicPid = readLiveMonolithicPid().pid;
141
+ const supervisorSocket = storage.exists(PATHS.PROFILES.SUPERVISOR_SOCK);
142
+ let credentialDaemonPid = 0;
143
+ try {
144
+ const pid = Number(storage.readFile(PATHS.PROFILES.MONOLITHIC_CRED_PID).trim());
145
+ if (Number.isInteger(pid) && pid > 0 && isPidAlive(pid))
146
+ credentialDaemonPid = pid;
147
+ }
148
+ catch (_) { }
149
+ const credentialDaemonAlive = credentialDaemonPid > 0;
150
+ const unlockRunning = monolithicPid > 0 || supervisorSocket || credentialDaemonAlive;
151
+ let pm2Processes = [];
152
+ let mode = 'none';
153
+ if (monolithicPid > 0) {
154
+ mode = 'monolithic';
155
+ }
156
+ else if (supervisorSocket) {
157
+ mode = 'isolated';
158
+ }
159
+ else {
160
+ pm2Processes = listDexbotPm2Processes();
161
+ if (pm2Processes.length > 0)
162
+ mode = 'pm2';
163
+ }
164
+ return { mode, monolithicPid, supervisorSocket, credentialDaemonAlive, credentialDaemonPid, unlockRunning, pm2Processes };
165
+ }
166
+ /** Human label for the active-runtime banner. */
167
+ export const RUNTIME_MODE_LABELS = {
168
+ monolithic: 'monolithic runtime (dexbot start)',
169
+ isolated: 'isolated supervisor (dexbot start --isolated)',
170
+ pm2: 'PM2 (dexbot pm2)',
171
+ none: 'none detected — standard monolithic runtime',
172
+ };
173
+ /**
174
+ * Banner label for a detection result. `none` with a live credential daemon
175
+ * is called out so the banner agrees with `dexbot status` (which reports the
176
+ * daemon that outlived a `stop`).
177
+ */
178
+ export function runtimeModeLabel(info) {
179
+ if (info.mode === 'none' && info.credentialDaemonAlive) {
180
+ return 'credential daemon only — no bot runtime';
181
+ }
182
+ return RUNTIME_MODE_LABELS[info.mode];
183
+ }
184
+ /**
185
+ * The Runtime command group, phrased for the runtime that is actually up.
186
+ * `none` shows the standard monolithic runtime (the `dexbot start` default)
187
+ * so the reference is always complete before anything is running.
188
+ */
189
+ export function runtimeControlHelp(mode) {
190
+ switch (mode) {
191
+ case 'isolated':
192
+ return [
193
+ { command: 'start [bot]', description: 'Start the runtime (flags below).' },
194
+ { command: 'stop [<bot>]', description: 'Stop one bot, or all bots when <bot> is omitted.' },
195
+ { command: 'reload [<bot>]', description: 'Reload one bot, or all bots, without re-unlocking keys.' },
196
+ { command: 'restart [<bot>]', description: 'Restart one bot, or all bots, and re-unlock keys.' },
197
+ { command: 'delete', description: 'Shut the supervisor down and clean up (all bots).' },
198
+ { command: 'status', description: 'Show runtime status (a <bot> is validated, then ignored).' },
199
+ { command: 'pm2 [<sub>]', description: 'Manage PM2 bots (see: dexbot pm2 help).' },
200
+ ];
201
+ case 'pm2':
202
+ return [
203
+ { command: 'pm2 [<bot>]', description: 'Start/replace the PM2 process set (unlocks the credential daemon).' },
204
+ { command: 'pm2 stop <bot|all>', description: 'Stop PM2 bot process(es).' },
205
+ { command: 'pm2 reload <bot|all>', description: 'Reload PM2 apps; dexbot-cred untouched.' },
206
+ { command: 'pm2 restart <bot|all|dexbot-cred>', description: 'Restart PM2 apps; dexbot-cred re-unlocks.' },
207
+ { command: 'pm2 delete <bot|all>', description: 'Delete PM2 bot process(es).' },
208
+ { command: 'status', description: 'Show runtime status (a <bot> is validated, then ignored).' },
209
+ ];
210
+ case 'monolithic':
211
+ default:
212
+ return [
213
+ { command: 'start [bot]', description: 'Start the runtime (flags below).' },
214
+ { command: 'stop [<bot>]', description: 'Stop all bots (a <bot> argument folds into the whole runtime).' },
215
+ { command: 'reload [<bot>]', description: 'Reload all bots without re-unlocking keys.' },
216
+ { command: 'restart [<bot>]', description: 'Restart all bots and re-unlock keys.' },
217
+ { command: 'delete', description: 'Stop and delete all runtime processes.' },
218
+ { command: 'status', description: 'Show runtime status (a <bot> is validated, then ignored).' },
219
+ { command: 'pm2 [<sub>]', description: 'Manage PM2 bots (see: dexbot pm2 help).' },
220
+ ];
221
+ }
222
+ }
223
+ //# sourceMappingURL=runtime_mode.js.map
@@ -26,6 +26,14 @@ declare function isBotAsymmetricBoundsWhitelisted(botKey: string): boolean;
26
26
  * Stores the market-adapter flags for a single bot key. This is the bot
27
27
  * editor's write-through path for section `6) Adapter` and writes the same
28
28
  * file/shape the market adapter reads back.
29
+ *
30
+ * Unlike renameWhitelistEntry this intentionally overwrites any existing entry
31
+ * for the key: it is the generic "set flags for this key" primitive used by
32
+ * new-bot, modify and copy, where claiming a stale/orphan entry is expected. A
33
+ * live key collision can not reach here because bots.json rejects duplicate
34
+ * botKeys before the editor's commit hook runs. The rename guard is stricter
35
+ * only because a move deletes the source, so refusing on an occupied target
36
+ * keeps both entries intact.
29
37
  * @param {string} botKey - Whitelist key (sanitized bot name).
30
38
  * @param {Partial<WhitelistFlags>} flags - Flags to apply; omitted keys keep
31
39
  * their current value.
@@ -162,6 +162,14 @@ function writeWhitelistDocument(doc, entries) {
162
162
  * Stores the market-adapter flags for a single bot key. This is the bot
163
163
  * editor's write-through path for section `6) Adapter` and writes the same
164
164
  * file/shape the market adapter reads back.
165
+ *
166
+ * Unlike renameWhitelistEntry this intentionally overwrites any existing entry
167
+ * for the key: it is the generic "set flags for this key" primitive used by
168
+ * new-bot, modify and copy, where claiming a stale/orphan entry is expected. A
169
+ * live key collision can not reach here because bots.json rejects duplicate
170
+ * botKeys before the editor's commit hook runs. The rename guard is stricter
171
+ * only because a move deletes the source, so refusing on an occupied target
172
+ * keeps both entries intact.
165
173
  * @param {string} botKey - Whitelist key (sanitized bot name).
166
174
  * @param {Partial<WhitelistFlags>} flags - Flags to apply; omitted keys keep
167
175
  * their current value.
@@ -6,7 +6,7 @@
6
6
  * Exports a single Accountant class that manages all fund accounting operations.
7
7
  *
8
8
  * ===============================================================================
9
- * TABLE OF CONTENTS - Accountant Class (17 methods)
9
+ * TABLE OF CONTENTS - Accountant Class (26 methods)
10
10
  * ===============================================================================
11
11
  *
12
12
  * CORE INITIALIZATION & RECALCULATION (2 methods)
@@ -43,6 +43,20 @@
43
43
  * RECOVERY & VALIDATION (1 method)
44
44
  * 17. resetRecoveryState() - Reset recovery backoff and state
45
45
  *
46
+ * INTERNAL FEE / BALANCE HELPERS (9 methods - internal)
47
+ * 18. _logThrottled(key, message, level, intervalMs) - Throttled logging helper
48
+ * 19. _applyBalanceAdjustments(list) - Apply a list of balance adjustments
49
+ * 20. _getBtsOrderType() - Resolve which side pays BTS fees
50
+ * 21. _normalizeBtsFeeState(order) - Normalize an order's deferred-BTS-fee state
51
+ * 22. _calculateUpdateDeferredCharge(oldDeferredFee, feeSchedule) - Deferred charge on update
52
+ * 23. _resolveBtsFeeLifecycle(oldOrder, newOrder, context, explicitFee) - Resolve the
53
+ * BTS fee lifecycle for an order transition
54
+ * 24. _buildBtsDeferredRefundAdjustment(orderId, isMaker) - Build the deferred refund
55
+ * adjustment for a fill
56
+ * 25. _recalibrateTrackedFundsFromChain(mgr, openOrders) - Recalibrate tracked funds
57
+ * from a fresh chain snapshot
58
+ * 26. _tryTrustChainFreeHeal(mgr, driftValidation) - Attempt a trust-chain-free heal
59
+ *
46
60
  * ===============================================================================
47
61
  * FUND STRUCTURE (managed by Accountant)
48
62
  * ===============================================================================