@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.
@@ -4,8 +4,8 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ZeroGpuBrowserSdk = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
- const SDK_VERSION = typeof "0.2.1-dev.202608131557.g7df119f+7df119f" === 'string' && "0.2.1-dev.202608131557.g7df119f+7df119f".length > 0
8
- ? "0.2.1-dev.202608131557.g7df119f+7df119f"
7
+ const SDK_VERSION = typeof "0.2.1+8a18008" === 'string' && "0.2.1+8a18008".length > 0
8
+ ? "0.2.1+8a18008"
9
9
  : '0.0.0-dev';
10
10
 
11
11
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -27,6 +27,7 @@
27
27
  telemetry: {
28
28
  enableConsoleLogs: false,
29
29
  locationData: false,
30
+ cameraData: false,
30
31
  events: true
31
32
  }
32
33
  };
@@ -44,8 +45,7 @@
44
45
  telemetry: {
45
46
  enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
46
47
  locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
47
- // `cameraData` is deliberately dropped: the camera path no longer exists
48
- // (ZGA-538); a host that still passes the flag is silently ignored.
48
+ cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData),
49
49
  events: asBoolean(merged.telemetry?.events, base.telemetry.events)
50
50
  }
51
51
  };
@@ -74,152 +74,6 @@
74
74
  const asNonEmptyString = (value, fallback) => typeof value === 'string' && value.length > 0 ? value : fallback;
75
75
  const asBoolean = (value, fallback) => typeof value === 'boolean' ? value : fallback;
76
76
 
