edge-impulse-linux 1.25.4 → 1.26.1

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 (66) hide show
  1. package/README.md +17 -3
  2. package/build/cli/linux/runner-downloader.js +24 -1
  3. package/build/cli/linux/runner-downloader.js.map +1 -1
  4. package/build/cli/linux/runner-utils.d.ts +5 -0
  5. package/build/cli/linux/runner-utils.js +6 -1
  6. package/build/cli/linux/runner-utils.js.map +1 -1
  7. package/build/cli/linux/runner.js +254 -73
  8. package/build/cli/linux/runner.js.map +1 -1
  9. package/build/cli-common/model-monitor.d.ts +13 -0
  10. package/build/cli-common/model-monitor.js +68 -8
  11. package/build/cli-common/model-monitor.js.map +1 -1
  12. package/build/cli-common/remote-mgmt-service.d.ts +1 -0
  13. package/build/cli-common/remote-mgmt-service.js +31 -16
  14. package/build/cli-common/remote-mgmt-service.js.map +1 -1
  15. package/build/library/classifier/audio-classifier.d.ts +12 -3
  16. package/build/library/classifier/audio-classifier.js +49 -39
  17. package/build/library/classifier/audio-classifier.js.map +1 -1
  18. package/build/library/classifier/libcwrapper.d.ts +7 -1
  19. package/build/library/classifier/libcwrapper.js +10 -2
  20. package/build/library/classifier/libcwrapper.js.map +1 -1
  21. package/build/library/classifier/linux-impulse-runner.d.ts +28 -0
  22. package/build/library/classifier/linux-impulse-runner.js +253 -55
  23. package/build/library/classifier/linux-impulse-runner.js.map +1 -1
  24. package/build/library/sensors/gstreamer.js +38 -5
  25. package/build/library/sensors/gstreamer.js.map +1 -1
  26. package/build/library/sensors/recorder.js +61 -23
  27. package/build/library/sensors/recorder.js.map +1 -1
  28. package/build/sdk/studio/sdk/model/device.d.ts +9 -0
  29. package/build/sdk/studio/sdk/model/device.js.map +1 -1
  30. package/build/sdk/studio/sdk/model/deviceDeploymentEvent.d.ts +9 -0
  31. package/build/sdk/studio/sdk/model/deviceDeploymentEvent.js.map +1 -1
  32. package/build/sdk/studio/sdk/model/deviceWorkload.d.ts +12 -0
  33. package/build/sdk/studio/sdk/model/deviceWorkload.js +4 -0
  34. package/build/sdk/studio/sdk/model/deviceWorkload.js.map +1 -0
  35. package/build/sdk/studio/sdk/model/deviceWorkloadModel.d.ts +13 -0
  36. package/build/sdk/studio/sdk/model/deviceWorkloadModel.js +4 -0
  37. package/build/sdk/studio/sdk/model/deviceWorkloadModel.js.map +1 -0
  38. package/build/sdk/studio/sdk/model/impulseType.d.ts +4 -2
  39. package/build/sdk/studio/sdk/model/impulseType.js +1 -1
  40. package/build/sdk/studio/sdk/model/impulseType.js.map +1 -1
  41. package/build/sdk/studio/sdk/model/inferenceHistoryAggregate.d.ts +8 -0
  42. package/build/sdk/studio/sdk/model/learnBlock.d.ts +2 -1
  43. package/build/sdk/studio/sdk/model/learnBlockType.d.ts +2 -3
  44. package/build/sdk/studio/sdk/model/learnBlockType.js +1 -1
  45. package/build/sdk/studio/sdk/model/learnBlockType.js.map +1 -1
  46. package/build/sdk/studio/sdk/model/models.d.ts +2 -0
  47. package/build/sdk/studio/sdk/model/models.js +2 -0
  48. package/build/sdk/studio/sdk/model/models.js.map +1 -1
  49. package/build/sdk/studio/sdk/model/monitoringEventContext.d.ts +8 -0
  50. package/build/sdk/studio/sdk/model/monitoringEventEvaluationConfig.d.ts +4 -2
  51. package/build/sdk/studio/sdk/model/monitoringEventEvaluationConfig.js +1 -1
  52. package/build/sdk/studio/sdk/model/monitoringEventEvaluationConfig.js.map +1 -1
  53. package/build/sdk/studio/sdk/model/organizationTransferLearningOperatesOn.d.ts +1 -1
  54. package/build/sdk/studio/sdk/model/organizationTransferLearningOperatesOn.js +1 -1
  55. package/build/sdk/studio/sdk/model/organizationTransferLearningOperatesOn.js.map +1 -1
  56. package/package.json +4 -1
  57. package/test/agent-bundle-lifecycle.test.ts +445 -0
  58. package/test/agent-client.test.ts +246 -16
  59. package/test/agent-command-processor.test.ts +194 -0
  60. package/test/agent-runner-configuration.test.ts +110 -0
  61. package/test/agent-runner-integration.test.ts +330 -0
  62. package/test/model-monitor.test.ts +121 -0
  63. package/test/monitoring-policy-protocol.test.ts +62 -0
  64. package/test/utils/agent-runner-fixtures.ts +132 -0
  65. package/test/agent-runner-metadata.test.ts +0 -31
  66. package/test/sensor-selection.test.ts +0 -26
