@senpi-ai/runtime 3.0.13 → 3.0.35

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 (198) 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 +35 -0
  6. package/dist/actions/decision-error-notification.d.ts.map +1 -0
  7. package/dist/actions/decision-error-notification.js +58 -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 +50 -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/approvals/approval-store.d.ts +35 -0
  15. package/dist/approvals/approval-store.d.ts.map +1 -0
  16. package/dist/approvals/approval-store.js +87 -0
  17. package/dist/approvals/approval-store.js.map +1 -0
  18. package/dist/approvals/manifest.d.ts +47 -0
  19. package/dist/approvals/manifest.d.ts.map +1 -0
  20. package/dist/approvals/manifest.js +90 -0
  21. package/dist/approvals/manifest.js.map +1 -0
  22. package/dist/approvals/telemetry.d.ts +41 -0
  23. package/dist/approvals/telemetry.d.ts.map +1 -0
  24. package/dist/approvals/telemetry.js +35 -0
  25. package/dist/approvals/telemetry.js.map +1 -0
  26. package/dist/approvals/tool-approval-gate.d.ts +96 -0
  27. package/dist/approvals/tool-approval-gate.d.ts.map +1 -0
  28. package/dist/approvals/tool-approval-gate.js +233 -0
  29. package/dist/approvals/tool-approval-gate.js.map +1 -0
  30. package/dist/approvals/tool-approvals-manifest.json +27 -0
  31. package/dist/cli/guide-commands.d.ts.map +1 -1
  32. package/dist/cli/guide-commands.js +6 -7
  33. package/dist/cli/guide-commands.js.map +1 -1
  34. package/dist/cli/senpi-cli-config.d.ts +0 -17
  35. package/dist/cli/senpi-cli-config.d.ts.map +1 -1
  36. package/dist/cli/senpi-cli-config.js +0 -30
  37. package/dist/cli/senpi-cli-config.js.map +1 -1
  38. package/dist/cli/senpi-config-commands.d.ts +1 -1
  39. package/dist/cli/senpi-config-commands.d.ts.map +1 -1
  40. package/dist/cli/senpi-config-commands.js +1 -16
  41. package/dist/cli/senpi-config-commands.js.map +1 -1
  42. package/dist/constants/dsl/index.d.ts +1 -5
  43. package/dist/constants/dsl/index.d.ts.map +1 -1
  44. package/dist/constants/dsl/index.js +1 -5
  45. package/dist/constants/dsl/index.js.map +1 -1
  46. package/dist/dsl/engine-client/event-mapping.d.ts +1 -1
  47. package/dist/dsl/engine-client/event-mapping.d.ts.map +1 -1
  48. package/dist/dsl/engine-client/event-mapping.js +6 -0
  49. package/dist/dsl/engine-client/event-mapping.js.map +1 -1
  50. package/dist/dsl/events/build-closed-event.d.ts +1 -1
  51. package/dist/dsl/events/build-closed-event.js +1 -1
  52. package/dist/dsl/events/handlers.js +1 -1
  53. package/dist/dsl/monitor/process-one-position.d.ts.map +1 -1
  54. package/dist/dsl/monitor/process-one-position.js +5 -3
  55. package/dist/dsl/monitor/process-one-position.js.map +1 -1
  56. package/dist/dsl/notifications/format-utils.d.ts +1 -11
  57. package/dist/dsl/notifications/format-utils.d.ts.map +1 -1
  58. package/dist/dsl/notifications/format-utils.js +1 -48
  59. package/dist/dsl/notifications/format-utils.js.map +1 -1
  60. package/dist/dsl/notifications/formatter.d.ts +17 -28
  61. package/dist/dsl/notifications/formatter.d.ts.map +1 -1
  62. package/dist/dsl/notifications/formatter.js +46 -129
  63. package/dist/dsl/notifications/formatter.js.map +1 -1
  64. package/dist/dsl/notifications/index.d.ts +2 -10
  65. package/dist/dsl/notifications/index.d.ts.map +1 -1
  66. package/dist/dsl/notifications/index.js +127 -50
  67. package/dist/dsl/notifications/index.js.map +1 -1
  68. package/dist/dsl/notifications/raise-correlator.d.ts +87 -0
  69. package/dist/dsl/notifications/raise-correlator.d.ts.map +1 -0
  70. package/dist/dsl/notifications/raise-correlator.js +136 -0
  71. package/dist/dsl/notifications/raise-correlator.js.map +1 -0
  72. package/dist/dsl/notifications/stop-raise-ratchet.d.ts +76 -0
  73. package/dist/dsl/notifications/stop-raise-ratchet.d.ts.map +1 -0
  74. package/dist/dsl/notifications/stop-raise-ratchet.js +113 -0
  75. package/dist/dsl/notifications/stop-raise-ratchet.js.map +1 -0
  76. package/dist/dsl/plugin/index.d.ts.map +1 -1
  77. package/dist/dsl/plugin/index.js +0 -27
  78. package/dist/dsl/plugin/index.js.map +1 -1
  79. package/dist/dsl/plugin/options.d.ts +3 -7
  80. package/dist/dsl/plugin/options.d.ts.map +1 -1
  81. package/dist/index.d.ts +15 -0
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +70 -142
  84. package/dist/index.js.map +1 -1
  85. package/dist/prompt/session-context-seed-hook.d.ts +11 -0
  86. package/dist/prompt/session-context-seed-hook.d.ts.map +1 -0
  87. package/dist/prompt/session-context-seed-hook.js +99 -0
  88. package/dist/prompt/session-context-seed-hook.js.map +1 -0
  89. package/dist/runtime/auto-update/coordinator.d.ts +39 -15
  90. package/dist/runtime/auto-update/coordinator.d.ts.map +1 -1
  91. package/dist/runtime/auto-update/coordinator.js +152 -34
  92. package/dist/runtime/auto-update/coordinator.js.map +1 -1
  93. package/dist/runtime/auto-update/gateway-restart.d.ts +4 -4
  94. package/dist/runtime/auto-update/gateway-restart.js +4 -4
  95. package/dist/runtime/auto-update/types.d.ts +1 -0
  96. package/dist/runtime/auto-update/types.d.ts.map +1 -1
  97. package/dist/runtime/auto-update/types.js.map +1 -1
  98. package/dist/runtime/backend-pause-registry.d.ts +38 -0
  99. package/dist/runtime/backend-pause-registry.d.ts.map +1 -0
  100. package/dist/runtime/backend-pause-registry.js +51 -0
  101. package/dist/runtime/backend-pause-registry.js.map +1 -0
  102. package/dist/runtime/create-action-context.d.ts.map +1 -1
  103. package/dist/runtime/create-action-context.js +1 -0
  104. package/dist/runtime/create-action-context.js.map +1 -1
  105. package/dist/runtime/create-runtime-context.d.ts +1 -0
  106. package/dist/runtime/create-runtime-context.d.ts.map +1 -1
  107. package/dist/runtime/create-runtime-context.js +3 -0
  108. package/dist/runtime/create-runtime-context.js.map +1 -1
  109. package/dist/runtime/decision-errors.d.ts +46 -53
  110. package/dist/runtime/decision-errors.d.ts.map +1 -1
  111. package/dist/runtime/decision-errors.js +72 -111
  112. package/dist/runtime/decision-errors.js.map +1 -1
  113. package/dist/runtime/notifications.d.ts +37 -16
  114. package/dist/runtime/notifications.d.ts.map +1 -1
  115. package/dist/runtime/notifications.js +211 -67
  116. package/dist/runtime/notifications.js.map +1 -1
  117. package/dist/runtime/runtime.d.ts +16 -2
  118. package/dist/runtime/runtime.d.ts.map +1 -1
  119. package/dist/runtime/runtime.js +109 -31
  120. package/dist/runtime/runtime.js.map +1 -1
  121. package/dist/runtime/strategy-lifecycle.d.ts +23 -9
  122. package/dist/runtime/strategy-lifecycle.d.ts.map +1 -1
  123. package/dist/runtime/strategy-lifecycle.js +90 -38
  124. package/dist/runtime/strategy-lifecycle.js.map +1 -1
  125. package/dist/runtime/supervisor/long-running-supervisor.js +3 -3
  126. package/dist/runtime/supervisor/long-running-supervisor.js.map +1 -1
  127. package/dist/runtime-api/lifecycle.d.ts +1 -1
  128. package/dist/runtime-api/lifecycle.js +1 -1
  129. package/dist/scanners/providers/client.d.ts.map +1 -1
  130. package/dist/scanners/providers/client.js +4 -1
  131. package/dist/scanners/providers/client.js.map +1 -1
  132. package/dist/scanners/providers/factory.d.ts.map +1 -1
  133. package/dist/scanners/providers/factory.js +43 -2
  134. package/dist/scanners/providers/factory.js.map +1 -1
  135. package/dist/scanners/runtime-module.d.ts.map +1 -1
  136. package/dist/scanners/runtime-module.js +35 -0
  137. package/dist/scanners/runtime-module.js.map +1 -1
  138. package/dist/scripts/run-dsl-standalone-live.d.ts +8 -6
  139. package/dist/scripts/run-dsl-standalone-live.d.ts.map +1 -1
  140. package/dist/scripts/run-dsl-standalone-live.js +26 -25
  141. package/dist/scripts/run-dsl-standalone-live.js.map +1 -1
  142. package/dist/senpi/client.d.ts.map +1 -1
  143. package/dist/senpi/client.js +10 -3
  144. package/dist/senpi/client.js.map +1 -1
  145. package/dist/senpi/tool-errors.d.ts +30 -0
  146. package/dist/senpi/tool-errors.d.ts.map +1 -0
  147. package/dist/senpi/tool-errors.js +87 -0
  148. package/dist/senpi/tool-errors.js.map +1 -0
  149. package/dist/senpi/types.d.ts +4 -0
  150. package/dist/senpi/types.d.ts.map +1 -1
  151. package/dist/skills-manager/coordinator.d.ts +2 -2
  152. package/dist/skills-manager/coordinator.js +2 -2
  153. package/dist/telemetry/metrics.d.ts +11 -0
  154. package/dist/telemetry/metrics.d.ts.map +1 -1
  155. package/dist/telemetry/metrics.js +22 -0
  156. package/dist/telemetry/metrics.js.map +1 -1
  157. package/dist/test-setup.d.ts +2 -0
  158. package/dist/test-setup.d.ts.map +1 -0
  159. package/dist/test-setup.js +21 -0
  160. package/dist/test-setup.js.map +1 -0
  161. package/dist/types/dsl/index.d.ts +14 -1
  162. package/dist/types/dsl/index.d.ts.map +1 -1
  163. package/dist/types/notification.d.ts +102 -1
  164. package/dist/types/notification.d.ts.map +1 -1
  165. package/dist/types/notification.js +80 -1
  166. package/dist/types/notification.js.map +1 -1
  167. package/dist/types/runtime.d.ts +13 -0
  168. package/dist/types/runtime.d.ts.map +1 -1
  169. package/dist/types/session-context.d.ts +19 -0
  170. package/dist/types/session-context.d.ts.map +1 -0
  171. package/dist/types/session-context.js +20 -0
  172. package/dist/types/session-context.js.map +1 -0
  173. package/dist/utils/event-catalog.d.ts +103 -2
  174. package/dist/utils/event-catalog.d.ts.map +1 -1
  175. package/dist/utils/event-catalog.js +28 -0
  176. package/dist/utils/event-catalog.js.map +1 -1
  177. package/dist/utils/logger.d.ts +2 -18
  178. package/dist/utils/logger.d.ts.map +1 -1
  179. package/dist/utils/logger.js +2 -40
  180. package/dist/utils/logger.js.map +1 -1
  181. package/openclaw.plugin.json +10 -1
  182. package/package.json +3 -2
  183. package/dist/actions/notifications/formatter.d.ts +0 -39
  184. package/dist/actions/notifications/formatter.d.ts.map +0 -1
  185. package/dist/actions/notifications/formatter.js +0 -68
  186. package/dist/actions/notifications/formatter.js.map +0 -1
  187. package/dist/actions/notifications/index.d.ts +0 -37
  188. package/dist/actions/notifications/index.d.ts.map +0 -1
  189. package/dist/actions/notifications/index.js +0 -89
  190. package/dist/actions/notifications/index.js.map +0 -1
  191. package/dist/dsl/notifications/close-resolver.d.ts +0 -92
  192. package/dist/dsl/notifications/close-resolver.d.ts.map +0 -1
  193. package/dist/dsl/notifications/close-resolver.js +0 -309
  194. package/dist/dsl/notifications/close-resolver.js.map +0 -1
  195. package/dist/dsl/notifications/types.d.ts +0 -27
  196. package/dist/dsl/notifications/types.d.ts.map +0 -1
  197. package/dist/dsl/notifications/types.js +0 -5
  198. package/dist/dsl/notifications/types.js.map +0 -1
