@senpi-ai/runtime 3.0.30 → 3.0.40

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 (188) hide show
  1. package/README.md +7 -4
  2. package/dist/actions/close-position/close-position.action.d.ts.map +1 -1
  3. package/dist/actions/close-position/close-position.action.js +2 -7
  4. package/dist/actions/close-position/close-position.action.js.map +1 -1
  5. package/dist/actions/decision-error-notification.d.ts +37 -0
  6. package/dist/actions/decision-error-notification.d.ts.map +1 -0
  7. package/dist/actions/decision-error-notification.js +63 -0
  8. package/dist/actions/decision-error-notification.js.map +1 -0
  9. package/dist/actions/open-position/open-position.action.d.ts.map +1 -1
  10. package/dist/actions/open-position/open-position.action.js +51 -7
  11. package/dist/actions/open-position/open-position.action.js.map +1 -1
  12. package/dist/actions/types.d.ts +2 -0
  13. package/dist/actions/types.d.ts.map +1 -1
  14. package/dist/cli/guide-commands.d.ts.map +1 -1
  15. package/dist/cli/guide-commands.js +6 -7
  16. package/dist/cli/guide-commands.js.map +1 -1
  17. package/dist/cli/senpi-cli-config.d.ts +0 -17
  18. package/dist/cli/senpi-cli-config.d.ts.map +1 -1
  19. package/dist/cli/senpi-cli-config.js +0 -30
  20. package/dist/cli/senpi-cli-config.js.map +1 -1
  21. package/dist/cli/senpi-config-commands.d.ts +1 -1
  22. package/dist/cli/senpi-config-commands.d.ts.map +1 -1
  23. package/dist/cli/senpi-config-commands.js +1 -16
  24. package/dist/cli/senpi-config-commands.js.map +1 -1
  25. package/dist/constants/dsl/index.d.ts +1 -5
  26. package/dist/constants/dsl/index.d.ts.map +1 -1
  27. package/dist/constants/dsl/index.js +1 -5
  28. package/dist/constants/dsl/index.js.map +1 -1
  29. package/dist/dsl/engine-client/event-mapping.d.ts +3 -1
  30. package/dist/dsl/engine-client/event-mapping.d.ts.map +1 -1
  31. package/dist/dsl/engine-client/event-mapping.js +9 -0
  32. package/dist/dsl/engine-client/event-mapping.js.map +1 -1
  33. package/dist/dsl/events/build-closed-event.d.ts +1 -1
  34. package/dist/dsl/events/build-closed-event.js +1 -1
  35. package/dist/dsl/events/handlers.d.ts +8 -0
  36. package/dist/dsl/events/handlers.d.ts.map +1 -1
  37. package/dist/dsl/events/handlers.js +26 -5
  38. package/dist/dsl/events/handlers.js.map +1 -1
  39. package/dist/dsl/events/initial-state.d.ts +11 -1
  40. package/dist/dsl/events/initial-state.d.ts.map +1 -1
  41. package/dist/dsl/events/initial-state.js +4 -1
  42. package/dist/dsl/events/initial-state.js.map +1 -1
  43. package/dist/dsl/monitor/process-one-position.d.ts.map +1 -1
  44. package/dist/dsl/monitor/process-one-position.js +10 -3
  45. package/dist/dsl/monitor/process-one-position.js.map +1 -1
  46. package/dist/dsl/notifications/floor-store.d.ts +16 -0
  47. package/dist/dsl/notifications/floor-store.d.ts.map +1 -0
  48. package/dist/dsl/notifications/floor-store.js +57 -0
  49. package/dist/dsl/notifications/floor-store.js.map +1 -0
  50. package/dist/dsl/notifications/format-utils.d.ts +36 -11
  51. package/dist/dsl/notifications/format-utils.d.ts.map +1 -1
  52. package/dist/dsl/notifications/format-utils.js +64 -50
  53. package/dist/dsl/notifications/format-utils.js.map +1 -1
  54. package/dist/dsl/notifications/formatter.d.ts +27 -28
  55. package/dist/dsl/notifications/formatter.d.ts.map +1 -1
  56. package/dist/dsl/notifications/formatter.js +58 -129
  57. package/dist/dsl/notifications/formatter.js.map +1 -1
  58. package/dist/dsl/notifications/index.d.ts +25 -18
  59. package/dist/dsl/notifications/index.d.ts.map +1 -1
  60. package/dist/dsl/notifications/index.js +225 -51
  61. package/dist/dsl/notifications/index.js.map +1 -1
  62. package/dist/dsl/notifications/raise-correlator.d.ts +87 -0
  63. package/dist/dsl/notifications/raise-correlator.d.ts.map +1 -0
  64. package/dist/dsl/notifications/raise-correlator.js +136 -0
  65. package/dist/dsl/notifications/raise-correlator.js.map +1 -0
  66. package/dist/dsl/notifications/stop-raise-ratchet.d.ts +76 -0
  67. package/dist/dsl/notifications/stop-raise-ratchet.d.ts.map +1 -0
  68. package/dist/dsl/notifications/stop-raise-ratchet.js +113 -0
  69. package/dist/dsl/notifications/stop-raise-ratchet.js.map +1 -0
  70. package/dist/dsl/plugin/index.d.ts.map +1 -1
  71. package/dist/dsl/plugin/index.js +5 -30
  72. package/dist/dsl/plugin/index.js.map +1 -1
  73. package/dist/dsl/plugin/options.d.ts +3 -9
  74. package/dist/dsl/plugin/options.d.ts.map +1 -1
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +16 -123
  77. package/dist/index.js.map +1 -1
  78. package/dist/prompt/session-context-seed-hook.d.ts +11 -0
  79. package/dist/prompt/session-context-seed-hook.d.ts.map +1 -0
  80. package/dist/prompt/session-context-seed-hook.js +99 -0
  81. package/dist/prompt/session-context-seed-hook.js.map +1 -0
  82. package/dist/runtime/auto-update/coordinator.d.ts +4 -5
  83. package/dist/runtime/auto-update/coordinator.d.ts.map +1 -1
  84. package/dist/runtime/auto-update/coordinator.js +18 -19
  85. package/dist/runtime/auto-update/coordinator.js.map +1 -1
  86. package/dist/runtime/backend-pause-registry.d.ts +38 -0
  87. package/dist/runtime/backend-pause-registry.d.ts.map +1 -0
  88. package/dist/runtime/backend-pause-registry.js +51 -0
  89. package/dist/runtime/backend-pause-registry.js.map +1 -0
  90. package/dist/runtime/create-action-context.d.ts.map +1 -1
  91. package/dist/runtime/create-action-context.js +1 -0
  92. package/dist/runtime/create-action-context.js.map +1 -1
  93. package/dist/runtime/create-runtime-context.d.ts +1 -0
  94. package/dist/runtime/create-runtime-context.d.ts.map +1 -1
  95. package/dist/runtime/create-runtime-context.js +3 -0
  96. package/dist/runtime/create-runtime-context.js.map +1 -1
  97. package/dist/runtime/decision-errors.d.ts +52 -53
  98. package/dist/runtime/decision-errors.d.ts.map +1 -1
  99. package/dist/runtime/decision-errors.js +77 -111
  100. package/dist/runtime/decision-errors.js.map +1 -1
  101. package/dist/runtime/lifecycle-events.d.ts +3 -1
  102. package/dist/runtime/lifecycle-events.d.ts.map +1 -1
  103. package/dist/runtime/lifecycle-events.js +3 -1
  104. package/dist/runtime/lifecycle-events.js.map +1 -1
  105. package/dist/runtime/notifications.d.ts +30 -16
  106. package/dist/runtime/notifications.d.ts.map +1 -1
  107. package/dist/runtime/notifications.js +217 -67
  108. package/dist/runtime/notifications.js.map +1 -1
  109. package/dist/runtime/risk-guard.d.ts.map +1 -1
  110. package/dist/runtime/risk-guard.js +3 -1
  111. package/dist/runtime/risk-guard.js.map +1 -1
  112. package/dist/runtime/runtime.d.ts +0 -2
  113. package/dist/runtime/runtime.d.ts.map +1 -1
  114. package/dist/runtime/runtime.js +22 -35
  115. package/dist/runtime/runtime.js.map +1 -1
  116. package/dist/runtime/strategy-lifecycle.d.ts +23 -9
  117. package/dist/runtime/strategy-lifecycle.d.ts.map +1 -1
  118. package/dist/runtime/strategy-lifecycle.js +115 -38
  119. package/dist/runtime/strategy-lifecycle.js.map +1 -1
  120. package/dist/runtime/supervisor/long-running-supervisor.js +3 -3
  121. package/dist/runtime/supervisor/long-running-supervisor.js.map +1 -1
  122. package/dist/runtime-api/lifecycle.d.ts +1 -1
  123. package/dist/runtime-api/lifecycle.js +1 -1
  124. package/dist/scanners/providers/client.d.ts.map +1 -1
  125. package/dist/scanners/providers/client.js +4 -1
  126. package/dist/scanners/providers/client.js.map +1 -1
  127. package/dist/scanners/providers/factory.d.ts.map +1 -1
  128. package/dist/scanners/providers/factory.js +43 -2
  129. package/dist/scanners/providers/factory.js.map +1 -1
  130. package/dist/scanners/runtime-module.d.ts.map +1 -1
  131. package/dist/scanners/runtime-module.js +35 -0
  132. package/dist/scanners/runtime-module.js.map +1 -1
  133. package/dist/scripts/run-dsl-standalone-live.d.ts +8 -6
  134. package/dist/scripts/run-dsl-standalone-live.d.ts.map +1 -1
  135. package/dist/scripts/run-dsl-standalone-live.js +26 -25
  136. package/dist/scripts/run-dsl-standalone-live.js.map +1 -1
  137. package/dist/senpi/client.d.ts.map +1 -1
  138. package/dist/senpi/client.js +10 -3
  139. package/dist/senpi/client.js.map +1 -1
  140. package/dist/senpi/tool-errors.d.ts +30 -0
  141. package/dist/senpi/tool-errors.d.ts.map +1 -0
  142. package/dist/senpi/tool-errors.js +87 -0
  143. package/dist/senpi/tool-errors.js.map +1 -0
  144. package/dist/senpi/types.d.ts +4 -0
  145. package/dist/senpi/types.d.ts.map +1 -1
  146. package/dist/skills-manager/coordinator.d.ts +2 -2
  147. package/dist/skills-manager/coordinator.js +2 -2
  148. package/dist/test-setup.d.ts +2 -0
  149. package/dist/test-setup.d.ts.map +1 -0
  150. package/dist/test-setup.js +21 -0
  151. package/dist/test-setup.js.map +1 -0
  152. package/dist/types/dsl/index.d.ts +36 -1
  153. package/dist/types/dsl/index.d.ts.map +1 -1
  154. package/dist/types/notification.d.ts +102 -1
  155. package/dist/types/notification.d.ts.map +1 -1
  156. package/dist/types/notification.js +30 -1
  157. package/dist/types/notification.js.map +1 -1
  158. package/dist/types/runtime.d.ts +13 -0
  159. package/dist/types/runtime.d.ts.map +1 -1
  160. package/dist/types/session-context.d.ts +19 -0
  161. package/dist/types/session-context.d.ts.map +1 -0
  162. package/dist/types/session-context.js +20 -0
  163. package/dist/types/session-context.js.map +1 -0
  164. package/dist/utils/event-catalog.d.ts +10 -0
  165. package/dist/utils/event-catalog.d.ts.map +1 -1
  166. package/dist/utils/event-catalog.js.map +1 -1
  167. package/dist/utils/logger.d.ts +2 -18
  168. package/dist/utils/logger.d.ts.map +1 -1
  169. package/dist/utils/logger.js +2 -40
  170. package/dist/utils/logger.js.map +1 -1
  171. package/openclaw.plugin.json +1 -1
  172. package/package.json +1 -1
  173. package/dist/actions/notifications/formatter.d.ts +0 -39
  174. package/dist/actions/notifications/formatter.d.ts.map +0 -1
  175. package/dist/actions/notifications/formatter.js +0 -68
  176. package/dist/actions/notifications/formatter.js.map +0 -1
  177. package/dist/actions/notifications/index.d.ts +0 -37
  178. package/dist/actions/notifications/index.d.ts.map +0 -1
  179. package/dist/actions/notifications/index.js +0 -89
  180. package/dist/actions/notifications/index.js.map +0 -1
  181. package/dist/dsl/notifications/close-resolver.d.ts +0 -92
  182. package/dist/dsl/notifications/close-resolver.d.ts.map +0 -1
  183. package/dist/dsl/notifications/close-resolver.js +0 -309
  184. package/dist/dsl/notifications/close-resolver.js.map +0 -1
  185. package/dist/dsl/notifications/types.d.ts +0 -27
  186. package/dist/dsl/notifications/types.d.ts.map +0 -1
  187. package/dist/dsl/notifications/types.js +0 -5
  188. package/dist/dsl/notifications/types.js.map +0 -1
