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

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