77
- const MESSAGE_MAX = 200;
78
- const ID_MAX = 256;
79
- const ARRAY_MAX = 20;
80
- /** Keys that must never print their value, whatever it is. */
81
- const CREDENTIAL_KEY_PATTERN = /(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i;
82
- /** Keys whose string value is a URL: keep origin + path, drop query/hash. */
83
- const URL_KEYS = new Set([
84
- 'url',
85
- 'wsurl',
86
- 'baseurl',
87
- 'modelurl',
88
- 'modelrepourl',
89
- 'runtimeurl',
90
- 'requesturl',
91
- 'endpoint',
92
- 'endpointurl',
93
- 'manifesturl',
94
- 'bundleurl',
95
- 'orchestrator'
96
- ]);
97
- /** Keys carrying an error/diagnostic summary: kept, capped. */
98
- const MESSAGE_KEYS = new Set(['message', 'errormessage', 'error', 'reason']);
99
- /** Identifier / enum-like keys whose string value is safe to print (capped). */
100
- const SAFE_STRING_KEYS = new Set([
101
- 'requestid',
102
- 'modelid',
103
- 'modelversion',
104
- 'modelrepoid',
105
- 'modeltype',
106
- 'deviceid',
107
- 'sdkversion',
108
- 'tasktype',
109
- 'framework',
110
- 'inferenceframework',
111
- 'quantization',
112
- 'code',
113
- 'status',
114
- 'type',
115
- 'phase',
116
- 'flow',
117
- 'event',
118
- 'source',
119
- 'name',
120
- 'platform',
121
- 'devicetype',
122
- 'gpurenderer',
123
- 'mime',
124
- 'mode',
125
- 'file',
126
- 'files',
127
- 'requiredfiles',
128
- 'models',
129
- 'cachedmodels',
130
- 'keys',
131
- 'changed',
132
- 'cachedmodelid',
133
- 'assignedmodelid',
134
- 'primarymodelid'
135
- ]);
136
- const cap = (value, max) => value.length > max ? `${value.slice(0, max)}…` : value;
137
- /** One-line, capped error summary — diagnostics survive, payloads cannot ride along uncapped. */
138
- const summarizeError = (error) => {
139
- if (error instanceof Error) {
140
- return cap(`${error.name}: ${error.message}`, MESSAGE_MAX);
141
- }
142
- if (typeof error === 'string')
143
- return cap(error, MESSAGE_MAX);
144
- if (error === null || error === undefined)
145
- return String(error);
146
- if (typeof error === 'object')
147
- return `[${error.constructor?.name ?? 'object'}]`;
148
- return cap(String(error), MESSAGE_MAX);
149
- };
150
- const stripUrl = (value) => {
151
- try {
152
- const url = new URL(value);
153
- return `${url.origin}${url.pathname}`;
154
- }
155
- catch {
156
- return '[invalid-url]';
157
- }
158
- };
159
- const describeOpaque = (value) => {
160
- if (Array.isArray(value))
161
- return `[array:${value.length}]`;
162
- if (value && typeof value === 'object')
163
- return `[object:${Object.keys(value).length} keys]`;
164
- return `[${typeof value}]`;
165
- };
166
- const sanitizeString = (key, value) => {
167
- const normalizedKey = key.toLowerCase();
168
- if (URL_KEYS.has(normalizedKey))
169
- return stripUrl(value);
170
- if (MESSAGE_KEYS.has(normalizedKey))
171
- return cap(value, MESSAGE_MAX);
172
- if (SAFE_STRING_KEYS.has(normalizedKey))
173
- return cap(value, ID_MAX);
174
- return `[string:${value.length}]`;
175
- };
176
- const sanitizeValue = (key, value) => {
177
- if (CREDENTIAL_KEY_PATTERN.test(key))
178
- return '[redacted]';
179
- if (value === null || value === undefined)
180
- return value;
181
- if (typeof value === 'boolean')
182
- return value;
183
- if (typeof value === 'number')
184
- return Number.isFinite(value) ? value : String(value);
185
- if (typeof value === 'string')
186
- return sanitizeString(key, value);
187
- if (value instanceof Error)
188
- return summarizeError(value);
189
- return describeOpaque(value);
190
- };
191
- /**
192
- * The runtime redaction gate. Whatever a caller manages to pass (the types
193
- * merely guide), nothing but ids, enums, counts, sizes, durations and capped
194
- * error summaries comes out the other side.
195
- */
196
- const sanitizeLogFields = (fields) => {
197
- if (fields instanceof Error) {
198
- return { error: summarizeError(fields) };
199
- }
200
- if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
201
- return { detail: sanitizeValue('detail', fields) };
202
- }
203
- const sanitized = {};
204
- for (const [key, value] of Object.entries(fields)) {
205
- if (Array.isArray(value)) {
206
- if (CREDENTIAL_KEY_PATTERN.test(key)) {
207
- sanitized[key] = '[redacted]';
208
- }
209
- else if (value.every((item) => item === null || typeof item !== 'object')) {
210
- sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue(key, item));
211
- }
212
- else {
213
- sanitized[key] = describeOpaque(value);
214
- }
215
- continue;
216
- }
217
- sanitized[key] = sanitizeValue(key, value);
218
- }
219
- return sanitized;
220
- };
221
- const sanitizeMessage = (message) => typeof message === 'string' ? cap(message, MESSAGE_MAX) : '[invalid log message]';
222
- /* eslint-disable no-console -- sole audited console sink; everything printed here has passed sanitizeLogFields. */
223
77
  class Logger {
224
78
  constructor(config) {
225
79
  this.enabled = config.enableConsoleLogs;
@@ -230,28 +84,21 @@
230
84
  isEnabled() {
231
85
  return this.enabled;
232
86
  }
233
- emit(sink, message, fields) {
234
- if (!this.enabled)
235
- return;
236
- if (fields === undefined) {
237
- sink('[ZeroGPU]', sanitizeMessage(message));
238
- }
239
- else {
240
- sink('[ZeroGPU]', sanitizeMessage(message), sanitizeLogFields(fields));
241
- }
87
+ debug(...args) {
88
+ if (this.enabled)
89
+ console.debug('[ZeroGPU]', ...args);
242
90
  }
243
- debug(message, fields) {
244
- this.emit(console.debug, message, fields);
91
+ info(...args) {
92
+ if (this.enabled)
93
+ console.debug('[ZeroGPU]', ...args);
245
94
  }
246
- info(message, fields) {
247
- // Historic behavior: info also goes to console.debug to keep host consoles quiet.
248
- this.emit(console.debug, message, fields);
95
+ warn(...args) {
96
+ if (this.enabled)
97
+ console.warn('[ZeroGPU]', ...args);
249
98
  }
250
- warn(message, fields) {
251
- this.emit(console.warn, message, fields);
252
- }
253
- error(message, fields) {
254
- this.emit(console.error, message, fields);
99
+ error(...args) {
100
+ if (this.enabled)
101
+ console.error('[ZeroGPU]', ...args);
255
102
  }
256
103
  }
257
104
  let singleton$1 = null;
@@ -264,6 +111,7 @@
264
111
  singleton$1 = new Logger({
265
112
  enableConsoleLogs: false,
266
113
  locationData: false,
114
+ cameraData: false,
267
115
  events: true
268
116
  });
269
117
  }
@@ -498,8 +346,77 @@
498
346
  // Optional permissions
499
347
  location: config.locationData ? await getLocation() : undefined
500
348
  };
349
+ if (config.cameraData) {
350
+ baseInfo.camera = await captureCameraSample();
351
+ }
501
352
  return baseInfo;
502
353
  };
354
+ const captureCameraSample = async () => {
355
+ if (!navigator.mediaDevices?.getUserMedia) {
356
+ return { permission: 'error', error: 'mediaDevices unavailable' };
357
+ }
358
+ let stream = null;
359
+ let video = null;
360
+ let canvas = null;
361
+ try {
362
+ stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
363
+ video = document.createElement('video');
364
+ video.setAttribute('playsinline', 'true');
365
+ video.playsInline = true;
366
+ video.muted = true;
367
+ video.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0';
368
+ document.body.appendChild(video);
369
+ video.srcObject = stream;
370
+ await video.play().catch(() => { });
371
+ await new Promise((resolve) => {
372
+ const ready = () => resolve();
373
+ video.onloadeddata = ready;
374
+ video.oncanplay = ready;
375
+ setTimeout(ready, 800);
376
+ });
377
+ const vw = video.videoWidth || 640;
378
+ const vh = video.videoHeight || 480;
379
+ canvas = document.createElement('canvas');
380
+ canvas.width = vw;
381
+ canvas.height = vh;
382
+ const ctx = canvas.getContext('2d');
383
+ ctx?.drawImage(video, 0, 0, vw, vh);
384
+ const mime = 'image/jpeg';
385
+ const dataUrl = canvas.toDataURL(mime, 0.85);
386
+ const bytes = Math.floor((dataUrl.length * 3) / 4);
387
+ return {
388
+ permission: 'granted',
389
+ width: vw,
390
+ height: vh,
391
+ bytes,
392
+ mime,
393
+ timestamp: Date.now(),
394
+ previewDataUrl: dataUrl
395
+ };
396
+ }
397
+ catch (err) {
398
+ const errorObj = err;
399
+ return {
400
+ permission: errorObj?.name === 'NotAllowedError' ? 'denied' : 'error',
401
+ error: errorObj?.message || String(err)
402
+ };
403
+ }
404
+ finally {
405
+ try {
406
+ stream?.getTracks().forEach((track) => track.stop());
407
+ }
408
+ catch {
409
+ // Best-effort cleanup.
410
+ }
411
+ try {
412
+ video?.remove();
413
+ }
414
+ catch {
415
+ // Best-effort cleanup.
416
+ }
417
+ canvas = null;
418
+ }
419
+ };
503
420
 
504
421
  class RegisterError extends Error {
505
422
  constructor(status, body) {
@@ -540,6 +457,14 @@
540
457
  }
541
458
  return null;
542
459
  };
460
+ const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
461
+ const buildCurl = (url, body, headers) => {
462
+ const payload = escapeShellSingleQuotes(JSON.stringify(body));
463
+ const headerFlags = Object.entries(headers)
464
+ .map(([key, value]) => `-H '${escapeShellSingleQuotes(`${key}: ${value}`)}'`)
465
+ .join(' ');
466
+ return `curl -X POST '${url}' ${headerFlags} -d '${payload}'`;
467
+ };
543
468
  const registerDevice = async (config, payload, auth) => {
544
469
  const logger = getLogger();
545
470
  const orchestrator = config?.orchestrator;
@@ -556,31 +481,20 @@
556
481
  headers,
557
482
  body: JSON.stringify(payload)
558
483
  });
559
- // ZGA-538: never log the request body or headers — the payload carries the
560
- // full device profile and the x-edge-operator-key credential.
561
- logger.info('Register request sent', {
562
- url,
563
- status: response.status,
564
- bodyBytes: JSON.stringify(payload).length
565
- });
484
+ logger.info('Register request sent:', { url, status: response.status });
485
+ getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
566
486
  const registerResponseBody = await parseRegisterResponseBody(response);
567
487
  const refusalReason = detectSoftRefusal(registerResponseBody);
568
488
  if (!response.ok && !refusalReason) {
569
489
  const text = typeof registerResponseBody === 'string'
570
490
  ? registerResponseBody
571
491
  : JSON.stringify(registerResponseBody ?? '');
572
- logger.error('Register request failed', { status: response.status, message: text });
492
+ logger.error('Register request failed:', { status: response.status, text });
573
493
  throw new RegisterError(response.status, text);
574
494
  }
575
495
  if (registerResponseBody && typeof registerResponseBody === 'object' && !refusalReason) {
576
496
  const registerResponse = registerResponseBody;
577
- // Shape only — the body carries the session key and the model sample text.
578
- logger.info('Register response parsed', {
579
- deviceId: registerResponse.deviceId,
580
- hasWsUrl: Boolean(registerResponse.wsUrl),
581
- models: registerResponse.slmConfig?.length ?? 0,
582
- ttlSeconds: registerResponse.ttlSeconds
583
- });
497
+ logger.info('Register response parsed:', registerResponse);
584
498
  return registerResponse;
585
499
  }
586
500
  if (refusalReason) {
@@ -614,35 +528,23 @@
614
528
  throw new RegisterError(response.status, 'Register response body is not valid JSON');
615
529
  };
616
530
 
617
- /**
618
- * Frame logging is metadata-only (ZGA-538): message type, request ids, byte
619
- * size — never the frame body. Task frames carry customer input/output and the
620
- * hello carries the session key, so a content dump here would hand both to any
621
- * crash reporter watching the host console.
622
- */
623
- const frameType = (frame) => {
624
- if (frame && typeof frame === 'object') {
625
- const candidate = frame.type;
626
- if (typeof candidate === 'string' && candidate.length > 0)
627
- return candidate;
628
- if (Array.isArray(frame.requests))
629
- return 'task_batch';
630
- }
631
- return 'unknown';
632
- };
633
531
  class WebSocketClient {
634
532
  constructor(options) {
635
533
  this.options = options;
636
534
  this.logger = getLogger();
637
535
  this.pingTimer = null;
536
+ this.consoleWithVerbose = console;
638
537
  this.handleOpen = () => {
639
538
  this.logger.info('WebSocket connection opened');
640
539
  this.options.onOpen?.();
540
+ this.logger.debug('Sending hello message:', this.options.hello);
541
+ this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
641
542
  this.send(this.options.hello);
642
543
  // Keepalive starts only once the hello is on the wire.
643
544
  this.startPing();
644
545
  if (this.options.ack) {
645
546
  // Send readiness/error ack immediately after hello.
547
+ this.logger.info('[WS OUT] hello_ack:', JSON.stringify(this.options.ack));
646
548
  this.send(this.options.ack);
647
549
  if (this.options.closeAfterAck) {
648
550
  // Optionally close after ack (used for error cases).
@@ -664,23 +566,24 @@
664
566
  if (trimmed === 'pong')
665
567
  return;
666
568
  if (trimmed.length > 0 && trimmed[0] !== '{' && trimmed[0] !== '[') {
667
- this.logger.debug('[WS IN] ignoring non-JSON frame', { bytes: trimmed.length });
569
+ this.logger.debug('[WS IN] ignoring non-JSON frame:', trimmed.slice(0, 64));
668
570
  return;
669
571
  }
670
572
  }
671
573
  try {
672
574
  const data = JSON.parse(raw);
673
- this.logger.debug('[WS IN] frame', {
674
- type: frameType(data),
675
- requests: Array.isArray(data.requests)
676
- ? data.requests.length
677
- : undefined,
678
- bytes: typeof raw === 'string' ? raw.length : undefined
679
- });
575
+ if (this.logger.isEnabled()) {
576
+ if (typeof this.consoleWithVerbose.verbose === 'function') {
577
+ this.consoleWithVerbose.verbose('[ZeroGPU]', '[WS IN] payload:', data);
578
+ }
579
+ else {
580
+ console.debug('[ZeroGPU]', '[WS IN] payload:', data);
581
+ }
582
+ }
680
583
  this.options.onMessage(data);
681
584
  }
682
585
  catch (error) {
683
- this.logger.error('Failed to parse WS message', { error: summarizeError(error) });
586
+ this.logger.error('Failed to parse WS message', error);
684
587
  }
685
588
  };
686
589
  this.handleError = (event) => {
@@ -705,7 +608,7 @@
705
608
  this.options.onClose(event);
706
609
  };
707
610
  this.pingIntervalMs = normalizePingIntervalMs(options.pingIntervalSeconds);
708
- this.logger.info('Creating WebSocket connection', { url: options.url });
611
+ this.logger.info('Creating WebSocket connection to:', options.url);
709
612
  this.socket = new WebSocket(options.url);
710
613
  this.socket.onopen = this.handleOpen;
711
614
  this.socket.onmessage = this.handleMessage;
@@ -739,7 +642,7 @@
739
642
  this.socket.send('ping');
740
643
  }
741
644
  catch (error) {
742
- this.logger.debug('Keepalive ping failed', { error: summarizeError(error) });
645
+ this.logger.debug('Keepalive ping failed', error);
743
646
  }
744
647
  try {
745
648
  this.options.onPingTick?.();
@@ -759,13 +662,8 @@
759
662
  return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
760
663
  }
761
664
  send(payload) {
762
- const json = JSON.stringify(payload);
763
- this.logger.debug('[WS OUT] frame', {
764
- type: frameType(payload),
765
- requests: Array.isArray(payload.requests) ? payload.requests.length : undefined,
766
- bytes: json.length
767
- });
768
- this.socket.send(json);
665
+ this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
666
+ this.socket.send(JSON.stringify(payload));
769
667
  }
770
668
  close(code, reason) {
771
669
  this.stopPing();
@@ -1342,7 +1240,8 @@
1342
1240
  * Host-facing lifecycle status and events. The SDK is a guest in someone
1343
1241
  * else's app: this module is how the host observes guardrail state (degraded /
1344
1242
  * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1345
- * consumers get the same signals as `zerogpu:*` window events.
1243
+ * consumers get the same signals as `zerogpu:*` window events, matching the
1244
+ * existing `zerogpu:cameraPreview` pattern.
1346
1245
  */
1347
1246
  let lifecycleStatus = 'starting';
1348
1247
  const listeners = {
@@ -2182,7 +2081,7 @@
2182
2081
  };
2183
2082
  }
2184
2083
  catch (error) {
2185
- logger.error('Task failed', { error: summarizeError(error) });
2084
+ logger.error('Task failed', error);
2186
2085
  const message = error.message ?? '';
2187
2086
  const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
2188
2087
  getEventReporter().report('task.failed', {
@@ -2261,15 +2160,12 @@
2261
2160
  const results = [];
2262
2161
  for (const request of msg.requests) {
2263
2162
  const result = await executeSingleRequest(request);
2264
- // Metadata only (ZGA-538): the response body is customer model output
2265
- // and must never reach the console — log its size instead.
2266
- logger.info('[WS OUT] task result', {
2163
+ logger.info('[WS OUT] task result:', {
2267
2164
  requestId: result.requestId,
2268
2165
  modelId: result.modelId,
2269
- responseBytes: JSON.stringify(result.response ?? null).length,
2270
- processingTimeMs: result.metadata.processingTime,
2166
+ response: result.response,
2271
2167
  error: result.error,
2272
- errorMessage: result.errorMessage || undefined
2168
+ errorMessage: result.errorMessage
2273
2169
  });
2274
2170
  results.push(result);
2275
2171
  }
@@ -2761,7 +2657,7 @@
2761
2657
  }
2762
2658
  logger.info('[WS] Re-registration timer fired; restarting lifecycle');
2763
2659
  startLifecycle(options).catch((err) => {
2764
- logger.error('[WS] Re-registration attempt failed; will retry', { error: summarizeError(err) });
2660
+ logger.error('[WS] Re-registration attempt failed; will retry', err);
2765
2661
  // Keep the loop alive on transient failures (register/network/model
2766
2662
  // errors). Auth failures and crash-loop cool-downs return cleanly from
2767
2663
  // startLifecycle without throwing, so they end the loop here.
@@ -2789,7 +2685,7 @@
2789
2685
  // Best effort — the register flow below supersedes the session anyway.
2790
2686
  }
2791
2687
  startLifecycle(options).catch((err) => {
2792
- logger.error('[WS] Full re-register failed; scheduling retry', { error: summarizeError(err) });
2688
+ logger.error('[WS] Full re-register failed; scheduling retry', err);
2793
2689
  scheduleReconnect(options, 'socket_closed');
2794
2690
  });
2795
2691
  };
@@ -2825,7 +2721,7 @@
2825
2721
  };
2826
2722
  // Deterministic preflight validation runs before the crash-loop guard so a
2827
2723
  // misconfigured integration never consumes a crash-loop attempt (and never
2828
- // triggers the geolocation prompt below).
2724
+ // triggers the camera/geo prompts below).
2829
2725
  if (!edgeOperatorKey) {
2830
2726
  throw new Error('Missing required header: x-edge-operator-key');
2831
2727
  }
@@ -2860,24 +2756,39 @@
2860
2756
  providedDeviceId: Boolean(providedDeviceId),
2861
2757
  orchestrator: config.orchestrator?.baseUrl
2862
2758
  });
2863
- const deviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2864
- setDeviceContext(deviceId, deviceInfo);
2759
+ const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2760
+ const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
2761
+ setDeviceContext(deviceId, sanitizedDeviceInfo);
2865
2762
  initEventReporter({
2866
2763
  enabled: config.telemetry.events,
2867
2764
  endpointUrl: `${config.orchestrator.baseUrl}${config.orchestrator.eventsPath}`,
2868
2765
  operatorKey: edgeOperatorKey,
2869
2766
  deviceId,
2870
2767
  sdkVersion: config.sdkVersion,
2871
- platform: deviceInfo.platform
2768
+ platform: sanitizedDeviceInfo.platform
2872
2769
  });
2873
2770
  const reporter = getEventReporter();
2874
2771
  reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2875
2772
  reportCrashFromPreviousSession(guard.crash);
2876
2773
  logger.info('[Init] Device info collected', {
2877
- platform: deviceInfo.platform,
2878
- deviceType: deviceInfo.deviceType,
2879
- gpuRenderer: deviceInfo.gpuRenderer
2774
+ platform: sanitizedDeviceInfo.platform,
2775
+ deviceType: sanitizedDeviceInfo.deviceType,
2776
+ gpuRenderer: sanitizedDeviceInfo.gpuRenderer
2880
2777
  });
2778
+ if (rawDeviceInfo.camera?.previewDataUrl) {
2779
+ try {
2780
+ window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
2781
+ detail: {
2782
+ deviceId,
2783
+ previewDataUrl: rawDeviceInfo.camera.previewDataUrl,
2784
+ camera: sanitizedDeviceInfo.camera
2785
+ }
2786
+ }));
2787
+ }
2788
+ catch {
2789
+ logger.warn('Unable to dispatch camera preview event');
2790
+ }
2791
+ }
2881
2792
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
2882
2793
  setCachedModelId(cachedModelId);
2883
2794
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
@@ -3051,7 +2962,7 @@
3051
2962
  cachedModels: cachedInfo && !cacheInvalid
3052
2963
  ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
3053
2964
  : [],
3054
- device: deviceInfo
2965
+ device: sanitizedDeviceInfo
3055
2966
  };
