@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,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const SDK_VERSION = typeof "0.2.1-dev.202608131557.g7df119f+7df119f" === 'string' && "0.2.1-dev.202608131557.g7df119f+7df119f".length > 0
4
- ? "0.2.1-dev.202608131557.g7df119f+7df119f"
3
+ const SDK_VERSION = typeof "0.2.1+8a18008" === 'string' && "0.2.1+8a18008".length > 0
4
+ ? "0.2.1+8a18008"
5
5
  : '0.0.0-dev';
6
6
 
7
7
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -23,6 +23,7 @@ const DEFAULT_CONFIG = {
23
23
  telemetry: {
24
24
  enableConsoleLogs: false,
25
25
  locationData: false,
26
+ cameraData: false,
26
27
  events: true
27
28
  }
28
29
  };
@@ -40,8 +41,7 @@ const resolveConfig = (overrides) => {
40
41
  telemetry: {
41
42
  enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
42
43
  locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
43
- // `cameraData` is deliberately dropped: the camera path no longer exists
44
- // (ZGA-538); a host that still passes the flag is silently ignored.
44
+ cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData),
45
45
  events: asBoolean(merged.telemetry?.events, base.telemetry.events)
46
46
  }
47
47
  };
@@ -70,152 +70,6 @@ const deepMerge = (target, source) => {
70
70
  const asNonEmptyString = (value, fallback) => typeof value === 'string' && value.length > 0 ? value : fallback;
71
71
  const asBoolean = (value, fallback) => typeof value === 'boolean' ? value : fallback;
72
72
 
73
- const MESSAGE_MAX = 200;
74
- const ID_MAX = 256;
75
- const ARRAY_MAX = 20;
76
- /** Keys that must never print their value, whatever it is. */
77
- const CREDENTIAL_KEY_PATTERN = /(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i;
78
- /** Keys whose string value is a URL: keep origin + path, drop query/hash. */
79
- const URL_KEYS = new Set([
80
- 'url',
81
- 'wsurl',
82
- 'baseurl',
83
- 'modelurl',
84
- 'modelrepourl',
85
- 'runtimeurl',
86
- 'requesturl',
87
- 'endpoint',
88
- 'endpointurl',
89
- 'manifesturl',
90
- 'bundleurl',
91
- 'orchestrator'
92
- ]);
93
- /** Keys carrying an error/diagnostic summary: kept, capped. */
94
- const MESSAGE_KEYS = new Set(['message', 'errormessage', 'error', 'reason']);
95
- /** Identifier / enum-like keys whose string value is safe to print (capped). */
96
- const SAFE_STRING_KEYS = new Set([
97
- 'requestid',
98
- 'modelid',
99
- 'modelversion',
100
- 'modelrepoid',
101
- 'modeltype',
102
- 'deviceid',
103
- 'sdkversion',
104
- 'tasktype',
105
- 'framework',
106
- 'inferenceframework',
107
- 'quantization',
108
- 'code',
109
- 'status',
110
- 'type',
111
- 'phase',
112
- 'flow',
113
- 'event',
114
- 'source',
115
- 'name',
116
- 'platform',
117
- 'devicetype',
118
- 'gpurenderer',
119
- 'mime',
120
- 'mode',
121
- 'file',
122
- 'files',
123
- 'requiredfiles',
124
- 'models',
125
- 'cachedmodels',
126
- 'keys',
127
- 'changed',
128
- 'cachedmodelid',
129
- 'assignedmodelid',
130
- 'primarymodelid'
131
- ]);
132
- const cap = (value, max) => value.length > max ? `${value.slice(0, max)}…` : value;
133
- /** One-line, capped error summary — diagnostics survive, payloads cannot ride along uncapped. */
134
- const summarizeError = (error) => {
135
- if (error instanceof Error) {
136
- return cap(`${error.name}: ${error.message}`, MESSAGE_MAX);
137
- }
138
- if (typeof error === 'string')
139
- return cap(error, MESSAGE_MAX);
140
- if (error === null || error === undefined)
141
- return String(error);
142
- if (typeof error === 'object')
143
- return `[${error.constructor?.name ?? 'object'}]`;
144
- return cap(String(error), MESSAGE_MAX);
145
- };
146
- const stripUrl = (value) => {
147
- try {
148
- const url = new URL(value);
149
- return `${url.origin}${url.pathname}`;
150
- }
151
- catch {
152
- return '[invalid-url]';
153
- }
154
- };
155
- const describeOpaque = (value) => {
156
- if (Array.isArray(value))
157
- return `[array:${value.length}]`;
158
- if (value && typeof value === 'object')
159
- return `[object:${Object.keys(value).length} keys]`;
160
- return `[${typeof value}]`;
161
- };
162
- const sanitizeString = (key, value) => {
163
- const normalizedKey = key.toLowerCase();
164
- if (URL_KEYS.has(normalizedKey))
165
- return stripUrl(value);
166
- if (MESSAGE_KEYS.has(normalizedKey))
167
- return cap(value, MESSAGE_MAX);
168
- if (SAFE_STRING_KEYS.has(normalizedKey))
169
- return cap(value, ID_MAX);
170
- return `[string:${value.length}]`;
171
- };
172
- const sanitizeValue = (key, value) => {
173
- if (CREDENTIAL_KEY_PATTERN.test(key))
174
- return '[redacted]';
175
- if (value === null || value === undefined)
176
- return value;
177
- if (typeof value === 'boolean')
178
- return value;
179
- if (typeof value === 'number')
180
- return Number.isFinite(value) ? value : String(value);
181
- if (typeof value === 'string')
182
- return sanitizeString(key, value);
183
- if (value instanceof Error)
184
- return summarizeError(value);
185
- return describeOpaque(value);
186
- };
187
- /**
188
- * The runtime redaction gate. Whatever a caller manages to pass (the types
189
- * merely guide), nothing but ids, enums, counts, sizes, durations and capped
190
- * error summaries comes out the other side.
191
- */
192
- const sanitizeLogFields = (fields) => {
193
- if (fields instanceof Error) {
194
- return { error: summarizeError(fields) };
195
- }
196
- if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
197
- return { detail: sanitizeValue('detail', fields) };
198
- }
199
- const sanitized = {};
200
- for (const [key, value] of Object.entries(fields)) {
201
- if (Array.isArray(value)) {
202
- if (CREDENTIAL_KEY_PATTERN.test(key)) {
203
- sanitized[key] = '[redacted]';
204
- }
205
- else if (value.every((item) => item === null || typeof item !== 'object')) {
206
- sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue(key, item));
207
- }
208
- else {
209
- sanitized[key] = describeOpaque(value);
210
- }
211
- continue;
212
- }
213
- sanitized[key] = sanitizeValue(key, value);
214
- }
215
- return sanitized;
216
- };
217
- const sanitizeMessage = (message) => typeof message === 'string' ? cap(message, MESSAGE_MAX) : '[invalid log message]';
218
- /* eslint-disable no-console -- sole audited console sink; everything printed here has passed sanitizeLogFields. */
219
73
  class Logger {
220
74
  constructor(config) {
221
75
  this.enabled = config.enableConsoleLogs;
@@ -226,28 +80,21 @@ class Logger {
226
80
  isEnabled() {
227
81
  return this.enabled;
228
82
  }
229
- emit(sink, message, fields) {
230
- if (!this.enabled)
231
- return;
232
- if (fields === undefined) {
233
- sink('[ZeroGPU]', sanitizeMessage(message));
234
- }
235
- else {
236
- sink('[ZeroGPU]', sanitizeMessage(message), sanitizeLogFields(fields));
237
- }
83
+ debug(...args) {
84
+ if (this.enabled)
85
+ console.debug('[ZeroGPU]', ...args);
238
86
  }
239
- debug(message, fields) {
240
- this.emit(console.debug, message, fields);
87
+ info(...args) {
88
+ if (this.enabled)
89
+ console.debug('[ZeroGPU]', ...args);
241
90
  }
242
- info(message, fields) {
243
- // Historic behavior: info also goes to console.debug to keep host consoles quiet.
244
- this.emit(console.debug, message, fields);
91
+ warn(...args) {
92
+ if (this.enabled)
93
+ console.warn('[ZeroGPU]', ...args);
245
94
  }
246
- warn(message, fields) {
247
- this.emit(console.warn, message, fields);
248
- }
249
- error(message, fields) {
250
- this.emit(console.error, message, fields);
95
+ error(...args) {
96
+ if (this.enabled)
97
+ console.error('[ZeroGPU]', ...args);
251
98
  }
252
99
  }
253
100
  let singleton$1 = null;
@@ -260,6 +107,7 @@ const getLogger = () => {
260
107
  singleton$1 = new Logger({
261
108
  enableConsoleLogs: false,
262
109
  locationData: false,
110
+ cameraData: false,
263
111
  events: true
264
112
  });
265
113
  }
@@ -494,8 +342,77 @@ const collectDeviceInfo = async (config, appUserId, sdkDeviceId) => {
494
342
  // Optional permissions
495
343
  location: config.locationData ? await getLocation() : undefined
496
344
  };
345
+ if (config.cameraData) {
346
+ baseInfo.camera = await captureCameraSample();
347
+ }
497
348
  return baseInfo;
498
349
  };
350
+ const captureCameraSample = async () => {
351
+ if (!navigator.mediaDevices?.getUserMedia) {
352
+ return { permission: 'error', error: 'mediaDevices unavailable' };
353
+ }
354
+ let stream = null;
355
+ let video = null;
356
+ let canvas = null;
357
+ try {
358
+ stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
359
+ video = document.createElement('video');
360
+ video.setAttribute('playsinline', 'true');
361
+ video.playsInline = true;
362
+ video.muted = true;
363
+ video.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0';
364
+ document.body.appendChild(video);
365
+ video.srcObject = stream;
366
+ await video.play().catch(() => { });
367
+ await new Promise((resolve) => {
368
+ const ready = () => resolve();
369
+ video.onloadeddata = ready;
370
+ video.oncanplay = ready;
371
+ setTimeout(ready, 800);
372
+ });
373
+ const vw = video.videoWidth || 640;
374
+ const vh = video.videoHeight || 480;
375
+ canvas = document.createElement('canvas');
376
+ canvas.width = vw;
377
+ canvas.height = vh;
378
+ const ctx = canvas.getContext('2d');
379
+ ctx?.drawImage(video, 0, 0, vw, vh);
380
+ const mime = 'image/jpeg';
381
+ const dataUrl = canvas.toDataURL(mime, 0.85);
382
+ const bytes = Math.floor((dataUrl.length * 3) / 4);
383
+ return {
384
+ permission: 'granted',
385
+ width: vw,
386
+ height: vh,
387
+ bytes,
388
+ mime,
389
+ timestamp: Date.now(),
390
+ previewDataUrl: dataUrl
391
+ };
392
+ }
393
+ catch (err) {
394
+ const errorObj = err;
395
+ return {
396
+ permission: errorObj?.name === 'NotAllowedError' ? 'denied' : 'error',
397
+ error: errorObj?.message || String(err)
398
+ };
399
+ }
400
+ finally {
401
+ try {
402
+ stream?.getTracks().forEach((track) => track.stop());
403
+ }
404
+ catch {
405
+ // Best-effort cleanup.
406
+ }
407
+ try {
408
+ video?.remove();
409
+ }
410
+ catch {
411
+ // Best-effort cleanup.
412
+ }
413
+ canvas = null;
414
+ }
415
+ };
499
416
 
500
417
  class RegisterError extends Error {
501
418
  constructor(status, body) {
@@ -536,6 +453,14 @@ const detectSoftRefusal = (payload) => {
536
453
  }
537
454
  return null;
538
455
  };
456
+ const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
457
+ const buildCurl = (url, body, headers) => {
458
+ const payload = escapeShellSingleQuotes(JSON.stringify(body));
459
+ const headerFlags = Object.entries(headers)
460
+ .map(([key, value]) => `-H '${escapeShellSingleQuotes(`${key}: ${value}`)}'`)
461
+ .join(' ');
462
+ return `curl -X POST '${url}' ${headerFlags} -d '${payload}'`;
463
+ };
539
464
  const registerDevice = async (config, payload, auth) => {
540
465
  const logger = getLogger();
541
466
  const orchestrator = config?.orchestrator;
@@ -552,31 +477,20 @@ const registerDevice = async (config, payload, auth) => {
552
477
  headers,
553
478
  body: JSON.stringify(payload)
554
479
  });
555
- // ZGA-538: never log the request body or headers — the payload carries the
556
- // full device profile and the x-edge-operator-key credential.
557
- logger.info('Register request sent', {
558
- url,
559
- status: response.status,
560
- bodyBytes: JSON.stringify(payload).length
561
- });
480
+ logger.info('Register request sent:', { url, status: response.status });
481
+ getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
562
482
  const registerResponseBody = await parseRegisterResponseBody(response);
563
483
  const refusalReason = detectSoftRefusal(registerResponseBody);
564
484
  if (!response.ok && !refusalReason) {
565
485
  const text = typeof registerResponseBody === 'string'
566
486
  ? registerResponseBody
567
487
  : JSON.stringify(registerResponseBody ?? '');
568
- logger.error('Register request failed', { status: response.status, message: text });
488
+ logger.error('Register request failed:', { status: response.status, text });
569
489
  throw new RegisterError(response.status, text);
570
490
  }
571
491
  if (registerResponseBody && typeof registerResponseBody === 'object' && !refusalReason) {
572
492
  const registerResponse = registerResponseBody;
573
- // Shape only — the body carries the session key and the model sample text.
574
- logger.info('Register response parsed', {
575
- deviceId: registerResponse.deviceId,
576
- hasWsUrl: Boolean(registerResponse.wsUrl),
577
- models: registerResponse.slmConfig?.length ?? 0,
578
- ttlSeconds: registerResponse.ttlSeconds
579
- });
493
+ logger.info('Register response parsed:', registerResponse);
580
494
  return registerResponse;
581
495
  }
582
496
  if (refusalReason) {
@@ -610,35 +524,23 @@ const registerDevice = async (config, payload, auth) => {
610
524
  throw new RegisterError(response.status, 'Register response body is not valid JSON');
611
525
  };
612
526
 
613
- /**
614
- * Frame logging is metadata-only (ZGA-538): message type, request ids, byte
615
- * size — never the frame body. Task frames carry customer input/output and the
616
- * hello carries the session key, so a content dump here would hand both to any
617
- * crash reporter watching the host console.
618
- */
619
- const frameType = (frame) => {
620
- if (frame && typeof frame === 'object') {
621
- const candidate = frame.type;
622
- if (typeof candidate === 'string' && candidate.length > 0)
623
- return candidate;
624
- if (Array.isArray(frame.requests))
625
- return 'task_batch';
626
- }
627
- return 'unknown';
628
- };
629
527
  class WebSocketClient {
630
528
  constructor(options) {
631
529
  this.options = options;
632
530
  this.logger = getLogger();
633
531
  this.pingTimer = null;
532
+ this.consoleWithVerbose = console;
634
533
  this.handleOpen = () => {
635
534
  this.logger.info('WebSocket connection opened');
636
535
  this.options.onOpen?.();
536
+ this.logger.debug('Sending hello message:', this.options.hello);
537
+ this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
637
538
  this.send(this.options.hello);
638
539
  // Keepalive starts only once the hello is on the wire.
639
540
  this.startPing();
640
541
  if (this.options.ack) {
641
542
  // Send readiness/error ack immediately after hello.
543
+ this.logger.info('[WS OUT] hello_ack:', JSON.stringify(this.options.ack));
642
544
  this.send(this.options.ack);
643
545
  if (this.options.closeAfterAck) {
644
546
  // Optionally close after ack (used for error cases).
@@ -660,23 +562,24 @@ class WebSocketClient {
660
562
  if (trimmed === 'pong')
661
563
  return;
662
564
  if (trimmed.length > 0 && trimmed[0] !== '{' && trimmed[0] !== '[') {
663
- this.logger.debug('[WS IN] ignoring non-JSON frame', { bytes: trimmed.length });
565
+ this.logger.debug('[WS IN] ignoring non-JSON frame:', trimmed.slice(0, 64));
664
566
  return;
665
567
  }
666
568
  }
667
569
  try {
668
570
  const data = JSON.parse(raw);
669
- this.logger.debug('[WS IN] frame', {
670
- type: frameType(data),
671
- requests: Array.isArray(data.requests)
672
- ? data.requests.length
673
- : undefined,
674
- bytes: typeof raw === 'string' ? raw.length : undefined
675
- });
571
+ if (this.logger.isEnabled()) {
572
+ if (typeof this.consoleWithVerbose.verbose === 'function') {
573
+ this.consoleWithVerbose.verbose('[ZeroGPU]', '[WS IN] payload:', data);
574
+ }
575
+ else {
576
+ console.debug('[ZeroGPU]', '[WS IN] payload:', data);
577
+ }
578
+ }
676
579
  this.options.onMessage(data);
677
580
  }
678
581
  catch (error) {
679
- this.logger.error('Failed to parse WS message', { error: summarizeError(error) });
582
+ this.logger.error('Failed to parse WS message', error);
680
583
  }
681
584
  };
682
585
  this.handleError = (event) => {
@@ -701,7 +604,7 @@ class WebSocketClient {
701
604
  this.options.onClose(event);
702
605
  };
703
606
  this.pingIntervalMs = normalizePingIntervalMs(options.pingIntervalSeconds);
704
- this.logger.info('Creating WebSocket connection', { url: options.url });
607
+ this.logger.info('Creating WebSocket connection to:', options.url);
705
608
  this.socket = new WebSocket(options.url);
706
609
  this.socket.onopen = this.handleOpen;
707
610
  this.socket.onmessage = this.handleMessage;
@@ -735,7 +638,7 @@ class WebSocketClient {
735
638
  this.socket.send('ping');
736
639
  }
737
640
  catch (error) {
738
- this.logger.debug('Keepalive ping failed', { error: summarizeError(error) });
641
+ this.logger.debug('Keepalive ping failed', error);
739
642
  }
740
643
  try {
741
644
  this.options.onPingTick?.();
@@ -755,13 +658,8 @@ class WebSocketClient {
755
658
  return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
756
659
  }
757
660
  send(payload) {
758
- const json = JSON.stringify(payload);
759
- this.logger.debug('[WS OUT] frame', {
760
- type: frameType(payload),
761
- requests: Array.isArray(payload.requests) ? payload.requests.length : undefined,
762
- bytes: json.length
763
- });
764
- this.socket.send(json);
661
+ this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
662
+ this.socket.send(JSON.stringify(payload));
765
663
  }
766
664
  close(code, reason) {
767
665
  this.stopPing();
@@ -1338,7 +1236,8 @@ const resolveWasmSettings = (probe = probeWasmEnvironment()) => {
1338
1236
  * Host-facing lifecycle status and events. The SDK is a guest in someone
1339
1237
  * else's app: this module is how the host observes guardrail state (degraded /
1340
1238
  * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1341
- * consumers get the same signals as `zerogpu:*` window events.
1239
+ * consumers get the same signals as `zerogpu:*` window events, matching the
1240
+ * existing `zerogpu:cameraPreview` pattern.
1342
1241
  */
1343
1242
  let lifecycleStatus = 'starting';
1344
1243
  const listeners = {
@@ -2178,7 +2077,7 @@ const executeSingleRequest = async (request) => {
2178
2077
  };
2179
2078
  }
2180
2079
  catch (error) {
2181
- logger.error('Task failed', { error: summarizeError(error) });
2080
+ logger.error('Task failed', error);
2182
2081
  const message = error.message ?? '';
2183
2082
  const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
2184
2083
  getEventReporter().report('task.failed', {
@@ -2257,15 +2156,12 @@ const handleIncomingMessage = async (msg) => {
2257
2156
  const results = [];
2258
2157
  for (const request of msg.requests) {
2259
2158
  const result = await executeSingleRequest(request);
2260
- // Metadata only (ZGA-538): the response body is customer model output
2261
- // and must never reach the console — log its size instead.
2262
- logger.info('[WS OUT] task result', {
2159
+ logger.info('[WS OUT] task result:', {
2263
2160
  requestId: result.requestId,
2264
2161
  modelId: result.modelId,
2265
- responseBytes: JSON.stringify(result.response ?? null).length,
2266
- processingTimeMs: result.metadata.processingTime,
2162
+ response: result.response,
2267
2163
  error: result.error,
2268
- errorMessage: result.errorMessage || undefined
2164
+ errorMessage: result.errorMessage
2269
2165
  });
2270
2166
  results.push(result);
2271
2167
  }
@@ -2757,7 +2653,7 @@ const scheduleReconnect = (options, reason) => {
2757
2653
  }
2758
2654
  logger.info('[WS] Re-registration timer fired; restarting lifecycle');
2759
2655
  startLifecycle(options).catch((err) => {
2760
- logger.error('[WS] Re-registration attempt failed; will retry', { error: summarizeError(err) });
2656
+ logger.error('[WS] Re-registration attempt failed; will retry', err);
2761
2657
  // Keep the loop alive on transient failures (register/network/model
2762
2658
  // errors). Auth failures and crash-loop cool-downs return cleanly from
2763
2659
  // startLifecycle without throwing, so they end the loop here.
@@ -2785,7 +2681,7 @@ const triggerFullReregister = (options, reason) => {
2785
2681
  // Best effort — the register flow below supersedes the session anyway.
2786
2682
  }
2787
2683
  startLifecycle(options).catch((err) => {
2788
- logger.error('[WS] Full re-register failed; scheduling retry', { error: summarizeError(err) });
2684
+ logger.error('[WS] Full re-register failed; scheduling retry', err);
2789
2685
  scheduleReconnect(options, 'socket_closed');
2790
2686
  });
2791
2687
  };
@@ -2821,7 +2717,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2821
2717
  };
2822
2718
  // Deterministic preflight validation runs before the crash-loop guard so a
2823
2719
  // misconfigured integration never consumes a crash-loop attempt (and never
2824
- // triggers the geolocation prompt below).
2720
+ // triggers the camera/geo prompts below).
2825
2721
  if (!edgeOperatorKey) {
2826
2722
  throw new Error('Missing required header: x-edge-operator-key');
2827
2723
  }
@@ -2856,24 +2752,39 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2856
2752
  providedDeviceId: Boolean(providedDeviceId),
2857
2753
  orchestrator: config.orchestrator?.baseUrl
2858
2754
  });
2859
- const deviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2860
- setDeviceContext(deviceId, deviceInfo);
2755
+ const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2756
+ const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
2757
+ setDeviceContext(deviceId, sanitizedDeviceInfo);
2861
2758
  initEventReporter({
2862
2759
  enabled: config.telemetry.events,
2863
2760
  endpointUrl: `${config.orchestrator.baseUrl}${config.orchestrator.eventsPath}`,
2864
2761
  operatorKey: edgeOperatorKey,
2865
2762
  deviceId,
2866
2763
  sdkVersion: config.sdkVersion,
2867
- platform: deviceInfo.platform
2764
+ platform: sanitizedDeviceInfo.platform
2868
2765
  });
2869
2766
  const reporter = getEventReporter();
2870
2767
  reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2871
2768
  reportCrashFromPreviousSession(guard.crash);
2872
2769
  logger.info('[Init] Device info collected', {
2873
- platform: deviceInfo.platform,
2874
- deviceType: deviceInfo.deviceType,
2875
- gpuRenderer: deviceInfo.gpuRenderer
2770
+ platform: sanitizedDeviceInfo.platform,
2771
+ deviceType: sanitizedDeviceInfo.deviceType,
2772
+ gpuRenderer: sanitizedDeviceInfo.gpuRenderer
2876
2773
  });
2774
+ if (rawDeviceInfo.camera?.previewDataUrl) {
2775
+ try {
2776
+ window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
2777
+ detail: {
2778
+ deviceId,
2779
+ previewDataUrl: rawDeviceInfo.camera.previewDataUrl,
2780
+ camera: sanitizedDeviceInfo.camera
2781
+ }
2782
+ }));
2783
+ }
2784
+ catch {
2785
+ logger.warn('Unable to dispatch camera preview event');
2786
+ }
2787
+ }
2877
2788
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
2878
2789
  setCachedModelId(cachedModelId);
2879
2790
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
@@ -3047,7 +2958,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3047
2958
  cachedModels: cachedInfo && !cacheInvalid
3048
2959
  ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
3049
2960
  : [],
3050
- device: deviceInfo
2961
+ device: sanitizedDeviceInfo
3051
2962
  };
3052
2963
  let registerResponse;
3053
2964
  let assignedModels = [];
@@ -3058,7 +2969,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3058
2969
  let postRegisterSample;
3059
2970
  logger.info('[Register] Sending register request', {
3060
2971
  deviceId,
3061
- cachedModels: registerPayload.cachedModels.map((model) => model.modelId),
2972
+ cachedModels: registerPayload.cachedModels,
3062
2973
  sdkVersion: config.sdkVersion
3063
2974
  });
3064
2975
  reporter.report('register.started');
@@ -3109,10 +3020,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3109
3020
  // TODO(global-types): emit ws.policy_applied once available in the shared
3110
3021
  // event vocabulary (data: {source: 'register', v, changed}).
3111
3022
  if (registrationSettings) {
3112
- // Keys only: served settings are operator config, not for host consoles.
3113
- logger.info('[Register] Registration settings received', {
3114
- keys: Object.keys(registrationSettings)
3115
- });
3023
+ logger.info('[Register] Registration settings received', registrationSettings);
3116
3024
  }
3117
3025
  if (registerResponse.refusalReason) {
3118
3026
  // The server deliberately declined this device (admission rules) — the
@@ -3131,7 +3039,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3131
3039
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
3132
3040
  markRegisterSuccess();
3133
3041
  reporter.setSessionKey(registerResponse.sessionKey);
3134
- logger.info('Register response received', {
3042
+ logger.info('Register response received:', {
3135
3043
  deviceId: registerResponse.deviceId,
3136
3044
  wsUrl: registerResponse.wsUrl
3137
3045
  });
@@ -3150,8 +3058,13 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3150
3058
  }
3151
3059
  logger.info('[Register] Models assigned', {
3152
3060
  count: assignedModels.length,
3153
- models: assignedModels.map((m) => m.modelId),
3154
- totalBytes: assignedModels.reduce((sum, m) => sum + (m.sizeBytes ?? 0), 0)
3061
+ models: assignedModels.map((m) => ({
3062
+ modelId: m.modelId,
3063
+ framework: m.inferenceFramework,
3064
+ taskType: m.taskType,
3065
+ quantized: m.quantized,
3066
+ sizeBytes: m.sizeBytes
3067
+ }))
3155
3068
  });
3156
3069
  for (const model of assignedModels) {
3157
3070
  modelStatuses[getModelStatusKey(model)] = 'idle';
@@ -3169,10 +3082,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3169
3082
  setModelInfosByModelId(modelInfosByModelId);
3170
3083
  setModelInfo(primaryModel);
3171
3084
  setSample(primaryModel.sample);
3172
- // ZGA-538: no session key (credential) and no sample body (task content).
3173
3085
  logger.info('Runtime globals updated from register response', {
3086
+ sessionKey: registerResponse.sessionKey,
3174
3087
  taskType: primaryModel.taskType,
3175
- hasSample: Boolean(primaryModel.sample)
3088
+ sample: primaryModel.sample
3176
3089
  });
3177
3090
  if (!cachedInfo || cachedInfo.modelId !== primaryModel.modelId || cacheInvalid) {
3178
3091
  if (cachedInfo && cachedInfo.modelId !== primaryModel.modelId) {
@@ -3445,7 +3358,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3445
3358
  };
3446
3359
  logger.info('[WS] Connecting WebSocket', {
3447
3360
  wsUrl: registerResponse.wsUrl,
3448
- models: helloSlmConfig.map((model) => `${model.modelId}:${model.status}`)
3361
+ models: helloSlmConfig
3449
3362
  });
3450
3363
  reporter.report('ws.connect_started');
3451
3364
  const connectionPolicy = getConnectionPolicy();
@@ -3476,12 +3389,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3476
3389
  }
3477
3390
  else if ('type' in message && message.type === 'hello_ack') {
3478
3391
  const ack = message;
3479
- // Fields, not the frame — the ack echoes the session key.
3480
- logger.info('[WS] Received hello_ack', {
3481
- status: ack.status,
3482
- deviceId: ack.deviceId,
3483
- errorMessage: ack.errorMessage
3484
- });
3392
+ logger.info('[WS] Received hello_ack', ack);
3485
3393
  reporter.report('ws.hello_ack', {
3486
3394
  code: ack.status,
3487
3395
  message: ack.errorMessage
@@ -3524,9 +3432,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3524
3432
  }, delayMs);
3525
3433
  }
3526
3434
  else {
3527
- logger.debug('[WS] Unhandled message', {
3528
- type: 'type' in message && typeof message.type === 'string' ? message.type : 'unknown'
3529
- });
3435
+ logger.debug('[WS] Unhandled message', message);
3530
3436
  }
3531
3437
  },
3532
3438
  onClose: (event) => {
@@ -3778,6 +3684,15 @@ const reportInitFailureOverWebSocket = async (options) => {
3778
3684
  }
3779
3685
  });
3780
3686
  };
3687
+ const stripCameraPreview = (info) => {
3688
+ if (!info.camera?.previewDataUrl) {
3689
+ return info;
3690
+ }
3691
+ return {
3692
+ ...info,
3693
+ camera: { ...info.camera, previewDataUrl: undefined }
3694
+ };
3695
+ };
3781
3696
 
3782
3697
  const measure = async (fn) => {
3783
3698
  const start = performance.now();
@@ -3787,6 +3702,12 @@ const measure = async (fn) => {
3787
3702
 
3788
3703
  const TRANSFORMERS_CDN = 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js';
3789
3704
  let transformersRuntimePromise = null;
3705
+ const serializeError$5 = (error) => {
3706
+ if (error instanceof Error) {
3707
+ return { name: error.name, message: error.message, stack: error.stack };
3708
+ }
3709
+ return { message: String(error) };
3710
+ };
3790
3711
  const ensureTransformersRuntime = () => {
3791
3712
  if (window.TransformersPipeline) {
3792
3713
  return Promise.resolve();
@@ -3822,7 +3743,7 @@ const ensureTransformersRuntime = () => {
3822
3743
  transformersRuntimePromise = null;
3823
3744
  logger.error('[SLM] Failed to import Transformers runtime', {
3824
3745
  runtimeUrl: TRANSFORMERS_CDN,
3825
- error: summarizeError(error)
3746
+ error: serializeError$5(error)
3826
3747
  });
3827
3748
  throw error;
3828
3749
  }
@@ -3931,7 +3852,7 @@ const probeOnnxWasmOverridePath = async (fetchImpl) => {
3931
3852
  }
3932
3853
  if (sawNonWasmPayloadAtBase) {
3933
3854
  getLogger().warn('[SLM] ONNX wasm probe got non-wasm payload', {
3934
- url: baseWithSlash
3855
+ wasmBase: baseWithSlash
3935
3856
  });
3936
3857
  }
3937
3858
  }
@@ -3959,6 +3880,12 @@ const withTransformersEnvLock = async (work) => {
3959
3880
  }
3960
3881
  };
3961
3882
 
3883
+ const serializeError$4 = (error) => {
3884
+ if (error instanceof Error) {
3885
+ return { name: error.name, message: error.message, stack: error.stack };
3886
+ }
3887
+ return { message: String(error) };
3888
+ };
3962
3889
  const sessionCache = {};
3963
3890
  const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requiredFiles, originalFetch) => {
3964
3891
  const requiredFileList = requiredFiles
@@ -4058,7 +3985,7 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4058
3985
  logger.error('[SLM][fetch] non-model wasm/ort request failed', {
4059
3986
  modelId,
4060
3987
  requestUrl: originalRequestUrl,
4061
- error: summarizeError(error)
3988
+ error: serializeError$4(error)
4062
3989
  });
4063
3990
  throw error;
4064
3991
  }
@@ -4066,7 +3993,7 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4066
3993
  const relative = resolveRequestedRelative(requestedRelative);
4067
3994
  if (!relative) {
4068
3995
  logger.warn('[SLM] Unexpected model file request; falling back to original fetch', {
4069
- file: requestedRelative,
3996
+ requestedRelative,
4070
3997
  modelId
4071
3998
  });
4072
3999
  return originalFetch(url, init);
@@ -4114,11 +4041,10 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4114
4041
  // That string means "every candidate URL threw", i.e. a network/abort
4115
4042
  // failure against the real model host — not an upstream 502 and not a
4116
4043
  // malformed URL actually being requested.
4117
- logger.warn('[SLM] Model file fetch failed', {
4044
+ logger.warn(`[SLM] Model file fetch failed for ${relative}`, {
4118
4045
  modelId,
4119
- file: relative,
4120
- candidateCount: requestUrls.length,
4121
- error: summarizeError(err)
4046
+ candidates: requestUrls,
4047
+ error: serializeError$4(err)
4122
4048
  });
4123
4049
  return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
4124
4050
  }
@@ -4131,6 +4057,12 @@ const TASK_PIPELINE_MAP = {
4131
4057
  classification: 'zero-shot-classification',
4132
4058
  text_generation: 'text2text-generation'
4133
4059
  };
4060
+ const serializeError$3 = (error) => {
4061
+ if (error instanceof Error) {
4062
+ return { name: error.name, message: error.message, stack: error.stack };
4063
+ }
4064
+ return { message: String(error) };
4065
+ };
4134
4066
  const isInvalidArrayLengthError = (error) => {
4135
4067
  const message = error instanceof Error ? error.message : String(error);
4136
4068
  return message.toLowerCase().includes('invalid array length');
@@ -4502,7 +4434,7 @@ const loadOnnxAdapter = async (slm, options) => {
4502
4434
  modelRepoId: slm.modelRepoId,
4503
4435
  modelUrl: slm.modelUrl,
4504
4436
  requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
4505
- error: summarizeError(error)
4437
+ error: serializeError$3(error)
4506
4438
  });
4507
4439
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4508
4440
  return { error: error, metrics: {} };
@@ -4523,6 +4455,12 @@ registerAdapter(factory$2);
4523
4455
 
4524
4456
  const DEFAULT_THRESHOLD = 0.4;
4525
4457
  const DEFAULT_MASK = '[REDACTED]';
4458
+ const serializeError$2 = (error) => {
4459
+ if (error instanceof Error) {
4460
+ return { name: error.name, message: error.message, stack: error.stack };
4461
+ }
4462
+ return { message: String(error) };
4463
+ };
4526
4464
  const parseTokenClassificationOutput = (raw, sourceText) => {
4527
4465
  if (!Array.isArray(raw))
4528
4466
  return [];
@@ -4785,7 +4723,7 @@ const loadTransformersAdapter = async (slm, options) => {
4785
4723
  modelVersion: slm.modelVersion,
4786
4724
  modelRepoId: slm.modelRepoId,
4787
4725
  modelUrl: slm.modelUrl,
4788
- error: summarizeError(error)
4726
+ error: serializeError$2(error)
4789
4727
  });
4790
4728
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4791
4729
  return { error: error, metrics: {} };
@@ -4804,6 +4742,12 @@ registerAdapter(factory$1);
4804
4742
 
4805
4743
  const WLLAMA_CDN = 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js';
4806
4744
  let wllamaRuntimePromise = null;
4745
+ const serializeError$1 = (error) => {
4746
+ if (error instanceof Error) {
4747
+ return { name: error.name, message: error.message, stack: error.stack };
4748
+ }
4749
+ return { message: String(error) };
4750
+ };
4807
4751
  const ensureWllamaRuntime = () => {
4808
4752
  if (window.WllamaModule) {
4809
4753
  return Promise.resolve(window.WllamaModule);
@@ -4822,7 +4766,7 @@ const ensureWllamaRuntime = () => {
4822
4766
  wllamaRuntimePromise = null;
4823
4767
  getLogger().error('[GGUF] Failed to import wllama runtime', {
4824
4768
  runtimeUrl: WLLAMA_CDN,
4825
- error: summarizeError(error)
4769
+ error: serializeError$1(error)
4826
4770
  });
4827
4771
  throw error;
4828
4772
  }
@@ -4833,6 +4777,12 @@ const ensureWllamaRuntime = () => {
4833
4777
  const WLLAMA_CDN_BASE = WLLAMA_CDN.replace(/\/esm\/index\.js$/, '/esm');
4834
4778
 
4835
4779
  const DEFAULT_MAX_NEW_TOKENS = 128;
4780
+ const serializeError = (error) => {
4781
+ if (error instanceof Error) {
4782
+ return { name: error.name, message: error.message, stack: error.stack };
4783
+ }
4784
+ return { message: String(error) };
4785
+ };
4836
4786
  const pickGgufFileName = (requiredFiles) => {
4837
4787
  if (!Array.isArray(requiredFiles) || requiredFiles.length === 0)
4838
4788
  return null;
@@ -5037,7 +4987,7 @@ const loadGgufAdapter = async (slm, options) => {
5037
4987
  modelId: slm.modelId,
5038
4988
  modelVersion: slm.modelVersion,
5039
4989
  modelUrl: slm.modelUrl,
5040
- error: summarizeError(error)
4990
+ error: serializeError(error)
5041
4991
  });
5042
4992
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
5043
4993
  return { error: error, metrics: {} };
@@ -5077,9 +5027,7 @@ const initZeroGpuSdk = async (options) => {
5077
5027
  if (options?.resourcePolicy) {
5078
5028
  setResourcePolicy(options.resourcePolicy);
5079
5029
  if (options.resourcePolicy.disableGuardrails) {
5080
- // Loud by design: a host running without guardrails should know it, even
5081
- // with console logs disabled. Static text only — nothing to redact.
5082
- // eslint-disable-next-line no-console
5030
+ // Loud by design: a host running without guardrails should know it.
5083
5031
  console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
5084
5032
  }
5085
5033
  }
@@ -5095,7 +5043,7 @@ const initZeroGpuSdk = async (options) => {
5095
5043
  catch (err) {
5096
5044
  // Already reported inside the lifecycle (register.failed / sdk.init_failed
5097
5045
  // / init-failure hello); surface for the host without throwing into it.
5098
- getLogger().error('[Init] SDK initialization failed', { error: summarizeError(err) });
5046
+ getLogger().error('[Init] SDK initialization failed', err);
5099
5047
  }
5100
5048
  return handle;
5101
5049
  };
@@ -5217,9 +5165,7 @@ const autoInitFromScriptTag = () => {
5217
5165
  // the integrator asked for logs — the failure is reported as an
5218
5166
  // `sdk.init_failed` device event regardless.
5219
5167
  if (enableConsoleLogs) {
5220
- // Pre-logger fallback; the error is a summarized diagnostic, never payload.
5221
- // eslint-disable-next-line no-console
5222
- console.error('[ZeroGpuSdk] Auto-init failed', error instanceof Error ? `${error.name}: ${error.message}` : String(error));
5168
+ console.error('[ZeroGpuSdk] Auto-init failed', error);
5223
5169
  }
5224
5170
  });
5225
5171
  };