@@ -53,12 +53,26 @@ 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 terminateRunner;
61
68
  let vlmServerProcess = null;
69
+ /** Requests terminal agent-mode shutdown without returning to the command result path. */
70
+ async function restartForBundleActivation() {
71
+ if (!terminateRunner) {
72
+ throw new Error('Cannot restart for bundle activation before serving has started');
73
+ }
74
+ return terminateRunner('A different bundle is ready for activation', PLANNED_RESTART_EXIT_CODE);
75
+ }
62
76
  // total inference count
63
77
  let totalInferenceCount = 0;
64
78
  const packageVersion = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(__dirname, '..', '..', '..', 'package.json'), 'utf-8')).version;
@@ -66,7 +80,7 @@ commander_1.default
66
80
  .description('Edge Impulse Linux runner ' + packageVersion)
67
81
  .version(packageVersion)
68
82
  .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')
83
+ 'if not provided the model will be fetched from Edge Impulse. Cannot be used in agent mode')
70
84
  .option('--api-key <key>', 'API key to authenticate with Edge Impulse (overrides current credentials)')
71
85
  .option('--agent <socket>', 'Report to the Edge Impulse device agent over this Unix socket. Also reads EI_AGENT_SOCKET')
72
86
  .option('--download <file>', 'Just download the model and store it on the file system')
@@ -76,7 +90,7 @@ commander_1.default
76
90
  .option('--force-variant <variant>', 'Do not autodetect the model variant, but set it by hand (e.g. "int8")')
77
91
  .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
92
  .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')
93
+ .option('--impulse-id <impulseId>', 'Select the impulse ID (if you have multiple impulses). Cannot be used in agent mode')
80
94
  .option('--run-http-server <port>', 'Do not run using a sensor, but instead expose an API server at the specified port. ' +
81
95
  'Agent mode also reads EI_RUNNER_HTTP_PORT')
82
96
  .option('--preview-port <port>', 'Port to use to render the preview HTTP interface (default: 4912) (ignored when running with --run-http-server). ' +
@@ -86,7 +100,7 @@ commander_1.default
86
100
  .option('--preview-original-resolution', 'If set, does not resize the preview image to the impulse resolution')
87
101
  .option('--monitor', 'Enable model monitoring', false)
88
102
  .option('--monitor-max-storage-size <size>', 'The maximum storage size to be used for model monitoring, in MB. Defaults to 250.')
89
- .option('--monitor-summary-interval-ms <ms>', `The time interval (in milliseconds) for model monitoring summaries. Defaults to ${model_monitor_1.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS}.`)
103
+ .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}.`)
90
104
  .option('--clean', 'Clear credentials')
91
105
  .option('--silent', `Run in silent mode, don't prompt for credentials`)