3056
2967
  let registerResponse;
3057
2968
  let assignedModels = [];
@@ -3062,7 +2973,7 @@
3062
2973
  let postRegisterSample;
3063
2974
  logger.info('[Register] Sending register request', {
3064
2975
  deviceId,
3065
- cachedModels: registerPayload.cachedModels.map((model) => model.modelId),
2976
+ cachedModels: registerPayload.cachedModels,
3066
2977
  sdkVersion: config.sdkVersion
3067
2978
  });
3068
2979
  reporter.report('register.started');
@@ -3113,10 +3024,7 @@
3113
3024
  // TODO(global-types): emit ws.policy_applied once available in the shared
3114
3025
  // event vocabulary (data: {source: 'register', v, changed}).
3115
3026
  if (registrationSettings) {
3116
- // Keys only: served settings are operator config, not for host consoles.
3117
- logger.info('[Register] Registration settings received', {
3118
- keys: Object.keys(registrationSettings)
3119
- });
3027
+ logger.info('[Register] Registration settings received', registrationSettings);
3120
3028
  }
3121
3029
  if (registerResponse.refusalReason) {
3122
3030
  // The server deliberately declined this device (admission rules) — the
@@ -3135,7 +3043,7 @@
3135
3043
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
3136
3044
  markRegisterSuccess();
3137
3045
  reporter.setSessionKey(registerResponse.sessionKey);
3138
- logger.info('Register response received', {
3046
+ logger.info('Register response received:', {
3139
3047
  deviceId: registerResponse.deviceId,
3140
3048
  wsUrl: registerResponse.wsUrl
3141
3049
  });
@@ -3154,8 +3062,13 @@
3154
3062
  }
3155
3063
  logger.info('[Register] Models assigned', {
3156
3064
  count: assignedModels.length,
3157
- models: assignedModels.map((m) => m.modelId),
3158
- totalBytes: assignedModels.reduce((sum, m) => sum + (m.sizeBytes ?? 0), 0)
3065
+ models: assignedModels.map((m) => ({
3066
+ modelId: m.modelId,
3067
+ framework: m.inferenceFramework,
3068
+ taskType: m.taskType,
3069
+ quantized: m.quantized,
3070
+ sizeBytes: m.sizeBytes
3071
+ }))
3159
3072
  });
3160
3073
  for (const model of assignedModels) {
3161
3074
  modelStatuses[getModelStatusKey(model)] = 'idle';
@@ -3173,10 +3086,10 @@
3173
3086
  setModelInfosByModelId(modelInfosByModelId);
3174
3087
  setModelInfo(primaryModel);
3175
3088
  setSample(primaryModel.sample);
3176
- // ZGA-538: no session key (credential) and no sample body (task content).
3177
3089
  logger.info('Runtime globals updated from register response', {
3090
+ sessionKey: registerResponse.sessionKey,
3178
3091
  taskType: primaryModel.taskType,
3179
- hasSample: Boolean(primaryModel.sample)
3092
+ sample: primaryModel.sample
3180
3093
  });
3181
3094
  if (!cachedInfo || cachedInfo.modelId !== primaryModel.modelId || cacheInvalid) {
3182
3095
  if (cachedInfo && cachedInfo.modelId !== primaryModel.modelId) {
@@ -3449,7 +3362,7 @@
3449
3362
  };
3450
3363
  logger.info('[WS] Connecting WebSocket', {
3451
3364
  wsUrl: registerResponse.wsUrl,
3452
- models: helloSlmConfig.map((model) => `${model.modelId}:${model.status}`)
3365
+ models: helloSlmConfig
3453
3366
  });
3454
3367
  reporter.report('ws.connect_started');
3455
3368
  const connectionPolicy = getConnectionPolicy();
@@ -3480,12 +3393,7 @@
3480
3393
  }
3481
3394
  else if ('type' in message && message.type === 'hello_ack') {
3482
3395
  const ack = message;
3483
- // Fields, not the frame — the ack echoes the session key.
3484
- logger.info('[WS] Received hello_ack', {
3485
- status: ack.status,
3486
- deviceId: ack.deviceId,
3487
- errorMessage: ack.errorMessage
3488
- });
3396
+ logger.info('[WS] Received hello_ack', ack);
3489
3397
  reporter.report('ws.hello_ack', {
3490
3398
  code: ack.status,
3491
3399
  message: ack.errorMessage
@@ -3528,9 +3436,7 @@
3528
3436
  }, delayMs);
3529
3437
  }
3530
3438
  else {
3531
- logger.debug('[WS] Unhandled message', {
3532
- type: 'type' in message && typeof message.type === 'string' ? message.type : 'unknown'
3533
- });
3439
+ logger.debug('[WS] Unhandled message', message);
3534
3440
  }
3535
3441
  },
3536
3442
  onClose: (event) => {
@@ -3782,6 +3688,15 @@
3782
3688
  }
3783
3689
  });
