edge-impulse-linux 1.26.0 → 1.26.2

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 (97) hide show
  1. package/README.md +14 -5
  2. package/build/cli/linux/agent-capture.d.ts +29 -0
  3. package/build/cli/linux/agent-capture.js +94 -0
  4. package/build/cli/linux/agent-capture.js.map +1 -0
  5. package/build/cli/linux/agent-runner-metadata.d.ts +12 -3
  6. package/build/cli/linux/agent-runner-metadata.js +15 -3
  7. package/build/cli/linux/agent-runner-metadata.js.map +1 -1
  8. package/build/cli/linux/audio-utils.d.ts +1 -10
  9. package/build/cli/linux/audio-utils.js +2 -25
  10. package/build/cli/linux/audio-utils.js.map +1 -1
  11. package/build/cli/linux/runner-downloader.js +27 -1
  12. package/build/cli/linux/runner-downloader.js.map +1 -1
  13. package/build/cli/linux/runner-utils.d.ts +5 -0
  14. package/build/cli/linux/runner-utils.js +7 -2
  15. package/build/cli/linux/runner-utils.js.map +1 -1
  16. package/build/cli/linux/runner.js +332 -117
  17. package/build/cli/linux/runner.js.map +1 -1
  18. package/build/cli-common/model-monitor.d.ts +97 -10
  19. package/build/cli-common/model-monitor.js +380 -373
  20. package/build/cli-common/model-monitor.js.map +1 -1
  21. package/build/cli-common/remote-mgmt-service.d.ts +1 -0
  22. package/build/cli-common/remote-mgmt-service.js +29 -11
  23. package/build/cli-common/remote-mgmt-service.js.map +1 -1
  24. package/build/library/classifier/audio-classifier.d.ts +28 -3
  25. package/build/library/classifier/audio-classifier.js +126 -40
  26. package/build/library/classifier/audio-classifier.js.map +1 -1
  27. package/build/library/classifier/image-classifier.d.ts +14 -0
  28. package/build/library/classifier/image-classifier.js +79 -3
  29. package/build/library/classifier/image-classifier.js.map +1 -1
  30. package/build/library/classifier/libcwrapper.d.ts +7 -1
  31. package/build/library/classifier/libcwrapper.js +10 -2
  32. package/build/library/classifier/libcwrapper.js.map +1 -1
  33. package/build/library/classifier/linux-impulse-runner.d.ts +36 -1
  34. package/build/library/classifier/linux-impulse-runner.js +266 -55
  35. package/build/library/classifier/linux-impulse-runner.js.map +1 -1
  36. package/build/library/sensors/audio-utils.d.ts +4 -0
  37. package/build/library/sensors/audio-utils.js +23 -0
  38. package/build/library/sensors/audio-utils.js.map +1 -0
  39. package/build/library/sensors/gstreamer.d.ts +1 -1
  40. package/build/library/sensors/gstreamer.js +45 -9
  41. package/build/library/sensors/gstreamer.js.map +1 -1
  42. package/build/library/sensors/recorder.js +61 -23
  43. package/build/library/sensors/recorder.js.map +1 -1
  44. package/build/sdk/studio/sdk/api/devicesApi.d.ts +2 -2
  45. package/build/sdk/studio/sdk/api/devicesApi.js +2 -2
  46. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.d.ts +7 -0
  47. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.js +4 -0
  48. package/build/sdk/studio/sdk/model/additionalMetricOptionalFullPrecisionValue.js.map +1 -0
  49. package/build/sdk/studio/sdk/model/dSPGroupItem.d.ts +9 -1
  50. package/build/sdk/studio/sdk/model/dSPGroupItem.js +3 -1
  51. package/build/sdk/studio/sdk/model/dSPGroupItem.js.map +1 -1
  52. package/build/sdk/studio/sdk/model/device.d.ts +9 -0
  53. package/build/sdk/studio/sdk/model/device.js.map +1 -1
  54. package/build/sdk/studio/sdk/model/deviceApplication.d.ts +12 -0
  55. package/build/sdk/studio/sdk/model/deviceApplication.js +4 -0
  56. package/build/sdk/studio/sdk/model/deviceApplication.js.map +1 -0
  57. package/build/sdk/studio/sdk/model/deviceApplicationModel.d.ts +13 -0
  58. package/build/sdk/studio/sdk/model/deviceApplicationModel.js +4 -0
  59. package/build/sdk/studio/sdk/model/deviceApplicationModel.js.map +1 -0
  60. package/build/sdk/studio/sdk/model/deviceDeploymentEvent.d.ts +9 -0
  61. package/build/sdk/studio/sdk/model/deviceDeploymentEvent.js.map +1 -1
  62. package/build/sdk/studio/sdk/model/deviceModelDeploymentRequest.d.ts +5 -0
  63. package/build/sdk/studio/sdk/model/foldModelMetadata.d.ts +5 -0
  64. package/build/sdk/studio/sdk/model/getMonitoringEventDetailsResponse.d.ts +4 -0
  65. package/build/sdk/studio/sdk/model/getMonitoringEventDetailsResponse.js.map +1 -1
  66. package/build/sdk/studio/sdk/model/inferenceHistoryAggregate.d.ts +8 -0
  67. package/build/sdk/studio/sdk/model/kerasModelMetadata.d.ts +5 -0
  68. package/build/sdk/studio/sdk/model/kerasModelMetadataBase.d.ts +5 -0
  69. package/build/sdk/studio/sdk/model/kerasModelMetadataResponse.d.ts +5 -0
  70. package/build/sdk/studio/sdk/model/models.d.ts +3 -0
  71. package/build/sdk/studio/sdk/model/models.js +3 -0
  72. package/build/sdk/studio/sdk/model/models.js.map +1 -1
  73. package/build/sdk/studio/sdk/model/monitoringEventContext.d.ts +12 -0
  74. package/build/sdk/studio/sdk/model/monitoringInferenceSummary.d.ts +4 -0
  75. package/build/sdk/studio/sdk/model/userOrganization.d.ts +2 -0
  76. package/build/shared/viewmodels/init.d.ts +0 -1
  77. package/build/shared/viewmodels/init.js +0 -1
  78. package/build/shared/viewmodels/init.js.map +1 -1
  79. package/package.json +5 -2
  80. package/test/agent-bundle-lifecycle.test.ts +445 -0
  81. package/test/agent-bundle.test.ts +104 -0
  82. package/test/agent-capture.test.ts +528 -0
  83. package/test/agent-client.test.ts +263 -138
  84. package/test/agent-command-processor.test.ts +194 -0
  85. package/test/agent-preview-replacement.test.ts +114 -0
  86. package/test/agent-runner-configuration.test.ts +119 -0
  87. package/test/agent-runner-integration.test.ts +372 -0
  88. package/test/gstreamer.test.ts +1 -1
  89. package/test/helpers/mock-agent.ts +106 -0
  90. package/test/model-monitor.test.ts +250 -55
  91. package/test/monitoring-fixture.ts +168 -0
  92. package/test/monitoring-policy-protocol.test.ts +193 -1
  93. package/test/runner-preview.test.ts +59 -0
  94. package/test/summary-rules-fixtures.test.ts +194 -0
  95. package/test/utils/agent-runner-fixtures.ts +147 -0
  96. package/test/agent-runner-metadata.test.ts +0 -31
  97. package/test/sensor-selection.test.ts +0 -26
