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