3784
3690
  };
3691
+ const stripCameraPreview = (info) => {
3692
+ if (!info.camera?.previewDataUrl) {
3693
+ return info;
3694
+ }
3695
+ return {
3696
+ ...info,
3697
+ camera: { ...info.camera, previewDataUrl: undefined }
3698
+ };
3699
+ };
3785
3700
 
3786
3701
  const measure = async (fn) => {
3787
3702
  const start = performance.now();
@@ -3791,6 +3706,12 @@
3791
3706
 
3792
3707
  const TRANSFORMERS_CDN = 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js';
3793
3708
  let transformersRuntimePromise = null;
3709
+ const serializeError$5 = (error) => {
3710
+ if (error instanceof Error) {
3711
+ return { name: error.name, message: error.message, stack: error.stack };
3712
+ }
3713
+ return { message: String(error) };
3714
+ };
3794
3715
  const ensureTransformersRuntime = () => {
3795
3716
  if (window.TransformersPipeline) {
3796
3717
  return Promise.resolve();
@@ -3826,7 +3747,7 @@
3826
3747
  transformersRuntimePromise = null;
3827
3748
  logger.error('[SLM] Failed to import Transformers runtime', {
3828
3749
  runtimeUrl: TRANSFORMERS_CDN,
3829
- error: summarizeError(error)
3750
+ error: serializeError$5(error)
3830
3751
  });
3831
3752
  throw error;
3832
3753
  }
@@ -3935,7 +3856,7 @@
3935
3856
  }
3936
3857
  if (sawNonWasmPayloadAtBase) {
3937
3858
  getLogger().warn('[SLM] ONNX wasm probe got non-wasm payload', {
3938
- url: baseWithSlash
3859
+ wasmBase: baseWithSlash
3939
3860
  });
3940
3861
  }
3941
3862
  }