@@ -1,35 +1,44 @@
1
1
  /**
2
- * Plain-text messages for DSL lifecycle Telegram notifications.
2
+ * In-app / push copy for DSL lifecycle notifications.
3
+ *
4
+ * In-app text carries lightweight display markup the front-end renders:
5
+ * - `<b>…</b>` bold span
6
+ * - `<pnl>${x}</pnl>` a P&L value the FE colors green/red by sign
7
+ * - `<br>` a literal line break (the FE renders it as a newline)
8
+ * The push body is ALWAYS plain text (no markup) and carries no strategy label:
9
+ * there is no push title here at all — the notification service sets it to the
10
+ * strategy/skill name it resolves from `strategyWalletAddress`, so repeating the
11
+ * name in the body would double it.
3
12
  */
4
- import { fmtUsdPrice, fmtUsdPnl, fmtRoe, fmtDuration, fmtMargin, fmtFloorDistancePct, } from "./format-utils.js";
5
- function fmtDex(dex) {
6
- return dex ? ` (${dex})` : "";
7
- }
8
- function fmtLeverage(leverage) {
9
- const n = Number.isFinite(leverage) && leverage > 0 ? leverage : 1;
10
- return `${Number.isInteger(n) ? n : n.toFixed(1)}x`;
11
- }
13
+ import { fmtUsdPrice, fmtUsdPnl, fmtRoe, fmtPosition, fmtDistancePct, } from "./format-utils.js";
12
14
  /**
13
- * User-facing line for `dsl.created`. Returns `null` when the position change should stay silent
14
- * (increase / decrease / flip rebuilds).
15
+ * DSL-activated notification — Part 2 of the position-opened pair: the runtime
16
+ * attaches a trailing DSL when it starts tracking a freshly-opened position. (Part 1,
17
+ * "position opened", is emitted by whoever opened the position.) Every value comes
18
+ * from the event.
15
19
  */