@@ -53,12 +53,27 @@ const agent_runner_metadata_1 = require("./agent-runner-metadata");
53
53
  const audio_utils_1 = require("./audio-utils");
54
54
  const RUNNER_PREFIX = '\x1b[33m[RUN]\x1b[0m';
55
55
  const CLASSIFIER_THRESHOLD = { id: 42, type: 'classification', min_score: 0.001 };
56
+ // Leaves the current activation lease time to stop a failed candidate and post its failure result.
57
+ const DEFAULT_AGENT_BUNDLE_PREPARE_TIMEOUT_MS = 25000;
58
+ const AGENT_FAILURE_RESULT_GRACE_MS = 11000;
59
+ const TERMINAL_SHUTDOWN_TIMEOUT_MS = 10000;
60
+ const PLANNED_RESTART_EXIT_CODE = 75;
56
61
  let audioClassifier;
57
62
  let imageClassifier;
58
63
  let modelMonitor;
59
64
  let configFactory;
60
65
  let agentClient;
66
+ let agentBundleLifecycle;
67
+ let agentCapture;
68
+ let terminateRunner;
61
69
  let vlmServerProcess = null;
70
+ /** Requests terminal agent-mode shutdown without returning to the command result path. */
71
+ async function restartForBundleActivation() {
72
+ if (!terminateRunner) {
73
+ throw new Error('Cannot restart for bundle activation before serving has started');
74
+ }
75
+ return terminateRunner('A different bundle is ready for activation', PLANNED_RESTART_EXIT_CODE);
76
+ }
62
77
  // total inference count
63
78
  let totalInferenceCount = 0;
64
79
  const packageVersion = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(__dirname, '..', '..', '..', 'package.json'), 'utf-8')).version;
@@ -66,7 +81,7 @@ commander_1.default
66
81
  .description('Edge Impulse Linux runner ' + packageVersion)
67
82
  .version(packageVersion)
68
83
  .option('--model-file <file>', 'Specify model file (either path to .eim, or the socket on which the model is running), ' +
69
- 'if not provided the model will be fetched from Edge Impulse. Agent mode also reads EI_MODEL_FILE')
84
+ 'if not provided the model will be fetched from Edge Impulse. Cannot be used in agent mode')
70
85
  .option('--api-key <key>', 'API key to authenticate with Edge Impulse (overrides current credentials)')
71
86
  .option('--agent <socket>', 'Report to the Edge Impulse device agent over this Unix socket. Also reads EI_AGENT_SOCKET')
72
87
  .option('--download <file>', 'Just download the model and store it on the file system')
@@ -76,7 +91,7 @@ commander_1.default
76
91
  .option('--force-variant <variant>', 'Do not autodetect the model variant, but set it by hand (e.g. "int8")')
77
92
  .option('--force-resize-mode <mode>', 'Do not use the resize method from the impulse, but set it by hand (valid: "squash", "fit-shortest" or "fit-longest")')
78
93
  .option('--force-camera-resolution <width,height>', 'Do not auto-select camera resolution based on your impulse, but force a resolution (format: "1280,720" for w=1280, h=720)')
79
- .option('--impulse-id <impulseId>', 'Select the impulse ID (if you have multiple impulses). Agent mode also reads EI_IMPULSE_ID')
94
+ .option('--impulse-id <impulseId>', 'Select the impulse ID (if you have multiple impulses). Cannot be used in agent mode')
80
95
  .option('--run-http-server <port>', 'Do not run using a sensor, but instead expose an API server at the specified port. ' +
81
96
  'Agent mode also reads EI_RUNNER_HTTP_PORT')
