@reefclaw/connect 0.1.11 → 0.1.12

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 (397) hide show
  1. package/assets/bridge/gateway/heartbeat-cron.d.ts +27 -0
  2. package/assets/bridge/gateway/heartbeat-cron.js +85 -0
  3. package/assets/bridge/providers/gateway.d.ts +2 -0
  4. package/assets/bridge/providers/gateway.js +57 -16
  5. package/assets/bridge/setup.js +6 -51
  6. package/dist/deps.js +2 -2
  7. package/dist/plugin.js +35 -7
  8. package/package.json +1 -1
  9. package/assets/plugin/audit/mode-transition-audit.d.ts +0 -11
  10. package/assets/plugin/audit/mode-transition-audit.js +0 -29
  11. package/assets/plugin/balance-utils.d.ts +0 -36
  12. package/assets/plugin/balance-utils.js +0 -98
  13. package/assets/plugin/ccxt/binance-ban-gate.d.ts +0 -47
  14. package/assets/plugin/ccxt/binance-ban-gate.js +0 -420
  15. package/assets/plugin/ccxt/binance-private.d.ts +0 -346
  16. package/assets/plugin/ccxt/binance-private.js +0 -1525
  17. package/assets/plugin/ccxt/binance-public.d.ts +0 -34
  18. package/assets/plugin/ccxt/binance-public.js +0 -180
  19. package/assets/plugin/ccxt/intel-public.d.ts +0 -25
  20. package/assets/plugin/ccxt/intel-public.js +0 -80
  21. package/assets/plugin/ccxt/public-market-data-api.d.ts +0 -26
  22. package/assets/plugin/ccxt/public-market-data-api.js +0 -23
  23. package/assets/plugin/config/agent-config-client.d.ts +0 -77
  24. package/assets/plugin/config/agent-config-client.js +0 -188
  25. package/assets/plugin/config/agent-config-poller.d.ts +0 -32
  26. package/assets/plugin/config/agent-config-poller.js +0 -101
  27. package/assets/plugin/config/brackets-config.d.ts +0 -22
  28. package/assets/plugin/config/brackets-config.js +0 -58
  29. package/assets/plugin/config/entitlement-gate.d.ts +0 -51
  30. package/assets/plugin/config/entitlement-gate.js +0 -137
  31. package/assets/plugin/config/gate-store.d.ts +0 -18
  32. package/assets/plugin/config/gate-store.js +0 -61
  33. package/assets/plugin/config/plugin-config-io.d.ts +0 -222
  34. package/assets/plugin/config/plugin-config-io.js +0 -126
  35. package/assets/plugin/config/position-review-config.d.ts +0 -35
  36. package/assets/plugin/config/position-review-config.js +0 -105
  37. package/assets/plugin/config/tool-gate.d.ts +0 -53
  38. package/assets/plugin/config/tool-gate.js +0 -128
  39. package/assets/plugin/config/user-data-stream-config.d.ts +0 -89
  40. package/assets/plugin/config/user-data-stream-config.js +0 -239
  41. package/assets/plugin/connector-supervisor.d.ts +0 -36
  42. package/assets/plugin/connector-supervisor.js +0 -149
  43. package/assets/plugin/exchange-adapter.d.ts +0 -65
  44. package/assets/plugin/exchange-adapter.js +0 -4
  45. package/assets/plugin/index.d.ts +0 -30
  46. package/assets/plugin/index.js +0 -2756
  47. package/assets/plugin/ingest/pending-entry-metadata.d.ts +0 -74
  48. package/assets/plugin/ingest/pending-entry-metadata.js +0 -236
  49. package/assets/plugin/ingest/position-auto-capture.d.ts +0 -171
  50. package/assets/plugin/ingest/position-auto-capture.js +0 -709
  51. package/assets/plugin/ingest/position-decisions-client.d.ts +0 -327
  52. package/assets/plugin/ingest/position-decisions-client.js +0 -306
  53. package/assets/plugin/ingest/readiness-reporter.d.ts +0 -42
  54. package/assets/plugin/ingest/readiness-reporter.js +0 -163
  55. package/assets/plugin/ingest/reconcile-db-vs-exchange.d.ts +0 -51
  56. package/assets/plugin/ingest/reconcile-db-vs-exchange.js +0 -170
  57. package/assets/plugin/ingest/reconciler-cleanup.d.ts +0 -37
  58. package/assets/plugin/ingest/reconciler-cleanup.js +0 -147
  59. package/assets/plugin/ingest/rest-gap-filler.d.ts +0 -191
  60. package/assets/plugin/ingest/rest-gap-filler.js +0 -565
  61. package/assets/plugin/ingest/touched-symbols-store.d.ts +0 -25
  62. package/assets/plugin/ingest/touched-symbols-store.js +0 -96
  63. package/assets/plugin/ingest/trade-store-client.d.ts +0 -40
  64. package/assets/plugin/ingest/trade-store-client.js +0 -125
  65. package/assets/plugin/ingest/ws-ingest.d.ts +0 -43
  66. package/assets/plugin/ingest/ws-ingest.js +0 -126
  67. package/assets/plugin/learning/setup-family.d.ts +0 -21
  68. package/assets/plugin/learning/setup-family.js +0 -103
  69. package/assets/plugin/lifecycle/install-signal-handlers.d.ts +0 -33
  70. package/assets/plugin/lifecycle/install-signal-handlers.js +0 -112
  71. package/assets/plugin/lifecycle/shutdown-coordinator.d.ts +0 -43
  72. package/assets/plugin/lifecycle/shutdown-coordinator.js +0 -131
  73. package/assets/plugin/lifecycle/trading-operation-lock.d.ts +0 -17
  74. package/assets/plugin/lifecycle/trading-operation-lock.js +0 -14
  75. package/assets/plugin/live/bracket-id.d.ts +0 -26
  76. package/assets/plugin/live/bracket-id.js +0 -112
  77. package/assets/plugin/live/bracket-ledger.d.ts +0 -54
  78. package/assets/plugin/live/bracket-ledger.js +0 -267
  79. package/assets/plugin/live/bracket-manager.d.ts +0 -82
  80. package/assets/plugin/live/bracket-manager.js +0 -478
  81. package/assets/plugin/live/bracket-params.d.ts +0 -22
  82. package/assets/plugin/live/bracket-params.js +0 -124
  83. package/assets/plugin/live/bracket-reconciler.d.ts +0 -95
  84. package/assets/plugin/live/bracket-reconciler.js +0 -573
  85. package/assets/plugin/live/bracket-types.d.ts +0 -102
  86. package/assets/plugin/live/bracket-types.js +0 -8
  87. package/assets/plugin/live/deposit-tracker.d.ts +0 -62
  88. package/assets/plugin/live/deposit-tracker.js +0 -97
  89. package/assets/plugin/live/emergency-controls.d.ts +0 -32
  90. package/assets/plugin/live/emergency-controls.js +0 -226
  91. package/assets/plugin/live/exchange-errors.d.ts +0 -12
  92. package/assets/plugin/live/exchange-errors.js +0 -130
  93. package/assets/plugin/live/exchange-info-cache.d.ts +0 -37
  94. package/assets/plugin/live/exchange-info-cache.js +0 -134
  95. package/assets/plugin/live/fact-subscriber.d.ts +0 -78
  96. package/assets/plugin/live/fact-subscriber.js +0 -182
  97. package/assets/plugin/live/fill-price.d.ts +0 -13
  98. package/assets/plugin/live/fill-price.js +0 -37
  99. package/assets/plugin/live/intent-journal.d.ts +0 -42
  100. package/assets/plugin/live/intent-journal.js +0 -122
  101. package/assets/plugin/live/listen-key-manager.d.ts +0 -70
  102. package/assets/plugin/live/listen-key-manager.js +0 -169
  103. package/assets/plugin/live/live-adapter.d.ts +0 -319
  104. package/assets/plugin/live/live-adapter.js +0 -1906
  105. package/assets/plugin/live/live-balance-enricher.d.ts +0 -32
  106. package/assets/plugin/live/live-balance-enricher.js +0 -104
  107. package/assets/plugin/live/live-bracket-api.d.ts +0 -13
  108. package/assets/plugin/live/live-bracket-api.js +0 -20
  109. package/assets/plugin/live/live-state-store.d.ts +0 -194
  110. package/assets/plugin/live/live-state-store.js +0 -450
  111. package/assets/plugin/live/local-signal-service.d.ts +0 -57
  112. package/assets/plugin/live/local-signal-service.js +0 -151
  113. package/assets/plugin/live/local-strategy-evaluator.d.ts +0 -62
  114. package/assets/plugin/live/local-strategy-evaluator.js +0 -131
  115. package/assets/plugin/live/microstructure-assembler.d.ts +0 -54
  116. package/assets/plugin/live/microstructure-assembler.js +0 -148
  117. package/assets/plugin/live/order-poller.d.ts +0 -29
  118. package/assets/plugin/live/order-poller.js +0 -125
  119. package/assets/plugin/live/position-state-store.d.ts +0 -87
  120. package/assets/plugin/live/position-state-store.js +0 -237
  121. package/assets/plugin/live/proposal-decision-listener.d.ts +0 -70
  122. package/assets/plugin/live/proposal-decision-listener.js +0 -292
  123. package/assets/plugin/live/proposal-manager.d.ts +0 -76
  124. package/assets/plugin/live/proposal-manager.js +0 -140
  125. package/assets/plugin/live/rate-limiter.d.ts +0 -47
  126. package/assets/plugin/live/rate-limiter.js +0 -159
  127. package/assets/plugin/live/reconciler.d.ts +0 -39
  128. package/assets/plugin/live/reconciler.js +0 -175
  129. package/assets/plugin/live/setup-buckets.d.ts +0 -7
  130. package/assets/plugin/live/setup-buckets.js +0 -33
  131. package/assets/plugin/live/slippage-tracker.d.ts +0 -45
  132. package/assets/plugin/live/slippage-tracker.js +0 -78
  133. package/assets/plugin/live/stop-watcher.d.ts +0 -67
  134. package/assets/plugin/live/stop-watcher.js +0 -218
  135. package/assets/plugin/live/user-data-active-probe.d.ts +0 -54
  136. package/assets/plugin/live/user-data-active-probe.js +0 -180
  137. package/assets/plugin/live/user-data-stream-controller.d.ts +0 -200
  138. package/assets/plugin/live/user-data-stream-controller.js +0 -579
  139. package/assets/plugin/live/user-data-stream-ws.d.ts +0 -22
  140. package/assets/plugin/live/user-data-stream-ws.js +0 -63
  141. package/assets/plugin/live/user-data-stream.d.ts +0 -243
  142. package/assets/plugin/live/user-data-stream.js +0 -704
  143. package/assets/plugin/logger.d.ts +0 -2
  144. package/assets/plugin/logger.js +0 -2
  145. package/assets/plugin/mfe.d.ts +0 -21
  146. package/assets/plugin/mfe.js +0 -68
  147. package/assets/plugin/onboarding/mode-ladder.d.ts +0 -1
  148. package/assets/plugin/onboarding/mode-ladder.js +0 -3
  149. package/assets/plugin/onboarding/runtime.d.ts +0 -90
  150. package/assets/plugin/onboarding/runtime.js +0 -184
  151. package/assets/plugin/openclaw.plugin.json +0 -92
  152. package/assets/plugin/paper-adapter.d.ts +0 -24
  153. package/assets/plugin/paper-adapter.js +0 -91
  154. package/assets/plugin/persistence/state-manager.d.ts +0 -66
  155. package/assets/plugin/persistence/state-manager.js +0 -222
  156. package/assets/plugin/pinned-plan.d.ts +0 -9
  157. package/assets/plugin/pinned-plan.js +0 -23
  158. package/assets/plugin/portfolio/reentry-tracker.d.ts +0 -36
  159. package/assets/plugin/portfolio/reentry-tracker.js +0 -127
  160. package/assets/plugin/portfolio/wave9-admission.d.ts +0 -67
  161. package/assets/plugin/portfolio/wave9-admission.js +0 -262
  162. package/assets/plugin/portfolio/wave9-policy.d.ts +0 -36
  163. package/assets/plugin/portfolio/wave9-policy.js +0 -183
  164. package/assets/plugin/risk/pre-trade-check.d.ts +0 -38
  165. package/assets/plugin/risk/pre-trade-check.js +0 -345
  166. package/assets/plugin/risk/pre-trade-types.d.ts +0 -60
  167. package/assets/plugin/risk/pre-trade-types.js +0 -3
  168. package/assets/plugin/shadow/shadow-tracker.d.ts +0 -36
  169. package/assets/plugin/shadow/shadow-tracker.js +0 -151
  170. package/assets/plugin/shadow/types.d.ts +0 -42
  171. package/assets/plugin/shadow/types.js +0 -20
  172. package/assets/plugin/shared/indicators-extended.d.ts +0 -52
  173. package/assets/plugin/shared/indicators-extended.js +0 -291
  174. package/assets/plugin/shared/indicators.d.ts +0 -15
  175. package/assets/plugin/shared/indicators.js +0 -114
  176. package/assets/plugin/signals/conditions/registry.d.ts +0 -16
  177. package/assets/plugin/signals/conditions/registry.js +0 -1333
  178. package/assets/plugin/signals/conditions/types.d.ts +0 -1
  179. package/assets/plugin/signals/conditions/types.js +0 -4
  180. package/assets/plugin/signals/direction-rules.d.ts +0 -3
  181. package/assets/plugin/signals/direction-rules.js +0 -24
  182. package/assets/plugin/signals/entry-rules.d.ts +0 -6
  183. package/assets/plugin/signals/entry-rules.js +0 -33
  184. package/assets/plugin/signals/serialize-context.d.ts +0 -4
  185. package/assets/plugin/signals/serialize-context.js +0 -39
  186. package/assets/plugin/signals/stop-rules.d.ts +0 -3
  187. package/assets/plugin/signals/stop-rules.js +0 -48
  188. package/assets/plugin/signals/strategy-adapter.d.ts +0 -47
  189. package/assets/plugin/signals/strategy-adapter.js +0 -209
  190. package/assets/plugin/signals/types.d.ts +0 -1
  191. package/assets/plugin/signals/types.js +0 -8
  192. package/assets/plugin/simulator/exchange-simulator.d.ts +0 -105
  193. package/assets/plugin/simulator/exchange-simulator.js +0 -759
  194. package/assets/plugin/simulator/fill-engine.d.ts +0 -53
  195. package/assets/plugin/simulator/fill-engine.js +0 -280
  196. package/assets/plugin/simulator/paper-market-feed.d.ts +0 -26
  197. package/assets/plugin/simulator/paper-market-feed.js +0 -104
  198. package/assets/plugin/simulator/realistic-fills.d.ts +0 -59
  199. package/assets/plugin/simulator/realistic-fills.js +0 -175
  200. package/assets/plugin/simulator/types.d.ts +0 -228
  201. package/assets/plugin/simulator/types.js +0 -43
  202. package/assets/plugin/strategy/builtin-strategies.d.ts +0 -2
  203. package/assets/plugin/strategy/builtin-strategies.js +0 -113
  204. package/assets/plugin/strategy/condition-registry.d.ts +0 -3
  205. package/assets/plugin/strategy/condition-registry.js +0 -153
  206. package/assets/plugin/strategy/evaluator.d.ts +0 -70
  207. package/assets/plugin/strategy/evaluator.js +0 -98
  208. package/assets/plugin/tools/assessment-validation.d.ts +0 -141
  209. package/assets/plugin/tools/assessment-validation.js +0 -473
  210. package/assets/plugin/tools/attach-brackets.d.ts +0 -39
  211. package/assets/plugin/tools/attach-brackets.js +0 -564
  212. package/assets/plugin/tools/audit-bracket-protection.d.ts +0 -49
  213. package/assets/plugin/tools/audit-bracket-protection.js +0 -683
  214. package/assets/plugin/tools/bracket-control.d.ts +0 -12
  215. package/assets/plugin/tools/bracket-control.js +0 -35
  216. package/assets/plugin/tools/cancel-all-orders.d.ts +0 -9
  217. package/assets/plugin/tools/cancel-all-orders.js +0 -8
  218. package/assets/plugin/tools/cancel-order.d.ts +0 -14
  219. package/assets/plugin/tools/cancel-order.js +0 -60
  220. package/assets/plugin/tools/check-position-health.d.ts +0 -46
  221. package/assets/plugin/tools/check-position-health.js +0 -194
  222. package/assets/plugin/tools/clear-exchange-credentials.d.ts +0 -24
  223. package/assets/plugin/tools/clear-exchange-credentials.js +0 -70
  224. package/assets/plugin/tools/close-position.d.ts +0 -45
  225. package/assets/plugin/tools/close-position.js +0 -722
  226. package/assets/plugin/tools/create-order.d.ts +0 -82
  227. package/assets/plugin/tools/create-order.js +0 -1544
  228. package/assets/plugin/tools/exit-gate.d.ts +0 -58
  229. package/assets/plugin/tools/exit-gate.js +0 -162
  230. package/assets/plugin/tools/fetch-balance.d.ts +0 -5
  231. package/assets/plugin/tools/fetch-balance.js +0 -4
  232. package/assets/plugin/tools/fetch-ohlcv.d.ts +0 -11
  233. package/assets/plugin/tools/fetch-ohlcv.js +0 -8
  234. package/assets/plugin/tools/fetch-open-orders.d.ts +0 -7
  235. package/assets/plugin/tools/fetch-open-orders.js +0 -4
  236. package/assets/plugin/tools/fetch-positions.d.ts +0 -7
  237. package/assets/plugin/tools/fetch-positions.js +0 -4
  238. package/assets/plugin/tools/fetch-ticker.d.ts +0 -11
  239. package/assets/plugin/tools/fetch-ticker.js +0 -5
  240. package/assets/plugin/tools/get-agent-profile.d.ts +0 -4
  241. package/assets/plugin/tools/get-agent-profile.js +0 -6
  242. package/assets/plugin/tools/get-analytics.d.ts +0 -6
  243. package/assets/plugin/tools/get-analytics.js +0 -7
  244. package/assets/plugin/tools/get-backtest.d.ts +0 -12
  245. package/assets/plugin/tools/get-backtest.js +0 -91
  246. package/assets/plugin/tools/get-basis.d.ts +0 -7
  247. package/assets/plugin/tools/get-basis.js +0 -7
  248. package/assets/plugin/tools/get-bracket-config.d.ts +0 -11
  249. package/assets/plugin/tools/get-bracket-config.js +0 -24
  250. package/assets/plugin/tools/get-cascade-risk.d.ts +0 -7
  251. package/assets/plugin/tools/get-cascade-risk.js +0 -8
  252. package/assets/plugin/tools/get-crypto-metrics.d.ts +0 -18
  253. package/assets/plugin/tools/get-crypto-metrics.js +0 -62
  254. package/assets/plugin/tools/get-cvd.d.ts +0 -6
  255. package/assets/plugin/tools/get-cvd.js +0 -6
  256. package/assets/plugin/tools/get-divergences.d.ts +0 -6
  257. package/assets/plugin/tools/get-divergences.js +0 -6
  258. package/assets/plugin/tools/get-funding-context.d.ts +0 -6
  259. package/assets/plugin/tools/get-funding-context.js +0 -16
  260. package/assets/plugin/tools/get-liquidation-levels.d.ts +0 -7
  261. package/assets/plugin/tools/get-liquidation-levels.js +0 -7
  262. package/assets/plugin/tools/get-liquidation-pulse.d.ts +0 -9
  263. package/assets/plugin/tools/get-liquidation-pulse.js +0 -22
  264. package/assets/plugin/tools/get-market-breadth.d.ts +0 -6
  265. package/assets/plugin/tools/get-market-breadth.js +0 -8
  266. package/assets/plugin/tools/get-market-intel.d.ts +0 -19
  267. package/assets/plugin/tools/get-market-intel.js +0 -116
  268. package/assets/plugin/tools/get-market-structure.d.ts +0 -47
  269. package/assets/plugin/tools/get-market-structure.js +0 -198
  270. package/assets/plugin/tools/get-my-mined-patterns.d.ts +0 -20
  271. package/assets/plugin/tools/get-my-mined-patterns.js +0 -61
  272. package/assets/plugin/tools/get-my-proposed-learnings.d.ts +0 -20
  273. package/assets/plugin/tools/get-my-proposed-learnings.js +0 -55
  274. package/assets/plugin/tools/get-my-recent-reviews.d.ts +0 -22
  275. package/assets/plugin/tools/get-my-recent-reviews.js +0 -66
  276. package/assets/plugin/tools/get-orderbook.d.ts +0 -21
  277. package/assets/plugin/tools/get-orderbook.js +0 -32
  278. package/assets/plugin/tools/get-pattern-scan.d.ts +0 -7
  279. package/assets/plugin/tools/get-pattern-scan.js +0 -8
  280. package/assets/plugin/tools/get-regime.d.ts +0 -6
  281. package/assets/plugin/tools/get-regime.js +0 -7
  282. package/assets/plugin/tools/get-relevant-learnings.d.ts +0 -21
  283. package/assets/plugin/tools/get-relevant-learnings.js +0 -65
  284. package/assets/plugin/tools/get-resting-liquidity.d.ts +0 -6
  285. package/assets/plugin/tools/get-resting-liquidity.js +0 -11
  286. package/assets/plugin/tools/get-risk-scenario.d.ts +0 -29
  287. package/assets/plugin/tools/get-risk-scenario.js +0 -47
  288. package/assets/plugin/tools/get-risk-summary.d.ts +0 -51
  289. package/assets/plugin/tools/get-risk-summary.js +0 -118
  290. package/assets/plugin/tools/get-sentiment.d.ts +0 -4
  291. package/assets/plugin/tools/get-sentiment.js +0 -6
  292. package/assets/plugin/tools/get-session-review.d.ts +0 -7
  293. package/assets/plugin/tools/get-session-review.js +0 -8
  294. package/assets/plugin/tools/get-setup-detail.d.ts +0 -7
  295. package/assets/plugin/tools/get-setup-detail.js +0 -322
  296. package/assets/plugin/tools/get-signals.d.ts +0 -15
  297. package/assets/plugin/tools/get-signals.js +0 -54
  298. package/assets/plugin/tools/get-sizing.d.ts +0 -6
  299. package/assets/plugin/tools/get-sizing.js +0 -6
  300. package/assets/plugin/tools/get-trade-feedback.d.ts +0 -7
  301. package/assets/plugin/tools/get-trade-feedback.js +0 -8
  302. package/assets/plugin/tools/get-trade-flow.d.ts +0 -7
  303. package/assets/plugin/tools/get-trade-flow.js +0 -7
  304. package/assets/plugin/tools/get-volume-analysis.d.ts +0 -21
  305. package/assets/plugin/tools/get-volume-analysis.js +0 -74
  306. package/assets/plugin/tools/get-volume-profile.d.ts +0 -7
  307. package/assets/plugin/tools/get-volume-profile.js +0 -7
  308. package/assets/plugin/tools/get-wave9-status.d.ts +0 -127
  309. package/assets/plugin/tools/get-wave9-status.js +0 -796
  310. package/assets/plugin/tools/helpers.d.ts +0 -26
  311. package/assets/plugin/tools/helpers.js +0 -39
  312. package/assets/plugin/tools/intel-api.d.ts +0 -34
  313. package/assets/plugin/tools/intel-api.js +0 -119
  314. package/assets/plugin/tools/intel-cache.d.ts +0 -25
  315. package/assets/plugin/tools/intel-cache.js +0 -148
  316. package/assets/plugin/tools/list-strategies.d.ts +0 -17
  317. package/assets/plugin/tools/list-strategies.js +0 -23
  318. package/assets/plugin/tools/modify-stop.d.ts +0 -21
  319. package/assets/plugin/tools/modify-stop.js +0 -120
  320. package/assets/plugin/tools/modify-target.d.ts +0 -21
  321. package/assets/plugin/tools/modify-target.js +0 -110
  322. package/assets/plugin/tools/propose-learning.d.ts +0 -22
  323. package/assets/plugin/tools/propose-learning.js +0 -65
  324. package/assets/plugin/tools/query-review-outcomes.d.ts +0 -30
  325. package/assets/plugin/tools/query-review-outcomes.js +0 -64
  326. package/assets/plugin/tools/query-trades.d.ts +0 -21
  327. package/assets/plugin/tools/query-trades.js +0 -37
  328. package/assets/plugin/tools/record-position-reviews.d.ts +0 -38
  329. package/assets/plugin/tools/record-position-reviews.js +0 -147
  330. package/assets/plugin/tools/save-strategy.d.ts +0 -16
  331. package/assets/plugin/tools/save-strategy.js +0 -46
  332. package/assets/plugin/tools/scan-pairs.d.ts +0 -22
  333. package/assets/plugin/tools/scan-pairs.js +0 -234
  334. package/assets/plugin/tools/score-setup.d.ts +0 -31
  335. package/assets/plugin/tools/score-setup.js +0 -268
  336. package/assets/plugin/tools/set-bracket-requirement.d.ts +0 -18
  337. package/assets/plugin/tools/set-bracket-requirement.js +0 -81
  338. package/assets/plugin/tools/set-exchange-credentials.d.ts +0 -25
  339. package/assets/plugin/tools/set-exchange-credentials.js +0 -80
  340. package/assets/plugin/tools/set-trading-mode.d.ts +0 -26
  341. package/assets/plugin/tools/set-trading-mode.js +0 -135
  342. package/assets/plugin/tools/test-exchange-credentials.d.ts +0 -16
  343. package/assets/plugin/tools/test-exchange-credentials.js +0 -100
  344. package/assets/plugin/tools/toggle-strategy.d.ts +0 -8
  345. package/assets/plugin/tools/toggle-strategy.js +0 -15
  346. package/assets/plugin/trading-params-cache.d.ts +0 -26
  347. package/assets/plugin/trading-params-cache.js +0 -52
  348. package/assets/plugin/types.d.ts +0 -134
  349. package/assets/plugin/types.js +0 -7
  350. package/assets/plugin/util/plugin-paths.d.ts +0 -3
  351. package/assets/plugin/util/plugin-paths.js +0 -15
  352. package/assets/plugin/venues/hyperliquid/hl-balance.d.ts +0 -116
  353. package/assets/plugin/venues/hyperliquid/hl-balance.js +0 -145
  354. package/assets/plugin/venues/hyperliquid/hl-bracket-coordinator.d.ts +0 -123
  355. package/assets/plugin/venues/hyperliquid/hl-bracket-coordinator.js +0 -533
  356. package/assets/plugin/venues/hyperliquid/hl-brackets.d.ts +0 -102
  357. package/assets/plugin/venues/hyperliquid/hl-brackets.js +0 -172
  358. package/assets/plugin/venues/hyperliquid/hl-cloid.d.ts +0 -22
  359. package/assets/plugin/venues/hyperliquid/hl-cloid.js +0 -82
  360. package/assets/plugin/venues/hyperliquid/hl-info-cache.d.ts +0 -46
  361. package/assets/plugin/venues/hyperliquid/hl-info-cache.js +0 -125
  362. package/assets/plugin/venues/hyperliquid/hl-live-adapter.d.ts +0 -146
  363. package/assets/plugin/venues/hyperliquid/hl-live-adapter.js +0 -728
  364. package/assets/plugin/venues/hyperliquid/hl-precision.d.ts +0 -61
  365. package/assets/plugin/venues/hyperliquid/hl-precision.js +0 -176
  366. package/assets/plugin/venues/hyperliquid/hl-private.d.ts +0 -88
  367. package/assets/plugin/venues/hyperliquid/hl-private.js +0 -357
  368. package/assets/plugin/venues/hyperliquid/hl-public.d.ts +0 -79
  369. package/assets/plugin/venues/hyperliquid/hl-public.js +0 -436
  370. package/assets/plugin/venues/hyperliquid/hl-rate-gate.d.ts +0 -57
  371. package/assets/plugin/venues/hyperliquid/hl-rate-gate.js +0 -220
  372. package/assets/plugin/venues/hyperliquid/hl-user-stream.d.ts +0 -90
  373. package/assets/plugin/venues/hyperliquid/hl-user-stream.js +0 -220
  374. package/assets/plugin/venues/registry.d.ts +0 -38
  375. package/assets/plugin/venues/registry.js +0 -46
  376. package/assets/plugin/venues/symbols.d.ts +0 -43
  377. package/assets/plugin/venues/symbols.js +0 -107
  378. package/assets/plugin/wave9/live-account-capture.d.ts +0 -67
  379. package/assets/plugin/wave9/live-account-capture.js +0 -435
  380. package/assets/plugin/wave9/live-autonomous-protection.d.ts +0 -39
  381. package/assets/plugin/wave9/live-autonomous-protection.js +0 -112
  382. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.d.ts +0 -33
  383. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.js +0 -115
  384. package/assets/plugin/wave9/live-execution-ledger.d.ts +0 -107
  385. package/assets/plugin/wave9/live-execution-ledger.js +0 -498
  386. package/assets/plugin/wave9/live-position-confirmation.d.ts +0 -18
  387. package/assets/plugin/wave9/live-position-confirmation.js +0 -111
  388. package/assets/plugin/wave9/live-residual-protection.d.ts +0 -18
  389. package/assets/plugin/wave9/live-residual-protection.js +0 -250
  390. package/assets/plugin/wave9/live-startup-reconciliation.d.ts +0 -38
  391. package/assets/plugin/wave9/live-startup-reconciliation.js +0 -454
  392. package/assets/plugin/wave9/live-symbol-ownership.d.ts +0 -20
  393. package/assets/plugin/wave9/live-symbol-ownership.js +0 -132
  394. package/assets/plugin/wave9/paper-admission-guard.d.ts +0 -199
  395. package/assets/plugin/wave9/paper-admission-guard.js +0 -650
  396. package/assets/plugin/wave9/usdm-evidence-provider.d.ts +0 -42
  397. package/assets/plugin/wave9/usdm-evidence-provider.js +0 -133
