edge-impulse-linux 1.26.0 → 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 (45) hide show
  1. package/README.md +7 -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 +244 -65
  8. package/build/cli/linux/runner.js.map +1 -1
  9. package/build/library/classifier/audio-classifier.d.ts +12 -3
  10. package/build/library/classifier/audio-classifier.js +49 -39
  11. package/build/library/classifier/audio-classifier.js.map +1 -1
  12. package/build/library/classifier/libcwrapper.d.ts +7 -1
  13. package/build/library/classifier/libcwrapper.js +10 -2
  14. package/build/library/classifier/libcwrapper.js.map +1 -1
  15. package/build/library/classifier/linux-impulse-runner.d.ts +28 -0
  16. package/build/library/classifier/linux-impulse-runner.js +253 -55
  17. package/build/library/classifier/linux-impulse-runner.js.map +1 -1
  18. package/build/library/sensors/gstreamer.js +38 -5
  19. package/build/library/sensors/gstreamer.js.map +1 -1
  20. package/build/library/sensors/recorder.js +61 -23
  21. package/build/library/sensors/recorder.js.map +1 -1
  22. package/build/sdk/studio/sdk/model/device.d.ts +9 -0
  23. package/build/sdk/studio/sdk/model/device.js.map +1 -1
  24. package/build/sdk/studio/sdk/model/deviceDeploymentEvent.d.ts +9 -0
  25. package/build/sdk/studio/sdk/model/deviceDeploymentEvent.js.map +1 -1
  26. package/build/sdk/studio/sdk/model/deviceWorkload.d.ts +12 -0
  27. package/build/sdk/studio/sdk/model/deviceWorkload.js +4 -0
  28. package/build/sdk/studio/sdk/model/deviceWorkload.js.map +1 -0
  29. package/build/sdk/studio/sdk/model/deviceWorkloadModel.d.ts +13 -0
  30. package/build/sdk/studio/sdk/model/deviceWorkloadModel.js +4 -0
  31. package/build/sdk/studio/sdk/model/deviceWorkloadModel.js.map +1 -0
  32. package/build/sdk/studio/sdk/model/inferenceHistoryAggregate.d.ts +8 -0
  33. package/build/sdk/studio/sdk/model/models.d.ts +2 -0
  34. package/build/sdk/studio/sdk/model/models.js +2 -0
  35. package/build/sdk/studio/sdk/model/models.js.map +1 -1
  36. package/build/sdk/studio/sdk/model/monitoringEventContext.d.ts +8 -0
  37. package/package.json +4 -1
  38. package/test/agent-bundle-lifecycle.test.ts +445 -0
  39. package/test/agent-client.test.ts +246 -16
  40. package/test/agent-command-processor.test.ts +194 -0
  41. package/test/agent-runner-configuration.test.ts +110 -0
  42. package/test/agent-runner-integration.test.ts +330 -0
  43. package/test/utils/agent-runner-fixtures.ts +132 -0
  44. package/test/agent-runner-metadata.test.ts +0 -31
  45. 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). ' +
@@ -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;
@@ -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) {
@@ -505,12 +533,59 @@ async function ensureVlmServer(opts) {
505
533
  process.exit(0);
506
534
  }
507
535
  if (agentSocketArgv) {
508
- const AgentClientConstructor = await loadAgentClient();
536
+ const { AgentClient: AgentClientConstructor, AgentBundleLifecycle: AgentBundleLifecycleConstructor, } = await loadAgentModules();
509
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.
510
580
  await agentClient.connect(createAgentRegistration(undefined, undefined));
581
+ preparedAgentBundle = await agentBundleLifecycle.waitForInitialBundle();
511
582
  }
512
583
  let initializedProjectState;
513
- if (modelFileArgv) {
584
+ if (preparedAgentBundle) {
585
+ modelFile = undefined;
586
+ initializedProjectState = undefined;
587
+ }
588
+ else if (modelFileArgv) {
514
589
  // if we have the model file, just use that and make it executable
515
590
  modelFile = modelFileArgv;
516
591
  await node_fs_1.default.promises.chmod(modelFile, 0o755);
@@ -685,18 +760,80 @@ async function ensureVlmServer(opts) {
685
760
  };
686
761
  }
687
762
  // 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));
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
+ });
697
834
  }
698
835
  // treat the user provided resize arguments as-if from the model