16
20
  export function formatDslCreated(e) {
17
- if (e.triggerReason !== "position_opened")
18
- return null;
19
- const dex = fmtDex(e.dex);
20
- const dist = fmtFloorDistancePct(e.entryPrice, e.floorPrice, e.direction);
21
- const lev = e.leverage != null && Number.isFinite(e.leverage) ? e.leverage : 1;
22
- const line1 = `Opened ${e.asset}${dex} ${e.direction} at ${fmtUsdPrice(e.entryPrice, e.asset)} · ${fmtLeverage(lev)} · ${fmtMargin(e.margin ?? 0)} margin`;
23
- const line2 = `DSL active: ${fmtUsdPrice(e.floorPrice, e.asset)} (${dist} from entry)`;
24
- return `${line1}\n${line2}`;
21
+ const asset = e.asset;
22
+ const position = fmtPosition(asset, e.direction, e.leverage);
23
+ // % gap between entry and the initial stop floor; abs so LONG (floor below) and
24
+ // SHORT (floor above) both read as a positive distance "away".
25
+ const distPct = Number.isFinite(e.entryPrice) && e.entryPrice !== 0
26
+ ? Math.abs((e.entryPrice - e.floorPrice) / e.entryPrice) * 100
27
+ : 0;
28
+ const dist = fmtDistancePct(distPct);
29
+ return {
30
+ pushBody: `DSL activated on ${position}`,
31
+ inApp: `<b>DSL activated on</b> ${position} — ` +
32
+ `stop at ${fmtUsdPrice(e.floorPrice, asset)} (${dist} away) — trails up as the trade gains.`,
33
+ };
25
34
  }
26
35
  /**
27
- * Tier / profit-lock notification.
36
+ * Profit-lock notification — a tier advance locked in profit. The
37
+ * A-vs-B selection lives in the subscriber (`index.ts`): this fires only when the
38
+ * tier locked profit (`lockedProfitPct > 0`). The push body carries no label.
28
39
  */
