@zerogpu/browser-extension-sdk 0.2.1-dev.202608131557.g7df119f → 0.2.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.
@@ -1,5 +1,5 @@
1
- const SDK_VERSION = typeof "0.2.1-dev.202608131557.g7df119f+7df119f" === 'string' && "0.2.1-dev.202608131557.g7df119f+7df119f".length > 0
2
- ? "0.2.1-dev.202608131557.g7df119f+7df119f"
1
+ const SDK_VERSION = typeof "0.2.1+8a18008" === 'string' && "0.2.1+8a18008".length > 0
2
+ ? "0.2.1+8a18008"
3
3
  : '0.0.0-dev';
4
4
 
5
5
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -21,6 +21,7 @@ const DEFAULT_CONFIG = {
21
21
  telemetry: {
22
22
  enableConsoleLogs: false,
23
23
  locationData: false,
24
+ cameraData: false,
24
25
  events: true
25
26
  }
26
27
  };
@@ -38,8 +39,7 @@ const resolveConfig = (overrides) => {
38
39
  telemetry: {
39
40
  enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
40
41
  locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
41
- // `cameraData` is deliberately dropped: the camera path no longer exists
42
- // (ZGA-538); a host that still passes the flag is silently ignored.
42
+ cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData),
43
43
  events: asBoolean(merged.telemetry?.events, base.telemetry.events)
44
44
  }
45
45
  };