@@ -1,564 +0,0 @@
1
- // Tool: attach_brackets — bootstrap exchange-side protection on an existing
2
- // open live position that is currently naked (no STOP_MARKET / TAKE_PROFIT_MARKET
3
- // order). Complements modify_stop / modify_target, which can only MOVE an
4
- // already-active bracket — they can't attach one from nothing.
5
- //
6
- // Why this tool exists (2026-04-21 naked-position incident): kill-switch
7
- // sweeps were stripping bracket protective orders off open positions without
8
- // flattening them. The agent then had no recovery path because modify_*
9
- // requires state ∈ {active, partial}. This tool + the bracket-preserving
10
- // cancel filter in BinancePrivateApi together close the loop.
11
- //
12
- // Responsibilities:
13
- // 1. Validate inputs + mode (live only, brackets enabled).
14
- // 2. Confirm an open position exists with >0 contracts.
15
- // 3. Sanity-check stop / target direction vs the position side.
16
- // 4. Reject if a fresh bracket is already active (caller wants modify_*).
17
- // 5. Clear any stale bracket orders on the exchange for this symbol.
18
- // 6. Register a new bracket + attach it. Retries inherit BracketManager policy.
19
- //
20
- // Paper mode: rejected with an explanatory error (paper uses per-position
21
- // metadata + stop-watcher, not exchange orders).
22
- import { generateBracketId, buildBracketCid } from '../live/bracket-id.js';
23
- import { validateStopDirection, validateTargetDirection } from '../live/bracket-params.js';
24
- import { formatError, logger } from '../logger.js';
25
- import { HyperliquidLiveAdapter } from '../venues/hyperliquid/hl-live-adapter.js';
26
- import { isTerminalBracketState } from '../venues/hyperliquid/hl-bracket-coordinator.js';
27
- import { buildHlBracketCloid } from '../venues/hyperliquid/hl-cloid.js';
28
- const TAG = 'attach-brackets';
29
- export async function attachBracketsTool(args, deps) {
30
- // ---- 1. Argument validation ----
31
- if (!args.symbol || typeof args.symbol !== 'string') {
32
- return { error: 'symbol is required.' };
33
- }
34
- if (args.stop_price === undefined && args.target_price === undefined) {
35
- return { error: 'at least one of stop_price or target_price must be provided.' };
36
- }
37
- if (args.stop_price !== undefined && (!Number.isFinite(args.stop_price) || args.stop_price <= 0)) {
38
- return { error: 'stop_price must be a positive finite number.' };
39
- }
40
- if (args.target_price !== undefined && (!Number.isFinite(args.target_price) || args.target_price <= 0)) {
41
- return { error: 'target_price must be a positive finite number.' };
42
- }
43
- // ---- 2. Mode gate ----
44
- if (!deps.adapter.isLive) {
45
- return { error: 'attach_brackets is live-mode only (it places exchange-side STOP/TP orders). In paper mode, use modify_stop / modify_target to set or move the position\'s protective levels in place — the paper stop-watcher enforces metadata.stopPrice.' };
46
- }
47
- if (deps.checkWave9LiveSymbolOwnership && !deps.operationLock) {
48
- return {
49
- error: 'Live attach_brackets refused: the shared trading operation lock is required ' +
50
- 'while Wave 9 LIVE ownership checks are enabled.',
51
- };
52
- }
53
- const attachLive = () => attachBracketsLive(args, deps);
54
- try {
55
- return deps.operationLock
56
- ? await deps.operationLock.withAccountLock(`generic-attach-brackets-final:${args.symbol}`, attachLive)
57
- : await attachLive();
58
- }
59
- catch (err) {
60
- return { error: formatError(err) };
61
- }
62
- }
63
- async function attachBracketsLive(args, deps) {
64
- if (deps.checkWave9LiveSymbolOwnership) {
65
- let ownership;
66
- try {
67
- ownership = await deps.checkWave9LiveSymbolOwnership(args.symbol);
68
- }
69
- catch (err) {
70
- return {
71
- error: `attach_brackets refused at mutation boundary: Wave 9 LIVE ownership check failed ` +
72
- `for ${args.symbol} (${formatError(err)}).`,
73
- };
74
- }
75
- if (ownership.status === 'owned' || ownership.status === 'ambiguous') {
76
- return {
77
- error: `attach_brackets refused at mutation boundary: ${args.symbol} has ` +
78
- `${ownership.status} Wave 9 LIVE ownership (${ownership.reason}). ` +
79
- 'Wave 9 protection is candidate-bound and cannot be replaced by the generic bracket tool.',
80
- };
81
- }
82
- }
83
- // Venue dispatch (issue #209): the HL arm drives the HlBracketCoordinator —
84
- // the Binance-shaped path below would silently no-op ("not enabled") on HL,
85
- // which is exactly the recovery gap the boot guard existed for.
86
- if (deps.adapter instanceof HyperliquidLiveAdapter) {
87
- return attachBracketsHl(args, deps.adapter);
88
- }
89
- const live = deps.adapter;
90
- const mgr = live.getBracketManager?.();
91
- const ledger = live.getBracketLedger?.();
92
- if (!mgr || !ledger) {
93
- return { error: 'Bracket orders are not enabled. Set brackets.mode in plugin-config.json to "observe" or "enforce".' };
94
- }
95
- // ---- 3. Position must exist ----
96
- // getPositionsOrNull() returns null when the fetch FAILED (429 / weight-
97
- // paced / transient) — position state is UNKNOWN, NOT "no position". If
98
- // we collapsed null→[] here, attach_brackets would tell the agent "No open
99
- // position" for a position that is actually live and NAKED on Binance; the
100
- // agent reads that as "nothing to protect", stops trying, and the naked
101
- // position rides unprotected. Distinct error → agent retries next
102
- // heartbeat. Same null≠empty contract as audit/closePosition/flatten.
103
- const positions = await deps.adapter.getPositionsOrNull(args.symbol);
104
- if (positions === null) {
105
- return {
106
- error: `Exchange data unavailable for ${args.symbol} (likely Binance 429 or transient ` +
107
- `network) — position state UNKNOWN. NOT treating this as "no position"; ` +
108
- `bracket attach skipped this cycle. Retry on next heartbeat.`,
109
- };
110
- }
111
- const position = positions.find(p => p.symbol === args.symbol) ?? positions[0];
112
- if (!position || position.contracts <= 0) {
113
- return { error: `No open position for ${args.symbol}.` };
114
- }
115
- const entrySide = position.side === 'long' ? 'buy' : 'sell';
116
- // ---- 4. Direction sanity check vs entry price ----
117
- const refPrice = position.entryPrice > 0 ? position.entryPrice : await deps.adapter.getLastPrice(position.symbol);
118
- if (refPrice != null && refPrice > 0) {
119
- if (args.stop_price !== undefined) {
120
- const msg = validateStopDirection(entrySide, refPrice, args.stop_price);
121
- if (msg)
122
- return { error: msg };
123
- }
124
- if (args.target_price !== undefined) {
125
- const msg = validateTargetDirection(entrySide, refPrice, args.target_price);
126
- if (msg)
127
- return { error: msg };
128
- }
129
- }
130
- // ---- 5. Handle existing ledger row ----
131
- // If the ledger has a non-terminal row AND its stored SL/TP cids correspond
132
- // to live exchange orders, a fresh bracket really is active. Two sub-cases:
133
- // (a) Caller passed the SAME prices the ledger already stores → idempotent
134
- // no-op success. This is the agent's defensive re-attach pattern: it
135
- // sees a flickery audit verdict, calls attach_brackets to "repair",
136
- // passes the same stop/target it remembers from the entry. Pre-fix
137
- // this returned an error, the agent escalated to close_position
138
- // (bracket_integrity), and we lost ~$3 of bracket-integrity flushes
139
- // on 2026-05-15. With idempotency, the defensive re-call costs
140
- // nothing and the position survives.
141
- // (b) Caller passed DIFFERENT prices → they want to change levels. Point
142
- // them at modify_stop / modify_target so we don't have two paths
143
- // that mutate the bracket geometry.
144
- //
145
- // If the ledger is non-terminal but the cids do NOT match any live exchange
146
- // order, the row is stale (exchange brackets got cancelled out-of-band,
147
- // plugin restart + lost attach, etc.). Force the row terminal so
148
- // registerEntry below can seed a fresh pending_entry. Without this, stale
149
- // rows deadlock recovery: audit reports has_stop=false (no exchange match),
150
- // attach refuses (ledger says active), agent can't resolve. Incident:
151
- // 2026-04-21 ADA death loop — 12 cycles panic-closed in 3 hours.
152
- const existing = ledger.getBySymbol(position.symbol);
153
- let clearedStaleLedgerRow = false;
154
- if (existing && NON_TERMINAL_STATES.has(existing.state)) {
155
- // Tri-state classification. `unknown` means we COULD NOT positively
156
- // confirm the ledger's cids against live exchange orders — getOpenOrders
157
- // threw (429 / weight-paced / sticky cooldown), OR the row has no cids to
158
- // check (in-flight pending_entry/attaching). We must NOT collapse
159
- // "unverifiable" into "live" — doing so makes attach_brackets return
160
- // idempotent_no_op / "already active" for a position that is actually
161
- // NAKED on the exchange, and the agent files a complacent hold/protected
162
- // review on an unprotected live position. 2026-05-15 NEAR incident: a
163
- // weight-paced getOpenOrders → verifyLedgerStale safe-defaulted to "not
164
- // stale" → idempotent_no_op on an `attaching` row whose brackets were
165
- // never placed. Same null≠empty / never-coerce-unverifiable-to-a-positive-
166
- // safety-claim contract as getOpenOrders / getPositions / closePosition.
167
- const cls = await classifyLedgerVsExchange(live, position.symbol, existing.slCid, existing.tpCid);
168
- if (cls === 'unknown') {
169
- logger.warn(TAG, `CANNOT CONFIRM bracket protection for ${position.symbol}: ledger row ` +
170
- `state=${existing.state} (slCid=${existing.slCid ?? '-'}, tpCid=${existing.tpCid ?? '-'}) ` +
171
- `but getOpenOrders unavailable or no cids to verify. Refusing to claim ` +
172
- `protected; NOT clearing/reattaching (could race an in-flight attach).`);
173
- return {
174
- error: `Cannot confirm whether ${position.symbol} brackets are live on the exchange ` +
175
- `(getOpenOrders unavailable — Binance 429 / weight-paced / transient — or the ` +
176
- `ledger row is still in-flight with no cids yet). NOT assuming the position is ` +
177
- `protected and NOT reattaching this cycle. Retry on the next heartbeat. If this ` +
178
- `persists, treat the position as potentially NAKED: verify on the exchange and ` +
179
- `place a manual stop. Do NOT record a hold/protected review on the basis of this call.`,
180
- };
181
- }
182
- if (cls === 'live') {
183
- // Idempotency check: same protection levels = no-op success.
184
- if (pricesMatch(args.stop_price, existing.stopPrice)
185
- && pricesMatch(args.target_price, existing.targetPrice)) {
186
- logger.info(TAG, `idempotent no-op for ${position.symbol}: bracket already ${existing.state} ` +
187
- `at stop=${existing.stopPrice ?? 'none'} target=${existing.targetPrice ?? 'none'} ` +
188
- `(slCid=${existing.slCid ?? '-'}, tpCid=${existing.tpCid ?? '-'})`);
189
- return {
190
- ok: true,
191
- symbol: position.symbol,
192
- bracket_id: existing.bracketId,
193
- entry_side: entrySide,
194
- stop_price: existing.stopPrice,
195
- target_price: existing.targetPrice,
196
- sl_cid: existing.slCid,
197
- tp_cid: existing.tpCid,
198
- attach_latency_ms: 0,
199
- cancelled_stale_bracket_orders: 0,
200
- cleared_stale_ledger_row: false,
201
- attempts: 0,
202
- idempotent_no_op: true,
203
- note: `Bracket already ${existing.state} on exchange with matching prices — no-op. If the audit reports has_stop=false anyway, suspect audit unreliability, not protection loss.`,
204
- };
205
- }
206
- return {
207
- error: `Bracket already ${existing.state} for ${position.symbol} ` +
208
- `at stop=${formatPrice(existing.stopPrice)} target=${formatPrice(existing.targetPrice)}. ` +
209
- `Use modify_stop / modify_target to change levels, or close_position to exit.`,
210
- };
211
- }
212
- logger.warn(TAG, `Ledger row for ${position.symbol} is stale (state=${existing.state}, slCid=${existing.slCid}, tpCid=${existing.tpCid} not on exchange); forcing terminal to re-attach`);
213
- try {
214
- ledger.markState(position.symbol, 'cancelled', {
215
- closeReason: 'cancelled_auto',
216
- lastError: 'stale_ledger_detected_by_attach_brackets',
217
- });
218
- clearedStaleLedgerRow = true;
219
- }
220
- catch (err) {
221
- return { error: `failed to clear stale ledger row: ${formatError(err)}` };
222
- }
223
- }
224
- // ---- 6. Clear any stale bracket orders on the exchange for this symbol ----
225
- // The ledger row (if any) is terminal at this point; its stored SL/TP cids
226
- // may or may not still be live on the exchange. Orphan bracket orders not
227
- // tracked by the ledger may also exist. Cancel all bracket-cid orders on
228
- // this symbol so only our fresh pair remains after attach.
229
- let cancelledOrphans = 0;
230
- try {
231
- cancelledOrphans = await live.cancelSymbolBracketOrders(position.symbol);
232
- }
233
- catch (err) {
234
- logger.warn(TAG, `orphan cleanup failed for ${position.symbol}: ${formatError(err)}`);
235
- }
236
- // ---- 7. Register + attach ----
237
- // BracketManager.registerEntry auto-clears terminal rows for the same symbol
238
- // (see ledger-hygiene change landed alongside this tool).
239
- const bracketId = generateBracketId();
240
- try {
241
- mgr.registerEntry({
242
- symbol: position.symbol,
243
- side: entrySide,
244
- stopPrice: args.stop_price,
245
- targetPrice: args.target_price,
246
- }, bracketId, buildBracketCid(bracketId, 'entry'));
247
- }
248
- catch (err) {
249
- return { error: `registerEntry failed: ${formatError(err)}` };
250
- }
251
- let attachResult;
252
- try {
253
- attachResult = await mgr.attachBrackets(position.symbol, position.contracts);
254
- }
255
- catch (err) {
256
- return { error: `attachBrackets threw: ${formatError(err)}` };
257
- }
258
- if (!attachResult.ok) {
259
- return {
260
- error: `Bracket attach failed after ${attachResult.attempts} attempt(s): ${attachResult.error ?? 'unknown error'}. ` +
261
- `Position remains open. Try again with adjusted levels, or close_position to exit.`,
262
- };
263
- }
264
- return {
265
- ok: true,
266
- symbol: position.symbol,
267
- bracket_id: bracketId,
268
- entry_side: entrySide,
269
- stop_price: args.stop_price,
270
- target_price: args.target_price,
271
- sl_cid: attachResult.slCid,
272
- tp_cid: attachResult.tpCid,
273
- attach_latency_ms: attachResult.latencyMs,
274
- cancelled_stale_bracket_orders: cancelledOrphans,
275
- cleared_stale_ledger_row: clearedStaleLedgerRow || (!!existing && !NON_TERMINAL_STATES.has(existing.state)),
276
- attempts: attachResult.attempts,
277
- };
278
- }
279
- /**
280
- * Hyperliquid recovery attach (issue #209). Same safety contract as the
281
- * Binance path — null ≠ empty, positive-evidence-only destructive decisions,
282
- * idempotent no-op on a live matching bracket — expressed against the
283
- * HlBracketCoordinator. Classification is the d59e51b floor: a stored cid
284
- * positively present in a successful getOpenOrders is 'live'; a NON-EMPTY set
285
- * lacking every stored cid is 'stale'; an EMPTY set or a thrown fetch is
286
- * 'unknown' (empty is never positive disconfirmation).
287
- */
288
- async function attachBracketsHl(args, adapter) {
289
- const coordinator = adapter.getHlBracketCoordinator();
290
- const ledger = coordinator.getLedger();
291
- // ---- Position must exist (null ≠ empty) ----
292
- const positions = await adapter.getPositionsOrNull(args.symbol);
293
- if (positions === null) {
294
- return {
295
- error: `Exchange data unavailable for ${args.symbol} (Hyperliquid fetch failed / rate-gated) — ` +
296
- `position state UNKNOWN. NOT treating this as "no position"; bracket attach skipped ` +
297
- `this cycle. Retry on next heartbeat.`,
298
- };
299
- }
300
- const base = args.symbol.split(':')[0];
301
- const position = positions.find(p => p.symbol?.startsWith(base)) ?? positions[0];
302
- const contracts = Math.abs(Number(position?.contracts ?? 0));
303
- if (!position || contracts <= 0) {
304
- return { error: `No open position for ${args.symbol}.` };
305
- }
306
- const entrySide = position.side === 'long' ? 'buy' : 'sell';
307
- // ---- Direction sanity vs entry price ----
308
- const refPrice = position.entryPrice > 0 ? position.entryPrice : await adapter.getLastPrice(position.symbol);
309
- if (refPrice != null && refPrice > 0) {
310
- if (args.stop_price !== undefined) {
311
- const msg = validateStopDirection(entrySide, refPrice, args.stop_price);
312
- if (msg)
313
- return { error: msg };
314
- }
315
- if (args.target_price !== undefined) {
316
- const msg = validateTargetDirection(entrySide, refPrice, args.target_price);
317
- if (msg)
318
- return { error: msg };
319
- }
320
- }
321
- // ---- Existing ledger row: classify against the exchange ----
322
- const existing = ledger.getBySymbol(position.symbol);
323
- let clearedStaleLedgerRow = false;
324
- if (existing && !isTerminalBracketState(existing.state)) {
325
- let cls = 'unknown';
326
- const hasCids = Boolean(existing.slCid || existing.tpCid);
327
- if (hasCids) {
328
- try {
329
- const open = await adapter.getOpenOrders(position.symbol);
330
- const liveCids = new Set(open.map(o => o.clientOrderId).filter(Boolean));
331
- if ((existing.slCid && liveCids.has(existing.slCid)) || (existing.tpCid && liveCids.has(existing.tpCid))) {
332
- cls = 'live';
333
- }
334
- else if (open.length > 0) {
335
- cls = 'stale'; // non-empty set positively lacking our cids
336
- } // empty set → 'unknown' (d59e51b: empty is never disconfirmation)
337
- }
338
- catch {
339
- cls = 'unknown';
340
- }
341
- }
342
- if (cls === 'unknown') {
343
- return {
344
- error: `Cannot confirm whether ${position.symbol} brackets are live on Hyperliquid ` +
345
- `(open-orders unavailable, the set came back empty, or the row is in-flight with no ` +
346
- `cids yet). NOT assuming protected and NOT reattaching this cycle. Retry next ` +
347
- `heartbeat; if this persists treat the position as potentially NAKED and verify on ` +
348
- `the exchange. Do NOT record a hold/protected review on the basis of this call.`,
349
- };
350
- }
351
- if (cls === 'live') {
352
- if (pricesMatch(args.stop_price, existing.stopPrice)
353
- && pricesMatch(args.target_price, existing.targetPrice)) {
354
- return {
355
- ok: true,
356
- symbol: position.symbol,
357
- bracket_id: existing.bracketId,
358
- entry_side: entrySide,
359
- stop_price: existing.stopPrice,
360
- target_price: existing.targetPrice,
361
- sl_cid: existing.slCid,
362
- tp_cid: existing.tpCid,
363
- attach_latency_ms: 0,
364
- cancelled_stale_bracket_orders: 0,
365
- cleared_stale_ledger_row: false,
366
- attempts: 0,
367
- idempotent_no_op: true,
368
- note: `Bracket already ${existing.state} on exchange with matching prices — no-op.`,
369
- };
370
- }
371
- return {
372
- error: `Bracket already ${existing.state} for ${position.symbol} at ` +
373
- `stop=${existing.stopPrice ?? 'none'} target=${existing.targetPrice ?? 'none'}. ` +
374
- `Use modify_stop / modify_target to change levels, or close_position to exit.`,
375
- };
376
- }
377
- logger.warn(TAG, `HL ledger row for ${position.symbol} is stale (state=${existing.state}; stored cloids not ` +
378
- `on exchange, non-empty order set) — forcing terminal to re-attach`);
379
- ledger.markState(position.symbol, 'cancelled', {
380
- closeReason: 'cancelled_auto',
381
- lastError: 'stale_ledger_detected_by_attach_brackets',
382
- });
383
- clearedStaleLedgerRow = true;
384
- }
385
- // ---- Orphan cleanup (best-effort; protection beats hygiene) ----
386
- let cancelledOrphans = 0;
387
- try {
388
- cancelledOrphans = await adapter.cancelSymbolBracketLegs(position.symbol);
389
- }
390
- catch (err) {
391
- logger.warn(TAG, `HL orphan cleanup failed for ${position.symbol}: ${formatError(err)}`);
392
- }
393
- // ---- Register + attach ----
394
- const bracketId = generateBracketId();
395
- try {
396
- coordinator.registerEntry({
397
- symbol: position.symbol,
398
- side: entrySide,
399
- stopPrice: args.stop_price,
400
- targetPrice: args.target_price,
401
- }, bracketId, buildHlBracketCloid(bracketId, 'entry'));
402
- }
403
- catch (err) {
404
- return { error: `registerEntry failed: ${formatError(err)}` };
405
- }
406
- let attachResult;
407
- try {
408
- attachResult = await coordinator.attachOnFill(position.symbol, contracts);
409
- }
410
- catch (err) {
411
- return { error: `attach failed: ${formatError(err)}` };
412
- }
413
- if (!attachResult.ok) {
414
- return {
415
- error: `Bracket attach failed after ${attachResult.attempts} attempt(s): ` +
416
- `${attachResult.error ?? 'unknown error'}. Position remains open. Try again with ` +
417
- `adjusted levels, or close_position to exit.`,
418
- };
419
- }
420
- return {
421
- ok: true,
422
- symbol: position.symbol,
423
- bracket_id: bracketId,
424
- entry_side: entrySide,
425
- stop_price: args.stop_price,
426
- target_price: args.target_price,
427
- sl_cid: attachResult.slCid,
428
- tp_cid: attachResult.tpCid,
429
- attach_latency_ms: attachResult.latencyMs,
430
- cancelled_stale_bracket_orders: cancelledOrphans,
431
- cleared_stale_ledger_row: clearedStaleLedgerRow,
432
- attempts: attachResult.attempts,
433
- };
434
- }
435
- // Non-terminal bracket states — a row in any of these means brackets are
436
- // either in-flight or fully live; attach_brackets refuses to clobber them
437
- // UNLESS the ledger cids don't match any live exchange order (stale row).
438
- const NON_TERMINAL_STATES = new Set([
439
- 'pending_entry',
440
- 'attaching',
441
- 'active',
442
- 'partial',
443
- ]);
444
- /** Classify a non-terminal ledger row against live exchange open orders.
445
- *
446
- * - `'live'` — getOpenOrders SUCCEEDED and at least one stored cid is
447
- * positively present in the live open orders. Only this
448
- * result may produce an idempotent_no_op / "already active"
449
- * reply: protection is PROVEN on the exchange.
450
- * - `'stale'` — getOpenOrders SUCCEEDED and NONE of the stored cids are
451
- * present. The exchange definitively does not have our
452
- * brackets → clear the row and re-attach.
453
- * - `'unknown'` — we could NOT positively verify: getOpenOrders threw
454
- * (429 / weight-paced / sticky cooldown / transient), OR the
455
- * row has no cids to check (in-flight pending_entry/attaching
456
- * whose attach hasn't assigned cids yet). We must NOT treat
457
- * this as `live` (false "protected" on a possibly-naked
458
- * position — the 2026-05-15 NEAR incident) NOR as `stale`
459
- * (clearing + reattaching could race a genuine in-flight
460
- * attach and double up). The caller refuses honestly and
461
- * tells the agent to retry / verify manually.
462
- *
463
- * Same null≠empty / never-coerce-unverifiable-into-a-positive-safety-claim
464
- * contract as getOpenOrders / getPositions / closePosition / the reconciler. */
465
- async function classifyLedgerVsExchange(live, symbol, slCid, tpCid) {
466
- if (!slCid && !tpCid)
467
- return 'unknown';
468
- // Cheap positive check first: a stored cid present in a SUCCESSFUL,
469
- // non-empty getOpenOrders is immediate, zero-extra-weight proof of life.
470
- // This keeps the common happy-path free. A throw or an empty set is NOT
471
- // disconfirmation — fall through to the authoritative per-leg resolver.
472
- try {
473
- const openOrders = await live.getOpenOrders(symbol);
474
- const liveCids = new Set();
475
- for (const o of openOrders) {
476
- if (o.clientOrderId)
477
- liveCids.add(o.clientOrderId);
478
- }
479
- if ((slCid && liveCids.has(slCid)) || (tpCid && liveCids.has(tpCid))) {
480
- return 'live';
481
- }
482
- }
483
- catch (err) {
484
- logger.warn(TAG, `classifyLedgerVsExchange: getOpenOrders(${symbol}) unavailable ` +
485
- `(${formatError(err)}) — deferring to the per-leg liveness resolver, ` +
486
- `NOT assuming protected or stale`);
487
- }
488
- // No positive snapshot match (empty, threw, or non-empty-without-our-cids).
489
- // The SOL/INJ spiral root: a *successful* empty /fapi/v1/openAlgoOrders is
490
- // NOT proof a leg is gone. Ask the authoritative per-leg resolver instead
491
- // of inferring from absence — trusted-WS fast-path → weight-1 REST
492
- // /fapi/v1/algoOrder → 'unknown' floor:
493
- // any leg 'live' → 'live' (do NOT clobber)
494
- // ALL present legs 'terminal' → 'stale' (POSITIVELY confirmed gone —
495
- // the only state that licenses repair)
496
- // otherwise (any 'unknown') → 'unknown' (d59e51b safe floor)
497
- const cids = [slCid, tpCid].filter((c) => !!c);
498
- const verdicts = await Promise.all(cids.map(c => live.resolveBracketLegLiveness(c)));
499
- if (verdicts.some(v => v === 'live'))
500
- return 'live';
501
- if (verdicts.length > 0 && verdicts.every(v => v === 'terminal')) {
502
- // #2 — AUTHORITATIVE action-layer spiral guard (2026-05-16 INJ).
503
- // The LEDGER's cids are positively terminal — but that is NOT proof the
504
- // position is unprotected. A prior reattach's FRESH bracket may be live
505
- // on the exchange under a NEW cid the ledger never caught up to.
506
- // Returning 'stale' here licenses the clear+reattach that cancels that
507
- // live bracket → naked → audit unprotected → attach → spiral. Before
508
- // licensing repair, positively prove NO other rc-* leg for this symbol
509
- // is live. Only positive evidence licenses the destructive action —
510
- // same invariant as d59e51b / getOpenOrders / the reconciler.
511
- const sweep = live.findTrustedLiveBracketCidsForSymbol(symbol);
512
- if (sweep.trusted && sweep.liveCids.length > 0) {
513
- logger.warn(TAG, `classifyLedgerVsExchange: ${symbol} ledger cids (slCid=${slCid ?? '-'}, ` +
514
- `tpCid=${tpCid ?? '-'}) are terminal BUT the trusted WS shows live ` +
515
- `rc-* leg(s) under other cid(s) [${sweep.liveCids.join(', ')}] — a prior ` +
516
- `reattach's fresh bracket is live and the ledger row lagged. Returning ` +
517
- `'live' (NOT 'stale') to break the clear+reattach spiral; the position ` +
518
- `IS protected on the exchange.`);
519
- return 'live';
520
- }
521
- if (!sweep.trusted) {
522
- // WS store untrusted → we cannot rule out a live fresh bracket under
523
- // an untracked cid using the zero-weight signal, and the spiral REST
524
- // is weight-paced. Refuse the destructive 'stale' (retry next cycle);
525
- // a genuinely-naked position is still caught by the reconciler /
526
- // ALGO_UPDATE / audit backstops. Worst case is a one-cycle delayed
527
- // repair — far safer than cancelling a live bracket on a false 'stale'.
528
- logger.warn(TAG, `classifyLedgerVsExchange: ${symbol} ledger cids REST-confirmed terminal ` +
529
- `but the WS store is UNTRUSTED — cannot positively rule out a live fresh ` +
530
- `bracket under an untracked cid (weight-paced REST can't either). ` +
531
- `Returning 'unknown' (NOT 'stale'); no force-reattach this cycle.`);
532
- return 'unknown';
533
- }
534
- logger.info(TAG, `classifyLedgerVsExchange: ${symbol} legs POSITIVELY confirmed terminal ` +
535
- `via per-leg resolver AND the trusted WS shows no other live rc-* leg ` +
536
- `(slCid=${slCid ?? '-'}, tpCid=${tpCid ?? '-'}) — 'stale', safe to ` +
537
- `clear+reattach.`);
538
- return 'stale';
539
- }
540
- logger.warn(TAG, `classifyLedgerVsExchange: ${symbol} bracket liveness UNVERIFIABLE ` +
541
- `(slCid=${slCid ?? '-'}, tpCid=${tpCid ?? '-'}; verdicts=${JSON.stringify(verdicts)}) ` +
542
- `— returning 'unknown', NOT 'stale'. No force-reattach this cycle.`);
543
- return 'unknown';
544
- }
545
- /** Compare a requested price against the ledger's stored price for the same
546
- * bracket leg. Match means: both undefined (caller didn't ask for that leg
547
- * and ledger doesn't have it) OR both defined within 0.01% relative
548
- * tolerance (covers exchange rounding of trigger prices vs the operator's
549
- * request). Any other shape is a mismatch — interpret as the caller wanting
550
- * to CHANGE the level, route to modify_*. */
551
- function pricesMatch(requested, stored) {
552
- if (requested === undefined && stored === undefined)
553
- return true;
554
- if (requested === undefined || stored === undefined)
555
- return false;
556
- if (!Number.isFinite(requested) || !Number.isFinite(stored))
557
- return false;
558
- if (stored === 0)
559
- return requested === 0;
560
- return Math.abs(requested - stored) / Math.abs(stored) <= 1e-4;
561
- }
562
- function formatPrice(p) {
563
- return p === undefined ? 'none' : String(p);
564
- }
@@ -1,49 +0,0 @@
1
- import type { IExchangeAdapter } from '../exchange-adapter.js';
2
- import type { BracketState } from '../live/bracket-types.js';
3
- type ProtectionReason = 'bracket_active' | 'manual_order_protecting' | 'no_protective_order' | 'brackets_disabled' | 'stale_ledger_row' | 'ledger_terminal_no_order';
4
- interface PositionAuditEntry {
5
- symbol: string;
6
- side: 'long' | 'short';
7
- contracts: number;
8
- entry_price: number;
9
- mark_price: number;
10
- has_stop: boolean;
11
- has_target: boolean;
12
- stop_price?: number;
13
- target_price?: number;
14
- ledger_state: BracketState | 'no_ledger_row';
15
- reason: ProtectionReason;
16
- recommended_action: 'none' | 'attach_brackets' | 'close_position' | 'enable_brackets_mode';
17
- }
18
- interface AuditBracketProtectionResult {
19
- ok: true;
20
- mode: 'paper' | 'live';
21
- brackets_enabled: boolean;
22
- total_positions: number;
23
- protected_count: number;
24
- unprotected_count: number;
25
- positions: PositionAuditEntry[];
26
- }
27
- export declare function auditBracketProtectionTool(_args: Record<string, never>, deps: {
28
- adapter: IExchangeAdapter;
29
- }): Promise<AuditBracketProtectionResult | {
30
- error: string;
31
- }>;
32
- /** Public getter — returns the recent audit verdict samples for a symbol so
33
- * close_position can copy them into the position's close record for the
34
- * dashboard Position Timeline drawer. Read-only snapshot; mutating the
35
- * return value does not affect internal state. */
36
- export declare function getRecentAuditVerdictHistory(symbol: string): ReadonlyArray<{
37
- ts: number;
38
- protected: boolean;
39
- }>;
40
- /** Test seam — clears the in-memory flicker history between unit tests. */
41
- export declare const __testing__: {
42
- resetFlickerHistory(): void;
43
- /** Inspect current history for a symbol — used by tests to assert state. */
44
- getHistory(symbol: string): ReadonlyArray<{
45
- ts: number;
46
- protected: boolean;
47
- }>;
48
- };
49
- export {};