@senpi/runtime 1.0.95-dev.runtime-phase-2.20260506193916 → 1.0.95-dev.runtime-phase-2-api.20260507130312

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 (95) hide show
  1. package/README.md +13 -0
  2. package/dist/index.d.ts +35 -100
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +33 -930
  5. package/dist/index.js.map +1 -1
  6. package/dist/plugin.d.ts +110 -0
  7. package/dist/plugin.d.ts.map +1 -0
  8. package/dist/plugin.js +1055 -0
  9. package/dist/plugin.js.map +1 -0
  10. package/dist/runtime/__tests__/helpers/runtime-gateway-harness.d.ts +3 -3
  11. package/dist/runtime/audit-query.types.d.ts +113 -0
  12. package/dist/runtime/audit-query.types.d.ts.map +1 -0
  13. package/dist/runtime/audit-query.types.js +35 -0
  14. package/dist/runtime/audit-query.types.js.map +1 -0
  15. package/dist/runtime/auto-update/coordinator.d.ts +12 -8
  16. package/dist/runtime/auto-update/coordinator.d.ts.map +1 -1
  17. package/dist/runtime/auto-update/coordinator.js +18 -17
  18. package/dist/runtime/auto-update/coordinator.js.map +1 -1
  19. package/dist/runtime/auto-update/gateway-restart.d.ts +9 -2
  20. package/dist/runtime/auto-update/gateway-restart.d.ts.map +1 -1
  21. package/dist/runtime/auto-update/gateway-restart.js +23 -13
  22. package/dist/runtime/auto-update/gateway-restart.js.map +1 -1
  23. package/dist/runtime/create-actions.d.ts.map +1 -1
  24. package/dist/runtime/create-actions.js +13 -2
  25. package/dist/runtime/create-actions.js.map +1 -1
  26. package/dist/runtime/run.d.ts +52 -1
  27. package/dist/runtime/run.d.ts.map +1 -1
  28. package/dist/runtime/run.js +9 -0
  29. package/dist/runtime/run.js.map +1 -1
  30. package/dist/runtime/runtime.d.ts +56 -0
  31. package/dist/runtime/runtime.d.ts.map +1 -1
  32. package/dist/runtime/runtime.js +169 -1
  33. package/dist/runtime/runtime.js.map +1 -1
  34. package/dist/runtime-api/config.d.ts +47 -0
  35. package/dist/runtime-api/config.d.ts.map +1 -0
  36. package/dist/runtime-api/config.js +74 -0
  37. package/dist/runtime-api/config.js.map +1 -0
  38. package/dist/runtime-api/handlers/audit.d.ts +78 -0
  39. package/dist/runtime-api/handlers/audit.d.ts.map +1 -0
  40. package/dist/runtime-api/handlers/audit.js +65 -0
  41. package/dist/runtime-api/handlers/audit.js.map +1 -0
  42. package/dist/runtime-api/handlers/group-by-scanner.d.ts +43 -0
  43. package/dist/runtime-api/handlers/group-by-scanner.d.ts.map +1 -0
  44. package/dist/runtime-api/handlers/group-by-scanner.js +43 -0
  45. package/dist/runtime-api/handlers/group-by-scanner.js.map +1 -0
  46. package/dist/runtime-api/handlers/ingest-signals.d.ts +54 -0
  47. package/dist/runtime-api/handlers/ingest-signals.d.ts.map +1 -0
  48. package/dist/runtime-api/handlers/ingest-signals.js +141 -0
  49. package/dist/runtime-api/handlers/ingest-signals.js.map +1 -0
  50. package/dist/runtime-api/handlers/lookup.d.ts +36 -0
  51. package/dist/runtime-api/handlers/lookup.d.ts.map +1 -0
  52. package/dist/runtime-api/handlers/lookup.js +31 -0
  53. package/dist/runtime-api/handlers/lookup.js.map +1 -0
  54. package/dist/runtime-api/handlers/types.d.ts +85 -0
  55. package/dist/runtime-api/handlers/types.d.ts.map +1 -0
  56. package/dist/runtime-api/handlers/types.js +8 -0
  57. package/dist/runtime-api/handlers/types.js.map +1 -0
  58. package/dist/runtime-api/lifecycle.d.ts +98 -0
  59. package/dist/runtime-api/lifecycle.d.ts.map +1 -0
  60. package/dist/runtime-api/lifecycle.js +137 -0
  61. package/dist/runtime-api/lifecycle.js.map +1 -0
  62. package/dist/runtime-api/readiness.d.ts +37 -0
  63. package/dist/runtime-api/readiness.d.ts.map +1 -0
  64. package/dist/runtime-api/readiness.js +35 -0
  65. package/dist/runtime-api/readiness.js.map +1 -0
  66. package/dist/runtime-api/routes/audit.d.ts +40 -0
  67. package/dist/runtime-api/routes/audit.d.ts.map +1 -0
  68. package/dist/runtime-api/routes/audit.js +90 -0
  69. package/dist/runtime-api/routes/audit.js.map +1 -0
  70. package/dist/runtime-api/routes/audit.schema.d.ts +75 -0
  71. package/dist/runtime-api/routes/audit.schema.d.ts.map +1 -0
  72. package/dist/runtime-api/routes/audit.schema.js +78 -0
  73. package/dist/runtime-api/routes/audit.schema.js.map +1 -0
  74. package/dist/runtime-api/routes/health.d.ts +53 -0
  75. package/dist/runtime-api/routes/health.d.ts.map +1 -0
  76. package/dist/runtime-api/routes/health.js +48 -0
  77. package/dist/runtime-api/routes/health.js.map +1 -0
  78. package/dist/runtime-api/routes/signals.d.ts +50 -0
  79. package/dist/runtime-api/routes/signals.d.ts.map +1 -0
  80. package/dist/runtime-api/routes/signals.js +90 -0
  81. package/dist/runtime-api/routes/signals.js.map +1 -0
  82. package/dist/runtime-api/routes/signals.schema.d.ts +94 -0
  83. package/dist/runtime-api/routes/signals.schema.d.ts.map +1 -0
  84. package/dist/runtime-api/routes/signals.schema.js +58 -0
  85. package/dist/runtime-api/routes/signals.schema.js.map +1 -0
  86. package/dist/runtime-api/server.d.ts +79 -0
  87. package/dist/runtime-api/server.d.ts.map +1 -0
  88. package/dist/runtime-api/server.js +109 -0
  89. package/dist/runtime-api/server.js.map +1 -0
  90. package/dist/senpi/client.d.ts +92 -2
  91. package/dist/senpi/client.d.ts.map +1 -1
  92. package/dist/senpi/client.js +181 -8
  93. package/dist/senpi/client.js.map +1 -1
  94. package/openclaw.plugin.json +24 -0
  95. package/package.json +6 -2