699
- if (forceResizeModeArgv) {
836
+ if (forceResizeModeArgv && !preparedAgentBundle) {
700
837
  const resizeParam = model.modelParameters.image_resize_mode;
701
838
  model.modelParameters.image_resize_mode = forceResizeModeArgv || resizeParam || 'none';
702
839
  }
@@ -752,16 +889,18 @@ async function ensureVlmServer(opts) {
752
889
  model.modelParameters.image_resize_mode = "none";
753
890
  previewOriginalResolutionArgv = true;
754
891
  }
755
- if (model.modelParameters.model_type === 'classification' &&
892
+ if (!preparedAgentBundle && model.modelParameters.model_type === 'classification' &&
756
893
  model.modelParameters.sensorType === 'camera') {
757
894
  model.modelParameters.thresholds?.push(CLASSIFIER_THRESHOLD);
758
895
  }
759
- await setThresholdsFromArgv(runner, model);
896
+ if (!preparedAgentBundle) {
897
+ await setThresholdsFromArgv(runner, model);
898
+ }
760
899
  if (greengrassArgv && awsIOT?.isConnected() === true) {
761
900
  awsIOT.initModelInfo(model.project.name, "v" + model.project.deploy_version, model.modelParameters);
762
901
  }
763
902
  // if downloaded? then store...
764
- if (!modelFileArgv && modelPath) {
903
+ if (!agentSocketArgv && !modelFileArgv && modelPath && modelFile) {
765
904
  let file = modelPath.getModelPath(model.project.deploy_version);
766
905
  if (file !== modelFile) {
767
906
  await node_fs_1.default.promises.mkdir(node_path_1.default.dirname(file), { recursive: true });
@@ -774,6 +913,15 @@ async function ensureVlmServer(opts) {
774
913
  await configFactory.setDeploymentVersion(model.project.deploy_version);
775
914
  }
776
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
+ };
777
925
  if (monitorArgv) {
778
926
  // make sure the config is set
779
927
  if (!config) {
@@ -921,6 +1069,7 @@ async function ensureVlmServer(opts) {
921
1069
  }
922
1070
  try {
923
1071
  await (0, runner_utils_1.startApiServer)({
1072
+ availability: inferenceAvailability,
924
1073
  model,
925
1074
  runner,
926
1075
  projectStudioUrl,
@@ -938,13 +1087,14 @@ async function ensureVlmServer(opts) {
938
1087
  console.log(``);
939
1088
  console.log(` edge-impulse-linux-runner --run-http-server ${runHttpServerPort + 1}`);
940
1089
  console.log(``);
941
- process.exit(1);
1090
+ throw ex;
942
1091
  }
943
1092
  throw ex;
944
1093
  }
945
1094
  console.log(RUNNER_PREFIX, '');
946
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}`);
947
1096
  console.log(RUNNER_PREFIX, '');
1097
+ await completeInitialAgentBundleActivation();
948
1098
  return;
949
1099
  }
950
1100
  if (param.sensorType === 'microphone') {
@@ -984,13 +1134,17 @@ async function ensureVlmServer(opts) {
984
1134
  catch (ex2) {
985
1135
  const ex = ex2;
986
1136
  console.warn(RUNNER_PREFIX, (ex.message || ex.toString()));
987
- process.exit(1);
1137
+ throw ex;
988
1138
  }
989
1139
  if (!agentSocketArgv) {
990
1140
  await configFactory.storeAudio(audioDeviceName);
991
1141
  }
992
1142
  console.log(RUNNER_PREFIX, 'Using microphone ' + audioDeviceName);
993
- 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
+ });
994
1148
  audioClassifier.on('noAudioError', async () => {
995
1149
  console.log('');
996
1150
  console.log(RUNNER_PREFIX, 'ERR: Did not receive any audio.');
@@ -999,10 +1153,11 @@ async function ensureVlmServer(opts) {
999
1153
  console.log(' Are you running this command from a simulated shell (like in Visual Studio Code)?');
1000
1154
  console.log('* If you are on Linux and use a microphone in a webcam, you might also want');
1001
1155
  console.log(' to initialize the camera with --enable-camera');
1002
- await audioClassifier?.stop();
1003
- process.exit(1);
1156
+ await terminateRunner?.('The microphone did not provide usable audio');
1004
1157
  });
1005
1158
  await audioClassifier.start(audioDeviceName);
1159
+ if (agentSocketArgv)
1160
+ audioClassifier.pause();
1006
1161
  try {
1007
1162
  await (0, runner_utils_1.startWebServer)({
1008
1163
  type: 'audio',
@@ -1022,7 +1177,7 @@ async function ensureVlmServer(opts) {
1022
1177
  console.log(``);
1023
1178
  console.log(` edge-impulse-linux-runner --preview-port ${previewPortArgv + 1}`);
1024
1179
  console.log(``);
1025
- process.exit(1);
1180
+ throw ex;
1026
1181
  }
1027
1182
  throw ex;
1028
1183
  }
@@ -1155,7 +1310,7 @@ async function ensureVlmServer(opts) {
1155
1310
  }
1156
1311
  }
1157
1312
  else {
1158
- process.exit(1);
1313
+ void terminateRunner?.(`Camera capture failed: ${String(error)}`);
1159
1314
  }
1160
1315
  });
1161
1316
  let opts = camera.getLastOptions();
@@ -1164,6 +1319,8 @@ async function ensureVlmServer(opts) {
1164
1319
  }
1165
1320
  console.log(RUNNER_PREFIX, `Connected to camera "${opts.device}" (run with --clean to select another one)`);
1166
1321
  await imageClassifier.start();
1322
+ if (agentSocketArgv)
1323
+ imageClassifier.pause();
1167
1324
  try {
1168
1325
  await (0, runner_utils_1.startWebServer)({
1169
1326
  type: 'camera',
@@ -1187,7 +1344,7 @@ async function ensureVlmServer(opts) {
1187
1344
  console.log(``);
1188
1345
  console.log(` edge-impulse-linux-runner --preview-port ${previewPortArgv + 1}`);
1189
1346
  console.log(``);
1190
- process.exit(1);
1347
+ throw ex;
1191
1348
  }
1192
1349
  throw ex;
1193
1350
  }
@@ -1322,6 +1479,7 @@ async function ensureVlmServer(opts) {
1322
1479
  else {
1323
1480
  throw new Error('Invalid sensorType: ' + param.sensorType);
1324
1481
  }
1482
+ await completeInitialAgentBundleActivation();
1325
1483
  }
1326
1484
  catch (ex2) {
1327
1485
  // The signal handler owns cleanup and the successful exit code once shutdown has started.
@@ -1329,6 +1487,10 @@ async function ensureVlmServer(opts) {
1329
1487
  return;
1330
1488
  }
1331
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);
1332
1494
  console.warn(RUNNER_PREFIX, 'Failed to run impulse', ex.message || ex.toString());
1333
1495
  if ((ex.message || ex.toString()).indexOf('libtensorflowlite_flex') > -1) {
1334
1496
  console.log('You will need to install the flex delegates ' +
@@ -1340,25 +1502,40 @@ async function ensureVlmServer(opts) {
1340
1502
  console.log(ex.stack);
1341
1503
  }
1342
1504
  }
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
- }
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());
1352
1522
  process.exit(1);
1353
1523
  }
1354
1524
  })();
1355
1525
  /**
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.
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.
1358
1528
  */
1359
- async function loadAgentClient() {
1529
+ async function loadAgentModules() {
1360
1530
  try {
1361
- 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
+ };
1362
1539
  }
1363
1540
  catch (ex2) {
1364
1541
  const ex = ex2;
@@ -1374,37 +1551,35 @@ async function loadAgentClient() {
1374
1551
  * loaded `.eim` so the agent knows which model this runner currently serves.
1375
1552
  *
1376
1553
  * @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.
1554
+ * @param manifestModel Model identity supplied by the activated bundle manifest.
1378
1555
  */
1379
- function createAgentRegistration(model, impulseId) {
1556
+ function createAgentRegistration(model, manifestModel) {
1380
1557
  const imageReference = process.env.EI_RUNNER_IMAGE || `edge-impulse-linux-runner:${packageVersion}`;
1381
1558
  const imageDigest = process.env.EI_RUNNER_IMAGE_DIGEST;
1382
1559
  const mode = (0, agent_runner_metadata_1.agentRunnerMode)(runHttpServerPort, cameraArgv, microphoneArgv, model);
1383
1560
  let modelRegistrations = [];
1384
1561
  if (model) {
1385
- if (!impulseId) {
1386
- 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');
1387
1564
  }
1388
- const engine = model.modelParameters.inferencing_engine;
1389
1565
  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,
1566
+ id: manifestModel.id,
1567
+ projectId: manifestModel.projectId,
1393
1568
  projectName: model.project.name,
1394
1569
  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,
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 })),
1401
1576
  }];
1402
1577
  }
1403
1578
  return {
1404
1579
  kind: 'inference_runner',
1405
1580
  version: packageVersion,
1406
1581
  contractVersion: 1,
1407
- capabilities: ['inputPolicy'],
1582
+ capabilities: ['activateBundle', 'inputPolicy'],
1408
1583
  artifact: {
1409
1584
  kind: 'containerImage',
1410
1585
  reference: imageReference,
@@ -1423,15 +1598,15 @@ function createAgentRegistration(model, impulseId) {
1423
1598
  * @param input Input consumed by the model, when the current inference mode exposes it.
1424
1599
  */
1425
1600
  async function reportAgentInference(result, input) {
1426
- if (!agentClient || !impulseIdArgv) {
1601
+ const activeModelId = agentBundleLifecycle?.activeModelId();
1602
+ if (!agentClient || !activeModelId) {
1427
1603
  return;
1428
1604
  }
1429
1605
  const event = {
1430
1606
  id: (0, uuid_1.v4)(),
1431
1607
  inferenceTimestamp: Date.now(),
1432
1608
  results: [{
1433
- // TODO(closed-loop-demo#67): Use the same bundle-local model ID as registration.
1434
- modelId: `impulse-${impulseIdArgv}`,
1609
+ modelId: activeModelId,
1435
1610
  result: result.result,
1436
1611
  timing: result.timing,
1437
1612
  ...(result.info ? { info: result.info } : {}),
@@ -1445,6 +1620,10 @@ async function reportAgentInference(result, input) {
1445
1620
  console.warn(RUNNER_PREFIX, `Failed to report inference to the device agent: ${ex.message || ex.toString()}`);
1446
1621
  }
1447
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
+ }
1448
1627
  function getFriendlyModelTypeName(modelType) {
1449
1628
  switch (modelType) {
1450
1629
  case 'int8':