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