92
106
  .option('--quantized', 'Download int8 quantized neural networks, rather than the float32 neural networks. ' +
@@ -137,16 +151,17 @@ const enableGpuArgv = !!commander_1.default.enableGpu;
137
151
  const apiKeyArgv = commander_1.default.apiKey;
138
152
  const agentSocketArgv = commander_1.default.agent || process.env.EI_AGENT_SOCKET;
139
153
  const greengrassArgv = !!commander_1.default.greengrass;
140
- const modelFileArgv = commander_1.default.modelFile ||
141
- (agentSocketArgv ? process.env.EI_MODEL_FILE : undefined);
154
+ const agentModelFileArgv = commander_1.default.modelFile || process.env.EI_MODEL_FILE;
155
+ const modelFileArgv = agentSocketArgv ? undefined : commander_1.default.modelFile;
142
156
  const downloadArgv = commander_1.default.download;
143
- const forceTargetArgv = commander_1.default.forceTarget;
157
+ const forceTargetArgv = commander_1.default.forceTarget ||
158
+ (agentSocketArgv ? process.env.EI_RUNNER_TARGET : undefined);
144
159
  const forceEngineArgv = commander_1.default.forceEngine;
145
160
  const forceVariantArgv = commander_1.default.forceVariant;
146
161
  const forceResizeModeArgv = commander_1.default.forceResizeMode;
147
162
  const forceCameraResolutionArgv = commander_1.default.forceCameraResolution;
148
- const impulseIdArgvStr = commander_1.default.impulseId ||
149
- (agentSocketArgv ? process.env.EI_IMPULSE_ID : undefined);
163
+ const agentImpulseIdArgvStr = commander_1.default.impulseId || process.env.EI_IMPULSE_ID;
164
+ const impulseIdArgvStr = agentSocketArgv ? undefined : commander_1.default.impulseId;
150
165
  const impulseIdArgv = impulseIdArgvStr && !isNaN(Number(impulseIdArgvStr)) ? Number(impulseIdArgvStr) : undefined;
151
166
  const monitorArgv = !!commander_1.default.monitor;
152
167
  const monitorMaxStorageSizeStr = commander_1.default.monitorMaxStorageSize;
@@ -154,7 +169,7 @@ const monitorMaxStorageSizeArgv = monitorMaxStorageSizeStr && !isNaN(Number(moni
154
169
  ? Number(monitorMaxStorageSizeStr)
155
170
  : undefined;
156
171
  const monitorSummaryIntervalStr = commander_1.default.monitorSummaryIntervalMs;
157
- const monitorSummaryIntervalArgv = monitorSummaryIntervalStr && !isNaN(Number(monitorSummaryIntervalStr))
172
+ const monitorSummaryIntervalArgv = monitorSummaryIntervalStr !== undefined
158
173
  ? Number(monitorSummaryIntervalStr)
159
174
  : undefined;
160
175
  const listTargetsArgv = !!commander_1.default.listTargets;
@@ -191,6 +206,10 @@ const experimentalGstPreferJpegArgv = !!commander_1.default.experimentalGstPrefe
191
206
  let modeArgv = (commander_1.default.mode ||
192
207
  (agentSocketArgv ? process.env.EI_RUNNER_MODE : undefined));
193
208
  const fakeCameraArgv = commander_1.default.fakeCamera;
209
+ const agentBundlePrepareTimeoutValue = agentSocketArgv ?
210
+ process.env.EI_AGENT_BUNDLE_PREPARE_TIMEOUT_MS : undefined;
211
+ const agentBundlePrepareTimeoutMs = agentBundlePrepareTimeoutValue ?
212
+ Number(agentBundlePrepareTimeoutValue) : DEFAULT_AGENT_BUNDLE_PREPARE_TIMEOUT_MS;
194
213
  if (modeArgv === 'http-server' && typeof runHttpServerPort === 'undefined') {
195
214
  runHttpServerPort = 1337;
196
215
  }
@@ -250,6 +269,7 @@ const onSignal = async () => {
250
269
  if (imageClassifier) {
251
270
  await imageClassifier.stop();
252
271
  }
272
+ await agentBundleLifecycle?.stopPendingRunner();
253
273
  if (profiling) {
254
274
  profiling.printSummary();
255
275
  }
@@ -329,6 +349,8 @@ async function ensureVlmServer(opts) {
329
349
  }
330
350
  // eslint-disable-next-line @typescript-eslint/no-floating-promises
331
351
  (async () => {
352
+ // Retained outside the startup try block so failure handling can restore an empty registration.
353
+ let preparedAgentBundle;
332
354
  try {
333
355
  let modelFile;
334
356
  let remoteMgmt;
@@ -366,6 +388,8 @@ async function ensureVlmServer(opts) {
366
388
  throw new Error(`Invalid runner mode "${modeArgv}", expected "streaming" or "http-server"`);
367
389
  }
368
390
  if (agentSocketArgv) {
391
+ // Agent deployments start empty and receive their model through activateBundle. The
392
+ // reference Compose migration to this invocation is tracked by #16494.
369
393
  if (apiKeyArgv) {
370
394
  throw new Error('Cannot combine --agent and --api-key');
371
395
  }
@@ -375,11 +399,15 @@ async function ensureVlmServer(opts) {
375
399
  if (greengrassArgv) {
376
400
  throw new Error('Cannot combine --agent and --greengrass');
377
401
  }
378
- if (!modelFileArgv) {
379
- throw new Error('--agent currently requires --model-file until inference bundle activation is implemented');
402
+ if (agentModelFileArgv) {
403
+ throw new Error('Cannot combine --agent and --model-file or EI_MODEL_FILE; models are selected by activateBundle');
380
404
  }
381
- if (!impulseIdArgv) {
382
- throw new Error('--agent with --model-file requires --impulse-id because the .eim does not report its impulse ID');
405
+ if (agentImpulseIdArgvStr) {
406
+ throw new Error('Cannot combine --agent and --impulse-id or EI_IMPULSE_ID; model identity comes from the bundle manifest');
407
+ }
408
+ if (!Number.isInteger(agentBundlePrepareTimeoutMs) || agentBundlePrepareTimeoutMs <= 0) {
409
+ throw new Error(`Invalid EI_AGENT_BUNDLE_PREPARE_TIMEOUT_MS "${agentBundlePrepareTimeoutValue}", ` +
410
+ 'expected a positive integer');
383
411
  }
384
412
  }
385
413
  if (forceVariantArgv && quantizedArgv) {
@@ -396,13 +424,15 @@ async function ensureVlmServer(opts) {
396
424
  if (monitorMaxStorageSizeArgv && (isNaN(monitorMaxStorageSizeArgv) || monitorMaxStorageSizeArgv <= 0)) {
397
425
  throw new Error('Invalid value for --monitor-max-storage-size (was: "' + monitorMaxStorageSizeArgv + '")');
398
426
  }
399
- if (monitorSummaryIntervalArgv && !monitorArgv) {
427
+ if (monitorSummaryIntervalArgv !== undefined && !monitorArgv) {
400
428
  throw new Error('Cannot use --monitor-summary-interval-ms without --monitor');
401
429
  }
402
- if (monitorSummaryIntervalArgv &&
403
- (isNaN(monitorSummaryIntervalArgv) || monitorSummaryIntervalArgv < model_monitor_1.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS)) {
404
- throw new Error(`Invalid value for --monitor-summary-interval-ms (was: "${monitorSummaryIntervalArgv}"). ` +
405
- `Minimum value is ${model_monitor_1.DEFAULT_MONITOR_SUMMARY_INTERVAL_MS} (1 minute).`);
430
+ if (monitorSummaryIntervalArgv !== undefined &&
431
+ (!Number.isFinite(monitorSummaryIntervalArgv) ||
432
+ monitorSummaryIntervalArgv < model_monitor_1.MIN_MONITOR_SUMMARY_INTERVAL_MS)) {
433
+ throw new Error(`Invalid value for --monitor-summary-interval-ms (was: "${monitorSummaryIntervalStr}"). ` +
434
+ `Minimum value is ${model_monitor_1.MIN_MONITOR_SUMMARY_INTERVAL_MS} ` +
435
+ `(${model_monitor_1.MIN_MONITOR_SUMMARY_INTERVAL_MS / 1000} seconds).`);
406
436
  }
407
437
  if (forceResizeModeArgv) {
408
438
  if (forceResizeModeArgv !== 'squash' && forceResizeModeArgv !== 'fit-longest' && forceResizeModeArgv !== 'fit-shortest') {
@@ -503,12 +533,59 @@ async function ensureVlmServer(opts) {
503
533
  process.exit(0);
504
534
  }
505
535
  if (agentSocketArgv) {
506
- const AgentClientConstructor = await loadAgentClient();
536
+ const { AgentClient: AgentClientConstructor, AgentBundleLifecycle: AgentBundleLifecycleConstructor, } = await loadAgentModules();
507
537
  agentClient = new AgentClientConstructor(agentSocketArgv);
538
+ agentBundleLifecycle = new AgentBundleLifecycleConstructor({
539
+ agentClient,
540
+ policy: {
541
+ // When lifecycle identity changes, include both manifest identity and initialized metadata.
542
+ createRegistration(bundle) {
543
+ return createAgentRegistration(bundle?.registrationModel, bundle?.manifestModel);
544
+ },
545
+ // Before activation, apply CLI thresholds and resize overrides to runtime metadata only.
546
+ async configure(candidate) {
547
+ if (forceResizeModeArgv) {
548
+ candidate.model.modelParameters.image_resize_mode = forceResizeModeArgv;
549
+ }
550
+ if (candidate.model.modelParameters.model_type === 'classification' &&
551
+ candidate.model.modelParameters.sensorType === 'camera') {
552
+ candidate.model.modelParameters.thresholds?.push(CLASSIFIER_THRESHOLD);
553
+ }
554
+ await setThresholdsFromArgv(candidate.runner, candidate.model);
555
+ },
556
+ // Before initial preparation, derive the configured input mode for runtime validation.
557
+ servingMode() {
558
+ return (0, agent_runner_metadata_1.agentRunnerMode)(runHttpServerPort, cameraArgv, microphoneArgv, undefined);
559
+ },
560
+ },
561
+ validateOptions: {
562
+ forceTarget: forceTargetArgv,
563
+ packageVersion,
564
+ },
565
+ prepareOptions: {
566
+ shmBehavior: shmBehaviorArgv,
567
+ startupTimeoutMs: agentBundlePrepareTimeoutMs,
568
+ verbose: verboseArgv,
569
+ },
570
+ });
571
+ // On activation delivery, restart after static validation so a fresh process owns the new model.
572
+ agentClient.commands.on('activateBundle', async (command) => {
573
+ const result = await agentBundleLifecycle.activateBundle(command);
574
+ if (result.kind === 'restart-required') {
575
+ await restartForBundleActivation();
576
+ }
577
+ });
578
+ // Agent mode deliberately starts without a model. The first activateBundle command is
579
+ // held open by the lifecycle until the selected sensor or HTTP server is ready to use it.
508
580
  await agentClient.connect(createAgentRegistration(undefined, undefined));
581
+ preparedAgentBundle = await agentBundleLifecycle.waitForInitialBundle();
509
582
  }
510
583
  let initializedProjectState;
511
- if (modelFileArgv) {
584
+ if (preparedAgentBundle) {
585
+ modelFile = undefined;
586
+ initializedProjectState = undefined;
587
+ }
588
+ else if (modelFileArgv) {
512
589
  // if we have the model file, just use that and make it executable
513
590
  modelFile = modelFileArgv;
514
591
  await node_fs_1.default.promises.chmod(modelFile, 0o755);
@@ -683,18 +760,80 @@ async function ensureVlmServer(opts) {
683
760
  };
684
761
  }
685
762
  // create the runner and init (get info from model file)
686
- runner = new linux_impulse_runner_1.LinuxImpulseRunner(modelFile, {
687
- verbose: verboseArgv,
688
- shmBehavior: shmBehaviorArgv,
689
- });
690
- model = await runner.init();
691
- if (agentClient) {
692
- // Register before applying runner-only threshold defaults or command-line overrides. The agent receives
693
- // the model metadata exactly as the .eim reported it.
694
- await agentClient.updateRegistration(createAgentRegistration(model, impulseIdArgv));
763
+ if (preparedAgentBundle) {
764
+ runner = preparedAgentBundle.runner;
765
+ model = preparedAgentBundle.model;
766
+ }
767
+ else {
768
+ if (!modelFile) {
769
+ throw new Error('No model file available');
770
+ }
771
+ runner = new linux_impulse_runner_1.LinuxImpulseRunner(modelFile, {
772
+ verbose: verboseArgv,
773
+ shmBehavior: shmBehaviorArgv,
774
+ });
775
+ model = await runner.init();
776
+ }
777
+ const inferenceAvailability = {
778
+ // Agent mode serves only after the agent accepts the model registration.
779
+ available: !agentSocketArgv,
780
+ };
781
+ let terminalShutdown;
782
+ terminateRunner = (reason, exitCode = 1) => {
783
+ if (terminalShutdown)
784
+ return terminalShutdown;
785
+ terminalShutdown = (async () => {
786
+ inferenceAvailability.available = false;
787
+ const recovery = agentSocketArgv ? ' so the process supervisor can restart the runner' : '';
788
+ console.log(RUNNER_PREFIX, `${reason}; stopping${recovery}`);
789
+ const forceExit = setTimeout(() => {
790
+ console.warn(RUNNER_PREFIX, `Shutdown did not complete within ${TERMINAL_SHUTDOWN_TIMEOUT_MS} ms; exiting`);
791
+ if (vlmServerProcess)
792
+ (0, runner_utils_1.stopVlmServer)(vlmServerProcess);
793
+ process.exit(exitCode);
794
+ }, TERMINAL_SHUTDOWN_TIMEOUT_MS);
795
+ const cleanup = async (description, operation) => {
796
+ try {
797
+ await operation();
798
+ }
799
+ catch (cleanupError) {
800
+ console.warn(RUNNER_PREFIX, `Failed to ${description}`, asError(cleanupError).message);
801
+ }
802
+ };
803
+ try {
804
+ if (audioClassifier) {
805
+ await cleanup('stop audio inference', () => audioClassifier.stop());
806
+ }
807
+ else if (imageClassifier) {
808
+ await cleanup('stop image inference', () => imageClassifier.stop());
809
+ }
810
+ else {
811
+ await cleanup('stop model inference', () => runner.stop());
812
+ }
813
+ if (vlmServerProcess) {
814
+ await cleanup('stop the VLM server', () => (0, runner_utils_1.stopVlmServer)(vlmServerProcess));
815
+ }
816
+ // close() destroys the command stream and gives started event requests a bounded flush.
817
+ await cleanup('close the agent connection', async () => agentClient?.close());
818
+ }
819
+ finally {
820
+ clearTimeout(forceExit);
821
+ }
822
+ process.exit(exitCode);
823
+ })();
824
+ return terminalShutdown;
825
+ };
826
+ if (agentSocketArgv) {
827
+ // Agent mode exits for supervisor recovery when its serving model cannot recover in place.
828
+ runner.on('unexpectedTermination', termination => {
829
+ const detail = termination.signal ?
830
+ `signal ${termination.signal}` : termination.code !== null ?
831
+ `exit code ${termination.code}` : 'serving socket closed';
832
+ void terminateRunner?.(`The serving .eim terminated unexpectedly (${detail})`);
833
+ });
695
834
  }
696
835
  // treat the user provided resize arguments as-if from the model
697
- if (forceResizeModeArgv) {
836
+ if (forceResizeModeArgv && !preparedAgentBundle) {
698
837
  const resizeParam = model.modelParameters.image_resize_mode;
699
838
  model.modelParameters.image_resize_mode = forceResizeModeArgv || resizeParam || 'none';
700
839
  }
@@ -750,16 +889,18 @@ async function ensureVlmServer(opts) {
750
889
  model.modelParameters.image_resize_mode = "none";
751
890
  previewOriginalResolutionArgv = true;
752
891
  }
753
- if (model.modelParameters.model_type === 'classification' &&
892
+ if (!preparedAgentBundle && model.modelParameters.model_type === 'classification' &&
754
893
  model.modelParameters.sensorType === 'camera') {
755
894
  model.modelParameters.thresholds?.push(CLASSIFIER_THRESHOLD);
756
895
  }
757
- await setThresholdsFromArgv(runner, model);
896
+ if (!preparedAgentBundle) {
897
+ await setThresholdsFromArgv(runner, model);
898
+ }
758
899
  if (greengrassArgv && awsIOT?.isConnected() === true) {
759
900
  awsIOT.initModelInfo(model.project.name, "v" + model.project.deploy_version, model.modelParameters);
760
901
  }
761
902
  // if downloaded? then store...
762
- if (!modelFileArgv && modelPath) {
903
+ if (!agentSocketArgv && !modelFileArgv && modelPath && modelFile) {
763
904
  let file = modelPath.getModelPath(model.project.deploy_version);
764
905
  if (file !== modelFile) {
765
906
  await node_fs_1.default.promises.mkdir(node_path_1.default.dirname(file), { recursive: true });
@@ -772,6 +913,15 @@ async function ensureVlmServer(opts) {
772
913
  await configFactory.setDeploymentVersion(model.project.deploy_version);
773
914
  }
774
915
  let param = model.modelParameters;
916
+ // When sensor or HTTP startup completes, finish initial commit because inference can now be served.
917
+ const completeInitialAgentBundleActivation = async () => {
918
+ await agentBundleLifecycle?.completeInitialActivation();
919
+ inferenceAvailability.available = true;
920
+ if (agentSocketArgv) {
921
+ audioClassifier?.resume();
922
+ imageClassifier?.resume();
923
+ }
924
+ };
775
925
  if (monitorArgv) {
776
926
  // make sure the config is set
777
927
  if (!config) {
@@ -787,7 +937,7 @@ async function ensureVlmServer(opts) {
787
937
  if (monitorMaxStorageSizeArgv) {
788
938
  await configFactory.setStorageMaxSizeMb(monitorMaxStorageSizeArgv);
789
939
  }
790
- if (monitorSummaryIntervalArgv) {
940
+ if (monitorSummaryIntervalArgv !== undefined) {
791
941
  await configFactory.setMonitorSummaryIntervalMs(monitorSummaryIntervalArgv);
792
942
  }
793
943
  let device = new linux_device_1.LinuxDevice(config, projectId, devKeys, param.sensorType === 'microphone', enableVideo, verboseArgv, configFactory);
@@ -919,6 +1069,7 @@ async function ensureVlmServer(opts) {
919
1069
  }
920
1070
  try {
921
1071
  await (0, runner_utils_1.startApiServer)({
1072
+ availability: inferenceAvailability,
922
1073
  model,
923
1074
  runner,
924
1075
  projectStudioUrl,
@@ -936,13 +1087,14 @@ async function ensureVlmServer(opts) {
936
1087
  console.log(``);
937
1088
  console.log(` edge-impulse-linux-runner --run-http-server ${runHttpServerPort + 1}`);
938
1089
  console.log(``);
939
- process.exit(1);
1090
+ throw ex;
940
1091
  }
941
1092
  throw ex;
942
1093
  }
943
1094
  console.log(RUNNER_PREFIX, '');
944
1095
  console.log(RUNNER_PREFIX, `HTTP Server now running at http://${(get_ips_1.ips.length > 0 ? get_ips_1.ips[0].address : 'localhost')}:${runHttpServerPort}`);
945
1096
  console.log(RUNNER_PREFIX, '');
1097
+ await completeInitialAgentBundleActivation();
946
1098
  return;
947
1099
  }
948
1100
  if (param.sensorType === 'microphone') {
@@ -982,13 +1134,17 @@ async function ensureVlmServer(opts) {
982
1134
  catch (ex2) {
983
1135
  const ex = ex2;
984
1136
  console.warn(RUNNER_PREFIX, (ex.message || ex.toString()));
985
- process.exit(1);
1137
+ throw ex;
986
1138
  }
987
1139
  if (!agentSocketArgv) {
988
1140
  await configFactory.storeAudio(audioDeviceName);
989
1141
  }
990
1142
  console.log(RUNNER_PREFIX, 'Using microphone ' + audioDeviceName);
991
- audioClassifier = new audio_classifier_1.AudioClassifier(runner, verboseArgv);
1143
+ // Silence is valid model input in managed workloads, so only interactive mode applies
1144
+ // the legacy first-frame device diagnostic.
1145
+ audioClassifier = new audio_classifier_1.AudioClassifier(runner, verboseArgv, {
1146
+ rejectSilentFirstFrame: !agentSocketArgv,
1147
+ });
992
1148
  audioClassifier.on('noAudioError', async () => {
993
1149
  console.log('');
994
1150
  console.log(RUNNER_PREFIX, 'ERR: Did not receive any audio.');
@@ -997,10 +1153,11 @@ async function ensureVlmServer(opts) {
997
1153
  console.log(' Are you running this command from a simulated shell (like in Visual Studio Code)?');
998
1154
  console.log('* If you are on Linux and use a microphone in a webcam, you might also want');
999
1155
  console.log(' to initialize the camera with --enable-camera');
1000
- await audioClassifier?.stop();
1001
- process.exit(1);
1156
+ await terminateRunner?.('The microphone did not provide usable audio');
1002
1157
  });
1003
1158
  await audioClassifier.start(audioDeviceName);
1159
+ if (agentSocketArgv)
1160
+ audioClassifier.pause();
1004
1161
  try {
1005
1162
  await (0, runner_utils_1.startWebServer)({
1006
1163
  type: 'audio',
@@ -1020,7 +1177,7 @@ async function ensureVlmServer(opts) {
1020
1177
  console.log(``);
1021
1178
  console.log(` edge-impulse-linux-runner --preview-port ${previewPortArgv + 1}`);
1022
1179
  console.log(``);
1023
- process.exit(1);
1180
+ throw ex;
1024
1181
  }
1025
1182
  throw ex;
1026
1183
  }
@@ -1153,7 +1310,7 @@ async function ensureVlmServer(opts) {
1153
1310
  }
1154
1311
  }
1155
1312
  else {
1156
- process.exit(1);
1313
+ void terminateRunner?.(`Camera capture failed: ${String(error)}`);
1157
1314
  }
1158
1315
  });
1159
1316
  let opts = camera.getLastOptions();
@@ -1162,6 +1319,8 @@ async function ensureVlmServer(opts) {
1162
1319
  }
1163
1320
  console.log(RUNNER_PREFIX, `Connected to camera "${opts.device}" (run with --clean to select another one)`);
1164
1321
  await imageClassifier.start();
1322
+ if (agentSocketArgv)
1323
+ imageClassifier.pause();
1165
1324
  try {
1166
1325
  await (0, runner_utils_1.startWebServer)({
1167
1326
  type: 'camera',
@@ -1185,7 +1344,7 @@ async function ensureVlmServer(opts) {
1185
1344
  console.log(``);
1186
1345
  console.log(` edge-impulse-linux-runner --preview-port ${previewPortArgv + 1}`);
1187
1346
  console.log(``);
1188
- process.exit(1);
1347
+ throw ex;
1189
1348
  }
1190
1349
  throw ex;
1191
1350
  }
@@ -1320,6 +1479,7 @@ async function ensureVlmServer(opts) {
1320
1479
  else {
1321
1480
  throw new Error('Invalid sensorType: ' + param.sensorType);
1322
1481
  }
1482
+ await completeInitialAgentBundleActivation();
1323
1483
  }
1324
1484
  catch (ex2) {
1325
1485
  // The signal handler owns cleanup and the successful exit code once shutdown has started.
@@ -1327,6 +1487,10 @@ async function ensureVlmServer(opts) {
1327
1487
  return;
1328
1488
  }
1329
1489
  let ex = ex2;
1490
+ agentBundleLifecycle?.failInitialBundle(ex);
1491
+ // The command handler resumes after failInitialBundle(). Give it a bounded opportunity to
1492
+ // post the operator-visible failure before this process terminates.
1493
+ await agentClient?.commands.waitForIdle(AGENT_FAILURE_RESULT_GRACE_MS);
1330
1494
  console.warn(RUNNER_PREFIX, 'Failed to run impulse', ex.message || ex.toString());
1331
1495
  if ((ex.message || ex.toString()).indexOf('libtensorflowlite_flex') > -1) {
1332
1496
  console.log('You will need to install the flex delegates ' +
@@ -1338,25 +1502,40 @@ async function ensureVlmServer(opts) {
1338
1502
  console.log(ex.stack);
1339
1503
  }
1340
1504
  }
1341
- if (audioClassifier) {
1342
- await audioClassifier.stop();
1343
- }
1344
- if (imageClassifier) {
1345
- await imageClassifier.stop();
1346
- }
1347
- if (vlmServerProcess) {
1348
- await (0, runner_utils_1.stopVlmServer)(vlmServerProcess);
1349
- }
1505
+ const cleanup = async (description, operation) => {
1506
+ try {
1507
+ await operation();
1508
+ }
1509
+ catch (cleanupError) {
1510
+ console.warn(RUNNER_PREFIX, `Failed to ${description}`, asError(cleanupError).message);
1511
+ }
1512
+ };
1513
+ if (audioClassifier)
1514
+ await cleanup('stop audio inference', () => audioClassifier.stop());
1515
+ if (imageClassifier)
1516
+ await cleanup('stop image inference', () => imageClassifier.stop());
1517
+ await cleanup('stop a partially initialized model', async () => agentBundleLifecycle?.stopPendingRunner());
1518
+ if (vlmServerProcess)
1519
+ await cleanup('stop the VLM server', () => (0, runner_utils_1.stopVlmServer)(vlmServerProcess));
1520
+ if (agentClient)
1521
+ await cleanup('close the agent connection', () => agentClient.close());
1350
1522
  process.exit(1);
1351
1523
  }
1352
1524
  })();
1353
1525
  /**
1354
- * Loads the experimental workload API client only after agent-managed mode is selected, so ordinary
1355
- * runner modes do not depend on a module that is intentionally absent from some builds.
1526
+ * Loads agent-managed command and bundle support only after agent mode is selected. Ordinary runner
1527
+ * modes therefore remain independent of validators intentionally absent from some public builds.
1356
1528
  */
1357
- async function loadAgentClient() {
1529
+ async function loadAgentModules() {
1358
1530
  try {
1359
- return (await Promise.resolve().then(() => __importStar(require('../../cli-common/agent-client')))).AgentClient;
1531
+ const [agentClientModule, bundleLifecycleModule] = await Promise.all([
1532
+ Promise.resolve().then(() => __importStar(require('../../cli-common/agent-client'))),
1533
+ Promise.resolve().then(() => __importStar(require('./agent-bundle-lifecycle'))),
1534
+ ]);
1535
+ return {
1536
+ AgentClient: agentClientModule.AgentClient,
1537
+ AgentBundleLifecycle: bundleLifecycleModule.AgentBundleLifecycle,
1538
+ };
1360
1539
  }
1361
1540
  catch (ex2) {
1362
1541
  const ex = ex2;
@@ -1372,37 +1551,35 @@ async function loadAgentClient() {
1372
1551
  * loaded `.eim` so the agent knows which model this runner currently serves.
1373
1552
  *
1374
1553
  * @param model Metadata reported by the loaded `.eim`, or undefined for the initial registration.
1375
- * @param impulseId Studio impulse ID supplied separately because the `.eim` does not report it.
1554
+ * @param manifestModel Model identity supplied by the activated bundle manifest.
1376
1555
  */
1377
- function createAgentRegistration(model, impulseId) {
1556
+ function createAgentRegistration(model, manifestModel) {
1378
1557
  const imageReference = process.env.EI_RUNNER_IMAGE || `edge-impulse-linux-runner:${packageVersion}`;
1379
1558
  const imageDigest = process.env.EI_RUNNER_IMAGE_DIGEST;
1380
1559
  const mode = (0, agent_runner_metadata_1.agentRunnerMode)(runHttpServerPort, cameraArgv, microphoneArgv, model);
1381
1560
  let modelRegistrations = [];
1382
1561
  if (model) {
1383
- if (!impulseId) {
1384
- throw new Error('Cannot register a loaded model with the agent without an impulse ID');
1562
+ if (!manifestModel) {
1563
+ throw new Error('Cannot register a loaded model with the agent without bundle manifest identity');
1385
1564
  }
1386
- const engine = model.modelParameters.inferencing_engine;
1387
1565
  modelRegistrations = [{
1388
- // TODO(closed-loop-demo#67): Use the bundle-local model ID from manifest.json.
1389
- id: `impulse-${impulseId}`,
1390
- projectId: model.project.id,
1566
+ id: manifestModel.id,
1567
+ projectId: manifestModel.projectId,
1391
1568
  projectName: model.project.name,
1392
1569
  projectOwner: model.project.owner,
1393
- impulseId,
1394
- deploymentVersion: model.project.deploy_version,
1395
- engine: typeof engine === 'number' ? (0, agent_runner_metadata_1.agentEngineName)(engine) : 'unknown',
1396
- modelType: model.modelParameters.model_type,
1397
- labels: model.modelParameters.labels,
1398
- thresholds: model.modelParameters.thresholds,
1570
+ impulseId: manifestModel.impulseId,
1571
+ deploymentVersion: manifestModel.deploymentVersion,
1572
+ engine: manifestModel.engine,
1573
+ modelType: manifestModel.modelType,
1574
+ labels: [...model.modelParameters.labels],
1575
+ thresholds: model.modelParameters.thresholds?.map(threshold => ({ ...threshold })),
1399
1576
  }];
1400
1577
  }
1401
1578
  return {
1402
1579
  kind: 'inference_runner',
1403
1580
  version: packageVersion,
1404
1581
  contractVersion: 1,
1405
- capabilities: ['inputPolicy'],
1582
+ capabilities: ['activateBundle', 'inputPolicy'],
1406
1583
  artifact: {
1407
1584
  kind: 'containerImage',
1408
1585
  reference: imageReference,
@@ -1421,15 +1598,15 @@ function createAgentRegistration(model, impulseId) {
1421
1598
  * @param input Input consumed by the model, when the current inference mode exposes it.
1422
1599
  */
1423
1600
  async function reportAgentInference(result, input) {
1424
- if (!agentClient || !impulseIdArgv) {
1601
+ const activeModelId = agentBundleLifecycle?.activeModelId();
1602
+ if (!agentClient || !activeModelId) {
1425
1603
  return;
1426
1604
  }
1427
1605
  const event = {
1428
1606
  id: (0, uuid_1.v4)(),
1429
1607
  inferenceTimestamp: Date.now(),
1430
1608
  results: [{
1431
- // TODO(closed-loop-demo#67): Use the same bundle-local model ID as registration.
1432
- modelId: `impulse-${impulseIdArgv}`,
1609
+ modelId: activeModelId,
1433
1610
  result: result.result,
1434
1611
  timing: result.timing,
1435
1612
  ...(result.info ? { info: result.info } : {}),
@@ -1443,6 +1620,10 @@ async function reportAgentInference(result, input) {
1443
1620
  console.warn(RUNNER_PREFIX, `Failed to report inference to the device agent: ${ex.message || ex.toString()}`);
1444
1621
  }
1445
1622
  }
1623
+ /** Converts an unknown cleanup failure into an Error suitable for terminal logging. */
1624
+ function asError(error) {
1625
+ return error instanceof Error ? error : new Error(String(error));
1626
+ }
1446
1627
  function getFriendlyModelTypeName(modelType) {
1447
1628
  switch (modelType) {
1448
1629
  case 'int8':