@@ -1,92 +1,236 @@
1
+ import { toPayload, truncateForPush, PUSH_TITLE_MAX, PUSH_BODY_MAX } from "../types/notification.js";
2
+ import { decodeSenpiUserId } from "../telemetry/otel-sdk.js";
1
3
  import { createLogger } from "../utils/logger.js";
2
4
  import { classifyDecisionError } from "./decision-errors.js";
5
+ import { randomUUID } from "node:crypto";
3
6
  const logger = createLogger("[senpi-core][notifications]");
4
7
  /**
5
- * Map a raw LLM-decision error string to the user-facing Telegram message.
8
+ * Every notification the runtime emits is a strategy/trading alert, so the ingest
9
+ * envelope's top-level category is fixed. Per-alert differentiation (limit trip,
10
+ * decision error, scanner alert, ...) travels in `actionMetadata.notificationSubtype`.
11
+ */
12
+ const NOTIFICATION_CATEGORY = "PERPS";
13
+ const NOTIFICATION_SOURCE = "senpi-trading-runtime";
14
+ /**
15
+ * Bounded per-request timeout for the ingest POST. The service is called both
16
+ * fire-and-forget and awaited inline by producers on the serial signal path, so
17
+ * this must never hang indefinitely: one retry on a retryable failure, no more.
18
+ * Worst-case latency is therefore ~2x this value, never unbounded.
19
+ */
20
+ const DEFAULT_TIMEOUT_MS = 5000;
21
+ /** Only one retry attempt on a retryable failure — see {@link classifyOutcome}. */
22
+ const MAX_ATTEMPTS = 2;
23
+ /** Suppress repeat WARN logs for the same failure reason within this window. */
24
+ const WARN_REPEAT_WINDOW_MS = 30_000;
25
+ /**
26
+ * Production ingest endpoint, used when neither `options.ingest_url` nor
27
+ * `NOTIFICATIONS_INGEST_URL` supplies one. The typical deployment IS production,
28
+ * so the runtime boots and delivers with zero notification config; non-prod
29
+ * environments must set the env var to point at their own ingest endpoint.
30
+ */
31
+ export const DEFAULT_INGEST_URL = "https://notifications.prod.senpi.ai/notify";
32
+ /**
33
+ * Map a raw LLM-decision error string to a user-facing notification message.
6
34
  *
7
- * Thin wrapper over {@link classifyDecisionError} — all message wording and the
35
+ * Thin wrapper over {@link classifyDecisionError} — the two-bucket copy and the
8
36
  * failure-mode lookup live in `decision-errors.ts` (the single source of truth
9
37
  * shared with the retry logic in `openclaw-llm-decision.ts`). The runtime catches
10
38
  * errors from the LLM-decision call and passes `err.message` here.
11
39
  *
12
40
  * @param rawMessage - Error message thrown by the decision client (may embed an
13
41
  * OpenClaw gateway message).
14
- * @param ctx - Optional plugin-side context (action name, configured model) for
15
- * placeholders the gateway error string cannot supply.
16
42
  */
