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
@@ -0,0 +1,194 @@
1
+ import assert from 'node:assert';
2
+ import { AgentCommandProcessor } from '../cli-common/agent-client';
3
+ import {
4
+ ActivateBundleCommand,
5
+ Command,
6
+ CommandResult,
7
+ UpdateInputPolicyCommand,
8
+ } from '../shared/device-protocol/application-contract';
9
+
10
+ type Deferred = {
11
+ promise: Promise<void>;
12
+ resolve: () => void;
13
+ };
14
+
15
+ /**
16
+ * Exercises `AgentCommandProcessor`, the serial in-process dispatcher between command delivery and
17
+ * result posting. Successful handlers run in delivery order and produce one acknowledgement each.
18
+ * Missing or failing handlers produce explicit failures, acknowledgement errors do not poison the
19
+ * queue, duplicate ownership is rejected, and redelivery reapplies the command for state recovery.
20
+ */
21
+ describe('AgentCommandProcessor', () => {
22
+ // A resolved handler produces the success result that lets the agent commit the command.
23
+ it('acknowledges a successful command', async () => {
24
+ const acknowledged: CommandResult[] = [];
25
+ const processor = processorRecording(acknowledged);
26
+ const command = activateBundleCommand('activate-1');
27
+ let delivered: Command | undefined;
28
+ processor.on('activateBundle', received => {
29
+ delivered = received;
30
+ return Promise.resolve();
31
+ });
32
+
33
+ await processor.process(command);
34
+
35
+ assert.deepStrictEqual(delivered, command);
36
+ assert.deepStrictEqual(acknowledged, [{
37
+ commandId: command.id,
38
+ type: command.type,
39
+ success: true,
40
+ }]);
41
+ });
42
+
43
+ // A handler failure becomes a command failure result so later commands can still run.
44
+ it('acknowledges a handler error as a command failure', async () => {
45
+ const acknowledged: CommandResult[] = [];
46
+ const processor = processorRecording(acknowledged);
47
+ const command = activateBundleCommand('activate-1');
48
+ processor.on('activateBundle', () => Promise.reject(new Error('bundle is incompatible')));
49
+
50
+ await processor.process(command);
51
+
52
+ assert.deepStrictEqual(acknowledged, [{
53
+ commandId: command.id,
54
+ type: command.type,
55
+ success: false,
56
+ reason: 'bundle is incompatible',
57
+ }]);
58
+ });
59
+
60
+ // An unsupported command receives an explicit failure instead of being silently accepted.
61
+ it('acknowledges a command without a registered handler as a failure', async () => {
62
+ const acknowledged: CommandResult[] = [];
63
+ const processor = processorRecording(acknowledged);
64
+ const command = updateInputPolicyCommand('policy-1');
65
+
66
+ await processor.process(command);
67
+
68
+ assert.deepStrictEqual(acknowledged, [{
69
+ commandId: command.id,
70
+ type: command.type,
71
+ success: false,
72
+ reason: 'No handler is registered for command "updateInputPolicy"',
73
+ }]);
74
+ });
75
+
76
+ // A command type has one owner so execution and result handling cannot become ambiguous.
77
+ it('rejects a second handler for the same command type', () => {
78
+ const processor = processorRecording([]);
79
+ processor.on('activateBundle', () => Promise.resolve());
80
+
81
+ assert.throws(
82
+ () => processor.on('activateBundle', () => Promise.resolve()),
83
+ /already registered for command "activateBundle"/
84
+ );
85
+ });
86
+
87
+ // The next command waits for the preceding result POST, preserving agent delivery order.
88
+ it('executes and acknowledges commands in delivery order', async () => {
89
+ const events: string[] = [];
90
+ const firstAcknowledgementStarted = deferred();
91
+ const releaseFirstAcknowledgement = deferred();
92
+ const processor = new AgentCommandProcessor(async result => {
93
+ events.push(`acknowledge:${result.commandId}`);
94
+ if (result.commandId === 'activate-1') {
95
+ firstAcknowledgementStarted.resolve();
96
+ await releaseFirstAcknowledgement.promise;
97
+ }
98
+ });
99
+ processor.on('activateBundle', command => {
100
+ events.push(`handle:${command.id}`);
101
+ return Promise.resolve();
102
+ });
103
+
104
+ const first = processor.process(activateBundleCommand('activate-1'));
105
+ await firstAcknowledgementStarted.promise;
106
+ const second = processor.process(activateBundleCommand('activate-2'));
107
+ assert.deepStrictEqual(events, [ 'handle:activate-1', 'acknowledge:activate-1' ]);
108
+
109
+ releaseFirstAcknowledgement.resolve();
110
+ await Promise.all([ first, second ]);
111
+ assert.deepStrictEqual(events, [
112
+ 'handle:activate-1',
113
+ 'acknowledge:activate-1',
114
+ 'handle:activate-2',
115
+ 'acknowledge:activate-2',
116
+ ]);
117
+ });
118
+
119
+ // A failed result POST rejects that delivery without permanently poisoning the serial queue.
120
+ it('continues processing after an acknowledgement failure', async () => {
121
+ const handled: string[] = [];
122
+ const acknowledged: string[] = [];
123
+ const processor = new AgentCommandProcessor(result => {
124
+ acknowledged.push(result.commandId);
125
+ return result.commandId === 'activate-1' ?
126
+ Promise.reject(new Error('agent unavailable')) : Promise.resolve();
127
+ });
128
+ processor.on('activateBundle', command => {
129
+ handled.push(command.id);
130
+ return Promise.resolve();
131
+ });
132
+
133
+ const first = processor.process(activateBundleCommand('activate-1'));
134
+ const second = processor.process(activateBundleCommand('activate-2'));
135
+
136
+ await assert.rejects(first, /agent unavailable/);
137
+ await second;
138
+ assert.deepStrictEqual(handled, [ 'activate-1', 'activate-2' ]);
139
+ assert.deepStrictEqual(acknowledged, [ 'activate-1', 'activate-2' ]);
140
+ });
141
+
142
+ // Redelivery reruns the idempotent handler so local state is recovered from the command itself.
143
+ it('reapplies a command when it is redelivered', async () => {
144
+ let handlerCalls = 0;
145
+ const processor = processorRecording([]);
146
+ const command = activateBundleCommand('activate-1');
147
+ processor.on('activateBundle', () => {
148
+ handlerCalls++;
149
+ return Promise.resolve();
150
+ });
151
+
152
+ await processor.process(command);
153
+ await processor.process(command);
154
+
155
+ assert.strictEqual(handlerCalls, 2);
156
+ });
157
+ });
158
+
159
+ /** Creates a processor whose acknowledgement calls append to the supplied array. */
160
+ function processorRecording(acknowledged: CommandResult[]): AgentCommandProcessor {
161
+ return new AgentCommandProcessor(result => {
162
+ acknowledged.push(result);
163
+ return Promise.resolve();
164
+ });
165
+ }
166
+
167
+ /** Creates a valid model-bundle activation command for processor tests. */
168
+ function activateBundleCommand(id: string): ActivateBundleCommand {
169
+ return {
170
+ id,
171
+ type: 'activateBundle',
172
+ bundle: {
173
+ deploymentVersion: 2,
174
+ kind: 'model',
175
+ path: '/models/version-2',
176
+ },
177
+ };
178
+ }
179
+
180
+ /** Creates an input-policy command used to verify unsupported-command reporting. */
181
+ function updateInputPolicyCommand(id: string): UpdateInputPolicyCommand {
182
+ return {
183
+ id,
184
+ type: 'updateInputPolicy',
185
+ inputPolicy: { mode: 'all' },
186
+ };
187
+ }
188
+
189
+ /** Creates a promise whose completion is controlled by the test. */
190
+ function deferred(): Deferred {
191
+ let resolve: () => void = () => undefined;
192
+ const promise = new Promise<void>(resolvePromise => resolve = resolvePromise);
193
+ return { promise, resolve };
194
+ }
@@ -0,0 +1,114 @@
1
+ import assert from 'node:assert';
2
+ import fs from 'node:fs/promises';
3
+ import http from 'node:http';
4
+ import net from 'node:net';
5
+ import os from 'node:os';
6
+ import Path from 'node:path';
7
+ import sharp from 'sharp';
8
+ import { EventEmitter } from 'tsee';
9
+ import WebSocket from 'ws';
10
+ import { prepareAgentBundle, validateAgentBundle } from '../cli/linux/agent-bundle';
11
+ import { startWebServer } from '../cli/linux/runner-utils';
12
+ import { ImageClassifier } from '../library/classifier/image-classifier';
13
+ import { ICamera } from '../library/sensors/icamera';
14
+ import { writeBundle } from './utils/agent-runner-fixtures';
15
+
16
+ describe('preview for a replaced bundle', () => {
17
+ it('serves each bundle\'s camera, hello, thresholds and results from a fresh stack', async () => {
18
+ const root = await fs.mkdtemp(Path.join(os.tmpdir(), 'ei-preview-'));
19
+ try {
20
+ for (const version of [ 3, 7 ]) {
21
+ const command = await writeBundle(root, { deploymentVersion: version,
22
+ classifyScore: version / 10,
23
+ thresholds: [{ id: 1, type: 'classification', min_score: version / 100 }],
24
+ mock: { imageWidth: version, resizeMode: version === 3 ? 'fit-shortest' : 'squash' } });
25
+ const bundle = await prepareAgentBundle(await validateAgentBundle(command,
26
+ { forceTarget: 'test-target', packageVersion: '1.26.1' }),
27
+ { shmBehavior: 'never', startupTimeoutMs: 1000, verbose: false, servingMode: 'camera' });
28
+ const camera = <ICamera><unknown>new EventEmitter();
29
+ const classifier = new ImageClassifier(bundle.runner, camera);
30
+ const sockets: net.Socket[] = [];
31
+ const clients: WebSocket[] = [];
32
+ let listener: http.Server | undefined;
33
+ try {
34
+ await classifier.start();
35
+ const originalListen = http.Server.prototype.listen;
36
+ http.Server.prototype.listen = function(this: http.Server, ...args: unknown[]) {
37
+ listener = this;
38
+ return Reflect.apply(originalListen, this, args) as http.Server;
39
+ };
40
+ try {
41
+ await startWebServer({ type: 'camera', camera, imgClassifier: classifier,
42
+ streamResolution: 'scaled-using-impulse', model: bundle.model,
43
+ host: '127.0.0.1', port: 0, verbose: false });
44
+ }
45
+ finally { http.Server.prototype.listen = originalListen; }
46
+ assert.ok(listener);
47
+ const server = listener;
48
+ server.on('connection', socket => sockets.push(socket));
49
+ const port = (server.address() as net.AddressInfo).port;
50
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/`);
51
+ const io = new WebSocket(`ws://127.0.0.1:${port}/socket.io/?EIO=4&transport=websocket`);
52
+ clients.push(ws, io);
53
+ const messages: Array<{ type: string; project?: { deploy_version: number };
54
+ modelParameters?: { image_input_width: number; image_resize_mode: string };
55
+ result?: object; image?: string }> = [];
56
+ const events: Array<[string, { project?: { deploy_version: number };
57
+ result?: object; min_score?: number; img?: string; thresholds?: object[] }]> = [];
58
+ ws.on('message', data => messages.push(JSON.parse(data.toString())));
59
+ io.on('message', data => {
60
+ const packet = data.toString();
61
+ if (packet.startsWith('0')) io.send('40');
62
+ else if (packet.startsWith('42')) events.push(JSON.parse(packet.slice(2)));
63
+ else if (packet === '2') io.send('3');
64
+ });
65
+ await waitUntil(() => messages.some(message => message.type === 'hello') &&
66
+ events.some(([ event ]) => event === 'hello'));
67
+ assert.strictEqual(messages[0].project?.deploy_version, version);
68
+ assert.deepStrictEqual(events.find(([ event ]) => event === 'hello')?.[1].thresholds,
69
+ [{ id: 1, type: 'classification', min_score: version / 100 }]);
70
+ assert.strictEqual(classifier.getRunner().getModel().modelParameters.image_input_width, version);
71
+ assert.strictEqual(classifier.getRunner().getModel().modelParameters.image_resize_mode,
72
+ version === 3 ? 'fit-shortest' : 'squash');
73
+ ws.send(JSON.stringify({ type: 'set-camera-preview', enabled: true, messageId: 1 }));
74
+ await waitUntil(() => messages.some(message => message.type === 'handling-message-success'));
75
+ const jpg = await sharp({ create: { width: 1, height: 2, channels: 3,
76
+ background: '#ff0000' } }).jpeg().toBuffer();
77
+ camera.emit('snapshot', jpg, 'frame.jpg');
78
+ camera.emit('snapshotForInference', { filename: 'frame.jpg', imageForInferenceJpg: jpg,
79
+ imageForInferenceRgb: undefined, imageFromCameraJpg: jpg });
80
+ await waitUntil(() => messages.some(message => message.type === 'classification') &&
81
+ messages.some(message => message.type === 'camera-preview') &&
82
+ events.some(([ event ]) => event === 'classification') &&
83
+ events.some(([ event ]) => event === 'image'));
84
+ const result = { classification: { value: version / 10 } };
85
+ assert.deepStrictEqual(messages.find(message => message.type === 'classification')?.result, result);
86
+ assert.deepStrictEqual(events.find(([ event ]) => event === 'classification')?.[1].result, result);
87
+ assert.strictEqual(events.find(([ event ]) => event === 'classification')?.[1].min_score,
88
+ version / 100);
89
+ const image = messages.find(message => message.type === 'camera-preview')!.image!;
90
+ assert.strictEqual(events.find(([ event ]) => event === 'image')?.[1].img, image);
91
+ assert.strictEqual((await sharp(Buffer.from(image.split(',')[1], 'base64')).metadata()).width,
92
+ version);
93
+ }
94
+ finally {
95
+ for (const socket of sockets) socket.destroy();
96
+ for (const client of clients) client.terminate();
97
+ if (listener) await new Promise<void>(resolve => listener!.close(() => resolve()));
98
+ camera.removeAllListeners();
99
+ await bundle.runner.stop();
100
+ await waitUntil(() => clients.every(client => client.readyState === WebSocket.CLOSED));
101
+ }
102
+ }
103
+ }
104
+ finally { await fs.rm(root, { recursive: true, force: true }); }
105
+ }).timeout(15_000);
106
+ });
107
+
108
+ async function waitUntil(predicate: () => boolean) {
109
+ const deadline = Date.now() + 5000;
110
+ while (!predicate()) {
111
+ assert.ok(Date.now() < deadline, 'Timed out waiting for preview messages');
112
+ await new Promise(resolve => setTimeout(resolve, 10));
113
+ }
114
+ }
@@ -0,0 +1,119 @@
1
+ import assert from 'node:assert';
2
+ import { EventEmitter } from 'tsee';
3
+ import { agentEngineName, agentRunnerMode, previewServerEnabled } from '../cli/linux/agent-runner-metadata';
4
+ import { AudioClassifier } from '../library/classifier/audio-classifier';
5
+ import {
6
+ LinuxImpulseRunner,
7
+ ModelInformation,
8
+ RunnerHelloInferencingEngine,
9
+ } from '../library/classifier/linux-impulse-runner';
10
+ import { AudioRecorder } from '../library/sensors/recorder';
11
+ import { selectNonInteractiveDevice } from '../library/sensors/sensors-helper';
12
+
13
+ /**
14
+ * Exercises the startup decisions that let an agent-managed runner describe and acquire its input
15
+ * without user interaction. It verifies explicit and model-derived serving modes, stable engine
16
+ * names, explicit or unambiguous device selection, and managed handling of silent audio. Ambiguous
17
+ * hardware must fail with configuration guidance instead of blocking on an interactive prompt.
18
+ */
19
+ describe('agent runner configuration', () => {
20
+ // Empty registration needs a mode derived from startup configuration before a bundle exists.
21
+ it('reports modes from explicit configuration before a model is loaded', () => {
22
+ assert.strictEqual(agentRunnerMode(1337, undefined, undefined, undefined), 'http');
23
+ assert.strictEqual(agentRunnerMode(undefined, '/dev/video0', undefined, undefined), 'camera');
24
+ assert.strictEqual(agentRunnerMode(undefined, undefined, 'default', undefined), 'microphone');
25
+ assert.strictEqual(agentRunnerMode(undefined, undefined, undefined, undefined), undefined);
26
+ });
27
+
28
+ // Model metadata supplies the mode when startup arguments did not select a streaming input.
29
+ it('reports the mode from a loaded model when no input was selected explicitly', () => {
30
+ const model = <ModelInformation>{ modelParameters: { sensorType: 'camera' } };
31
+ assert.strictEqual(agentRunnerMode(undefined, undefined, undefined, model), 'camera');
32
+ });
33
+
34
+ // The preview interface is unreachable and unauthenticated in agent mode, so it starts only on request.
35
+ it('serves the preview interface in agent mode only when asked', () => {
36
+ assert.strictEqual(previewServerEnabled(false, false, undefined), true);
37
+ assert.strictEqual(previewServerEnabled(true, false, undefined), false);
38
+ assert.strictEqual(previewServerEnabled(true, true, undefined), true);
39
+ assert.strictEqual(previewServerEnabled(true, false, '1'), true);
40
+ assert.strictEqual(previewServerEnabled(true, false, 'true'), false);
41
+ });
42
+
43
+ // Registration uses stable names and must tolerate an engine introduced after this CLI version.
44
+ it('uses stable engine names and accepts future engine values', () => {
45
+ assert.strictEqual(agentEngineName(RunnerHelloInferencingEngine.Tflite), 'tflite');
46
+ assert.strictEqual(agentEngineName(RunnerHelloInferencingEngine.TfliteFull), 'tflite');
47
+ assert.strictEqual(agentEngineName(RunnerHelloInferencingEngine.TensorRT), 'tensorrt');
48
+ assert.strictEqual(agentEngineName(18), 'unknown');
49
+ });
50
+
51
+ // Agent mode cannot prompt, so an explicit device must win when several devices are available.
52
+ it('uses an explicitly selected input device', () => {
53
+ assert.strictEqual(selectNonInteractiveDevice(
54
+ [ 'camera-1', 'camera-2' ], 'camera-2', '--camera', 'EI_CAMERA'), 'camera-2');
55
+ });
56
+
57
+ // A sole device is unambiguous and should start without redundant container configuration.
58
+ it('automatically uses the only available input device', () => {
59
+ assert.strictEqual(selectNonInteractiveDevice(
60
+ [ 'microphone-1' ], undefined, '--microphone', 'EI_MICROPHONE'), 'microphone-1');
61
+ });
62
+
63
+ // Ambiguous hardware must fail rather than blocking a headless application on an interactive prompt.
64
+ it('rejects ambiguous input device selection', () => {
65
+ assert.throws(
66
+ () => selectNonInteractiveDevice(
67
+ [ 'camera-1', 'camera-2' ], undefined, '--camera', 'EI_CAMERA'),
68
+ /set --camera or EI_CAMERA/
69
+ );
70
+ });
71
+
72
+ // Managed applications accept silence because it does not reliably identify a broken microphone.
73
+ it('classifies a silent first audio frame when the legacy diagnostic is disabled', async () => {
74
+ const originalStart = AudioRecorder.prototype.start;
75
+ const audio = new EventEmitter<{ data: (data: Buffer) => void }>();
76
+ AudioRecorder.prototype.start = async () => ({ ee: audio, stop: async () => undefined });
77
+ let classifyCount = 0;
78
+ const classifier = new AudioClassifier(fakeRunner(async () => {
79
+ classifyCount++;
80
+ return classifyResponse();
81
+ }), false, { rejectSilentFirstFrame: false });
82
+ const result = new Promise<void>(resolve => classifier.on('result', () => resolve()));
83
+
84
+ try {
85
+ await classifier.start('test');
86
+ audio.emit('data', Buffer.alloc(2));
87
+ await result;
88
+ assert.strictEqual(classifyCount, 1);
89
+ await classifier.stop();
90
+ }
91
+ finally {
92
+ AudioRecorder.prototype.start = originalStart;
93
+ }
94
+ });
95
+ });
96
+
97
+ /** Creates the minimal initialized runner contract consumed by `AudioClassifier`. */
98
+ function fakeRunner(classify: (values: number[]) => Promise<ReturnType<typeof classifyResponse>>): LinuxImpulseRunner {
99
+ return <LinuxImpulseRunner><unknown>{
100
+ getModel: () => <ModelInformation><unknown>{
101
+ modelParameters: {
102
+ sensorType: 'microphone',
103
+ input_features_count: 1,
104
+ frequency: 1,
105
+ use_continuous_mode: false,
106
+ },
107
+ },
108
+ classify,
109
+ stop: async () => undefined,
110
+ };
111
+ }
112
+
113
+ /** Returns the minimal successful inference response consumed by `AudioClassifier`. */
114
+ function classifyResponse() {
115
+ return {
116
+ result: { classification: { silence: 1 } },
117
+ timing: { dsp: 1, classification: 1, anomaly: 0 },
118
+ };
119
+ }