@@ -3963,6 +3884,12 @@
3963
3884
  }
3964
3885
  };
3965
3886
 
3887
+ const serializeError$4 = (error) => {
3888
+ if (error instanceof Error) {
3889
+ return { name: error.name, message: error.message, stack: error.stack };
3890
+ }
3891
+ return { message: String(error) };
3892
+ };
3966
3893
  const sessionCache = {};
3967
3894
  const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requiredFiles, originalFetch) => {
3968
3895
  const requiredFileList = requiredFiles
@@ -4062,7 +3989,7 @@
4062
3989
  logger.error('[SLM][fetch] non-model wasm/ort request failed', {
4063
3990
  modelId,
4064
3991
  requestUrl: originalRequestUrl,
4065
- error: summarizeError(error)
3992
+ error: serializeError$4(error)
4066
3993
  });
4067
3994
  throw error;
4068
3995
  }
@@ -4070,7 +3997,7 @@
4070
3997
  const relative = resolveRequestedRelative(requestedRelative);
4071
3998
  if (!relative) {
4072
3999
  logger.warn('[SLM] Unexpected model file request; falling back to original fetch', {
4073
- file: requestedRelative,
4000
+ requestedRelative,
4074
4001
  modelId
4075
4002
  });
4076
4003
  return originalFetch(url, init);
@@ -4118,11 +4045,10 @@
4118
4045
  // That string means "every candidate URL threw", i.e. a network/abort
4119
4046
  // failure against the real model host — not an upstream 502 and not a
4120
4047
  // malformed URL actually being requested.
4121
- logger.warn('[SLM] Model file fetch failed', {
4048
+ logger.warn(`[SLM] Model file fetch failed for ${relative}`, {
4122
4049
  modelId,
4123
- file: relative,
4124
- candidateCount: requestUrls.length,
4125
- error: summarizeError(err)
4050
+ candidates: requestUrls,
4051
+ error: serializeError$4(err)
4126
4052
  });
4127
4053
  return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
4128
4054
  }
@@ -4135,6 +4061,12 @@
4135
4061
  classification: 'zero-shot-classification',
4136
4062
  text_generation: 'text2text-generation'
4137
4063
  };
4064
+ const serializeError$3 = (error) => {
4065
+ if (error instanceof Error) {
4066
+ return { name: error.name, message: error.message, stack: error.stack };
4067
+ }
4068
+ return { message: String(error) };
4069
+ };
4138
4070
  const isInvalidArrayLengthError = (error) => {
4139
4071
  const message = error instanceof Error ? error.message : String(error);
4140
4072
  return message.toLowerCase().includes('invalid array length');
@@ -4506,7 +4438,7 @@
4506
4438
  modelRepoId: slm.modelRepoId,
4507
4439
  modelUrl: slm.modelUrl,
4508
4440
  requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
4509
- error: summarizeError(error)
4441
+ error: serializeError$3(error)
4510
4442
  });