17
- export function formatDecisionErrorNotification(rawMessage, ctx) {
18
- return classifyDecisionError(rawMessage, ctx).userMessage;
43
+ export function formatDecisionErrorNotification(rawMessage) {
44
+ return classifyDecisionError(rawMessage).userMessage;
45
+ }
46
+ /** Strip anything shaped like a bearer credential before it can reach a log line. */
47
+ function redactSecrets(text) {
48
+ return text.replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]");
49
+ }
50
+ function describeError(err) {
51
+ const raw = err instanceof Error ? err.message : String(err);
52
+ return redactSecrets(raw);
53
+ }
54
+ /** Classify an HTTP response status into a delivery outcome. 503 and any 5xx are
55
+ * transient (server-side produce failure) and get one retry; every other non-2xx
56
+ * (400 malformed envelope, 401 bad/expired token, 403 recipient mismatch, or any
57
+ * other 4xx) is a caller-side condition a retry cannot fix, so it drops immediately. */
58
+ function classifyStatus(status) {
59
+ if (status >= 200 && status < 300)
60
+ return "ok";
61
+ if (status === 503 || status >= 500)
62
+ return "retry";
63
+ return "drop";
64
+ }
65
+ /** Log a WARN, but suppress repeats of the same reason within {@link WARN_REPEAT_WINDOW_MS}
66
+ * so a hot failure path (e.g. a sustained outage) doesn't flood the log. The suppression
67
+ * map is passed in (owned per service instance — see {@link createNotificationService}), so
68
+ * two services with different tokens never suppress each other's WARNs. */
69
+ function warnRateLimited(lastWarnedAt, key, message, attributes) {
70
+ const now = Date.now();
71
+ const last = lastWarnedAt.get(key);
72
+ if (last !== undefined && now - last < WARN_REPEAT_WINDOW_MS)
73
+ return;
74
+ lastWarnedAt.set(key, now);
75
+ logger.warn(message, undefined, attributes);
76
+ }
77
+ async function postOnce(ingestUrl, authToken, envelope, timeoutMs) {
78
+ const controller = new AbortController();
79
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
80
+ try {
81
+ const res = await fetch(ingestUrl, {
82
+ method: "POST",
83
+ headers: {
84
+ "Content-Type": "application/json",
85
+ Authorization: `Bearer ${authToken}`,
86
+ },
87
+ body: JSON.stringify(envelope),
88
+ signal: controller.signal,
89
+ });
90
+ if (res.ok)
91
+ return { kind: "ok" };
92
+ const bodyText = await res.text().catch(() => "");
93
+ const kind = classifyStatus(res.status);
94
+ return { kind, status: res.status, reason: redactSecrets(bodyText).slice(0, 300) };
95
+ }
96
+ catch (err) {
97
+ // Network failure, DNS failure, connection refused, or our own timeout abort.
98
+ return { kind: "retry", reason: describeError(err) };
99
+ }
100
+ finally {
101
+ clearTimeout(timer);
102
+ }
103
+ }
104
+ /** POST the envelope with a single bounded retry on a transient failure (5xx / network / timeout).
105
+ * Never throws — every outcome resolves, so a delivery failure can never surface as a rejected
106
+ * promise into the caller's (often serial, trading-critical) code path. */
107
+ async function deliver(lastWarnedAt, ingestUrl, authToken, envelope, timeoutMs) {
108
+ let outcome = await postOnce(ingestUrl, authToken, envelope, timeoutMs);
109
+ for (let attempt = 2; outcome.kind === "retry" && attempt <= MAX_ATTEMPTS; attempt++) {
110
+ outcome = await postOnce(ingestUrl, authToken, envelope, timeoutMs);
111
+ }
112
+ if (outcome.kind === "ok")
113
+ return;
114
+ const notificationId = envelope.notificationId;
115
+ const subtype = envelope.actionMetadata?.notificationSubtype;
116
+ const rateLimitKey = `${outcome.status ?? "network"}:${typeof subtype === "string" ? subtype : "unknown"}`;
117
+ warnRateLimited(lastWarnedAt, rateLimitKey, `Notification delivery dropped notificationId=${String(notificationId)} status=${outcome.status ?? "n/a"}: ${outcome.reason}`, { notificationId, status: outcome.status });
118
+ }
119
+ /**
120
+ * User-facing alert when the backend rejects orders because the strategy is
121
+ * paused or closed on Senpi. Fired once when the backend-pause registry arms
122
+ * (open-position action); subsequent signals are skipped until the registry's
123
+ * recheck window elapses, so the copy must not promise instant resumption.
124
+ */
125
+ export function formatBackendPausedNotification(address) {
126
+ return (`⏸️ Orders for strategy ${address} are being rejected because the strategy ` +
127
+ `is paused or closed on Senpi. The runtime will pause order submission and ` +
128
+ `re-check every few minutes — after you resume the strategy on Senpi, ` +
129
+ `trading picks up again within about 5 minutes.`);
19
130
  }
