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,372 @@
1
+ import assert from 'node:assert';
2
+ import { spawn, ChildProcess } from 'node:child_process';
3
+ import fs from 'node:fs/promises';
4
+ import http, { ServerResponse } from 'node:http';
5
+ import net from 'node:net';
6
+ import os from 'node:os';
7
+ import Path from 'node:path';
8
+ import {
9
+ ActivateBundleCommand,
10
+ CommandResult,
11
+ EventBatch,
12
+ InferenceRunnerRegistration,
13
+ } from '../shared/device-protocol/application-contract';
14
+ import { writeBundle } from './utils/agent-runner-fixtures';
15
+
16
+ /** Requests observed by the fake agent across the retiring and replacement application sessions. */
17
+ type AgentObservations = {
18
+ registrations: InferenceRunnerRegistration[];
19
+ results: CommandResult[];
20
+ resultRegistrations: InferenceRunnerRegistration[];
21
+ events: EventBatch[];
22
+ commandStreams: number;
23
+ commandStream?: ServerResponse;
24
+ pendingEventResponse?: ServerResponse;
25
+ holdNextEvent: boolean;
26
+ };
27
+
28
+ /** Exit details retained before assertions begin so an early runner failure cannot be missed. */
29
+ type ProcessExit = {
30
+ code: number | null;
31
+ signal: NodeJS.Signals | null;
32
+ };
33
+
34
+ /** Retains one runner process, its diagnostics and its single eventual exit observation. */
35
+ type SpawnedRunner = {
36
+ child: ChildProcess;
37
+ output: Buffer[];
38
+ exited: Promise<ProcessExit>;
39
+ };
40
+
41
+ /**
42
+ * Exercises the externally visible agent-managed CLI flow using real runner processes and a fake
43
+ * application API. Startup registers empty state, activation commits model 1 and serves inference, and
44
+ * replacement closes inference, flushes pending events and exits for supervisor restart. A fresh
45
+ * process then registers empty state, receives the replayed command, prepares changed sensor metadata,
46
+ * commits model 2 and reports subsequent inference against that new canonical identity.
47
+ */
48
+ describe('agent-managed runner process', () => {
49
+ // The real process must commit canonical metadata, serve inference, then retire atomically for replacement.
50
+ it('activates an initial bundle, retires, then activates the replayed replacement', async () => {
51
+ // Arrange a complete local application boundary: staged bundles, agent socket and inference port.
52
+ const tempDir = await fs.mkdtemp(Path.join(os.tmpdir(), 'ei-agent-runner-'));
53
+ const socketPath = Path.join(tempDir, 'agent.sock');
54
+ const observations: AgentObservations = {
55
+ registrations: [],
56
+ results: [],
57
+ resultRegistrations: [],
58
+ events: [],
59
+ commandStreams: 0,
60
+ holdNextEvent: true,
61
+ };
62
+ const agentServer = await startAgentServer(socketPath, observations);
63
+ const port = await availablePort();
64
+ const bundleOptions = {
65
+ thresholds: [{ id: 1, type: 'classification', min_score: 0.5 }],
66
+ classifyScore: 0.6,
67
+ };
68
+ // Replacement changes accelerometer to positional input, proving the fresh process prepares
69
+ // runtime metadata from the replayed bundle rather than retaining properties from model 1.
70
+ const first = await writeBundle(tempDir, { ...bundleOptions, deploymentVersion: 1, sensor: 2 });
71
+ const replacement = await writeBundle(tempDir, { ...bundleOptions, deploymentVersion: 2, sensor: 4 });
72
+ const runnerPath = Path.resolve(__dirname, '..', 'build', 'cli', 'linux', 'runner.js');
73
+
74
+ // Run the compiled CLI so this test covers its argument handling, lifecycle wiring and process exit.
75
+ const firstProcess = spawnRunner(runnerPath, socketPath, port);
76
+ let secondProcess: SpawnedRunner | undefined;
77
+ let thirdProcess: SpawnedRunner | undefined;
78
+
79
+ try {
80
+ // Initial startup registers an empty application before the agent is allowed to select a bundle.
81
+ await waitFor(() => observations.commandStream !== undefined, 'runner command stream');
82
+ sendCommand(observations, first);
83
+
84
+ // Activation completes only after the model is prepared, the HTTP pipeline is serving and
85
+ // the agent has accepted a registration containing that model.
86
+ await waitFor(() => observations.registrations.length === 2, 'active model registration');
87
+ await waitFor(() => observations.results.some(result => result.commandId === first.id),
88
+ 'initial activation result');
89
+
90
+ assert.deepStrictEqual(observations.registrations[0].models, []);
91
+ assert.deepStrictEqual(observations.registrations[0].capabilities, [ 'activateBundle', 'inputPolicy' ]);
92
+ assert.strictEqual(observations.registrations[0].activeBundle, undefined);
93
+ // Registration describes the original `.eim`; the 0.8 CLI override belongs only to runtime state.
94
+ assert.deepStrictEqual(observations.registrations[1].models[0]?.thresholds, [
95
+ { id: 1, type: 'classification', min_score: 0.5 },
96
+ ]);
97
+ assert.strictEqual(observations.results.find(result => result.commandId === first.id)?.success, true);
98
+ assert.strictEqual(observations.resultRegistrations[0].models[0]?.deploymentVersion, 1);
99
+
100
+ // A 0.6 result is filtered by the runtime 0.8 threshold while its raw event is posted to the agent.
101
+ const inference = await requestJson(port, '/api/features', { features: [ 0 ] });
102
+ assert.strictEqual(inference.statusCode, 200);
103
+ assert.deepStrictEqual((JSON.parse(inference.body) as { result: { classification: object } })
104
+ .result.classification, { value: 0 });
105
+ await waitFor(() => observations.events.length === 1, 'pending inference event');
106
+ assert.deepStrictEqual(
107
+ observations.events[0]?.events[0]?.results?.[0]?.result.classification,
108
+ { value: 0.6 }
109
+ );
110
+
111
+ // Keep that event request pending, then replace the bundle. The retiring process must close
112
+ // inference immediately, leave the activation command unanswered and wait for the event flush.
113
+ sendCommand(observations, replacement);
114
+ await waitForAsync(async () => (await requestJson(port, '/', undefined)).statusCode === 503,
115
+ 'inference shutdown gate');
116
+
117
+ // Accepting the pending event releases graceful shutdown and allows the supervisor restart exit.
118
+ observations.pendingEventResponse?.writeHead(200, { 'content-type': 'application/json' });
119
+ observations.pendingEventResponse?.end(JSON.stringify({ accepted: 1, dropped: 0 }));
120
+ observations.pendingEventResponse = undefined;
121
+
122
+ const termination = await firstProcess.exited;
123
+ assert.deepStrictEqual(
124
+ termination,
125
+ { code: 75, signal: null },
126
+ Buffer.concat(firstProcess.output).toString('utf8')
127
+ );
128
+ assert.strictEqual(observations.results.some(result => result.commandId === replacement.id), false);
129
+ assert.strictEqual(observations.events[0]?.events[0]?.results?.[0]?.modelId, 'model-1');
130
+
131
+ // A fresh process advertises empty state before the agent replays the unanswered command.
132
+ secondProcess = spawnRunner(runnerPath, socketPath, port);
133
+ await waitFor(
134
+ () => observations.commandStreams === 2 && observations.registrations.length === 3,
135
+ 'replacement runner session'
136
+ );
137
+ assert.deepStrictEqual(observations.registrations[2].models, []);
138
+ sendCommand(observations, replacement);
139
+
140
+ // Replay completes only after model 2 is serving and registered as canonical.
141
+ await waitFor(() => observations.registrations.length === 4, 'replacement model registration');
142
+ await waitFor(
143
+ () => observations.results.some(result => result.commandId === replacement.id),
144
+ 'replacement activation result'
145
+ );
146
+ assert.strictEqual(observations.registrations[3].models[0]?.id, 'model-2');
147
+ assert.strictEqual(
148
+ observations.results.find(result => result.commandId === replacement.id)?.success,
149
+ true
150
+ );
151
+
152
+ // Inference from the replacement process must report the new canonical model identity.
153
+ const replacementInference = await requestJson(port, '/api/features', { features: [ 0 ] });
154
+ assert.strictEqual(replacementInference.statusCode, 200);
155
+ await waitFor(() => observations.events.length === 2, 'replacement inference event');
156
+ assert.strictEqual(observations.events[1]?.events[0]?.results?.[0]?.modelId, 'model-2');
157
+ assert.strictEqual(observations.resultRegistrations[1].models[0]?.deploymentVersion, 2);
158
+
159
+ // Static rejection leaves B serving; runtime rejection happens only after a fresh restart.
160
+ const corrupt = await writeBundle(tempDir, { ...bundleOptions, deploymentVersion: 3 });
161
+ await fs.appendFile(Path.join(corrupt.bundle.path, 'model.eim'), '\nchanged');
162
+ sendCommand(observations, corrupt);
163
+ await waitFor(() => observations.results.some(result => result.commandId === corrupt.id),
164
+ 'static candidate rejection');
165
+ assert.strictEqual(observations.results.find(result => result.commandId === corrupt.id)?.success, false);
166
+ assert.strictEqual((await requestJson(port, '/api/features', { features: [ 0 ] })).statusCode, 200);
167
+
168
+ const badRuntime = await writeBundle(tempDir, { ...bundleOptions, deploymentVersion: 4,
169
+ mock: { deploymentVersion: 99 } });
170
+ sendCommand(observations, badRuntime);
171
+ assert.deepStrictEqual(await secondProcess.exited, { code: 75, signal: null });
172
+ assert.strictEqual(observations.results.some(result => result.commandId === badRuntime.id), false);
173
+ thirdProcess = spawnRunner(runnerPath, socketPath, port);
174
+ await waitFor(() => observations.commandStreams === 3, 'recovery runner session');
175
+ assert.deepStrictEqual(observations.registrations[observations.registrations.length - 1].models, []);
176
+ sendCommand(observations, badRuntime);
177
+ await waitFor(() => observations.results.some(result => result.commandId === badRuntime.id),
178
+ 'runtime candidate rejection after restart');
179
+ assert.strictEqual(observations.results.find(result => result.commandId === badRuntime.id)?.success, false);
180
+ const rollback = { ...first, id: 'rollback-to-1' };
181
+ sendCommand(observations, rollback);
182
+ await waitFor(() => observations.results.some(result => result.commandId === rollback.id),
183
+ 'rollback command registration and result');
184
+ assert.strictEqual(observations.results.find(result => result.commandId === rollback.id)?.success, true);
185
+ assert.strictEqual(observations.resultRegistrations[observations.resultRegistrations.length - 1]
186
+ .models[0]?.deploymentVersion, 1);
187
+ assert.strictEqual((await requestJson(port, '/api/features', { features: [ 0 ] })).statusCode, 200);
188
+ await waitFor(() => observations.events.length === 4, 'rollback inference event');
189
+ assert.strictEqual(observations.events[3]?.events[0]?.results?.[0]?.modelId, 'model-1');
190
+
191
+ }
192
+ finally {
193
+ // Keep a failed assertion from leaving the fake agent or child runner alive for later tests.
194
+ observations.pendingEventResponse?.end();
195
+ observations.commandStream?.end();
196
+ await stopRunner(thirdProcess);
197
+ await stopRunner(secondProcess);
198
+ await stopRunner(firstProcess);
199
+ await closeServer(agentServer);
200
+ await fs.rm(tempDir, { recursive: true, force: true });
201
+ }
202
+ }).timeout(25_000);
203
+ });
204
+
205
+ /** Starts the application API needed to drive and observe a real runner process. */
206
+ async function startAgentServer(socketPath: string, observations: AgentObservations): Promise<http.Server> {
207
+ const server = http.createServer(async (request, response) => {
208
+ const body = await requestBody(request);
209
+ if (request.method === 'POST' && request.url === '/v1/register') {
210
+ // Retain both the empty startup registration and the canonical committed model registration.
211
+ observations.registrations.push(JSON.parse(body) as InferenceRunnerRegistration);
212
+ respondJson(response, {
213
+ applicationId: 'runner',
214
+ inputPolicy: { mode: 'none' },
215
+ inlineSizeLimitBytes: 1024,
216
+ });
217
+ return;
218
+ }
219
+ if (request.method === 'GET' && request.url === '/v1/commands') {
220
+ // Hold the stream open so the test can deliver initial activation and replacement in order.
221
+ response.writeHead(200, {
222
+ 'content-type': 'text/event-stream',
223
+ 'cache-control': 'no-cache',
224
+ });
225
+ response.flushHeaders();
226
+ observations.commandStreams++;
227
+ observations.commandStream = response;
228
+ return;
229
+ }
230
+ if (request.method === 'POST' && request.url?.startsWith('/v1/commands/') &&
231
+ request.url.endsWith('/result')) {
232
+ // Results reveal whether each command completed in this process or was left for replay.
233
+ observations.results.push(JSON.parse(body) as CommandResult);
234
+ observations.resultRegistrations.push(observations.registrations[observations.registrations.length - 1]);
235
+ respondJson(response, {});
236
+ return;
237
+ }
238
+ if (request.method === 'POST' && request.url === '/v1/events') {
239
+ observations.events.push(JSON.parse(body) as EventBatch);
240
+ if (observations.holdNextEvent) {
241
+ // Hold the first event so replacement shutdown proves that close() flushes started events.
242
+ observations.holdNextEvent = false;
243
+ observations.pendingEventResponse = response;
244
+ }
245
+ else {
246
+ respondJson(response, { accepted: 1, dropped: 0 });
247
+ }
248
+ return;
249
+ }
250
+ response.writeHead(404).end();
251
+ });
252
+ await new Promise<void>(resolve => server.listen(socketPath, resolve));
253
+ return server;
254
+ }
255
+
256
+ /** Sends one command record over the fake agent's established server-sent event stream. */
257
+ function sendCommand(observations: AgentObservations, command: ActivateBundleCommand): void {
258
+ if (!observations.commandStream) throw new Error('Command stream is not open');
259
+ observations.commandStream.write(`data: ${JSON.stringify(command)}\n\n`);
260
+ }
261
+
262
+ /** Starts the production CLI with the arguments shared by both supervised process generations. */
263
+ function spawnRunner(runnerPath: string, socketPath: string, port: number): SpawnedRunner {
264
+ const child = spawn(process.execPath, [
265
+ runnerPath,
266
+ '--agent', socketPath,
267
+ '--run-http-server', String(port),
268
+ '--force-target', 'test-target',
269
+ '--thresholds', '1.min_score=0.8',
270
+ '--shm-behavior', 'never',
271
+ '--dont-print-predictions',
272
+ ], {
273
+ cwd: Path.resolve(__dirname, '..'),
274
+ env: { ...process.env, EI_RUNNER_IMAGE: 'runner:test' },
275
+ });
276
+ const output: Buffer[] = [];
277
+ child.stdout?.on('data', data => output.push(data));
278
+ child.stderr?.on('data', data => output.push(data));
279
+ return { child, output, exited: processExit(child) };
280
+ }
281
+
282
+ /** Terminates a surviving fixture process and waits briefly for its exit listener to settle. */
283
+ async function stopRunner(runner: SpawnedRunner | undefined): Promise<void> {
284
+ if (!runner) return;
285
+ if (runner.child.exitCode === null && runner.child.signalCode === null) runner.child.kill('SIGKILL');
286
+ await Promise.race([ runner.exited, new Promise(resolve => setTimeout(resolve, 1000)) ]);
287
+ }
288
+
289
+ /** Reserves and releases an ephemeral TCP port for the child runner's inference server. */
290
+ async function availablePort(): Promise<number> {
291
+ const server = net.createServer();
292
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
293
+ const address = server.address();
294
+ if (!address || typeof address === 'string') throw new Error('Cannot allocate an HTTP port');
295
+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
296
+ return address.port;
297
+ }
298
+
299
+ /** Posts optional JSON to the runner and returns its complete HTTP response. */
300
+ function requestJson(port: number, path: string, body: object | undefined): Promise<{
301
+ statusCode: number | undefined;
302
+ body: string;
303
+ }> {
304
+ const encoded = body === undefined ? undefined : JSON.stringify(body);
305
+ return new Promise((resolve, reject) => {
306
+ const request = http.request({
307
+ host: '127.0.0.1',
308
+ port,
309
+ path,
310
+ method: body === undefined ? 'GET' : 'POST',
311
+ headers: encoded === undefined ? undefined : {
312
+ 'content-type': 'application/json',
313
+ 'content-length': Buffer.byteLength(encoded),
314
+ },
315
+ }, response => {
316
+ let responseBody = '';
317
+ response.setEncoding('utf8');
318
+ response.on('data', chunk => responseBody += chunk);
319
+ response.on('end', () => resolve({ statusCode: response.statusCode, body: responseBody }));
320
+ });
321
+ request.on('error', reject);
322
+ request.end(encoded);
323
+ });
324
+ }
325
+
326
+ /** Resolves with one child exit even when it occurs before the test reaches its assertions. */
327
+ function processExit(child: ChildProcess): Promise<ProcessExit> {
328
+ return new Promise(resolve => child.once('exit', (code, signal) => resolve({ code, signal })));
329
+ }
330
+
331
+ /** Reads one small JSON request body from the fake agent transport. */
332
+ async function requestBody(request: http.IncomingMessage): Promise<string> {
333
+ let body = '';
334
+ request.setEncoding('utf8');
335
+ for await (const chunk of request) body += chunk;
336
+ return body;
337
+ }
338
+
339
+ /** Completes one fake-agent request with a JSON response. */
340
+ function respondJson(response: ServerResponse, body: object): void {
341
+ response.writeHead(200, { 'content-type': 'application/json' });
342
+ response.end(JSON.stringify(body));
343
+ }
344
+
345
+ /** Waits for a synchronous observation without coupling the test to process scheduling. */
346
+ async function waitFor(predicate: () => boolean, description: string): Promise<void> {
347
+ const deadline = Date.now() + 10_000;
348
+ while (!predicate()) {
349
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${description}`);
350
+ await new Promise(resolve => setTimeout(resolve, 10));
351
+ }
352
+ }
353
+
354
+ /** Waits for an HTTP-observed state transition while tolerating connection setup races. */
355
+ async function waitForAsync(predicate: () => Promise<boolean>, description: string): Promise<void> {
356
+ const deadline = Date.now() + 10_000;
357
+ while (true) {
358
+ try {
359
+ if (await predicate()) return;
360
+ }
361
+ catch {
362
+ // The HTTP server may not yet be listening or may be between lifecycle operations.
363
+ }
364
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${description}`);
365
+ await new Promise(resolve => setTimeout(resolve, 10));
366
+ }
367
+ }
368
+
369
+ /** Stops the fake agent after its runner has released the open command stream. */
370
+ function closeServer(server: http.Server): Promise<void> {
371
+ return new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
372
+ }
@@ -2154,7 +2154,7 @@ Freeing pipeline ...
2154
2154
  const devices = await testGetDevices({
2155
2155
  gstDeviceMonitor: () => gstMonitorOutput,
2156
2156
  gstInspect: () => gstInspectOutput,
2157
- modeOverride: 'qualcomm-yupik'
2157
+ modeOverride: 'jmo-perspec-1'
2158
2158
  });