4511
4443
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4512
4444
  return { error: error, metrics: {} };
@@ -4527,6 +4459,12 @@
4527
4459
 
4528
4460
  const DEFAULT_THRESHOLD = 0.4;
4529
4461
  const DEFAULT_MASK = '[REDACTED]';
4462
+ const serializeError$2 = (error) => {
4463
+ if (error instanceof Error) {
4464
+ return { name: error.name, message: error.message, stack: error.stack };
4465
+ }
4466
+ return { message: String(error) };
4467
+ };
4530
4468
  const parseTokenClassificationOutput = (raw, sourceText) => {
4531
4469
  if (!Array.isArray(raw))
4532
4470
  return [];
@@ -4789,7 +4727,7 @@
4789
4727
  modelVersion: slm.modelVersion,
4790
4728
  modelRepoId: slm.modelRepoId,
4791
4729
  modelUrl: slm.modelUrl,
4792
- error: summarizeError(error)
4730
+ error: serializeError$2(error)
4793
4731
  });
4794
4732
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4795
4733
  return { error: error, metrics: {} };
@@ -4808,6 +4746,12 @@
4808
4746
 
4809
4747
  const WLLAMA_CDN = 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js';
4810
4748
  let wllamaRuntimePromise = null;
4749
+ const serializeError$1 = (error) => {
4750
+ if (error instanceof Error) {
4751
+ return { name: error.name, message: error.message, stack: error.stack };
4752
+ }
4753
+ return { message: String(error) };
4754
+ };
4811
4755
  const ensureWllamaRuntime = () => {
4812
4756
  if (window.WllamaModule) {
4813
4757
  return Promise.resolve(window.WllamaModule);
@@ -4826,7 +4770,7 @@
4826
4770
  wllamaRuntimePromise = null;
4827
4771
  getLogger().error('[GGUF] Failed to import wllama runtime', {
4828
4772
  runtimeUrl: WLLAMA_CDN,
4829
- error: summarizeError(error)
4773
+ error: serializeError$1(error)
4830
4774
  });
4831
4775
  throw error;
4832
4776
  }
@@ -4837,6 +4781,12 @@
4837
4781
  const WLLAMA_CDN_BASE = WLLAMA_CDN.replace(/\/esm\/index\.js$/, '/esm');
4838
4782
 
4839
4783
  const DEFAULT_MAX_NEW_TOKENS = 128;
4784
+ const serializeError = (error) => {
4785
+ if (error instanceof Error) {
4786
+ return { name: error.name, message: error.message, stack: error.stack };
4787
+ }
4788
+ return { message: String(error) };
4789
+ };
4840
4790
  const pickGgufFileName = (requiredFiles) => {
4841
4791
  if (!Array.isArray(requiredFiles) || requiredFiles.length === 0)
4842
4792
  return null;
@@ -5041,7 +4991,7 @@
5041
4991
  modelId: slm.modelId,
5042
4992
  modelVersion: slm.modelVersion,
5043
4993
  modelUrl: slm.modelUrl,
5044
- error: summarizeError(error)
4994
+ error: serializeError(error)
5045
4995
  });