package/dist/index.js CHANGED
@@ -1,935 +1,38 @@
1
1
  /**
2
- * Senpi core trading plugin — single plugin exposing all core features:
3
- * actions, scanners, dsl, risk, health.
4
- * Default export: OpenClaw plugin entry (register(api)).
5
- * Named export run(): programmatic/standalone entry.
6
- */
7
- import { join } from "node:path";
8
- import { SenpiClient } from "./senpi/client.js";
9
- import { buildRuntimeStateDir, archiveStateDir } from "./runtime/state-layout.js";
10
- import { registerSenpiCli } from "./cli/senpi-commands.js";
11
- import { readSenpiCliStore, resolveSenpiApiKeyFromStore, resolveSenpiBaseStateDir, resolveTelegramChatIdFromStore, } from "./cli/senpi-cli-config.js";
12
- import { getDefaultStateDir } from "./runtime/default-state-dir.js";
13
- import { createNotificationService } from "./runtime/notifications.js";
14
- import { run } from "./runtime/run.js";
15
- import { AutoUpdateCoordinator } from "./runtime/auto-update/coordinator.js";
16
- import { runCommand } from "./runtime/auto-update/command-runner.js";
17
- import { resolveAutoUpdateConfig } from "./runtime/auto-update/types.js";
18
- import { createScannerProvidersForRun } from "./runtime/create-scanner-providers-for-run.js";
19
- import { initDsl } from "./dsl/index.js";
20
- import { initHealth } from "./health/index.js";
21
- import { initRisk } from "./risk/index.js";
22
- import { VERSION } from "./version.js";
23
- import { BUS_EVENT_MAP } from "./tracking/constants.js";
24
- import { createPluginEventTracker } from "./tracking/plugin-event-tracker.js";
25
- import { getLogLevel, getLogLevelSource, parseLogLevel, setErrorNotifier, setLogLevel, } from "./utils/logger.js";
26
- import { ExternalScannerIngestError, } from "./scanners/external-scanner-receiver.js";
27
- /** Initialize all core features (DSL, risk, health) on the given event bus. */
28
- export function initCore(bus) {
29
- initDsl(bus);
30
- initRisk(bus);
31
- initHealth(bus);
32
- }
33
- // DSL feature (exit/dsl component, types, config)
34
- export { initDsl, DslPlugin, dslLogger, setDslLogLevel, parseDslPluginConfig, DslConfigValidationError, dslValidationIssue, EVENTS as DslEvents, DSL_EVENTS, } from "./dsl/index.js";
35
- // Risk feature (placeholder)
36
- export { initRisk } from "./risk/index.js";
37
- // Health feature
38
- export { createHealthStateModule, initHealth } from "./health/index.js";
39
- // Shared types
40
- export { HOOK_EVENT } from './types/index.js';
41
- export { ScanStatus } from './types/index.js';
42
- export { DecisionEngine, LlmDecisionStrategy, NoDecisionStrategy, } from './actions/decision-engine.js';
43
- export { OpenClawLlmDecision, AnthropicLlmDecision, createLlmDecision } from './actions/llm-decision/index.js';
44
- /** @deprecated Use OpenClawLlmDecision instead */
45
- export { OpenClawLlmDecision as LlmDecisionClient } from './actions/llm-decision/index.js';
46
- export { OpenPositionAction, openPositionFactory, openPositionManifest, } from './actions/open-position/open-position.action.js';
47
- export { ClosePositionAction, closePositionFactory, closePositionManifest, } from './actions/close-position/close-position.action.js';
48
- // Senpi client
49
- export { SenpiClient } from './senpi/index.js';
50
- // Scanner runtime module
51
- export { createScannerRuntimeModule, createSenpiScannerProviders, emergingMoversScanner, momentumScanner, oiTrackerScanner, providerInput, prescreenerScanner, PersistencePolicy, RetentionPolicy, ScanStatus as ScannerScanStatus, SkipScan, } from './scanners/index.js';
52
- // Runtime loader — programmatic API and OpenClaw plugin entry
53
- export { run } from "./runtime/run.js";
54
- export { loadRuntimeConfig } from "./runtime/load-runtime-config.js";
55
- export { Runtime } from "./runtime/runtime.js";
56
- function toSerializable(value, seen = new WeakSet()) {
57
- if (value instanceof Error) {
58
- return {
59
- name: value.name,
60
- message: value.message,
61
- stack: value.stack,
62
- cause: toSerializable(value.cause, seen),
63
- };
64
- }
65
- if (typeof value === "bigint")
66
- return value.toString();
67
- if (value == null ||
68
- typeof value === "string" ||
69
- typeof value === "number" ||
70
- typeof value === "boolean") {
71
- return value;
72
- }
73
- if (Array.isArray(value))
74
- return value.map((v) => toSerializable(v, seen));
75
- if (typeof value === "object") {
76
- const obj = value;
77
- if (seen.has(obj))
78
- return "[Circular]";
79
- seen.add(obj);
80
- const out = {};
81
- for (const key of Object.keys(obj).sort()) {
82
- out[key] = toSerializable(obj[key], seen);
83
- }
84
- seen.delete(obj);
85
- return out;
86
- }
87
- return String(value);
88
- }
89
- function stringifyForTelegram(value) {
90
- try {
91
- return JSON.stringify(toSerializable(value), null, 2);
92
- }
93
- catch {
94
- return String(value);
95
- }
96
- }
97
- function trimTelegramMessage(message, maxLength = 3900) {
98
- if (message.length <= maxLength)
99
- return message;
100
- const clipped = message.slice(0, maxLength);
101
- return `${clipped}\n...[truncated ${message.length - maxLength} chars]`;
102
- }
103
- function formatSharedLoggerErrorNotification(payload) {
104
- const lines = [
105
- "Senpi error log",
106
- "source: shared-logger",
107
- `timestamp: ${payload.timestamp}`,
108
- `namespace: ${payload.namespace}`,
109
- `level: ${payload.level}`,
110
- `message: ${payload.message}`,
111
- ];
112
- if (payload.meta !== undefined) {
113
- lines.push(`meta:\n${stringifyForTelegram(payload.meta)}`);
114
- }
115
- return trimTelegramMessage(lines.join("\n"));
116
- }
117
- function formatApiLoggerErrorNotification(message, meta) {
118
- const msg = typeof message === "string" ? message : stringifyForTelegram(message);
119
- const lines = [
120
- "Senpi error log",
121
- "source: plugin-api-logger",
122
- `timestamp: ${new Date().toISOString()}`,
123
- `message: ${msg}`,
124
- ];
125
- if (meta !== undefined) {
126
- lines.push(`meta:\n${stringifyForTelegram(meta)}`);
127
- }
128
- return trimTelegramMessage(lines.join("\n"));
129
- }
130
- function fireAndForgetErrorNotification(notifications, message) {
131
- if (!notifications)
132
- return;
133
- try {
134
- void notifications.notify(message).catch(() => { });
135
- }
136
- catch {
137
- // Intentionally swallow; error notifications must never fail call sites.
138
- }
139
- }
140
- /**
141
- * OpenClaw plugin entry.
142
- * Boots from internal registry (installed_runtimes.json) in stateDir; does not read runtime list from config.
143
- */
144
- const senpiRuntimePlugin = {
145
- id: "@senpi-ai/runtime",
146
- name: "Senpi Trading Runtime",
147
- version: VERSION,
148
- description: "Senpi trading runtime plugin for OpenClaw — orchestrates scanners, actions, and DSL exit engine",
149
- configSchema: {
150
- parse(value) {
151
- if (value && typeof value === "object" && !Array.isArray(value)) {
152
- return value;
153
- }
154
- return {};
155
- },
156
- },
157
- register(api) {
158
- const pluginLogger = {
159
- info: (...args) => api.logger.info(...args),
160
- warn: (...args) => api.logger.warn(...args),
161
- error: (message, meta) => api.logger.error(message, meta),
162
- };
163
- pluginLogger.info("[senpi-runtime] register(api) invoked");
164
- const config = api.pluginConfig;
165
- if (!config) {
166
- pluginLogger.warn("[senpi-runtime] No plugin config found — skipping registration");
167
- return;
168
- }
169
- if (typeof config.logLevel === "string" && config.logLevel.length > 0) {
170
- const parsed = parseLogLevel(config.logLevel);
171
- if (parsed !== null) {
172
- setLogLevel(parsed, "config");
173
- }
174
- else {
175
- pluginLogger.warn(`[senpi-runtime] Ignoring invalid plugin config logLevel="${config.logLevel}" (expected debug|info|warn|error); keeping ${getLogLevel()}.`);
176
- }
177
- }
178
- const startupLogLevel = getLogLevel();
179
- const startupLogLevelSource = getLogLevelSource();
180
- const logLevelSourceLabel = startupLogLevelSource === "config"
181
- ? "plugin config logLevel"
182
- : startupLogLevelSource === "env"
183
- ? "env SENPI_LOG_LEVEL"
184
- : "default";
185
- pluginLogger.info(`[senpi-runtime] log level: ${startupLogLevel} (source: ${logLevelSourceLabel}). Set plugin config "logLevel" or env SENPI_LOG_LEVEL to debug|info|warn|error to override.`);
186
- const senpiCliStore = readSenpiCliStore();
187
- const baseStateDir = resolveSenpiBaseStateDir({
188
- store: senpiCliStore,
189
- configStateDir: typeof config.stateDir === "string" ? config.stateDir : undefined,
190
- resolveOpenclawStateDir: typeof api.runtime?.state?.resolveStateDir === "function"
191
- ? () => api.runtime.state.resolveStateDir()
192
- : undefined,
193
- getDefaultStateDir,
194
- });
195
- const mcpTransport = api.mcpTransport;
196
- const apiKey = resolveSenpiApiKeyFromStore(senpiCliStore, typeof config.apiKey === "string" && config.apiKey.length > 0 ? config.apiKey : undefined);
197
- if (!mcpTransport && !apiKey) {
198
- pluginLogger.error("[senpi-runtime] mcpTransport or apiKey is required (provide via gateway, api, or config)");
199
- return;
200
- }
201
- const pluginEventTracker = createPluginEventTracker(apiKey ?? process.env.SENPI_API_KEY);
202
- const runtimeHandles = new Map();
203
- const lifecycleChatId = resolveTelegramChatIdFromStore(senpiCliStore);
204
- const lifecycleNotifications = lifecycleChatId
205
- ? createNotificationService({
206
- telegram_chat_id: lifecycleChatId,
207
- gateway_url: process.env.OPENCLAW_GATEWAY_URL || "http://127.0.0.1:18789",
208
- gateway_token: process.env.OPENCLAW_GATEWAY_TOKEN,
209
- })
210
- : undefined;
211
- setErrorNotifier(lifecycleNotifications
212
- ? (payload) => {
213
- fireAndForgetErrorNotification(lifecycleNotifications, formatSharedLoggerErrorNotification(payload));
214
- }
215
- : null);
216
- pluginLogger.error = (message, meta) => {
217
- api.logger.error(message, meta);
218
- fireAndForgetErrorNotification(lifecycleNotifications, formatApiLoggerErrorNotification(message, meta));
219
- };
220
- const autoUpdateConfig = resolveAutoUpdateConfig(config?.autoUpdate);
221
- const autoUpdateCoordinator = new AutoUpdateCoordinator({
222
- enabled: true,
223
- config: autoUpdateConfig,
224
- packageName: "@senpi-ai/runtime",
225
- currentVersion: VERSION,
226
- stateDir: join(baseStateDir, "auto-update"),
227
- logger: pluginLogger,
228
- notify: lifecycleNotifications
229
- ? (msg) => lifecycleNotifications.notify(msg)
230
- : async () => { },
231
- stopRuntimesForUpdate: async () => {
232
- for (const [, handle] of runtimeHandles) {
233
- await handle.stop();
234
- }
235
- },
236
- runUpdateCommand: async () => {
237
- const result = await runCommand("sh", ["-lc", "yes | openclaw plugins update runtime"], {
238
- timeoutMs: 120_000,
239
- });
240
- if (result.code !== 0) {
241
- throw new Error(result.stderr || `openclaw plugins update failed with code ${result.code}`);
242
- }
243
- },
244
- configFromApi: api.config,
245
- loadConfig: api.runtime?.config
246
- ? () => api.runtime.config.loadConfig()
247
- : undefined,
248
- writeConfigFile: api.runtime?.config
249
- ? (c) => api.runtime.config.writeConfigFile(c)
250
- : undefined,
251
- pluginId: api.id,
252
- });
253
- api.registerService({
254
- id: "senpi-runtime",
255
- async start() {
256
- await autoUpdateCoordinator.start();
257
- const { readRegistry } = await import("./runtime/strategy-registry.js");
258
- const registry = await readRegistry(baseStateDir);
259
- const scannerProviders = await createScannerProvidersForRun({
260
- mcpTransport,
261
- apiKey,
262
- });
263
- const started = [];
264
- try {
265
- for (const entry of registry.runtimes) {
266
- const hasPath = typeof entry.runtimeYamlPath === "string" && entry.runtimeYamlPath.length > 0;
267
- const hasContent = typeof entry.runtimeYamlContent === "string";
268
- if (hasPath && hasContent)
269
- continue;
270
- if (!hasPath && !hasContent)
271
- continue;
272
- const pathOrContent = entry.runtimeYamlPath ?? entry.runtimeYamlContent;
273
- const entryStateDir = buildRuntimeStateDir(baseStateDir, entry.id, entry.wallet ?? "");
274
- const handle = await run(pathOrContent, {
275
- fromPath: hasPath,
276
- stateDir: entryStateDir,
277
- mcpTransport,
278
- apiKey,
279
- scannerProviders,
280
- });
281
- runtimeHandles.set(entry.id, handle);
282
- started.push(entry.id);
283
- }
284
- }
285
- catch (err) {
286
- for (let i = started.length - 1; i >= 0; i--) {
287
- const h = runtimeHandles.get(started[i]);
288
- if (h)
289
- await h.stop().catch(() => { });
290
- runtimeHandles.delete(started[i]);
291
- }
292
- throw err;
293
- }
294
- pluginLogger.info(`[senpi-runtime] Started ${started.length} runtime${started.length === 1 ? "" : "s"}`);
295
- if (lifecycleNotifications) {
296
- const n = started.length;
297
- lifecycleNotifications
298
- .notify(`Senpi started. ${n} runtime${n === 1 ? "" : "s"} running.`)
299
- .catch(() => { });
300
- }
301
- else if (started.length > 0) {
302
- pluginLogger.info("[senpi-runtime] Lifecycle notification skipped (set telegram-chat-id via `openclaw senpi config set-chat-id` or TELEGRAM_CHAT_ID / SENPI_LIFECYCLE_TELEGRAM_CHAT_ID)");
303
- }
304
- },
305
- async stop() {
306
- if (lifecycleNotifications) {
307
- lifecycleNotifications.notify("Senpi shutting down.").catch(() => { });
308
- }
309
- // Stop the coordinator first so it cannot schedule a new tick or call
310
- // stopRuntimesForUpdate() while we are tearing down the handles below.
311
- await autoUpdateCoordinator.stop();
312
- const ids = Array.from(runtimeHandles.keys());
313
- for (let i = ids.length - 1; i >= 0; i--) {
314
- const h = runtimeHandles.get(ids[i]);
315
- if (h)
316
- await h.stop();
317
- runtimeHandles.delete(ids[i]);
318
- }
319
- pluginLogger.info("[senpi-runtime] All runtimes stopped");
320
- // Flush plugin-scoped telemetry (lifecycle.runtime.created/deleted); otherwise
321
- // BatchingTransport may still hold buffered events until the interval fires.
322
- await pluginEventTracker.shutdown().catch((err) => {
323
- pluginLogger.warn("[senpi-runtime] plugin telemetry shutdown failed", {
324
- err: err instanceof Error ? err.message : String(err),
325
- });
326
- });
327
- },
328
- });
329
- pluginLogger.info("[senpi-runtime] calling api.registerCli(..., { commands: ['senpi'] })");
330
- api.registerCli((ctx) => {
331
- pluginLogger.info("[senpi-runtime] CLI registrar callback invoked — attaching senpi subcommands to program");
332
- registerSenpiCli(ctx.program);
333
- }, { commands: ["senpi"] });
334
- /** Gateway respond accepts (ok, payload?, error?) with error as { code, message }; plugin SDK types may omit the third arg. */
335
- api.registerGatewayMethod("senpi.installRuntime", async (ctx) => {
336
- const { params } = ctx;
337
- const respond = ctx.respond;
338
- const toError = (message) => ({ code: "INVALID_REQUEST", message });
339
- const toUnavailable = (message) => ({ code: "UNAVAILABLE", message });
340
- const { readRegistry, writeRegistry, validateEntry, hasId, deriveRuntimeId, sanitizeId } = await import("./runtime/strategy-registry.js");
341
- const id = typeof params?.id === "string" ? params.id : undefined;
342
- const runtimeYamlPath = typeof params?.runtimeYamlPath === "string" ? params.runtimeYamlPath : undefined;
343
- const runtimeYamlContent = typeof params?.runtimeYamlContent === "string" ? params.runtimeYamlContent : undefined;
344
- const hasPath = runtimeYamlPath !== undefined && runtimeYamlPath.length > 0;
345
- const hasContent = runtimeYamlContent !== undefined;
346
- if (!hasPath && !hasContent) {
347
- respond(false, undefined, toError("Please provide your runtime YAML: use the create command with --path <file> or --content \"<yaml text>\"."));
348
- return;
349
- }
350
- if (hasPath && hasContent) {
351
- respond(false, undefined, toError("Please provide either a file path (--path) or YAML content (--content), not both."));
352
- return;
353
- }
354
- const pathOrContent = runtimeYamlPath ?? runtimeYamlContent;
355
- // Parse YAML first to extract name, version, and wallet for ID derivation.
356
- let parsedSchemaVersion;
357
- let runtimeName = "";
358
- let wallet = "";
359
- try {
360
- const { loadRuntimeConfig } = await import("./runtime/load-runtime-config.js");
361
- const { extractMajorVersion } = await import("./runtime/runtime-version.js");
362
- const parsedConfig = await loadRuntimeConfig(pathOrContent, { fromPath: hasPath });
363
- parsedSchemaVersion = extractMajorVersion(parsedConfig.version);
364
- runtimeName = parsedConfig.name;
365
- wallet = parsedConfig.strategy?.wallet ?? "";
366
- }
367
- catch (err) {
368
- const msg = err instanceof Error ? err.message : String(err);
369
- respond(false, undefined, toUnavailable(`Could not start the runtime. This is usually due to invalid or incomplete YAML.\n\n${msg}`));
370
- return;
371
- }
372
- const registry = await readRegistry(baseStateDir);
373
- const resolvedId = id && id.length > 0
374
- ? (sanitizeId(id) || "runtime")
375
- : deriveRuntimeId(runtimeName, wallet);
376
- if (hasId(registry, resolvedId)) {
377
- respond(false, undefined, toError(`A runtime with id "${resolvedId}" already exists. Use a different id (e.g. --runtime-id another-name) or remove the existing one first: openclaw senpi runtime delete ${resolvedId}`));
378
- return;
379
- }
380
- // Enforce one running runtime per wallet address
381
- if (wallet) {
382
- for (const [existingId, existingHandle] of runtimeHandles) {
383
- if (existingHandle.wallet === wallet) {
384
- respond(false, undefined, toError(`A runtime for wallet "${wallet}" is already running (runtime "${existingId}"). ` +
385
- `Stop it first: openclaw senpi runtime delete --id ${existingId}`));
386
- return;
387
- }
388
- }
389
- }
390
- // Best-effort wallet ownership validation: calls the MCP server to check
391
- // whether the wallet belongs to the authenticated user's strategies.
392
- // If the MCP call fails (network issue, bad apiKey, server down), we warn
393
- // and allow the install to proceed rather than blocking the user.
394
- if (wallet) {
395
- try {
396
- const client = mcpTransport
397
- ? new SenpiClient(mcpTransport)
398
- : new SenpiClient({ apiKey });
399
- if (!mcpTransport)
400
- await client.connect();
401
- try {
402
- const strategies = await client.listStrategies({ strategyAddresses: [wallet] });
403
- const match = strategies.find((s) => s.strategyWalletAddress.toLowerCase() === wallet.toLowerCase());
404
- if (!match) {
405
- pluginLogger.info("[senpi-runtime] Wallet validation failed: not owned", { wallet });
406
- respond(false, undefined, toError(`Strategy wallet "${wallet}" (YAML field: strategy.wallet) was not found in your Senpi account's strategies. ` +
407
- `Check the address for typos. ` +
408
- `To list all your strategies and their wallet addresses, call the MCP tool: strategy_list (no arguments needed). ` +
409
- `Each result includes "strategyWalletAddress" — use that value as strategy.wallet in your YAML.`));
410
- // `return` triggers the inner `finally` (disconnect) before exiting.
411
- return;
412
- }
413
- if (match.status !== "ACTIVE") {
414
- pluginLogger.info("[senpi-runtime] Wallet validation failed: strategy not active", { wallet, status: match.status, strategyId: match.id });
415
- respond(false, undefined, toError((() => {
416
- const initializingStatuses = new Set([
417
- "SET_REFERRER_CODE", "SET_BUILDER_FEE", "SUBSCRIBE_TRADER",
418
- "CREATE_WALLET", "FUND_WALLET", "INITIALIZE_POSITIONS",
419
- ]);
420
- const terminalStatuses = new Set([
421
- "CLOSED", "FAILED", "CLOSING_POSITIONS", "CLOSE_STRATEGY",
422
- "UNSUBSCRIBE_TRADER", "FUND_SOURCE_WALLET", "INACTIVE",
423
- ]);
424
- let hint;
425
- if (initializingStatuses.has(match.status)) {
426
- hint =
427
- `The strategy is still initializing (${match.status}). ` +
428
- `It will reach ACTIVE automatically — wait a few minutes, then retry. ` +
429
- `Initialization order: CREATE_WALLET → FUND_WALLET → INITIALIZE_POSITIONS → ACTIVE.`;
430
- }
431
- else if (match.status === "PAUSED") {
432
- hint =
433
- `The strategy is paused and cannot be used to create a runtime — please create a new strategy instead.`;
434
- }
435
- else if (terminalStatuses.has(match.status)) {
436
- hint =
437
- `The strategy is closing or already closed (${match.status}). ` +
438
- `A runtime cannot be created for a closed strategy — please create a new strategy instead.`;
439
- }
440
- else {
441
- hint = `Only ACTIVE strategies can run a runtime.`;
442
- }
443
- return (`Strategy wallet "${wallet}" (YAML field: strategy.wallet) has status "${match.status}" — a runtime requires ACTIVE status. ` +
444
- hint +
445
- ` To check the latest status, call the MCP tool: strategy_list.`);
446
- })()));
447
- return;
448
- }
449
- pluginLogger.info("[senpi-runtime] Wallet validation passed", { wallet, strategyId: match.id, status: match.status });
450
- }
451
- finally {
452
- if (!mcpTransport)
453
- await client.disconnect().catch(() => { });
454
- }
455
- }
456
- catch (err) {
457
- // Soft-fail: validation is best-effort. If connect() or listStrategies()
458
- // throws, log a warning and let the install proceed.
459
- const msg = err instanceof Error ? err.message : String(err);
460
- pluginLogger.warn("[senpi-runtime] Could not validate strategy wallet ownership", { wallet, err: msg });
461
- }
462
- }
463
- const entry = hasPath
464
- ? { id: resolvedId, runtimeYamlPath, schemaVersion: parsedSchemaVersion, wallet }
465
- : { id: resolvedId, runtimeYamlContent: runtimeYamlContent, schemaVersion: parsedSchemaVersion, wallet };
466
- const valid = validateEntry(entry);
467
- if (!valid.ok) {
468
- respond(false, undefined, toError(valid.error));
469
- return;
470
- }
471
- registry.runtimes.push(entry);
472
- await writeRegistry(baseStateDir, registry);
473
- const createdMapping = BUS_EVENT_MAP["tracking.runtime_created"];
474
- pluginEventTracker.capture({
475
- eventType: createdMapping.eventType,
476
- category: createdMapping.category,
477
- address: wallet,
478
- data: {
479
- id: resolvedId,
480
- name: runtimeName,
481
- wallet,
482
- schemaVersion: parsedSchemaVersion,
483
- source: hasPath ? "file" : "inline",
484
- config: entry,
485
- timestamp: new Date().toISOString(),
486
- },
487
- });
488
- try {
489
- const scannerProviders = await createScannerProvidersForRun({
490
- mcpTransport,
491
- apiKey,
492
- });
493
- const entryStateDir = buildRuntimeStateDir(baseStateDir, resolvedId, wallet);
494
- const handle = await run(pathOrContent, {
495
- fromPath: hasPath,
496
- stateDir: entryStateDir,
497
- mcpTransport,
498
- apiKey,
499
- scannerProviders,
500
- });
501
- runtimeHandles.set(resolvedId, handle);
502
- respond(true, { id: resolvedId, name: runtimeName, wallet });
503
- }
504
- catch (err) {
505
- const next = registry.runtimes.filter((e) => e.id !== resolvedId);
506
- await writeRegistry(baseStateDir, { ...registry, runtimes: next });
507
- const msg = err instanceof Error ? err.message : String(err);
508
- respond(false, undefined, toUnavailable(`Could not start the runtime. This is usually due to invalid or incomplete YAML.\n\n${msg}`));
509
- }
510
- });
511
- api.registerGatewayMethod("senpi.listRuntimes", async (ctx) => {
512
- const respond = ctx.respond;
513
- const { readRegistry } = await import("./runtime/strategy-registry.js");
514
- const registry = await readRegistry(baseStateDir);
515
- const runtimes = registry.runtimes.map((e) => ({
516
- id: e.id,
517
- wallet: e.wallet ?? "",
518
- source: typeof e.runtimeYamlPath === "string" && e.runtimeYamlPath.length > 0 ? e.runtimeYamlPath : "(inline)",
519
- status: runtimeHandles.has(e.id) ? "running" : "stopped",
520
- }));
521
- respond(true, { runtimes });
522
- });
523
- api.registerGatewayMethod("senpi.deleteRuntime", async (ctx) => {
524
- const { params } = ctx;
525
- const respond = ctx.respond;
526
- const { readRegistry, writeRegistry } = await import("./runtime/strategy-registry.js");
527
- const registry = await readRegistry(baseStateDir);
528
- let targetId = typeof params?.id === "string" ? params.id : undefined;
529
- const targetAddress = typeof params?.address === "string" ? params.address : undefined;
530
- // Resolve target by address if id not provided
531
- if (!targetId && targetAddress) {
532
- const entry = registry.runtimes.find((e) => e.wallet === targetAddress);
533
- if (!entry) {
534
- respond(false, undefined, {
535
- code: "NOT_FOUND",
536
- message: `No runtime found for wallet address "${targetAddress}".`,
537
- });
538
- return;
539
- }
540
- targetId = entry.id;
541
- }
542
- if (!targetId) {
543
- respond(false, undefined, {
544
- code: "INVALID_REQUEST",
545
- message: "Please provide the runtime id or wallet address. Example: openclaw senpi runtime delete --id my-runtime",
546
- });
547
- return;
548
- }
549
- const deletedEntry = registry.runtimes.find((e) => e.id === targetId);
550
- const handle = runtimeHandles.get(targetId);
551
- if (!deletedEntry && !handle) {
552
- respond(false, undefined, {
553
- code: "NOT_FOUND",
554
- message: `No runtime found with id "${targetId}".`,
555
- });
556
- return;
557
- }
558
- const targetWallet = deletedEntry?.wallet ??
559
- handle?.wallet ??
560
- (typeof targetAddress === "string" ? targetAddress : "");
561
- let openPositionsAbandoned = 0;
562
- let archivePath;
563
- if (handle) {
564
- openPositionsAbandoned = await handle.teardownDslForRuntimeDeletion();
565
- await handle.stop();
566
- runtimeHandles.delete(targetId);
567
- }
568
- // Archive state directory before removing from registry
569
- if (deletedEntry) {
570
- const runtimeStateDir = buildRuntimeStateDir(baseStateDir, targetId, deletedEntry.wallet ?? "");
571
- const archivesDir = join(baseStateDir, "archives");
572
- try {
573
- archivePath = await archiveStateDir(runtimeStateDir, archivesDir, targetId, deletedEntry.wallet ?? "");
574
- api.logger.info(`[senpi-runtime] Archived state to ${archivePath}`);
575
- }
576
- catch (err) {
577
- api.logger.warn("[senpi-runtime] Failed to archive state dir", { err });
578
- }
579
- }
580
- const deletedMapping = BUS_EVENT_MAP["tracking.runtime_deleted"];
581
- pluginEventTracker.capture({
582
- eventType: deletedMapping.eventType,
583
- category: deletedMapping.category,
584
- address: targetWallet,
585
- data: {
586
- id: targetId,
587
- wallet: targetWallet,
588
- schemaVersion: deletedEntry?.schemaVersion,
589
- reason: "user_initiated",
590
- openPositionsAbandoned,
591
- ...(typeof archivePath === "string" ? { archivedAt: archivePath } : {}),
592
- timestamp: new Date().toISOString(),
593
- },
594
- });
595
- if (deletedEntry) {
596
- const next = registry.runtimes.filter((e) => e.id !== targetId);
597
- await writeRegistry(baseStateDir, { ...registry, runtimes: next });
598
- }
599
- respond(true, { id: targetId });
600
- });
601
- api.registerGatewayMethod("senpi.ingestExternalScannerData", async (ctx) => {
602
- const respond = ctx.respond;
603
- try {
604
- const { address, request } = parseGatewayExternalScannerIngestParams(ctx.params);
605
- const runtime = getRuntimeHandleByAddressOrRespond(runtimeHandles, address, respond);
606
- if (!runtime) {
607
- return;
608
- }
609
- pluginLogger.info("[senpi-runtime] senpi.ingestExternalScannerData", {
610
- runtimeId: runtime.runtimeId,
611
- address,
612
- scanner: request.scanner,
613
- });
614
- const result = await runtime.handle.ingestExternalScannerData(request);
615
- respond(true, result);
616
- }
617
- catch (error) {
618
- if (error instanceof ExternalScannerIngestError) {
619
- respond(false, undefined, {
620
- code: error.code,
621
- message: error.message,
622
- });
623
- return;
624
- }
625
- pluginLogger.warn("[senpi-runtime] ingestExternalScannerData error", {
626
- address: typeof ctx.params?.address === "string" ? ctx.params.address : undefined,
627
- scanner: typeof ctx.params?.scanner === "string" ? ctx.params.scanner : undefined,
628
- err: error,
629
- });
630
- respond(false, undefined, {
631
- code: "UNAVAILABLE",
632
- message: `Failed to ingest external scanner data: ${formatGatewayError(error)}`,
633
- });
634
- }
635
- });
636
- api.registerGatewayMethod("senpi.listDslPositions", async (ctx) => {
637
- const respond = ctx.respond;
638
- const runtimeId = typeof ctx.params?.runtimeId === "string" ? ctx.params.runtimeId : undefined;
639
- const address = typeof ctx.params?.address === "string" ? ctx.params.address : undefined;
640
- pluginLogger.info("[senpi-runtime] senpi.listDslPositions", { runtimeId, address });
641
- const positions = [];
642
- for (const [id, handle] of runtimeHandles) {
643
- if (runtimeId && id !== runtimeId)
644
- continue;
645
- if (!handle.dsl)
646
- continue;
647
- try {
648
- const items = handle.dsl.listActivePositions();
649
- for (const s of items) {
650
- if (address && s.address !== address)
651
- continue;
652
- positions.push({ ...s, runtimeId: id });
653
- }
654
- }
655
- catch (err) {
656
- pluginLogger.warn("[senpi-runtime] listDslPositions error", { runtimeId: id, err });
657
- }
658
- }
659
- respond(true, { positions });
660
- });
661
- api.registerGatewayMethod("senpi.getDslPositionState", async (ctx) => {
662
- const respond = ctx.respond;
663
- const asset = typeof ctx.params?.asset === "string" ? ctx.params.asset : undefined;
664
- if (!asset) {
665
- respond(false, undefined, { code: "INVALID_REQUEST", message: "asset is required" });
666
- return;
667
- }
668
- const runtimeId = typeof ctx.params?.runtimeId === "string" ? ctx.params.runtimeId : undefined;
669
- const address = typeof ctx.params?.address === "string" ? ctx.params.address : undefined;
670
- pluginLogger.info("[senpi-runtime] senpi.getDslPositionState", { asset, runtimeId, address });
671
- const matches = [];
672
- for (const [id, handle] of runtimeHandles) {
673
- if (runtimeId && id !== runtimeId)
674
- continue;
675
- if (!handle.dsl)
676
- continue;
677
- try {
678
- if (address) {
679
- const state = handle.dsl.getPositionState(address, asset);
680
- if (state)
681
- matches.push({ runtimeId: id, address, state });
682
- }
683
- else {
684
- const found = handle.dsl.findPositionByAsset(asset);
685
- if (found)
686
- matches.push({ runtimeId: id, address: found.address, state: found.state });
687
- }
688
- }
689
- catch (err) {
690
- pluginLogger.warn("[senpi-runtime] getDslPositionState error", { runtimeId: id, err });
691
- }
692
- }
693
- if (matches.length === 0) {
694
- respond(false, undefined, {
695
- code: "NOT_FOUND",
696
- message: `No active DSL position found for asset ${asset}`,
697
- });
698
- return;
699
- }
700
- respond(true, { positions: matches });
701
- });
702
- api.registerGatewayMethod("senpi.listDslArchives", async (ctx) => {
703
- const respond = ctx.respond;
704
- const runtimeId = typeof ctx.params?.runtimeId === "string" ? ctx.params.runtimeId : undefined;
705
- const address = typeof ctx.params?.address === "string" ? ctx.params.address : undefined;
706
- const limit = typeof ctx.params?.limit === "number" ? ctx.params.limit : undefined;
707
- pluginLogger.info("[senpi-runtime] senpi.listDslArchives", { runtimeId, address, limit });
708
- let closes = [];
709
- for (const [id, handle] of runtimeHandles) {
710
- if (runtimeId && id !== runtimeId)
711
- continue;
712
- if (!handle.dsl)
713
- continue;
714
- try {
715
- const items = await handle.dsl.listArchivedCloses({ address });
716
- for (const c of items)
717
- closes.push({ ...c, runtimeId: id });
718
- }
719
- catch (err) {
720
- pluginLogger.warn("[senpi-runtime] listDslArchives error", { runtimeId: id, err });
721
- }
722
- }
723
- closes.sort((a, b) => (b.closedAt ?? "").localeCompare(a.closedAt ?? ""));
724
- if (limit && limit > 0)
725
- closes = closes.slice(0, limit);
726
- respond(true, { closes });
727
- });
728
- api.registerGatewayMethod("senpi.getHealthStatus", async (ctx) => {
729
- const respond = ctx.respond;
730
- const updater = autoUpdateCoordinator.getSnapshot();
731
- const runtimeId = typeof ctx.params?.runtimeId === "string" ? ctx.params.runtimeId : undefined;
732
- if (runtimeId) {
733
- const handle = getRuntimeHandleOrRespond(runtimeHandles, runtimeId, respond);
734
- if (!handle) {
735
- return;
736
- }
737
- try {
738
- const status = await handle.getHealthStatus();
739
- respond(true, {
740
- status: status ? { ...status, runtimeId } : null,
741
- updater,
742
- });
743
- }
744
- catch (err) {
745
- api.logger.warn("[senpi-runtime] getHealthStatus error", { runtimeId, err });
746
- respond(false, undefined, {
747
- code: "INTERNAL_ERROR",
748
- message: `Failed to get health status for runtime ${runtimeId}: ${formatGatewayError(err)}`,
749
- });
750
- }
751
- return;
752
- }
753
- const statuses = await collectRuntimeHealthStatuses(runtimeHandles, api.logger);
754
- respond(true, { statuses, updater });
755
- });
756
- api.registerGatewayMethod("senpi.getSystemState", async (ctx) => {
757
- const respond = ctx.respond;
758
- const updater = autoUpdateCoordinator.getSnapshot();
759
- const runtimeId = typeof ctx.params?.runtimeId === "string" ? ctx.params.runtimeId : undefined;
760
- if (runtimeId) {
761
- const handle = getRuntimeHandleOrRespond(runtimeHandles, runtimeId, respond);
762
- if (!handle) {
763
- return;
764
- }
765
- try {
766
- const state = await handle.getSystemState();
767
- respond(true, {
768
- state: state ? { ...state, runtimeId } : null,
769
- updater,
770
- });
771
- }
772
- catch (err) {
773
- api.logger.warn("[senpi-runtime] getSystemState error", { runtimeId, err });
774
- respond(false, undefined, {
775
- code: "INTERNAL_ERROR",
776
- message: `Failed to get system state for runtime ${runtimeId}: ${formatGatewayError(err)}`,
777
- });
778
- }
779
- return;
780
- }
781
- const states = await collectRuntimeSystemStates(runtimeHandles, api.logger, baseStateDir);
782
- respond(true, { states, updater });
783
- });
784
- api.logger.info(`[senpi-runtime] v${VERSION} plugin registered — stateDir: ${baseStateDir}`);
785
- },
786
- };
787
- function getRuntimeHandleOrRespond(runtimeHandles, runtimeId, respond) {
788
- const handle = runtimeHandles.get(runtimeId);
789
- if (handle) {
790
- return handle;
791
- }
792
- respond(false, undefined, {
793
- code: "NOT_FOUND",
794
- message: `No running runtime found for id ${runtimeId}`,
795
- });
796
- return null;
797
- }
798
- /**
799
- * Parse the gateway request shape for `senpi.ingestExternalScannerData`.
2
+ * Plugin entry — thin wrapper that initializes dd-trace before loading the
3
+ * real plugin module.
800
4
  *
801
- * The plugin contract keeps `address` at the gateway layer because the plugin
802
- * owns the map of running runtimes keyed by runtime id, while the runtime's
803
- * programmatic ingest API is already scoped to one strategy wallet. This
804
- * helper validates only the routing-critical fields (`address`, `scanner`) and
805
- * forwards the remaining payload as-is so the runtime keeps ownership of the
806
- * external-scanner data contract.
807
- */
808
- function parseGatewayExternalScannerIngestParams(params) {
809
- const address = typeof params?.address === "string" ? params.address.trim() : "";
810
- if (!address) {
811
- throw new ExternalScannerIngestError("INVALID_REQUEST", "External scanner ingest requires address as a non-empty string.");
812
- }
813
- const scanner = typeof params?.scanner === "string" ? params.scanner.trim() : "";
814
- if (!scanner) {
815
- throw new ExternalScannerIngestError("INVALID_REQUEST", "External scanner ingest requires scanner as a non-empty string.");
816
- }
817
- return {
818
- address,
819
- request: {
820
- scanner,
821
- asset: params?.asset,
822
- direction: params?.direction,
823
- score: params?.score,
824
- signal_type: params?.signal_type,
825
- data: params?.data,
826
- signals: params?.signals,
827
- },
828
- };
829
- }
830
- /**
831
- * Resolve one running runtime by strategy wallet address.
5
+ * Why this file exists:
6
+ * ESM hoists static `import` statements above any module-body code. If
7
+ * dd-trace.init() lived inside `plugin.ts`, the `import { ... } from "fastify"`
8
+ * line at the top of that file would already have loaded Fastify (with
9
+ * un-patched prototypes) before init() ran. dd-trace can't patch modules
10
+ * retroactively, so the in-file gate would yield zero coverage.
11
+ *
12
+ * This wrapper sidesteps the problem. ESM resolves the static imports below
13
+ * in source order: `dd-trace/initialize.mjs` runs first (registering the
14
+ * ESM loader hook + CJS require interceptors), then `./plugin.js` loads.
15
+ * Anything `plugin.ts` imports — Fastify, our HTTP server, the Senpi MCP
16
+ * client — flows through dd-trace's hooks and gets patched.
17
+ *
18
+ * We can't rely on `NODE_OPTIONS="--require dd-trace/init"` because the
19
+ * openclaw container's env is owned by upstream and out of our control.
20
+ *
21
+ * Caveat — partial coverage:
22
+ * Modules that the OpenClaw harness already loaded before importing this
23
+ * plugin (e.g. its own `http` usage) are NOT patched. dd-trace can only
24
+ * patch modules that are loaded *after* its hooks are installed. Within
25
+ * our plugin's own object graph, that's everything; outside it, nothing.
26
+ *
27
+ * Gating:
28
+ * `dd-trace/initialize.mjs` reads `DD_TRACE_ENABLED` and other `DD_*` env
29
+ * vars internally. With no agent configured, it stays a near-no-op — no
30
+ * spans are emitted and the connection-failure noise is silent. Tests do
31
+ * not need to opt out.
832
32
  *
833
- * Runtime handles are stored by runtime id, but the external-scanner gateway
834
- * contract routes by wallet address because the ingest payload comes from an
835
- * operator or upstream system that knows which strategy wallet it is targeting.
836
- * Runtime install already enforces one running runtime per wallet, so a
837
- * case-insensitive wallet match is enough to identify the correct runtime.
33
+ * Operator docs: see `docs/runtime-docs/runtime-api.md` § "Tracing (Datadog APM)".
838
34
  */
