@zerogpu/browser-extension-sdk 0.1.0
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.
- package/README.md +264 -0
- package/bin/zerogpu.mjs +331 -0
- package/dist/assets/ort-wasm-simd-threaded.wasm +0 -0
- package/dist/assets/ort-wasm-simd.wasm +0 -0
- package/dist/assets/ort-wasm-threaded.wasm +0 -0
- package/dist/assets/ort-wasm.wasm +0 -0
- package/dist/assets/transformers.min.js +107 -0
- package/dist/assets/wllama/index.js +3374 -0
- package/dist/assets/wllama/multi-thread/wllama.wasm +0 -0
- package/dist/assets/wllama/single-thread/wllama.wasm +0 -0
- package/dist/assets/zerogpu-assets.json +17 -0
- package/dist/extension/zerogpu-offscreen.js +2904 -0
- package/dist/extension/zerogpu-offscreen.js.map +1 -0
- package/dist/loader.js +2 -0
- package/dist/loader.js.map +1 -0
- package/dist/manifest.json +7 -0
- package/dist/types/adapters/gguf/adapter.d.ts +3 -0
- package/dist/types/adapters/gguf/factory.d.ts +3 -0
- package/dist/types/adapters/gguf/index.d.ts +2 -0
- package/dist/types/adapters/gguf/runtime.d.ts +16 -0
- package/dist/types/adapters/index.d.ts +5 -0
- package/dist/types/adapters/onnx/adapter.d.ts +3 -0
- package/dist/types/adapters/onnx/env-fetch.d.ts +1 -0
- package/dist/types/adapters/onnx/factory.d.ts +3 -0
- package/dist/types/adapters/onnx/index.d.ts +2 -0
- package/dist/types/adapters/onnx/runtime.d.ts +15 -0
- package/dist/types/adapters/registry.d.ts +5 -0
- package/dist/types/adapters/transformers/adapter.d.ts +10 -0
- package/dist/types/adapters/transformers/factory.d.ts +3 -0
- package/dist/types/adapters/transformers/index.d.ts +2 -0
- package/dist/types/adapters/types.d.ts +64 -0
- package/dist/types/auto-init.d.ts +1 -0
- package/dist/types/config/defaults.d.ts +2 -0
- package/dist/types/config/env.d.ts +7 -0
- package/dist/types/config/orchestrator-url.d.ts +1 -0
- package/dist/types/config/types.d.ts +34 -0
- package/dist/types/device/fingerprint.d.ts +2 -0
- package/dist/types/device/telemetry.d.ts +3 -0
- package/dist/types/device/types.d.ts +58 -0
- package/dist/types/extension/offscreen.d.ts +49 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/loader.d.ts +25 -0
- package/dist/types/public-api.d.ts +13 -0
- package/dist/types/runtime/lifecycle.d.ts +8 -0
- package/dist/types/runtime/router.d.ts +2 -0
- package/dist/types/runtime/sdk-state.d.ts +56 -0
- package/dist/types/sdk-version.d.ts +1 -0
- package/dist/types/storage/cached-model.d.ts +29 -0
- package/dist/types/storage/index.d.ts +4 -0
- package/dist/types/storage/meta-store.d.ts +2 -0
- package/dist/types/storage/model-store.d.ts +9 -0
- package/dist/types/storage/types.d.ts +19 -0
- package/dist/types/transport/http.d.ts +54 -0
- package/dist/types/transport/protocol.d.ts +47 -0
- package/dist/types/transport/status.d.ts +1 -0
- package/dist/types/transport/websocket.d.ts +25 -0
- package/dist/types/utils/errors.d.ts +4 -0
- package/dist/types/utils/logger.d.ts +15 -0
- package/dist/types/utils/timers.d.ts +7 -0
- package/dist/types/utils/uuid.d.ts +1 -0
- package/dist/v/zerogpu-browser-sdk.f47bae4f15c9.umd.js +2855 -0
- package/dist/v/zerogpu-browser-sdk.f47bae4f15c9.umd.js.map +1 -0
- package/dist/zerogpu-browser-sdk.cjs +2849 -0
- package/dist/zerogpu-browser-sdk.cjs.map +1 -0
- package/dist/zerogpu-browser-sdk.esm.js +2847 -0
- package/dist/zerogpu-browser-sdk.esm.js.map +1 -0
- package/dist/zerogpu-browser-sdk.umd.js +2855 -0
- package/dist/zerogpu-browser-sdk.umd.js.map +1 -0
- package/docs/INTEGRATION.md +213 -0
- package/docs/auto-update-loader.md +451 -0
- package/docs/multi-model-support.md +537 -0
- package/package.json +91 -0
|
@@ -0,0 +1,2849 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const SDK_VERSION = typeof "0.1.0+2fdfb71" === 'string' && "0.1.0+2fdfb71".length > 0
|
|
4
|
+
? "0.1.0+2fdfb71"
|
|
5
|
+
: '0.0.0-dev';
|
|
6
|
+
|
|
7
|
+
const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
|
|
8
|
+
? "https://devices.zerogpu.ai"
|
|
9
|
+
: 'https://dev.devices.zerogpu.ai';
|
|
10
|
+
|
|
11
|
+
// The orchestrator URL is baked in at build time per deployment (develop/staging/
|
|
12
|
+
// production). See ./orchestrator-url for the env-var injection and fallback.
|
|
13
|
+
const DEFAULT_CONFIG = {
|
|
14
|
+
sdkVersion: SDK_VERSION,
|
|
15
|
+
orchestrator: {
|
|
16
|
+
baseUrl: ORCHESTRATOR_BASE_URL,
|
|
17
|
+
registerPath: '/register'
|
|
18
|
+
},
|
|
19
|
+
telemetry: {
|
|
20
|
+
enableConsoleLogs: false,
|
|
21
|
+
locationData: false,
|
|
22
|
+
cameraData: false
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const resolveConfig = (overrides) => {
|
|
27
|
+
const base = DEFAULT_CONFIG;
|
|
28
|
+
const merged = deepMerge(base, overrides ?? {});
|
|
29
|
+
return {
|
|
30
|
+
sdkVersion: asNonEmptyString(merged.sdkVersion, base.sdkVersion),
|
|
31
|
+
orchestrator: {
|
|
32
|
+
baseUrl: asNonEmptyString(merged.orchestrator?.baseUrl, base.orchestrator.baseUrl),
|
|
33
|
+
registerPath: asNonEmptyString(merged.orchestrator?.registerPath, base.orchestrator.registerPath)
|
|
34
|
+
},
|
|
35
|
+
telemetry: {
|
|
36
|
+
enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
|
|
37
|
+
locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
|
|
38
|
+
cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData)
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
43
|
+
const deepMerge = (target, source) => {
|
|
44
|
+
const result = Array.isArray(target) ? [...target] : { ...target };
|
|
45
|
+
for (const key of Object.keys(source)) {
|
|
46
|
+
const srcValue = source[key];
|
|
47
|
+
if (srcValue === undefined)
|
|
48
|
+
continue;
|
|
49
|
+
const tgtValue = result[key];
|
|
50
|
+
if (isObject(srcValue) && isObject(tgtValue)) {
|
|
51
|
+
result[key] = deepMerge(tgtValue, srcValue);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
result[key] = srcValue;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
};
|
|
59
|
+
const asNonEmptyString = (value, fallback) => typeof value === 'string' && value.length > 0 ? value : fallback;
|
|
60
|
+
const asBoolean = (value, fallback) => typeof value === 'boolean' ? value : fallback;
|
|
61
|
+
|
|
62
|
+
class Logger {
|
|
63
|
+
constructor(config) {
|
|
64
|
+
this.enabled = config.enableConsoleLogs;
|
|
65
|
+
}
|
|
66
|
+
setEnabled(enabled) {
|
|
67
|
+
this.enabled = enabled;
|
|
68
|
+
}
|
|
69
|
+
isEnabled() {
|
|
70
|
+
return this.enabled;
|
|
71
|
+
}
|
|
72
|
+
debug(...args) {
|
|
73
|
+
if (this.enabled)
|
|
74
|
+
console.debug('[ZeroGPU]', ...args);
|
|
75
|
+
}
|
|
76
|
+
info(...args) {
|
|
77
|
+
if (this.enabled)
|
|
78
|
+
console.debug('[ZeroGPU]', ...args);
|
|
79
|
+
}
|
|
80
|
+
warn(...args) {
|
|
81
|
+
if (this.enabled)
|
|
82
|
+
console.warn('[ZeroGPU]', ...args);
|
|
83
|
+
}
|
|
84
|
+
error(...args) {
|
|
85
|
+
if (this.enabled)
|
|
86
|
+
console.error('[ZeroGPU]', ...args);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
let singleton = null;
|
|
90
|
+
const initLogger = (config) => {
|
|
91
|
+
singleton = new Logger(config);
|
|
92
|
+
return singleton;
|
|
93
|
+
};
|
|
94
|
+
const getLogger = () => {
|
|
95
|
+
if (!singleton) {
|
|
96
|
+
singleton = new Logger({
|
|
97
|
+
enableConsoleLogs: false,
|
|
98
|
+
locationData: false,
|
|
99
|
+
cameraData: false
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
return singleton;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const DEVICE_ID_KEY = 'zerogpu_device_id';
|
|
106
|
+
const getStoredDeviceId = () => {
|
|
107
|
+
try {
|
|
108
|
+
return window.localStorage.getItem(DEVICE_ID_KEY);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const setStoredDeviceId = (deviceId) => {
|
|
115
|
+
try {
|
|
116
|
+
window.localStorage.setItem(DEVICE_ID_KEY, deviceId);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// ignored
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const createUuid = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
124
|
+
const r = (crypto.getRandomValues(new Uint8Array(1))[0] & 0xf) >> 0;
|
|
125
|
+
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
|
126
|
+
return v.toString(16);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
const getDeviceId = () => {
|
|
130
|
+
const existing = getStoredDeviceId();
|
|
131
|
+
if (existing)
|
|
132
|
+
return existing;
|
|
133
|
+
const fresh = createUuid();
|
|
134
|
+
setStoredDeviceId(fresh);
|
|
135
|
+
return fresh;
|
|
136
|
+
};
|
|
137
|
+
const setDeviceId = (deviceId) => {
|
|
138
|
+
setStoredDeviceId(deviceId);
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const getPlatform = () => {
|
|
142
|
+
const ua = navigator.userAgent.toLowerCase();
|
|
143
|
+
const tg = window.Telegram?.WebApp;
|
|
144
|
+
if (tg?.platform)
|
|
145
|
+
return tg.platform;
|
|
146
|
+
if (tg)
|
|
147
|
+
return 'telegram-webapp';
|
|
148
|
+
if (ua.includes('android'))
|
|
149
|
+
return 'android-web';
|
|
150
|
+
if (ua.includes('iphone') || ua.includes('ipad'))
|
|
151
|
+
return 'ios-web';
|
|
152
|
+
if (ua.includes('mac os'))
|
|
153
|
+
return 'macos-web';
|
|
154
|
+
if (ua.includes('windows'))
|
|
155
|
+
return 'windows-web';
|
|
156
|
+
return 'web';
|
|
157
|
+
};
|
|
158
|
+
const getDeviceType = () => {
|
|
159
|
+
const ua = navigator.userAgent ?? '';
|
|
160
|
+
const uaData = navigator.userAgentData;
|
|
161
|
+
if (uaData?.mobile === true)
|
|
162
|
+
return 'mobile';
|
|
163
|
+
const isTablet = /iPad|Tablet|PlayBook|Silk/i.test(ua) || (navigator.maxTouchPoints > 1 && window.innerWidth >= 768);
|
|
164
|
+
if (isTablet)
|
|
165
|
+
return 'tablet';
|
|
166
|
+
const isMobile = /Mobi|Android|iPhone|iPod/i.test(ua);
|
|
167
|
+
return isMobile ? 'mobile' : 'desktop';
|
|
168
|
+
};
|
|
169
|
+
const getWebGLRenderer = () => {
|
|
170
|
+
try {
|
|
171
|
+
const canvas = document.createElement('canvas');
|
|
172
|
+
const gl = canvas.getContext('webgl') ||
|
|
173
|
+
canvas.getContext('experimental-webgl');
|
|
174
|
+
if (!gl)
|
|
175
|
+
return undefined;
|
|
176
|
+
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
|
|
177
|
+
return dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return undefined;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const getBatteryInfo = async () => {
|
|
184
|
+
try {
|
|
185
|
+
if ('getBattery' in navigator) {
|
|
186
|
+
const battery = await navigator.getBattery();
|
|
187
|
+
return {
|
|
188
|
+
level: battery.level,
|
|
189
|
+
charging: battery.charging
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
// ignored
|
|
195
|
+
}
|
|
196
|
+
return undefined;
|
|
197
|
+
};
|
|
198
|
+
const getNetworkInfo = () => {
|
|
199
|
+
const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
|
|
200
|
+
if (conn) {
|
|
201
|
+
return {
|
|
202
|
+
type: conn.effectiveType || 'unknown',
|
|
203
|
+
downlink: conn.downlink || 0,
|
|
204
|
+
rtt: conn.rtt || 0
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
return undefined;
|
|
208
|
+
};
|
|
209
|
+
const getLocation = async () => {
|
|
210
|
+
if (!navigator.geolocation)
|
|
211
|
+
return undefined;
|
|
212
|
+
return new Promise((resolve) => {
|
|
213
|
+
navigator.geolocation.getCurrentPosition((pos) => {
|
|
214
|
+
resolve({
|
|
215
|
+
lat: pos.coords.latitude,
|
|
216
|
+
lon: pos.coords.longitude,
|
|
217
|
+
accuracy: pos.coords.accuracy
|
|
218
|
+
});
|
|
219
|
+
}, () => resolve(undefined), { timeout: 5000, maximumAge: 60000 });
|
|
220
|
+
});
|
|
221
|
+
};
|
|
222
|
+
const parseTelegramUserFromHash = () => {
|
|
223
|
+
try {
|
|
224
|
+
const hash = window.location?.hash || '';
|
|
225
|
+
if (!hash.includes('tgWebAppData'))
|
|
226
|
+
return undefined;
|
|
227
|
+
const hashParams = new URLSearchParams(hash.startsWith('#') ? hash.substring(1) : hash);
|
|
228
|
+
const encodedData = hashParams.get('tgWebAppData');
|
|
229
|
+
if (!encodedData)
|
|
230
|
+
return undefined;
|
|
231
|
+
const decodedData = decodeURIComponent(encodedData);
|
|
232
|
+
const dataParams = new URLSearchParams(decodedData);
|
|
233
|
+
const userJson = dataParams.get('user');
|
|
234
|
+
if (!userJson)
|
|
235
|
+
return undefined;
|
|
236
|
+
return JSON.parse(userJson);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
return undefined;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
const getTelegramUser = () => {
|
|
243
|
+
const tg = window.Telegram?.WebApp;
|
|
244
|
+
const user = tg?.initDataUnsafe?.user;
|
|
245
|
+
if (user) {
|
|
246
|
+
return user;
|
|
247
|
+
}
|
|
248
|
+
return parseTelegramUserFromHash();
|
|
249
|
+
};
|
|
250
|
+
const collectDeviceInfo = async (config, appUserId, sdkDeviceId) => {
|
|
251
|
+
const screen = window.screen || { width: null, height: null };
|
|
252
|
+
const tg = window.Telegram?.WebApp;
|
|
253
|
+
const telegramUser = getTelegramUser();
|
|
254
|
+
const telegramFullName = telegramUser?.first_name || telegramUser?.last_name
|
|
255
|
+
? [telegramUser?.first_name, telegramUser?.last_name].filter(Boolean).join(' ')
|
|
256
|
+
: undefined;
|
|
257
|
+
const resolvedAppUserId = telegramUser?.id?.toString() || appUserId;
|
|
258
|
+
const baseInfo = {
|
|
259
|
+
// Identity
|
|
260
|
+
appUserId: resolvedAppUserId,
|
|
261
|
+
appUsername: telegramUser?.username,
|
|
262
|
+
appFirstName: telegramUser?.first_name,
|
|
263
|
+
appLastName: telegramUser?.last_name,
|
|
264
|
+
appFullName: telegramFullName,
|
|
265
|
+
sdkDeviceId: sdkDeviceId ?? getDeviceId(),
|
|
266
|
+
// Platform
|
|
267
|
+
platform: getPlatform(),
|
|
268
|
+
deviceType: getDeviceType(),
|
|
269
|
+
userAgent: navigator.userAgent,
|
|
270
|
+
language: navigator.language,
|
|
271
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
272
|
+
appPlatform: tg?.platform,
|
|
273
|
+
appVersion: tg?.version,
|
|
274
|
+
appLanguage: telegramUser?.language_code,
|
|
275
|
+
themeParams: tg?.themeParams,
|
|
276
|
+
// Hardware
|
|
277
|
+
cpuCores: navigator.hardwareConcurrency || 1,
|
|
278
|
+
memoryGb: navigator.deviceMemory,
|
|
279
|
+
gpuRenderer: getWebGLRenderer(),
|
|
280
|
+
webglFingerprint: getWebGLRenderer(), // Using renderer as simple fingerprint for now
|
|
281
|
+
screen: {
|
|
282
|
+
width: screen?.width ?? null,
|
|
283
|
+
height: screen?.height ?? null,
|
|
284
|
+
pixelRatio: window.devicePixelRatio ?? null
|
|
285
|
+
},
|
|
286
|
+
battery: await getBatteryInfo(),
|
|
287
|
+
// Network
|
|
288
|
+
connection: getNetworkInfo(),
|
|
289
|
+
// Context
|
|
290
|
+
pageUrl: window.location?.href,
|
|
291
|
+
referrer: document.referrer,
|
|
292
|
+
// Optional permissions
|
|
293
|
+
location: config.locationData ? await getLocation() : undefined
|
|
294
|
+
};
|
|
295
|
+
if (config.cameraData) {
|
|
296
|
+
baseInfo.camera = await captureCameraSample();
|
|
297
|
+
}
|
|
298
|
+
return baseInfo;
|
|
299
|
+
};
|
|
300
|
+
const captureCameraSample = async () => {
|
|
301
|
+
if (!navigator.mediaDevices?.getUserMedia) {
|
|
302
|
+
return { permission: 'error', error: 'mediaDevices unavailable' };
|
|
303
|
+
}
|
|
304
|
+
let stream = null;
|
|
305
|
+
let video = null;
|
|
306
|
+
let canvas = null;
|
|
307
|
+
try {
|
|
308
|
+
stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
|
|
309
|
+
video = document.createElement('video');
|
|
310
|
+
video.setAttribute('playsinline', 'true');
|
|
311
|
+
video.playsInline = true;
|
|
312
|
+
video.muted = true;
|
|
313
|
+
video.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0';
|
|
314
|
+
document.body.appendChild(video);
|
|
315
|
+
video.srcObject = stream;
|
|
316
|
+
await video.play().catch(() => { });
|
|
317
|
+
await new Promise((resolve) => {
|
|
318
|
+
const ready = () => resolve();
|
|
319
|
+
video.onloadeddata = ready;
|
|
320
|
+
video.oncanplay = ready;
|
|
321
|
+
setTimeout(ready, 800);
|
|
322
|
+
});
|
|
323
|
+
const vw = video.videoWidth || 640;
|
|
324
|
+
const vh = video.videoHeight || 480;
|
|
325
|
+
canvas = document.createElement('canvas');
|
|
326
|
+
canvas.width = vw;
|
|
327
|
+
canvas.height = vh;
|
|
328
|
+
const ctx = canvas.getContext('2d');
|
|
329
|
+
ctx?.drawImage(video, 0, 0, vw, vh);
|
|
330
|
+
const mime = 'image/jpeg';
|
|
331
|
+
const dataUrl = canvas.toDataURL(mime, 0.85);
|
|
332
|
+
const bytes = Math.floor((dataUrl.length * 3) / 4);
|
|
333
|
+
return {
|
|
334
|
+
permission: 'granted',
|
|
335
|
+
width: vw,
|
|
336
|
+
height: vh,
|
|
337
|
+
bytes,
|
|
338
|
+
mime,
|
|
339
|
+
timestamp: Date.now(),
|
|
340
|
+
previewDataUrl: dataUrl
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
catch (err) {
|
|
344
|
+
const errorObj = err;
|
|
345
|
+
return {
|
|
346
|
+
permission: errorObj?.name === 'NotAllowedError' ? 'denied' : 'error',
|
|
347
|
+
error: errorObj?.message || String(err)
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
finally {
|
|
351
|
+
try {
|
|
352
|
+
stream?.getTracks().forEach((track) => track.stop());
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
// Best-effort cleanup.
|
|
356
|
+
}
|
|
357
|
+
try {
|
|
358
|
+
video?.remove();
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
// Best-effort cleanup.
|
|
362
|
+
}
|
|
363
|
+
canvas = null;
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
class RegisterError extends Error {
|
|
368
|
+
constructor(status, body) {
|
|
369
|
+
super(`Register failed: ${status} ${body ?? ''}`.trim());
|
|
370
|
+
this.status = status;
|
|
371
|
+
this.body = body;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const parseRegisterResponseBody = async (response) => {
|
|
375
|
+
try {
|
|
376
|
+
return await response.clone().json();
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
const isEdgeSdkTypeNotAllowedResponse = (payload) => {
|
|
383
|
+
if (!payload || typeof payload !== 'object') {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
const body = payload;
|
|
387
|
+
const status = typeof body.status === 'string' ? body.status.toLowerCase() : '';
|
|
388
|
+
if (status !== 'ok') {
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
const nestedError = body.error;
|
|
392
|
+
const candidateCodes = [body.code, body.errorCode, body.reason, nestedError?.code];
|
|
393
|
+
return candidateCodes.some((value) => typeof value === 'string' && value.toLowerCase() === 'edge_sdk_type_not_allowed');
|
|
394
|
+
};
|
|
395
|
+
const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
|
|
396
|
+
const buildCurl = (url, body, headers) => {
|
|
397
|
+
const payload = escapeShellSingleQuotes(JSON.stringify(body));
|
|
398
|
+
const headerFlags = Object.entries(headers)
|
|
399
|
+
.map(([key, value]) => `-H '${escapeShellSingleQuotes(`${key}: ${value}`)}'`)
|
|
400
|
+
.join(' ');
|
|
401
|
+
return `curl -X POST '${url}' ${headerFlags} -d '${payload}'`;
|
|
402
|
+
};
|
|
403
|
+
const registerDevice = async (config, payload, auth) => {
|
|
404
|
+
const logger = getLogger();
|
|
405
|
+
const orchestrator = config?.orchestrator;
|
|
406
|
+
if (!orchestrator?.baseUrl || !orchestrator?.registerPath) {
|
|
407
|
+
throw new Error('Invalid SDK config: orchestrator.baseUrl and orchestrator.registerPath are required');
|
|
408
|
+
}
|
|
409
|
+
const url = `${orchestrator.baseUrl}${orchestrator.registerPath}`;
|
|
410
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
411
|
+
const edgeOperatorKey = auth?.edgeOperatorKey?.trim();
|
|
412
|
+
if (edgeOperatorKey)
|
|
413
|
+
headers['x-edge-operator-key'] = edgeOperatorKey;
|
|
414
|
+
const response = await fetch(url, {
|
|
415
|
+
method: 'POST',
|
|
416
|
+
headers,
|
|
417
|
+
body: JSON.stringify(payload)
|
|
418
|
+
});
|
|
419
|
+
logger.info('Register request sent:', { url, status: response.status });
|
|
420
|
+
getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
|
|
421
|
+
const registerResponseBody = await parseRegisterResponseBody(response);
|
|
422
|
+
const edgeSdkTypeNotAllowed = isEdgeSdkTypeNotAllowedResponse(registerResponseBody);
|
|
423
|
+
if (!response.ok && !edgeSdkTypeNotAllowed) {
|
|
424
|
+
const text = typeof registerResponseBody === 'string'
|
|
425
|
+
? registerResponseBody
|
|
426
|
+
: JSON.stringify(registerResponseBody ?? '');
|
|
427
|
+
logger.error('Register request failed:', { status: response.status, text });
|
|
428
|
+
throw new RegisterError(response.status, text);
|
|
429
|
+
}
|
|
430
|
+
if (registerResponseBody && typeof registerResponseBody === 'object' && !edgeSdkTypeNotAllowed) {
|
|
431
|
+
const registerResponse = registerResponseBody;
|
|
432
|
+
logger.info('Register response parsed:', registerResponse);
|
|
433
|
+
return registerResponse;
|
|
434
|
+
}
|
|
435
|
+
if (edgeSdkTypeNotAllowed) {
|
|
436
|
+
const responseObject = registerResponseBody && typeof registerResponseBody === 'object'
|
|
437
|
+
? registerResponseBody
|
|
438
|
+
: {};
|
|
439
|
+
const acceptedResponse = {
|
|
440
|
+
deviceId: typeof responseObject.deviceId === 'string' && responseObject.deviceId
|
|
441
|
+
? responseObject.deviceId
|
|
442
|
+
: payload.deviceId,
|
|
443
|
+
sessionKey: typeof responseObject.sessionKey === 'string' ? responseObject.sessionKey : '',
|
|
444
|
+
wsUrl: typeof responseObject.wsUrl === 'string' ? responseObject.wsUrl : '',
|
|
445
|
+
active: typeof responseObject.active === 'boolean' ? responseObject.active : false,
|
|
446
|
+
ttlSeconds: typeof responseObject.ttlSeconds === 'number' ? responseObject.ttlSeconds : 0,
|
|
447
|
+
slmConfig: typeof responseObject.slmConfig !== 'undefined'
|
|
448
|
+
? responseObject.slmConfig
|
|
449
|
+
: typeof responseObject.modelInfo !== 'undefined'
|
|
450
|
+
? [responseObject.modelInfo]
|
|
451
|
+
: undefined
|
|
452
|
+
};
|
|
453
|
+
logger.info('Handled edge_sdk_type_not_allowed register response');
|
|
454
|
+
return acceptedResponse;
|
|
455
|
+
}
|
|
456
|
+
throw new RegisterError(response.status, 'Register response body is not valid JSON');
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
class WebSocketClient {
|
|
460
|
+
constructor(options) {
|
|
461
|
+
this.options = options;
|
|
462
|
+
this.logger = getLogger();
|
|
463
|
+
this.consoleWithVerbose = console;
|
|
464
|
+
this.handleOpen = () => {
|
|
465
|
+
this.logger.info('WebSocket connection opened');
|
|
466
|
+
this.logger.debug('Sending hello message:', this.options.hello);
|
|
467
|
+
this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
|
|
468
|
+
this.send(this.options.hello);
|
|
469
|
+
if (this.options.ack) {
|
|
470
|
+
// Send readiness/error ack immediately after hello.
|
|
471
|
+
this.logger.info('[WS OUT] hello_ack:', JSON.stringify(this.options.ack));
|
|
472
|
+
this.send(this.options.ack);
|
|
473
|
+
if (this.options.closeAfterAck) {
|
|
474
|
+
// Optionally close after ack (used for error cases).
|
|
475
|
+
const code = this.options.closeCode ?? 4000;
|
|
476
|
+
const reason = (this.options.closeReason ?? '').slice(0, 120);
|
|
477
|
+
this.logger.warn('Closing WebSocket after ack', { code, reason });
|
|
478
|
+
window.setTimeout(() => {
|
|
479
|
+
this.socket.close(code, reason);
|
|
480
|
+
}, 50);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
this.handleMessage = (event) => {
|
|
485
|
+
try {
|
|
486
|
+
const data = JSON.parse(event.data);
|
|
487
|
+
if (this.logger.isEnabled()) {
|
|
488
|
+
if (typeof this.consoleWithVerbose.verbose === 'function') {
|
|
489
|
+
this.consoleWithVerbose.verbose('[ZeroGPU]', '[WS IN] payload:', data);
|
|
490
|
+
}
|
|
491
|
+
else {
|
|
492
|
+
console.debug('[ZeroGPU]', '[WS IN] payload:', data);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
this.options.onMessage(data);
|
|
496
|
+
}
|
|
497
|
+
catch (error) {
|
|
498
|
+
this.logger.error('Failed to parse WS message', error);
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
this.handleError = (event) => {
|
|
502
|
+
const ws = event.target;
|
|
503
|
+
this.logger.error('WebSocket error', {
|
|
504
|
+
url: ws.url,
|
|
505
|
+
readyState: ws.readyState,
|
|
506
|
+
event: event.type
|
|
507
|
+
});
|
|
508
|
+
this.options.onError(event);
|
|
509
|
+
};
|
|
510
|
+
this.handleClose = (event) => {
|
|
511
|
+
const ws = event.target;
|
|
512
|
+
this.logger.warn('WebSocket closed', {
|
|
513
|
+
url: ws.url,
|
|
514
|
+
code: event.code,
|
|
515
|
+
reason: event.reason || 'No reason provided',
|
|
516
|
+
wasClean: event.wasClean
|
|
517
|
+
});
|
|
518
|
+
this.options.onClose(event);
|
|
519
|
+
};
|
|
520
|
+
this.logger.info('Creating WebSocket connection to:', options.url);
|
|
521
|
+
this.socket = new WebSocket(options.url);
|
|
522
|
+
this.socket.onopen = this.handleOpen;
|
|
523
|
+
this.socket.onmessage = this.handleMessage;
|
|
524
|
+
this.socket.onerror = this.handleError;
|
|
525
|
+
this.socket.onclose = this.handleClose;
|
|
526
|
+
}
|
|
527
|
+
send(payload) {
|
|
528
|
+
this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
|
|
529
|
+
this.socket.send(JSON.stringify(payload));
|
|
530
|
+
}
|
|
531
|
+
close() {
|
|
532
|
+
this.socket.close();
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
const state = { status: 'idle' };
|
|
537
|
+
const setConfig = (config) => {
|
|
538
|
+
state.config = config;
|
|
539
|
+
};
|
|
540
|
+
const setDeviceContext = (deviceId, deviceInfo) => {
|
|
541
|
+
state.deviceId = deviceId;
|
|
542
|
+
state.deviceInfo = deviceInfo;
|
|
543
|
+
};
|
|
544
|
+
const setAdapter = (modelId, adapter) => {
|
|
545
|
+
if (!state.adaptersByModelId) {
|
|
546
|
+
state.adaptersByModelId = {};
|
|
547
|
+
}
|
|
548
|
+
if (adapter) {
|
|
549
|
+
state.adaptersByModelId[modelId] = adapter;
|
|
550
|
+
}
|
|
551
|
+
else {
|
|
552
|
+
delete state.adaptersByModelId[modelId];
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
const setAdaptersByModelId = (adapters) => {
|
|
556
|
+
state.adaptersByModelId = adapters ?? {};
|
|
557
|
+
};
|
|
558
|
+
const setModelInfo = (modelInfo) => {
|
|
559
|
+
state.modelInfo = modelInfo;
|
|
560
|
+
state.taskType = modelInfo?.taskType;
|
|
561
|
+
if (!state.modelInfosByModelId) {
|
|
562
|
+
state.modelInfosByModelId = {};
|
|
563
|
+
}
|
|
564
|
+
if (modelInfo?.modelId) {
|
|
565
|
+
state.modelInfosByModelId[modelInfo.modelId] = modelInfo;
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
const setModelInfosByModelId = (modelInfos) => {
|
|
569
|
+
state.modelInfosByModelId = modelInfos ?? {};
|
|
570
|
+
};
|
|
571
|
+
const setSample = (sample) => {
|
|
572
|
+
state.sample = sample;
|
|
573
|
+
};
|
|
574
|
+
const setCachedModelId = (cachedModelId) => {
|
|
575
|
+
state.cachedModelId = cachedModelId ?? null;
|
|
576
|
+
};
|
|
577
|
+
const setSessionKey = (sessionKey) => {
|
|
578
|
+
state.sessionKey = sessionKey;
|
|
579
|
+
};
|
|
580
|
+
const setWebSocket = (ws) => {
|
|
581
|
+
state.ws = ws;
|
|
582
|
+
};
|
|
583
|
+
const setStatus = (status) => {
|
|
584
|
+
state.status = status;
|
|
585
|
+
};
|
|
586
|
+
const getState = () => {
|
|
587
|
+
if (!state.config || !state.deviceId || !state.deviceInfo) {
|
|
588
|
+
throw new Error('SDK state not initialized');
|
|
589
|
+
}
|
|
590
|
+
return state;
|
|
591
|
+
};
|
|
592
|
+
|
|
593
|
+
const factories = [];
|
|
594
|
+
const registerAdapter = (factory) => {
|
|
595
|
+
factories.push(factory);
|
|
596
|
+
};
|
|
597
|
+
const matches = (capability, framework, taskType) => capability.inferenceFramework.toLowerCase() === framework.toLowerCase() &&
|
|
598
|
+
capability.taskType.toLowerCase() === taskType.toLowerCase();
|
|
599
|
+
const getAdapterFactory = (framework, taskType) => {
|
|
600
|
+
if (!framework || !taskType)
|
|
601
|
+
return undefined;
|
|
602
|
+
return factories.find((factory) => factory.capabilities.some((capability) => matches(capability, framework, taskType)));
|
|
603
|
+
};
|
|
604
|
+
|
|
605
|
+
let executing = false;
|
|
606
|
+
const buildInferenceInput = (request) => {
|
|
607
|
+
const input = request.input ?? {};
|
|
608
|
+
return {
|
|
609
|
+
...input,
|
|
610
|
+
text: typeof input.text === 'string' ? input.text : '',
|
|
611
|
+
usecase: typeof input.usecase === 'string' ? input.usecase : undefined
|
|
612
|
+
};
|
|
613
|
+
};
|
|
614
|
+
const lazyLoadAdapter = async (modelId) => {
|
|
615
|
+
const logger = getLogger();
|
|
616
|
+
const { modelInfosByModelId } = getState();
|
|
617
|
+
const info = modelInfosByModelId?.[modelId];
|
|
618
|
+
if (!info)
|
|
619
|
+
return undefined;
|
|
620
|
+
const factory = getAdapterFactory(info.inferenceFramework, info.taskType);
|
|
621
|
+
if (!factory) {
|
|
622
|
+
logger.warn('No adapter factory registered for assigned model', {
|
|
623
|
+
modelId,
|
|
624
|
+
inferenceFramework: info.inferenceFramework,
|
|
625
|
+
taskType: info.taskType
|
|
626
|
+
});
|
|
627
|
+
return undefined;
|
|
628
|
+
}
|
|
629
|
+
const slmConfig = {
|
|
630
|
+
modelId: info.modelId,
|
|
631
|
+
modelVersion: info.modelVersion ?? '',
|
|
632
|
+
modelUrl: info.modelUrl,
|
|
633
|
+
modelRepoId: info.modelRepoId,
|
|
634
|
+
modelType: info.modelType,
|
|
635
|
+
inferenceFramework: info.inferenceFramework,
|
|
636
|
+
requiredFiles: info.requiredFiles,
|
|
637
|
+
quantized: info.quantized ?? false,
|
|
638
|
+
quantization: info.quantization,
|
|
639
|
+
taskType: info.taskType,
|
|
640
|
+
maxInputTokens: info.maxTokens
|
|
641
|
+
};
|
|
642
|
+
const result = await factory.load(slmConfig);
|
|
643
|
+
if (!result.adapter) {
|
|
644
|
+
logger.warn('Lazy adapter load failed', {
|
|
645
|
+
modelId,
|
|
646
|
+
error: result.error?.message
|
|
647
|
+
});
|
|
648
|
+
return undefined;
|
|
649
|
+
}
|
|
650
|
+
setAdapter(modelId, result.adapter);
|
|
651
|
+
return result.adapter;
|
|
652
|
+
};
|
|
653
|
+
const executeSingleRequest = async (request) => {
|
|
654
|
+
const logger = getLogger();
|
|
655
|
+
const start = performance.now();
|
|
656
|
+
const { adaptersByModelId } = getState();
|
|
657
|
+
let adapter = adaptersByModelId?.[request.modelId];
|
|
658
|
+
if (!adapter) {
|
|
659
|
+
adapter = await lazyLoadAdapter(request.modelId);
|
|
660
|
+
}
|
|
661
|
+
if (!adapter) {
|
|
662
|
+
return {
|
|
663
|
+
requestId: request.requestId,
|
|
664
|
+
modelId: request.modelId,
|
|
665
|
+
modelVersion: request.modelVersion,
|
|
666
|
+
response: { text: '' },
|
|
667
|
+
error: true,
|
|
668
|
+
errorMessage: 'model_not_ready',
|
|
669
|
+
metadata: {
|
|
670
|
+
processingTime: Math.round(performance.now() - start)
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
const input = buildInferenceInput(request);
|
|
676
|
+
const result = await adapter.runInference(input);
|
|
677
|
+
return {
|
|
678
|
+
requestId: request.requestId,
|
|
679
|
+
modelId: request.modelId,
|
|
680
|
+
modelVersion: request.modelVersion,
|
|
681
|
+
response: result.output,
|
|
682
|
+
error: false,
|
|
683
|
+
errorMessage: '',
|
|
684
|
+
metadata: {
|
|
685
|
+
processingTime: Math.round(performance.now() - start)
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
catch (error) {
|
|
690
|
+
logger.error('Task failed', error);
|
|
691
|
+
return {
|
|
692
|
+
requestId: request.requestId,
|
|
693
|
+
modelId: request.modelId,
|
|
694
|
+
modelVersion: request.modelVersion,
|
|
695
|
+
response: { text: '' },
|
|
696
|
+
error: true,
|
|
697
|
+
errorMessage: error.message,
|
|
698
|
+
metadata: {
|
|
699
|
+
processingTime: Math.round(performance.now() - start)
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
const handleIncomingMessage = async (msg) => {
|
|
705
|
+
const { ws, sessionKey, deviceId } = getState();
|
|
706
|
+
const logger = getLogger();
|
|
707
|
+
const sendBatchResponse = (requests) => {
|
|
708
|
+
const payload = {
|
|
709
|
+
requests,
|
|
710
|
+
deviceId,
|
|
711
|
+
sessionKey
|
|
712
|
+
};
|
|
713
|
+
ws?.send(payload);
|
|
714
|
+
};
|
|
715
|
+
if (msg.requests.length === 0) {
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (executing) {
|
|
719
|
+
sendBatchResponse(msg.requests.map((request) => ({
|
|
720
|
+
requestId: request.requestId,
|
|
721
|
+
modelId: request.modelId,
|
|
722
|
+
modelVersion: request.modelVersion,
|
|
723
|
+
response: { text: '' },
|
|
724
|
+
error: true,
|
|
725
|
+
errorMessage: 'device_busy',
|
|
726
|
+
metadata: { processingTime: 0 }
|
|
727
|
+
})));
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
executing = true;
|
|
731
|
+
setStatus('busy');
|
|
732
|
+
try {
|
|
733
|
+
const results = [];
|
|
734
|
+
for (const request of msg.requests) {
|
|
735
|
+
const result = await executeSingleRequest(request);
|
|
736
|
+
logger.info('[WS OUT] task result:', {
|
|
737
|
+
requestId: result.requestId,
|
|
738
|
+
modelId: result.modelId,
|
|
739
|
+
response: result.response,
|
|
740
|
+
error: result.error,
|
|
741
|
+
errorMessage: result.errorMessage
|
|
742
|
+
});
|
|
743
|
+
results.push(result);
|
|
744
|
+
}
|
|
745
|
+
sendBatchResponse(results);
|
|
746
|
+
}
|
|
747
|
+
finally {
|
|
748
|
+
executing = false;
|
|
749
|
+
setStatus('idle');
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
const DB_NAME = 'zerogpu-slm-cache';
|
|
754
|
+
const STORE_NAME = 'models';
|
|
755
|
+
const DB_VERSION = 1;
|
|
756
|
+
const openDb = () => new Promise((resolve, reject) => {
|
|
757
|
+
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
|
758
|
+
req.onupgradeneeded = () => {
|
|
759
|
+
const db = req.result;
|
|
760
|
+
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
|
761
|
+
db.createObjectStore(STORE_NAME, { keyPath: 'key' });
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
req.onsuccess = () => resolve(req.result);
|
|
765
|
+
req.onerror = () => reject(req.error);
|
|
766
|
+
});
|
|
767
|
+
const runTx = async (mode, handler) => {
|
|
768
|
+
const db = await openDb();
|
|
769
|
+
return new Promise((resolve, reject) => {
|
|
770
|
+
const tx = db.transaction(STORE_NAME, mode);
|
|
771
|
+
const store = tx.objectStore(STORE_NAME);
|
|
772
|
+
handler(store)
|
|
773
|
+
.then((val) => {
|
|
774
|
+
tx.oncomplete = () => resolve(val);
|
|
775
|
+
tx.onerror = () => reject(tx.error);
|
|
776
|
+
})
|
|
777
|
+
.catch(reject);
|
|
778
|
+
});
|
|
779
|
+
};
|
|
780
|
+
const buildKey = (modelId, version) => `${modelId}:${version}`;
|
|
781
|
+
const putModelComplete = async (modelId, version, metadata, files) => {
|
|
782
|
+
const finalMeta = {
|
|
783
|
+
...metadata,
|
|
784
|
+
modelId,
|
|
785
|
+
modelVersion: version,
|
|
786
|
+
status: 'complete',
|
|
787
|
+
updatedAt: Date.now(),
|
|
788
|
+
sizeBytes: metadata.sizeBytes
|
|
789
|
+
};
|
|
790
|
+
await runTx('readwrite', async (store) => {
|
|
791
|
+
const record = { key: buildKey(modelId, version), metadata: finalMeta, files };
|
|
792
|
+
store.put(record);
|
|
793
|
+
});
|
|
794
|
+
};
|
|
795
|
+
const getModel = async (modelId, version) => {
|
|
796
|
+
const key = buildKey(modelId, version);
|
|
797
|
+
return runTx('readonly', async (store) => {
|
|
798
|
+
return new Promise((resolve, reject) => {
|
|
799
|
+
const req = store.get(key);
|
|
800
|
+
req.onsuccess = () => {
|
|
801
|
+
const record = req.result;
|
|
802
|
+
if (!record || record.metadata.status !== 'complete') {
|
|
803
|
+
resolve(null);
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
resolve({ metadata: record.metadata, files: record.files });
|
|
807
|
+
};
|
|
808
|
+
req.onerror = () => reject(req.error);
|
|
809
|
+
});
|
|
810
|
+
});
|
|
811
|
+
};
|
|
812
|
+
const clearModel = async (modelId, version) => {
|
|
813
|
+
await runTx('readwrite', async (store) => {
|
|
814
|
+
store.delete(buildKey(modelId, version));
|
|
815
|
+
});
|
|
816
|
+
};
|
|
817
|
+
const clearAllModels = async () => {
|
|
818
|
+
await runTx('readwrite', async (store) => {
|
|
819
|
+
store.clear();
|
|
820
|
+
});
|
|
821
|
+
};
|
|
822
|
+
|
|
823
|
+
const CACHED_MODEL_ID_KEY = 'zerogpu_cached_model_id';
|
|
824
|
+
const safeGetItem = (key) => {
|
|
825
|
+
try {
|
|
826
|
+
return window.localStorage.getItem(key);
|
|
827
|
+
}
|
|
828
|
+
catch {
|
|
829
|
+
return null;
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
const safeSetItem = (key, value) => {
|
|
833
|
+
try {
|
|
834
|
+
window.localStorage.setItem(key, value);
|
|
835
|
+
}
|
|
836
|
+
catch {
|
|
837
|
+
// ignore storage failures
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
const safeRemoveItem = (key) => {
|
|
841
|
+
try {
|
|
842
|
+
window.localStorage.removeItem(key);
|
|
843
|
+
}
|
|
844
|
+
catch {
|
|
845
|
+
// ignore storage failures
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
const getCachedModelId = () => safeGetItem(CACHED_MODEL_ID_KEY);
|
|
849
|
+
const getCachedModelInfo = (modelId) => {
|
|
850
|
+
const raw = safeGetItem(modelId);
|
|
851
|
+
if (!raw)
|
|
852
|
+
return null;
|
|
853
|
+
try {
|
|
854
|
+
return JSON.parse(raw);
|
|
855
|
+
}
|
|
856
|
+
catch {
|
|
857
|
+
return null;
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
const setCachedModelInfo = (info) => {
|
|
861
|
+
safeSetItem(CACHED_MODEL_ID_KEY, info.modelId);
|
|
862
|
+
safeSetItem(info.modelId, JSON.stringify(info));
|
|
863
|
+
};
|
|
864
|
+
const clearCachedModelInfo = (modelId) => {
|
|
865
|
+
const existing = modelId ?? getCachedModelId();
|
|
866
|
+
if (existing) {
|
|
867
|
+
safeRemoveItem(existing);
|
|
868
|
+
}
|
|
869
|
+
safeRemoveItem(CACHED_MODEL_ID_KEY);
|
|
870
|
+
};
|
|
871
|
+
|
|
872
|
+
const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
|
|
873
|
+
initLogger(config.telemetry);
|
|
874
|
+
const logger = getLogger();
|
|
875
|
+
setConfig(config);
|
|
876
|
+
const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
|
|
877
|
+
const isFreshDevice = !providedDeviceId && !storedDeviceId;
|
|
878
|
+
const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
|
|
879
|
+
if (providedDeviceId) {
|
|
880
|
+
setDeviceId(providedDeviceId);
|
|
881
|
+
}
|
|
882
|
+
const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
|
|
883
|
+
const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
|
|
884
|
+
setDeviceContext(deviceId, sanitizedDeviceInfo);
|
|
885
|
+
if (!edgeOperatorKey) {
|
|
886
|
+
throw new Error('Missing required header: x-edge-operator-key');
|
|
887
|
+
}
|
|
888
|
+
if (rawDeviceInfo.camera?.previewDataUrl) {
|
|
889
|
+
try {
|
|
890
|
+
window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
|
|
891
|
+
detail: {
|
|
892
|
+
deviceId,
|
|
893
|
+
previewDataUrl: rawDeviceInfo.camera.previewDataUrl,
|
|
894
|
+
camera: sanitizedDeviceInfo.camera
|
|
895
|
+
}
|
|
896
|
+
}));
|
|
897
|
+
}
|
|
898
|
+
catch {
|
|
899
|
+
logger.warn('Unable to dispatch camera preview event');
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
const cachedModelId = isFreshDevice ? null : getCachedModelId();
|
|
903
|
+
setCachedModelId(cachedModelId);
|
|
904
|
+
let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
|
|
905
|
+
if (!isFreshDevice) {
|
|
906
|
+
logger.info('Cache lookup', {
|
|
907
|
+
cachedModelId,
|
|
908
|
+
hasCachedInfo: Boolean(cachedInfo)
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
let cachedAdapter;
|
|
912
|
+
let cachedSampleMetrics;
|
|
913
|
+
let cacheInvalid = false;
|
|
914
|
+
const logFlow = (flow, details) => {
|
|
915
|
+
logger.info(`[Flow] ${flow}`, details ?? {});
|
|
916
|
+
};
|
|
917
|
+
if (isFreshDevice) {
|
|
918
|
+
logFlow('Fresh device detected; skip cache checks');
|
|
919
|
+
cachedInfo = null;
|
|
920
|
+
cachedAdapter = undefined;
|
|
921
|
+
cachedSampleMetrics = undefined;
|
|
922
|
+
cacheInvalid = false;
|
|
923
|
+
}
|
|
924
|
+
else if (cachedInfo &&
|
|
925
|
+
cachedInfo.modelId &&
|
|
926
|
+
cachedInfo.modelUrl &&
|
|
927
|
+
cachedInfo.taskType &&
|
|
928
|
+
cachedInfo.requiredFiles) {
|
|
929
|
+
logFlow('Cache detected; validating cached model', {
|
|
930
|
+
modelId: cachedInfo.modelId,
|
|
931
|
+
taskType: cachedInfo.taskType
|
|
932
|
+
});
|
|
933
|
+
if (!cachedInfo.modelVersion || !cachedInfo.sample?.text || !cachedInfo.requiredFiles) {
|
|
934
|
+
cacheInvalid = true;
|
|
935
|
+
cachedSampleMetrics = {
|
|
936
|
+
taskType: cachedInfo.taskType,
|
|
937
|
+
processingTimeMs: 0,
|
|
938
|
+
error: true,
|
|
939
|
+
errorMessage: 'response from processing sample'
|
|
940
|
+
};
|
|
941
|
+
logger.warn('Pre-register cache invalid: missing metadata', {
|
|
942
|
+
modelId: cachedInfo.modelId,
|
|
943
|
+
taskType: cachedInfo.taskType
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
else {
|
|
947
|
+
const hasCachedFiles = await hasCachedFilesForModel(cachedInfo);
|
|
948
|
+
if (!hasCachedFiles) {
|
|
949
|
+
cacheInvalid = true;
|
|
950
|
+
cachedSampleMetrics = {
|
|
951
|
+
taskType: cachedInfo.taskType,
|
|
952
|
+
processingTimeMs: 0,
|
|
953
|
+
error: true,
|
|
954
|
+
errorMessage: 'response from processing sample'
|
|
955
|
+
};
|
|
956
|
+
logger.warn('Pre-register cache invalid: required files missing', {
|
|
957
|
+
modelId: cachedInfo.modelId,
|
|
958
|
+
taskType: cachedInfo.taskType
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
else {
|
|
962
|
+
const slmConfig = buildSlmConfigFromCached(cachedInfo);
|
|
963
|
+
const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
|
|
964
|
+
if (!factory) {
|
|
965
|
+
cacheInvalid = true;
|
|
966
|
+
cachedSampleMetrics = {
|
|
967
|
+
taskType: cachedInfo.taskType,
|
|
968
|
+
processingTimeMs: 0,
|
|
969
|
+
error: true,
|
|
970
|
+
errorMessage: 'no_adapter_factory'
|
|
971
|
+
};
|
|
972
|
+
logger.warn('No adapter factory for cached model', {
|
|
973
|
+
framework: slmConfig.inferenceFramework,
|
|
974
|
+
taskType: slmConfig.taskType
|
|
975
|
+
});
|
|
976
|
+
}
|
|
977
|
+
else {
|
|
978
|
+
const loadResult = await factory.load(slmConfig, { allowDownload: hasCachedFiles });
|
|
979
|
+
if (!loadResult.adapter || loadResult.error) {
|
|
980
|
+
cacheInvalid = true;
|
|
981
|
+
cachedSampleMetrics = {
|
|
982
|
+
taskType: cachedInfo.taskType,
|
|
983
|
+
processingTimeMs: 0,
|
|
984
|
+
error: true,
|
|
985
|
+
errorMessage: 'response from processing sample'
|
|
986
|
+
};
|
|
987
|
+
logger.warn('Pre-register cache invalid: adapter load failed', {
|
|
988
|
+
modelId: cachedInfo.modelId,
|
|
989
|
+
taskType: cachedInfo.taskType,
|
|
990
|
+
error: loadResult.error?.message
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
else {
|
|
994
|
+
cachedAdapter = loadResult.adapter;
|
|
995
|
+
setAdapter(cachedInfo.modelId, cachedAdapter);
|
|
996
|
+
const sample = cachedInfo.sample;
|
|
997
|
+
const sampleResult = await cachedAdapter.runSample(sample);
|
|
998
|
+
cachedSampleMetrics = {
|
|
999
|
+
taskType: cachedInfo.taskType,
|
|
1000
|
+
processingTimeMs: sampleResult.processingTimeMs,
|
|
1001
|
+
error: sampleResult.error,
|
|
1002
|
+
errorMessage: sampleResult.error
|
|
1003
|
+
? (sampleResult.errorMessage ?? 'response from processing sample')
|
|
1004
|
+
: undefined
|
|
1005
|
+
};
|
|
1006
|
+
if (!sampleResult.ok) {
|
|
1007
|
+
cacheInvalid = true;
|
|
1008
|
+
logFlow('Cache invalid; sample test failed', {
|
|
1009
|
+
reason: 'sample_failed'
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
else if (cachedModelId) {
|
|
1018
|
+
cacheInvalid = true;
|
|
1019
|
+
cachedSampleMetrics = {
|
|
1020
|
+
taskType: cachedInfo?.taskType ?? 'summary',
|
|
1021
|
+
processingTimeMs: 0,
|
|
1022
|
+
error: true,
|
|
1023
|
+
errorMessage: 'response from processing sample'
|
|
1024
|
+
};
|
|
1025
|
+
logFlow('Cache metadata missing; will purge before register', {
|
|
1026
|
+
modelId: cachedModelId
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
else {
|
|
1030
|
+
logFlow('No cache detected; first run flow');
|
|
1031
|
+
}
|
|
1032
|
+
if (cachedSampleMetrics) {
|
|
1033
|
+
logFlow('Cached sample evaluated', cachedSampleMetrics);
|
|
1034
|
+
}
|
|
1035
|
+
if (cacheInvalid) {
|
|
1036
|
+
await clearAllModels().catch(() => { });
|
|
1037
|
+
await clearTransformersCaches().catch(() => { });
|
|
1038
|
+
clearCachedModelInfo(cachedModelId);
|
|
1039
|
+
setCachedModelId(null);
|
|
1040
|
+
cachedInfo = null;
|
|
1041
|
+
cachedAdapter = undefined;
|
|
1042
|
+
setAdaptersByModelId({});
|
|
1043
|
+
setModelInfosByModelId({});
|
|
1044
|
+
}
|
|
1045
|
+
const registerPayload = {
|
|
1046
|
+
deviceId,
|
|
1047
|
+
sdkVersion: config.sdkVersion,
|
|
1048
|
+
cachedModels: cachedInfo && !cacheInvalid
|
|
1049
|
+
? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
|
|
1050
|
+
: [],
|
|
1051
|
+
device: sanitizedDeviceInfo
|
|
1052
|
+
};
|
|
1053
|
+
let registerResponse;
|
|
1054
|
+
let assignedModels = [];
|
|
1055
|
+
const adaptersByModelId = {};
|
|
1056
|
+
const modelInfosByModelId = {};
|
|
1057
|
+
const modelStatuses = {};
|
|
1058
|
+
let loadErrorMessage;
|
|
1059
|
+
let postRegisterSample;
|
|
1060
|
+
try {
|
|
1061
|
+
registerResponse = await registerDevice(config, registerPayload, {
|
|
1062
|
+
edgeOperatorKey
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
catch (err) {
|
|
1066
|
+
if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
|
|
1067
|
+
logger.warn('Register auth failed, stopping lifecycle');
|
|
1068
|
+
logFlow('Auth failure; no WS connection', { status: err.status });
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
throw err;
|
|
1072
|
+
}
|
|
1073
|
+
logger.info('Register response received:', {
|
|
1074
|
+
deviceId: registerResponse.deviceId,
|
|
1075
|
+
wsUrl: registerResponse.wsUrl
|
|
1076
|
+
});
|
|
1077
|
+
if (!registerResponse.wsUrl) {
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
|
|
1081
|
+
const primaryModel = assignedModels[0];
|
|
1082
|
+
for (const model of assignedModels) {
|
|
1083
|
+
modelStatuses[getModelStatusKey(model)] = 'idle';
|
|
1084
|
+
modelInfosByModelId[model.modelId] = model;
|
|
1085
|
+
}
|
|
1086
|
+
if (!primaryModel) {
|
|
1087
|
+
await clearAllModels().catch(() => { });
|
|
1088
|
+
await clearTransformersCaches().catch(() => { });
|
|
1089
|
+
clearCachedModelInfo(cachedModelId);
|
|
1090
|
+
setCachedModelId(null);
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
setSessionKey(registerResponse.sessionKey);
|
|
1094
|
+
setModelInfosByModelId(modelInfosByModelId);
|
|
1095
|
+
setModelInfo(primaryModel);
|
|
1096
|
+
setSample(primaryModel.sample);
|
|
1097
|
+
logger.info('Runtime globals updated from register response', {
|
|
1098
|
+
sessionKey: registerResponse.sessionKey,
|
|
1099
|
+
taskType: primaryModel.taskType,
|
|
1100
|
+
sample: primaryModel.sample
|
|
1101
|
+
});
|
|
1102
|
+
if (!cachedInfo || cachedInfo.modelId !== primaryModel.modelId || cacheInvalid) {
|
|
1103
|
+
if (cachedInfo && cachedInfo.modelId !== primaryModel.modelId) {
|
|
1104
|
+
logFlow('Server assigned different model; refreshing cache', {
|
|
1105
|
+
cachedModelId: cachedInfo.modelId,
|
|
1106
|
+
assignedModelId: primaryModel.modelId
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
await clearAllModels().catch(() => { });
|
|
1110
|
+
await clearTransformersCaches().catch(() => { });
|
|
1111
|
+
clearCachedModelInfo(cachedModelId);
|
|
1112
|
+
setCachedModelId(null);
|
|
1113
|
+
setAdaptersByModelId({});
|
|
1114
|
+
const slmConfig = buildSlmConfigFromAssigned(primaryModel);
|
|
1115
|
+
const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
|
|
1116
|
+
if (!factory) {
|
|
1117
|
+
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
1118
|
+
loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
|
|
1119
|
+
}
|
|
1120
|
+
else {
|
|
1121
|
+
const loadResult = await factory.load(slmConfig);
|
|
1122
|
+
loadErrorMessage = loadResult.error?.message;
|
|
1123
|
+
if (loadResult.adapter) {
|
|
1124
|
+
adaptersByModelId[primaryModel.modelId] = loadResult.adapter;
|
|
1125
|
+
setAdapter(primaryModel.modelId, loadResult.adapter);
|
|
1126
|
+
setCachedModelId(primaryModel.modelId);
|
|
1127
|
+
setCachedModelInfo({
|
|
1128
|
+
modelId: primaryModel.modelId,
|
|
1129
|
+
modelVersion: primaryModel.modelVersion ?? '1',
|
|
1130
|
+
modelUrl: primaryModel.modelUrl,
|
|
1131
|
+
modelRepoId: primaryModel.modelRepoId,
|
|
1132
|
+
maxInputTokens: primaryModel.maxTokens,
|
|
1133
|
+
quantized: primaryModel.quantized,
|
|
1134
|
+
quantization: primaryModel.quantization,
|
|
1135
|
+
taskType: primaryModel.taskType,
|
|
1136
|
+
sizeBytes: primaryModel.sizeBytes,
|
|
1137
|
+
sample: primaryModel.sample,
|
|
1138
|
+
requiredFiles: primaryModel.requiredFiles
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
else {
|
|
1142
|
+
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
else if (cachedInfo && cachedInfo.modelId === primaryModel.modelId && cachedAdapter) {
|
|
1147
|
+
logFlow('Cache reuse flow; modelId matches assigned', { modelId: primaryModel.modelId });
|
|
1148
|
+
setCachedModelId(primaryModel.modelId);
|
|
1149
|
+
adaptersByModelId[primaryModel.modelId] = cachedAdapter;
|
|
1150
|
+
setAdapter(primaryModel.modelId, cachedAdapter);
|
|
1151
|
+
setCachedModelInfo({
|
|
1152
|
+
modelId: primaryModel.modelId,
|
|
1153
|
+
modelVersion: primaryModel.modelVersion ?? '1',
|
|
1154
|
+
modelUrl: primaryModel.modelUrl,
|
|
1155
|
+
modelRepoId: primaryModel.modelRepoId,
|
|
1156
|
+
maxInputTokens: primaryModel.maxTokens,
|
|
1157
|
+
quantized: primaryModel.quantized,
|
|
1158
|
+
quantization: primaryModel.quantization,
|
|
1159
|
+
taskType: primaryModel.taskType,
|
|
1160
|
+
sizeBytes: primaryModel.sizeBytes,
|
|
1161
|
+
sample: primaryModel.sample,
|
|
1162
|
+
requiredFiles: primaryModel.requiredFiles
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
// Load secondary models
|
|
1166
|
+
for (const model of assignedModels) {
|
|
1167
|
+
if (model.modelId === primaryModel.modelId)
|
|
1168
|
+
continue;
|
|
1169
|
+
const slmConfig = buildSlmConfigFromAssigned(model);
|
|
1170
|
+
const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
|
|
1171
|
+
if (!factory) {
|
|
1172
|
+
modelStatuses[getModelStatusKey(model)] = 'error';
|
|
1173
|
+
logger.warn('No adapter factory for secondary model', {
|
|
1174
|
+
modelId: model.modelId,
|
|
1175
|
+
framework: slmConfig.inferenceFramework,
|
|
1176
|
+
taskType: slmConfig.taskType
|
|
1177
|
+
});
|
|
1178
|
+
continue;
|
|
1179
|
+
}
|
|
1180
|
+
const loadResult = await factory.load(slmConfig);
|
|
1181
|
+
if (loadResult.adapter) {
|
|
1182
|
+
adaptersByModelId[model.modelId] = loadResult.adapter;
|
|
1183
|
+
setAdapter(model.modelId, loadResult.adapter);
|
|
1184
|
+
}
|
|
1185
|
+
else {
|
|
1186
|
+
modelStatuses[getModelStatusKey(model)] = 'error';
|
|
1187
|
+
logger.warn('Failed to load secondary model', {
|
|
1188
|
+
modelId: model.modelId,
|
|
1189
|
+
taskType: model.taskType,
|
|
1190
|
+
error: loadResult.error?.message
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
const primaryAdapter = adaptersByModelId[primaryModel.modelId];
|
|
1195
|
+
if (!primaryAdapter) {
|
|
1196
|
+
setStatus('error');
|
|
1197
|
+
const reason = loadErrorMessage || 'model_not_ready';
|
|
1198
|
+
if (registerResponse?.wsUrl) {
|
|
1199
|
+
await reportInitFailureOverWebSocket({
|
|
1200
|
+
wsUrl: registerResponse.wsUrl,
|
|
1201
|
+
hello: {
|
|
1202
|
+
type: 'hello',
|
|
1203
|
+
deviceId: registerResponse.deviceId,
|
|
1204
|
+
sessionKey: registerResponse.sessionKey,
|
|
1205
|
+
sdkVersion: config.sdkVersion,
|
|
1206
|
+
slmConfig: assignedModels.map((model) => ({
|
|
1207
|
+
modelId: model.modelId,
|
|
1208
|
+
modelVersion: model.modelVersion ?? '1',
|
|
1209
|
+
status: modelStatuses[getModelStatusKey(model)] || 'idle'
|
|
1210
|
+
}))
|
|
1211
|
+
},
|
|
1212
|
+
ack: {
|
|
1213
|
+
type: 'hello_ack',
|
|
1214
|
+
deviceId: registerResponse.deviceId,
|
|
1215
|
+
sdkVersion: config.sdkVersion,
|
|
1216
|
+
sessionKey: registerResponse.sessionKey,
|
|
1217
|
+
status: 'error',
|
|
1218
|
+
timestamp: Date.now(),
|
|
1219
|
+
errorMessage: `primary_model_load_failed:${reason}`
|
|
1220
|
+
}
|
|
1221
|
+
}).catch(() => { });
|
|
1222
|
+
}
|
|
1223
|
+
logger.error('Primary model failed to initialize; aborting lifecycle before WebSocket connect', {
|
|
1224
|
+
modelId: primaryModel.modelId,
|
|
1225
|
+
modelVersion: primaryModel.modelVersion,
|
|
1226
|
+
taskType: primaryModel.taskType,
|
|
1227
|
+
reason
|
|
1228
|
+
});
|
|
1229
|
+
throw new Error(`primary_model_load_failed:${reason}`);
|
|
1230
|
+
}
|
|
1231
|
+
if (primaryAdapter && primaryModel.sample?.text) {
|
|
1232
|
+
postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
|
|
1233
|
+
logger.info('Post-register sample test result', {
|
|
1234
|
+
taskType: primaryModel.taskType,
|
|
1235
|
+
ok: postRegisterSample.ok,
|
|
1236
|
+
error: postRegisterSample.error,
|
|
1237
|
+
errorMessage: postRegisterSample.errorMessage,
|
|
1238
|
+
processingTimeMs: postRegisterSample.processingTimeMs
|
|
1239
|
+
});
|
|
1240
|
+
if (postRegisterSample.error) {
|
|
1241
|
+
modelStatuses[getModelStatusKey(primaryModel)] = 'error';
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
const helloDeviceId = registerResponse.deviceId;
|
|
1245
|
+
const helloSlmConfig = assignedModels.map((model) => ({
|
|
1246
|
+
modelId: model.modelId,
|
|
1247
|
+
modelVersion: model.modelVersion ?? '1',
|
|
1248
|
+
status: modelStatuses[getModelStatusKey(model)] || 'idle'
|
|
1249
|
+
}));
|
|
1250
|
+
const hello = {
|
|
1251
|
+
type: 'hello',
|
|
1252
|
+
deviceId: helloDeviceId,
|
|
1253
|
+
sessionKey: registerResponse.sessionKey,
|
|
1254
|
+
sdkVersion: config.sdkVersion,
|
|
1255
|
+
slmConfig: helloSlmConfig
|
|
1256
|
+
};
|
|
1257
|
+
const client = new WebSocketClient({
|
|
1258
|
+
url: registerResponse.wsUrl,
|
|
1259
|
+
hello,
|
|
1260
|
+
onMessage: (message) => {
|
|
1261
|
+
if ('requests' in message && Array.isArray(message.requests)) {
|
|
1262
|
+
handleIncomingMessage(message);
|
|
1263
|
+
}
|
|
1264
|
+
else if ('type' in message && message.type === 'hello_ack') {
|
|
1265
|
+
const ack = message;
|
|
1266
|
+
logger.info('Received WS hello_ack', ack);
|
|
1267
|
+
setStatus(ack.status === 'error' ? 'error' : 'idle');
|
|
1268
|
+
}
|
|
1269
|
+
else {
|
|
1270
|
+
logger.debug('Unhandled WS message', message);
|
|
1271
|
+
}
|
|
1272
|
+
},
|
|
1273
|
+
onClose: () => {
|
|
1274
|
+
setStatus('error');
|
|
1275
|
+
},
|
|
1276
|
+
onError: () => {
|
|
1277
|
+
setStatus('error');
|
|
1278
|
+
}
|
|
1279
|
+
});
|
|
1280
|
+
setWebSocket(client);
|
|
1281
|
+
setStatus('idle');
|
|
1282
|
+
};
|
|
1283
|
+
const normalizeAssignedModels = (slmConfig) => {
|
|
1284
|
+
if (!Array.isArray(slmConfig))
|
|
1285
|
+
return [];
|
|
1286
|
+
const normalized = [];
|
|
1287
|
+
for (const model of slmConfig) {
|
|
1288
|
+
if (!model?.modelId || !model?.modelVersion || !model?.modelUrl)
|
|
1289
|
+
continue;
|
|
1290
|
+
const taskType = pickTaskType(model);
|
|
1291
|
+
if (!taskType)
|
|
1292
|
+
continue;
|
|
1293
|
+
normalized.push({
|
|
1294
|
+
modelId: model.modelId,
|
|
1295
|
+
modelType: model.modelType,
|
|
1296
|
+
modelVersion: model.modelVersion,
|
|
1297
|
+
modelUrl: model.modelUrl,
|
|
1298
|
+
modelRepoId: model.modelRepoId,
|
|
1299
|
+
maxTokens: model.maxTokens,
|
|
1300
|
+
requiredFiles: model.requiredFiles,
|
|
1301
|
+
inferenceFramework: model.inferenceFramework,
|
|
1302
|
+
quantized: Boolean(model.quantized),
|
|
1303
|
+
quantization: model.quantization,
|
|
1304
|
+
taskType,
|
|
1305
|
+
sizeBytes: model.sizeBytes,
|
|
1306
|
+
sample: model.sample
|
|
1307
|
+
});
|
|
1308
|
+
}
|
|
1309
|
+
return normalized;
|
|
1310
|
+
};
|
|
1311
|
+
const pickTaskType = (model) => {
|
|
1312
|
+
const declared = model.taskType;
|
|
1313
|
+
if (typeof declared === 'string' && declared.length > 0) {
|
|
1314
|
+
return declared;
|
|
1315
|
+
}
|
|
1316
|
+
return null;
|
|
1317
|
+
};
|
|
1318
|
+
const getModelStatusKey = (model) => `${model.modelId}@${model.modelVersion ?? '1'}`;
|
|
1319
|
+
const buildSlmConfigFromCached = (cached) => ({
|
|
1320
|
+
modelId: cached.modelId,
|
|
1321
|
+
modelVersion: cached.modelVersion || '1',
|
|
1322
|
+
modelUrl: cached.modelUrl,
|
|
1323
|
+
modelRepoId: cached.modelRepoId,
|
|
1324
|
+
modelType: cached.modelType,
|
|
1325
|
+
inferenceFramework: cached.inferenceFramework,
|
|
1326
|
+
requiredFiles: cached.requiredFiles,
|
|
1327
|
+
quantized: Boolean(cached.quantized),
|
|
1328
|
+
quantization: cached.quantization,
|
|
1329
|
+
taskType: cached.taskType,
|
|
1330
|
+
maxInputTokens: cached.maxInputTokens
|
|
1331
|
+
});
|
|
1332
|
+
const buildSlmConfigFromAssigned = (modelInfo) => ({
|
|
1333
|
+
modelId: modelInfo.modelId,
|
|
1334
|
+
modelVersion: modelInfo.modelVersion ?? '1',
|
|
1335
|
+
modelUrl: modelInfo.modelUrl,
|
|
1336
|
+
modelRepoId: modelInfo.modelRepoId,
|
|
1337
|
+
modelType: modelInfo.modelType,
|
|
1338
|
+
inferenceFramework: modelInfo.inferenceFramework,
|
|
1339
|
+
requiredFiles: modelInfo.requiredFiles,
|
|
1340
|
+
quantized: modelInfo.quantized ?? false,
|
|
1341
|
+
quantization: modelInfo.quantization,
|
|
1342
|
+
taskType: modelInfo.taskType,
|
|
1343
|
+
maxInputTokens: modelInfo.maxTokens
|
|
1344
|
+
});
|
|
1345
|
+
const hasCachedFilesForModel = async (cached) => {
|
|
1346
|
+
if (!Array.isArray(cached.requiredFiles))
|
|
1347
|
+
return false;
|
|
1348
|
+
if (cached.requiredFiles.length === 0)
|
|
1349
|
+
return true;
|
|
1350
|
+
const requiredFiles = normalizeRequiredFiles(cached.requiredFiles);
|
|
1351
|
+
if (!requiredFiles.length)
|
|
1352
|
+
return false;
|
|
1353
|
+
try {
|
|
1354
|
+
const model = await getModel(cached.modelId, cached.modelVersion || '1');
|
|
1355
|
+
if (!model?.files)
|
|
1356
|
+
return false;
|
|
1357
|
+
const storedKeys = new Set();
|
|
1358
|
+
for (const key of Object.keys(model.files)) {
|
|
1359
|
+
const normalized = key.replace(/^\/+/, '').replace(/^resolve\/main\//, '');
|
|
1360
|
+
storedKeys.add(normalized);
|
|
1361
|
+
const modelScopedPrefix = `${cached.modelId}/`;
|
|
1362
|
+
if (normalized.startsWith(modelScopedPrefix)) {
|
|
1363
|
+
storedKeys.add(normalized.slice(modelScopedPrefix.length));
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
return requiredFiles.every((file) => {
|
|
1367
|
+
if (storedKeys.has(file))
|
|
1368
|
+
return true;
|
|
1369
|
+
if (storedKeys.has(`onnx/${file}`))
|
|
1370
|
+
return true;
|
|
1371
|
+
if (file.startsWith('onnx/') && storedKeys.has(file.slice('onnx/'.length)))
|
|
1372
|
+
return true;
|
|
1373
|
+
return false;
|
|
1374
|
+
});
|
|
1375
|
+
}
|
|
1376
|
+
catch {
|
|
1377
|
+
return false;
|
|
1378
|
+
}
|
|
1379
|
+
};
|
|
1380
|
+
const normalizeRequiredFiles = (requiredFiles) => requiredFiles
|
|
1381
|
+
.filter((file) => typeof file === 'object' && file !== null && typeof file.name === 'string')
|
|
1382
|
+
.map((file) => file.name.trim().replace(/^\/+/, ''))
|
|
1383
|
+
.filter((name) => typeof name === 'string' && name.length > 0);
|
|
1384
|
+
const clearTransformersCaches = async () => {
|
|
1385
|
+
if (typeof caches === 'undefined')
|
|
1386
|
+
return;
|
|
1387
|
+
const cacheNames = await caches.keys();
|
|
1388
|
+
const targetNames = cacheNames.filter((name) => name.includes('transformers-cache'));
|
|
1389
|
+
await Promise.all(targetNames.map((name) => caches.delete(name)));
|
|
1390
|
+
};
|
|
1391
|
+
const reportInitFailureOverWebSocket = async (options) => {
|
|
1392
|
+
await new Promise((resolve) => {
|
|
1393
|
+
let settled = false;
|
|
1394
|
+
const settle = () => {
|
|
1395
|
+
if (settled)
|
|
1396
|
+
return;
|
|
1397
|
+
settled = true;
|
|
1398
|
+
resolve();
|
|
1399
|
+
};
|
|
1400
|
+
const timeout = window.setTimeout(settle, 1500);
|
|
1401
|
+
try {
|
|
1402
|
+
new WebSocketClient({
|
|
1403
|
+
url: options.wsUrl,
|
|
1404
|
+
hello: options.hello,
|
|
1405
|
+
ack: options.ack,
|
|
1406
|
+
closeAfterAck: true,
|
|
1407
|
+
closeCode: 4001,
|
|
1408
|
+
closeReason: 'primary_model_load_failed',
|
|
1409
|
+
onMessage: () => { },
|
|
1410
|
+
onClose: () => {
|
|
1411
|
+
window.clearTimeout(timeout);
|
|
1412
|
+
settle();
|
|
1413
|
+
},
|
|
1414
|
+
onError: () => {
|
|
1415
|
+
window.clearTimeout(timeout);
|
|
1416
|
+
settle();
|
|
1417
|
+
}
|
|
1418
|
+
});
|
|
1419
|
+
}
|
|
1420
|
+
catch {
|
|
1421
|
+
window.clearTimeout(timeout);
|
|
1422
|
+
settle();
|
|
1423
|
+
}
|
|
1424
|
+
});
|
|
1425
|
+
};
|
|
1426
|
+
const stripCameraPreview = (info) => {
|
|
1427
|
+
if (!info.camera?.previewDataUrl) {
|
|
1428
|
+
return info;
|
|
1429
|
+
}
|
|
1430
|
+
return {
|
|
1431
|
+
...info,
|
|
1432
|
+
camera: { ...info.camera, previewDataUrl: undefined }
|
|
1433
|
+
};
|
|
1434
|
+
};
|
|
1435
|
+
|
|
1436
|
+
const measure = async (fn) => {
|
|
1437
|
+
const start = performance.now();
|
|
1438
|
+
const result = await fn();
|
|
1439
|
+
return { result, ms: Math.round(performance.now() - start) };
|
|
1440
|
+
};
|
|
1441
|
+
|
|
1442
|
+
const TRANSFORMERS_CDN = 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js';
|
|
1443
|
+
let transformersRuntimePromise = null;
|
|
1444
|
+
const serializeError$5 = (error) => {
|
|
1445
|
+
if (error instanceof Error) {
|
|
1446
|
+
return { name: error.name, message: error.message, stack: error.stack };
|
|
1447
|
+
}
|
|
1448
|
+
return { message: String(error) };
|
|
1449
|
+
};
|
|
1450
|
+
const ensureTransformersRuntime = () => {
|
|
1451
|
+
if (window.TransformersPipeline) {
|
|
1452
|
+
return Promise.resolve();
|
|
1453
|
+
}
|
|
1454
|
+
if (!transformersRuntimePromise) {
|
|
1455
|
+
transformersRuntimePromise = (async () => {
|
|
1456
|
+
try {
|
|
1457
|
+
const runtimeUrl = TRANSFORMERS_CDN;
|
|
1458
|
+
const transformersModule = await import(/* @vite-ignore */ runtimeUrl);
|
|
1459
|
+
const pipeline = transformersModule?.pipeline;
|
|
1460
|
+
const env = transformersModule?.env;
|
|
1461
|
+
if (typeof pipeline !== 'function' || !env) {
|
|
1462
|
+
throw new Error('Transformers runtime missing pipeline/env exports');
|
|
1463
|
+
}
|
|
1464
|
+
env.allowLocalModels = true;
|
|
1465
|
+
env.allowRemoteModels = true;
|
|
1466
|
+
if (env?.backends?.onnx?.env) {
|
|
1467
|
+
env.backends.onnx.env.logLevel = 'warning';
|
|
1468
|
+
}
|
|
1469
|
+
if ('logLevel' in env) {
|
|
1470
|
+
env.logLevel = 'warning';
|
|
1471
|
+
}
|
|
1472
|
+
window.TransformersPipeline = pipeline;
|
|
1473
|
+
window.TransformersEnv = env;
|
|
1474
|
+
}
|
|
1475
|
+
catch (error) {
|
|
1476
|
+
transformersRuntimePromise = null;
|
|
1477
|
+
console.error('[ZeroGPU][SLM] Failed to import Transformers runtime', {
|
|
1478
|
+
runtimeUrl: TRANSFORMERS_CDN,
|
|
1479
|
+
error: serializeError$5(error)
|
|
1480
|
+
});
|
|
1481
|
+
throw error;
|
|
1482
|
+
}
|
|
1483
|
+
})();
|
|
1484
|
+
}
|
|
1485
|
+
return transformersRuntimePromise;
|
|
1486
|
+
};
|
|
1487
|
+
const sanitizeBaseUrl = (url) => url.replace(/\/$/, '');
|
|
1488
|
+
const HUGGING_FACE_BASE = 'https://huggingface.co';
|
|
1489
|
+
const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());
|
|
1490
|
+
const normalizeRepoId = (value) => {
|
|
1491
|
+
const trimmed = value.trim();
|
|
1492
|
+
if (!trimmed)
|
|
1493
|
+
return '';
|
|
1494
|
+
if (isHttpUrl(trimmed)) {
|
|
1495
|
+
try {
|
|
1496
|
+
const url = new URL(trimmed);
|
|
1497
|
+
return url.pathname.replace(/^\/+|\/+$/g, '');
|
|
1498
|
+
}
|
|
1499
|
+
catch {
|
|
1500
|
+
return '';
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
return trimmed.replace(/^\/+|\/+$/g, '');
|
|
1504
|
+
};
|
|
1505
|
+
const buildRepoResolveBase = (repoId) => {
|
|
1506
|
+
const normalizedRepoId = normalizeRepoId(repoId);
|
|
1507
|
+
if (!normalizedRepoId)
|
|
1508
|
+
return '';
|
|
1509
|
+
return sanitizeBaseUrl(`${HUGGING_FACE_BASE}/${normalizedRepoId}/resolve/main`);
|
|
1510
|
+
};
|
|
1511
|
+
const buildFileBase = (modelUrl, modelRepoId) => {
|
|
1512
|
+
const trimmed = (modelUrl || '').trim();
|
|
1513
|
+
if (isHttpUrl(trimmed)) {
|
|
1514
|
+
return sanitizeBaseUrl(trimmed);
|
|
1515
|
+
}
|
|
1516
|
+
const repoBase = buildRepoResolveBase(modelRepoId || trimmed);
|
|
1517
|
+
if (repoBase)
|
|
1518
|
+
return repoBase;
|
|
1519
|
+
return sanitizeBaseUrl(trimmed);
|
|
1520
|
+
};
|
|
1521
|
+
const normalizeCacheRelativePath = (value) => value.replace(/^\/+/, '').replace(/^resolve\/main\//, '').split('?')[0];
|
|
1522
|
+
const buildModelFileCacheKey = (modelId, relative) => `${modelId}/${normalizeCacheRelativePath(relative)}`;
|
|
1523
|
+
const resolveOnnxWasmPath = () => {
|
|
1524
|
+
try {
|
|
1525
|
+
return new URL('/onnx-wasm/', window.location.origin).toString();
|
|
1526
|
+
}
|
|
1527
|
+
catch {
|
|
1528
|
+
return '/onnx-wasm/';
|
|
1529
|
+
}
|
|
1530
|
+
};
|
|
1531
|
+
const ONNX_WASM_MAGIC = [0x00, 0x61, 0x73, 0x6d];
|
|
1532
|
+
const ONNX_WASM_PROBE_FILES = [
|
|
1533
|
+
'ort-wasm-simd-threaded.wasm',
|
|
1534
|
+
'ort-wasm-simd.wasm',
|
|
1535
|
+
'ort-wasm-threaded.wasm',
|
|
1536
|
+
'ort-wasm.wasm'
|
|
1537
|
+
];
|
|
1538
|
+
const normalizeWasmBase = (value) => (value.endsWith('/') ? value : `${value}/`);
|
|
1539
|
+
const buildTransformersDistBaseFromCdn = () => {
|
|
1540
|
+
try {
|
|
1541
|
+
const url = new URL(TRANSFORMERS_CDN);
|
|
1542
|
+
const pathname = url.pathname;
|
|
1543
|
+
const index = pathname.lastIndexOf('/');
|
|
1544
|
+
const directory = index >= 0 ? pathname.slice(0, index + 1) : '/';
|
|
1545
|
+
return `${url.origin}${directory}`;
|
|
1546
|
+
}
|
|
1547
|
+
catch {
|
|
1548
|
+
return 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/';
|
|
1549
|
+
}
|
|
1550
|
+
};
|
|
1551
|
+
const hasWasmMagic = (bytes) => bytes.length >= ONNX_WASM_MAGIC.length &&
|
|
1552
|
+
ONNX_WASM_MAGIC.every((expected, index) => bytes[index] === expected);
|
|
1553
|
+
let onnxWasmOverrideProbePromise = null;
|
|
1554
|
+
const probeOnnxWasmOverridePath = async (fetchImpl) => {
|
|
1555
|
+
const candidateBases = [
|
|
1556
|
+
resolveOnnxWasmPath(),
|
|
1557
|
+
buildTransformersDistBaseFromCdn(),
|
|
1558
|
+
'https://unpkg.com/@xenova/transformers@2.17.2/dist/'
|
|
1559
|
+
].map(normalizeWasmBase);
|
|
1560
|
+
for (const baseWithSlash of candidateBases) {
|
|
1561
|
+
let sawNonWasmPayloadAtBase = false;
|
|
1562
|
+
for (const filename of ONNX_WASM_PROBE_FILES) {
|
|
1563
|
+
const requestUrl = (() => {
|
|
1564
|
+
try {
|
|
1565
|
+
return new URL(filename, baseWithSlash).toString();
|
|
1566
|
+
}
|
|
1567
|
+
catch {
|
|
1568
|
+
return `${baseWithSlash}${filename}`;
|
|
1569
|
+
}
|
|
1570
|
+
})();
|
|
1571
|
+
try {
|
|
1572
|
+
const response = await fetchImpl(requestUrl, { cache: 'no-store' });
|
|
1573
|
+
if (!response.ok)
|
|
1574
|
+
continue;
|
|
1575
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
1576
|
+
if (hasWasmMagic(bytes)) {
|
|
1577
|
+
return baseWithSlash;
|
|
1578
|
+
}
|
|
1579
|
+
sawNonWasmPayloadAtBase = true;
|
|
1580
|
+
break;
|
|
1581
|
+
}
|
|
1582
|
+
catch {
|
|
1583
|
+
// ignore probe failures
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
if (sawNonWasmPayloadAtBase) {
|
|
1587
|
+
console.warn('[ZeroGPU][SLM] ONNX wasm probe got non-wasm payload', {
|
|
1588
|
+
wasmBase: baseWithSlash
|
|
1589
|
+
});
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
return null;
|
|
1593
|
+
};
|
|
1594
|
+
const getUsableOnnxWasmOverridePath = (fetchImpl) => {
|
|
1595
|
+
if (!onnxWasmOverrideProbePromise) {
|
|
1596
|
+
onnxWasmOverrideProbePromise = probeOnnxWasmOverridePath(fetchImpl);
|
|
1597
|
+
}
|
|
1598
|
+
return onnxWasmOverrideProbePromise;
|
|
1599
|
+
};
|
|
1600
|
+
let transformersEnvMutationChain = Promise.resolve();
|
|
1601
|
+
const withTransformersEnvLock = async (work) => {
|
|
1602
|
+
const previous = transformersEnvMutationChain;
|
|
1603
|
+
let release = () => { };
|
|
1604
|
+
transformersEnvMutationChain = new Promise((resolve) => {
|
|
1605
|
+
release = resolve;
|
|
1606
|
+
});
|
|
1607
|
+
await previous;
|
|
1608
|
+
try {
|
|
1609
|
+
return await work();
|
|
1610
|
+
}
|
|
1611
|
+
finally {
|
|
1612
|
+
release();
|
|
1613
|
+
}
|
|
1614
|
+
};
|
|
1615
|
+
|
|
1616
|
+
const serializeError$4 = (error) => {
|
|
1617
|
+
if (error instanceof Error) {
|
|
1618
|
+
return { name: error.name, message: error.message, stack: error.stack };
|
|
1619
|
+
}
|
|
1620
|
+
return { message: String(error) };
|
|
1621
|
+
};
|
|
1622
|
+
const sessionCache = {};
|
|
1623
|
+
const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requiredFiles, originalFetch) => {
|
|
1624
|
+
const requiredFileList = requiredFiles
|
|
1625
|
+
.map((name) => normalizeCacheRelativePath(name.trim()))
|
|
1626
|
+
.filter((name) => name.length > 0);
|
|
1627
|
+
const requiredFileSet = new Set(requiredFileList);
|
|
1628
|
+
const logger = getLogger();
|
|
1629
|
+
const resolveRequestedRelative = (requestedRelative) => {
|
|
1630
|
+
const normalized = normalizeCacheRelativePath(requestedRelative);
|
|
1631
|
+
if (!normalized)
|
|
1632
|
+
return null;
|
|
1633
|
+
if (requiredFileSet.size === 0 || requiredFileSet.has(normalized)) {
|
|
1634
|
+
return normalized;
|
|
1635
|
+
}
|
|
1636
|
+
if (normalized.startsWith('onnx/') &&
|
|
1637
|
+
normalized.endsWith('.onnx') &&
|
|
1638
|
+
!normalized.endsWith('_quantized.onnx')) {
|
|
1639
|
+
const quantizedCandidate = normalized.replace(/\.onnx$/, '_quantized.onnx');
|
|
1640
|
+
if (requiredFileSet.has(quantizedCandidate)) {
|
|
1641
|
+
return quantizedCandidate;
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
return null;
|
|
1645
|
+
};
|
|
1646
|
+
const buildModelRequestUrls = (relative) => {
|
|
1647
|
+
const normalized = normalizeCacheRelativePath(relative);
|
|
1648
|
+
const urls = [];
|
|
1649
|
+
const pushUrl = (value) => {
|
|
1650
|
+
if (!urls.includes(value))
|
|
1651
|
+
urls.push(value);
|
|
1652
|
+
};
|
|
1653
|
+
try {
|
|
1654
|
+
const base = new URL(fileBase);
|
|
1655
|
+
const baseWithSlash = base.toString().endsWith('/') ? base.toString() : `${base.toString()}/`;
|
|
1656
|
+
if (fileBase.endsWith('/resolve/main')) {
|
|
1657
|
+
pushUrl(new URL(normalized, baseWithSlash).toString());
|
|
1658
|
+
}
|
|
1659
|
+
else {
|
|
1660
|
+
pushUrl(new URL(normalized, baseWithSlash).toString());
|
|
1661
|
+
pushUrl(new URL(`resolve/main/${normalized}`, baseWithSlash).toString());
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
catch {
|
|
1665
|
+
if (fileBase.endsWith('/resolve/main')) {
|
|
1666
|
+
pushUrl(`${fileBase}/${normalized}`);
|
|
1667
|
+
}
|
|
1668
|
+
else {
|
|
1669
|
+
pushUrl(`${fileBase}/${normalized}`);
|
|
1670
|
+
pushUrl(`${fileBase}/resolve/main/${normalized}`);
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
return urls;
|
|
1674
|
+
};
|
|
1675
|
+
const fileBaseUrl = (() => {
|
|
1676
|
+
try {
|
|
1677
|
+
return new URL(fileBase);
|
|
1678
|
+
}
|
|
1679
|
+
catch {
|
|
1680
|
+
return null;
|
|
1681
|
+
}
|
|
1682
|
+
})();
|
|
1683
|
+
const extractModelRelativePath = (requestUrl) => {
|
|
1684
|
+
const pathname = (() => {
|
|
1685
|
+
try {
|
|
1686
|
+
return new URL(requestUrl).pathname;
|
|
1687
|
+
}
|
|
1688
|
+
catch {
|
|
1689
|
+
return requestUrl.split('?')[0] || '';
|
|
1690
|
+
}
|
|
1691
|
+
})();
|
|
1692
|
+
const resolveMainSegment = '/resolve/main/';
|
|
1693
|
+
const resolveMainIndex = pathname.indexOf(resolveMainSegment);
|
|
1694
|
+
if (resolveMainIndex >= 0) {
|
|
1695
|
+
const resolved = pathname.slice(resolveMainIndex + resolveMainSegment.length);
|
|
1696
|
+
return normalizeCacheRelativePath(resolved);
|
|
1697
|
+
}
|
|
1698
|
+
if (!fileBaseUrl)
|
|
1699
|
+
return null;
|
|
1700
|
+
const basePath = fileBaseUrl.pathname.replace(/\/$/, '');
|
|
1701
|
+
if (!pathname.startsWith(`${basePath}/`))
|
|
1702
|
+
return null;
|
|
1703
|
+
const relative = pathname.slice(basePath.length + 1);
|
|
1704
|
+
return normalizeCacheRelativePath(relative);
|
|
1705
|
+
};
|
|
1706
|
+
return async (url, init) => {
|
|
1707
|
+
const originalRequestUrl = typeof url === 'string' ? url : url instanceof URL ? url.toString() : url.url;
|
|
1708
|
+
const requestedRelative = extractModelRelativePath(originalRequestUrl);
|
|
1709
|
+
if (!requestedRelative) {
|
|
1710
|
+
const isWasmOrOrtRequest = /\.wasm(?:\?|$)/i.test(originalRequestUrl) || /onnxruntime|ort-wasm/i.test(originalRequestUrl);
|
|
1711
|
+
if (!isWasmOrOrtRequest) {
|
|
1712
|
+
return originalFetch(url, init);
|
|
1713
|
+
}
|
|
1714
|
+
try {
|
|
1715
|
+
return await originalFetch(url, init);
|
|
1716
|
+
}
|
|
1717
|
+
catch (error) {
|
|
1718
|
+
console.error('[ZeroGPU][SLM][fetch] non-model wasm/ort request failed', {
|
|
1719
|
+
modelId,
|
|
1720
|
+
requestUrl: originalRequestUrl,
|
|
1721
|
+
error: serializeError$4(error)
|
|
1722
|
+
});
|
|
1723
|
+
throw error;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
const relative = resolveRequestedRelative(requestedRelative);
|
|
1727
|
+
if (!relative) {
|
|
1728
|
+
logger.warn('[SLM] Unexpected model file request; falling back to original fetch', {
|
|
1729
|
+
requestedRelative,
|
|
1730
|
+
modelId
|
|
1731
|
+
});
|
|
1732
|
+
return originalFetch(url, init);
|
|
1733
|
+
}
|
|
1734
|
+
const requestUrls = buildModelRequestUrls(relative);
|
|
1735
|
+
const normalizedRelative = normalizeCacheRelativePath(relative);
|
|
1736
|
+
const modelScopedKey = buildModelFileCacheKey(modelId, normalizedRelative);
|
|
1737
|
+
let blob = sessionCache[modelScopedKey] ||
|
|
1738
|
+
cachedFiles[modelScopedKey] ||
|
|
1739
|
+
sessionCache[normalizedRelative] ||
|
|
1740
|
+
cachedFiles[normalizedRelative] ||
|
|
1741
|
+
cachedFiles[`onnx/${normalizedRelative}`] ||
|
|
1742
|
+
sessionCache[`onnx/${normalizedRelative}`];
|
|
1743
|
+
if (!blob && normalizedRelative.startsWith('onnx/')) {
|
|
1744
|
+
const trimmed = normalizedRelative.replace('onnx/', '');
|
|
1745
|
+
blob =
|
|
1746
|
+
cachedFiles[trimmed] ||
|
|
1747
|
+
sessionCache[trimmed] ||
|
|
1748
|
+
cachedFiles[buildModelFileCacheKey(modelId, trimmed)] ||
|
|
1749
|
+
sessionCache[buildModelFileCacheKey(modelId, trimmed)];
|
|
1750
|
+
}
|
|
1751
|
+
if (blob) {
|
|
1752
|
+
return new Response(blob);
|
|
1753
|
+
}
|
|
1754
|
+
try {
|
|
1755
|
+
for (const requestUrl of requestUrls) {
|
|
1756
|
+
const response = await originalFetch(requestUrl, init);
|
|
1757
|
+
if (response.ok) {
|
|
1758
|
+
const downloadedBlob = await response.blob();
|
|
1759
|
+
sessionCache[modelScopedKey] = downloadedBlob;
|
|
1760
|
+
if (onFileDownloaded) {
|
|
1761
|
+
onFileDownloaded(modelScopedKey, downloadedBlob);
|
|
1762
|
+
}
|
|
1763
|
+
return new Response(downloadedBlob);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
return new Response('required_file_not_found', { status: 404, statusText: 'Not Found' });
|
|
1767
|
+
}
|
|
1768
|
+
catch (err) {
|
|
1769
|
+
logger.warn(`[ZeroGPU] Failed to fetch ${relative}:`, err);
|
|
1770
|
+
return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
|
|
1771
|
+
}
|
|
1772
|
+
};
|
|
1773
|
+
};
|
|
1774
|
+
|
|
1775
|
+
const TASK_PIPELINE_MAP = {
|
|
1776
|
+
summary: 'summarization',
|
|
1777
|
+
iab_classify: 'text-classification',
|
|
1778
|
+
classification: 'zero-shot-classification',
|
|
1779
|
+
text_generation: 'text2text-generation'
|
|
1780
|
+
};
|
|
1781
|
+
const serializeError$3 = (error) => {
|
|
1782
|
+
if (error instanceof Error) {
|
|
1783
|
+
return { name: error.name, message: error.message, stack: error.stack };
|
|
1784
|
+
}
|
|
1785
|
+
return { message: String(error) };
|
|
1786
|
+
};
|
|
1787
|
+
const isInvalidArrayLengthError = (error) => {
|
|
1788
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1789
|
+
return message.toLowerCase().includes('invalid array length');
|
|
1790
|
+
};
|
|
1791
|
+
const extractTextFromRaw = (raw) => {
|
|
1792
|
+
if (typeof raw === 'string')
|
|
1793
|
+
return raw;
|
|
1794
|
+
if (Array.isArray(raw) && raw.length) {
|
|
1795
|
+
const first = raw[0];
|
|
1796
|
+
if (first && typeof first.summary_text === 'string')
|
|
1797
|
+
return first.summary_text;
|
|
1798
|
+
if (first && typeof first.generated_text === 'string')
|
|
1799
|
+
return first.generated_text;
|
|
1800
|
+
if (first && typeof first.label === 'string')
|
|
1801
|
+
return first.label;
|
|
1802
|
+
try {
|
|
1803
|
+
return JSON.stringify(first);
|
|
1804
|
+
}
|
|
1805
|
+
catch {
|
|
1806
|
+
return String(first ?? '');
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
if (raw && typeof raw === 'object') {
|
|
1810
|
+
const obj = raw;
|
|
1811
|
+
if (typeof obj.summary_text === 'string')
|
|
1812
|
+
return obj.summary_text;
|
|
1813
|
+
if (typeof obj.generated_text === 'string')
|
|
1814
|
+
return obj.generated_text;
|
|
1815
|
+
if (typeof obj.label === 'string')
|
|
1816
|
+
return obj.label;
|
|
1817
|
+
try {
|
|
1818
|
+
return JSON.stringify(obj);
|
|
1819
|
+
}
|
|
1820
|
+
catch {
|
|
1821
|
+
return String(obj);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
return '';
|
|
1825
|
+
};
|
|
1826
|
+
const isZeroShotClassificationOutput = (output) => {
|
|
1827
|
+
if (!output || typeof output !== 'object' || Array.isArray(output))
|
|
1828
|
+
return false;
|
|
1829
|
+
const candidate = output;
|
|
1830
|
+
return Array.isArray(candidate.labels) && Array.isArray(candidate.scores);
|
|
1831
|
+
};
|
|
1832
|
+
const mapLabelsToScores = (output) => {
|
|
1833
|
+
const labels = output.labels;
|
|
1834
|
+
const scores = output.scores;
|
|
1835
|
+
if (!Array.isArray(labels) || !Array.isArray(scores))
|
|
1836
|
+
return null;
|
|
1837
|
+
const entries = labels.flatMap((label, index) => {
|
|
1838
|
+
const score = scores[index];
|
|
1839
|
+
return typeof label === 'string' && typeof score === 'number'
|
|
1840
|
+
? [[label, score]]
|
|
1841
|
+
: [];
|
|
1842
|
+
});
|
|
1843
|
+
return entries.length > 0 ? Object.fromEntries(entries) : null;
|
|
1844
|
+
};
|
|
1845
|
+
const normalizeCategories = (value) => {
|
|
1846
|
+
if (Array.isArray(value)) {
|
|
1847
|
+
const categories = value.filter((category) => typeof category === 'string');
|
|
1848
|
+
return categories.length > 0 ? categories : undefined;
|
|
1849
|
+
}
|
|
1850
|
+
if (typeof value === 'string' && value.length > 0)
|
|
1851
|
+
return [value];
|
|
1852
|
+
return undefined;
|
|
1853
|
+
};
|
|
1854
|
+
const sanitizeText = (text, fallback) => {
|
|
1855
|
+
const trimmed = (text ?? '').trim();
|
|
1856
|
+
if (!trimmed)
|
|
1857
|
+
return fallback;
|
|
1858
|
+
return trimmed.slice(0, 1024);
|
|
1859
|
+
};
|
|
1860
|
+
const hasMeaningfulOutput = (output) => {
|
|
1861
|
+
if (output == null)
|
|
1862
|
+
return false;
|
|
1863
|
+
if (typeof output === 'string')
|
|
1864
|
+
return output.trim().length > 0;
|
|
1865
|
+
if (Array.isArray(output))
|
|
1866
|
+
return output.length > 0;
|
|
1867
|
+
if (typeof output === 'object')
|
|
1868
|
+
return Object.keys(output).length > 0;
|
|
1869
|
+
return true;
|
|
1870
|
+
};
|
|
1871
|
+
const runPipeline = async (state, text, options) => {
|
|
1872
|
+
const { pipeline, pipelineTask } = state;
|
|
1873
|
+
const { result, ms } = await measure(async () => {
|
|
1874
|
+
if (pipelineTask === 'zero-shot-classification') {
|
|
1875
|
+
if (!options?.categories || options.categories.length === 0) {
|
|
1876
|
+
throw new Error('classification_categories_required');
|
|
1877
|
+
}
|
|
1878
|
+
return pipeline(text, options.categories);
|
|
1879
|
+
}
|
|
1880
|
+
if (pipelineTask === 'summarization') {
|
|
1881
|
+
return pipeline(text, {
|
|
1882
|
+
max_new_tokens: options?.maxNewTokens ?? 64,
|
|
1883
|
+
min_length: 1,
|
|
1884
|
+
do_sample: false
|
|
1885
|
+
});
|
|
1886
|
+
}
|
|
1887
|
+
if (pipelineTask === 'text2text-generation') {
|
|
1888
|
+
return pipeline(text, {
|
|
1889
|
+
max_new_tokens: options?.maxNewTokens ?? 128,
|
|
1890
|
+
do_sample: false
|
|
1891
|
+
});
|
|
1892
|
+
}
|
|
1893
|
+
return pipeline(text);
|
|
1894
|
+
});
|
|
1895
|
+
return { raw: result, ms };
|
|
1896
|
+
};
|
|
1897
|
+
const runWithFallback = async (state, text, options) => {
|
|
1898
|
+
try {
|
|
1899
|
+
return await runPipeline(state, text, options);
|
|
1900
|
+
}
|
|
1901
|
+
catch (error) {
|
|
1902
|
+
if (!isInvalidArrayLengthError(error) || text.length <= 256)
|
|
1903
|
+
throw error;
|
|
1904
|
+
const truncated = text.slice(0, 256);
|
|
1905
|
+
return await runPipeline(state, truncated, options);
|
|
1906
|
+
}
|
|
1907
|
+
};
|
|
1908
|
+
class OnnxAdapter {
|
|
1909
|
+
constructor(config, state, metrics) {
|
|
1910
|
+
this.config = config;
|
|
1911
|
+
this.capability = {
|
|
1912
|
+
inferenceFramework: 'ONNX',
|
|
1913
|
+
taskType: config.taskType,
|
|
1914
|
+
modelType: config.modelType
|
|
1915
|
+
};
|
|
1916
|
+
this.state = state;
|
|
1917
|
+
this.metrics = metrics;
|
|
1918
|
+
}
|
|
1919
|
+
async runInference(input) {
|
|
1920
|
+
const taskType = this.config.taskType;
|
|
1921
|
+
const text = sanitizeText(input.text, 'summarize this text');
|
|
1922
|
+
if (taskType === 'classification') {
|
|
1923
|
+
const categories = normalizeCategories(input.categories) ?? normalizeCategories(input.category);
|
|
1924
|
+
const { raw, ms } = await runWithFallback(this.state, text, { categories });
|
|
1925
|
+
if (isZeroShotClassificationOutput(raw)) {
|
|
1926
|
+
const scoreDict = mapLabelsToScores(raw);
|
|
1927
|
+
return { output: scoreDict ?? raw, inferenceMs: ms };
|
|
1928
|
+
}
|
|
1929
|
+
return { output: raw, inferenceMs: ms };
|
|
1930
|
+
}
|
|
1931
|
+
if (taskType === 'iab_classify') {
|
|
1932
|
+
const { raw, ms } = await runWithFallback(this.state, text);
|
|
1933
|
+
return { output: raw, inferenceMs: ms };
|
|
1934
|
+
}
|
|
1935
|
+
if (taskType === 'summary') {
|
|
1936
|
+
const { raw, ms } = await runWithFallback(this.state, text, {
|
|
1937
|
+
maxNewTokens: input.maxNewTokens
|
|
1938
|
+
});
|
|
1939
|
+
return { output: { text: extractTextFromRaw(raw) }, inferenceMs: ms };
|
|
1940
|
+
}
|
|
1941
|
+
if (taskType === 'text_generation') {
|
|
1942
|
+
const { raw, ms } = await runWithFallback(this.state, text, {
|
|
1943
|
+
maxNewTokens: input.maxNewTokens
|
|
1944
|
+
});
|
|
1945
|
+
return { output: { text: extractTextFromRaw(raw) }, inferenceMs: ms };
|
|
1946
|
+
}
|
|
1947
|
+
const { raw, ms } = await runWithFallback(this.state, text);
|
|
1948
|
+
return { output: raw, inferenceMs: ms };
|
|
1949
|
+
}
|
|
1950
|
+
async runSample(sample) {
|
|
1951
|
+
const start = performance.now();
|
|
1952
|
+
if (typeof sample.text !== 'string') {
|
|
1953
|
+
return {
|
|
1954
|
+
ok: false,
|
|
1955
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
1956
|
+
error: true,
|
|
1957
|
+
errorMessage: 'response from processing sample'
|
|
1958
|
+
};
|
|
1959
|
+
}
|
|
1960
|
+
try {
|
|
1961
|
+
const result = await this.runInference({
|
|
1962
|
+
text: sample.text,
|
|
1963
|
+
categories: sample.categories,
|
|
1964
|
+
category: sample.category,
|
|
1965
|
+
usecase: sample.usecase
|
|
1966
|
+
});
|
|
1967
|
+
const processingTimeMs = Math.round(performance.now() - start);
|
|
1968
|
+
if (!hasMeaningfulOutput(result.output)) {
|
|
1969
|
+
return {
|
|
1970
|
+
ok: false,
|
|
1971
|
+
processingTimeMs,
|
|
1972
|
+
error: true,
|
|
1973
|
+
errorMessage: 'response from processing sample'
|
|
1974
|
+
};
|
|
1975
|
+
}
|
|
1976
|
+
return { ok: true, processingTimeMs, error: false };
|
|
1977
|
+
}
|
|
1978
|
+
catch (err) {
|
|
1979
|
+
return {
|
|
1980
|
+
ok: false,
|
|
1981
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
1982
|
+
error: true,
|
|
1983
|
+
errorMessage: err instanceof Error ? err.message : String(err)
|
|
1984
|
+
};
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
const instantiatePipeline = async (slm, cachedFiles, onFileDownloaded) => {
|
|
1989
|
+
const logger = getLogger();
|
|
1990
|
+
try {
|
|
1991
|
+
await ensureTransformersRuntime();
|
|
1992
|
+
}
|
|
1993
|
+
catch (error) {
|
|
1994
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1995
|
+
throw new Error(`transformers_runtime_load_failed:${message}`);
|
|
1996
|
+
}
|
|
1997
|
+
const fileBase = sanitizeBaseUrl(buildFileBase(slm.modelUrl, slm.modelRepoId));
|
|
1998
|
+
const pipelineTask = TASK_PIPELINE_MAP[slm.taskType] ?? slm.taskType;
|
|
1999
|
+
const modelSource = isHttpUrl(slm.modelUrl || '')
|
|
2000
|
+
? (slm.modelUrl || '').trim()
|
|
2001
|
+
: (slm.modelRepoId || slm.modelUrl || '').trim();
|
|
2002
|
+
if (!modelSource) {
|
|
2003
|
+
throw new Error('[SLM] Invalid modelSource: expected non-empty modelRepoId or modelUrl');
|
|
2004
|
+
}
|
|
2005
|
+
const loadResult = await withTransformersEnvLock(async () => {
|
|
2006
|
+
const env = window.TransformersEnv || {};
|
|
2007
|
+
env.allowRemoteModels = true;
|
|
2008
|
+
env.allowLocalModels = true;
|
|
2009
|
+
if (!env.backends)
|
|
2010
|
+
env.backends = {};
|
|
2011
|
+
if (!env.backends.onnx)
|
|
2012
|
+
env.backends.onnx = {};
|
|
2013
|
+
if (!env.backends.onnx.wasm)
|
|
2014
|
+
env.backends.onnx.wasm = {};
|
|
2015
|
+
const transformersLogLevel = logger.isEnabled() ? 'error' : 'fatal';
|
|
2016
|
+
if (env?.backends?.onnx?.env) {
|
|
2017
|
+
env.backends.onnx.env.logLevel = transformersLogLevel;
|
|
2018
|
+
}
|
|
2019
|
+
env.backends.onnx.wasm.proxy = false;
|
|
2020
|
+
env.backends.onnx.wasm.numThreads = 1;
|
|
2021
|
+
const originalFetch = window.fetch.bind(window);
|
|
2022
|
+
const wasmOverridePath = await getUsableOnnxWasmOverridePath(originalFetch);
|
|
2023
|
+
if (wasmOverridePath) {
|
|
2024
|
+
env.backends.onnx.wasm.wasmPaths = wasmOverridePath;
|
|
2025
|
+
}
|
|
2026
|
+
else {
|
|
2027
|
+
try {
|
|
2028
|
+
delete env.backends.onnx.wasm.wasmPaths;
|
|
2029
|
+
}
|
|
2030
|
+
catch {
|
|
2031
|
+
env.backends.onnx.wasm.wasmPaths = undefined;
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
if ('logLevel' in env) {
|
|
2035
|
+
env.logLevel = transformersLogLevel;
|
|
2036
|
+
}
|
|
2037
|
+
const ort = window.ort;
|
|
2038
|
+
if (ort?.env) {
|
|
2039
|
+
ort.env.logLevel = transformersLogLevel;
|
|
2040
|
+
}
|
|
2041
|
+
env.fetch = createEnvFetch(slm.modelId, fileBase, cachedFiles, onFileDownloaded, (slm.requiredFiles ?? []).map((file) => file.name), originalFetch);
|
|
2042
|
+
window.TransformersEnv = env;
|
|
2043
|
+
window.fetch = env.fetch;
|
|
2044
|
+
const runPipelineLoad = () => measure(() => window.TransformersPipeline(pipelineTask, modelSource, {
|
|
2045
|
+
device: 'wasm',
|
|
2046
|
+
quantized: slm.quantized,
|
|
2047
|
+
progress_callback: () => { }
|
|
2048
|
+
}));
|
|
2049
|
+
try {
|
|
2050
|
+
return await runPipelineLoad();
|
|
2051
|
+
}
|
|
2052
|
+
catch (firstError) {
|
|
2053
|
+
const wasmEnv = env?.backends?.onnx?.wasm;
|
|
2054
|
+
const hadWasmPathOverride = Boolean(wasmEnv && 'wasmPaths' in wasmEnv && wasmEnv.wasmPaths);
|
|
2055
|
+
let lastError = firstError;
|
|
2056
|
+
if (wasmEnv) {
|
|
2057
|
+
const previousSimd = wasmEnv.simd;
|
|
2058
|
+
const previousThreads = wasmEnv.numThreads;
|
|
2059
|
+
const previousProxy = wasmEnv.proxy;
|
|
2060
|
+
wasmEnv.simd = false;
|
|
2061
|
+
wasmEnv.numThreads = 1;
|
|
2062
|
+
wasmEnv.proxy = false;
|
|
2063
|
+
try {
|
|
2064
|
+
return await runPipelineLoad();
|
|
2065
|
+
}
|
|
2066
|
+
catch (compatError) {
|
|
2067
|
+
lastError = compatError;
|
|
2068
|
+
wasmEnv.simd = previousSimd;
|
|
2069
|
+
wasmEnv.numThreads = previousThreads;
|
|
2070
|
+
wasmEnv.proxy = previousProxy;
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
if (!hadWasmPathOverride || !wasmEnv) {
|
|
2074
|
+
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
2075
|
+
throw new Error(`pipeline_load_failed:${message}`);
|
|
2076
|
+
}
|
|
2077
|
+
const previousWasmPaths = wasmEnv.wasmPaths;
|
|
2078
|
+
try {
|
|
2079
|
+
delete wasmEnv.wasmPaths;
|
|
2080
|
+
}
|
|
2081
|
+
catch {
|
|
2082
|
+
wasmEnv.wasmPaths = undefined;
|
|
2083
|
+
}
|
|
2084
|
+
try {
|
|
2085
|
+
return await runPipelineLoad();
|
|
2086
|
+
}
|
|
2087
|
+
catch (secondError) {
|
|
2088
|
+
const message = secondError instanceof Error ? secondError.message : String(secondError);
|
|
2089
|
+
throw new Error(`pipeline_load_failed:${message}`);
|
|
2090
|
+
}
|
|
2091
|
+
finally {
|
|
2092
|
+
wasmEnv.wasmPaths = previousWasmPaths;
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
finally {
|
|
2096
|
+
window.fetch = originalFetch;
|
|
2097
|
+
}
|
|
2098
|
+
});
|
|
2099
|
+
const { result: pipeline, ms: loadModelMs } = loadResult;
|
|
2100
|
+
return { pipeline: pipeline, pipelineTask, loadModelMs };
|
|
2101
|
+
};
|
|
2102
|
+
const loadOnnxAdapter = async (slm, options) => {
|
|
2103
|
+
const logger = getLogger();
|
|
2104
|
+
const startTime = performance.now();
|
|
2105
|
+
const downloadedFiles = {};
|
|
2106
|
+
try {
|
|
2107
|
+
const cached = await getModel(slm.modelId, slm.modelVersion);
|
|
2108
|
+
const cachedFiles = cached?.files || {};
|
|
2109
|
+
if (!cached && options?.allowDownload === false) {
|
|
2110
|
+
return { error: new Error('model_not_cached'), metrics: {} };
|
|
2111
|
+
}
|
|
2112
|
+
const onFileDownloaded = (filename, blob) => {
|
|
2113
|
+
downloadedFiles[filename] = blob;
|
|
2114
|
+
};
|
|
2115
|
+
const baseMetrics = cached
|
|
2116
|
+
? {
|
|
2117
|
+
downloadMs: cached.metadata.downloadMs,
|
|
2118
|
+
loadModelMs: cached.metadata.loadModelMs,
|
|
2119
|
+
sizeBytes: cached.metadata.sizeBytes
|
|
2120
|
+
}
|
|
2121
|
+
: {};
|
|
2122
|
+
const state = await instantiatePipeline(slm, cachedFiles, onFileDownloaded);
|
|
2123
|
+
const metrics = { ...baseMetrics, loadModelMs: state.loadModelMs };
|
|
2124
|
+
if (Object.keys(downloadedFiles).length > 0) {
|
|
2125
|
+
const allFiles = { ...cachedFiles, ...downloadedFiles };
|
|
2126
|
+
const calculatedSize = Object.values(allFiles).reduce((sum, blob) => sum + blob.size, 0);
|
|
2127
|
+
const downloadMs = Math.round(performance.now() - startTime);
|
|
2128
|
+
await putModelComplete(slm.modelId, slm.modelVersion, {
|
|
2129
|
+
modelId: slm.modelId,
|
|
2130
|
+
modelVersion: slm.modelVersion,
|
|
2131
|
+
sizeBytes: calculatedSize,
|
|
2132
|
+
downloadMs: cached ? 0 : downloadMs,
|
|
2133
|
+
loadModelMs: state.loadModelMs
|
|
2134
|
+
}, allFiles);
|
|
2135
|
+
metrics.sizeBytes = calculatedSize;
|
|
2136
|
+
if (!cached)
|
|
2137
|
+
metrics.downloadMs = downloadMs;
|
|
2138
|
+
}
|
|
2139
|
+
const adapter = new OnnxAdapter(slm, state, metrics);
|
|
2140
|
+
return { adapter, metrics };
|
|
2141
|
+
}
|
|
2142
|
+
catch (error) {
|
|
2143
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2144
|
+
if (message.includes("Unexpected token '<'")) {
|
|
2145
|
+
console.error('[ZeroGPU][SLM][loadOnnxAdapter] Parse error suggests HTML returned where JSON expected', { modelId: slm.modelId, modelUrl: slm.modelUrl });
|
|
2146
|
+
}
|
|
2147
|
+
console.error('[ZeroGPU][SLM][loadOnnxAdapter] failed', {
|
|
2148
|
+
modelId: slm.modelId,
|
|
2149
|
+
modelVersion: slm.modelVersion,
|
|
2150
|
+
modelRepoId: slm.modelRepoId,
|
|
2151
|
+
modelUrl: slm.modelUrl,
|
|
2152
|
+
requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
|
|
2153
|
+
error: serializeError$3(error)
|
|
2154
|
+
});
|
|
2155
|
+
logger.error('ONNX adapter load failed', error);
|
|
2156
|
+
await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
|
|
2157
|
+
return { error: error, metrics: {} };
|
|
2158
|
+
}
|
|
2159
|
+
};
|
|
2160
|
+
|
|
2161
|
+
const capabilities$2 = [
|
|
2162
|
+
{ inferenceFramework: 'ONNX', taskType: 'summary' },
|
|
2163
|
+
{ inferenceFramework: 'ONNX', taskType: 'iab_classify' },
|
|
2164
|
+
{ inferenceFramework: 'ONNX', taskType: 'classification' },
|
|
2165
|
+
{ inferenceFramework: 'ONNX', taskType: 'text_generation' }
|
|
2166
|
+
];
|
|
2167
|
+
const factory$2 = {
|
|
2168
|
+
capabilities: capabilities$2,
|
|
2169
|
+
load: (config, options) => loadOnnxAdapter(config, options)
|
|
2170
|
+
};
|
|
2171
|
+
registerAdapter(factory$2);
|
|
2172
|
+
|
|
2173
|
+
const DEFAULT_THRESHOLD = 0.4;
|
|
2174
|
+
const DEFAULT_MASK = '[REDACTED]';
|
|
2175
|
+
const serializeError$2 = (error) => {
|
|
2176
|
+
if (error instanceof Error) {
|
|
2177
|
+
return { name: error.name, message: error.message, stack: error.stack };
|
|
2178
|
+
}
|
|
2179
|
+
return { message: String(error) };
|
|
2180
|
+
};
|
|
2181
|
+
const parseTokenClassificationOutput = (raw, sourceText) => {
|
|
2182
|
+
if (!Array.isArray(raw))
|
|
2183
|
+
return [];
|
|
2184
|
+
return raw.flatMap((item) => {
|
|
2185
|
+
if (!item || typeof item !== 'object')
|
|
2186
|
+
return [];
|
|
2187
|
+
const obj = item;
|
|
2188
|
+
const label = typeof obj.entity_group === 'string'
|
|
2189
|
+
? obj.entity_group
|
|
2190
|
+
: typeof obj.entity === 'string'
|
|
2191
|
+
? obj.entity
|
|
2192
|
+
: typeof obj.label === 'string'
|
|
2193
|
+
? obj.label
|
|
2194
|
+
: null;
|
|
2195
|
+
if (!label)
|
|
2196
|
+
return [];
|
|
2197
|
+
const score = typeof obj.score === 'number' ? obj.score : 0;
|
|
2198
|
+
const start = typeof obj.start === 'number' ? obj.start : -1;
|
|
2199
|
+
const end = typeof obj.end === 'number' ? obj.end : -1;
|
|
2200
|
+
const word = typeof obj.word === 'string'
|
|
2201
|
+
? obj.word
|
|
2202
|
+
: typeof obj.text === 'string'
|
|
2203
|
+
? obj.text
|
|
2204
|
+
: start >= 0 && end > start
|
|
2205
|
+
? sourceText.slice(start, end)
|
|
2206
|
+
: '';
|
|
2207
|
+
if (!word)
|
|
2208
|
+
return [];
|
|
2209
|
+
return [{ text: word, label, score, start, end }];
|
|
2210
|
+
});
|
|
2211
|
+
};
|
|
2212
|
+
const filterByThreshold = (entities, threshold) => entities.filter((entity) => entity.score >= threshold);
|
|
2213
|
+
const filterByLabels = (entities, labels) => {
|
|
2214
|
+
if (!labels || labels.length === 0)
|
|
2215
|
+
return entities;
|
|
2216
|
+
const allowed = new Set(labels.map((label) => label.toLowerCase()));
|
|
2217
|
+
return entities.filter((entity) => allowed.has(entity.label.toLowerCase()));
|
|
2218
|
+
};
|
|
2219
|
+
const redactEntities = (text, entities, mask) => {
|
|
2220
|
+
if (entities.length === 0)
|
|
2221
|
+
return text;
|
|
2222
|
+
const sorted = [...entities].sort((a, b) => b.start - a.start);
|
|
2223
|
+
let result = text;
|
|
2224
|
+
for (const entity of sorted) {
|
|
2225
|
+
if (entity.start < 0 || entity.end <= entity.start)
|
|
2226
|
+
continue;
|
|
2227
|
+
const replacement = mask.includes('LABEL') ? mask.replace('LABEL', entity.label) : mask;
|
|
2228
|
+
result = result.slice(0, entity.start) + replacement + result.slice(entity.end);
|
|
2229
|
+
}
|
|
2230
|
+
return result;
|
|
2231
|
+
};
|
|
2232
|
+
const buildJsonFromSchema = (schema, entities) => {
|
|
2233
|
+
if (!schema || typeof schema !== 'object')
|
|
2234
|
+
return {};
|
|
2235
|
+
const result = {};
|
|
2236
|
+
for (const [groupKey, groupValue] of Object.entries(schema)) {
|
|
2237
|
+
const fields = Array.isArray(groupValue) ? groupValue : [];
|
|
2238
|
+
const subResult = {};
|
|
2239
|
+
for (const field of fields) {
|
|
2240
|
+
if (typeof field !== 'string')
|
|
2241
|
+
continue;
|
|
2242
|
+
const name = field.split('::')[0];
|
|
2243
|
+
const match = entities.find((entity) => entity.label.toLowerCase() === name.toLowerCase());
|
|
2244
|
+
if (match)
|
|
2245
|
+
subResult[name] = match.text;
|
|
2246
|
+
}
|
|
2247
|
+
result[groupKey] = subResult;
|
|
2248
|
+
}
|
|
2249
|
+
return result;
|
|
2250
|
+
};
|
|
2251
|
+
const computeClassificationScores = (entities, labels) => {
|
|
2252
|
+
const scores = {};
|
|
2253
|
+
for (const label of labels) {
|
|
2254
|
+
const best = entities
|
|
2255
|
+
.filter((entity) => entity.label.toLowerCase() === label.toLowerCase())
|
|
2256
|
+
.reduce((max, entity) => Math.max(max, entity.score), 0);
|
|
2257
|
+
scores[label] = best;
|
|
2258
|
+
}
|
|
2259
|
+
return scores;
|
|
2260
|
+
};
|
|
2261
|
+
class TransformersAdapter {
|
|
2262
|
+
constructor(config, state, metrics) {
|
|
2263
|
+
this.config = config;
|
|
2264
|
+
this.capability = {
|
|
2265
|
+
inferenceFramework: 'Transformers',
|
|
2266
|
+
taskType: config.taskType,
|
|
2267
|
+
modelType: config.modelType
|
|
2268
|
+
};
|
|
2269
|
+
this.state = state;
|
|
2270
|
+
this.metrics = metrics;
|
|
2271
|
+
}
|
|
2272
|
+
async runInference(input) {
|
|
2273
|
+
const text = (input.text ?? '').trim();
|
|
2274
|
+
if (!text) {
|
|
2275
|
+
return { output: { entities: [] }, inferenceMs: 0 };
|
|
2276
|
+
}
|
|
2277
|
+
const threshold = typeof input.threshold === 'number' && Number.isFinite(input.threshold)
|
|
2278
|
+
? input.threshold
|
|
2279
|
+
: DEFAULT_THRESHOLD;
|
|
2280
|
+
const usecase = (input.usecase ?? 'ner').toLowerCase();
|
|
2281
|
+
const { result, ms } = await measure(async () => this.state.pipeline(text));
|
|
2282
|
+
const allEntities = parseTokenClassificationOutput(result, text);
|
|
2283
|
+
const thresholded = filterByThreshold(allEntities, threshold);
|
|
2284
|
+
const labels = Array.isArray(input.labels) ? input.labels : undefined;
|
|
2285
|
+
const filtered = filterByLabels(thresholded, labels);
|
|
2286
|
+
if (usecase === 'redact') {
|
|
2287
|
+
const mask = typeof input.mask === 'string' && input.mask.length > 0 ? input.mask : DEFAULT_MASK;
|
|
2288
|
+
const redacted = redactEntities(text, filtered, mask);
|
|
2289
|
+
return { output: { text: redacted, entities: filtered }, inferenceMs: ms };
|
|
2290
|
+
}
|
|
2291
|
+
if (usecase === 'json') {
|
|
2292
|
+
const json = buildJsonFromSchema(input.schema, filtered);
|
|
2293
|
+
return { output: json, inferenceMs: ms };
|
|
2294
|
+
}
|
|
2295
|
+
if (usecase === 'classification') {
|
|
2296
|
+
const classificationLabels = labels ?? [];
|
|
2297
|
+
const scores = computeClassificationScores(thresholded, classificationLabels);
|
|
2298
|
+
return { output: scores, inferenceMs: ms };
|
|
2299
|
+
}
|
|
2300
|
+
// ner, extract-pii, extract-entities, default
|
|
2301
|
+
return { output: { entities: filtered }, inferenceMs: ms };
|
|
2302
|
+
}
|
|
2303
|
+
async runSample(sample) {
|
|
2304
|
+
const start = performance.now();
|
|
2305
|
+
if (typeof sample.text !== 'string') {
|
|
2306
|
+
return {
|
|
2307
|
+
ok: false,
|
|
2308
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
2309
|
+
error: true,
|
|
2310
|
+
errorMessage: 'response from processing sample'
|
|
2311
|
+
};
|
|
2312
|
+
}
|
|
2313
|
+
try {
|
|
2314
|
+
await this.runInference({
|
|
2315
|
+
text: sample.text,
|
|
2316
|
+
labels: sample.labels,
|
|
2317
|
+
threshold: sample.threshold,
|
|
2318
|
+
usecase: sample.usecase ?? 'ner',
|
|
2319
|
+
schema: sample.schema,
|
|
2320
|
+
mask: sample.mask,
|
|
2321
|
+
categories: sample.categories
|
|
2322
|
+
});
|
|
2323
|
+
return {
|
|
2324
|
+
ok: true,
|
|
2325
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
2326
|
+
error: false,
|
|
2327
|
+
errorMessage: undefined
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
catch (err) {
|
|
2331
|
+
return {
|
|
2332
|
+
ok: false,
|
|
2333
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
2334
|
+
error: true,
|
|
2335
|
+
errorMessage: err instanceof Error ? err.message : String(err)
|
|
2336
|
+
};
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
const instantiateTokenPipeline = async (slm, cachedFiles, onFileDownloaded) => {
|
|
2341
|
+
const logger = getLogger();
|
|
2342
|
+
try {
|
|
2343
|
+
await ensureTransformersRuntime();
|
|
2344
|
+
}
|
|
2345
|
+
catch (error) {
|
|
2346
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2347
|
+
throw new Error(`transformers_runtime_load_failed:${message}`);
|
|
2348
|
+
}
|
|
2349
|
+
const fileBase = sanitizeBaseUrl(buildFileBase(slm.modelUrl, slm.modelRepoId));
|
|
2350
|
+
const modelSource = isHttpUrl(slm.modelUrl || '')
|
|
2351
|
+
? (slm.modelUrl || '').trim()
|
|
2352
|
+
: (slm.modelRepoId || slm.modelUrl || '').trim();
|
|
2353
|
+
if (!modelSource) {
|
|
2354
|
+
throw new Error('[Transformers] Invalid modelSource: expected non-empty modelRepoId or modelUrl');
|
|
2355
|
+
}
|
|
2356
|
+
const loadResult = await withTransformersEnvLock(async () => {
|
|
2357
|
+
const env = window.TransformersEnv || {};
|
|
2358
|
+
env.allowRemoteModels = true;
|
|
2359
|
+
env.allowLocalModels = true;
|
|
2360
|
+
if (!env.backends)
|
|
2361
|
+
env.backends = {};
|
|
2362
|
+
if (!env.backends.onnx)
|
|
2363
|
+
env.backends.onnx = {};
|
|
2364
|
+
if (!env.backends.onnx.wasm)
|
|
2365
|
+
env.backends.onnx.wasm = {};
|
|
2366
|
+
env.backends.onnx.wasm.proxy = false;
|
|
2367
|
+
env.backends.onnx.wasm.numThreads = 1;
|
|
2368
|
+
const originalFetch = window.fetch.bind(window);
|
|
2369
|
+
const wasmOverridePath = await getUsableOnnxWasmOverridePath(originalFetch);
|
|
2370
|
+
if (wasmOverridePath) {
|
|
2371
|
+
env.backends.onnx.wasm.wasmPaths = wasmOverridePath;
|
|
2372
|
+
}
|
|
2373
|
+
env.fetch = createEnvFetch(slm.modelId, fileBase, cachedFiles, onFileDownloaded, (slm.requiredFiles ?? []).map((file) => file.name), originalFetch);
|
|
2374
|
+
window.TransformersEnv = env;
|
|
2375
|
+
window.fetch = env.fetch;
|
|
2376
|
+
const runPipelineLoad = () => measure(() => window.TransformersPipeline('token-classification', modelSource, {
|
|
2377
|
+
device: 'wasm',
|
|
2378
|
+
quantized: slm.quantized,
|
|
2379
|
+
aggregation_strategy: 'simple',
|
|
2380
|
+
progress_callback: () => { }
|
|
2381
|
+
}));
|
|
2382
|
+
try {
|
|
2383
|
+
return await runPipelineLoad();
|
|
2384
|
+
}
|
|
2385
|
+
catch (firstError) {
|
|
2386
|
+
const message = firstError instanceof Error ? firstError.message : String(firstError);
|
|
2387
|
+
logger.warn('[Transformers] token-classification pipeline load failed', { message });
|
|
2388
|
+
throw new Error(`transformers_pipeline_load_failed:${message}`);
|
|
2389
|
+
}
|
|
2390
|
+
finally {
|
|
2391
|
+
window.fetch = originalFetch;
|
|
2392
|
+
}
|
|
2393
|
+
});
|
|
2394
|
+
const { result: pipeline, ms: loadModelMs } = loadResult;
|
|
2395
|
+
return { pipeline: pipeline, loadModelMs };
|
|
2396
|
+
};
|
|
2397
|
+
const loadTransformersAdapter = async (slm, options) => {
|
|
2398
|
+
const logger = getLogger();
|
|
2399
|
+
const startTime = performance.now();
|
|
2400
|
+
const downloadedFiles = {};
|
|
2401
|
+
try {
|
|
2402
|
+
const cached = await getModel(slm.modelId, slm.modelVersion);
|
|
2403
|
+
const cachedFiles = cached?.files || {};
|
|
2404
|
+
if (!cached && options?.allowDownload === false) {
|
|
2405
|
+
return { error: new Error('model_not_cached'), metrics: {} };
|
|
2406
|
+
}
|
|
2407
|
+
const onFileDownloaded = (filename, blob) => {
|
|
2408
|
+
downloadedFiles[filename] = blob;
|
|
2409
|
+
};
|
|
2410
|
+
const baseMetrics = cached
|
|
2411
|
+
? {
|
|
2412
|
+
downloadMs: cached.metadata.downloadMs,
|
|
2413
|
+
loadModelMs: cached.metadata.loadModelMs,
|
|
2414
|
+
sizeBytes: cached.metadata.sizeBytes
|
|
2415
|
+
}
|
|
2416
|
+
: {};
|
|
2417
|
+
const state = await instantiateTokenPipeline(slm, cachedFiles, onFileDownloaded);
|
|
2418
|
+
const metrics = { ...baseMetrics, loadModelMs: state.loadModelMs };
|
|
2419
|
+
if (Object.keys(downloadedFiles).length > 0) {
|
|
2420
|
+
const allFiles = { ...cachedFiles, ...downloadedFiles };
|
|
2421
|
+
const calculatedSize = Object.values(allFiles).reduce((sum, blob) => sum + blob.size, 0);
|
|
2422
|
+
const downloadMs = Math.round(performance.now() - startTime);
|
|
2423
|
+
await putModelComplete(slm.modelId, slm.modelVersion, {
|
|
2424
|
+
modelId: slm.modelId,
|
|
2425
|
+
modelVersion: slm.modelVersion,
|
|
2426
|
+
sizeBytes: calculatedSize,
|
|
2427
|
+
downloadMs: cached ? 0 : downloadMs,
|
|
2428
|
+
loadModelMs: state.loadModelMs
|
|
2429
|
+
}, allFiles);
|
|
2430
|
+
metrics.sizeBytes = calculatedSize;
|
|
2431
|
+
if (!cached)
|
|
2432
|
+
metrics.downloadMs = downloadMs;
|
|
2433
|
+
}
|
|
2434
|
+
const adapter = new TransformersAdapter(slm, state, metrics);
|
|
2435
|
+
return { adapter, metrics };
|
|
2436
|
+
}
|
|
2437
|
+
catch (error) {
|
|
2438
|
+
console.error('[ZeroGPU][Transformers][load] failed', {
|
|
2439
|
+
modelId: slm.modelId,
|
|
2440
|
+
modelVersion: slm.modelVersion,
|
|
2441
|
+
modelRepoId: slm.modelRepoId,
|
|
2442
|
+
modelUrl: slm.modelUrl,
|
|
2443
|
+
error: serializeError$2(error)
|
|
2444
|
+
});
|
|
2445
|
+
logger.error('Transformers adapter load failed', error);
|
|
2446
|
+
await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
|
|
2447
|
+
return { error: error, metrics: {} };
|
|
2448
|
+
}
|
|
2449
|
+
};
|
|
2450
|
+
|
|
2451
|
+
const capabilities$1 = [
|
|
2452
|
+
{ inferenceFramework: 'Transformers', taskType: 'gliner' },
|
|
2453
|
+
{ inferenceFramework: 'Transformers', taskType: 'gliner2' }
|
|
2454
|
+
];
|
|
2455
|
+
const factory$1 = {
|
|
2456
|
+
capabilities: capabilities$1,
|
|
2457
|
+
load: (config, options) => loadTransformersAdapter(config, options)
|
|
2458
|
+
};
|
|
2459
|
+
registerAdapter(factory$1);
|
|
2460
|
+
|
|
2461
|
+
const WLLAMA_CDN = 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js';
|
|
2462
|
+
let wllamaRuntimePromise = null;
|
|
2463
|
+
const serializeError$1 = (error) => {
|
|
2464
|
+
if (error instanceof Error) {
|
|
2465
|
+
return { name: error.name, message: error.message, stack: error.stack };
|
|
2466
|
+
}
|
|
2467
|
+
return { message: String(error) };
|
|
2468
|
+
};
|
|
2469
|
+
const ensureWllamaRuntime = () => {
|
|
2470
|
+
if (window.WllamaModule) {
|
|
2471
|
+
return Promise.resolve(window.WllamaModule);
|
|
2472
|
+
}
|
|
2473
|
+
if (!wllamaRuntimePromise) {
|
|
2474
|
+
wllamaRuntimePromise = (async () => {
|
|
2475
|
+
try {
|
|
2476
|
+
const mod = await import(/* @vite-ignore */ WLLAMA_CDN);
|
|
2477
|
+
if (!mod?.Wllama) {
|
|
2478
|
+
throw new Error('Wllama runtime missing Wllama export');
|
|
2479
|
+
}
|
|
2480
|
+
window.WllamaModule = mod;
|
|
2481
|
+
return mod;
|
|
2482
|
+
}
|
|
2483
|
+
catch (error) {
|
|
2484
|
+
wllamaRuntimePromise = null;
|
|
2485
|
+
console.error('[ZeroGPU][GGUF] Failed to import wllama runtime', {
|
|
2486
|
+
runtimeUrl: WLLAMA_CDN,
|
|
2487
|
+
error: serializeError$1(error)
|
|
2488
|
+
});
|
|
2489
|
+
throw error;
|
|
2490
|
+
}
|
|
2491
|
+
})();
|
|
2492
|
+
}
|
|
2493
|
+
return wllamaRuntimePromise;
|
|
2494
|
+
};
|
|
2495
|
+
const WLLAMA_CDN_BASE = WLLAMA_CDN.replace(/\/esm\/index\.js$/, '/esm');
|
|
2496
|
+
|
|
2497
|
+
const DEFAULT_MAX_NEW_TOKENS = 128;
|
|
2498
|
+
const serializeError = (error) => {
|
|
2499
|
+
if (error instanceof Error) {
|
|
2500
|
+
return { name: error.name, message: error.message, stack: error.stack };
|
|
2501
|
+
}
|
|
2502
|
+
return { message: String(error) };
|
|
2503
|
+
};
|
|
2504
|
+
const pickGgufFileName = (requiredFiles) => {
|
|
2505
|
+
if (!Array.isArray(requiredFiles) || requiredFiles.length === 0)
|
|
2506
|
+
return null;
|
|
2507
|
+
const ggufFile = requiredFiles.find((file) => file?.name?.toLowerCase().endsWith('.gguf'));
|
|
2508
|
+
return ggufFile?.name ?? requiredFiles[0]?.name ?? null;
|
|
2509
|
+
};
|
|
2510
|
+
const buildPrompt = (text, modelType) => {
|
|
2511
|
+
const trimmed = (text ?? '').trim();
|
|
2512
|
+
if (!trimmed)
|
|
2513
|
+
return '';
|
|
2514
|
+
if (modelType && modelType.toLowerCase().includes('instruct')) {
|
|
2515
|
+
return `<|im_start|>user\n${trimmed}<|im_end|>\n<|im_start|>assistant\n`;
|
|
2516
|
+
}
|
|
2517
|
+
return trimmed;
|
|
2518
|
+
};
|
|
2519
|
+
class GgufAdapter {
|
|
2520
|
+
constructor(config, state, metrics) {
|
|
2521
|
+
this.config = config;
|
|
2522
|
+
this.capability = {
|
|
2523
|
+
inferenceFramework: 'GGUF',
|
|
2524
|
+
taskType: config.taskType,
|
|
2525
|
+
modelType: config.modelType
|
|
2526
|
+
};
|
|
2527
|
+
this.state = state;
|
|
2528
|
+
this.metrics = metrics;
|
|
2529
|
+
}
|
|
2530
|
+
async runInference(input) {
|
|
2531
|
+
const prompt = buildPrompt(input.text ?? '', this.config.modelType);
|
|
2532
|
+
if (!prompt) {
|
|
2533
|
+
return { output: { text: '' }, inferenceMs: 0 };
|
|
2534
|
+
}
|
|
2535
|
+
const maxNewTokens = typeof input.maxNewTokens === 'number' && input.maxNewTokens > 0
|
|
2536
|
+
? input.maxNewTokens
|
|
2537
|
+
: DEFAULT_MAX_NEW_TOKENS;
|
|
2538
|
+
const { result, ms } = await measure(async () => this.state.wllama.createCompletion(prompt, { nPredict: maxNewTokens }));
|
|
2539
|
+
const text = typeof result === 'string' ? result : extractCompletionText(result);
|
|
2540
|
+
return { output: { text }, inferenceMs: ms };
|
|
2541
|
+
}
|
|
2542
|
+
async runSample(sample) {
|
|
2543
|
+
const start = performance.now();
|
|
2544
|
+
if (typeof sample.text !== 'string') {
|
|
2545
|
+
return {
|
|
2546
|
+
ok: false,
|
|
2547
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
2548
|
+
error: true,
|
|
2549
|
+
errorMessage: 'response from processing sample'
|
|
2550
|
+
};
|
|
2551
|
+
}
|
|
2552
|
+
try {
|
|
2553
|
+
const result = await this.runInference({
|
|
2554
|
+
text: sample.text,
|
|
2555
|
+
maxNewTokens: 32,
|
|
2556
|
+
usecase: sample.usecase
|
|
2557
|
+
});
|
|
2558
|
+
const output = result.output;
|
|
2559
|
+
const text = typeof output?.text === 'string' ? output.text.trim() : '';
|
|
2560
|
+
if (!text) {
|
|
2561
|
+
return {
|
|
2562
|
+
ok: false,
|
|
2563
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
2564
|
+
error: true,
|
|
2565
|
+
errorMessage: 'response from processing sample'
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
return {
|
|
2569
|
+
ok: true,
|
|
2570
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
2571
|
+
error: false
|
|
2572
|
+
};
|
|
2573
|
+
}
|
|
2574
|
+
catch (err) {
|
|
2575
|
+
return {
|
|
2576
|
+
ok: false,
|
|
2577
|
+
processingTimeMs: Math.round(performance.now() - start),
|
|
2578
|
+
error: true,
|
|
2579
|
+
errorMessage: err instanceof Error ? err.message : String(err)
|
|
2580
|
+
};
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
const extractCompletionText = (raw) => {
|
|
2585
|
+
if (!raw)
|
|
2586
|
+
return '';
|
|
2587
|
+
if (typeof raw === 'string')
|
|
2588
|
+
return raw;
|
|
2589
|
+
if (typeof raw === 'object') {
|
|
2590
|
+
const obj = raw;
|
|
2591
|
+
if (typeof obj.text === 'string')
|
|
2592
|
+
return obj.text;
|
|
2593
|
+
if (typeof obj.content === 'string')
|
|
2594
|
+
return obj.content;
|
|
2595
|
+
if (typeof obj.completion === 'string')
|
|
2596
|
+
return obj.completion;
|
|
2597
|
+
}
|
|
2598
|
+
try {
|
|
2599
|
+
return JSON.stringify(raw);
|
|
2600
|
+
}
|
|
2601
|
+
catch {
|
|
2602
|
+
return String(raw);
|
|
2603
|
+
}
|
|
2604
|
+
};
|
|
2605
|
+
const fetchGgufBlob = async (slm, ggufFileName, cachedFiles, onFileDownloaded) => {
|
|
2606
|
+
const modelScopedKey = `${slm.modelId}/${ggufFileName}`;
|
|
2607
|
+
const existing = cachedFiles[modelScopedKey] ||
|
|
2608
|
+
cachedFiles[ggufFileName];
|
|
2609
|
+
if (existing)
|
|
2610
|
+
return existing;
|
|
2611
|
+
const rawUrl = (slm.modelUrl || '').replace(/\/$/, '');
|
|
2612
|
+
if (!rawUrl) {
|
|
2613
|
+
throw new Error('gguf_model_url_missing');
|
|
2614
|
+
}
|
|
2615
|
+
// Strip Hugging Face browser-view paths (/tree/<branch>, /blob/<branch>) so we
|
|
2616
|
+
// can rebuild the correct /resolve/<branch>/ download URL.
|
|
2617
|
+
const hfViewMatch = rawUrl.match(/^(.*?\/huggingface\.co\/[^/]+\/[^/]+)\/(?:tree|blob)\/([^/]+)(?:\/.*)?$/i);
|
|
2618
|
+
const baseUrl = hfViewMatch ? hfViewMatch[1] : rawUrl;
|
|
2619
|
+
const branch = hfViewMatch ? hfViewMatch[2] : 'main';
|
|
2620
|
+
const candidates = [
|
|
2621
|
+
`${baseUrl}/resolve/${branch}/${ggufFileName}`,
|
|
2622
|
+
`${baseUrl}/${ggufFileName}`
|
|
2623
|
+
];
|
|
2624
|
+
const failures = [];
|
|
2625
|
+
for (const url of candidates) {
|
|
2626
|
+
try {
|
|
2627
|
+
const response = await fetch(url);
|
|
2628
|
+
if (response.ok) {
|
|
2629
|
+
const blob = await response.blob();
|
|
2630
|
+
onFileDownloaded(modelScopedKey, blob);
|
|
2631
|
+
return blob;
|
|
2632
|
+
}
|
|
2633
|
+
failures.push(`${url} → HTTP ${response.status}`);
|
|
2634
|
+
}
|
|
2635
|
+
catch (err) {
|
|
2636
|
+
failures.push(`${url} → ${err instanceof Error ? err.message : String(err)}`);
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
throw new Error(`gguf_file_fetch_failed: ${failures.join('; ')}`);
|
|
2640
|
+
};
|
|
2641
|
+
const instantiateWllama = async (slm, cachedFiles, onFileDownloaded) => {
|
|
2642
|
+
const ggufFileName = pickGgufFileName(slm.requiredFiles);
|
|
2643
|
+
if (!ggufFileName) {
|
|
2644
|
+
throw new Error('gguf_required_file_missing');
|
|
2645
|
+
}
|
|
2646
|
+
const mod = await ensureWllamaRuntime();
|
|
2647
|
+
const blob = await fetchGgufBlob(slm, ggufFileName, cachedFiles, onFileDownloaded);
|
|
2648
|
+
// A host that vendors wllama locally (e.g. an MV3 extension offscreen document)
|
|
2649
|
+
// can point the wasm at packaged files via `window.WllamaWasmPaths`; otherwise
|
|
2650
|
+
// fall back to the jsDelivr CDN used on the web/Telegram.
|
|
2651
|
+
const wllamaConfig = window.WllamaWasmPaths ?? {
|
|
2652
|
+
'single-thread/wllama.wasm': `${WLLAMA_CDN_BASE}/single-thread/wllama.wasm`,
|
|
2653
|
+
'multi-thread/wllama.wasm': `${WLLAMA_CDN_BASE}/multi-thread/wllama.wasm`
|
|
2654
|
+
};
|
|
2655
|
+
const wllama = new mod.Wllama(wllamaConfig);
|
|
2656
|
+
const { ms: loadModelMs } = await measure(async () => {
|
|
2657
|
+
await wllama.loadModel([blob], {
|
|
2658
|
+
n_ctx: slm.maxInputTokens && slm.maxInputTokens > 0 ? slm.maxInputTokens : 2048
|
|
2659
|
+
});
|
|
2660
|
+
});
|
|
2661
|
+
return { wllama, loadModelMs };
|
|
2662
|
+
};
|
|
2663
|
+
const loadGgufAdapter = async (slm, options) => {
|
|
2664
|
+
const logger = getLogger();
|
|
2665
|
+
const startTime = performance.now();
|
|
2666
|
+
const downloadedFiles = {};
|
|
2667
|
+
try {
|
|
2668
|
+
const cached = await getModel(slm.modelId, slm.modelVersion);
|
|
2669
|
+
const cachedFiles = cached?.files || {};
|
|
2670
|
+
if (!cached && options?.allowDownload === false) {
|
|
2671
|
+
return { error: new Error('model_not_cached'), metrics: {} };
|
|
2672
|
+
}
|
|
2673
|
+
const onFileDownloaded = (filename, blob) => {
|
|
2674
|
+
downloadedFiles[filename] = blob;
|
|
2675
|
+
};
|
|
2676
|
+
const baseMetrics = cached
|
|
2677
|
+
? {
|
|
2678
|
+
downloadMs: cached.metadata.downloadMs,
|
|
2679
|
+
loadModelMs: cached.metadata.loadModelMs,
|
|
2680
|
+
sizeBytes: cached.metadata.sizeBytes
|
|
2681
|
+
}
|
|
2682
|
+
: {};
|
|
2683
|
+
const state = await instantiateWllama(slm, cachedFiles, onFileDownloaded);
|
|
2684
|
+
const metrics = { ...baseMetrics, loadModelMs: state.loadModelMs };
|
|
2685
|
+
if (Object.keys(downloadedFiles).length > 0) {
|
|
2686
|
+
const allFiles = { ...cachedFiles, ...downloadedFiles };
|
|
2687
|
+
const calculatedSize = Object.values(allFiles).reduce((sum, blob) => sum + blob.size, 0);
|
|
2688
|
+
const downloadMs = Math.round(performance.now() - startTime);
|
|
2689
|
+
await putModelComplete(slm.modelId, slm.modelVersion, {
|
|
2690
|
+
modelId: slm.modelId,
|
|
2691
|
+
modelVersion: slm.modelVersion,
|
|
2692
|
+
sizeBytes: calculatedSize,
|
|
2693
|
+
downloadMs: cached ? 0 : downloadMs,
|
|
2694
|
+
loadModelMs: state.loadModelMs
|
|
2695
|
+
}, allFiles);
|
|
2696
|
+
metrics.sizeBytes = calculatedSize;
|
|
2697
|
+
if (!cached)
|
|
2698
|
+
metrics.downloadMs = downloadMs;
|
|
2699
|
+
}
|
|
2700
|
+
const adapter = new GgufAdapter(slm, state, metrics);
|
|
2701
|
+
return { adapter, metrics };
|
|
2702
|
+
}
|
|
2703
|
+
catch (error) {
|
|
2704
|
+
console.error('[ZeroGPU][GGUF][load] failed', {
|
|
2705
|
+
modelId: slm.modelId,
|
|
2706
|
+
modelVersion: slm.modelVersion,
|
|
2707
|
+
modelUrl: slm.modelUrl,
|
|
2708
|
+
error: serializeError(error)
|
|
2709
|
+
});
|
|
2710
|
+
logger.error('GGUF adapter load failed', error);
|
|
2711
|
+
await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
|
|
2712
|
+
return { error: error, metrics: {} };
|
|
2713
|
+
}
|
|
2714
|
+
};
|
|
2715
|
+
|
|
2716
|
+
const capabilities = [
|
|
2717
|
+
{ inferenceFramework: 'GGUF', taskType: 'text_generation' },
|
|
2718
|
+
{ inferenceFramework: 'GGUF', taskType: 'summary' }
|
|
2719
|
+
];
|
|
2720
|
+
const factory = {
|
|
2721
|
+
capabilities,
|
|
2722
|
+
load: (config, options) => loadGgufAdapter(config, options)
|
|
2723
|
+
};
|
|
2724
|
+
registerAdapter(factory);
|
|
2725
|
+
|
|
2726
|
+
let initialized = false;
|
|
2727
|
+
const initZeroGpuSdk = async (options) => {
|
|
2728
|
+
if (initialized) {
|
|
2729
|
+
return;
|
|
2730
|
+
}
|
|
2731
|
+
const config = resolveConfig(options?.overrides);
|
|
2732
|
+
await startLifecycle({
|
|
2733
|
+
config,
|
|
2734
|
+
appUserId: options?.appUserId,
|
|
2735
|
+
edgeOperatorKey: options?.edgeOperatorKey,
|
|
2736
|
+
deviceId: options?.deviceId
|
|
2737
|
+
});
|
|
2738
|
+
initialized = true;
|
|
2739
|
+
};
|
|
2740
|
+
|
|
2741
|
+
const readAttr = (script, names) => {
|
|
2742
|
+
for (const name of names) {
|
|
2743
|
+
const value = script.getAttribute(name)?.trim();
|
|
2744
|
+
if (value) {
|
|
2745
|
+
return value;
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
return undefined;
|
|
2749
|
+
};
|
|
2750
|
+
const readSearchParam = (searchParams, names) => {
|
|
2751
|
+
if (!searchParams) {
|
|
2752
|
+
return undefined;
|
|
2753
|
+
}
|
|
2754
|
+
for (const name of names) {
|
|
2755
|
+
const value = searchParams.get(name)?.trim();
|
|
2756
|
+
if (value) {
|
|
2757
|
+
return value;
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
return undefined;
|
|
2761
|
+
};
|
|
2762
|
+
const getCurrentScript = () => {
|
|
2763
|
+
if (typeof document === 'undefined') {
|
|
2764
|
+
return null;
|
|
2765
|
+
}
|
|
2766
|
+
return document.currentScript instanceof HTMLScriptElement
|
|
2767
|
+
? document.currentScript
|
|
2768
|
+
: null;
|
|
2769
|
+
};
|
|
2770
|
+
const readBooleanAttr = (script, names) => {
|
|
2771
|
+
for (const name of names) {
|
|
2772
|
+
const value = script.getAttribute(name);
|
|
2773
|
+
if (value === null) {
|
|
2774
|
+
continue;
|
|
2775
|
+
}
|
|
2776
|
+
const normalized = value.trim().toLowerCase();
|
|
2777
|
+
if (normalized === '') {
|
|
2778
|
+
return true; // Valueless attribute treated as true
|
|
2779
|
+
}
|
|
2780
|
+
else if (normalized === 'true' || normalized === '1') {
|
|
2781
|
+
return true;
|
|
2782
|
+
}
|
|
2783
|
+
if (normalized === 'false' || normalized === '0') {
|
|
2784
|
+
return false;
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
return undefined;
|
|
2788
|
+
};
|
|
2789
|
+
const autoInitFromScriptTag = () => {
|
|
2790
|
+
const script = getCurrentScript();
|
|
2791
|
+
if (!script) {
|
|
2792
|
+
return;
|
|
2793
|
+
}
|
|
2794
|
+
let searchParams;
|
|
2795
|
+
const src = script.getAttribute('src')?.trim();
|
|
2796
|
+
if (src) {
|
|
2797
|
+
try {
|
|
2798
|
+
const url = new URL(src, typeof document !== 'undefined' ? document.baseURI : undefined);
|
|
2799
|
+
searchParams = url.searchParams;
|
|
2800
|
+
}
|
|
2801
|
+
catch {
|
|
2802
|
+
searchParams = undefined;
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
const edgeOperatorKey = readAttr(script, ['data-edge-operator-key', 'edgeOperatorKey']) ??
|
|
2806
|
+
readSearchParam(searchParams, ['edge-operator-key', 'edgeOperatorKey']);
|
|
2807
|
+
if (!edgeOperatorKey) {
|
|
2808
|
+
return;
|
|
2809
|
+
}
|
|
2810
|
+
const options = {
|
|
2811
|
+
appUserId: readAttr(script, ['data-app-user-id', 'appUserId']) ??
|
|
2812
|
+
readSearchParam(searchParams, ['app-user-id', 'appUserId']),
|
|
2813
|
+
deviceId: readAttr(script, ['data-device-id', 'deviceId']) ??
|
|
2814
|
+
readSearchParam(searchParams, ['device-id', 'deviceId']),
|
|
2815
|
+
edgeOperatorKey
|
|
2816
|
+
};
|
|
2817
|
+
const enableConsoleLogs = readBooleanAttr(script, ['data-enable-console-logs', 'enableConsoleLogs']) ??
|
|
2818
|
+
(() => {
|
|
2819
|
+
const value = readSearchParam(searchParams, ['enable-console-logs', 'enableConsoleLogs']);
|
|
2820
|
+
if (value === undefined) {
|
|
2821
|
+
return undefined;
|
|
2822
|
+
}
|
|
2823
|
+
const normalized = value.toLowerCase();
|
|
2824
|
+
if (normalized === 'true' || normalized === '1') {
|
|
2825
|
+
return true;
|
|
2826
|
+
}
|
|
2827
|
+
if (normalized === 'false' || normalized === '0') {
|
|
2828
|
+
return false;
|
|
2829
|
+
}
|
|
2830
|
+
return undefined;
|
|
2831
|
+
})();
|
|
2832
|
+
if (enableConsoleLogs !== undefined) {
|
|
2833
|
+
options.overrides = {
|
|
2834
|
+
telemetry: {
|
|
2835
|
+
enableConsoleLogs,
|
|
2836
|
+
locationData: false,
|
|
2837
|
+
cameraData: false
|
|
2838
|
+
}
|
|
2839
|
+
};
|
|
2840
|
+
}
|
|
2841
|
+
void initZeroGpuSdk(options).catch((error) => {
|
|
2842
|
+
console.error('[ZeroGpuSdk] Auto-init failed', error);
|
|
2843
|
+
});
|
|
2844
|
+
};
|
|
2845
|
+
|
|
2846
|
+
autoInitFromScriptTag();
|
|
2847
|
+
|
|
2848
|
+
exports.initZeroGpuSdk = initZeroGpuSdk;
|
|
2849
|
+
//# sourceMappingURL=zerogpu-browser-sdk.cjs.map
|