82
97
  .option('--preview-port <port>', 'Port to use to render the preview HTTP interface (default: 4912) (ignored when running with --run-http-server). ' +
@@ -84,6 +99,8 @@ commander_1.default
84
99
  .option('--preview-host <host>', 'Host to listen on for the preview HTTP interface (default: 0.0.0.0) (ignored when running with --run-http-server). ' +
85
100
  'Alternatively you can use the HOST environmental variable. If both are set then `--preview-host` takes precedence.')
86
101
  .option('--preview-original-resolution', 'If set, does not resize the preview image to the impulse resolution')
102
+ .option('--preview-server', 'Serve the preview HTTP interface in agent mode, where it is off by default, for debugging. ' +
103
+ 'Agent mode also reads EI_RUNNER_PREVIEW_SERVER=1')
87
104
  .option('--monitor', 'Enable model monitoring', false)
88
105
  .option('--monitor-max-storage-size <size>', 'The maximum storage size to be used for model monitoring, in MB. Defaults to 250.')
89
106
  .option('--monitor-summary-interval-ms <ms>', `Preferred summary interval in milliseconds (minimum ${model_monitor_1.MIN_MONITOR_SUMMARY_INTERVAL_MS}). Adapts to active alert rules; without cadence negotiation the effective interval is at least ${model_monitor_1.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS}.`)
@@ -137,16 +154,17 @@ const enableGpuArgv = !!commander_1.default.enableGpu;
137
154
  const apiKeyArgv = commander_1.default.apiKey;
138
155
  const agentSocketArgv = commander_1.default.agent || process.env.EI_AGENT_SOCKET;
139
156
  const greengrassArgv = !!commander_1.default.greengrass;
140
- const modelFileArgv = commander_1.default.modelFile ||
141
- (agentSocketArgv ? process.env.EI_MODEL_FILE : undefined);
157
+ const agentModelFileArgv = commander_1.default.modelFile || process.env.EI_MODEL_FILE;
158
+ const modelFileArgv = agentSocketArgv ? undefined : commander_1.default.modelFile;
142
159
  const downloadArgv = commander_1.default.download;
143
- const forceTargetArgv = commander_1.default.forceTarget;
160
+ const forceTargetArgv = commander_1.default.forceTarget ||
161
+ (agentSocketArgv ? process.env.EI_RUNNER_TARGET : undefined);
144
162
  const forceEngineArgv = commander_1.default.forceEngine;
145
163
  const forceVariantArgv = commander_1.default.forceVariant;
146
164
  const forceResizeModeArgv = commander_1.default.forceResizeMode;
147
165
  const forceCameraResolutionArgv = commander_1.default.forceCameraResolution;
148
- const impulseIdArgvStr = commander_1.default.impulseId ||
149
- (agentSocketArgv ? process.env.EI_IMPULSE_ID : undefined);
166
+ const agentImpulseIdArgvStr = commander_1.default.impulseId || process.env.EI_IMPULSE_ID;
167
+ const impulseIdArgvStr = agentSocketArgv ? undefined : commander_1.default.impulseId;
150
168
  const impulseIdArgv = impulseIdArgvStr && !isNaN(Number(impulseIdArgvStr)) ? Number(impulseIdArgvStr) : undefined;
151
169
  const monitorArgv = !!commander_1.default.monitor;
152
170
  const monitorMaxStorageSizeStr = commander_1.default.monitorMaxStorageSize;
@@ -178,6 +196,7 @@ else if (process.env.HOST) {
178
196
  }
179
197
  const gstSourceArgv = commander_1.default.gstSource;
180
198
  let previewOriginalResolutionArgv = !!commander_1.default.previewOriginalResolution;
199
+ const previewServerArgv = (0, agent_runner_metadata_1.previewServerEnabled)(!!agentSocketArgv, !!commander_1.default.previewServer, agentSocketArgv ? process.env.EI_RUNNER_PREVIEW_SERVER : undefined);
181
200
  const enableVideo = (process.env.PROPHESEE_CAM === '1') || (process.env.ENABLE_VIDEO === '1');
182
201
  const dontPrintPredictionsArgv = !!commander_1.default.dontPrintPredictions;
183
202
  const thresholdsArgv = commander_1.default.thresholds;
@@ -191,6 +210,10 @@ const experimentalGstPreferJpegArgv = !!commander_1.default.experimentalGstPrefe
191
210
  let modeArgv = (commander_1.default.mode ||
192
211
  (agentSocketArgv ? process.env.EI_RUNNER_MODE : undefined));
193
212
  const fakeCameraArgv = commander_1.default.fakeCamera;
213
+ const agentBundlePrepareTimeoutValue = agentSocketArgv ?
214
+ process.env.EI_AGENT_BUNDLE_PREPARE_TIMEOUT_MS : undefined;
215
+ const agentBundlePrepareTimeoutMs = agentBundlePrepareTimeoutValue ?
216
+ Number(agentBundlePrepareTimeoutValue) : DEFAULT_AGENT_BUNDLE_PREPARE_TIMEOUT_MS;
194
217
  if (modeArgv === 'http-server' && typeof runHttpServerPort === 'undefined') {
195
218
  runHttpServerPort = 1337;
196
219
  }
@@ -239,17 +262,20 @@ const onSignal = async () => {
239
262
  console.log(RUNNER_PREFIX, 'Received stop signal, stopping application... ' +
240
263
  'Press CTRL+C again to force quit.');
241
264
  firstExit = false;
265
+ agentCapture?.disable();
242
266
  try {
243
- // Flush metrics before stopping
244
- if (modelMonitor) {
245
- await modelMonitor.flushMetrics();
246
- }
247
- if (audioClassifier) {
248
- await audioClassifier.stop();
267
+ try {
268
+ if (audioClassifier) {
269
+ await audioClassifier.stop();
270
+ }
271
+ if (imageClassifier) {
272
+ await imageClassifier.stop();
273
+ }
249
274
  }
250
- if (imageClassifier) {
251
- await imageClassifier.stop();
275
+ finally {
276
+ await modelMonitor?.stop();
252
277
  }
278
+ await agentBundleLifecycle?.stopPendingRunner();
253
279
  if (profiling) {
254
280
  profiling.printSummary();
255
281
  }
@@ -269,6 +295,24 @@ const onSignal = async () => {
269
295
  process.on('SIGHUP', onSignal);
270
296
  process.on('SIGINT', onSignal);
271
297
  process.on('SIGTERM', onSignal);
298
+ async function startPreviewServer(opts) {
299
+ try {
300
+ await (0, runner_utils_1.startWebServer)(opts);
301
+ }
302
+ catch (ex2) {
303
+ const ex = ex2;
304
+ if ((ex.message || ex.toString()).indexOf('EADDRINUSE') > -1) {
305
+ console.log('');
306
+ console.log(`EADDRINUSE: Could not listen on ${previewHostArgv}:${previewPortArgv}`);
307
+ console.log(`Most likely another application (for example, another instance of edge-impulse-linux-runner) is already listening on this port. You can select another port via --preview-port <port>, for example:`);
308
+ console.log(``);
309
+ console.log(` edge-impulse-linux-runner --preview-port ${previewPortArgv + 1}`);
310
+ console.log(``);
311
+ throw ex;
312
+ }
313
+ throw ex;
314
+ }
315
+ }
272
316
  async function ensureVlmServer(opts) {
273
317
  const { serverPath, modelFolder, modelName, serverDownloadUrl, modelDownloadUrl, serverAddress, serverPort, enableGpu } = opts;
274
318
  const serverExists = node_fs_1.default.existsSync(serverPath);
@@ -329,6 +373,8 @@ async function ensureVlmServer(opts) {
329
373
  }
330
374
  // eslint-disable-next-line @typescript-eslint/no-floating-promises
331
375
  (async () => {
376
+ // Retained outside the startup try block so failure handling can restore an empty registration.
377
+ let preparedAgentBundle;
332
378
  try {
333
379
  let modelFile;
334
380
  let remoteMgmt;
@@ -366,6 +412,8 @@ async function ensureVlmServer(opts) {
366
412
  throw new Error(`Invalid runner mode "${modeArgv}", expected "streaming" or "http-server"`);
367
413
  }
368
414
  if (agentSocketArgv) {
415
+ // Agent deployments start empty and receive their model through activateBundle. The
416
+ // reference Compose migration to this invocation is tracked by #16494.
369
417
  if (apiKeyArgv) {
370
418
  throw new Error('Cannot combine --agent and --api-key');
371
419
  }
@@ -375,11 +423,15 @@ async function ensureVlmServer(opts) {
375
423
  if (greengrassArgv) {
376
424
  throw new Error('Cannot combine --agent and --greengrass');
377
425
  }
378
- if (!modelFileArgv) {
379
- throw new Error('--agent currently requires --model-file until inference bundle activation is implemented');
426
+ if (agentModelFileArgv) {
427
+ throw new Error('Cannot combine --agent and --model-file or EI_MODEL_FILE; models are selected by activateBundle');
428
+ }
429
+ if (agentImpulseIdArgvStr) {
430
+ throw new Error('Cannot combine --agent and --impulse-id or EI_IMPULSE_ID; model identity comes from the bundle manifest');
380
431
  }
381
- if (!impulseIdArgv) {
382
- throw new Error('--agent with --model-file requires --impulse-id because the .eim does not report its impulse ID');
432
+ if (!Number.isInteger(agentBundlePrepareTimeoutMs) || agentBundlePrepareTimeoutMs <= 0) {
433
+ throw new Error(`Invalid EI_AGENT_BUNDLE_PREPARE_TIMEOUT_MS "${agentBundlePrepareTimeoutValue}", ` +
434
+ 'expected a positive integer');
383
435
  }
384
436
  }
385
437
  if (forceVariantArgv && quantizedArgv) {
@@ -505,12 +557,68 @@ async function ensureVlmServer(opts) {
505
557
  process.exit(0);
506
558
  }
507
559
  if (agentSocketArgv) {
508
- const AgentClientConstructor = await loadAgentClient();
560
+ const { AgentClient: AgentClientConstructor, AgentBundleLifecycle: AgentBundleLifecycleConstructor, AgentCaptureController: AgentCaptureControllerConstructor, } = await loadAgentModules();
509
561
  agentClient = new AgentClientConstructor(agentSocketArgv);
562
+ agentCapture = new AgentCaptureControllerConstructor();
563
+ agentBundleLifecycle = new AgentBundleLifecycleConstructor({
564
+ agentClient,
565
+ policy: {
566
+ // When lifecycle identity changes, include both manifest identity and initialized metadata.
567
+ createRegistration(bundle) {
568
+ return createAgentRegistration(bundle?.registrationModel, bundle?.manifestModel);
569
+ },
570
+ // Before activation, apply CLI thresholds and resize overrides to runtime metadata only.
571
+ async configure(candidate) {
572
+ if (forceResizeModeArgv) {
573
+ candidate.model.modelParameters.image_resize_mode = forceResizeModeArgv;
574
+ }
575
+ if (candidate.model.modelParameters.model_type === 'classification' &&
576
+ candidate.model.modelParameters.sensorType === 'camera') {
577
+ candidate.model.modelParameters.thresholds?.push(CLASSIFIER_THRESHOLD);
578
+ }
579
+ await setThresholdsFromArgv(candidate.runner, candidate.model);
580
+ },
581
+ // Before initial preparation, derive the configured input mode for runtime validation.
582
+ servingMode() {
583
+ return (0, agent_runner_metadata_1.agentRunnerMode)(runHttpServerPort, cameraArgv, microphoneArgv, undefined);
584
+ },
585
+ },
586
+ validateOptions: {
587
+ forceTarget: forceTargetArgv,
588
+ packageVersion,
589
+ },
590
+ prepareOptions: {
591
+ shmBehavior: shmBehaviorArgv,
592
+ startupTimeoutMs: agentBundlePrepareTimeoutMs,
593
+ verbose: verboseArgv,
594
+ },
595
+ });
596
+ // On activation delivery, restart after static validation so a fresh process owns the new model.
597
+ agentClient.commands.on('activateBundle', async (command) => {
598
+ const result = await agentBundleLifecycle.activateBundle(command);
599
+ if (result.kind === 'restart-required') {
600
+ await restartForBundleActivation();
601
+ }
602
+ });
603
+ // On capture delivery, read the canonical live sensor and prepare its required agent input.
604
+ agentClient.commands.on('capture', async (command) => {
605
+ const captured = await agentCapture.capture(command.capture);
606
+ return agentClient.prepareCapture({
607
+ type: captured.format,
608
+ buffer: captured.buffer,
609
+ }, captured.metadata);
610
+ });
611
+ // Agent mode deliberately starts without a model. The first activateBundle command is
612
+ // held open by the lifecycle until the selected sensor or HTTP server is ready to use it.
510
613
  await agentClient.connect(createAgentRegistration(undefined, undefined));
614
+ preparedAgentBundle = await agentBundleLifecycle.waitForInitialBundle();
511
615
  }
512
616
  let initializedProjectState;
513
- if (modelFileArgv) {
617
+ if (preparedAgentBundle) {
618
+ modelFile = undefined;
619
+ initializedProjectState = undefined;
620
+ }
621
+ else if (modelFileArgv) {
514
622
  // if we have the model file, just use that and make it executable
515
623
  modelFile = modelFileArgv;
516
624
  await node_fs_1.default.promises.chmod(modelFile, 0o755);
@@ -685,18 +793,81 @@ async function ensureVlmServer(opts) {
685
793
  };
686
794
  }
687
795
  // create the runner and init (get info from model file)
688
- runner = new linux_impulse_runner_1.LinuxImpulseRunner(modelFile, {
689
- verbose: verboseArgv,
690
- shmBehavior: shmBehaviorArgv,
691
- });
692
- model = await runner.init();
693
- if (agentClient) {
694
- // Register before applying runner-only threshold defaults or command-line overrides. The agent receives
695
- // the model metadata exactly as the .eim reported it.
696
- await agentClient.updateRegistration(createAgentRegistration(model, impulseIdArgv));
796
+ if (preparedAgentBundle) {
797
+ runner = preparedAgentBundle.runner;
798
+ model = preparedAgentBundle.model;
799
+ }
800
+ else {
801
+ if (!modelFile) {
802
+ throw new Error('No model file available');
803
+ }
804
+ runner = new linux_impulse_runner_1.LinuxImpulseRunner(modelFile, {
805
+ verbose: verboseArgv,
806
+ shmBehavior: shmBehaviorArgv,
807
+ });
808
+ model = await runner.init();
809
+ }
810
+ const inferenceAvailability = {
811
+ // Agent mode serves only after the agent accepts the model registration.
812
+ available: !agentSocketArgv,
813
+ };
814
+ let terminalShutdown;
815
+ terminateRunner = (reason, exitCode = 1) => {
816
+ if (terminalShutdown)
817
+ return terminalShutdown;
818
+ terminalShutdown = (async () => {
819
+ inferenceAvailability.available = false;
820
+ agentCapture?.disable();
821
+ const recovery = agentSocketArgv ? ' so the process supervisor can restart the runner' : '';
822
+ console.log(RUNNER_PREFIX, `${reason}; stopping${recovery}`);
823
+ const forceExit = setTimeout(() => {
824
+ console.warn(RUNNER_PREFIX, `Shutdown did not complete within ${TERMINAL_SHUTDOWN_TIMEOUT_MS} ms; exiting`);
825
+ if (vlmServerProcess)
826
+ (0, runner_utils_1.stopVlmServer)(vlmServerProcess);
827
+ process.exit(exitCode);
828
+ }, TERMINAL_SHUTDOWN_TIMEOUT_MS);
829
+ const cleanup = async (description, operation) => {
830
+ try {
831
+ await operation();
832
+ }
833
+ catch (cleanupError) {
834
+ console.warn(RUNNER_PREFIX, `Failed to ${description}`, asError(cleanupError).message);
835
+ }
836
+ };
837
+ try {
838
+ if (audioClassifier) {
839
+ await cleanup('stop audio inference', () => audioClassifier.stop());
840
+ }
841
+ else if (imageClassifier) {
842
+ await cleanup('stop image inference', () => imageClassifier.stop());
843
+ }
844
+ else {
845
+ await cleanup('stop model inference', () => runner.stop());
846
+ }
847
+ if (vlmServerProcess) {
848
+ await cleanup('stop the VLM server', () => (0, runner_utils_1.stopVlmServer)(vlmServerProcess));
849
+ }
850
+ // close() destroys the command stream and gives started event requests a bounded flush.
851
+ await cleanup('close the agent connection', async () => agentClient?.close());
852
+ }
853
+ finally {
854
+ clearTimeout(forceExit);
855
+ }
856
+ process.exit(exitCode);
857
+ })();
858
+ return terminalShutdown;
859
+ };
860
+ if (agentSocketArgv) {
861
+ // Agent mode exits for supervisor recovery when its serving model cannot recover in place.
862
+ runner.on('unexpectedTermination', termination => {
863
+ const detail = termination.signal ?
864
+ `signal ${termination.signal}` : termination.code !== null ?
865
+ `exit code ${termination.code}` : 'serving socket closed';
866
+ void terminateRunner?.(`The serving .eim terminated unexpectedly (${detail})`);
867
+ });
697
868
  }
698
869
  // treat the user provided resize arguments as-if from the model
699
- if (forceResizeModeArgv) {
870
+ if (forceResizeModeArgv && !preparedAgentBundle) {
700
871
  const resizeParam = model.modelParameters.image_resize_mode;
701
872
  model.modelParameters.image_resize_mode = forceResizeModeArgv || resizeParam || 'none';
702
873
  }
@@ -752,16 +923,18 @@ async function ensureVlmServer(opts) {
752
923
  model.modelParameters.image_resize_mode = "none";
753
924
  previewOriginalResolutionArgv = true;
754
925
  }
755
- if (model.modelParameters.model_type === 'classification' &&
926
+ if (!preparedAgentBundle && model.modelParameters.model_type === 'classification' &&
756
927
  model.modelParameters.sensorType === 'camera') {
757
928
  model.modelParameters.thresholds?.push(CLASSIFIER_THRESHOLD);
758
929
  }
759
- await setThresholdsFromArgv(runner, model);
930
+ if (!preparedAgentBundle) {
931
+ await setThresholdsFromArgv(runner, model);
932
+ }
760
933
  if (greengrassArgv && awsIOT?.isConnected() === true) {
761
934
  awsIOT.initModelInfo(model.project.name, "v" + model.project.deploy_version, model.modelParameters);
762
935
  }
763
936
  // if downloaded? then store...
764
- if (!modelFileArgv && modelPath) {
937
+ if (!agentSocketArgv && !modelFileArgv && modelPath && modelFile) {
765
938
  let file = modelPath.getModelPath(model.project.deploy_version);
766
939
  if (file !== modelFile) {
767
940
  await node_fs_1.default.promises.mkdir(node_path_1.default.dirname(file), { recursive: true });
@@ -774,6 +947,15 @@ async function ensureVlmServer(opts) {
774
947
  await configFactory.setDeploymentVersion(model.project.deploy_version);
775
948
  }
776
949
  let param = model.modelParameters;
950
+ // When sensor or HTTP startup completes, finish initial commit because inference can now be served.
951
+ const completeInitialAgentBundleActivation = async () => {
952
+ await agentBundleLifecycle?.completeInitialActivation();
953
+ inferenceAvailability.available = true;
954
+ if (agentSocketArgv) {
955
+ audioClassifier?.resume();
956
+ imageClassifier?.resume();
957
+ }
958
+ };
777
959
  if (monitorArgv) {
778
960
  // make sure the config is set
779
961
  if (!config) {
@@ -793,7 +975,9 @@ async function ensureVlmServer(opts) {
793
975
  await configFactory.setMonitorSummaryIntervalMs(monitorSummaryIntervalArgv);
794
976
  }
795
977
  let device = new linux_device_1.LinuxDevice(config, projectId, devKeys, param.sensorType === 'microphone', enableVideo, verboseArgv, configFactory);
796
- modelMonitor = await model_monitor_1.ModelMonitor.getModelMonitor(configFactory, model);
978
+ modelMonitor = await model_monitor_1.ModelMonitor.getModelMonitor(configFactory, model, {
979
+ reportedThresholds: runner.getReportedModelThresholds(),
980
+ });
797
981
  let storageStatus = await modelMonitor?.getStorageStatus();
798
982
  if (!projectId) {
799
983
  throw new Error('No project ID found');
@@ -878,6 +1062,7 @@ async function ensureVlmServer(opts) {
878
1062
  // pause features streaming
879
1063
  imageClassifier?.pause();
880
1064
  audioClassifier?.pause();
1065
+ await modelMonitor?.flushMetrics();
881
1066
  // load the new model
882
1067
  model = await runner.init(modelFile);
883
1068
  if (model.modelParameters.model_type === 'classification' &&
@@ -885,17 +1070,23 @@ async function ensureVlmServer(opts) {
885
1070
  model.modelParameters.thresholds?.push(CLASSIFIER_THRESHOLD);
886
1071
  }
887
1072
  await setThresholdsFromArgv(runner, model);
1073
+ if (modelMonitor) {
1074
+ await configFactory.setDeploymentVersion(model.project.deploy_version);
1075
+ await modelMonitor.replaceModel(configFactory, model, {
1076
+ reportedThresholds: runner.getReportedModelThresholds(),
1077
+ });
1078
+ }
888
1079
  console.log(RUNNER_PREFIX, 'Model updated successfully');
889
1080
  // resume (refresh the model info internally as well)
890
1081
  if (model.modelParameters.sensorType === 'microphone') {
891
1082
  (0, runner_utils_1.audioClassifierHelloMsg)(model);
892
- audioClassifier?.resume();
893
1083
  await remoteMgmt?.sendModelUpdateStatus(model, true);
1084
+ audioClassifier?.resume();
894
1085
  }
895
1086
  else if (model.modelParameters.sensorType === 'camera') {
896
1087
  (0, runner_utils_1.imageClassifierHelloMsg)(model);
897
- imageClassifier?.resume();
898
1088
  await remoteMgmt?.sendModelUpdateStatus(model, true);
1089
+ imageClassifier?.resume();
899
1090
  }
900
1091
  }
901
1092
  catch (ex) {
@@ -921,6 +1112,7 @@ async function ensureVlmServer(opts) {
921
1112
  }
922
1113
  try {
923
1114
  await (0, runner_utils_1.startApiServer)({
1115
+ availability: inferenceAvailability,
924
1116
  model,
925
1117
  runner,
926
1118
  projectStudioUrl,
@@ -938,13 +1130,14 @@ async function ensureVlmServer(opts) {
938
1130
  console.log(``);
939
1131
  console.log(` edge-impulse-linux-runner --run-http-server ${runHttpServerPort + 1}`);
940
1132
  console.log(``);
941
- process.exit(1);
1133
+ throw ex;
942
1134
  }
943
1135
  throw ex;
944
1136
  }
945
1137
  console.log(RUNNER_PREFIX, '');
946
1138
  console.log(RUNNER_PREFIX, `HTTP Server now running at http://${(get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost')}:${runHttpServerPort}`);
947
1139
  console.log(RUNNER_PREFIX, '');
1140
+ await completeInitialAgentBundleActivation();
948
1141
  return;
949
1142
  }
950
1143
  if (param.sensorType === 'microphone') {
@@ -984,13 +1177,17 @@ async function ensureVlmServer(opts) {
984
1177
  catch (ex2) {
985
1178
  const ex = ex2;
986
1179
  console.warn(RUNNER_PREFIX, (ex.message || ex.toString()));
987
- process.exit(1);
1180
+ throw ex;
988
1181
  }
989
1182
  if (!agentSocketArgv) {
990
1183
  await configFactory.storeAudio(audioDeviceName);
991
1184
  }
992
1185
  console.log(RUNNER_PREFIX, 'Using microphone ' + audioDeviceName);
993
- audioClassifier = new audio_classifier_1.AudioClassifier(runner, verboseArgv);
1186
+ // Silence is valid model input in managed applications, so only interactive mode applies
1187
+ // the legacy first-frame device diagnostic.
1188
+ audioClassifier = new audio_classifier_1.AudioClassifier(runner, verboseArgv, {
1189
+ rejectSilentFirstFrame: !agentSocketArgv,
1190
+ });
994
1191
  audioClassifier.on('noAudioError', async () => {
995
1192
  console.log('');
996
1193
  console.log(RUNNER_PREFIX, 'ERR: Did not receive any audio.');
@@ -999,12 +1196,16 @@ async function ensureVlmServer(opts) {
999
1196
  console.log(' Are you running this command from a simulated shell (like in Visual Studio Code)?');
1000
1197
  console.log('* If you are on Linux and use a microphone in a webcam, you might also want');
1001
1198
  console.log(' to initialize the camera with --enable-camera');
1002
- await audioClassifier?.stop();
1003
- process.exit(1);
1199
+ await terminateRunner?.('The microphone did not provide usable audio');
1004
1200
  });
1005
1201
  await audioClassifier.start(audioDeviceName);
1006
- try {
1007
- await (0, runner_utils_1.startWebServer)({
1202
+ if (agentSocketArgv) {
1203
+ // Pause inference before exposing the live microphone, until activation commits registration.
1204
+ audioClassifier.pause();
1205
+ agentCapture?.useMicrophone(audioClassifier);
1206
+ }
1207
+ if (previewServerArgv) {
1208
+ await startPreviewServer({
1008
1209
  type: 'audio',
1009
1210
  model: model,
1010
1211
  audioClassifier: audioClassifier,
@@ -1012,27 +1213,17 @@ async function ensureVlmServer(opts) {
1012
1213
  host: previewHostArgv,
1013
1214
  port: previewPortArgv,
1014
1215
  });
1216
+ console.log('');
1217
+ console.log('Want to see live classification in your browser? ' +
1218
+ 'Go to http://' + (get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost') + ':' + previewPortArgv);
1219
+ console.log('');
1220
+ console.log('Want to use predictions in your application? ' +
1221
+ 'Open a websocket to ws://' + (get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost') + ':' + previewPortArgv);
1222
+ console.log('');
1015
1223
  }
1016
- catch (ex2) {
1017
- const ex = ex2;
1018
- if ((ex.message || ex.toString()).indexOf('EADDRINUSE') > -1) {
1019
- console.log('');
1020
- console.log(`EADDRINUSE: Could not listen on ${previewHostArgv}:${previewPortArgv}`);
1021
- console.log(`Most likely another application (for example, another instance of edge-impulse-linux-runner) is already listening on this port. You can select another port via --preview-port <port>, for example:`);
1022
- console.log(``);
1023
- console.log(` edge-impulse-linux-runner --preview-port ${previewPortArgv + 1}`);
1024
- console.log(``);
1025
- process.exit(1);
1026
- }
1027
- throw ex;
1224
+ else {
1225
+ console.log(RUNNER_PREFIX, 'Preview HTTP interface is off in agent mode (enable it with --preview-server)');
1028
1226
  }
1029
- console.log('');
1030
- console.log('Want to see live classification in your browser? ' +
1031
- 'Go to http://' + (get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost') + ':' + previewPortArgv);
1032
- console.log('');
1033
- console.log('Want to use predictions in your application? ' +
1034
- 'Open a websocket to ws://' + (get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost') + ':' + previewPortArgv);
1035
- console.log('');
1036
1227
  if (model.modelParameters.has_performance_calibration) {
1037
1228
  console.log(`Performance calibration is configured for your project. If no event is detected, all values are 0.`);
1038
1229
  console.log(``);
@@ -1155,7 +1346,7 @@ async function ensureVlmServer(opts) {
1155
1346
  }
1156
1347
  }
1157
1348
  else {
1158
- process.exit(1);
1349
+ void terminateRunner?.(`Camera capture failed: ${String(error)}`);
1159
1350
  }
1160
1351
  });
1161
1352
  let opts = camera.getLastOptions();
@@ -1164,8 +1355,13 @@ async function ensureVlmServer(opts) {
1164
1355
  }
1165
1356
  console.log(RUNNER_PREFIX, `Connected to camera "${opts.device}" (run with --clean to select another one)`);
1166
1357
  await imageClassifier.start();
1167
- try {
1168
- await (0, runner_utils_1.startWebServer)({
1358
+ if (agentSocketArgv) {
1359
+ // While inference is paused, read a source frame so registration uses the live camera dimensions.
1360
+ imageClassifier.pause();
1361
+ await agentCapture?.useCamera(imageClassifier);
1362
+ }
1363
+ if (previewServerArgv) {
1364
+ await startPreviewServer({
1169
1365
  type: 'camera',
1170
1366
  model: model,
1171
1367
  camera: camera,
@@ -1177,27 +1373,17 @@ async function ensureVlmServer(opts) {
1177
1373
  'original' :
1178
1374
  'scaled-using-impulse',
1179
1375
  });
1376
+ console.log('');
1377
+ console.log('Want to see a feed of the camera and live classification in your browser? ' +
1378
+ 'Go to http://' + (get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost') + ':' + previewPortArgv);
1379
+ console.log('');
1380
+ console.log('Want to use predictions in your application? ' +
1381
+ 'Open a websocket to ws://' + (get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost') + ':' + previewPortArgv);
1382
+ console.log('');
1180
1383
  }
1181
- catch (ex2) {
1182
- const ex = ex2;
1183
- if ((ex.message || ex.toString()).indexOf('EADDRINUSE') > -1) {
1184
- console.log('');
1185
- console.log(`EADDRINUSE: Could not listen on ${previewHostArgv}:${previewPortArgv}`);
1186
- console.log(`Most likely another application (for example, another instance of edge-impulse-linux-runner) is already listening on this port. You can select another port via --preview-port <port>, for example:`);
1187
- console.log(``);
1188
- console.log(` edge-impulse-linux-runner --preview-port ${previewPortArgv + 1}`);
1189
- console.log(``);
1190
- process.exit(1);
1191
- }
1192
- throw ex;
1384
+ else {
1385
+ console.log(RUNNER_PREFIX, 'Preview HTTP interface is off in agent mode (enable it with --preview-server)');
1193
1386
  }
1194
- console.log('');
1195
- console.log('Want to see a feed of the camera and live classification in your browser? ' +
1196
- 'Go to http://' + (get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost') + ':' + previewPortArgv);
1197
- console.log('');
1198
- console.log('Want to use predictions in your application? ' +
1199
- 'Open a websocket to ws://' + (get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost') + ':' + previewPortArgv);
1200
- console.log('');
1201
1387
  imageClassifier.on('result', async (ev, timeMs, imgAsJpg) => {
1202
1388
  // AWS Integration
1203
1389
  let awsResult;
@@ -1322,6 +1508,7 @@ async function ensureVlmServer(opts) {
1322
1508
  else {
1323
1509
  throw new Error('Invalid sensorType: ' + param.sensorType);
1324
1510
  }
1511
+ await completeInitialAgentBundleActivation();
1325
1512
  }
1326
1513
  catch (ex2) {
1327
1514
  // The signal handler owns cleanup and the successful exit code once shutdown has started.
@@ -1329,6 +1516,11 @@ async function ensureVlmServer(opts) {
1329
1516
  return;
1330
1517
  }
1331
1518
  let ex = ex2;
1519
+ agentCapture?.disable();
1520
+ agentBundleLifecycle?.failInitialBundle(ex);
1521
+ // The command handler resumes after failInitialBundle(). Give it a bounded opportunity to
1522
+ // post the operator-visible failure before this process terminates.
1523
+ await agentClient?.commands.waitForIdle(AGENT_FAILURE_RESULT_GRACE_MS);
1332
1524
  console.warn(RUNNER_PREFIX, 'Failed to run impulse', ex.message || ex.toString());
1333
1525
  if ((ex.message || ex.toString()).indexOf('libtensorflowlite_flex') > -1) {
1334
1526
  console.log('You will need to install the flex delegates ' +
@@ -1340,25 +1532,44 @@ async function ensureVlmServer(opts) {
1340
1532
  console.log(ex.stack);
1341
1533
  }
1342
1534
  }
1343
- if (audioClassifier) {
1344
- await audioClassifier.stop();
1345
- }
1346
- if (imageClassifier) {
1347
- await imageClassifier.stop();
1348
- }
1349
- if (vlmServerProcess) {
1350
- await (0, runner_utils_1.stopVlmServer)(vlmServerProcess);
1351
- }
1535
+ const cleanup = async (description, operation) => {
1536
+ try {
1537
+ await operation();
1538
+ }
1539
+ catch (cleanupError) {
1540
+ console.warn(RUNNER_PREFIX, `Failed to ${description}`, asError(cleanupError).message);
1541
+ }
1542
+ };
1543
+ if (audioClassifier)
1544
+ await cleanup('stop audio inference', () => audioClassifier.stop());
1545
+ if (imageClassifier)
1546
+ await cleanup('stop image inference', () => imageClassifier.stop());
1547
+ if (modelMonitor)
1548
+ await cleanup('stop model monitoring', () => modelMonitor.stop());
1549
+ await cleanup('stop a partially initialized model', async () => agentBundleLifecycle?.stopPendingRunner());
1550
+ if (vlmServerProcess)
1551
+ await cleanup('stop the VLM server', () => (0, runner_utils_1.stopVlmServer)(vlmServerProcess));
1552
+ if (agentClient)
1553
+ await cleanup('close the agent connection', () => agentClient.close());
1352
1554
  process.exit(1);
1353
1555
  }
1354
1556
  })();
1355
1557
  /**
1356
- * Loads the experimental workload API client only after agent-managed mode is selected, so ordinary
1357
- * runner modes do not depend on a module that is intentionally absent from some builds.
1558
+ * Loads agent-managed command and bundle support only after agent mode is selected. Ordinary runner
1559
+ * modes therefore remain independent of validators intentionally absent from some public builds.
1358
1560
  */
1359
- async function loadAgentClient() {
1561
+ async function loadAgentModules() {
1360
1562
  try {
1361
- return (await Promise.resolve().then(() => __importStar(require('../../cli-common/agent-client')))).AgentClient;
1563
+ const [agentClientModule, bundleLifecycleModule, captureModule] = await Promise.all([
1564
+ Promise.resolve().then(() => __importStar(require('../../cli-common/agent-client'))),
1565
+ Promise.resolve().then(() => __importStar(require('./agent-bundle-lifecycle'))),
1566
+ Promise.resolve().then(() => __importStar(require('./agent-capture'))),
1567
+ ]);
1568
+ return {
1569
+ AgentClient: agentClientModule.AgentClient,
1570
+ AgentBundleLifecycle: bundleLifecycleModule.AgentBundleLifecycle,
1571
+ AgentCaptureController: captureModule.AgentCaptureController,
1572
+ };
1362
1573
  }
1363
1574
  catch (ex2) {
1364
1575
  const ex = ex2;
@@ -1370,41 +1581,40 @@ async function loadAgentClient() {
1370
1581
  }
1371
1582
  /**
1372
1583
  * Builds the runner state sent to the device agent. The runner first calls this without a model so
1373
- * the agent knows the workload is alive, then calls it again with the metadata reported by the
1584
+ * the agent knows the application is alive, then calls it again with the metadata reported by the
1374
1585
  * loaded `.eim` so the agent knows which model this runner currently serves.
1375
1586
  *
1376
1587
  * @param model Metadata reported by the loaded `.eim`, or undefined for the initial registration.
1377
- * @param impulseId Studio impulse ID supplied separately because the `.eim` does not report it.
1588
+ * @param manifestModel Model identity supplied by the activated bundle manifest.
1378
1589
  */
1379
- function createAgentRegistration(model, impulseId) {
1590
+ function createAgentRegistration(model, manifestModel) {
1380
1591
  const imageReference = process.env.EI_RUNNER_IMAGE || `edge-impulse-linux-runner:${packageVersion}`;
1381
1592
  const imageDigest = process.env.EI_RUNNER_IMAGE_DIGEST;
1382
1593
  const mode = (0, agent_runner_metadata_1.agentRunnerMode)(runHttpServerPort, cameraArgv, microphoneArgv, model);
1594
+ const sensors = agentCapture?.sensors() || [];
1383
1595
  let modelRegistrations = [];
1384
1596
  if (model) {
1385
- if (!impulseId) {
1386
- throw new Error('Cannot register a loaded model with the agent without an impulse ID');
1597
+ if (!manifestModel) {
1598
+ throw new Error('Cannot register a loaded model with the agent without bundle manifest identity');
1387
1599
  }
1388
- const engine = model.modelParameters.inferencing_engine;
1389
1600
  modelRegistrations = [{
1390
- // TODO(closed-loop-demo#67): Use the bundle-local model ID from manifest.json.
1391
- id: `impulse-${impulseId}`,
1392
- projectId: model.project.id,
1601
+ id: manifestModel.id,
1602
+ projectId: manifestModel.projectId,
1393
1603
  projectName: model.project.name,
1394
1604
  projectOwner: model.project.owner,
1395
- impulseId,
1396
- deploymentVersion: model.project.deploy_version,
1397
- engine: typeof engine === 'number' ? (0, agent_runner_metadata_1.agentEngineName)(engine) : 'unknown',
1398
- modelType: model.modelParameters.model_type,
1399
- labels: model.modelParameters.labels,
1400
- thresholds: model.modelParameters.thresholds,
1605
+ impulseId: manifestModel.impulseId,
1606
+ deploymentVersion: manifestModel.deploymentVersion,
1607
+ engine: manifestModel.engine,
1608
+ modelType: manifestModel.modelType,
1609
+ labels: [...model.modelParameters.labels],
1610
+ thresholds: model.modelParameters.thresholds?.map(threshold => ({ ...threshold })),
1401
1611
  }];
1402
1612
  }
1403
1613
  return {
1404
1614
  kind: 'inference_runner',
1405
1615
  version: packageVersion,
1406
1616
  contractVersion: 1,
1407
- capabilities: ['inputPolicy'],
1617
+ capabilities: ['activateBundle', 'inputPolicy', ...(sensors.length > 0 ? ['capture'] : [])],
1408
1618
  artifact: {
1409
1619
  kind: 'containerImage',
1410
1620
  reference: imageReference,
@@ -1412,6 +1622,7 @@ function createAgentRegistration(model, impulseId) {
1412
1622
  },
1413
1623
  ...(mode ? { mode } : {}),
1414
1624
  models: modelRegistrations,
1625
+ ...(sensors.length > 0 ? { sensors } : {}),
1415
1626
  };
1416
1627
  }
1417
1628
  /**
@@ -1423,15 +1634,15 @@ function createAgentRegistration(model, impulseId) {
1423
1634
  * @param input Input consumed by the model, when the current inference mode exposes it.
1424
1635
  */
1425
1636
  async function reportAgentInference(result, input) {
1426
- if (!agentClient || !impulseIdArgv) {
1637
+ const activeModelId = agentBundleLifecycle?.activeModelId();
1638
+ if (!agentClient || !activeModelId) {
1427
1639
  return;
1428
1640
  }
1429
1641
  const event = {
1430
1642
  id: (0, uuid_1.v4)(),
1431
1643
  inferenceTimestamp: Date.now(),
1432
1644
  results: [{
1433
- // TODO(closed-loop-demo#67): Use the same bundle-local model ID as registration.
1434
- modelId: `impulse-${impulseIdArgv}`,
1645
+ modelId: activeModelId,
1435
1646
  result: result.result,
1436
1647
  timing: result.timing,
1437
1648
  ...(result.info ? { info: result.info } : {}),
@@ -1445,6 +1656,10 @@ async function reportAgentInference(result, input) {
1445
1656
  console.warn(RUNNER_PREFIX, `Failed to report inference to the device agent: ${ex.message || ex.toString()}`);
1446
1657
  }
1447
1658
  }
1659
+ /** Converts an unknown cleanup failure into an Error suitable for terminal logging. */
1660
+ function asError(error) {
1661
+ return error instanceof Error ? error : new Error(String(error));
1662
+ }
1448
1663
  function getFriendlyModelTypeName(modelType) {
1449
1664
  switch (modelType) {
1450
1665
  case 'int8':