29
40
  export function formatDslTierAdvanced(e) {
30
- const dex = fmtDex(e.dex ?? "");
31
- const tierNum = e.tier + 1;
32
- const label = `T${tierNum}`;
41
+ const asset = e.asset;
33
42
  const margin = e.margin ?? 0;
34
43
  const lockedPct = e.lockedProfitPct ?? 0;
35
44
  const lockedUsd = margin * (lockedPct / 100);
@@ -37,114 +46,34 @@ export function formatDslTierAdvanced(e) {
37
46
  const hw = e.highWaterRoe ?? 0;
38
47
  const currentPnl = margin * (curRoe / 100);
39
48
  const direction = e.direction ?? "LONG";
40
- const line1 = `${e.asset}${dex} ${direction} — DSL ${label} 🔒 min ${fmtUsdPnl(lockedUsd)} (${fmtRoe(lockedPct)})`;
41
- const line2 = `Stop raised to ${fmtUsdPrice(e.newFloorPrice, e.asset)} · Current: ${fmtUsdPnl(currentPnl)} (${fmtRoe(curRoe)}) · High: ${fmtRoe(hw)}`;
42
- const line3 = `Position still live — trailing for more.`;
43
- return [line1, line2, line3].join("\n");
44
- }
45
- export function formatDslSlUpdated(e) {
46
- const dex = fmtDex(e.dex ?? "");
47
- return `DSL SL updated: ${e.asset}${dex} — ${fmtUsdPrice(e.newSLPrice, e.asset)}`;
48
- }
49
- export function formatDslClosePending(e) {
50
- return `DSL close pending: ${e.asset} (attempt ${e.attempt})`;
51
- }
52
- const CLOSE_REASON_LABEL = {
53
- exchange_sl_hit: "Exchange SL hit",
54
- dsl_breach: "DSL breach",
55
- hard_timeout: "DSL hard timeout",
56
- weak_peak_cut: "DSL weak peak cut",
57
- dead_weight_cut: "DSL dead weight cut",
58
- close_position_failed: "DSL close failed",
59
- backend_sl_triggered: "Exchange SL hit",
60
- backend_manually_closed: "Position manually closed",
61
- backend_liquidated: "Position liquidated",
62
- backend_adl: "Position auto-deleveraged",
63
- backend_deleted: "DSL deleted",
64
- backend_closed: "Position closed",
65
- manual_close: "Manual close",
66
- closed_externally: "Closed externally",
67
- flipped: "Position flipped",
68
- manual: "Manual close",
69
- dsl_deleted: "DSL removed",
70
- position_increased: "Position increased",
71
- position_decreased: "Position decreased",
72
- };
73
- export function plainEnglishCloseReason(closeReason) {
74
- return CLOSE_REASON_LABEL[closeReason] ?? closeReason.replace(/_/g, " ");
49
+ const position = fmtPosition(asset, direction, e.leverage);
50
+ return {
51
+ pushBody: `🔒 DSL locked ${fmtUsdPnl(lockedUsd)} on ${position}`,
52
+ inApp: `🔒 <b>${position} — DSL locked in ${fmtUsdPnl(lockedUsd)} (${fmtRoe(lockedPct)})</b><br>` +
53
+ `New peak ${fmtRoe(hw)}, stop now ${fmtUsdPrice(e.newFloorPrice, asset)} — ` +
54
+ `you keep at least ${fmtUsdPnl(lockedUsd)} even on a reversal. ` +
55
+ `Now <pnl>${fmtUsdPnl(currentPnl)} (${fmtRoe(curRoe)})</pnl>, still running.`,
56
+ };
75
57
  }
76
58
  /**
77
- * Context-aware close reason sentence for user-facing notifications.
78
- * Uses position context (tier reached, peak ROE, duration, profitability) to produce
79
- * a plain-English explanation rather than a generic label.
59
+ * Stop-raised notification — the DSL raised the stop but locked no
60
+ * profit yet. Both emit sites (local monitor and the backend-mapped path) carry
61
+ * leverage and the high-water price today; each is optional on the event, so the
62
+ * copy omits the `N×` / `new high` fragment cleanly rather than fabricating a
63
+ * value when a legacy emitter leaves it out. The push body carries no label.
80
64
  */
81
- function buildCloseReasonText(p, realizedPnl) {
82
- const { closeReason, currentTierIndex, peakROE } = p;
83
- if (closeReason === "dsl_breach" || closeReason === "exchange_sl_hit") {
84
- if (currentTierIndex != null && currentTierIndex >= 0) {
85
- return `DSL locked profit at T${currentTierIndex + 1} and triggered on pullback.`;
86
- }
87
- return "DSL stop triggered. Position never reached profit lock.";
88
- }
89
- if (closeReason === "hard_timeout") {
90
- const startMs = Date.parse(p.createdAt);
91
- const endMs = Date.parse(p.closedAt);
92
- const hours = Number.isFinite(startMs) && Number.isFinite(endMs)
93
- ? Math.round((endMs - startMs) / (60 * 60 * 1000))
94
- : 0;
95
- const inProfit = (realizedPnl != null ? realizedPnl : p.currentROE) >= 0;
96
- const suffix = inProfit ? " Closed in profit." : " Closed at a loss.";
97
- return `DSL timeout at ${hours}h.${suffix}`;
98
- }
99
- if (closeReason === "dead_weight_cut") {
100
- return "DSL cut — position stalled with no momentum.";
101
- }
102
- if (closeReason === "weak_peak_cut") {
103
- return `DSL cut — peaked at +${(peakROE ?? 0).toFixed(1)}% ROE then faded.`;
104
- }
105
- return plainEnglishCloseReason(closeReason);
106
- }
107
- /**
108
- * Full three-line close when trade history matched.
109
- */
110
- export function formatDslClosedEnriched(p, x) {
111
- const roePct = p.margin > 0 ? (x.realizedPnl / p.margin) * 100 : (p.currentROE ?? 0);
112
- const pnlLine = `${p.asset} ${p.direction} closed — ${fmtUsdPnl(x.realizedPnl)} (${fmtRoe(roePct)})`;
113
- const entryExit = `Entry ${fmtUsdPrice(p.entryPrice, p.asset)} → Exit ${fmtUsdPrice(x.closePx, p.asset)} · ${fmtLeverage(p.leverage)} · Held ${fmtDuration(p.createdAt, p.closedAt)}`;
114
- const feeUsd = `$${Math.abs(x.totalFees).toFixed(2)}`;
115
- const fees = `Fees: ${feeUsd} · ${buildCloseReasonText(p, x.realizedPnl)}`;
116
- return `${pnlLine}\n${entryExit}\n${fees}`;
117
- }
118
- /** Timeout path: no reliable exit PnL from history. */
119
- export function formatDslClosedFallback(p) {
120
- const line1 = `${p.asset} ${p.direction} closed`;
121
- const line2 = `Entry ${fmtUsdPrice(p.entryPrice, p.asset)} · ${fmtLeverage(p.leverage)} · Held ${fmtDuration(p.createdAt, p.closedAt)}`;
122
- const line3 = buildCloseReasonText(p);
123
- return `${line1}\n${line2}\n${line3}`;
124
- }
125
- export function formatDslDeleted(e) {
126
- const dex = fmtDex(e.dex ?? "");
127
- return `DSL deleted: ${e.asset}${dex}`;
128
- }
129
- function fmtElapsedOpen(mins) {
130
- if (!Number.isFinite(mins) || mins < 0)
131
- return "—";
132
- if (mins < 60)
133
- return `${Math.round(mins)}m`;
134
- const h = Math.floor(mins / 60);
135
- const m = Math.round(mins % 60);
136
- return m > 0 ? `${h}h ${m}m` : `${h}h`;
137
- }
138
- export function formatDslHeartbeat(e) {
139
- const dex = fmtDex(e.dex);
140
- const margin = e.margin ?? 0;
141
- const currentPnl = margin * (e.currentROE / 100);
142
- const line1 = `${e.asset}${dex} ${e.direction} active for ${fmtElapsedOpen(e.elapsedMinutes)} — ${fmtUsdPnl(currentPnl)} (${fmtRoe(e.currentROE)})`;
143
- const lockedPnl = margin * ((e.lockedProfitPct ?? 0) / 100);
144
- const lockedStatus = (e.lockedProfitPct ?? 0) > 0
145
- ? `${fmtUsdPnl(lockedPnl)} profit locked`
146
- : "No profit locked yet";
147
- const line2 = `Stop at ${fmtUsdPrice(e.floorPrice, e.asset)} · ${lockedStatus}`;
148
- return [line1, line2].join("\n");
65
+ export function formatDslSlUpdated(e) {
66
+ const asset = e.asset;
67
+ const position = fmtPosition(asset, e.direction ?? "", e.leverage);
68
+ const newSL = fmtUsdPrice(e.newSLPrice, asset);
69
+ const hwPrice = e.highWaterPrice;
70
+ const hw = typeof hwPrice === "number" && Number.isFinite(hwPrice) && hwPrice > 0
71
+ ? `new high ${fmtUsdPrice(hwPrice, asset)}, `
72
+ : "";
73
+ return {
74
+ pushBody: `${position} stop → ${newSL}`,
75
+ inApp: `<b>${position}</b> — ${hw}DSL stop raised to ${newSL}<br>` +
76
+ `Less at risk now if price pulls back.`,
77
+ };
149
78
  }
150
79
  //# sourceMappingURL=formatter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"formatter.js","sourceRoot":"","sources":["../../../src/dsl/notifications/formatter.ts"],"names":[],"mappings":"AAAA;;GAEG;AASH,OAAO,EACL,WAAW,EACX,SAAS,EACT,MAAM,EACN,WAAW,EACX,SAAS,EACT,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAE3B,SAAS,MAAM,CAAC,GAAW;IACzB,OAAO,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;AAChC,CAAC;AAED,SAAS,WAAW,CAAC,QAAgB;IACnC,MAAM,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;IACnE,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,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rD,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;IACtB,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC,SAAS,IAAI,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC;IACnE,MAAM,KAAK,GAAG,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IAC/C,MAAM,OAAO,GAAG,CAAC,CAAC,cAAc,CAAC;IACjC,MAAM,EAAE,GACN,OAAO,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC;QACpE,CAAC,CAAC,YAAY,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI;QAC7C,CAAC,CAAC,EAAE,CAAC;IACT,OAAO;QACL,QAAQ,EAAE,GAAG,QAAQ,WAAW,KAAK,EAAE;QACvC,KAAK,EACH,MAAM,QAAQ,UAAU,EAAE,sBAAsB,KAAK,MAAM;YAC3D,uCAAuC;KAC1C,CAAC;AACJ,CAAC"}
@@ -2,25 +2,32 @@
2
2
  * Subscribes to DSL_EVENTS on the bus and forwards formatted strings to NotificationService.
3
3
  */
4
4
  import type { SenpiEventBus } from "../events/index.js";
5
- import type { NotificationService } from "../../types/notification.js";
6
- import { type CloseNotificationResolver } from "./close-resolver.js";
7
- export type { CloseNotificationResolver } from "./close-resolver.js";
8
- export interface DslNotificationOptions {
9
- /** Also notify when the exchange SL price is updated (can fire every tick; default: false). */
10
- notifySlUpdates?: boolean;
11
- /**
12
- * Recipe name to prefix every notification message (e.g. "[my-recipe] DSL started: ...").
13
- * When omitted, no prefix is added.
14
- */
15
- strategyName?: string;
16
- /**
17
- * Resolves deferred close lines from trade history; when set, `dsl.closed` is enqueued instead of
18
- * notifying immediately.
19
- */
20
- closeResolver?: CloseNotificationResolver | null;
21
- }
5
+ import type { NotificationPayload, NotificationService } from "../../types/notification.js";
22
6
  export interface DslNotificationSubscriber {
23
7
  dispose(): void;
24
8
  }
25
- export declare function createDslNotificationSubscriber(bus: SenpiEventBus, notifier: NotificationService, options?: DslNotificationOptions): DslNotificationSubscriber;
9
+ export declare function safeNotify(notifier: NotificationService, input: string | NotificationPayload): void;
10
+ /**
11
+ * Persisted per-position notification baseline, backed by the DSL state manager.
12
+ * Optional: when absent (e.g. standalone/dev wiring or a bare test), the
13
+ * subscriber falls back to the in-memory ratchet alone and behaves exactly as
14
+ * before. When present it makes a retreat impossible to re-announce across a
15
+ * rebuild (fresh correlationId) or a process restart.
16
+ */
17
+ export interface DslNotifiedFloorStore {
18
+ /** Most-favorable floor already announced for this position, or undefined if none. */
19
+ getLastNotifiedStopFloor(ev: {
20
+ address: string;
21
+ asset: string;
22
+ }): Promise<number | undefined>;
23
+ /**
24
+ * Record `floor` as announced, advancing the persisted baseline favorably only
25
+ * (higher LONG / lower SHORT). A no-op when it would retreat the baseline.
26
+ */
27
+ stampNotifiedStopFloor(ev: {
28
+ address: string;
29
+ asset: string;
30
+ }, floor: number, direction: "LONG" | "SHORT"): Promise<void>;
31
+ }
32
+ export declare function createDslNotificationSubscriber(bus: SenpiEventBus, notifier: NotificationService, store?: DslNotifiedFloorStore): DslNotificationSubscriber;
26
33
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/dsl/notifications/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAmBvE,OAAO,EAA8B,KAAK,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAIjG,YAAY,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAErE,MAAM,WAAW,sBAAsB;IACrC,+FAA+F;IAC/F,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;OAGG;IACH,YAAY,CA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K3B"}
@@ -3,19 +3,118 @@
3
3
  */
4
4
  import { DSL_EVENTS } from "../../constants/dsl/index.js";
5
5
  import { createLogger } from "../../utils/logger.js";
6
- import { formatDslCreated, formatDslTierAdvanced, formatDslSlUpdated, formatDslClosePending, formatDslClosedFallback, formatDslDeleted, formatDslHeartbeat, } from "./formatter.js";
7
- import { buildPendingCloseFromEvent } from "./close-resolver.js";
6
+ import { randomUUID } from "node:crypto";
7
+ import { formatDslCreated, formatDslTierAdvanced, formatDslSlUpdated, } from "./formatter.js";
8
+ import { RaiseCorrelator, raiseKey } from "./raise-correlator.js";
9
+ import { StopRaiseRatchet } from "./stop-raise-ratchet.js";
10
+ /**
11
+ * Baseline key for the favorable-floor ratchet. Prefer the instance-scoped
12
+ * `correlationId` (fresh per DSL rebuild → auto-resets the baseline); fall back
13
+ * to the cross-flow position key so a missing id never collapses distinct
14
+ * positions onto one bucket.
15
+ */
16
+ function ratchetKey(ev) {
17
+ if (ev.correlationId != null && ev.correlationId !== "")
18
+ return ev.correlationId;
19
+ return raiseKey(ev);
20
+ }
8
21
  const logger = createLogger("[senpi-core][dsl-notifications]");
9
- function safeNotify(notifier, message) {
22
+ export function safeNotify(notifier, input) {
10
23
  try {
11
- const result = notifier.notify(message);
24
+ const result = notifier.notify(input);
12
25
  if (result != null && typeof result.then === "function") {
13
- void result.catch((err) => logger.warn("[dsl-notifications] notify rejected", { err, message }));
26
+ void result.catch((err) => logger.warn("[dsl-notifications] notify rejected", { err, input }));
14
27
  }
15
28
  }
16
29
  catch (err) {
17
- logger.warn("[dsl-notifications] notify threw synchronously", { err, message });
30
+ logger.warn("[dsl-notifications] notify threw synchronously", { err, input });
31
+ }
32
+ }
33
+ /**
34
+ * Builds the notification payload for a runtime-emitted trailing-stop event
35
+ * (profit-lock / stop-raise). Because the runtime holds the strategy context for
36
+ * the position, these open an agent chat by category alone — no order id and no
37
+ * lifecycle reason is consulted. The generic seed lives inside `context` (the
38
+ * notification service persists `context` verbatim and reads `context.contextText`
39
+ * from it; a sibling on the payload root is dropped before the wire).
40
+ *
41
+ * `strategyWalletAddress` is set from the same address but is NOT tied to
42
+ * openability — the notification service resolves the strategy/skill name from
43
+ * it, so it ships whenever the address is known.
44
+ *
45
+ * Fail-safe: without a strategy address the chat has nothing to key on (a dead
46
+ * tap), so we WARN and ship the message non-openable rather than an empty seed.
47
+ */
48
+ function buildOpenablePayload(copy, subtype, address, createdAt, asset, dex, dedupe) {
49
+ const message = copy.inApp;
50
+ // Content-derived dedupe (DSL trailing-stop family): forwarded verbatim so the
51
+ // ingest collapses near-duplicate alerts for the same real-world raise. Applied
52
+ // on BOTH the openable and non-openable paths — dedupe is orthogonal to whether
53
+ // the notification can open a chat.
54
+ const dedupeFields = dedupe
55
+ ? { uniqueKeys: dedupe.uniqueKeys, idempotencyKey: dedupe.idempotencyKey }
56
+ : {};
57
+ const strategyWalletAddress = address?.trim() ? address.trim() : undefined;
58
+ // A blank (empty or whitespace-only) address is as unusable a chat key as a
59
+ // missing one, so it takes the same non-openable path.
60
+ if (strategyWalletAddress === undefined) {
61
+ logger.warn("[dsl-notifications] openable notification missing strategy address; delivering non-openable", {
62
+ subtype,
63
+ });
64
+ return { message, canOpenAgentChat: false, subtype, copy, ...dedupeFields };
18
65
  }
66
+ return {
67
+ message,
68
+ canOpenAgentChat: true,
69
+ subtype,
70
+ copy,
71
+ strategyWalletAddress,
72
+ ...dedupeFields,
73
+ context: {
74
+ notificationId: randomUUID(),
75
+ subtype,
76
+ createdAt,
77
+ address,
78
+ asset,
79
+ dex,
80
+ contextText: message,
81
+ },
82
+ };
83
+ }
84
+ /**
85
+ * Content-derived dedupe key for the "Stop raised" family. Two runtime processes
86
+ * monitoring the same wallet (or a mid-trading rebuild) each mint their own
87
+ * `notificationId`, so the row id can never collapse a semantic duplicate — this
88
+ * key can. The `newSLPrice` component is stringified WITHOUT rounding: two
89
+ * genuinely different raises differ in price and must stay distinct.
90
+ */
91
+ function stopRaiseUniqueKey(ev) {
92
+ // The SL-updated event carries no book, so the `dex` slot is always empty here
93
+ // (kept in the key shape for symmetry with the profit-lock key).
94
+ return `dsl-stop-raise:${ev.address}:${ev.asset}::${ev.direction ?? ""}:${ev.newSLPrice}`;
95
+ }
96
+ /**
97
+ * Content-derived dedupe key for the "Profit locked" family, keyed on the locked
98
+ * floor (price). Same rationale as {@link stopRaiseUniqueKey}; the floor is
99
+ * stringified without rounding so distinct locks stay distinct.
100
+ */
101
+ function profitLockUniqueKey(ev) {
102
+ return `dsl-profit-lock:${ev.address}:${ev.asset}:${ev.dex ?? ""}:${ev.direction ?? ""}:${ev.newFloorPrice}`;
103
+ }
104
+ /**
105
+ * Is `floor` strictly more favorable than a persisted baseline (higher for LONG,
106
+ * lower for SHORT)? A missing baseline or an unjudgeable direction is permissive
107
+ * (returns true) — the in-memory ratchet remains the primary gate; this only ADDS
108
+ * cross-rebuild/restart suppression.
109
+ */
110
+ function beatsPersistedFloor(floor, baseline, direction) {
111
+ if (baseline === undefined)
112
+ return true;
113
+ if (direction === "LONG")
114
+ return floor > baseline;
115
+ if (direction === "SHORT")
116
+ return floor < baseline;
117
+ return true;
19
118
  }
20
119
  /** Ensures formatter + notify never throw back into `bus.emit` (would break DSL callers). */
21
120
  function runNotificationHandler(fn) {
@@ -26,76 +125,151 @@ function runNotificationHandler(fn) {
26
125
  logger.warn("[dsl-notifications] handler error (isolated from DSL)", { err });
27
126
  }
28
127
  }
29
- export function createDslNotificationSubscriber(bus, notifier, options) {
30
- const notifySlUpdates = options?.notifySlUpdates ?? false;
31
- const prefix = options?.strategyName ? `[${options.strategyName}] ` : "";
32
- const closeResolver = options?.closeResolver ?? null;
33
- function notify(message) {
34
- safeNotify(notifier, `${prefix}${message}`);
128
+ export function createDslNotificationSubscriber(bus, notifier, store) {
129
+ function notify(input) {
130
+ safeNotify(notifier, input);
35
131
  }
132
+ /** Fire-and-forget persisted-baseline stamp; never throws back into a handler. */
133
+ function stampFloor(ev, floor, direction) {
134
+ if (store === undefined || (direction !== "LONG" && direction !== "SHORT"))
135
+ return;
136
+ void store
137
+ .stampNotifiedStopFloor(ev, floor, direction)
138
+ .catch((err) => logger.warn("[dsl-notifications] failed to stamp lastNotifiedStopFloor", { err }));
139
+ }
140
+ // PF-2: a single DSL raise must yield EITHER "Profit locked" OR "Stop raised",
141
+ // never both. When a tier advance locks profit (lockedProfitPct > 0) it emits
142
+ // Profit locked and records intent here; the paired SL_UPDATED for the same
143
+ // raise is then suppressed. A tier that locks nothing (<= 0) emits no
144
+ // Profit-locked message and lets its stop-raise through. See RaiseCorrelator.
145
+ const correlator = new RaiseCorrelator();
146
+ // Gate "Stop raised" to GENUINE raises only. Keeps, per position instance, the
147
+ // most-favorable exchange-SL floor seen; fires only when a new floor beats it
148
+ // in the favorable direction. Suppresses the initial placement and every
149
+ // non-raise SL_UPDATED (tier-reset / lock_hw_pct retreat / backend re-anchor).
150
+ // Sits alongside the PF-2 correlator; the two gates are independent (this one
151
+ // is additional).
152
+ const stopRaiseRatchet = new StopRaiseRatchet();
153
+ // DSL attached at position open → "DSL activated". Gated to fresh opens only:
154
+ // resize/flip/rebuild (position_increased/decreased/flipped/adopted) re-emit
155
+ // dsl.created for bookkeeping but must not re-announce activation.
36
156
  const onCreated = (e) => {
37
157
  runNotificationHandler(() => {
38
- const text = formatDslCreated(e);
39
- if (text == null)
158
+ const ev = e;
159
+ if (ev.triggerReason !== "position_opened") {
160
+ logger.debug("[dsl-notifications] dsl.created ignored: not a fresh open", {
161
+ asset: ev.asset,
162
+ triggerReason: ev.triggerReason,
163
+ });
40
164
  return;
41
- notify(text);
165
+ }
166
+ const copy = formatDslCreated(ev);
167
+ notify(buildOpenablePayload(copy, "DSL_ACTIVATED", ev.address, ev.timestamp, ev.asset, ev.dex));
42
168
  });
43
169
  };
44
170
  const onTierAdvanced = (e) => {
45
171
  runNotificationHandler(() => {
46
- notify(formatDslTierAdvanced(e));
172
+ const ev = e;
173
+ const key = raiseKey(ev);
174
+ // lockedUSD > 0 ⟺ lockedProfitPct > 0 (lockedUSD = margin * pct/100, margin >= 0).
175
+ if ((ev.lockedProfitPct ?? 0) > 0) {
176
+ correlator.recordProfitLock(key, ev.timestamp);
177
+ const copy = formatDslTierAdvanced(ev);
178
+ notify(buildOpenablePayload(copy, "DSL_PROFIT_LOCK", ev.address, ev.timestamp, ev.asset, ev.dex, {
179
+ uniqueKeys: [profitLockUniqueKey(ev)],
180
+ idempotencyKey: profitLockUniqueKey(ev),
181
+ }));
182
+ // Announcing this locked floor advances the persisted baseline, so the
183
+ // paired (correlator-suppressed) SL and any later re-anchor at/below it
184
+ // cannot re-fire as a fresh raise across a rebuild or restart.
185
+ stampFloor({ address: ev.address, asset: ev.asset }, ev.newFloorPrice, ev.direction);
186
+ }
187
+ else {
188
+ // Else branch: nothing locked ("+$0.00"). Suppress the Profit-locked
189
+ // message and clear any stale marker so the paired stop-raise emits.
190
+ correlator.clear(key);
191
+ logger.debug("[dsl-notifications] tier advance locked no profit; deferring to stop-raise", {
192
+ asset: ev.asset,
193
+ });
194
+ }
47
195
  });
48
196
  };
197
+ /** Emit the "Stop raised" notification and stamp the persisted announced floor. */
198
+ function sendStopRaise(ev) {
199
+ const copy = formatDslSlUpdated(ev);
200
+ // The SL-updated event carries no book, so the seed omits `dex`.
201
+ notify(buildOpenablePayload(copy, "DSL_STOP_RAISE", ev.address, ev.timestamp, ev.asset, undefined, {
202
+ uniqueKeys: [stopRaiseUniqueKey(ev)],
203
+ idempotencyKey: stopRaiseUniqueKey(ev),
204
+ }));
205
+ stampFloor({ address: ev.address, asset: ev.asset }, ev.newSLPrice, ev.direction);
206
+ }
49
207
  const onSlUpdated = (e) => {
50
- if (!notifySlUpdates)
51
- return;
52
- runNotificationHandler(() => {
53
- notify(formatDslSlUpdated(e));
54
- });
55
- };
56
- const onClosePending = (e) => {
57
- runNotificationHandler(() => {
58
- notify(formatDslClosePending(e));
59
- });
60
- };
61
- const onClosed = (e) => {
62
208
  runNotificationHandler(() => {
63
209
  const ev = e;
64
- if (closeResolver) {
65
- void closeResolver.enqueue(ev).catch((err) => logger.warn("[dsl-notifications] close enqueue failed", { err }));
210
+ // Ratchet the per-instance baseline FIRST — unconditionally, before any
211
+ // suppression — so a correlator-suppressed profit-lock still advances the
212
+ // most-favorable floor. `isGenuineRaise` is judged against the PRIOR
213
+ // baseline (before this advance).
214
+ const isGenuineRaise = stopRaiseRatchet.evaluate(ratchetKey(ev), ev.newSLPrice, ev.direction);
215
+ if (correlator.shouldSuppressStopRaise(raiseKey(ev), ev.timestamp)) {
216
+ logger.debug("[dsl-notifications] stop-raise suppressed: same raise already sent Profit locked", {
217
+ asset: ev.asset,
218
+ });
66
219
  return;
67
220
  }
68
- const pending = buildPendingCloseFromEvent(ev, "immediate");
69
- notify(formatDslClosedFallback(pending));
70
- });
71
- };
72
- const onDeleted = (e) => {
73
- runNotificationHandler(() => {
74
- notify(formatDslDeleted(e));
75
- });
76
- };
77
- const onHeartbeat = (e) => {
78
- runNotificationHandler(() => {
79
- notify(formatDslHeartbeat(e));
221
+ if (!isGenuineRaise) {
222
+ logger.debug("[dsl-notifications] stop-raise suppressed: placement or non-raise SL_UPDATED", {
223
+ asset: ev.asset,
224
+ newSLPrice: ev.newSLPrice,
225
+ direction: ev.direction,
226
+ });
227
+ return;
228
+ }
229
+ // The in-memory ratchet passed. Without a persisted store, deliver now —
230
+ // identical to the pre-baseline behavior (fully synchronous).
231
+ if (store === undefined) {
232
+ sendStopRaise(ev);
233
+ return;
234
+ }
235
+ // With a store, add a cross-rebuild/restart gate: the in-memory ratchet
236
+ // resets on every rebuild (fresh correlationId) and on restart, so a LOWER
237
+ // stop could otherwise re-fire. Suppress unless the new floor is strictly
238
+ // MORE favorable than the last floor we actually ANNOUNCED (persisted).
239
+ void (async () => {
240
+ try {
241
+ const baseline = await store.getLastNotifiedStopFloor({ address: ev.address, asset: ev.asset });
242
+ if (!beatsPersistedFloor(ev.newSLPrice, baseline, ev.direction)) {
243
+ logger.debug("[dsl-notifications] stop-raise suppressed: not beyond persisted announced floor", {
244
+ asset: ev.asset,
245
+ newSLPrice: ev.newSLPrice,
246
+ baseline,
247
+ direction: ev.direction,
248
+ });
249
+ return;
250
+ }
251
+ sendStopRaise(ev);
252
+ }
253
+ catch (err) {
254
+ logger.warn("[dsl-notifications] persisted stop-raise gate error (delivering isolated)", { err });
255
+ }
256
+ })();
80
257
  });
81
258
  };
259
+ // DSL_EVENTS.DELETED and DSL_EVENTS.HEARTBEAT are intentionally not
260
+ // subscribed here: both were pure lifecycle/periodic pings with no
261
+ // notification subtype (unroutable to a preference bucket). The bus events
262
+ // themselves still fire for other consumers (e.g. dev/telemetry logging in
263
+ // src/scripts/run-dsl-standalone-*.ts); only the notify() forwarding was
264
+ // removed.
82
265
  bus.on(DSL_EVENTS.CREATED, onCreated);
83
266
  bus.on(DSL_EVENTS.TIER_ADVANCED, onTierAdvanced);
84
267
  bus.on(DSL_EVENTS.SL_UPDATED, onSlUpdated);
85
- bus.on(DSL_EVENTS.CLOSE_PENDING, onClosePending);
86
- bus.on(DSL_EVENTS.CLOSED, onClosed);
87
- bus.on(DSL_EVENTS.DELETED, onDeleted);
88
- bus.on(DSL_EVENTS.HEARTBEAT, onHeartbeat);
89
268
  return {
90
269
  dispose() {
91
270
  bus.off(DSL_EVENTS.CREATED, onCreated);
92
271
  bus.off(DSL_EVENTS.TIER_ADVANCED, onTierAdvanced);
93
272
  bus.off(DSL_EVENTS.SL_UPDATED, onSlUpdated);
94
- bus.off(DSL_EVENTS.CLOSE_PENDING, onClosePending);
95
- bus.off(DSL_EVENTS.CLOSED, onClosed);
96
- bus.off(DSL_EVENTS.DELETED, onDeleted);
97
- bus.off(DSL_EVENTS.HEARTBEAT, onHeartbeat);
98
- closeResolver?.stop();
99
273
  },
100
274
  };
101
275
  }