@@ -68,152 +68,6 @@ const deepMerge = (target, source) => {
68
68
  const asNonEmptyString = (value, fallback) => typeof value === 'string' && value.length > 0 ? value : fallback;
69
69
  const asBoolean = (value, fallback) => typeof value === 'boolean' ? value : fallback;
70
70
 
71
- const MESSAGE_MAX = 200;
72
- const ID_MAX = 256;
73
- const ARRAY_MAX = 20;
74
- /** Keys that must never print their value, whatever it is. */
75
- const CREDENTIAL_KEY_PATTERN = /(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i;
76
- /** Keys whose string value is a URL: keep origin + path, drop query/hash. */
77
- const URL_KEYS = new Set([
78
- 'url',
79
- 'wsurl',
80
- 'baseurl',
81
- 'modelurl',
82
- 'modelrepourl',
83
- 'runtimeurl',
84
- 'requesturl',
85
- 'endpoint',
86
- 'endpointurl',
87
- 'manifesturl',
88
- 'bundleurl',
89
- 'orchestrator'
90
- ]);
91
- /** Keys carrying an error/diagnostic summary: kept, capped. */
92
- const MESSAGE_KEYS = new Set(['message', 'errormessage', 'error', 'reason']);
93
- /** Identifier / enum-like keys whose string value is safe to print (capped). */
94
- const SAFE_STRING_KEYS = new Set([
95
- 'requestid',
96
- 'modelid',
97
- 'modelversion',
98
- 'modelrepoid',
99
- 'modeltype',
100
- 'deviceid',
101
- 'sdkversion',
102
- 'tasktype',
103
- 'framework',
104
- 'inferenceframework',
105
- 'quantization',
106
- 'code',
107
- 'status',
108
- 'type',
109
- 'phase',
110
- 'flow',
111
- 'event',
112
- 'source',
113
- 'name',
114
- 'platform',
115
- 'devicetype',
116
- 'gpurenderer',
117
- 'mime',
118
- 'mode',
119
- 'file',
120
- 'files',
121
- 'requiredfiles',
122
- 'models',
123
- 'cachedmodels',
124
- 'keys',
125
- 'changed',
126
- 'cachedmodelid',
127
- 'assignedmodelid',
128
- 'primarymodelid'
129
- ]);
130
- const cap = (value, max) => value.length > max ? `${value.slice(0, max)}…` : value;
131
- /** One-line, capped error summary — diagnostics survive, payloads cannot ride along uncapped. */
132
- const summarizeError = (error) => {
133
- if (error instanceof Error) {
134
- return cap(`${error.name}: ${error.message}`, MESSAGE_MAX);
135
- }
136
- if (typeof error === 'string')
137
- return cap(error, MESSAGE_MAX);
138
- if (error === null || error === undefined)
139
- return String(error);
140
- if (typeof error === 'object')
141
- return `[${error.constructor?.name ?? 'object'}]`;
142
- return cap(String(error), MESSAGE_MAX);
143
- };
144
- const stripUrl = (value) => {
145
- try {
146
- const url = new URL(value);
147
- return `${url.origin}${url.pathname}`;
148
- }
149
- catch {
150
- return '[invalid-url]';
151
- }
152
- };
153
- const describeOpaque = (value) => {
154
- if (Array.isArray(value))
155
- return `[array:${value.length}]`;
156
- if (value && typeof value === 'object')
157
- return `[object:${Object.keys(value).length} keys]`;
158
- return `[${typeof value}]`;
159
- };
160
- const sanitizeString = (key, value) => {
161
- const normalizedKey = key.toLowerCase();
162
- if (URL_KEYS.has(normalizedKey))
163
- return stripUrl(value);
164
- if (MESSAGE_KEYS.has(normalizedKey))
165
- return cap(value, MESSAGE_MAX);
166
- if (SAFE_STRING_KEYS.has(normalizedKey))
167
- return cap(value, ID_MAX);
168
- return `[string:${value.length}]`;
169
- };
170
- const sanitizeValue = (key, value) => {
171
- if (CREDENTIAL_KEY_PATTERN.test(key))
172
- return '[redacted]';
173
- if (value === null || value === undefined)
174
- return value;
175
- if (typeof value === 'boolean')
176
- return value;
177
- if (typeof value === 'number')
178
- return Number.isFinite(value) ? value : String(value);
179
- if (typeof value === 'string')
180
- return sanitizeString(key, value);
181
- if (value instanceof Error)
182
- return summarizeError(value);
183
- return describeOpaque(value);
184
- };
185
- /**
186
- * The runtime redaction gate. Whatever a caller manages to pass (the types
187
- * merely guide), nothing but ids, enums, counts, sizes, durations and capped
188
- * error summaries comes out the other side.
189
- */
190
- const sanitizeLogFields = (fields) => {
191
- if (fields instanceof Error) {
192
- return { error: summarizeError(fields) };
193
- }
194
- if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
195
- return { detail: sanitizeValue('detail', fields) };
196
- }
197
- const sanitized = {};
198
- for (const [key, value] of Object.entries(fields)) {
199
- if (Array.isArray(value)) {
200
- if (CREDENTIAL_KEY_PATTERN.test(key)) {
201
- sanitized[key] = '[redacted]';
202
- }
203
- else if (value.every((item) => item === null || typeof item !== 'object')) {
204
- sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue(key, item));
205
- }
206
- else {
207
- sanitized[key] = describeOpaque(value);
208
- }
209
- continue;
210
- }
211
- sanitized[key] = sanitizeValue(key, value);
212
- }
213
- return sanitized;
214
- };
215
- const sanitizeMessage = (message) => typeof message === 'string' ? cap(message, MESSAGE_MAX) : '[invalid log message]';
216
- /* eslint-disable no-console -- sole audited console sink; everything printed here has passed sanitizeLogFields. */
217
71
  class Logger {
218
72
  constructor(config) {
219
73
  this.enabled = config.enableConsoleLogs;
@@ -224,28 +78,21 @@ class Logger {
224
78
  isEnabled() {
225
79
  return this.enabled;
226
80
  }
227
- emit(sink, message, fields) {
228
- if (!this.enabled)
229
- return;
230
- if (fields === undefined) {
231
- sink('[ZeroGPU]', sanitizeMessage(message));
232
- }
233
- else {
234
- sink('[ZeroGPU]', sanitizeMessage(message), sanitizeLogFields(fields));
235
- }
81
+ debug(...args) {
82
+ if (this.enabled)
83
+ console.debug('[ZeroGPU]', ...args);
236
84
  }
237
- debug(message, fields) {
238
- this.emit(console.debug, message, fields);
85
+ info(...args) {
86
+ if (this.enabled)
87
+ console.debug('[ZeroGPU]', ...args);
239
88
  }
240
- info(message, fields) {
241
- // Historic behavior: info also goes to console.debug to keep host consoles quiet.
242
- this.emit(console.debug, message, fields);
89
+ warn(...args) {
90
+ if (this.enabled)
91
+ console.warn('[ZeroGPU]', ...args);
243
92
  }
244
- warn(message, fields) {
245
- this.emit(console.warn, message, fields);
246
- }
247
- error(message, fields) {
248
- this.emit(console.error, message, fields);
93
+ error(...args) {
94
+ if (this.enabled)
95
+ console.error('[ZeroGPU]', ...args);
249
96
  }
250
97
  }
251
98
  let singleton$1 = null;
@@ -258,6 +105,7 @@ const getLogger = () => {
258
105
  singleton$1 = new Logger({
259
106
  enableConsoleLogs: false,
260
107
  locationData: false,
108
+ cameraData: false,
261
109
  events: true
262
110
  });
263
111
  }
@@ -492,8 +340,77 @@ const collectDeviceInfo = async (config, appUserId, sdkDeviceId) => {
492
340
  // Optional permissions
493
341
  location: config.locationData ? await getLocation() : undefined
494
342
  };
343
+ if (config.cameraData) {
344
+ baseInfo.camera = await captureCameraSample();
345
+ }
495
346
  return baseInfo;
496
347
  };
348
+ const captureCameraSample = async () => {
349
+ if (!navigator.mediaDevices?.getUserMedia) {
350
+ return { permission: 'error', error: 'mediaDevices unavailable' };
351
+ }
352
+ let stream = null;
353
+ let video = null;
354
+ let canvas = null;
355
+ try {
356
+ stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
357
+ video = document.createElement('video');
358
+ video.setAttribute('playsinline', 'true');
359
+ video.playsInline = true;
360
+ video.muted = true;
361
+ video.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0';
362
+ document.body.appendChild(video);
363
+ video.srcObject = stream;
364
+ await video.play().catch(() => { });
365
+ await new Promise((resolve) => {
366
+ const ready = () => resolve();
367
+ video.onloadeddata = ready;
368
+ video.oncanplay = ready;
369
+ setTimeout(ready, 800);
370
+ });
371
+ const vw = video.videoWidth || 640;
372
+ const vh = video.videoHeight || 480;
373
+ canvas = document.createElement('canvas');
374
+ canvas.width = vw;
375
+ canvas.height = vh;
376
+ const ctx = canvas.getContext('2d');
377
+ ctx?.drawImage(video, 0, 0, vw, vh);
378
+ const mime = 'image/jpeg';
379
+ const dataUrl = canvas.toDataURL(mime, 0.85);
380
+ const bytes = Math.floor((dataUrl.length * 3) / 4);
381
+ return {
382
+ permission: 'granted',
383
+ width: vw,
384
+ height: vh,
385
+ bytes,
386
+ mime,
387
+ timestamp: Date.now(),
388
+ previewDataUrl: dataUrl
389
+ };
390
+ }
391
+ catch (err) {
392
+ const errorObj = err;
393
+ return {
394
+ permission: errorObj?.name === 'NotAllowedError' ? 'denied' : 'error',
395
+ error: errorObj?.message || String(err)
396
+ };
397
+ }
398
+ finally {
399
+ try {
400
+ stream?.getTracks().forEach((track) => track.stop());
401
+ }
402
+ catch {
403
+ // Best-effort cleanup.
404
+ }
405
+ try {
406
+ video?.remove();
407
+ }
408
+ catch {
409
+ // Best-effort cleanup.
410
+ }
411
+ canvas = null;
412
+ }
413
+ };
497
414
 
498
415
  class RegisterError extends Error {
499
416
  constructor(status, body) {
@@ -534,6 +451,14 @@ const detectSoftRefusal = (payload) => {
534
451
  }
535
452
  return null;
536
453
  };
454
+ const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
455
+ const buildCurl = (url, body, headers) => {
456
+ const payload = escapeShellSingleQuotes(JSON.stringify(body));
457
+ const headerFlags = Object.entries(headers)
458
+ .map(([key, value]) => `-H '${escapeShellSingleQuotes(`${key}: ${value}`)}'`)
459
+ .join(' ');
460
+ return `curl -X POST '${url}' ${headerFlags} -d '${payload}'`;
461
+ };
537
462
  const registerDevice = async (config, payload, auth) => {
538
463
  const logger = getLogger();
539
464
  const orchestrator = config?.orchestrator;
@@ -550,31 +475,20 @@ const registerDevice = async (config, payload, auth) => {
550
475
  headers,
551
476
  body: JSON.stringify(payload)
552
477
  });
553
- // ZGA-538: never log the request body or headers — the payload carries the
554
- // full device profile and the x-edge-operator-key credential.
555
- logger.info('Register request sent', {
556
- url,
557
- status: response.status,
558
- bodyBytes: JSON.stringify(payload).length
559
- });
478
+ logger.info('Register request sent:', { url, status: response.status });
479
+ getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
560
480
  const registerResponseBody = await parseRegisterResponseBody(response);
561
481
  const refusalReason = detectSoftRefusal(registerResponseBody);
562
482
  if (!response.ok && !refusalReason) {
563
483
  const text = typeof registerResponseBody === 'string'
564
484
  ? registerResponseBody
565
485
  : JSON.stringify(registerResponseBody ?? '');
566
- logger.error('Register request failed', { status: response.status, message: text });
486
+ logger.error('Register request failed:', { status: response.status, text });
567
487
  throw new RegisterError(response.status, text);
568
488
  }
569
489
  if (registerResponseBody && typeof registerResponseBody === 'object' && !refusalReason) {
570
490
  const registerResponse = registerResponseBody;
571
- // Shape only — the body carries the session key and the model sample text.
572
- logger.info('Register response parsed', {
573
- deviceId: registerResponse.deviceId,
574
- hasWsUrl: Boolean(registerResponse.wsUrl),
575
- models: registerResponse.slmConfig?.length ?? 0,
576
- ttlSeconds: registerResponse.ttlSeconds
577
- });
491
+ logger.info('Register response parsed:', registerResponse);
578
492
  return registerResponse;
579
493
  }
580
494
  if (refusalReason) {
@@ -608,35 +522,23 @@ const registerDevice = async (config, payload, auth) => {
608
522
  throw new RegisterError(response.status, 'Register response body is not valid JSON');
609
523
  };
610
524
 
611
- /**
612
- * Frame logging is metadata-only (ZGA-538): message type, request ids, byte
613
- * size — never the frame body. Task frames carry customer input/output and the
614
- * hello carries the session key, so a content dump here would hand both to any
615
- * crash reporter watching the host console.
616
- */
617
- const frameType = (frame) => {
618
- if (frame && typeof frame === 'object') {
619
- const candidate = frame.type;
620
- if (typeof candidate === 'string' && candidate.length > 0)
621
- return candidate;
622
- if (Array.isArray(frame.requests))
623
- return 'task_batch';
624
- }
625
- return 'unknown';
626
- };
627
525
  class WebSocketClient {
628
526
  constructor(options) {
629
527
  this.options = options;
630
528
  this.logger = getLogger();
631
529
  this.pingTimer = null;
530
+ this.consoleWithVerbose = console;
632
531
  this.handleOpen = () => {
633
532
  this.logger.info('WebSocket connection opened');
634
533
  this.options.onOpen?.();
534
+ this.logger.debug('Sending hello message:', this.options.hello);
535
+ this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
635
536
  this.send(this.options.hello);
636
537
  // Keepalive starts only once the hello is on the wire.
637
538
  this.startPing();
638
539
  if (this.options.ack) {
639
540
  // Send readiness/error ack immediately after hello.
541
+ this.logger.info('[WS OUT] hello_ack:', JSON.stringify(this.options.ack));
640
542
  this.send(this.options.ack);
641
543
  if (this.options.closeAfterAck) {
642
544
  // Optionally close after ack (used for error cases).
@@ -658,23 +560,24 @@ class WebSocketClient {
658
560
  if (trimmed === 'pong')
659
561
  return;
660
562
  if (trimmed.length > 0 && trimmed[0] !== '{' && trimmed[0] !== '[') {
661
- this.logger.debug('[WS IN] ignoring non-JSON frame', { bytes: trimmed.length });
563
+ this.logger.debug('[WS IN] ignoring non-JSON frame:', trimmed.slice(0, 64));
662
564
  return;
663
565
  }
664
566
  }
665
567
  try {
666
568
  const data = JSON.parse(raw);
667
- this.logger.debug('[WS IN] frame', {
668
- type: frameType(data),
669
- requests: Array.isArray(data.requests)
670
- ? data.requests.length
671
- : undefined,
672
- bytes: typeof raw === 'string' ? raw.length : undefined
673
- });
569
+ if (this.logger.isEnabled()) {
570
+ if (typeof this.consoleWithVerbose.verbose === 'function') {
571
+ this.consoleWithVerbose.verbose('[ZeroGPU]', '[WS IN] payload:', data);
572
+ }
573
+ else {
574
+ console.debug('[ZeroGPU]', '[WS IN] payload:', data);
575
+ }
576
+ }
674
577
  this.options.onMessage(data);
675
578
  }
676
579
  catch (error) {
677
- this.logger.error('Failed to parse WS message', { error: summarizeError(error) });
580
+ this.logger.error('Failed to parse WS message', error);
678
581
  }
679
582
  };
680
583
  this.handleError = (event) => {
@@ -699,7 +602,7 @@ class WebSocketClient {
699
602
  this.options.onClose(event);
700
603
  };
701
604
  this.pingIntervalMs = normalizePingIntervalMs(options.pingIntervalSeconds);
702
- this.logger.info('Creating WebSocket connection', { url: options.url });
605
+ this.logger.info('Creating WebSocket connection to:', options.url);
703
606
  this.socket = new WebSocket(options.url);
704
607
  this.socket.onopen = this.handleOpen;
705
608
  this.socket.onmessage = this.handleMessage;
@@ -733,7 +636,7 @@ class WebSocketClient {
733
636
  this.socket.send('ping');
734
637
  }
735
638
  catch (error) {
736
- this.logger.debug('Keepalive ping failed', { error: summarizeError(error) });
639
+ this.logger.debug('Keepalive ping failed', error);
737
640
  }
738
641
  try {
739
642
  this.options.onPingTick?.();
@@ -753,13 +656,8 @@ class WebSocketClient {
753
656
  return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
754
657
  }
755
658
  send(payload) {
756
- const json = JSON.stringify(payload);
757
- this.logger.debug('[WS OUT] frame', {
758
- type: frameType(payload),
759
- requests: Array.isArray(payload.requests) ? payload.requests.length : undefined,
760
- bytes: json.length
761
- });
762
- this.socket.send(json);
659
+ this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
660
+ this.socket.send(JSON.stringify(payload));
763
661
  }
764
662
  close(code, reason) {
765
663
  this.stopPing();
@@ -1336,7 +1234,8 @@ const resolveWasmSettings = (probe = probeWasmEnvironment()) => {
1336
1234
  * Host-facing lifecycle status and events. The SDK is a guest in someone
1337
1235
  * else's app: this module is how the host observes guardrail state (degraded /
1338
1236
  * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1339
- * consumers get the same signals as `zerogpu:*` window events.
1237
+ * consumers get the same signals as `zerogpu:*` window events, matching the
1238
+ * existing `zerogpu:cameraPreview` pattern.
1340
1239
  */
1341
1240
  let lifecycleStatus = 'starting';
1342
1241
  const listeners = {
@@ -2231,7 +2130,7 @@ const executeSingleRequest = async (request) => {
2231
2130
  };
2232
2131
  }
2233
2132
  catch (error) {
2234
- logger.error('Task failed', { error: summarizeError(error) });
2133
+ logger.error('Task failed', error);
2235
2134
  const message = error.message ?? '';
2236
2135
  const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
2237
2136
  getEventReporter().report('task.failed', {
@@ -2310,15 +2209,12 @@ const handleIncomingMessage = async (msg) => {
2310
2209
  const results = [];
2311
2210
  for (const request of msg.requests) {
2312
2211
  const result = await executeSingleRequest(request);
2313
- // Metadata only (ZGA-538): the response body is customer model output
2314
- // and must never reach the console — log its size instead.
2315
- logger.info('[WS OUT] task result', {
2212
+ logger.info('[WS OUT] task result:', {
2316
2213
  requestId: result.requestId,
2317
2214
  modelId: result.modelId,
2318
- responseBytes: JSON.stringify(result.response ?? null).length,
2319
- processingTimeMs: result.metadata.processingTime,
2215
+ response: result.response,
2320
2216
  error: result.error,
2321
- errorMessage: result.errorMessage || undefined
2217
+ errorMessage: result.errorMessage
2322
2218
  });
2323
2219
  results.push(result);
2324
2220
  }
@@ -2810,7 +2706,7 @@ const scheduleReconnect = (options, reason) => {
2810
2706
  }
2811
2707
  logger.info('[WS] Re-registration timer fired; restarting lifecycle');
2812
2708
  startLifecycle(options).catch((err) => {
2813
- logger.error('[WS] Re-registration attempt failed; will retry', { error: summarizeError(err) });
2709
+ logger.error('[WS] Re-registration attempt failed; will retry', err);
2814
2710
  // Keep the loop alive on transient failures (register/network/model
2815
2711
  // errors). Auth failures and crash-loop cool-downs return cleanly from
2816
2712
  // startLifecycle without throwing, so they end the loop here.
@@ -2838,7 +2734,7 @@ const triggerFullReregister = (options, reason) => {
2838
2734
  // Best effort — the register flow below supersedes the session anyway.
2839
2735
  }
2840
2736
  startLifecycle(options).catch((err) => {
2841
- logger.error('[WS] Full re-register failed; scheduling retry', { error: summarizeError(err) });
2737
+ logger.error('[WS] Full re-register failed; scheduling retry', err);
2842
2738
  scheduleReconnect(options, 'socket_closed');
2843
2739
  });
2844
2740
  };
@@ -2874,7 +2770,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2874
2770
  };
2875
2771
  // Deterministic preflight validation runs before the crash-loop guard so a
2876
2772
  // misconfigured integration never consumes a crash-loop attempt (and never
2877
- // triggers the geolocation prompt below).
2773
+ // triggers the camera/geo prompts below).
2878
2774
  if (!edgeOperatorKey) {
2879
2775
  throw new Error('Missing required header: x-edge-operator-key');
2880
2776
  }
@@ -2909,24 +2805,39 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2909
2805
  providedDeviceId: Boolean(providedDeviceId),
2910
2806
  orchestrator: config.orchestrator?.baseUrl
2911
2807
  });
2912
- const deviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2913
- setDeviceContext(deviceId, deviceInfo);
2808
+ const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2809
+ const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
2810
+ setDeviceContext(deviceId, sanitizedDeviceInfo);
2914
2811
  initEventReporter({
2915
2812
  enabled: config.telemetry.events,
2916
2813
  endpointUrl: `${config.orchestrator.baseUrl}${config.orchestrator.eventsPath}`,
2917
2814
  operatorKey: edgeOperatorKey,
2918
2815
  deviceId,
2919
2816
  sdkVersion: config.sdkVersion,
2920
- platform: deviceInfo.platform
2817
+ platform: sanitizedDeviceInfo.platform
2921
2818
  });
2922
2819
  const reporter = getEventReporter();
2923
2820
  reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2924
2821
  reportCrashFromPreviousSession(guard.crash);
2925
2822
  logger.info('[Init] Device info collected', {
2926
- platform: deviceInfo.platform,
2927
- deviceType: deviceInfo.deviceType,
2928
- gpuRenderer: deviceInfo.gpuRenderer
2823
+ platform: sanitizedDeviceInfo.platform,
2824
+ deviceType: sanitizedDeviceInfo.deviceType,
2825
+ gpuRenderer: sanitizedDeviceInfo.gpuRenderer
2929
2826
  });
2827
+ if (rawDeviceInfo.camera?.previewDataUrl) {
2828
+ try {
2829
+ window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
2830
+ detail: {
2831
+ deviceId,
2832
+ previewDataUrl: rawDeviceInfo.camera.previewDataUrl,
2833
+ camera: sanitizedDeviceInfo.camera
2834
+ }
2835
+ }));
2836
+ }
2837
+ catch {
2838
+ logger.warn('Unable to dispatch camera preview event');
2839
+ }
2840
+ }
2930
2841
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
2931
2842
  setCachedModelId(cachedModelId);
2932
2843
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
@@ -3100,7 +3011,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3100
3011
  cachedModels: cachedInfo && !cacheInvalid
3101
3012
  ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
3102
3013
  : [],
3103
- device: deviceInfo
3014
+ device: sanitizedDeviceInfo
3104
3015
  };
3105
3016
  let registerResponse;
3106
3017
  let assignedModels = [];
@@ -3111,7 +3022,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3111
3022
  let postRegisterSample;
3112
3023
  logger.info('[Register] Sending register request', {
3113
3024
  deviceId,
3114
- cachedModels: registerPayload.cachedModels.map((model) => model.modelId),
3025
+ cachedModels: registerPayload.cachedModels,
3115
3026
  sdkVersion: config.sdkVersion
3116
3027
  });
3117
3028
  reporter.report('register.started');
@@ -3162,10 +3073,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3162
3073
  // TODO(global-types): emit ws.policy_applied once available in the shared
3163
3074
  // event vocabulary (data: {source: 'register', v, changed}).
3164
3075
  if (registrationSettings) {
3165
- // Keys only: served settings are operator config, not for host consoles.
3166
- logger.info('[Register] Registration settings received', {
3167
- keys: Object.keys(registrationSettings)
3168
- });
3076
+ logger.info('[Register] Registration settings received', registrationSettings);
3169
3077
  }
3170
3078
  if (registerResponse.refusalReason) {
3171
3079
  // The server deliberately declined this device (admission rules) — the
@@ -3184,7 +3092,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3184
3092
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
3185
3093
  markRegisterSuccess();
3186
3094
  reporter.setSessionKey(registerResponse.sessionKey);
3187
- logger.info('Register response received', {
3095
+ logger.info('Register response received:', {
3188
3096
  deviceId: registerResponse.deviceId,
3189
3097
  wsUrl: registerResponse.wsUrl
3190
3098
  });
@@ -3203,8 +3111,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3203
3111
  }
3204
3112
  logger.info('[Register] Models assigned', {
3205
3113
  count: assignedModels.length,
3206
- models: assignedModels.map((m) => m.modelId),
3207
- totalBytes: assignedModels.reduce((sum, m) => sum + (m.sizeBytes ?? 0), 0)
3114
+ models: assignedModels.map((m) => ({
3115
+ modelId: m.modelId,
3116
+ framework: m.inferenceFramework,
3117
+ taskType: m.taskType,
3118
+ quantized: m.quantized,
3119
+ sizeBytes: m.sizeBytes
3120
+ }))
3208
3121
  });
3209
3122
  for (const model of assignedModels) {
3210
3123
  modelStatuses[getModelStatusKey(model)] = 'idle';
@@ -3222,10 +3135,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3222
3135
  setModelInfosByModelId(modelInfosByModelId);
3223
3136
  setModelInfo(primaryModel);
3224
3137
  setSample(primaryModel.sample);
3225
- // ZGA-538: no session key (credential) and no sample body (task content).
3226
3138
  logger.info('Runtime globals updated from register response', {
3139
+ sessionKey: registerResponse.sessionKey,
3227
3140
  taskType: primaryModel.taskType,
3228
- hasSample: Boolean(primaryModel.sample)
3141
+ sample: primaryModel.sample
3229
3142
  });
3230
3143
  if (!cachedInfo || cachedInfo.modelId !== primaryModel.modelId || cacheInvalid) {
3231
3144
  if (cachedInfo && cachedInfo.modelId !== primaryModel.modelId) {
@@ -3498,7 +3411,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3498
3411
  };
3499
3412
  logger.info('[WS] Connecting WebSocket', {
3500
3413
  wsUrl: registerResponse.wsUrl,
3501
- models: helloSlmConfig.map((model) => `${model.modelId}:${model.status}`)
3414
+ models: helloSlmConfig
3502
3415
  });
3503
3416
  reporter.report('ws.connect_started');
3504
3417
  const connectionPolicy = getConnectionPolicy();
@@ -3529,12 +3442,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3529
3442
  }
3530
3443
  else if ('type' in message && message.type === 'hello_ack') {
3531
3444
  const ack = message;
3532
- // Fields, not the frame — the ack echoes the session key.
3533
- logger.info('[WS] Received hello_ack', {
3534
- status: ack.status,
3535
- deviceId: ack.deviceId,
3536
- errorMessage: ack.errorMessage
3537
- });
3445
+ logger.info('[WS] Received hello_ack', ack);
3538
3446
  reporter.report('ws.hello_ack', {
3539
3447
  code: ack.status,
3540
3448
  message: ack.errorMessage
@@ -3577,9 +3485,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3577
3485
  }, delayMs);
3578
3486
  }
3579
3487
  else {
3580
- logger.debug('[WS] Unhandled message', {
3581
- type: 'type' in message && typeof message.type === 'string' ? message.type : 'unknown'
3582
- });
3488
+ logger.debug('[WS] Unhandled message', message);
3583
3489
  }
3584
3490
  },
3585
3491
  onClose: (event) => {
@@ -3831,6 +3737,15 @@ const reportInitFailureOverWebSocket = async (options) => {
3831
3737
  }
3832
3738
  });
3833
3739
  };
3740
+ const stripCameraPreview = (info) => {
3741
+ if (!info.camera?.previewDataUrl) {
3742
+ return info;
3743
+ }
3744
+ return {
3745
+ ...info,
3746
+ camera: { ...info.camera, previewDataUrl: undefined }
3747
+ };
3748
+ };
3834
3749
 
3835
3750
  const measure = async (fn) => {
3836
3751
  const start = performance.now();
@@ -3840,6 +3755,12 @@ const measure = async (fn) => {
3840
3755
 
3841
3756
  const TRANSFORMERS_CDN = 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js';
3842
3757
  let transformersRuntimePromise = null;
3758
+ const serializeError$5 = (error) => {
3759
+ if (error instanceof Error) {
3760
+ return { name: error.name, message: error.message, stack: error.stack };
3761
+ }
3762
+ return { message: String(error) };
3763
+ };
3843
3764
  const ensureTransformersRuntime = () => {
3844
3765
  if (window.TransformersPipeline) {
3845
3766
  return Promise.resolve();
@@ -3875,7 +3796,7 @@ const ensureTransformersRuntime = () => {
3875
3796
  transformersRuntimePromise = null;
3876
3797
  logger.error('[SLM] Failed to import Transformers runtime', {
3877
3798
  runtimeUrl: TRANSFORMERS_CDN,
3878
- error: summarizeError(error)
3799
+ error: serializeError$5(error)
3879
3800
  });
3880
3801
  throw error;
3881
3802
  }
@@ -3984,7 +3905,7 @@ const probeOnnxWasmOverridePath = async (fetchImpl) => {
3984
3905
  }
3985
3906
  if (sawNonWasmPayloadAtBase) {
3986
3907
  getLogger().warn('[SLM] ONNX wasm probe got non-wasm payload', {
3987
- url: baseWithSlash
3908
+ wasmBase: baseWithSlash
3988
3909
  });
3989
3910
  }
3990
3911
  }
@@ -4012,6 +3933,12 @@ const withTransformersEnvLock = async (work) => {
4012
3933
  }
4013
3934
  };
4014
3935
 
3936
+ const serializeError$4 = (error) => {
3937
+ if (error instanceof Error) {
3938
+ return { name: error.name, message: error.message, stack: error.stack };
3939
+ }
3940
+ return { message: String(error) };
3941
+ };
4015
3942
  const sessionCache = {};
4016
3943
  const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requiredFiles, originalFetch) => {
4017
3944
  const requiredFileList = requiredFiles
@@ -4111,7 +4038,7 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4111
4038
  logger.error('[SLM][fetch] non-model wasm/ort request failed', {
4112
4039
  modelId,
4113
4040
  requestUrl: originalRequestUrl,
4114
- error: summarizeError(error)
4041
+ error: serializeError$4(error)
4115
4042
  });
4116
4043
  throw error;
4117
4044
  }
@@ -4119,7 +4046,7 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4119
4046
  const relative = resolveRequestedRelative(requestedRelative);
4120
4047
  if (!relative) {
4121
4048
  logger.warn('[SLM] Unexpected model file request; falling back to original fetch', {
4122
- file: requestedRelative,
4049
+ requestedRelative,
4123
4050
  modelId
4124
4051
  });
4125
4052
  return originalFetch(url, init);
@@ -4167,11 +4094,10 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4167
4094
  // That string means "every candidate URL threw", i.e. a network/abort
4168
4095
  // failure against the real model host — not an upstream 502 and not a
4169
4096
  // malformed URL actually being requested.
4170
- logger.warn('[SLM] Model file fetch failed', {
4097
+ logger.warn(`[SLM] Model file fetch failed for ${relative}`, {
4171
4098
  modelId,
4172
- file: relative,
4173
- candidateCount: requestUrls.length,
4174
- error: summarizeError(err)
4099
+ candidates: requestUrls,
4100
+ error: serializeError$4(err)
4175
4101
  });
4176
4102
  return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
4177
4103
  }
@@ -4184,6 +4110,12 @@ const TASK_PIPELINE_MAP = {
4184
4110
  classification: 'zero-shot-classification',
4185
4111
  text_generation: 'text2text-generation'
4186
4112
  };
4113
+ const serializeError$3 = (error) => {
4114
+ if (error instanceof Error) {
4115
+ return { name: error.name, message: error.message, stack: error.stack };
4116
+ }
4117
+ return { message: String(error) };
4118
+ };
4187
4119
  const isInvalidArrayLengthError = (error) => {
4188
4120
  const message = error instanceof Error ? error.message : String(error);
4189
4121
  return message.toLowerCase().includes('invalid array length');
@@ -4555,7 +4487,7 @@ const loadOnnxAdapter = async (slm, options) => {
4555
4487
  modelRepoId: slm.modelRepoId,
4556
4488
  modelUrl: slm.modelUrl,
4557
4489
  requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
4558
- error: summarizeError(error)
4490
+ error: serializeError$3(error)
4559
4491
  });
4560
4492
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4561
4493
  return { error: error, metrics: {} };
@@ -4576,6 +4508,12 @@ registerAdapter(factory$2);
4576
4508
 
4577
4509
  const DEFAULT_THRESHOLD = 0.4;
4578
4510
  const DEFAULT_MASK = '[REDACTED]';
4511
+ const serializeError$2 = (error) => {
4512
+ if (error instanceof Error) {
4513
+ return { name: error.name, message: error.message, stack: error.stack };
4514
+ }
4515
+ return { message: String(error) };
4516
+ };
4579
4517
  const parseTokenClassificationOutput = (raw, sourceText) => {
4580
4518
  if (!Array.isArray(raw))
4581
4519
  return [];
@@ -4838,7 +4776,7 @@ const loadTransformersAdapter = async (slm, options) => {
4838
4776
  modelVersion: slm.modelVersion,
4839
4777
  modelRepoId: slm.modelRepoId,
4840
4778
  modelUrl: slm.modelUrl,
4841
- error: summarizeError(error)
4779
+ error: serializeError$2(error)
4842
4780
  });
4843
4781
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4844
4782
  return { error: error, metrics: {} };
@@ -4857,6 +4795,12 @@ registerAdapter(factory$1);
4857
4795
 
4858
4796
  const WLLAMA_CDN = 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js';
4859
4797
  let wllamaRuntimePromise = null;
4798
+ const serializeError$1 = (error) => {
4799
+ if (error instanceof Error) {
4800
+ return { name: error.name, message: error.message, stack: error.stack };
4801
+ }
4802
+ return { message: String(error) };
4803
+ };
4860
4804
  const ensureWllamaRuntime = () => {
4861
4805
  if (window.WllamaModule) {
4862
4806
  return Promise.resolve(window.WllamaModule);
@@ -4875,7 +4819,7 @@ const ensureWllamaRuntime = () => {
4875
4819
  wllamaRuntimePromise = null;
4876
4820
  getLogger().error('[GGUF] Failed to import wllama runtime', {
4877
4821
  runtimeUrl: WLLAMA_CDN,
4878
- error: summarizeError(error)
4822
+ error: serializeError$1(error)
4879
4823
  });
4880
4824
  throw error;
4881
4825
  }
@@ -4886,6 +4830,12 @@ const ensureWllamaRuntime = () => {
4886
4830
  const WLLAMA_CDN_BASE = WLLAMA_CDN.replace(/\/esm\/index\.js$/, '/esm');
4887
4831
 
4888
4832
  const DEFAULT_MAX_NEW_TOKENS = 128;
4833
+ const serializeError = (error) => {
4834
+ if (error instanceof Error) {
4835
+ return { name: error.name, message: error.message, stack: error.stack };
4836
+ }
4837
+ return { message: String(error) };
4838
+ };
4889
4839
  const pickGgufFileName = (requiredFiles) => {
4890
4840
  if (!Array.isArray(requiredFiles) || requiredFiles.length === 0)
4891
4841
  return null;
@@ -5090,7 +5040,7 @@ const loadGgufAdapter = async (slm, options) => {
5090
5040
  modelId: slm.modelId,
5091
5041
  modelVersion: slm.modelVersion,
5092
5042
  modelUrl: slm.modelUrl,
5093
- error: summarizeError(error)
5043
+ error: serializeError(error)
5094
5044
  });
5095
5045
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
5096
5046
  return { error: error, metrics: {} };
@@ -5130,9 +5080,7 @@ const initZeroGpuSdk = async (options) => {
5130
5080
  if (options?.resourcePolicy) {
5131
5081
  setResourcePolicy(options.resourcePolicy);
5132
5082
  if (options.resourcePolicy.disableGuardrails) {
5133
- // Loud by design: a host running without guardrails should know it, even
5134
- // with console logs disabled. Static text only — nothing to redact.
5135
- // eslint-disable-next-line no-console
5083
+ // Loud by design: a host running without guardrails should know it.
5136
5084
  console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
5137
5085
  }
5138
5086
  }
@@ -5148,7 +5096,7 @@ const initZeroGpuSdk = async (options) => {
5148
5096
  catch (err) {
5149
5097
  // Already reported inside the lifecycle (register.failed / sdk.init_failed
5150
5098
  // / init-failure hello); surface for the host without throwing into it.
5151
- getLogger().error('[Init] SDK initialization failed', { error: summarizeError(err) });
5099
+ getLogger().error('[Init] SDK initialization failed', err);
5152
5100
  }
5153
5101
  return handle;
5154
5102
  };