2159
2159
  assert.equal(devices.length, 3);
2160
2160
  assert.equal(devices[0].id, '0');
@@ -0,0 +1,106 @@
1
+ import http from 'node:http';
2
+ import { InferenceRunnerRegistration } from '../../shared/device-protocol/application-contract';
3
+
4
+ /** Decoded request body exposed to a mock application API handler. */
5
+ export type MockAgentRequest = {
6
+ body: unknown;
7
+ };
8
+
9
+ /** HTTP response or open command stream returned by a mock application API route. */
10
+ export type MockAgentResponse = {
11
+ statusCode?: number;
12
+ headers?: http.OutgoingHttpHeaders;
13
+ body?: object | string;
14
+ keepOpen?: boolean;
15
+ };
16
+
17
+ /** Application API method and path paired with a fixed response or request handler. */
18
+ export type MockAgentRoute = {
19
+ method: 'GET' | 'POST';
20
+ path: string;
21
+ response: MockAgentResponse | ((request: MockAgentRequest) => MockAgentResponse | Promise<MockAgentResponse>);
22
+ };
23
+
24
+ /**
25
+ * Starts a mock device agent on a Unix socket. Routes declare the response data directly or provide
26
+ * a callback when a test needs to inspect a request, delay a response or record that a stream opened.
27
+ * Unregistered method/path combinations return HTTP 404.
28
+ *
29
+ * @param socketPath Unix socket on which the mock agent should listen.
30
+ * @param routes Application API routes and the responses they should return.
31
+ */
32
+ export async function mockAgentServer(socketPath: string, routes: MockAgentRoute[]): Promise<http.Server> {
33
+ const server = http.createServer(async (request, response) => {
34
+ const route = routes.find(candidate =>
35
+ candidate.method === request.method && candidate.path === request.url);
36
+ if (!route) {
37
+ response.writeHead(404).end();
38
+ return;
39
+ }
40
+
41
+ try {
42
+ let requestBody = '';
43
+ request.setEncoding('utf-8');
44
+ for await (const chunk of request) {
45
+ requestBody += chunk;
46
+ }
47
+ const mockRequest: MockAgentRequest = {
48
+ body: requestBody ? JSON.parse(requestBody) : undefined,
49
+ };
50
+ const mockResponse = typeof route.response === 'function' ?
51
+ await route.response(mockRequest) : route.response;
52
+ const statusCode = mockResponse.statusCode ?? 200;
53
+ const headers = { ...mockResponse.headers };
54
+ const body = typeof mockResponse.body === 'string' ?
55
+ mockResponse.body : mockResponse.body === undefined ? undefined : JSON.stringify(mockResponse.body);
56
+ if (typeof mockResponse.body === 'object' && !headers['content-type']) {
57
+ headers['content-type'] = 'application/json';
58
+ }
59
+ response.writeHead(statusCode, headers);
60
+ if (body !== undefined) {
61
+ response.write(body);
62
+ }
63
+ if (!mockResponse.keepOpen) {
64
+ response.end();
65
+ }
66
+ }
67
+ catch (error) {
68
+ response.writeHead(500).end(error instanceof Error ? error.message : String(error));
69
+ }
70
+ });
71
+ await new Promise<void>(resolve => server.listen(socketPath, resolve));
72
+ return server;
73
+ }
74
+
75
+ /**
76
+ * Returns the smallest valid inference-runner registration used to exercise the client transport
77
+ * independently of model loading.
78
+ */
79
+ export function testRegistration(): InferenceRunnerRegistration {
80
+ return {
81
+ kind: 'inference_runner',
82
+ version: '1.0.0',
83
+ contractVersion: 1,
84
+ artifact: {
85
+ kind: 'containerImage',
86
+ reference: 'inference-container:test',
87
+ },
88
+ models: [],
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Waits for an asynchronous server observation so the tests can verify command-stream setup without
94
+ * coupling themselves to the exact ordering of Node.js HTTP callbacks.
95
+ *
96
+ * @param predicate Returns true once the expected server-side observation has occurred.
97
+ */
98
+ export async function waitFor(predicate: () => boolean) {
99
+ const deadline = Date.now() + 1000;
100
+ while (!predicate()) {
101
+ if (Date.now() >= deadline) {
102
+ throw new Error('Timed out waiting for condition');
103
+ }
104
+ await new Promise(resolve => setTimeout(resolve, 10));
105
+ }
106
+ }