miravo 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +1 -1
  2. package/console-dist/assets/activity-DsWeRq4h.js +1 -0
  3. package/console-dist/assets/api-4AqKvsm9.js +1 -0
  4. package/console-dist/assets/arrow-right-Ea_UhTNi.js +1 -0
  5. package/console-dist/assets/arrow-up-down-DFSjzzl2.js +1 -0
  6. package/console-dist/assets/blueprint-card-classes-DBFCDy0M.js +1 -0
  7. package/console-dist/assets/box-C1WaoOMF.js +1 -0
  8. package/console-dist/assets/card-BjeP32PN.js +1 -0
  9. package/console-dist/assets/catalog-BJzyzbLR.js +1 -0
  10. package/console-dist/assets/catalog-DKjEm-c4.js +1 -0
  11. package/console-dist/assets/catalog-template-icons-BrUeHaCY.js +1 -0
  12. package/console-dist/assets/checkbox-DZlJXTE4.js +1 -0
  13. package/console-dist/assets/chunk-OE4NN4TA-CEjpfhS6.js +3 -0
  14. package/console-dist/assets/combobox-BGnuCYxO.js +1 -0
  15. package/console-dist/assets/control-CPhvwx9o.js +1 -0
  16. package/console-dist/assets/control-Cg2up9NA.js +1 -0
  17. package/console-dist/assets/copy-button-WkbNkMcd.js +1 -0
  18. package/console-dist/assets/createLucideIcon-Bwxw859K.js +1 -0
  19. package/console-dist/assets/deploy-tab-JeWDwPoZ.js +1 -0
  20. package/console-dist/assets/dist-BhbDML0a.js +1 -0
  21. package/console-dist/assets/dist-Cy8XTNFT.js +2 -0
  22. package/console-dist/assets/download-DQ6NH16U.js +1 -0
  23. package/console-dist/assets/engine-store-CrLnz692.js +1 -0
  24. package/console-dist/assets/events-CXm29Ok4.js +1 -0
  25. package/console-dist/assets/events-D01IxhnP.js +1 -0
  26. package/console-dist/assets/fleet-CfxbKXt9.js +1 -0
  27. package/console-dist/assets/fleet-lotMGVqe.js +1 -0
  28. package/console-dist/assets/format-kXTonpDJ.js +1 -0
  29. package/console-dist/assets/gauge-Ci8zNZlk.js +1 -0
  30. package/console-dist/assets/get-error-message-3Q5Q-2G5.js +1 -0
  31. package/console-dist/assets/index-CVPKSDvJ.js +12 -0
  32. package/console-dist/assets/index-DJkgDeun.css +2 -0
  33. package/console-dist/assets/input-BWEQFptx.js +1 -0
  34. package/console-dist/assets/instance-detail-C5IVwuh3.js +1 -0
  35. package/console-dist/assets/label-uephX5ZG.js +1 -0
  36. package/console-dist/assets/layers-CUsLQ1fq.js +1 -0
  37. package/console-dist/assets/login-C3RJli0m.js +126 -0
  38. package/console-dist/assets/models-B_UioWQ5.js +1 -0
  39. package/console-dist/assets/models-_IPlPiZ7.js +1 -0
  40. package/console-dist/assets/not-found-B8gAm08S.js +1 -0
  41. package/console-dist/assets/platform-targets-R3T-4eJ7.js +1 -0
  42. package/console-dist/assets/platforms-BWh0BQ3Y.js +1 -0
  43. package/console-dist/assets/platforms-DStNbtVc.js +1 -0
  44. package/console-dist/assets/proxy-CsnYqnPp.js +9 -0
  45. package/console-dist/assets/query-keys-BvtE7BMs.js +1 -0
  46. package/console-dist/assets/radio-CoHegOv5.js +1 -0
  47. package/console-dist/assets/rolldown-runtime-COnpUsM8.js +1 -0
  48. package/console-dist/assets/select-CeO4vP0G.js +1 -0
  49. package/console-dist/assets/select-display-items-CIzY8953.js +1 -0
  50. package/console-dist/assets/server-D9Kfn8fQ.js +1 -0
  51. package/console-dist/assets/shallow-6lGjQhtJ.js +1 -0
  52. package/console-dist/assets/tags-CiXOIHtY.js +4 -0
  53. package/console-dist/assets/tags-FQCXIxrP.js +1 -0
  54. package/console-dist/assets/tooltip-HGLF366Q.js +1 -0
  55. package/console-dist/assets/transition-nav-link-Df4Rk6vV.js +1 -0
  56. package/console-dist/assets/transition-types-CPlGtM8w.js +1 -0
  57. package/console-dist/assets/triangle-alert-adNk_sea.js +1 -0
  58. package/console-dist/assets/use-platform-stream-DGbK1k2L.js +2 -0
  59. package/console-dist/assets/use-transition-navigate-CCpcWXB0.js +2 -0
  60. package/console-dist/assets/validation-Blvud9_O.js +1 -0
  61. package/console-dist/assets/vendor-charts-CAZdaPlq.js +60 -0
  62. package/console-dist/assets/vendor-table-wd8JuMmT.js +4 -0
  63. package/console-dist/assets/vendor-ui-ByahnaY0.js +1 -0
  64. package/console-dist/index.html +70 -2
  65. package/package.json +9 -8
  66. package/src/__tests__/integration/executable-methods-runner.ts +7 -6
  67. package/src/__tests__/integration/executable-methods.integration.ts +214 -122
  68. package/src/__tests__/integration/opcua-concurrent-clients.integration.ts +314 -0
  69. package/src/commands/adapter.ts +180 -7
  70. package/src/commands/apply.test.ts +62 -0
  71. package/src/commands/apply.ts +216 -0
  72. package/src/commands/cleanup.test.ts +34 -0
  73. package/src/commands/cleanup.ts +201 -0
  74. package/src/commands/export.test.ts +51 -0
  75. package/src/commands/export.ts +404 -0
  76. package/src/commands/fork.ts +2 -2
  77. package/src/commands/inject.ts +2 -2
  78. package/src/commands/load.ts +1 -1
  79. package/src/commands/logs.ts +13 -15
  80. package/src/commands/models.test.ts +1 -1
  81. package/src/commands/models.ts +1 -1
  82. package/src/commands/pause.ts +3 -3
  83. package/src/commands/platforms.test.ts +186 -0
  84. package/src/commands/platforms.ts +371 -0
  85. package/src/commands/remove.ts +1 -1
  86. package/src/commands/reset.ts +2 -2
  87. package/src/commands/spawn.ts +2 -2
  88. package/src/commands/speed.ts +2 -2
  89. package/src/commands/start/adapter-config.ts +157 -0
  90. package/src/commands/start/catalog-le-dt.test.ts +50 -0
  91. package/src/commands/start/catalog-le-dt.ts +187 -0
  92. package/src/commands/start/catalog-model-schema.ts +89 -0
  93. package/src/commands/start/catalog-template-detail.ts +54 -0
  94. package/src/commands/start/daemon.ts +255 -0
  95. package/src/commands/start/display.ts +150 -0
  96. package/src/commands/start/engine-setup.ts +247 -0
  97. package/src/commands/start/events.ts +126 -0
  98. package/src/commands/start/index.ts +897 -0
  99. package/src/commands/start/protocol-plans.ts +239 -0
  100. package/src/commands/start/template-loader.ts +197 -0
  101. package/src/commands/start/template-resolver.ts +185 -0
  102. package/src/commands/start/types.ts +73 -0
  103. package/src/commands/start.test.ts +137 -16
  104. package/src/commands/status.ts +1 -1
  105. package/src/commands/stop.ts +19 -8
  106. package/src/commands/templates.test.ts +1 -1
  107. package/src/commands/templates.ts +1 -3
  108. package/src/index.ts +11 -3
  109. package/src/lib/admin-auth.ts +157 -0
  110. package/src/lib/admin-client.test.ts +31 -15
  111. package/src/lib/admin-client.ts +106 -6
  112. package/src/lib/admin-platform-routes.ts +1017 -0
  113. package/src/lib/admin-platform-stream.test.ts +434 -0
  114. package/src/lib/admin-platform-stream.ts +788 -0
  115. package/src/lib/admin-responses.ts +211 -0
  116. package/src/lib/admin-server.test.ts +274 -55
  117. package/src/lib/admin-server.ts +387 -248
  118. package/src/lib/auth-store.ts +87 -0
  119. package/src/lib/daemon-registry.ts +12 -14
  120. package/src/lib/le/le-apply.test.ts +591 -0
  121. package/src/lib/le/le-apply.ts +832 -0
  122. package/src/lib/le/le-auth.ts +89 -0
  123. package/src/lib/le/le-cleanup.test.ts +168 -0
  124. package/src/lib/le/le-cleanup.ts +399 -0
  125. package/src/lib/le/le-cli-helpers.ts +77 -0
  126. package/src/lib/le/le-client.ts +184 -0
  127. package/src/lib/le/le-concurrency.test.ts +157 -0
  128. package/src/lib/le/le-concurrency.ts +78 -0
  129. package/src/lib/le/le-connection-test.ts +42 -0
  130. package/src/lib/le/le-devicehub-properties.test.ts +53 -0
  131. package/src/lib/le/le-devicehub-properties.ts +33 -0
  132. package/src/lib/le/le-devicehub.ts +213 -0
  133. package/src/lib/le/le-digital-twins.ts +285 -0
  134. package/src/lib/le/le-drivers.ts +23 -0
  135. package/src/lib/le/le-endpoint.ts +40 -0
  136. package/src/lib/le/le-environments.test.ts +73 -0
  137. package/src/lib/le/le-environments.ts +156 -0
  138. package/src/lib/le/le-markers.ts +87 -0
  139. package/src/lib/le/le-plan.test.ts +26 -0
  140. package/src/lib/le/le-plan.ts +109 -0
  141. package/src/lib/le/le-platform-operations.test.ts +198 -0
  142. package/src/lib/le/le-platform-operations.ts +340 -0
  143. package/src/lib/le/le-static-model-schema.ts +78 -0
  144. package/src/lib/le/le-static-planner.test.ts +255 -0
  145. package/src/lib/le/le-static-planner.ts +442 -0
  146. package/src/lib/le/le-template-exporter.test.ts +527 -0
  147. package/src/lib/le/le-template-exporter.ts +459 -0
  148. package/src/lib/le/le-value-types.ts +23 -0
  149. package/src/lib/mqtt-client.ts +1 -2
  150. package/src/lib/resolve-simulation.ts +1 -6
  151. package/src/lib/session-store.ts +110 -0
  152. package/src/lib/shutdown.test.ts +184 -2
  153. package/src/lib/shutdown.ts +104 -34
  154. package/src/lib/template-category.ts +3 -3
  155. package/src/lib/template-locator.ts +8 -2
  156. package/src/lib/ws-hub.ts +72 -46
  157. package/src/logger.ts +39 -14
  158. package/src/output.ts +3 -0
  159. package/console-dist/assets/index-C3XMYq26.css +0 -2
  160. package/console-dist/assets/index-hUJSpKtB.js +0 -119
  161. package/src/commands/start.ts +0 -2023
