@senpi/runtime 3.0.221 → 3.0.222

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.
@@ -29,6 +29,9 @@ export class ScannerLauncher {
29
29
  * called after eager wiring.
30
30
  */
31
31
  _initialized = false;
32
+ started = false;
33
+ stopped = false;
34
+ pausing = Promise.resolve();
32
35
  constructor(rawDeps) {
33
36
  this.deps = rawDeps;
34
37
  }
@@ -46,253 +49,15 @@ export class ScannerLauncher {
46
49
  _buildAndRegister() {
47
50
  if (this._initialized)
48
51
  return;
49
- const { runtimeId, wallet, scanners, registry, liveness, intakeUrl, scaffoldPackageDir, launchConfigDir, logger, supervisorOptions = {}, } = this.deps;
50
- // Resolve MCP creds: explicit deps win, else fall back to process.env.
51
- // Empty/absent values are dropped so we never inject a misleading "".
52
- const senpiApiKey = this.deps.senpiApiKey ||
53
- process.env.SENPI_AUTH_TOKEN ||
54
- process.env.SENPI_API_KEY ||
55
- undefined;
56
- const senpiMcpUrl = this.deps.senpiMcpUrl || process.env.SENPI_MCP_URL || undefined;
57
- const mintScannerId = this.deps.mintScannerId ?? (() => makeId("scanner"));
58
- const createSupervisor = this.deps.createSupervisor ??
59
- ((spec, lg) => new LongRunningSupervisor(spec, lg));
60
- const onSupervisorEvent = this.deps.onSupervisorEvent;
61
- const simulation = walletMode(wallet) === "paper";
52
+ const { scanners, registry, logger, wallet } = this.deps;
62
53
  // Track ids registered in this call so we can roll back on partial failure.
63
54
  const registeredInThisCall = [];
64
55
  // The scanner being wired when a failure throws — names it on the launch-failed event.
65
56
  let failingScanner;
66
57
  try {
67
58
  for (let i = 0; i < scanners.length; i++) {
68
- const scanner = scanners[i];
69
- failingScanner = scanner.name;
70
- if (!scanner.path) {
71
- throw new Error(`ScannerLauncher: scanner "${scanner.name}" is missing required field "path"`);
72
- }
73
- if (!scanner.entrypoint) {
74
- throw new Error(`ScannerLauncher: scanner "${scanner.name}" is missing required field "entrypoint"`);
75
- }
76
- const safeName = scanner.name.replace(/[^a-zA-Z0-9_-]/g, "_");
77
- // Include the scanner's array index so two scanners that share a name (or
78
- // whose names sanitize to the same string) never share a state directory
79
- // or delivery journal. The index is stable across relaunch (same config
80
- // position), so state and the journal survive a restart.
81
- const stateDir = path.join(launchConfigDir, "scanner-state", `${safeName}-${i}`);
82
- fs.mkdirSync(stateDir, { recursive: true });
83
- const classes = this.deps.scannerClassesMb;
84
- const classMb = simulation && classes !== undefined && Object.hasOwn(classes, scanner.name)
85
- ? classes[scanner.name]
86
- : undefined;
87
- const identity = {
88
- scannerName: scanner.name,
89
- classMb,
90
- codeDigest: classMb !== undefined ? scannerCodeDigest(scanner) : "",
91
- };
92
- const sizeStop = readSizeStop(stateDir);
93
- if (sizeStop !== undefined && holds(sizeStop, identity)) {
94
- logger.info("simulation scanner stays stopped for size until its class or code changes", {
95
- runtimeId,
96
- scannerName: scanner.name,
97
- classMb,
98
- nextClassMb: sizeStop.nextClassMb,
99
- });
100
- this.active.push({
101
- kind: "stopped-for-size",
102
- scannerName: scanner.name,
103
- intervalSeconds: scanner.intervalSeconds,
104
- record: sizeStop,
105
- });
106
- continue;
107
- }
108
- if (sizeStop !== undefined) {
109
- clearSizeStop(stateDir);
110
- logger.info("simulation scanner's stop for size cleared: its class or code changed", {
111
- runtimeId,
112
- scannerName: scanner.name,
113
- stoppedClassMb: sizeStop.classMb,
114
- classMb,
115
- });
116
- }
117
- // 1. Mint.
118
- const scannerId = mintScannerId();
119
- // 2. Register.
120
- registry.register({
121
- scannerId,
122
- runtimeId,
123
- scannerName: scanner.name,
124
- wallet,
125
- fields: scanner.fields,
126
- });
127
- registeredInThisCall.push(scannerId);
128
- // 3. Write launch config. The filename is keyed on the unique scanner_id
129
- // so two scanners that share a name never overwrite each other on disk.
130
- // The state directory is keyed on the scanner NAME so it is stable
131
- // across relaunch — the restarted child resumes its state and replays
132
- // its delivery journal (the scaffold derives the journal from state_path).
133
- const cfgPath = path.join(launchConfigDir, `${scannerId}.launch.json`);
134
- // Launch-config JSON — the FROZEN launcher↔scaffold key contract (design §4a).
135
- // Hard cut: `interval` → `interval_seconds`, `params` → `inputs`.
136
- const launchCfg = {
137
- path: scanner.path,
138
- entrypoint: scanner.entrypoint,
139
- interval_seconds: scanner.intervalSeconds,
140
- state_path: path.join(stateDir, "state.json"),
141
- default_signal_validity_seconds: scanner.defaultSignalValiditySeconds,
142
- // Per-signal data{} schema (recipe `signal_data_schema`, held here as
143
- // `scanner.fields`). The scaffold reads it and validates each signal's
144
- // `data` scaffold-side, POSTing a violation to /errors for early, loud
145
- // feedback. Additive — intake keeps its authoritative server-side check.
146
- signal_data_schema: scanner.fields,
147
- wallet,
148
- scanner_name: scanner.name,
149
- };
150
- if (scanner.timeoutSeconds !== undefined) {
151
- launchCfg.timeout_seconds = scanner.timeoutSeconds;
152
- }
153
- if (scanner.inputs !== undefined) {
154
- launchCfg.inputs = scanner.inputs;
155
- }
156
- if (scanner.stateHistoryMaxCount !== undefined) {
157
- launchCfg.state_history_max_count = scanner.stateHistoryMaxCount;
158
- }
159
- if (classMb !== undefined) {
160
- launchCfg.class_mb = classMb;
161
- }
162
- else if (simulation) {
163
- logger.warn("simulation scanner has no memory class in the registry; running it unlimited", {
164
- runtimeId,
165
- scannerName: scanner.name,
166
- wallet,
167
- });
168
- }
169
- fs.writeFileSync(cfgPath, JSON.stringify(launchCfg, null, 2), "utf8");
170
- // Mutable id holder so the lastAliveAt closure always reads the current id.
171
- const idHolder = { value: scannerId };
172
- // 4. Build spawn spec.
173
- const pythonBin = process.env.PYTHON ?? "python3";
174
- const existingPythonPath = process.env.PYTHONPATH ?? "";
175
- const pythonPath = existingPythonPath
176
- ? `${scaffoldPackageDir}:${existingPythonPath}`
177
- : scaffoldPackageDir;
178
- const maxSilenceMs = Math.max(scanner.intervalSeconds * 2, 30) * 1000;
179
- const spec = {
180
- command: pythonBin,
181
- args: ["-m", "scaffold", cfgPath],
182
- env: {
183
- EXTERNAL_SCANNER_ID: scannerId,
184
- SIGNAL_INGESTION_URL: intakeUrl,
185
- PYTHONPATH: pythonPath,
186
- // Inject MCP creds only when present — omit (never "") when absent so
187
- // the Python ctx.senpi_mcp client stays loud at first use.
188
- ...(senpiApiKey ? { SENPI_AUTH_TOKEN: senpiApiKey } : {}),
189
- ...(senpiMcpUrl ? { SENPI_MCP_URL: senpiMcpUrl } : {}),
190
- },
191
- marker: runtimeId,
192
- initialDelayMs: i * 250,
193
- lastAliveAt: () => liveness.lastAliveAt(idHolder.value),
194
- maxSilenceMs,
195
- ...(classMb !== undefined ? { memoryClassMb: classMb } : {}),
196
- ...supervisorOptions,
197
- };
198
- // 5. Construct supervisor (NOT started yet — start() calls supervisor.start()).
199
- const supervisor = createSupervisor(spec, logger);
200
- // Per-scanner supervision accumulator, read by describeSupervision(). Kept
201
- // alongside the supervisor (whose getStatus() is the status source of truth).
202
- const supervision = {
203
- restartCount: 0,
204
- };
205
- // Wire the supervisor event hook (used by E2E to capture pid).
206
- if (onSupervisorEvent) {
207
- supervisor.on("event", (e) => {
208
- onSupervisorEvent(e);
209
- });
210
- }
211
- // Telemetry bridge: translate each lifecycle event into its `scanner.*` catalog event and its
212
- // health metric. Read the scanner id fresh from the holder so it reflects the run being
213
- // reported — this is wired BEFORE the remint listener below, so a `restarting` event still
214
- // carries the exiting run's id.
215
- supervisor.on("event", (e) => {
216
- const evt = e;
217
- const lifecycleCtx = {
218
- scannerName: scanner.name,
219
- scannerId: idHolder.value,
220
- supervisorId: supervisor.supervisorId,
221
- wallet,
222
- };
223
- emitEvent(logger, () => buildScannerLifecycleEvent(evt, lifecycleCtx));
224
- recordScannerLifecycleMetrics(evt, lifecycleCtx);
225
- // Accumulate supervision facts for describeSupervision(). restartCount is
226
- // the cumulative child-restart tally; degradedReason mirrors the supervisor's
227
- // degraded/recovered transitions so it never lingers after recovery.
228
- if (evt.type === "restarting") {
229
- supervision.restartCount++;
230
- }
231
- else if (evt.type === "degraded") {
232
- supervision.degradedReason = evt.reason;
233
- }
234
- else if (evt.type === "recovered") {
235
- supervision.degradedReason = undefined;
236
- }
237
- else if (evt.type === "stopped-for-size") {
238
- supervision.degradedReason = stoppedForSizeReason(evt.classMb, evt.memoryMb);
239
- try {
240
- writeSizeStop(stateDir, sizeStopRecord({ ...identity, classMb: evt.classMb }, evt.memoryMb, new Date()));
241
- }
242
- catch (err) {
243
- logger.warn("could not record the stop for size; the scanner starts again at the next boot", {
244
- runtimeId,
245
- scannerName: scanner.name,
246
- error: err instanceof Error ? err.message : String(err),
247
- });
248
- }
249
- }
250
- });
251
- // 6. Subscribe to restarting for remint.
252
- supervisor.on("event", (e) => {
253
- const evt = e;
254
- if (evt.type === "restarting") {
255
- const oldId = idHolder.value;
256
- try {
257
- registry.unregister(oldId);
258
- const newId = mintScannerId();
259
- idHolder.value = newId;
260
- registry.register({
261
- scannerId: newId,
262
- runtimeId,
263
- scannerName: scanner.name,
264
- wallet,
265
- fields: scanner.fields,
266
- });
267
- // Rewrite env so the next spawn carries the new id.
268
- supervisor.spec.env = {
269
- ...supervisor.spec.env,
270
- EXTERNAL_SCANNER_ID: newId,
271
- };
272
- }
273
- catch (err) {
274
- // A failed re-mint breaks the zombie fence — the scanner can be left with no registry
275
- // entry, so its signals are refused (UNKNOWN_SCANNER). Surface it rather than let the
276
- // supervisor's safeEmit swallow it as a generic listener throw.
277
- emitEvent(logger, () => buildScannerLaunchFailedEvent({
278
- scannerName: scanner.name,
279
- phase: "remint",
280
- wallet,
281
- scannerId: oldId,
282
- supervisorId: supervisor.supervisorId,
283
- error: err,
284
- }));
285
- }
286
- }
287
- });
288
- this.active.push({
289
- kind: "supervised",
290
- scannerName: scanner.name,
291
- intervalSeconds: scanner.intervalSeconds,
292
- currentId: idHolder,
293
- supervisor,
294
- supervision,
295
- });
59
+ failingScanner = scanners[i].name;
60
+ this.active.push(this.buildScanner(i, registeredInThisCall));
296
61
  }
297
62
  // Mark as initialized only after the full loop succeeds (so a partial
298
63
  // failure does not prevent a clean retry on start()).
@@ -318,8 +83,251 @@ export class ScannerLauncher {
318
83
  throw err;
319
84
  }
320
85
  }
86
+ buildScanner(i, registered) {
87
+ const { runtimeId, wallet, scanners, registry, liveness, intakeUrl, scaffoldPackageDir, launchConfigDir, logger, supervisorOptions = {}, } = this.deps;
88
+ // Resolve MCP creds: explicit deps win, else fall back to process.env.
89
+ // Empty/absent values are dropped so we never inject a misleading "".
90
+ const senpiApiKey = this.deps.senpiApiKey ||
91
+ process.env.SENPI_AUTH_TOKEN ||
92
+ process.env.SENPI_API_KEY ||
93
+ undefined;
94
+ const senpiMcpUrl = this.deps.senpiMcpUrl || process.env.SENPI_MCP_URL || undefined;
95
+ const mintScannerId = this.deps.mintScannerId ?? (() => makeId("scanner"));
96
+ const createSupervisor = this.deps.createSupervisor ??
97
+ ((spec, lg) => new LongRunningSupervisor(spec, lg));
98
+ const onSupervisorEvent = this.deps.onSupervisorEvent;
99
+ const simulation = walletMode(wallet) === "paper";
100
+ const scanner = scanners[i];
101
+ if (!scanner.path) {
102
+ throw new Error(`ScannerLauncher: scanner "${scanner.name}" is missing required field "path"`);
103
+ }
104
+ if (!scanner.entrypoint) {
105
+ throw new Error(`ScannerLauncher: scanner "${scanner.name}" is missing required field "entrypoint"`);
106
+ }
107
+ const safeName = scanner.name.replace(/[^a-zA-Z0-9_-]/g, "_");
108
+ // Include the scanner's array index so two scanners that share a name (or
109
+ // whose names sanitize to the same string) never share a state directory
110
+ // or delivery journal. The index is stable across relaunch (same config
111
+ // position), so state and the journal survive a restart.
112
+ const stateDir = path.join(launchConfigDir, "scanner-state", `${safeName}-${i}`);
113
+ fs.mkdirSync(stateDir, { recursive: true });
114
+ const classes = this.deps.scannerClassesMb;
115
+ const classMb = simulation && classes !== undefined && Object.hasOwn(classes, scanner.name)
116
+ ? classes[scanner.name]
117
+ : undefined;
118
+ const identity = {
119
+ scannerName: scanner.name,
120
+ classMb,
121
+ codeDigest: classMb !== undefined ? scannerCodeDigest(scanner) : "",
122
+ };
123
+ const sizeStop = readSizeStop(stateDir);
124
+ if (sizeStop !== undefined && holds(sizeStop, identity)) {
125
+ logger.info("simulation scanner stays stopped for size until its class or code changes", {
126
+ runtimeId,
127
+ scannerName: scanner.name,
128
+ classMb,
129
+ nextClassMb: sizeStop.nextClassMb,
130
+ });
131
+ return {
132
+ kind: "stopped-for-size",
133
+ scannerName: scanner.name,
134
+ intervalSeconds: scanner.intervalSeconds,
135
+ record: sizeStop,
136
+ };
137
+ }
138
+ if (sizeStop !== undefined) {
139
+ clearSizeStop(stateDir);
140
+ logger.info("simulation scanner's stop for size cleared: its class or code changed", {
141
+ runtimeId,
142
+ scannerName: scanner.name,
143
+ stoppedClassMb: sizeStop.classMb,
144
+ classMb,
145
+ });
146
+ }
147
+ // 1. Mint.
148
+ const scannerId = mintScannerId();
149
+ // 2. Register.
150
+ registry.register({
151
+ scannerId,
152
+ runtimeId,
153
+ scannerName: scanner.name,
154
+ wallet,
155
+ fields: scanner.fields,
156
+ });
157
+ registered.push(scannerId);
158
+ // 3. Write launch config. The filename is keyed on the unique scanner_id
159
+ // so two scanners that share a name never overwrite each other on disk.
160
+ // The state directory is keyed on the scanner NAME so it is stable
161
+ // across relaunch — the restarted child resumes its state and replays
162
+ // its delivery journal (the scaffold derives the journal from state_path).
163
+ const cfgPath = path.join(launchConfigDir, `${scannerId}.launch.json`);
164
+ // Launch-config JSON — the FROZEN launcher↔scaffold key contract (design §4a).
165
+ // Hard cut: `interval` → `interval_seconds`, `params` → `inputs`.
166
+ const launchCfg = {
167
+ path: scanner.path,
168
+ entrypoint: scanner.entrypoint,
169
+ interval_seconds: scanner.intervalSeconds,
170
+ state_path: path.join(stateDir, "state.json"),
171
+ default_signal_validity_seconds: scanner.defaultSignalValiditySeconds,
172
+ // Per-signal data{} schema (recipe `signal_data_schema`, held here as
173
+ // `scanner.fields`). The scaffold reads it and validates each signal's
174
+ // `data` scaffold-side, POSTing a violation to /errors for early, loud
175
+ // feedback. Additive — intake keeps its authoritative server-side check.
176
+ signal_data_schema: scanner.fields,
177
+ wallet,
178
+ scanner_name: scanner.name,
179
+ };
180
+ if (scanner.timeoutSeconds !== undefined) {
181
+ launchCfg.timeout_seconds = scanner.timeoutSeconds;
182
+ }
183
+ if (scanner.inputs !== undefined) {
184
+ launchCfg.inputs = scanner.inputs;
185
+ }
186
+ if (scanner.stateHistoryMaxCount !== undefined) {
187
+ launchCfg.state_history_max_count = scanner.stateHistoryMaxCount;
188
+ }
189
+ if (classMb !== undefined) {
190
+ launchCfg.class_mb = classMb;
191
+ }
192
+ else if (simulation) {
193
+ logger.warn("simulation scanner has no memory class in the registry; running it unlimited", {
194
+ runtimeId,
195
+ scannerName: scanner.name,
196
+ wallet,
197
+ });
198
+ }
199
+ fs.writeFileSync(cfgPath, JSON.stringify(launchCfg, null, 2), "utf8");
200
+ // Mutable id holder so the lastAliveAt closure always reads the current id.
201
+ const idHolder = { value: scannerId };
202
+ // 4. Build spawn spec.
203
+ const pythonBin = process.env.PYTHON ?? "python3";
204
+ const existingPythonPath = process.env.PYTHONPATH ?? "";
205
+ const pythonPath = existingPythonPath
206
+ ? `${scaffoldPackageDir}:${existingPythonPath}`
207
+ : scaffoldPackageDir;
208
+ const maxSilenceMs = Math.max(scanner.intervalSeconds * 2, 30) * 1000;
209
+ const spec = {
210
+ command: pythonBin,
211
+ args: ["-m", "scaffold", cfgPath],
212
+ env: {
213
+ EXTERNAL_SCANNER_ID: scannerId,
214
+ SIGNAL_INGESTION_URL: intakeUrl,
215
+ PYTHONPATH: pythonPath,
216
+ // Inject MCP creds only when present — omit (never "") when absent so
217
+ // the Python ctx.senpi_mcp client stays loud at first use.
218
+ ...(senpiApiKey ? { SENPI_AUTH_TOKEN: senpiApiKey } : {}),
219
+ ...(senpiMcpUrl ? { SENPI_MCP_URL: senpiMcpUrl } : {}),
220
+ },
221
+ marker: runtimeId,
222
+ initialDelayMs: i * 250,
223
+ lastAliveAt: () => liveness.lastAliveAt(idHolder.value),
224
+ maxSilenceMs,
225
+ ...(classMb !== undefined ? { memoryClassMb: classMb } : {}),
226
+ ...supervisorOptions,
227
+ };
228
+ // 5. Construct supervisor (NOT started yet — start() calls supervisor.start()).
229
+ const supervisor = createSupervisor(spec, logger);
230
+ // Per-scanner supervision accumulator, read by describeSupervision(). Kept
231
+ // alongside the supervisor (whose getStatus() is the status source of truth).
232
+ const supervision = {
233
+ restartCount: 0,
234
+ };
235
+ // Wire the supervisor event hook (used by E2E to capture pid).
236
+ if (onSupervisorEvent) {
237
+ supervisor.on("event", (e) => {
238
+ onSupervisorEvent(e);
239
+ });
240
+ }
241
+ // Telemetry bridge: translate each lifecycle event into its `scanner.*` catalog event and its
242
+ // health metric. Read the scanner id fresh from the holder so it reflects the run being
243
+ // reported — this is wired BEFORE the remint listener below, so a `restarting` event still
244
+ // carries the exiting run's id.
245
+ supervisor.on("event", (e) => {
246
+ const evt = e;
247
+ const lifecycleCtx = {
248
+ scannerName: scanner.name,
249
+ scannerId: idHolder.value,
250
+ supervisorId: supervisor.supervisorId,
251
+ wallet,
252
+ };
253
+ emitEvent(logger, () => buildScannerLifecycleEvent(evt, lifecycleCtx));
254
+ recordScannerLifecycleMetrics(evt, lifecycleCtx);
255
+ // Accumulate supervision facts for describeSupervision(). restartCount is
256
+ // the cumulative child-restart tally; degradedReason mirrors the supervisor's
257
+ // degraded/recovered transitions so it never lingers after recovery.
258
+ if (evt.type === "restarting") {
259
+ supervision.restartCount++;
260
+ }
261
+ else if (evt.type === "degraded") {
262
+ supervision.degradedReason = evt.reason;
263
+ }
264
+ else if (evt.type === "recovered") {
265
+ supervision.degradedReason = undefined;
266
+ }
267
+ else if (evt.type === "stopped-for-size") {
268
+ supervision.degradedReason = stoppedForSizeReason(evt.classMb, evt.memoryMb);
269
+ try {
270
+ writeSizeStop(stateDir, sizeStopRecord({ ...identity, classMb: evt.classMb }, evt.memoryMb, new Date()));
271
+ }
272
+ catch (err) {
273
+ logger.warn("could not record the stop for size; the scanner starts again at the next boot", {
274
+ runtimeId,
275
+ scannerName: scanner.name,
276
+ error: err instanceof Error ? err.message : String(err),
277
+ });
278
+ }
279
+ }
280
+ });
281
+ // 6. Subscribe to restarting for remint.
282
+ supervisor.on("event", (e) => {
283
+ const evt = e;
284
+ if (evt.type === "restarting") {
285
+ const oldId = idHolder.value;
286
+ try {
287
+ registry.unregister(oldId);
288
+ const newId = mintScannerId();
289
+ idHolder.value = newId;
290
+ registry.register({
291
+ scannerId: newId,
292
+ runtimeId,
293
+ scannerName: scanner.name,
294
+ wallet,
295
+ fields: scanner.fields,
296
+ });
297
+ // Rewrite env so the next spawn carries the new id.
298
+ supervisor.spec.env = {
299
+ ...supervisor.spec.env,
300
+ EXTERNAL_SCANNER_ID: newId,
301
+ };
302
+ }
303
+ catch (err) {
304
+ // A failed re-mint breaks the zombie fence — the scanner can be left with no registry
305
+ // entry, so its signals are refused (UNKNOWN_SCANNER). Surface it rather than let the
306
+ // supervisor's safeEmit swallow it as a generic listener throw.
307
+ emitEvent(logger, () => buildScannerLaunchFailedEvent({
308
+ scannerName: scanner.name,
309
+ phase: "remint",
310
+ wallet,
311
+ scannerId: oldId,
312
+ supervisorId: supervisor.supervisorId,
313
+ error: err,
314
+ }));
315
+ }
316
+ }
317
+ });
318
+ return {
319
+ kind: "supervised",
320
+ index: i,
321
+ scannerName: scanner.name,
322
+ intervalSeconds: scanner.intervalSeconds,
323
+ currentId: idHolder,
324
+ supervisor,
325
+ supervision,
326
+ };
327
+ }
321
328
  async start() {
322
329
  this._buildAndRegister();
330
+ this.started = true;
323
331
  for (const scanner of this.active) {
324
332
  if (scanner.kind === "supervised")
325
333
  scanner.supervisor.start();
@@ -346,6 +354,15 @@ export class ScannerLauncher {
346
354
  degradedReason: scanner.record.reason,
347
355
  };
348
356
  }
357
+ if (scanner.kind === "paused") {
358
+ return {
359
+ scannerName: scanner.scannerName,
360
+ supervisorStatus: "paused",
361
+ restartCount: 0,
362
+ intervalSeconds: scanner.intervalSeconds,
363
+ lastAliveAt: null,
364
+ };
365
+ }
349
366
  const { scannerName, intervalSeconds, currentId, supervisor, supervision } = scanner;
350
367
  const supervisorStatus = supervisor.getStatus();
351
368
  const row = {
@@ -364,13 +381,83 @@ export class ScannerLauncher {
364
381
  return row;
365
382
  });
366
383
  }
367
- async stop() {
368
- await Promise.all(this.active.map(async (scanner) => {
369
- if (scanner.kind === "stopped-for-size")
384
+ /**
385
+ * Stop every running scanner because its simulation is paused, and show it `paused`. A scanner
386
+ * held stopped for size stays held. A no-op when nothing runs, so every status read may call it.
387
+ */
388
+ async pause() {
389
+ const stopping = [];
390
+ const paused = [];
391
+ this.active.forEach((scanner, k) => {
392
+ if (scanner.kind !== "supervised" || scanner.supervisor.getStatus() === "stopped-for-size")
370
393
  return;
371
394
  this.deps.registry.unregister(scanner.currentId.value);
372
- await scanner.supervisor.stop();
373
- }));
395
+ stopping.push(scanner.supervisor.stop());
396
+ paused.push(scanner.scannerName);
397
+ this.active[k] = {
398
+ kind: "paused",
399
+ index: scanner.index,
400
+ scannerName: scanner.scannerName,
401
+ intervalSeconds: scanner.intervalSeconds,
402
+ };
403
+ });
404
+ if (paused.length === 0)
405
+ return;
406
+ this.deps.logger.info("simulation paused: its scanners are stopped until it is active again", {
407
+ runtimeId: this.deps.runtimeId,
408
+ scanners: paused,
409
+ });
410
+ this.pausing = Promise.allSettled([this.pausing, ...stopping]);
411
+ await Promise.all(stopping);
412
+ }
413
+ /**
414
+ * Start every paused scanner again, rebuilt as at boot: one whose stop-for-size record still holds
415
+ * stays stopped. A no-op when nothing is paused or after `stop()`. A scanner that fails to rebuild
416
+ * stays paused, so the next status read retries it.
417
+ */
418
+ resume() {
419
+ if (this.stopped)
420
+ return;
421
+ const resumed = [];
422
+ this.active.forEach((scanner, k) => {
423
+ if (scanner.kind !== "paused")
424
+ return;
425
+ const registered = [];
426
+ try {
427
+ const next = this.buildScanner(scanner.index, registered);
428
+ if (this.started && next.kind === "supervised")
429
+ next.supervisor.start();
430
+ this.active[k] = next;
431
+ resumed.push(scanner.scannerName);
432
+ }
433
+ catch (err) {
434
+ for (const id of registered)
435
+ this.deps.registry.unregister(id);
436
+ this.deps.logger.warn("simulation scanner not started again; the next status read retries", {
437
+ runtimeId: this.deps.runtimeId,
438
+ scannerName: scanner.scannerName,
439
+ error: err instanceof Error ? err.message : String(err),
440
+ });
441
+ }
442
+ });
443
+ if (resumed.length === 0)
444
+ return;
445
+ this.deps.logger.info("simulation active again: its scanners are started", {
446
+ runtimeId: this.deps.runtimeId,
447
+ scanners: resumed,
448
+ });
449
+ }
450
+ async stop() {
451
+ this.stopped = true;
452
+ await Promise.all([
453
+ this.pausing,
454
+ ...this.active.map(async (scanner) => {
455
+ if (scanner.kind !== "supervised")
456
+ return;
457
+ this.deps.registry.unregister(scanner.currentId.value);
458
+ await scanner.supervisor.stop();
459
+ }),
460
+ ]);
374
461
  this.active.length = 0;
375
462
  }
376
463
  }