20
131
  /**
21
- * IMPORTANT: Do NOT use logger.error(...) anywhere inside this service.
22
- * NotificationService is itself the Telegram delivery path for error notifications.
23
- * Using logger.error here would trigger the error notifier hook recursively,
24
- * which is blocked by the reentrancy guard (causing the notification to be silently dropped)
25
- * or could cause unexpected feedback loops in future. Use logger.warn for all failure paths.
132
+ * Create the runtime's notification service. Every notification is delivered by
133
+ * POSTing the full structured envelope to the authenticated notification-ingest
134
+ * endpoint — there is no other delivery path. The endpoint resolves in order:
135
+ * `options.ingest_url`, then `NOTIFICATIONS_INGEST_URL`, then the production
136
+ * default ({@link DEFAULT_INGEST_URL}), so the URL can never be missing. A missing
137
+ * auth token is still a startup error (thrown here, not discovered later as
138
+ * silent notification loss), so callers must construct this before a runtime
139
+ * starts trading, not lazily on first notify.
140
+ *
141
+ * Failure paths inside this service log at warn, not error: a delivery failure is a
142
+ * handled, degraded condition — the caller's notify() contract is fire-and-forget and
143
+ * the next notification retries the transport fresh.
26
144
  */
27
145
  export function createNotificationService(options) {
28
- const chatId = typeof options?.telegram_chat_id === "string" ? options.telegram_chat_id.trim() : undefined;
29
- const mcpTransport = options?.mcpTransport;
30
- const gatewayUrl = options?.gateway_url || process.env.OPENCLAW_GATEWAY_URL || "http://127.0.0.1:18789";
31
- const gatewayToken = options?.gateway_token || process.env.OPENCLAW_GATEWAY_TOKEN;
32
- if (chatId) {
33
- logger.info(`Notifications enabled for ${chatId}; routing via OpenClaw /tools/invoke`);
146
+ const ingestUrl = options?.ingest_url?.trim() ||
147
+ process.env.NOTIFICATIONS_INGEST_URL?.trim() ||
148
+ DEFAULT_INGEST_URL;
149
+ const authToken = (options?.senpi_auth_token ||
150
+ process.env.SENPI_AUTH_TOKEN ||
151
+ process.env.SENPI_API_KEY)?.trim();
152
+ if (!authToken) {
153
+ throw new Error("NotificationService misconfigured: no Senpi auth token available. " +
154
+ "Set options.senpi_auth_token, or SENPI_AUTH_TOKEN / SENPI_API_KEY in the environment — " +
155
+ "the runtime authenticates to the notification-ingest endpoint with its own Senpi token.");
156
+ }
157
+ const timeoutMs = options?.ingest_timeout_ms ?? DEFAULT_TIMEOUT_MS;
158
+ // Per-instance WARN suppression state. Owned by this service (not a module global)
159
+ // so sibling services don't suppress each other's WARNs, and each service's first
160
+ // delivery failure always logs — a module-global map would let one service's WARN
161
+ // rate-limit another's, and made this hard to observe/test.
162
+ const lastWarnedAt = new Map();
163
+ // Telegram delivery is gone; a recipe still carrying telegram_chat_id from before
164
+ // the cutover is a silent misconfiguration footgun otherwise — the operator set it
165
+ // expecting delivery and gets nothing. Ignore it, but say so loudly once.
166
+ if (typeof options?.telegram_chat_id === "string" && options.telegram_chat_id.trim().length > 0) {
167
+ logger.warn("telegram_chat_id is set but ignored: Telegram delivery has been removed.");
34
168
  }
169
+ // Resolve the recipient once from THIS service's own token — never a process
170
+ // global — so sibling services with different tokens stamp different users.
171
+ const recipientUserId = decodeSenpiUserId(authToken);
172
+ if (recipientUserId === undefined) {
173
+ // A live runtime always holds a valid token, so an undecodable one is an
174
+ // anomaly. WARN only (never logger.error — see the reentrancy note above);
175
+ // delivery still proceeds unstamped.
176
+ logger.warn("Could not resolve recipient senpi_user_id from auth token; delivering notification unstamped.");
177
+ }
178
+ logger.info(`Notifications enabled; routing via POST ${ingestUrl}`);
35
179
  return {
36
- async notify(message) {
180
+ async notify(input) {
181
+ const p = toPayload(input);
182
+ const message = p.message;
37
183
  if (typeof message !== "string" || message.length === 0)
38
184
  return;
185
+ // Precedence: the service's own resolved recipient wins, but an
186
+ // unresolved token must never clobber a value already on the payload.
187
+ const recipient = recipientUserId ?? p.recipientUserId;
39
188
  const preview = message.length > 120 ? message.slice(0, 120) + "…" : message;
40
189
  logger.info("Notification service invoked", { messagePreview: preview });
41
- if (!chatId) {
42
- logger.warn("Notification not sent: no telegram_chat_id in runtime config.");
43
- return;
44
- }
45
- // 1. Prefer MCP transport if host injects it in the future
46
- if (mcpTransport) {
47
- try {
48
- await mcpTransport("send_telegram_notification", { target: `telegram:${chatId}`, message });
49
- return;
50
- }
51
- catch (err) {
52
- logger.warn("MCP transport failed; falling back to Gateway HTTP", err);
53
- }
54
- }
55
- // 2. HTTP Gateway Tool Invocation (Matches your LLM Engine)
56
- if (gatewayToken) {
57
- try {
58
- const baseUrl = gatewayUrl.endsWith("/") ? gatewayUrl.slice(0, -1) : gatewayUrl;
59
- const res = await fetch(`${baseUrl}/tools/invoke`, {
60
- method: "POST",
61
- headers: {
62
- "Content-Type": "application/json",
63
- "Authorization": `Bearer ${gatewayToken}`
64
- },
65
- body: JSON.stringify({
66
- tool: "message",
67
- args: {
68
- action: "send",
69
- target: `telegram:${chatId}`,
70
- message: message,
71
- },
72
- })
73
- });
74
- if (!res.ok) {
75
- const errText = await res.text().catch(() => "No response body");
76
- throw new Error(`HTTP ${res.status}: ${errText}`);
77
- }
78
- const body = await res.json();
79
- if (!body.ok) {
80
- throw new Error(`Gateway rejected message tool: ${body.error ?? JSON.stringify(body)}`);
81
- }
82
- return;
83
- }
84
- catch (err) {
85
- logger.warn("Gateway tool invocation failed", err);
86
- }
87
- return;
88
- }
89
- logger.warn("Notification dropped: Missing OPENCLAW_GATEWAY_TOKEN in environment.");
190
+ // The openability fields (canOpenAgentChat + context) forward verbatim — never inferred,
191
+ // never repaired. notificationId/subtype fall back to the payload's own
192
+ // context when present (the producer already minted one), else this is the
193
+ // first and only place an id is minted for a bare-string/non-openable call.
194
+ const notificationId = p.context?.notificationId ?? randomUUID();
195
+ const subtype = p.subtype ?? p.context?.subtype;
196
+ // notifications-service renders user-visible text ONLY from these three
197
+ // actionMetadata fields (each `|| ""`) — it never displays the top-level
198
+ // `message`. A bare-string / copy-less notify() would otherwise ship a
199
+ // blank notification, so a copy-less payload always gets a synthesized
200
+ // fallback derived from `message` — every family ships non-empty copy.
201
+ const copy = p.copy ?? {
202
+ pushTitle: truncateForPush(message.split("\n")[0], PUSH_TITLE_MAX),
203
+ pushBody: truncateForPush(message.replace(/\n/g, " · "), PUSH_BODY_MAX),
204
+ inApp: message,
205
+ };
206
+ const envelope = {
207
+ notificationId,
208
+ message,
209
+ category: NOTIFICATION_CATEGORY,
210
+ source: NOTIFICATION_SOURCE,
211
+ timestamp: p.context?.createdAt ?? new Date().toISOString(),
212
+ canOpenAgentChat: p.canOpenAgentChat === true,
213
+ actionMetadata: {
214
+ uniqueKeys: [notificationId],
215
+ ...(subtype !== undefined ? { notificationSubtype: subtype } : {}),
216
+ id: notificationId,
217
+ pushNotificationTitle: copy.pushTitle,
218
+ pushNotificationMessage: copy.pushBody,
219
+ inAppNotificationMessage: copy.inApp,
220
+ senpiFormattedMessage: copy.inApp,
221
+ ctas: [],
222
+ category: NOTIFICATION_CATEGORY,
223
+ },
224
+ // Same id drives the ingest endpoint's idempotency precedence, so the two
225
+ // attempts of one delivery (see `deliver`'s bounded retry) collapse to a
226
+ // single ledger row even if the first attempt's response was lost.
227
+ idempotencyKey: notificationId,
228
+ };
229
+ if (p.context !== undefined)
230
+ envelope.context = p.context;
231
+ if (recipient !== undefined)
232
+ envelope.recipientUserId = recipient;
233
+ await deliver(lastWarnedAt, ingestUrl, authToken, envelope, timeoutMs);
90
234
  },
91
235
  };
92
236
  }
@@ -1 +1 @@
1
- {"version":3,"file":"notifications.js","sourceRoot":"","sources":["../../src/runtime/notifications.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAA6B,MAAM,sBAAsB,CAAC;AAExF,MAAM,MAAM,GAAG,YAAY,CAAC,6BAA6B,CAAC,CAAC;AAU3D;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,+BAA+B,CAC7C,UAAkB,EAClB,GAA0B;IAE1B,OAAO,qBAAqB,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC,WAAW,CAAC;AAC5D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAoC;IAC5E,MAAM,MAAM,GAAG,OAAO,OAAO,EAAE,gBAAgB,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;IAC3G,MAAM,YAAY,GAAG,OAAO,EAAE,YAAY,CAAC;IAC3C,MAAM,UAAU,GAAG,OAAO,EAAE,WAAW,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,wBAAwB,CAAC;IACxG,MAAM,YAAY,GAAG,OAAO,EAAE,aAAa,IAAI,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC;IAElF,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,CAAC,IAAI,CAAC,6BAA6B,MAAM,sCA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 export declare class Runtime {
63
63
  private cachedStrategyId;
64
64
  /** In-flight resolution promise; ensures concurrent first-burst callers reuse one `listStrategies`. */
65
65
  private strategyIdResolution;
66
- /** Action-layer Telegram subscriber (open submit / close); disposed in {@link Runtime.stop}. */
67
- private actionNotificationSubscriber;
66
+ /** Scanner-alert dedupe: (scannerId, message) key → last-emitted ms. Pruned opportunistically. */
67
+ private scannerAlertLastEmitted;
68
+ /** Suppression-WARN rate limiting for the same keyspace — at most one WARN per key per window. */
69
+ private scannerAlertLastWarned;
68
70
  /** Serializes reconcile vs the trade loop. One shared key "reconcile". */
69
71
  private reconcileMutex;
70
72
  /** Deferred gate: consumer awaits this before touching slot counts / running actions. */
@@ -156,6 +158,18 @@ export declare class Runtime {
156
158
  * states. Best-effort: a failure here must not block runtime start.
157
159
  */
158
160
  private rehydratePositionIdRegistry;
161
+ /**
162
+ * Filter one scan run's alerts down to the ones fresh enough to notify on,
163
+ * per (scannerId, message) — see {@link SCANNER_ALERT_DEDUPE_MS}. A run
164
+ * mixing a brand-new alert with a repeat of one already notified within the
165
+ * window still surfaces the new one; the repeat is silently dropped from
166
+ * the result and, on its first suppression this window, logs one rate-limited
167
+ * WARN. Freshly-emitted keys record `now` so the next occurrence inside the
168
+ * window is recognized as a repeat.
169
+ */
170
+ private freshScannerAlerts;
171
+ /** Opportunistic cleanup of scanner-alert dedupe state — bounds memory for long-running runtimes. */
172
+ private pruneScannerAlertDedupe;
159
173
  /**
160
174
  * Cached wallet → strategy-id lookup. Concurrent callers share one
161
175
  * in-flight `listStrategies` promise; the cached id is reused across
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/runtime/runtime.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAI/E,OAAO,KAAK,EACV,4BA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;IAS/B;;;;;OAKG;YACW,iBAAiB;IA6CzB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAoc5B;;OAEG;IACH,uEAAuE;IACjE,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAStD,0FAA0F;IACpF,6BAA6B,IAAI,OAAO,CAAC,IAAI,CAAC;IAIpD;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAY5B;;OAEG;YACW,iBAAiB;IAyI/B;;;;;;OAMG;IACH,OAAO,CAAC,oBAAoB;IAO5B;;;;OAIG;YACW,oBAAoB;IAiElC;;;OAGG;YACW,kBAAkB;IAc1B,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CA4D5B"}
@@ -28,7 +28,6 @@ import { initRisk } from "../risk/index.js";
28
28
  import { createHealthStateModule, } from "../health/index.js";
29
29
  import { DslPlugin as DslPluginClass } from "../dsl/plugin/index.js";
30
30
  import { HOOK_EVENT } from "../types/hooks.js";
31
- import { createActionNotificationSubscriber, isActionLifecycleNotificationsEnabled } from "../actions/notifications/index.js";
32
31
  import { MaxLeverageCache } from "../leverage/max-leverage-cache.js";
33
32
  import { buildStateLayout } from "./state-layout.js";
34
33
  import { createLogger } from "../utils/logger.js";
@@ -58,6 +57,23 @@ const RECONCILE_RETRY_INTERVAL_MS = 15_000;
58
57
  const SIGNAL_QUEUE_BACKPRESSURE_THRESHOLD = 10;
59
58
  /** Default liveness-heartbeat window (~15 min) when `health.window_seconds` is unset. */
60
59
  const DEFAULT_LIVENESS_WINDOW_SECONDS = 900;
60
+ /**
61
+ * Scanner-alert dedupe window: scanner intervals run in minutes, so an identical
62
+ * alert re-firing inside this window is noise from the same condition, not a new
63
+ * signal. Long enough to suppress a watchdog repeating every scan interval, short
64
+ * enough that a genuinely persistent condition still re-notifies within the hour.
65
+ */
66
+ const SCANNER_ALERT_DEDUPE_MS = 10 * 60_000;
67
+ /**
68
+ * Dedupe key for one scanner alert: NUL-joined so a scannerId/message never
69
+ * collides across the pair. Numeric runs in the message are collapsed to `#`
70
+ * before keying — watchdog-style alerts embed live floats (prices, margins)
71
+ * that drift every scan tick, and keying on the raw text would make every
72
+ * tick look like a new alert. Key-only: the delivered message is untouched.
73
+ */
74
+ function scannerAlertDedupeKey(scannerId, message) {
75
+ return `${scannerId}\u0000${message.replace(/\d+(?:\.\d+)?/g, "#")}`;
76
+ }
61
77
  export class Runtime {
62
78
  config;
63
79
  options;
@@ -99,8 +115,10 @@ export class Runtime {
99
115
  cachedStrategyId = null;
100
116
  /** In-flight resolution promise; ensures concurrent first-burst callers reuse one `listStrategies`. */
101
117
  strategyIdResolution = null;
102
- /** Action-layer Telegram subscriber (open submit / close); disposed in {@link Runtime.stop}. */
103
- actionNotificationSubscriber = null;
118
+ /** Scanner-alert dedupe: (scannerId, message) key → last-emitted ms. Pruned opportunistically. */
119
+ scannerAlertLastEmitted = new Map();
120
+ /** Suppression-WARN rate limiting for the same keyspace — at most one WARN per key per window. */
121
+ scannerAlertLastWarned = new Map();
104
122
  // ─── reconcile gate + mutex ──────────────────────────────────────────────────
105
123
  /** Serializes reconcile vs the trade loop. One shared key "reconcile". */
106
124
  reconcileMutex = new KeyedMutex();
@@ -251,6 +269,42 @@ export class Runtime {
251
269
  logger.warn("position.id registry rehydrate failed, continuing with empty registry", { err });
252
270
  }
253
271
  }
272
+ /**
273
+ * Filter one scan run's alerts down to the ones fresh enough to notify on,
274
+ * per (scannerId, message) — see {@link SCANNER_ALERT_DEDUPE_MS}. A run
275
+ * mixing a brand-new alert with a repeat of one already notified within the
276
+ * window still surfaces the new one; the repeat is silently dropped from
277
+ * the result and, on its first suppression this window, logs one rate-limited
278
+ * WARN. Freshly-emitted keys record `now` so the next occurrence inside the
279
+ * window is recognized as a repeat.
280
+ */
281
+ freshScannerAlerts(scannerId, alerts, now) {
282
+ return alerts.filter((alert) => {
283
+ const key = scannerAlertDedupeKey(scannerId, alert.message ?? "");
284
+ const lastEmitted = this.scannerAlertLastEmitted.get(key);
285
+ if (lastEmitted !== undefined && now - lastEmitted < SCANNER_ALERT_DEDUPE_MS) {
286
+ const lastWarned = this.scannerAlertLastWarned.get(key);
287
+ if (lastWarned === undefined || now - lastWarned >= SCANNER_ALERT_DEDUPE_MS) {
288
+ this.scannerAlertLastWarned.set(key, now);
289
+ logger.warn("scanner alert suppressed (dedupe)", { scannerId, window_ms: SCANNER_ALERT_DEDUPE_MS });
290
+ }
291
+ return false;
292
+ }
293
+ this.scannerAlertLastEmitted.set(key, now);
294
+ return true;
295
+ });
296
+ }
297
+ /** Opportunistic cleanup of scanner-alert dedupe state — bounds memory for long-running runtimes. */
298
+ pruneScannerAlertDedupe(now) {
299
+ for (const [key, ts] of this.scannerAlertLastEmitted) {
300
+ if (now - ts >= SCANNER_ALERT_DEDUPE_MS)
301
+ this.scannerAlertLastEmitted.delete(key);
302
+ }
303
+ for (const [key, ts] of this.scannerAlertLastWarned) {
304
+ if (now - ts >= SCANNER_ALERT_DEDUPE_MS)
305
+ this.scannerAlertLastWarned.delete(key);
306
+ }
307
+ }
254
308
  /**
255
309
  * Cached wallet → strategy-id lookup. Concurrent callers share one
256
310
  * in-flight `listStrategies` promise; the cached id is reused across
@@ -344,6 +398,9 @@ export class Runtime {
344
398
  this.senpi = senpi;
345
399
  this.strategyConfig = resolveStrategyConfig(this.config);
346
400
  await this.rehydratePositionIdRegistry();
401
+ // Human strategy label for every runtime notification family: the operator's
402
+ // `group` when set, else the recipe `name` (schema-required, always resolves).
403
+ const notificationLabel = this.config.group ?? this.config.name;
347
404
  // The OTLP exporter env is the telemetry master switch: the OTel SDK (stood up at plugin
348
405
  // register()) and the domain-event log both gate on it.
349
406
  const telemetryEnabled = isOtlpEndpointConfigured();
@@ -377,8 +434,11 @@ export class Runtime {
377
434
  const llmDecision = createLlmDecision({});
378
435
  const contextBuilder = createContextBuilder();
379
436
  const notifications = createNotificationService({
437
+ // A config-provided senpi_auth_token wins; when absent, createNotificationService
438
+ // resolves the token itself from apiKey/SENPI_AUTH_TOKEN/SENPI_API_KEY. Do NOT set
439
+ // senpi_auth_token here — spread after the config, it would clobber a config token.
440
+ senpi_auth_token: this.options.apiKey,
380
441
  ...this.config.notifications,
381
- mcpTransport: this.options.mcpTransport,
382
442
  });
383
443
  const riskBlock = this.config.risk;
384
444
  const strategyAddress = this.strategyConfig.address;
@@ -402,7 +462,7 @@ export class Runtime {
402
462
  strategies: new Map([[strategyAddress, this.strategyConfig]]),
403
463
  // Human strategy label for alerts; risk-guard falls back to the
404
464
  // truncated address when an address has no name here.
405
- strategyNames: { [strategyAddress]: this.config.name },
465
+ strategyNames: { [strategyAddress]: notificationLabel },
406
466
  auditLog,
407
467
  lifecycleTracker: lifecycle,
408
468
  })
@@ -436,6 +496,7 @@ export class Runtime {
436
496
  scannerModule: this.scannerModule,
437
497
  maxLeverageCache,
438
498
  positionIdRegistry: this.positionIdRegistry,
499
+ notificationLabel,
439
500
  });
440
501
  this.actionRuntimeModule = new ActionRuntimeModule({ stateDir: layout.actionRoot });
441
502
  const { runActionsForSignal } = await createActions(this.config, {
@@ -467,10 +528,7 @@ export class Runtime {
467
528
  })();
468
529
  // Build strategyStates map once — shared by DslPlugin and the reconcile loop.
469
530
  const strategyStatesMap = createStrategyStatesMap(this.strategyConfig, senpi);
470
- const notificationsConfig = this.config.notifications;
471
531
  if (hasDsl) {
472
- const dslNotificationsDisabled = notificationsConfig?.dsl_lifecycle === false;
473
- const dslNotifySlUpdates = notificationsConfig?.dsl_notify_sl_updates === true;
474
532
  this.dslPlugin = await DslPluginClass.create({
475
533
  config: exitConfig,
476
534
  bus: this.bus,
@@ -478,9 +536,8 @@ export class Runtime {
478
536
  stateManager: this.stateManager,
479
537
  senpiClient: senpi,
480
538
  strategyStates: strategyStatesMap,
481
- notifications: dslNotificationsDisabled ? undefined : notifications,
482
- notifySlUpdates: dslNotifySlUpdates,
483
- strategyName: this.config.name,
539
+ notifications,
540
+ strategyName: notificationLabel,
484
541
  // Monitor runs the unified periodic reconcile (adopt/resize/gone), serialized
485
542
  // against the trade loop on the same reconcileMutex key, and can resolve the boot gate.
486
543
  reconcileSerialize: (fn) => this.reconcileMutex.withKeyLock("reconcile", fn),
@@ -499,14 +556,6 @@ export class Runtime {
499
556
  void this.runBootReconcileLoop(strategyStatesMap).catch((err) => {
500
557
  logger.error("[runtime][reconcile] boot reconcile loop crashed", { err });
501
558
  });
502
- if (isActionLifecycleNotificationsEnabled(notificationsConfig)) {
503
- this.actionNotificationSubscriber = createActionNotificationSubscriber(this.bus, notifications, {
504
- strategyName: this.config.name,
505
- });
506
- }
507
- else {
508
- this.actionNotificationSubscriber = null;
509
- }
510
559
  initRisk(this.bus);
511
560
  this.healthStateModule = createHealthStateModule({
512
561
  runtimeName: this.config.name,
@@ -556,12 +605,49 @@ export class Runtime {
556
605
  // disturbs the scan path.
557
606
  emitEvent(logger, () => buildScannerSummaryEvent(scannerRunPayload, Date.now()));
558
607
  recordScannerRun({ scannerId: event.result.scannerId, outcome: event.result.status });
559
- // Forward scanner summary alerts (e.g. watchdog) to notification service
608
+ // Forward scanner summary alerts (e.g. watchdog) to notification service, deduped
609
+ // per (scannerId, message) within SCANNER_ALERT_DEDUPE_MS — see freshScannerAlerts.
560
610
  const alerts = event.result.summary?.alerts;
561
611
  if (Array.isArray(alerts) && alerts.length > 0) {
562
- const header = `[${event.result.scannerId}] ${alerts.length} alert(s):`;
563
- const lines = alerts.map((a) => ` ${a.level ?? "ALERT"}: ${a.message ?? ""}`);
564
- notifications.notify(`${header}\n${lines.join("\n")}`).catch(() => { });
612
+ const scannerId = event.result.scannerId;
613
+ const now = Date.now();
614
+ const freshAlerts = this.freshScannerAlerts(scannerId, alerts, now);
615
+ this.pruneScannerAlertDedupe(now);
616
+ if (freshAlerts.length > 0) {
617
+ // Push disabled until per-type notification opt-in exists; re-enable then.
618
+ // Push and in-app share this notify() payload, so both are disabled together.
619
+ //
620
+ // const copy: NotificationCopy = {
621
+ // pushTitle: "🔔 Market alert",
622
+ // pushBody: freshAlerts[0]?.message ?? "",
623
+ // inApp:
624
+ // `🔔 ${freshAlerts.length} market alert(s)<br>` +
625
+ // freshAlerts
626
+ // .map((a: { level?: string; message?: string }) => `${a.level ?? "ALERT"}: ${a.message ?? ""}`)
627
+ // .join("<br>"),
628
+ // };
629
+ // // Address-less by design: the scanner watches the market, not one
630
+ // // strategy, so the strategy wallet in scope must not leak into the seed.
631
+ // // The agent answers from the runtime's event log, so the alert opens a
632
+ // // chat by category alone.
633
+ // const createdAt = new Date().toISOString();
634
+ // const payload = applyMessagePrefix(
635
+ // {
636
+ // message: copy.inApp,
637
+ // canOpenAgentChat: true,
638
+ // subtype: "MARKET_SCANNER",
639
+ // copy,
640
+ // context: {
641
+ // notificationId: randomUUID(),
642
+ // subtype: "MARKET_SCANNER",
643
+ // createdAt,
644
+ // contextText: copy.inApp,
645
+ // },
646
+ // },
647
+ // labelPrefix(notificationLabel),
648
+ // );
649
+ // notifications.notify(payload).catch(() => {});
650
+ }
565
651
  }
566
652
  };
567
653
  this.scannerModule.on("scanner:run:complete", this.onScannerRunComplete);
@@ -608,10 +694,6 @@ export class Runtime {
608
694
  this.scannerModule.off("scanner:run:complete", this.onScannerRunComplete);
609
695
  this.onScannerRunComplete = null;
610
696
  }
611
- if (this.actionNotificationSubscriber != null) {
612
- this.actionNotificationSubscriber.dispose();
613
- this.actionNotificationSubscriber = null;
614
- }
615
697
  if (this.dslPlugin) {
616
698
  this.dslPlugin.stop();
617
699
  this.dslPlugin = null;
@@ -978,10 +1060,6 @@ export class Runtime {
978
1060
  this.scannerModule.off("scanner:run:complete", this.onScannerRunComplete);
979
1061
  this.onScannerRunComplete = null;
980
1062
  }
981
- if (this.actionNotificationSubscriber != null) {
982
- this.actionNotificationSubscriber.dispose();
983
- this.actionNotificationSubscriber = null;
984
- }
985
1063
  await this.scannerModule.stop();
986
1064
  if (this.dslPlugin) {
987
1065
  this.dslPlugin.stop();