@@ -1,2023 +0,0 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { basename, resolve } from "node:path";
3
- import type { Option as ClackOption } from "@clack/prompts";
4
- import { isCancel, select } from "@clack/prompts";
5
- import type { ContentCatalog, ControlPlane, Engine, TwinRuntime } from "@miravo/core";
6
- import {
7
- createControlPlane,
8
- createEngine,
9
- discoverTemplates,
10
- loadTemplate,
11
- loadTwinModel,
12
- resolveMiravoHome,
13
- resolveModelPath,
14
- validateFullTemplate,
15
- } from "@miravo/core";
16
- import { MQTTAdapter } from "@miravo/mqtt";
17
- import { OPCUAAdapter } from "@miravo/opcua";
18
- import type {
19
- CatalogTemplate,
20
- DiscoveredTemplate,
21
- MiravoTemplate,
22
- TemplateRun,
23
- TwinModel,
24
- } from "@miravo/shared";
25
- import {
26
- ConfigNotFoundError,
27
- ConfigValidationError,
28
- DEFAULT_MQTT_PORT,
29
- DEFAULT_OPCUA_PORT,
30
- DEFAULT_TICK_INTERVAL_MS,
31
- DEFAULT_TIME_MULTIPLIER,
32
- MIRAVO_VERSION,
33
- MiravoError,
34
- MiravoTemplateSchema,
35
- PersistedStateSchema,
36
- SimulationNameSchema,
37
- TWIN_FILE_EXTENSION,
38
- TwinModelSchema,
39
- } from "@miravo/shared";
40
- import { Glob } from "bun";
41
- import type { Command } from "commander";
42
- import { box, colors, stripAnsi } from "consola/utils";
43
- import { parse as parseYAML } from "yaml";
44
- import { startAdminServer } from "../lib/admin-server.ts";
45
- import type { DaemonRegistryEntry } from "../lib/daemon-registry.ts";
46
- import {
47
- acquireNameLock,
48
- checkNameConflict,
49
- checkPortConflicts,
50
- displayHost,
51
- isPidAlive,
52
- writeEntry,
53
- } from "../lib/daemon-registry.ts";
54
- import {
55
- parseDurationMs,
56
- parseNonNegativeInt,
57
- parsePort,
58
- parsePositiveFloat,
59
- parsePositiveInt,
60
- } from "../lib/parse.ts";
61
- import { createShutdownController, printSummaryLine } from "../lib/shutdown.ts";
62
- import {
63
- groupTemplatesByCategory,
64
- isStressBenchmarkTemplate,
65
- sortTemplatesByCategoryAndName,
66
- } from "../lib/template-category.ts";
67
- import {
68
- createCatalog,
69
- discoverPreferredLocalTemplates,
70
- isTemplatePathLike,
71
- resolveTemplateIdentifier,
72
- } from "../lib/template-locator.ts";
73
- import { buildUNSBasePath, collectReferencedModels, forEachTwin } from "../lib/template-utils.ts";
74
- import {
75
- clearRuntimeLogContext,
76
- configLog,
77
- controlLog,
78
- engineLog,
79
- faultLog,
80
- handleCommandError,
81
- isPlain,
82
- lifecycleLog,
83
- mqttLog,
84
- opcuaLog,
85
- setRuntimeLogContext,
86
- writeOutput,
87
- } from "../logger.ts";
88
- import { formatKeyValue, formatTable } from "../output.ts";
89
-
90
- interface StartOptions {
91
- readonly name?: string;
92
- readonly template?: string;
93
- readonly modelsDir?: string;
94
- readonly speed?: number;
95
- readonly seed?: number;
96
- readonly tick?: number;
97
- readonly mqttPort?: number;
98
- readonly mqttHost?: string;
99
- readonly mqttMode?: string;
100
- readonly mqttUrl?: string;
101
- readonly mqttUsername?: string;
102
- readonly mqttPassword?: string;
103
- readonly mqtt?: boolean;
104
- readonly opcuaPort?: number;
105
- readonly opcuaHost?: string;
106
- readonly opcua?: boolean;
107
- readonly adminHost?: string;
108
- readonly adminPort?: number;
109
- readonly dryRun?: boolean;
110
- readonly summaryInterval?: number;
111
- readonly noUi?: boolean;
112
- readonly resetState?: boolean;
113
- readonly detach?: boolean;
114
- readonly command?: Command;
115
- }
116
-
117
- interface RestoreSummary {
118
- readonly instanceCount: number;
119
- readonly templateRunCount: number;
120
- readonly adapterCount: number;
121
- }
122
-
123
- interface ProtocolBootPlan {
124
- readonly name: "mqtt" | "opcua";
125
- readonly shouldEnable: boolean;
126
- readonly overrideRestore: boolean;
127
- }
128
-
129
- type ProtocolOptionSource =
130
- | "mqtt"
131
- | "opcua"
132
- | "mqttPort"
133
- | "mqttHost"
134
- | "mqttMode"
135
- | "mqttUrl"
136
- | "mqttUsername"
137
- | "mqttPassword"
138
- | "opcuaPort"
139
- | "opcuaHost";
140
-
141
- type MqttMode = "embedded" | "external";
142
-
143
- /** Resolve the path to the built console dist directory. Returns undefined if not found. */
144
- function resolveConsoleDir(): string | undefined {
145
- // 1. Compiled standalone binary: Bun.main resolves to a /$bunfs/ virtual path.
146
- // Look for console-dist/ packaged alongside the binary.
147
- if (Bun.main.startsWith("/$bunfs/")) {
148
- const binaryDir = new URL(".", `file://${process.execPath}`).pathname.replace(/\/$/, "");
149
- const sibling = `${binaryDir}/console-dist`;
150
- if (Bun.file(`${sibling}/index.html`).size > 0) return sibling;
151
- }
152
-
153
- // 2. Dev / Docker: resolve via workspace package (@miravo/console is a devDependency,
154
- // available in workspace but not when installed from npm).
155
- try {
156
- const resolved = import.meta.resolve("@miravo/console");
157
- const resolvedDir = new URL(".", resolved).pathname.replace(/\/$/, "");
158
- if (resolvedDir.endsWith("/dist")) return resolvedDir;
159
- return `${resolvedDir}/dist`;
160
- } catch {
161
- // @miravo/console not installed (npm/bunx) — fall through
162
- }
163
-
164
- // 3. npm install / bunx: look for console-dist/ shipped inside the published package.
165
- // start.ts is at packages/cli/src/commands/ → ../../console-dist/
166
- const shipped = resolve(import.meta.dir, "..", "..", "console-dist");
167
- if (existsSync(`${shipped}/index.html`)) return shipped;
168
-
169
- return undefined;
170
- }
171
-
172
- interface MqttRunOverrides {
173
- readonly mode?: MqttMode;
174
- readonly host?: string;
175
- readonly url?: string;
176
- readonly username?: string;
177
- readonly password?: string;
178
- readonly drainBudget?: number;
179
- readonly batchSize?: number;
180
- readonly brokerConcurrency?: number;
181
- }
182
-
183
- const MAX_ERROR_CONTEXT_KEYS = 256;
184
- const ERROR_CONTEXT_OVERFLOW = "__overflow__";
185
-
186
- /**
187
- * Register the `miravo start` command with the root Commander program.
188
- * Resolves template, creates the engine, starts MQTT, and runs the simulation loop.
189
- */
190
- export function registerStartCommand(program: Command): void {
191
- program
192
- .command("start")
193
- .description("Start a simulation from a template")
194
- .option("-n, --name <name>", "Simulation name (env: MIRAVO_NAME, flag takes precedence)")
195
- .option(
196
- "-t, --template <id|name|path,...>",
197
- "Template id, name, path, or comma-separated list (env: MIRAVO_TEMPLATE, flag takes precedence)",
198
- )
199
- .option("--models-dir <path>", "Additional directory to search for .twin.yaml models")
200
- .option("-s, --speed <multiplier>", "Time multiplier (default: 1)", parsePositiveFloat)
201
- .option("--seed <number>", "RNG seed for deterministic simulation", parseNonNegativeInt)
202
- .option("--tick <ms>", "Tick interval in milliseconds (default: 1000)", parseDurationMs)
203
- .option(
204
- "-p, --mqtt-port <number>",
205
- "MQTT broker port (default: 1883, env: MIRAVO_MQTT_PORT)",
206
- parsePort,
207
- )
208
- .option("--mqtt-host <host>", "MQTT bind host (default: 127.0.0.1, env: MIRAVO_MQTT_HOST)")
209
- .option("--mqtt-mode <mode>", "MQTT mode: embedded | external (env: MIRAVO_MQTT_MODE)")
210
- .option("--mqtt-url <url>", "External MQTT broker URL (env: MIRAVO_MQTT_URL)")
211
- .option("--mqtt-username <username>", "External MQTT username (env: MIRAVO_MQTT_USERNAME)")
212
- .option("--mqtt-password <password>", "External MQTT password (env: MIRAVO_MQTT_PASSWORD)")
213
- .option("--no-mqtt", "Disable MQTT broker")
214
- .option("--opcua", "Enable OPC UA server")
215
- .option(
216
- "--opcua-port <number>",
217
- "OPC UA server port (default: 4840, env: MIRAVO_OPCUA_PORT)",
218
- parsePort,
219
- )
220
- .option("--opcua-host <host>", "OPC UA server bind host (env: MIRAVO_OPCUA_HOST)")
221
- .option("--admin-host <host>", "Admin server host (default: 127.0.0.1, env: MIRAVO_ADMIN_HOST)")
222
- .option(
223
- "--admin-port <number>",
224
- "Admin server port (default: 8080, env: MIRAVO_ADMIN_PORT)",
225
- parsePort,
226
- )
227
- .option("-d, --detach", "Start simulation in background (daemon mode)")
228
- .option("--dry-run", "Validate config and print summary without starting")
229
- .option("--no-ui", "Disable the embedded web console")
230
- .option("--reset-state", "Reset persisted state — start fresh (ignore any saved snapshot)")
231
- .option(
232
- "--summary-interval <seconds>",
233
- "Seconds between periodic summary lines (default: 5)",
234
- parsePositiveInt,
235
- )
236
- .addHelpText(
237
- "after",
238
- `
239
- Examples:
240
- $ miravo start Start with auto-detected template
241
- $ miravo start -t water-treatment Start a specific template
242
- $ miravo start -t smart-factory,water-treatment Start with two templates
243
- $ miravo start -d --name my-sim Start in background (daemon mode)
244
- $ miravo start -s 10 --seed 42 Run at 10x speed with fixed seed
245
- $ miravo start --no-mqtt --opcua Disable MQTT, enable OPC UA
246
- $ miravo start --dry-run Validate and print summary only`,
247
- )
248
- .action(async (options: StartOptions, command: Command) => {
249
- await startAction({ ...options, command });
250
- });
251
- }
252
-
253
- // ---------------------------------------------------------------------------
254
- // Start action orchestration
255
- // ---------------------------------------------------------------------------
256
-
257
- async function startAction(options: StartOptions): Promise<void> {
258
- let runtimeLogContextSet = false;
259
- let shutdown: ReturnType<typeof createShutdownController> | null = null;
260
- let engine: Engine | undefined;
261
- let stopCliResources = (): void => {};
262
- try {
263
- const catalog = createCatalog();
264
-
265
- // Resolve env-var fallbacks for common options
266
- const templateOptionRaw = options.template ?? Bun.env["MIRAVO_TEMPLATE"];
267
- // Support comma-separated template identifiers: first is the boot template, rest loaded after startup
268
- const templateParts: string[] = templateOptionRaw
269
- ? templateOptionRaw
270
- .split(",")
271
- .map((s) => s.trim())
272
- .filter(Boolean)
273
- : [];
274
- const templateOption: string | undefined = templateParts[0];
275
- const extraTemplateIdentifiers: string[] = templateParts.slice(1);
276
- const simulationNameEnv = Bun.env["MIRAVO_NAME"];
277
- // Protocol selection: CLI flags decide which protocols run
278
- const mqttEnabled = options.mqtt !== false; // --no-mqtt disables
279
- const opcuaEnabled = options.opcua === true; // --opcua enables
280
-
281
- // Warn on ignored protocol-specific flags
282
- if (!mqttEnabled) {
283
- if (options.mqttPort !== undefined) {
284
- configLog.warn("--mqtt-port ignored because MQTT is disabled.");
285
- }
286
- if (options.mqttHost !== undefined) {
287
- configLog.warn("--mqtt-host ignored because MQTT is disabled.");
288
- }
289
- if (options.mqttMode !== undefined) {
290
- configLog.warn("--mqtt-mode ignored because MQTT is disabled.");
291
- }
292
- }
293
- if (!opcuaEnabled) {
294
- if (options.opcuaPort !== undefined) {
295
- configLog.warn(
296
- "--opcua-port ignored because OPC UA is not enabled. Use --opcua to enable it.",
297
- );
298
- }
299
- if (options.opcuaHost !== undefined) {
300
- configLog.warn(
301
- "--opcua-host ignored because OPC UA is not enabled. Use --opcua to enable it.",
302
- );
303
- }
304
- }
305
-
306
- const adminHost = options.adminHost ?? Bun.env["MIRAVO_ADMIN_HOST"] ?? "127.0.0.1";
307
- const adminPortEnv = Bun.env["MIRAVO_ADMIN_PORT"];
308
- if (adminHost.trim().length === 0) {
309
- throw new ConfigValidationError({
310
- message: "Invalid admin server host: value is empty.",
311
- fix: "Set --admin-host / MIRAVO_ADMIN_HOST to a valid host (for example, 127.0.0.1 or 0.0.0.0).",
312
- });
313
- }
314
-
315
- // MQTT env overrides — only parsed when MQTT is enabled
316
- let portOption = options.mqttPort;
317
- let mqttOverrides: MqttRunOverrides = {};
318
- if (mqttEnabled) {
319
- const portEnv = Bun.env["MIRAVO_MQTT_PORT"];
320
- const mqttHost = options.mqttHost ?? Bun.env["MIRAVO_MQTT_HOST"];
321
- const mqttMode = parseMqttModeOption(options.mqttMode ?? Bun.env["MIRAVO_MQTT_MODE"]);
322
- const mqttUrl = options.mqttUrl ?? Bun.env["MIRAVO_MQTT_URL"];
323
- const mqttUsername = options.mqttUsername ?? Bun.env["MIRAVO_MQTT_USERNAME"];
324
- const mqttPassword = options.mqttPassword ?? Bun.env["MIRAVO_MQTT_PASSWORD"];
325
- // Tuning env vars for adapter performance
326
- const drainBudgetEnv = Bun.env["MIRAVO_MQTT_DRAIN_BUDGET"];
327
- const batchSizeEnv = Bun.env["MIRAVO_MQTT_BATCH_SIZE"];
328
- const brokerConcurrencyEnv = Bun.env["MIRAVO_MQTT_BROKER_CONCURRENCY"];
329
- const drainBudget = drainBudgetEnv ? parsePositiveInt(drainBudgetEnv) : undefined;
330
- const batchSize = batchSizeEnv ? parsePositiveInt(batchSizeEnv) : undefined;
331
- const brokerConcurrency = brokerConcurrencyEnv
332
- ? parsePositiveInt(brokerConcurrencyEnv)
333
- : undefined;
334
- mqttOverrides = {
335
- ...(mqttMode !== undefined ? { mode: mqttMode } : {}),
336
- ...(mqttHost !== undefined && mqttHost.length > 0 ? { host: mqttHost } : {}),
337
- ...(mqttUrl !== undefined && mqttUrl.length > 0 ? { url: mqttUrl } : {}),
338
- ...(mqttUsername !== undefined && mqttUsername.length > 0
339
- ? { username: mqttUsername }
340
- : {}),
341
- ...(mqttPassword !== undefined && mqttPassword.length > 0
342
- ? { password: mqttPassword }
343
- : {}),
344
- ...(drainBudget !== undefined ? { drainBudget } : {}),
345
- ...(batchSize !== undefined ? { batchSize } : {}),
346
- ...(brokerConcurrency !== undefined ? { brokerConcurrency } : {}),
347
- };
348
- if (portOption === undefined && portEnv) {
349
- try {
350
- portOption = parsePort(portEnv);
351
- } catch {
352
- throw new ConfigValidationError({
353
- message: `Invalid MIRAVO_MQTT_PORT environment variable: "${portEnv}".`,
354
- fix: "Set MIRAVO_MQTT_PORT to a valid port number between 1 and 65535 (for example, 1883).",
355
- });
356
- }
357
- }
358
- if (mqttHost !== undefined && mqttHost.trim().length === 0) {
359
- throw new ConfigValidationError({
360
- message: "Invalid MQTT bind host: value is empty.",
361
- fix: "Set --mqtt-host / MIRAVO_MQTT_HOST to a valid host (for example, 127.0.0.1 or 0.0.0.0).",
362
- });
363
- }
364
- }
365
-
366
- // OPC UA env overrides — only parsed when OPC UA is enabled
367
- let opcuaPort: number | undefined = options.opcuaPort;
368
- let opcuaHost: string | undefined;
369
- let opcuaWriteBudget: number | undefined;
370
- if (opcuaEnabled) {
371
- const opcuaPortEnv = Bun.env["MIRAVO_OPCUA_PORT"];
372
- if (opcuaPort === undefined && opcuaPortEnv) {
373
- try {
374
- opcuaPort = parsePort(opcuaPortEnv);
375
- } catch {
376
- throw new ConfigValidationError({
377
- message: `Invalid MIRAVO_OPCUA_PORT environment variable: "${opcuaPortEnv}".`,
378
- fix: "Set MIRAVO_OPCUA_PORT to a valid port number between 1 and 65535 (for example, 4840).",
379
- });
380
- }
381
- }
382
- opcuaHost = options.opcuaHost ?? Bun.env["MIRAVO_OPCUA_HOST"] ?? undefined;
383
- if (opcuaHost !== undefined && opcuaHost.trim().length === 0) {
384
- throw new ConfigValidationError({
385
- message: "Invalid OPC UA bind host: value is empty.",
386
- fix: "Set --opcua-host / MIRAVO_OPCUA_HOST to a valid host (for example, 0.0.0.0).",
387
- });
388
- }
389
- const writeBudgetEnv = Bun.env["MIRAVO_OPCUA_WRITE_BUDGET"];
390
- if (writeBudgetEnv) {
391
- opcuaWriteBudget = parsePositiveInt(writeBudgetEnv);
392
- }
393
- }
394
-
395
- let adminPort = options.adminPort;
396
- if (adminPort === undefined && adminPortEnv) {
397
- try {
398
- adminPort = parsePort(adminPortEnv);
399
- } catch {
400
- throw new ConfigValidationError({
401
- message: `Invalid MIRAVO_ADMIN_PORT environment variable: "${adminPortEnv}".`,
402
- fix: "Set MIRAVO_ADMIN_PORT to a valid port number between 1 and 65535 (for example, 8080).",
403
- });
404
- }
405
- }
406
- adminPort ??= 8080;
407
-
408
- // Step 1: Resolve template path(s)
409
- // If the simulation name is explicitly known and no template was given,
410
- // peek at persisted state to recover the template path — skipping the
411
- // interactive picker on resume.
412
- let effectiveTemplateOption = templateOption;
413
- if (!effectiveTemplateOption && !options.resetState) {
414
- const knownName = options.name ?? simulationNameEnv;
415
- if (knownName) {
416
- // Named: peek by explicit simulation name
417
- const peeked = await peekStateTemplatePath(knownName);
418
- if (peeked) {
419
- effectiveTemplateOption = peeked;
420
- configLog.debug(`Resuming from persisted state: template=${peeked}`);
421
- }
422
- } else {
423
- // Unnamed: scan state dir — auto-resume if exactly one simulation exists
424
- const peeked = await peekSingleStateTemplatePath();
425
- if (peeked) {
426
- effectiveTemplateOption = peeked;
427
- configLog.debug(`Resuming from persisted state: template=${peeked}`);
428
- }
429
- }
430
- }
431
- const templatePath = await resolveTemplatePath(effectiveTemplateOption, catalog);
432
- configLog.debug(`Resolved template: ${templatePath}`);
433
- // Resolve any additional comma-separated templates upfront so errors surface before engine start
434
- const extraTemplatePaths = await Promise.all(
435
- extraTemplateIdentifiers.map((id) => resolveTemplateIdentifier(id, catalog)),
436
- );
437
-
438
- // Step 2: Load and validate
439
- const { template, models, seed, seedExplicit } = await loadAndValidateTemplate(
440
- templatePath,
441
- options,
442
- catalog,
443
- );
444
- const simulationName = resolveSimulationName({
445
- template,
446
- ...(options.name !== undefined ? { cliName: options.name } : {}),
447
- ...(simulationNameEnv !== undefined ? { envName: simulationNameEnv } : {}),
448
- });
449
- configLog.debug(`Loaded ${models.size} models, seed=${seed} (explicit=${seedExplicit})`);
450
- controlLog.info(`Simulation name: ${simulationName}`);
451
-
452
- // Step 3: Dry-run check
453
- if (options.dryRun) {
454
- printDryRunSummary(template, models, seed, seedExplicit, templatePath);
455
- return;
456
- }
457
-
458
- // Step 3b: Detach check — spawn background process and exit
459
- if (options.detach) {
460
- await detachAction({
461
- simulationName,
462
- templatePath,
463
- seed,
464
- seedExplicit,
465
- adminHost,
466
- adminPort,
467
- mqttPort: options.mqttPort,
468
- mqttHost: options.mqttHost,
469
- mqttEnabled,
470
- opcuaPort,
471
- opcuaHost,
472
- opcuaEnabled,
473
- });
474
- return;
475
- }
476
-
477
- const runId = Bun.env["MIRAVO_DAEMON_RUN_ID"] ?? crypto.randomUUID();
478
- setRuntimeLogContext({ simulationName, runId });
479
- runtimeLogContextSet = true;
480
- controlLog.info(`Run ID: ${runId}`);
481
-
482
- shutdown = createShutdownController({
483
- seed,
484
- seedExplicit,
485
- });
486
- const shutdownRequested = shutdown.waitForShutdownRequest();
487
- shutdown.addTask("finalize", "runtime log context", () => {
488
- if (runtimeLogContextSet) {
489
- clearRuntimeLogContext();
490
- runtimeLogContextSet = false;
491
- }
492
- });
493
-
494
- // Step 4: Create engine and populate
495
- engine = createAndPopulateEngine(
496
- template,
497
- models,
498
- catalog,
499
- seed,
500
- options,
501
- templatePath,
502
- simulationName,
503
- );
504
- shutdown.setEngine(engine);
505
-
506
- // Wire up template loader for runtime loadTemplate commands
507
- // Single discovery pass builds both the path cache and catalog (avoids re-reading YAML)
508
- const { pathCache: templatePathCache, catalog: catalogTemplates } =
509
- await buildTemplateCacheAndCatalog(catalog);
510
- engine.setTemplateLoader(createRuntimeTemplateLoader(catalog, templatePathCache));
511
-
512
- // Load any additional comma-separated templates as extra template runs
513
- for (const extraPath of extraTemplatePaths) {
514
- const result = await engine.execute({
515
- type: "loadTemplate",
516
- templatePath: extraPath,
517
- count: 1,
518
- });
519
- if (!result.success) {
520
- throw new MiravoError(
521
- `Failed to load additional template "${extraPath}": ${result.message}`,
522
- result.error ?? "Check that the template is valid and compatible.",
523
- );
524
- }
525
- configLog.info(`Loaded additional template: ${extraPath}`);
526
- }
527
-
528
- let controlPlane: ControlPlane | null = null;
529
- let adminServer: { endpoint: string; stop: () => void } | null = null;
530
- let lastTickProgressAt = performance.now();
531
- let tickProgressSubscribed = false;
532
- const onTickProgress = (): void => {
533
- lastTickProgressAt = performance.now();
534
- };
535
- let unsubscribeEvents = (): void => {};
536
- let summaryTimer: ReturnType<typeof setInterval> | null = null;
537
-
538
- stopCliResources = (): void => {
539
- controlPlane?.stop();
540
- adminServer?.stop();
541
- if (summaryTimer !== null) {
542
- clearInterval(summaryTimer);
543
- summaryTimer = null;
544
- }
545
- if (tickProgressSubscribed && engine) {
546
- engine.bus.off("tick:complete", onTickProgress);
547
- tickProgressSubscribed = false;
548
- }
549
- unsubscribeEvents();
550
- };
551
-
552
- shutdown.addTask("cleanup", "CLI resources", stopCliResources);
553
-
554
- // Step 5: Register adapter factories and enable active adapters
555
- // Track the last created MQTT adapter via closure (needed for control plane transport)
556
- let lastCreatedMqttAdapter: MQTTAdapter | null = null;
557
- const eng = engine; // const alias for closures (engine is `let` and TS can't narrow across closures)
558
-
559
- const mqttDefaultConfig = buildMQTTDefaultConfig(
560
- template,
561
- portOption,
562
- mqttOverrides,
563
- simulationName,
564
- );
565
- eng.registerAvailableAdapter(
566
- "mqtt",
567
- async (config) => {
568
- const adapter = new MQTTAdapter(eng.bus);
569
- await adapter.start(config);
570
- lastCreatedMqttAdapter = adapter;
571
- return { adapter, endpoint: buildMQTTEndpoint(config) };
572
- },
573
- mqttDefaultConfig,
574
- );
575
-
576
- const opcuaDefaultConfig = buildOPCUADefaultConfig(
577
- template,
578
- opcuaPort,
579
- opcuaHost,
580
- simulationName,
581
- opcuaWriteBudget,
582
- );
583
- eng.registerAvailableAdapter(
584
- "opcua",
585
- async (config) => {
586
- const adapter = new OPCUAAdapter(eng.bus, eng);
587
- await adapter.start(config);
588
- return { adapter, endpoint: buildOPCUAEndpoint(config) };
589
- },
590
- opcuaDefaultConfig,
591
- );
592
-
593
- // Step 5b: Wire control plane (dynamically follows MQTT adapter lifecycle)
594
- function wireControlPlane(): void {
595
- // Stop old control plane before creating a new one (prevents listener leaks)
596
- if (controlPlane) {
597
- controlPlane.stop();
598
- controlPlane = null;
599
- }
600
- const mqttAdapter = lastCreatedMqttAdapter as MQTTAdapter | null;
601
- if (!mqttAdapter) return;
602
- const transport = mqttAdapter.getControlTransport();
603
- if (!transport) return;
604
- controlPlane = createControlPlane({
605
- simulationName,
606
- engine: eng,
607
- transport,
608
- bus: eng.bus,
609
- });
610
- controlPlane.start();
611
- controlLog.info(`active on $miravo/${simulationName}/* topics`);
612
- }
613
-
614
- // Wire now if MQTT was enabled at boot
615
- wireControlPlane();
616
-
617
- // Re-wire on runtime MQTT enable, tear down on disable
618
- eng.bus.on("adapter:enabled", (evt) => {
619
- if (evt.name === "mqtt") wireControlPlane();
620
- });
621
- eng.bus.on("adapter:disabled", (evt) => {
622
- if (evt.name === "mqtt") {
623
- controlPlane?.stop();
624
- controlPlane = null;
625
- lastCreatedMqttAdapter = null;
626
- controlLog.info("control plane stopped (MQTT adapter disabled)");
627
- }
628
- });
629
-
630
- // Step 5c: Subscribe to events + periodic summary before engine.start() so restore events are visible
631
- const errorContextCounts = new Map<string, number>();
632
- unsubscribeEvents = subscribeToEvents(eng, errorContextCounts);
633
- shutdown.setErrorContextCounts(errorContextCounts);
634
- const summaryInterval = options.summaryInterval ?? 5;
635
- summaryTimer = startPeriodicSummary(eng, summaryInterval);
636
-
637
- eng.bus.on("tick:complete", onTickProgress);
638
- tickProgressSubscribed = true;
639
-
640
- let restoredState: RestoreSummary | null = null;
641
- const onRestored = (event: RestoreSummary): void => {
642
- restoredState = event;
643
- };
644
- eng.bus.on("engine:restored", onRestored);
645
- try {
646
- await eng.start();
647
- } finally {
648
- eng.bus.off("engine:restored", onRestored);
649
- }
650
-
651
- // Step 6: Start admin HTTP server after restore + adapter reconciliation
652
- try {
653
- adminServer = startAdminServer({
654
- engine: eng,
655
- network: {
656
- host: adminHost,
657
- port: adminPort,
658
- tickIntervalMs: eng.getState().config.tickIntervalMs,
659
- },
660
- protocols: {
661
- getLastTickProgressAt: () => lastTickProgressAt,
662
- },
663
- ws: {
664
- bus: eng.bus,
665
- getEngineState: () => eng.getMetrics().core.state,
666
- getTickInfo: () => {
667
- const core = eng.getMetrics().core;
668
- return {
669
- tick: core.tickCount,
670
- simulationTime: core.simulationTimeSeconds,
671
- instanceCount: core.instanceCount,
672
- };
673
- },
674
- },
675
- adminToken: Bun.env["MIRAVO_ADMIN_TOKEN"],
676
- consoleDir: options.noUi ? undefined : resolveConsoleDir(),
677
- getCatalog: () => catalogTemplates,
678
- simulationName,
679
- runId,
680
- requestShutdown: (reason) => shutdown?.requestShutdown(reason),
681
- });
682
- controlLog.info(`admin server ready · endpoint: ${colors.cyan(adminServer.endpoint)}`);
683
- } catch (error) {
684
- const message = error instanceof Error ? error.message : String(error);
685
- throw new MiravoError(
686
- `Admin server failed to start on ${adminHost}:${adminPort}: ${message}`,
687
- "Set --admin-port / MIRAVO_ADMIN_PORT to a free port, or change --admin-host.",
688
- );
689
- }
690
-
691
- // Step 7: Print startup banner from the post-restore runtime state
692
- const availableAdapters = eng.getAvailableAdapters();
693
- const mqttEndpoint =
694
- availableAdapters.find((a) => a.name === "mqtt" && a.enabled)?.endpoint ?? null;
695
- const opcuaEndpoint =
696
- availableAdapters.find((a) => a.name === "opcua" && a.enabled)?.endpoint ?? null;
697
- printStartupBanner(
698
- templatePath,
699
- eng,
700
- seed,
701
- seedExplicit,
702
- mqttEndpoint,
703
- opcuaEndpoint,
704
- simulationName,
705
- runId,
706
- adminServer.endpoint,
707
- );
708
-
709
- const restoreSummary = restoredState as RestoreSummary | null;
710
- if (restoreSummary !== null) {
711
- engineLog.info(
712
- `restored saved state · ${colors.bold(String(restoreSummary.instanceCount))} instances · ${colors.bold(String(restoreSummary.templateRunCount))} template runs · ${colors.bold(String(restoreSummary.adapterCount))} adapters`,
713
- );
714
- } else if (options.resetState) {
715
- engineLog.info("starting fresh (--reset-state)");
716
- }
717
-
718
- shutdown.markRunning();
719
- engineLog.success("Simulation started.");
720
- await shutdownRequested;
721
- await shutdown.runShutdown();
722
- shutdown.teardown();
723
- } catch (error) {
724
- if (shutdown?.isShuttingDown()) {
725
- await shutdown.runShutdown();
726
- shutdown.teardown();
727
- return;
728
- }
729
- shutdown?.teardown();
730
- stopCliResources();
731
- try {
732
- await engine?.stop("boot error");
733
- } catch {
734
- // engine may not exist yet or stop may fail — swallow
735
- }
736
- if (runtimeLogContextSet) {
737
- clearRuntimeLogContext();
738
- runtimeLogContextSet = false;
739
- }
740
- handleCommandError(error);
741
- }
742
- }
743
-
744
- // ---------------------------------------------------------------------------
745
- // Detach mode — spawn background simulation
746
- // ---------------------------------------------------------------------------
747
-
748
- interface DetachOptions {
749
- readonly simulationName: string;
750
- readonly templatePath: string;
751
- readonly seed: number;
752
- readonly seedExplicit: boolean;
753
- readonly adminHost: string;
754
- readonly adminPort: number;
755
- readonly mqttPort: number | undefined;
756
- readonly mqttHost: string | undefined;
757
- readonly mqttEnabled: boolean;
758
- readonly opcuaPort: number | undefined;
759
- readonly opcuaHost: string | undefined;
760
- readonly opcuaEnabled: boolean;
761
- }
762
-
763
- async function detachAction(opts: DetachOptions): Promise<void> {
764
- const { simulationName } = opts;
765
-
766
- // 1. Acquire exclusive lock to prevent concurrent starts
767
- const releaseLock = await acquireNameLock(simulationName);
768
- try {
769
- await detachActionLocked(opts, releaseLock);
770
- } catch (error) {
771
- await releaseLock();
772
- throw error;
773
- }
774
- }
775
-
776
- async function detachActionLocked(
777
- opts: DetachOptions,
778
- releaseLock: () => Promise<void>,
779
- ): Promise<void> {
780
- const { simulationName, adminHost, adminPort } = opts;
781
-
782
- // 1. Check name conflict
783
- const existing = await checkNameConflict(simulationName);
784
- if (existing) {
785
- throw new MiravoError(
786
- `Simulation "${simulationName}" is already running (PID ${existing.pid}).`,
787
- `Stop it first: miravo stop ${simulationName}`,
788
- );
789
- }
790
-
791
- // 2. Check port conflicts
792
- const ports = new Map<string, number>();
793
- ports.set("admin", adminPort);
794
- if (opts.mqttEnabled && opts.mqttPort) ports.set("mqtt", opts.mqttPort);
795
- if (opts.mqttEnabled && !opts.mqttPort) ports.set("mqtt", DEFAULT_MQTT_PORT);
796
- if (opts.opcuaEnabled && opts.opcuaPort) ports.set("opcua", opts.opcuaPort);
797
- if (opts.opcuaEnabled && !opts.opcuaPort) ports.set("opcua", DEFAULT_OPCUA_PORT);
798
-
799
- const conflicts = await checkPortConflicts(ports);
800
- if (conflicts.length > 0) {
801
- throw new MiravoError(
802
- conflicts[0] ?? "Port conflict detected.",
803
- "Use different port options or stop the conflicting simulation.",
804
- );
805
- }
806
-
807
- // 3. Generate run ID and rebuild args
808
- const runId = crypto.randomUUID();
809
- const childArgs = rebuildArgsForDetach(opts);
810
-
811
- // 4. Spawn child process
812
- controlLog.info(`Starting simulation "${simulationName}" in background...`);
813
- const proc = Bun.spawn({
814
- cmd: [process.execPath, ...childArgs],
815
- stdin: "ignore",
816
- stdout: "ignore",
817
- stderr: "ignore",
818
- env: {
819
- ...process.env,
820
- MIRAVO_DAEMON_RUN_ID: runId,
821
- },
822
- });
823
- proc.unref();
824
-
825
- // 5. Poll for readiness
826
- const adminUrl = `http://${adminHost}:${adminPort}`;
827
- const ready = await pollReadiness(proc.pid, adminUrl, runId, 10, 1_000);
828
-
829
- if (!ready) {
830
- // Kill child if still alive
831
- if (isPidAlive(proc.pid)) {
832
- try {
833
- process.kill(proc.pid, "SIGKILL");
834
- } catch {
835
- // Ignore kill errors
836
- }
837
- }
838
-
839
- throw new MiravoError(
840
- `Simulation "${simulationName}" failed to start within the readiness timeout.`,
841
- "Check template and port availability. Run without -d to see full output.",
842
- );
843
- }
844
-
845
- // 6. Write registry entry
846
- const adapters: DaemonRegistryEntry["adapters"] = {};
847
- if (opts.mqttEnabled) {
848
- const mqttPort = opts.mqttPort ?? DEFAULT_MQTT_PORT;
849
- adapters["mqtt"] = { port: mqttPort, host: opts.mqttHost ?? "127.0.0.1" };
850
- }
851
- if (opts.opcuaEnabled) {
852
- const opcuaPort = opts.opcuaPort ?? DEFAULT_OPCUA_PORT;
853
- adapters["opcua"] = { port: opcuaPort, host: opts.opcuaHost ?? "0.0.0.0" };
854
- }
855
-
856
- const entry: DaemonRegistryEntry = {
857
- name: simulationName,
858
- pid: proc.pid,
859
- adminPort,
860
- adminHost,
861
- adapters,
862
- templatePath: resolve(opts.templatePath),
863
- startedAt: new Date().toISOString(),
864
- seed: opts.seed,
865
- runId,
866
- };
867
- try {
868
- await writeEntry(entry);
869
- } catch (err) {
870
- // Registry write failed — kill the orphan child so it doesn't run invisible
871
- // to miravo ps/stop/rm.
872
- try {
873
- process.kill(proc.pid, "SIGKILL");
874
- } catch {
875
- // Process may have already exited
876
- }
877
- throw err;
878
- }
879
- await releaseLock();
880
-
881
- // 7. Print detach summary
882
- printDetachSummary(entry);
883
- process.exit(0);
884
- }
885
-
886
- function rebuildArgsForDetach(opts: DetachOptions): string[] {
887
- // Start from the original argv, filtering out -d/--detach
888
- const originalArgs = process.argv.slice(1); // skip bun/node executable
889
- const filtered: string[] = [];
890
- let hasName = false;
891
- let hasSeed = false;
892
-
893
- for (let i = 0; i < originalArgs.length; i++) {
894
- const arg = originalArgs[i];
895
- if (arg === undefined) continue;
896
- if (arg === "-d" || arg === "--detach") continue;
897
- if (arg === "-n" || arg === "--name") hasName = true;
898
- if (arg === "--seed") hasSeed = true;
899
- filtered.push(arg);
900
- }
901
-
902
- // Inject --name if not explicitly passed (ensures child uses same resolved name)
903
- if (!hasName) {
904
- filtered.push("--name", opts.simulationName);
905
- }
906
- // Inject --seed to freeze the seed (so child reproduces the same simulation)
907
- if (!hasSeed) {
908
- filtered.push("--seed", String(opts.seed));
909
- }
910
-
911
- return filtered;
912
- }
913
-
914
- async function pollReadiness(
915
- pid: number,
916
- adminUrl: string,
917
- runId: string,
918
- maxRetries: number,
919
- intervalMs: number,
920
- ): Promise<boolean> {
921
- for (let attempt = 0; attempt < maxRetries; attempt++) {
922
- await Bun.sleep(intervalMs);
923
-
924
- if (!isPidAlive(pid)) return false;
925
-
926
- try {
927
- // Use /readyz to verify identity via runId. Accept any status (not just "ok")
928
- // so external-MQTT daemons with slow broker reconnect can still start.
929
- const response = await fetch(`${adminUrl}/readyz`, {
930
- signal: AbortSignal.timeout(2_000),
931
- });
932
- const body = (await response.json()) as Record<string, unknown>;
933
- if (body["runId"] === runId) return true;
934
- } catch {
935
- // Not ready yet — retry
936
- }
937
- }
938
- return false;
939
- }
940
-
941
- function printDetachSummary(entry: DaemonRegistryEntry): void {
942
- const admin = `http://${displayHost(entry.adminHost)}:${entry.adminPort}`;
943
- const lines = [
944
- `Simulation "${entry.name}" started in background (PID ${entry.pid})`,
945
- "",
946
- ` Console ${admin}`,
947
- ];
948
-
949
- for (const [name, adapter] of Object.entries(entry.adapters) as [
950
- string,
951
- { port: number; host: string },
952
- ][]) {
953
- const host = displayHost(adapter.host);
954
- if (name === "mqtt") {
955
- lines.push(` MQTT mqtt://${host}:${adapter.port}`);
956
- } else if (name === "opcua") {
957
- lines.push(` OPC UA opc.tcp://${host}:${adapter.port}`);
958
- } else {
959
- lines.push(` ${name} ${host}:${adapter.port}`);
960
- }
961
- }
962
-
963
- lines.push("");
964
- lines.push(` Use ${colors.cyan(`miravo logs ${entry.name}`)} to view events`);
965
- lines.push(` Use ${colors.cyan(`miravo stop ${entry.name}`)} to stop`);
966
-
967
- writeOutput(lines.join("\n"));
968
- }
969
-
970
- // ---------------------------------------------------------------------------
971
- // Step 1: Template resolution
972
- // ---------------------------------------------------------------------------
973
-
974
- async function peekStateTemplatePath(simulationName: string): Promise<string | undefined> {
975
- const stateDir = `${resolveMiravoHome()}/state`;
976
- const file = Bun.file(`${stateDir}/${simulationName}.json`);
977
- if (!(await file.exists())) return undefined;
978
- try {
979
- const parsed = JSON.parse(await file.text()) as unknown;
980
- const result = PersistedStateSchema.safeParse(parsed);
981
- if (!result.success) return undefined;
982
- return result.data.templateRuns.find((r) => r.templatePath.trim().length > 0)?.templatePath;
983
- } catch {
984
- return undefined;
985
- }
986
- }
987
-
988
- async function peekSingleStateTemplatePath(): Promise<string | undefined> {
989
- const stateDir = `${resolveMiravoHome()}/state`;
990
- let bestTemplatePath: string | undefined;
991
- let bestSavedAt = "";
992
- try {
993
- const glob = new Glob("*.json");
994
- for await (const file of glob.scan({ cwd: stateDir, onlyFiles: true })) {
995
- try {
996
- const parsed = JSON.parse(await Bun.file(`${stateDir}/${file}`).text()) as unknown;
997
- const result = PersistedStateSchema.safeParse(parsed);
998
- if (!result.success) continue;
999
- const templatePath = result.data.templateRuns.find(
1000
- (r) => r.templatePath.trim().length > 0,
1001
- )?.templatePath;
1002
- if (!templatePath) continue;
1003
- if (result.data.savedAt > bestSavedAt) {
1004
- bestSavedAt = result.data.savedAt;
1005
- bestTemplatePath = templatePath;
1006
- }
1007
- } catch {}
1008
- }
1009
- } catch {
1010
- return undefined; // state dir doesn't exist yet (first-ever run)
1011
- }
1012
- return bestTemplatePath;
1013
- }
1014
-
1015
- async function resolveTemplatePath(
1016
- templateOption: string | undefined,
1017
- catalog: ContentCatalog,
1018
- ): Promise<string> {
1019
- // 1. Explicit --template identifier or path
1020
- if (templateOption) {
1021
- return resolveTemplateIdentifier(templateOption, catalog);
1022
- }
1023
-
1024
- // 2. Auto-discover local templates from content dir (if configured) and CWD
1025
- const discovered = await discoverPreferredLocalTemplates(catalog);
1026
- if (discovered.length === 1) {
1027
- const first = discovered[0];
1028
- if (first !== undefined) {
1029
- configLog.info(`Found template: ${first.name} (${first.path})`);
1030
- return first.path;
1031
- }
1032
- }
1033
- if (discovered.length > 1) {
1034
- if (!process.stdout.isTTY || !process.stdin.isTTY) {
1035
- const names = discovered.map((t) => t.name).join(", ");
1036
- throw new MiravoError(
1037
- `Found ${discovered.length} templates: ${names}.`,
1038
- "Use '--template <name|path>' to specify which template to use.",
1039
- );
1040
- }
1041
- const first = discovered[0];
1042
- if (first !== undefined) {
1043
- configLog.warn(
1044
- `Found ${discovered.length} templates: ${discovered.map((t) => t.name).join(", ")}. Using ${first.name}. Use '--template <name|path>' to specify.`,
1045
- );
1046
- return first.path;
1047
- }
1048
- }
1049
-
1050
- // 3. Fall back to built-in templates
1051
- const builtinTemplateDir = catalog.getBuiltinTemplatesDir();
1052
- let builtinTemplates: readonly DiscoveredTemplate[] = [];
1053
- try {
1054
- const discovered = await discoverTemplates(builtinTemplateDir);
1055
- // Exclude stress/benchmark templates from built-in list (same as standalone binaries).
1056
- builtinTemplates = discovered.filter((t) => !isStressBenchmarkTemplate(t.id));
1057
- } catch {
1058
- // Builtin dir may not exist in edge cases (e.g. standalone binary extraction failure)
1059
- }
1060
- if (builtinTemplates.length > 0) {
1061
- if (process.stdout.isTTY && process.stdin.isTTY) {
1062
- return pickBuiltinTemplate(builtinTemplates);
1063
- }
1064
- const selected = selectDefaultBuiltinTemplate(builtinTemplates);
1065
- if (selected !== undefined) {
1066
- configLog.info(`No template specified. Using built-in "${selected.name}".`);
1067
- configLog.info(
1068
- "Run 'miravo templates list' to see all options, or use --template <name|path>.",
1069
- );
1070
- return selected.path;
1071
- }
1072
- }
1073
-
1074
- // 4. Nothing available
1075
- throw new ConfigNotFoundError(
1076
- "No template found. Use 'miravo templates list' to find built-ins or pass 'miravo start --template <name|path>'.",
1077
- );
1078
- }
1079
-
1080
- async function pickBuiltinTemplate(templates: readonly DiscoveredTemplate[]): Promise<string> {
1081
- configLog.info("No template found in current directory.\n");
1082
-
1083
- const choice = await select({
1084
- message: "Choose a built-in template to get started:",
1085
- options: buildBuiltinTemplateChoices(templates),
1086
- maxItems: 9,
1087
- });
1088
-
1089
- if (isCancel(choice)) {
1090
- process.exit(0);
1091
- }
1092
-
1093
- configLog.info("Tip: use --template <id> to skip this prompt next time.");
1094
-
1095
- return choice as string;
1096
- }
1097
-
1098
- export function buildBuiltinTemplateChoices(
1099
- templates: readonly DiscoveredTemplate[],
1100
- ): Array<ClackOption<string>> {
1101
- const groupedTemplates = groupTemplatesByCategory(sortTemplatesByCategoryAndName(templates));
1102
- const choices: ClackOption<string>[] = [];
1103
-
1104
- for (const group of groupedTemplates) {
1105
- choices.push({
1106
- value: `__header__${group.category}`,
1107
- label: group.category,
1108
- hint: `${group.templates.length} templates`,
1109
- disabled: true,
1110
- });
1111
-
1112
- for (const [index, template] of group.templates.entries()) {
1113
- const isLast = index === group.templates.length - 1;
1114
- const branch = isLast ? "\u2514\u2500" : "\u251C\u2500";
1115
- const label = ` ${branch} ${template.name}`;
1116
- const hintPrefix = template.description ?? template.id;
1117
- choices.push({
1118
- value: template.path,
1119
- label,
1120
- hint: `${hintPrefix} \u00B7 ${template.uniqueModelCount} models \u00B7 ${template.totalTwinCount} twins`,
1121
- });
1122
- }
1123
- }
1124
-
1125
- return choices;
1126
- }
1127
-
1128
- function selectDefaultBuiltinTemplate(
1129
- templates: readonly DiscoveredTemplate[],
1130
- ): DiscoveredTemplate | undefined {
1131
- const preferredFilename = "smart-factory.miravo.yaml";
1132
- return (
1133
- templates.find((template) => basename(template.path) === preferredFilename) ?? templates[0]
1134
- );
1135
- }
1136
-
1137
- // ---------------------------------------------------------------------------
1138
- // Step 2: Load and validate
1139
- // ---------------------------------------------------------------------------
1140
-
1141
- async function loadAndValidateTemplate(
1142
- templatePath: string,
1143
- options: StartOptions,
1144
- catalog: ContentCatalog,
1145
- ): Promise<{
1146
- template: MiravoTemplate;
1147
- models: Map<string, TwinModel>;
1148
- seed: number;
1149
- seedExplicit: boolean;
1150
- }> {
1151
- const template = await loadTemplate(templatePath);
1152
-
1153
- // Build model search paths from catalog
1154
- const catalogSearchPaths = catalog.getTemplateValidationSearchPaths(templatePath);
1155
- const searchPaths = [...catalogSearchPaths];
1156
- if (options.modelsDir) {
1157
- // Insert after template dir but before other paths
1158
- searchPaths.splice(1, 0, resolve(options.modelsDir));
1159
- }
1160
- const uniqueSearchPaths = [...new Set(searchPaths.map((path) => resolve(path)))];
1161
-
1162
- // Cross-validate
1163
- const validation = await validateFullTemplate(templatePath, uniqueSearchPaths);
1164
- for (const issue of validation.issues) {
1165
- if (issue.severity === "error") {
1166
- configLog.error(`${issue.message}\n Fix: ${issue.fix}`);
1167
- } else {
1168
- configLog.warn(issue.message);
1169
- }
1170
- }
1171
- if (!validation.valid) {
1172
- throw new ConfigValidationError({
1173
- message: "Template validation failed. See errors above.",
1174
- fix: "Fix the reported issues and try again.",
1175
- filePath: templatePath,
1176
- });
1177
- }
1178
-
1179
- // Build inline models map
1180
- const models = new Map<string, TwinModel>();
1181
- if (template.models) {
1182
- for (const inlineModel of template.models) {
1183
- models.set(inlineModel.model.name, inlineModel);
1184
- }
1185
- }
1186
-
1187
- // Resolve and load all referenced models not already inline
1188
- const referencedModelNames = collectReferencedModels(template);
1189
-
1190
- for (const modelName of referencedModelNames) {
1191
- if (models.has(modelName)) continue;
1192
- const modelPath = await resolveModelPath(modelName, uniqueSearchPaths);
1193
- const model = await loadTwinModel(modelPath);
1194
- models.set(modelName, model);
1195
- }
1196
-
1197
- // Resolve seed: CLI flag > config setting > random
1198
- const configSeed = template.settings?.seed;
1199
- const cliSeed = options.seed;
1200
- const seedExplicit = cliSeed !== undefined || configSeed !== undefined;
1201
- const seed = cliSeed ?? configSeed ?? Date.now();
1202
-
1203
- return { template, models, seed, seedExplicit };
1204
- }
1205
-
1206
- export function resolveSimulationName(input: {
1207
- readonly template: MiravoTemplate;
1208
- readonly cliName?: string;
1209
- readonly envName?: string;
1210
- }): string {
1211
- const { template, cliName, envName } = input;
1212
-
1213
- const nameFromNamespace = (): string | undefined => {
1214
- const namespace = template.namespace;
1215
- if (!namespace) return undefined;
1216
- if ("enterprise" in namespace) {
1217
- return `${namespace.enterprise}-${namespace.site}`.toLowerCase();
1218
- }
1219
- return namespace.prefix.toLowerCase();
1220
- };
1221
-
1222
- const rawName = cliName ?? envName ?? nameFromNamespace();
1223
- if (!rawName) {
1224
- throw new ConfigValidationError({
1225
- message: "Template has no namespace.",
1226
- fix: "Provide a simulation name via --name or MIRAVO_NAME.",
1227
- });
1228
- }
1229
-
1230
- const parsed = SimulationNameSchema.safeParse(rawName);
1231
- if (!parsed.success) {
1232
- throw new ConfigValidationError({
1233
- message: `Invalid simulation name "${rawName}".`,
1234
- fix: "Use lowercase letters, numbers, and hyphens only (for example: north-plant).",
1235
- });
1236
- }
1237
-
1238
- return parsed.data;
1239
- }
1240
-
1241
- // ---------------------------------------------------------------------------
1242
- // Step 4: Engine creation
1243
- // ---------------------------------------------------------------------------
1244
-
1245
- function createAndPopulateEngine(
1246
- template: MiravoTemplate,
1247
- models: Map<string, TwinModel>,
1248
- catalog: ContentCatalog,
1249
- seed: number,
1250
- options: StartOptions,
1251
- templatePath: string,
1252
- simulationName: string,
1253
- ): Engine {
1254
- const tickIntervalMs =
1255
- options.tick ?? template.settings?.tick_interval_ms ?? DEFAULT_TICK_INTERVAL_MS;
1256
- const timeMultiplier =
1257
- options.speed ?? template.settings?.time_multiplier ?? DEFAULT_TIME_MULTIPLIER;
1258
- const overrunThresholdMultiplier = template.settings?.overrun_threshold_multiplier;
1259
- const searchPaths = catalog.getTemplateValidationSearchPaths(templatePath);
1260
-
1261
- let engine!: Engine;
1262
- engine = createEngine({
1263
- simulationName,
1264
- seed,
1265
- tickIntervalMs,
1266
- timeMultiplier,
1267
- overrunThresholdMultiplier,
1268
- templateMetadata: {
1269
- name: template.name,
1270
- path: templatePath,
1271
- },
1272
- beforeRun: async ({ restoredFromPersistence }) => {
1273
- const protocolBootPlans = resolveProtocolBootPlans({
1274
- options,
1275
- optionSources: {
1276
- mqtt: getCommandOptionSource(options.command, "mqtt"),
1277
- opcua: getCommandOptionSource(options.command, "opcua"),
1278
- mqttPort: getCommandOptionSource(options.command, "mqttPort"),
1279
- mqttHost: getCommandOptionSource(options.command, "mqttHost"),
1280
- mqttMode: getCommandOptionSource(options.command, "mqttMode"),
1281
- mqttUrl: getCommandOptionSource(options.command, "mqttUrl"),
1282
- mqttUsername: getCommandOptionSource(options.command, "mqttUsername"),
1283
- mqttPassword: getCommandOptionSource(options.command, "mqttPassword"),
1284
- opcuaPort: getCommandOptionSource(options.command, "opcuaPort"),
1285
- opcuaHost: getCommandOptionSource(options.command, "opcuaHost"),
1286
- },
1287
- restoredFromPersistence,
1288
- });
1289
-
1290
- for (const plan of protocolBootPlans) {
1291
- await reconcileProtocolBootPlan(engine, plan);
1292
- }
1293
- },
1294
- persistence: {
1295
- enabled: true,
1296
- resetOnStart: options.resetState ?? false,
1297
- ensureModelRegistered: (modelName) =>
1298
- registerModelFromSearchPaths(engine.runtime, modelName, searchPaths),
1299
- loadTemplateModels: (persistedTemplatePath) => {
1300
- loadTemplateModels(catalog, persistedTemplatePath, engine.runtime);
1301
- },
1302
- },
1303
- });
1304
-
1305
- // Register all models
1306
- for (const [, model] of models) {
1307
- engine.runtime.registerModel(model);
1308
- }
1309
-
1310
- // Spawn instances from template with boot-time run ID
1311
- const bootRunId = 1;
1312
- const allInstanceIds: string[] = [];
1313
-
1314
- forEachTwin(template, (area, line, twin) => {
1315
- const unsBasePath = buildUNSBasePath(template, area.name, line.name);
1316
- const spawned = engine.runtime.spawn(twin.model, twin.count, {
1317
- variation: twin.variation,
1318
- unsBasePath,
1319
- ...(twin.parameters !== undefined ? { parameterOverrides: twin.parameters } : {}),
1320
- ...(twin.starting_hours !== undefined ? { startingHours: twin.starting_hours } : {}),
1321
- templateRunId: bootRunId,
1322
- });
1323
- for (const node of spawned) {
1324
- allInstanceIds.push(node.id);
1325
- }
1326
- });
1327
-
1328
- // Register boot-time template as a template run for persistence/unload support
1329
- engine.registerTemplateRun({
1330
- templateRunId: bootRunId,
1331
- templateName: template.name,
1332
- templatePath,
1333
- prefix: "boot",
1334
- instanceIds: allInstanceIds,
1335
- models: [...models.keys()],
1336
- });
1337
-
1338
- return engine;
1339
- }
1340
-
1341
- // ---------------------------------------------------------------------------
1342
- // Runtime template loader (for loadTemplate command from console/API)
1343
- // ---------------------------------------------------------------------------
1344
-
1345
- interface CachedTemplate {
1346
- readonly id: string;
1347
- readonly name: string;
1348
- readonly path: string;
1349
- }
1350
-
1351
- interface TemplateCacheResult {
1352
- readonly pathCache: Map<string, CachedTemplate>;
1353
- readonly catalog: readonly CatalogTemplate[];
1354
- }
1355
-
1356
- /**
1357
- * Discover templates once and build both the path lookup cache (for runtime
1358
- * template loading) and the catalog (for the REST API) in a single pass.
1359
- * All data comes from discovery metadata — no additional file I/O.
1360
- */
1361
- async function buildTemplateCacheAndCatalog(
1362
- contentCatalog: ContentCatalog,
1363
- ): Promise<TemplateCacheResult> {
1364
- const pathCache = new Map<string, CachedTemplate>();
1365
- const catalogEntries: CatalogTemplate[] = [];
1366
- const discovered = await discoverTemplates(contentCatalog.getBuiltinTemplatesDir());
1367
-
1368
- for (const t of discovered) {
1369
- const entry: CachedTemplate = { id: t.id, name: t.name, path: t.path };
1370
- pathCache.set(t.id, entry);
1371
- pathCache.set(t.name, entry);
1372
-
1373
- catalogEntries.push({
1374
- id: t.id,
1375
- name: t.name,
1376
- description: t.description ?? null,
1377
- category: "Industrial",
1378
- models: t.modelNames,
1379
- instanceCount: t.totalTwinCount,
1380
- memberCount: 0,
1381
- source: "builtin",
1382
- });
1383
- }
1384
-
1385
- return { pathCache, catalog: catalogEntries };
1386
- }
1387
-
1388
- function createRuntimeTemplateLoader(
1389
- catalog: ContentCatalog,
1390
- templatePathCache: Map<string, CachedTemplate>,
1391
- ): (templatePath: string, count: number, runId: number, runtime: TwinRuntime) => TemplateRun {
1392
- return (templateIdentifier, count, runId, runtime) => {
1393
- // Resolve template path from pre-built cache or as a file path
1394
- let templatePath: string;
1395
- let slugName: string;
1396
- if (isTemplatePathLike(templateIdentifier)) {
1397
- templatePath = resolve(templateIdentifier);
1398
- slugName = basename(templatePath).replace(/\.miravo\.yaml$/, "");
1399
- } else {
1400
- const cached = templatePathCache.get(templateIdentifier);
1401
- if (!cached) {
1402
- const ids = [...new Set([...templatePathCache.values()].map((e) => e.id))];
1403
- throw new MiravoError(
1404
- `Template "${templateIdentifier}" not found.`,
1405
- `Available templates: ${ids.join(", ") || "(none)"}`,
1406
- );
1407
- }
1408
- templatePath = cached.path;
1409
- slugName = cached.id;
1410
- }
1411
-
1412
- const template = loadTemplateSync(templatePath);
1413
- const referencedModels = registerTemplateModels(catalog, templatePath, template, runtime);
1414
-
1415
- // Spawn instances with auto-prefix using kebab-case slug
1416
- const prefix = `${slugName}-${runId}`;
1417
- const allInstanceIds: string[] = [];
1418
-
1419
- for (let c = 0; c < count; c++) {
1420
- const runPrefix = count > 1 ? `${prefix}-${c + 1}` : prefix;
1421
- forEachTwin(template, (area, line, twin) => {
1422
- const unsBasePath = `${runPrefix}/${buildUNSBasePath(template, area.name, line.name)}`;
1423
- const spawned = runtime.spawn(twin.model, twin.count, {
1424
- variation: twin.variation,
1425
- unsBasePath,
1426
- ...(twin.parameters !== undefined ? { parameterOverrides: twin.parameters } : {}),
1427
- ...(twin.starting_hours !== undefined ? { startingHours: twin.starting_hours } : {}),
1428
- templateRunId: runId,
1429
- });
1430
- for (const node of spawned) {
1431
- allInstanceIds.push(node.id);
1432
- }
1433
- });
1434
- }
1435
-
1436
- return {
1437
- templateRunId: runId,
1438
- templateName: template.name,
1439
- templatePath,
1440
- prefix,
1441
- instanceIds: allInstanceIds,
1442
- models: [...referencedModels],
1443
- };
1444
- };
1445
- }
1446
-
1447
- function loadTemplateSync(templatePath: string): MiravoTemplate {
1448
- try {
1449
- return MiravoTemplateSchema.parse(parseYAML(readFileSync(templatePath, "utf-8")));
1450
- } catch (err) {
1451
- throw new MiravoError(
1452
- `Failed to load template "${templatePath}".`,
1453
- err instanceof Error ? err.message : "Check that the file is valid YAML.",
1454
- );
1455
- }
1456
- }
1457
-
1458
- function registerModelFromSearchPaths(
1459
- runtime: TwinRuntime,
1460
- modelName: string,
1461
- searchPaths: readonly string[],
1462
- ): void {
1463
- if (runtime.getModel(modelName)) {
1464
- return;
1465
- }
1466
-
1467
- const { path: modelPath, content: modelContent } = loadModelSync(modelName, searchPaths);
1468
- try {
1469
- const model = TwinModelSchema.parse(parseYAML(modelContent));
1470
- runtime.registerModel(model);
1471
- } catch (err) {
1472
- throw new MiravoError(
1473
- `Failed to load model "${modelName}" from "${modelPath}".`,
1474
- err instanceof Error ? err.message : "Check that the model file is valid YAML.",
1475
- );
1476
- }
1477
- }
1478
-
1479
- function loadTemplateModels(
1480
- catalog: ContentCatalog,
1481
- templatePath: string,
1482
- runtime: TwinRuntime,
1483
- ): readonly string[] {
1484
- const template = loadTemplateSync(templatePath);
1485
- return registerTemplateModels(catalog, templatePath, template, runtime);
1486
- }
1487
-
1488
- function registerTemplateModels(
1489
- catalog: ContentCatalog,
1490
- templatePath: string,
1491
- template: MiravoTemplate,
1492
- runtime: TwinRuntime,
1493
- ): readonly string[] {
1494
- const referencedModels = collectReferencedModels(template);
1495
- const searchPaths = catalog.getTemplateValidationSearchPaths(templatePath);
1496
- for (const modelName of referencedModels) {
1497
- registerModelFromSearchPaths(runtime, modelName, searchPaths);
1498
- }
1499
- return [...referencedModels];
1500
- }
1501
-
1502
- function loadModelSync(
1503
- modelName: string,
1504
- searchPaths: readonly string[],
1505
- ): { path: string; content: string } {
1506
- for (const dir of searchPaths) {
1507
- const candidate = resolve(dir, `${modelName}${TWIN_FILE_EXTENSION}`);
1508
- try {
1509
- return { path: candidate, content: readFileSync(candidate, "utf-8") };
1510
- } catch {
1511
- // File doesn't exist or can't be read — try next path
1512
- }
1513
- }
1514
- throw new MiravoError(
1515
- `Model "${modelName}" not found in search paths.`,
1516
- `Searched: ${searchPaths.join(", ")}. Ensure the model file exists as "${modelName}${TWIN_FILE_EXTENSION}".`,
1517
- );
1518
- }
1519
-
1520
- // ---------------------------------------------------------------------------
1521
- // Step 5: Adapter default config builders
1522
- // ---------------------------------------------------------------------------
1523
-
1524
- function buildMQTTDefaultConfig(
1525
- template: MiravoTemplate,
1526
- portOverride: number | undefined,
1527
- mqttOverrides: MqttRunOverrides,
1528
- simulationName: string,
1529
- ): Record<string, unknown> {
1530
- const mqttConfig = template.protocols?.mqtt;
1531
- const port = portOverride ?? mqttConfig?.port ?? DEFAULT_MQTT_PORT;
1532
- let embedded = mqttConfig?.embedded ?? true;
1533
- let external = mqttConfig?.external;
1534
- let host = "127.0.0.1";
1535
- let username = mqttConfig?.username;
1536
- let password = mqttConfig?.password;
1537
- const modeOverride = mqttOverrides.mode;
1538
- if (modeOverride !== undefined) {
1539
- embedded = modeOverride === "embedded";
1540
- if (embedded) {
1541
- external = undefined;
1542
- username = undefined;
1543
- password = undefined;
1544
- }
1545
- }
1546
- if (mqttOverrides.url !== undefined) external = mqttOverrides.url;
1547
- if (mqttOverrides.host !== undefined) host = mqttOverrides.host;
1548
- if (mqttOverrides.username !== undefined) username = mqttOverrides.username;
1549
- if (mqttOverrides.password !== undefined) password = mqttOverrides.password;
1550
-
1551
- if (embedded && (external || username || password)) {
1552
- throw new ConfigValidationError({
1553
- message: "Embedded MQTT mode cannot be combined with external MQTT URL or credentials.",
1554
- fix: "Use --mqtt-mode external for external broker settings, or remove external MQTT overrides.",
1555
- });
1556
- }
1557
- if (!embedded && !external) {
1558
- throw new ConfigValidationError({
1559
- message: "MQTT mode is external but no broker URL was provided.",
1560
- fix: "Set protocols.mqtt.external in template or pass --mqtt-url / MIRAVO_MQTT_URL.",
1561
- });
1562
- }
1563
- if (password && !username) {
1564
- throw new ConfigValidationError({
1565
- message: "MQTT password was provided without username.",
1566
- fix: "Provide --mqtt-username / MIRAVO_MQTT_USERNAME when setting a password.",
1567
- });
1568
- }
1569
-
1570
- const drainBudget = mqttOverrides.drainBudget ?? mqttConfig?.drain_budget;
1571
- const batchSize = mqttOverrides.batchSize ?? mqttConfig?.batch_size;
1572
- const brokerConcurrency = mqttOverrides.brokerConcurrency ?? mqttConfig?.broker_concurrency;
1573
-
1574
- return {
1575
- name: "mqtt",
1576
- enabled: true,
1577
- simulationName,
1578
- embedded,
1579
- port,
1580
- host,
1581
- retain: mqttConfig?.retain ?? false,
1582
- ...(external !== undefined ? { external } : {}),
1583
- ...(username !== undefined ? { username } : {}),
1584
- ...(password !== undefined ? { password } : {}),
1585
- ...(mqttConfig?.reconnect !== undefined ? { reconnect: mqttConfig.reconnect } : {}),
1586
- ...(mqttConfig?.rbe !== undefined ? { rbe: mqttConfig.rbe } : {}),
1587
- ...(mqttConfig?.metadata !== undefined ? { metadata: mqttConfig.metadata } : {}),
1588
- ...(drainBudget !== undefined ? { drain_budget: drainBudget } : {}),
1589
- ...(batchSize !== undefined ? { batch_size: batchSize } : {}),
1590
- ...(brokerConcurrency !== undefined ? { broker_concurrency: brokerConcurrency } : {}),
1591
- };
1592
- }
1593
-
1594
- function buildOPCUADefaultConfig(
1595
- template: MiravoTemplate,
1596
- portOverride: number | undefined,
1597
- hostOverride: string | undefined,
1598
- simulationName: string,
1599
- writeBudgetOverride?: number,
1600
- ): Record<string, unknown> {
1601
- const opcuaConfig = template.protocols?.opcua;
1602
- const port = portOverride ?? opcuaConfig?.port ?? DEFAULT_OPCUA_PORT;
1603
- const host = hostOverride ?? opcuaConfig?.host ?? "0.0.0.0";
1604
- const writeBudget = writeBudgetOverride ?? opcuaConfig?.write_budget;
1605
-
1606
- return {
1607
- name: "opcua",
1608
- enabled: true,
1609
- port,
1610
- host,
1611
- security: opcuaConfig?.security ?? "none",
1612
- simulationName,
1613
- ...(opcuaConfig?.buildInfo ? { buildInfo: opcuaConfig.buildInfo } : {}),
1614
- ...(writeBudget !== undefined ? { write_budget: writeBudget } : {}),
1615
- };
1616
- }
1617
-
1618
- /** Derive the MQTT endpoint string from a resolved adapter config. */
1619
- function buildMQTTEndpoint(config: import("@miravo/shared").ProtocolConfig): string {
1620
- const cfg = config as Record<string, unknown>;
1621
- const port = cfg["port"] ?? DEFAULT_MQTT_PORT;
1622
- const embedded = cfg["embedded"] ?? true;
1623
- const external = cfg["external"] as string | undefined;
1624
- return embedded ? `mqtt://localhost:${port}` : (external as string);
1625
- }
1626
-
1627
- /** Derive the OPC UA endpoint string from a resolved adapter config. */
1628
- function buildOPCUAEndpoint(config: import("@miravo/shared").ProtocolConfig): string {
1629
- const cfg = config as Record<string, unknown>;
1630
- const port = cfg["port"] ?? DEFAULT_OPCUA_PORT;
1631
- const host = cfg["host"] ?? "0.0.0.0";
1632
- const displayHost = host === "0.0.0.0" ? "localhost" : host;
1633
- return `opc.tcp://${displayHost}:${port}`;
1634
- }
1635
-
1636
- // ---------------------------------------------------------------------------
1637
- // Step 6: Startup banner
1638
- // ---------------------------------------------------------------------------
1639
-
1640
- function printStartupBanner(
1641
- templatePath: string,
1642
- engine: Engine,
1643
- seed: number,
1644
- seedExplicit: boolean,
1645
- mqttEndpoint: string | null,
1646
- opcuaEndpoint: string | null,
1647
- simulationName: string,
1648
- runId: string,
1649
- adminEndpoint: string,
1650
- ): void {
1651
- const state = engine.getState();
1652
-
1653
- // Build model summary: one model per line for readability
1654
- const modelLines = state.models.map(
1655
- (m) => `${colors.bold(m.name)} ${colors.dim(`(${m.memberCount} members)`)}`,
1656
- );
1657
- const modelCount = `${colors.bold(String(state.models.length))} ${colors.dim("models")}`;
1658
-
1659
- const seedValue = seedExplicit
1660
- ? colors.bold(String(seed))
1661
- : `${colors.bold(String(seed))} ${colors.gray("(random — add seed to config to reproduce)")}`;
1662
-
1663
- const mqttValue = mqttEndpoint ? colors.cyan(mqttEndpoint) : colors.dim("disabled");
1664
- const opcuaValue = opcuaEndpoint ? colors.cyan(opcuaEndpoint) : colors.dim("disabled");
1665
-
1666
- const allEntries: ReadonlyArray<readonly [string, string]> = [
1667
- [colors.dim("Simulation"), colors.bold(simulationName)],
1668
- [colors.dim("Run ID"), colors.bold(runId)],
1669
- [colors.dim("Template"), templatePath],
1670
- [colors.dim("Models"), modelCount],
1671
- [colors.dim("Instances"), colors.bold(String(state.instances.length))],
1672
- [colors.dim("MQTT"), mqttValue],
1673
- [colors.dim("OPC UA"), opcuaValue],
1674
- [colors.dim("Admin"), colors.cyan(adminEndpoint)],
1675
- [colors.dim("Tick interval"), colors.bold(`${state.config.tickIntervalMs}ms`)],
1676
- [colors.dim("Time multiplier"), colors.bold(`${state.config.timeMultiplier}x`)],
1677
- [colors.dim("Seed"), seedValue],
1678
- ];
1679
-
1680
- const kvBlock = formatKeyValue(allEntries);
1681
-
1682
- // Compute the value column offset used by formatKeyValue so model detail
1683
- // lines align with the value of the "Models" row.
1684
- const maxKeyWidth = Math.max(...allEntries.map(([key]) => stripAnsi(key).length));
1685
- const valueIndent = 4 + maxKeyWidth + 3; // " " + key + ":" + padding(2) + " "
1686
-
1687
- // Inject per-model detail lines right after the "Models" row
1688
- const kvLines = kvBlock.split("\n");
1689
- const modelsIdx = kvLines.findIndex((line) => stripAnsi(line).includes("Models:"));
1690
- if (modelsIdx !== -1 && modelLines.length > 0) {
1691
- const detailLines = modelLines.map((line) => `${"".padEnd(valueIndent)}${line}`);
1692
- kvLines.splice(modelsIdx + 1, 0, ...detailLines);
1693
- }
1694
- const content = kvLines.join("\n");
1695
-
1696
- const header = `${colors.cyan(colors.bold("Miravo"))} ${colors.dim(`v${MIRAVO_VERSION}`)}`;
1697
-
1698
- if (isPlain()) {
1699
- writeOutput(`${header}`);
1700
- writeOutput(content);
1701
- writeOutput();
1702
- engineLog.start("Press Ctrl+C to stop.");
1703
- return;
1704
- }
1705
-
1706
- writeOutput(
1707
- box(content, {
1708
- title: header,
1709
- style: { borderColor: "cyan", borderStyle: "rounded" },
1710
- }),
1711
- );
1712
-
1713
- engineLog.start("Press Ctrl+C to stop.");
1714
- }
1715
-
1716
- function parseMqttModeOption(raw: string | undefined): MqttMode | undefined {
1717
- if (raw === undefined) {
1718
- return undefined;
1719
- }
1720
-
1721
- if (raw === "embedded" || raw === "external") {
1722
- return raw;
1723
- }
1724
-
1725
- throw new ConfigValidationError({
1726
- message: `Invalid MQTT mode "${raw}".`,
1727
- fix: "Use --mqtt-mode embedded|external or MIRAVO_MQTT_MODE=embedded|external.",
1728
- });
1729
- }
1730
-
1731
- // ---------------------------------------------------------------------------
1732
- // Step 7: Event subscriptions + periodic summary
1733
- // ---------------------------------------------------------------------------
1734
-
1735
- function subscribeToEvents(engine: Engine, errorContextCounts: Map<string, number>): () => void {
1736
- const onLifecycle = (event: {
1737
- instanceId: string;
1738
- from: string;
1739
- to: string;
1740
- operatingHours: number;
1741
- }): void => {
1742
- lifecycleLog.info(
1743
- `${event.instanceId} ${event.from} ${colors.dim("\u2192")} ${event.to} ${colors.gray(`(${event.operatingHours.toFixed(0)}h)`)}`,
1744
- );
1745
- };
1746
-
1747
- const onFaultTriggered = (event: { instanceId: string; fault: string }): void => {
1748
- faultLog.warn(`${event.instanceId} ${event.fault} triggered`);
1749
- };
1750
-
1751
- const onFaultCleared = (event: { instanceId: string; fault: string }): void => {
1752
- faultLog.debug(`${event.instanceId} ${event.fault} cleared`);
1753
- };
1754
-
1755
- const onWarn = (event: { message: string; context: string }): void => {
1756
- engineLog.debug(event.message, { context: event.context });
1757
- };
1758
-
1759
- const onReset = (event: {
1760
- instanceCount: number;
1761
- templateRunCount: number;
1762
- clearPersistence: boolean;
1763
- }): void => {
1764
- const suffix = event.clearPersistence ? " · saved state cleared" : "";
1765
- engineLog.info(
1766
- `simulation reset · ${colors.bold(String(event.instanceCount))} instances · ${colors.bold(String(event.templateRunCount))} template runs${suffix}`,
1767
- );
1768
- };
1769
-
1770
- const onError = (event: { context: string; error: Error }): void => {
1771
- incrementErrorContextCount(errorContextCounts, event.context);
1772
- engineLog.error(
1773
- "engine:error",
1774
- {
1775
- context: event.context,
1776
- errorName: event.error.name,
1777
- errorMessage: event.error.message,
1778
- },
1779
- event.error,
1780
- );
1781
- };
1782
-
1783
- engine.bus.on("lifecycle:changed", onLifecycle);
1784
- engine.bus.on("fault:triggered", onFaultTriggered);
1785
- engine.bus.on("fault:cleared", onFaultCleared);
1786
- engine.bus.on("engine:warn", onWarn);
1787
- engine.bus.on("engine:error", onError);
1788
- engine.bus.on("engine:reset", onReset);
1789
-
1790
- return () => {
1791
- engine.bus.off("lifecycle:changed", onLifecycle);
1792
- engine.bus.off("fault:triggered", onFaultTriggered);
1793
- engine.bus.off("fault:cleared", onFaultCleared);
1794
- engine.bus.off("engine:warn", onWarn);
1795
- engine.bus.off("engine:error", onError);
1796
- engine.bus.off("engine:reset", onReset);
1797
- };
1798
- }
1799
-
1800
- export function normalizeErrorContext(raw: string): string {
1801
- return raw
1802
- .replace(/tick=\d+/g, "tick=*")
1803
- .replace(/instance="[^"]+"/g, 'instance="*"')
1804
- .replace(/model="[^"]+"/g, 'model="*"');
1805
- }
1806
-
1807
- export function incrementErrorContextCount(counts: Map<string, number>, rawContext: string): void {
1808
- const normalizedContext = normalizeErrorContext(rawContext);
1809
- if (counts.has(normalizedContext)) {
1810
- counts.set(normalizedContext, (counts.get(normalizedContext) ?? 0) + 1);
1811
- return;
1812
- }
1813
-
1814
- if (counts.size < MAX_ERROR_CONTEXT_KEYS) {
1815
- counts.set(normalizedContext, 1);
1816
- return;
1817
- }
1818
-
1819
- counts.set(ERROR_CONTEXT_OVERFLOW, (counts.get(ERROR_CONTEXT_OVERFLOW) ?? 0) + 1);
1820
- }
1821
-
1822
- function getCommandOptionSource(
1823
- command: Command | undefined,
1824
- optionName: ProtocolOptionSource,
1825
- ): string | undefined {
1826
- const maybeGetOptionValueSource = (
1827
- command as Command & { getOptionValueSource?: (key: string) => string | undefined }
1828
- )?.getOptionValueSource;
1829
- return maybeGetOptionValueSource?.call(command, optionName);
1830
- }
1831
-
1832
- export function resolveProtocolBootPlans(input: {
1833
- readonly options: StartOptions & { readonly command?: Command | undefined };
1834
- readonly optionSources: Partial<Record<ProtocolOptionSource, string | undefined>>;
1835
- readonly restoredFromPersistence: boolean;
1836
- }): readonly ProtocolBootPlan[] {
1837
- const mqttConfigExplicit = [
1838
- "mqttPort",
1839
- "mqttHost",
1840
- "mqttMode",
1841
- "mqttUrl",
1842
- "mqttUsername",
1843
- "mqttPassword",
1844
- ].some((option) => input.optionSources[option as ProtocolOptionSource] === "cli");
1845
-
1846
- const opcuaConfigExplicit =
1847
- input.options.opcua === true &&
1848
- ["opcuaPort", "opcuaHost"].some(
1849
- (option) => input.optionSources[option as ProtocolOptionSource] === "cli",
1850
- );
1851
-
1852
- return [
1853
- {
1854
- name: "mqtt",
1855
- shouldEnable: input.options.mqtt !== false,
1856
- overrideRestore:
1857
- !input.restoredFromPersistence ||
1858
- input.optionSources["mqtt"] === "cli" ||
1859
- mqttConfigExplicit,
1860
- },
1861
- {
1862
- name: "opcua",
1863
- shouldEnable: input.options.opcua === true,
1864
- overrideRestore:
1865
- !input.restoredFromPersistence ||
1866
- input.optionSources["opcua"] === "cli" ||
1867
- opcuaConfigExplicit,
1868
- },
1869
- ];
1870
- }
1871
-
1872
- async function reconcileProtocolBootPlan(engine: Engine, plan: ProtocolBootPlan): Promise<void> {
1873
- const adapter = engine.getAvailableAdapters().find((candidate) => candidate.name === plan.name);
1874
- const isEnabled = adapter?.enabled === true;
1875
-
1876
- if (!plan.shouldEnable) {
1877
- if (!isEnabled || !plan.overrideRestore) {
1878
- return;
1879
- }
1880
-
1881
- const result = await engine.disableAdapter(plan.name);
1882
- if (!result.success) {
1883
- throw new MiravoError(
1884
- result.message,
1885
- result.error ?? `Disable adapter "${plan.name}" manually and retry startup.`,
1886
- );
1887
- }
1888
- return;
1889
- }
1890
-
1891
- if (plan.overrideRestore && isEnabled) {
1892
- const disableResult = await engine.disableAdapter(plan.name);
1893
- if (!disableResult.success) {
1894
- throw new MiravoError(
1895
- disableResult.message,
1896
- disableResult.error ?? `Disable adapter "${plan.name}" manually and retry startup.`,
1897
- );
1898
- }
1899
- if ((disableResult.data as { stopWarning?: boolean } | undefined)?.stopWarning === true) {
1900
- throw new MiravoError(
1901
- `Failed to safely reconfigure adapter "${plan.name}" during startup.`,
1902
- `The previous ${plan.name.toUpperCase()} adapter instance did not stop cleanly. Free the port or clear the persisted adapter state before retrying.`,
1903
- );
1904
- }
1905
- } else if (isEnabled) {
1906
- return;
1907
- }
1908
-
1909
- const result = await engine.enableAdapter(plan.name);
1910
- if (!result.success) {
1911
- throw new MiravoError(
1912
- result.message,
1913
- result.error ?? `Check ${plan.name.toUpperCase()} configuration.`,
1914
- );
1915
- }
1916
-
1917
- if (plan.name === "mqtt") {
1918
- mqttLog.ready(
1919
- `connected · broker: ${colors.cyan(String((result.data as Record<string, unknown>)?.["endpoint"] ?? ""))}`,
1920
- );
1921
- return;
1922
- }
1923
-
1924
- opcuaLog.ready(
1925
- `server ready · endpoint: ${colors.cyan(String((result.data as Record<string, unknown>)?.["endpoint"] ?? ""))}`,
1926
- );
1927
- }
1928
-
1929
- function startPeriodicSummary(
1930
- engine: Engine,
1931
- intervalSeconds: number,
1932
- ): ReturnType<typeof setInterval> {
1933
- return setInterval(() => {
1934
- const metrics = engine.getMetrics();
1935
- printSummaryLine(metrics);
1936
- }, intervalSeconds * 1_000);
1937
- }
1938
-
1939
- // ---------------------------------------------------------------------------
1940
- // Step 3: Dry-run summary
1941
- // ---------------------------------------------------------------------------
1942
-
1943
- function printDryRunSummary(
1944
- template: MiravoTemplate,
1945
- models: Map<string, TwinModel>,
1946
- seed: number,
1947
- seedExplicit: boolean,
1948
- templatePath: string,
1949
- ): void {
1950
- configLog.success("Dry-run validation passed.");
1951
-
1952
- const seedValue = seedExplicit
1953
- ? colors.bold(String(seed))
1954
- : `${colors.bold(String(seed))} ${colors.gray("(random — add seed to config to reproduce)")}`;
1955
-
1956
- const lines: string[] = [];
1957
-
1958
- lines.push(
1959
- formatKeyValue([
1960
- [colors.dim("Template"), templatePath],
1961
- [colors.dim("Seed"), seedValue],
1962
- ]),
1963
- );
1964
-
1965
- // Model table
1966
- const modelRows = [...models.values()].map((m) => ({
1967
- name: colors.cyan(m.model.name),
1968
- members: String(Object.keys(m.members).length),
1969
- faults: String(m.faults?.length ?? 0),
1970
- lifecycle: m.lifecycle ? `${m.lifecycle.stages.length} stages` : colors.dim("none"),
1971
- }));
1972
-
1973
- if (modelRows.length > 0) {
1974
- lines.push("");
1975
- lines.push(` ${colors.bold("Models:")}`);
1976
- lines.push(
1977
- formatTable(
1978
- {
1979
- name: colors.dim("Name"),
1980
- members: colors.dim("Members"),
1981
- faults: colors.dim("Faults"),
1982
- lifecycle: colors.dim("Lifecycle"),
1983
- },
1984
- modelRows,
1985
- ),
1986
- );
1987
- }
1988
-
1989
- // Instance summary
1990
- let totalInstances = 0;
1991
- let totalMembers = 0;
1992
- forEachTwin(template, (_area, _line, twin) => {
1993
- totalInstances += twin.count;
1994
- const model = models.get(twin.model);
1995
- if (model) {
1996
- totalMembers += twin.count * Object.keys(model.members).length;
1997
- }
1998
- });
1999
-
2000
- lines.push("");
2001
- lines.push(
2002
- formatKeyValue([
2003
- [colors.dim("Total instances"), colors.bold(String(totalInstances))],
2004
- [colors.dim("Total members"), colors.bold(String(totalMembers))],
2005
- ]),
2006
- );
2007
-
2008
- if (isPlain()) {
2009
- writeOutput("Summary");
2010
- for (const line of lines) {
2011
- writeOutput(line);
2012
- }
2013
- writeOutput();
2014
- return;
2015
- }
2016
-
2017
- writeOutput(
2018
- box(lines.join("\n"), {
2019
- title: " Summary ",
2020
- style: { borderColor: "cyan", borderStyle: "rounded" },
2021
- }),
2022
- );
2023
- }