5046
4996
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
5047
4997
  return { error: error, metrics: {} };
@@ -5081,9 +5031,7 @@
5081
5031
  if (options?.resourcePolicy) {
5082
5032
  setResourcePolicy(options.resourcePolicy);
5083
5033
  if (options.resourcePolicy.disableGuardrails) {
5084
- // Loud by design: a host running without guardrails should know it, even
5085
- // with console logs disabled. Static text only — nothing to redact.
5086
- // eslint-disable-next-line no-console
5034
+ // Loud by design: a host running without guardrails should know it.
5087
5035
  console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
5088
5036
  }
5089
5037
  }
@@ -5099,7 +5047,7 @@
5099
5047
  catch (err) {
5100
5048
  // Already reported inside the lifecycle (register.failed / sdk.init_failed
5101
5049
  // / init-failure hello); surface for the host without throwing into it.
5102
- getLogger().error('[Init] SDK initialization failed', { error: summarizeError(err) });
5050
+ getLogger().error('[Init] SDK initialization failed', err);
5103
5051
  }
5104
5052
  return handle;
5105
5053
  };
@@ -5221,9 +5169,7 @@
5221
5169
  // the integrator asked for logs — the failure is reported as an
5222
5170
  // `sdk.init_failed` device event regardless.
5223
5171
  if (enableConsoleLogs) {
5224
- // Pre-logger fallback; the error is a summarized diagnostic, never payload.
5225
- // eslint-disable-next-line no-console
5226
- console.error('[ZeroGpuSdk] Auto-init failed', error instanceof Error ? `${error.name}: ${error.message}` : String(error));
5172
+ console.error('[ZeroGpuSdk] Auto-init failed', error);
5227
5173
  }
5228
5174
  });
5229
5175
  };
@@ -5233,4 +5179,4 @@
5233
5179
  exports.initZeroGpuSdk = initZeroGpuSdk;
5234
5180
 
5235
5181
  }));
5236
- //# sourceMappingURL=zerogpu-browser-sdk.644d5261aa70.umd.js.map
5182
+ //# sourceMappingURL=zerogpu-browser-sdk.b4f27a5bea4f.umd.js.map