839
- function getRuntimeHandleByAddressOrRespond(runtimeHandles, address, respond) {
840
- const normalizedAddress = address.toLowerCase();
841
- for (const [runtimeId, handle] of runtimeHandles) {
842
- if (handle.wallet.toLowerCase() === normalizedAddress) {
843
- return { runtimeId, handle };
844
- }
845
- }
846
- respond(false, undefined, {
847
- code: "NOT_FOUND",
848
- message: `No running runtime found for wallet address "${address}".`,
849
- });
850
- return null;
851
- }
852
- async function collectRuntimeHealthStatuses(runtimeHandles, logger) {
853
- return (await Promise.all(Array.from(runtimeHandles, async ([runtimeId, handle]) => {
854
- try {
855
- const status = await handle.getHealthStatus();
856
- return status ? { ...status, runtimeId } : null;
857
- }
858
- catch (err) {
859
- logger.warn("[senpi-runtime] getHealthStatus error", { runtimeId, err });
860
- return createGatewayHealthErrorStatus(runtimeId, err);
861
- }
862
- }))).filter((status) => status !== null);
863
- }
864
- async function collectRuntimeSystemStates(runtimeHandles, logger, baseStateDir) {
865
- return (await Promise.all(Array.from(runtimeHandles, async ([runtimeId, handle]) => {
866
- try {
867
- const state = await handle.getSystemState();
868
- return state ? { ...state, runtimeId } : null;
869
- }
870
- catch (err) {
871
- logger.warn("[senpi-runtime] getSystemState error", { runtimeId, err });
872
- return createGatewaySystemStateError(runtimeId, join(baseStateDir, runtimeId), err);
873
- }
874
- }))).filter((state) => state !== null);
875
- }
876
- function createGatewayHealthErrorStatus(runtimeId, error) {
877
- const now = new Date().toISOString();
878
- const message = formatGatewayError(error);
879
- return {
880
- runtimeId,
881
- runtimeName: runtimeId,
882
- startedAt: now,
883
- generatedAt: now,
884
- health: "unhealthy",
885
- logLevel: getLogLevel(),
886
- components: {
887
- scanners: {
888
- component: "scanners",
889
- health: "unhealthy",
890
- updatedAt: now,
891
- summary: "Failed to query scanners health.",
892
- error: message,
893
- totals: {
894
- registered: 0,
895
- enabled: 0,
896
- inFlight: 0,
897
- degraded: 0,
898
- unhealthy: 1,
899
- },
900
- scanners: [],
901
- },
902
- },
903
- };
904
- }
905
- function createGatewaySystemStateError(runtimeId, stateDir, error) {
906
- const now = new Date().toISOString();
907
- const message = formatGatewayError(error);
908
- return {
909
- runtimeId,
910
- runtimeName: runtimeId,
911
- stateDir,
912
- startedAt: now,
913
- generatedAt: now,
914
- health: "unhealthy",
915
- logLevel: getLogLevel(),
916
- components: {
917
- scanners: {
918
- component: "scanners",
919
- health: "unhealthy",
920
- updatedAt: now,
921
- error: message,
922
- state: {
923
- totalRegistered: 0,
924
- totalEnabled: 0,
925
- scanners: [],
926
- },
927
- },
928
- },
929
- };
930
- }
931
- function formatGatewayError(error) {
932
- return error instanceof Error ? error.message : String(error);
933
- }
934
- export default senpiRuntimePlugin;
35
+ import "dd-trace/initialize.mjs";
36
+ export { default } from "./plugin.js";
37
+ export * from "./plugin.js";
935
38
  //# sourceMappingURL=index.js.map