@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.
Files changed (72) hide show
  1. package/README.md +264 -0
  2. package/bin/zerogpu.mjs +331 -0
  3. package/dist/assets/ort-wasm-simd-threaded.wasm +0 -0
  4. package/dist/assets/ort-wasm-simd.wasm +0 -0
  5. package/dist/assets/ort-wasm-threaded.wasm +0 -0
  6. package/dist/assets/ort-wasm.wasm +0 -0
  7. package/dist/assets/transformers.min.js +107 -0
  8. package/dist/assets/wllama/index.js +3374 -0
  9. package/dist/assets/wllama/multi-thread/wllama.wasm +0 -0
  10. package/dist/assets/wllama/single-thread/wllama.wasm +0 -0
  11. package/dist/assets/zerogpu-assets.json +17 -0
  12. package/dist/extension/zerogpu-offscreen.js +2904 -0
  13. package/dist/extension/zerogpu-offscreen.js.map +1 -0
  14. package/dist/loader.js +2 -0
  15. package/dist/loader.js.map +1 -0
  16. package/dist/manifest.json +7 -0
  17. package/dist/types/adapters/gguf/adapter.d.ts +3 -0
  18. package/dist/types/adapters/gguf/factory.d.ts +3 -0
  19. package/dist/types/adapters/gguf/index.d.ts +2 -0
  20. package/dist/types/adapters/gguf/runtime.d.ts +16 -0
  21. package/dist/types/adapters/index.d.ts +5 -0
  22. package/dist/types/adapters/onnx/adapter.d.ts +3 -0
  23. package/dist/types/adapters/onnx/env-fetch.d.ts +1 -0
  24. package/dist/types/adapters/onnx/factory.d.ts +3 -0
  25. package/dist/types/adapters/onnx/index.d.ts +2 -0
  26. package/dist/types/adapters/onnx/runtime.d.ts +15 -0
  27. package/dist/types/adapters/registry.d.ts +5 -0
  28. package/dist/types/adapters/transformers/adapter.d.ts +10 -0
  29. package/dist/types/adapters/transformers/factory.d.ts +3 -0
  30. package/dist/types/adapters/transformers/index.d.ts +2 -0
  31. package/dist/types/adapters/types.d.ts +64 -0
  32. package/dist/types/auto-init.d.ts +1 -0
  33. package/dist/types/config/defaults.d.ts +2 -0
  34. package/dist/types/config/env.d.ts +7 -0
  35. package/dist/types/config/orchestrator-url.d.ts +1 -0
  36. package/dist/types/config/types.d.ts +34 -0
  37. package/dist/types/device/fingerprint.d.ts +2 -0
  38. package/dist/types/device/telemetry.d.ts +3 -0
  39. package/dist/types/device/types.d.ts +58 -0
  40. package/dist/types/extension/offscreen.d.ts +49 -0
  41. package/dist/types/index.d.ts +1 -0
  42. package/dist/types/loader.d.ts +25 -0
  43. package/dist/types/public-api.d.ts +13 -0
  44. package/dist/types/runtime/lifecycle.d.ts +8 -0
  45. package/dist/types/runtime/router.d.ts +2 -0
  46. package/dist/types/runtime/sdk-state.d.ts +56 -0
  47. package/dist/types/sdk-version.d.ts +1 -0
  48. package/dist/types/storage/cached-model.d.ts +29 -0
  49. package/dist/types/storage/index.d.ts +4 -0
  50. package/dist/types/storage/meta-store.d.ts +2 -0
  51. package/dist/types/storage/model-store.d.ts +9 -0
  52. package/dist/types/storage/types.d.ts +19 -0
  53. package/dist/types/transport/http.d.ts +54 -0
  54. package/dist/types/transport/protocol.d.ts +47 -0
  55. package/dist/types/transport/status.d.ts +1 -0
  56. package/dist/types/transport/websocket.d.ts +25 -0
  57. package/dist/types/utils/errors.d.ts +4 -0
  58. package/dist/types/utils/logger.d.ts +15 -0
  59. package/dist/types/utils/timers.d.ts +7 -0
  60. package/dist/types/utils/uuid.d.ts +1 -0
  61. package/dist/v/zerogpu-browser-sdk.f47bae4f15c9.umd.js +2855 -0
  62. package/dist/v/zerogpu-browser-sdk.f47bae4f15c9.umd.js.map +1 -0
  63. package/dist/zerogpu-browser-sdk.cjs +2849 -0
  64. package/dist/zerogpu-browser-sdk.cjs.map +1 -0
  65. package/dist/zerogpu-browser-sdk.esm.js +2847 -0
  66. package/dist/zerogpu-browser-sdk.esm.js.map +1 -0
  67. package/dist/zerogpu-browser-sdk.umd.js +2855 -0
  68. package/dist/zerogpu-browser-sdk.umd.js.map +1 -0
  69. package/docs/INTEGRATION.md +213 -0
  70. package/docs/auto-update-loader.md +451 -0
  71. package/docs/multi-model-support.md +537 -0
  72. package/package.json +91 -0
@@ -0,0 +1,537 @@
1
+ # Multi-Model Support in the Browser SDK
2
+
3
+ A plain-language summary of what changed in the ZeroGPU Browser SDK to host any model from the model registry, what needs to happen on the backend, and how to verify it works.
4
+
5
+ Audience: project managers, product, anyone who wants the shape of the change without reading code.
6
+
7
+ ---
8
+
9
+ ## TL;DR
10
+
11
+ **Before:** the SDK only knew how to run three kinds of models (text summary, two flavors of text classification), and only one inference engine (ONNX via Transformers.js). Adding a new model type meant editing several files in the SDK.
12
+
13
+ **After:** the SDK has an internal "adapter" system. Each adapter knows how to run one family of models. We shipped three: **ONNX** (existing), **Transformers** (for entity / PII models like GLiNER), and **GGUF** (for small language models like LFM2.5 and Llama 3). Adding a new model type means dropping in one new adapter — the registration, caching, WebSocket, and lifecycle code never changes.
14
+
15
+ The backend still decides which model goes to which device. The SDK just runs whatever it's told to run.
16
+
17
+ ---
18
+
19
+ ## What the SDK had to support
20
+
21
+ The ZeroGPU model registry contains models across **three different inference frameworks** and **five different task types**, plus some models that expose multiple "use cases" from one loaded model (e.g. GLiNER can do entity extraction, PII redaction, JSON parsing, and classification from the same weights).
22
+
23
+ | Framework | What runs on it | Task types | Example models |
24
+ |---|---|---|---|
25
+ | **ONNX** | Standard ML models compiled to ONNX | classification, summary, iab_classify, text_generation | deberta-v3-small, t5-small, followup-questions |
26
+ | **Transformers** | HuggingFace token-classification models | gliner | gliner-multi-pii-v1, gliner2-base-v1 |
27
+ | **GGUF** | Quantized small language models | text_generation | LFM2.5-1.2B-Instruct, llama-3.1-8b-instruct-fast |
28
+
29
+ Some Transformers models do more than one thing — for example, the same loaded GLiNER model can do:
30
+ - **NER** — extract named entities
31
+ - **extract-pii** — find emails, phone numbers, IDs
32
+ - **redact** — replace PII spans with `[REDACTED]`
33
+ - **json** — extract structured data matching a schema
34
+ - **classification** — multi-label text classification
35
+
36
+ The SDK has to route each incoming task to the right operation without reloading the model.
37
+
38
+ ---
39
+
40
+ ## The Old Flow
41
+
42
+ ```mermaid
43
+ flowchart TD
44
+ A[Browser tab opens] --> B[initZeroGpuSdk]
45
+ B --> C[POST /register with device info]
46
+ C --> D{Model assigned?}
47
+ D -- No --> Stop1[Stop]
48
+ D -- Yes --> E[Hard-coded check:<br/>is taskType one of summary, iab_classify, classification?]
49
+ E -- No --> Reject[Reject model]
50
+ E -- Yes --> F[loadSlmEngine via Transformers.js + ONNX]
51
+ F --> G[Pre-cache sample test]
52
+ G --> H[Open WebSocket]
53
+ H --> I[Server sends task batch]
54
+ I --> J{Hard-coded branch:<br/>summary path? classification path?}
55
+ J --> K[Run engine.summarize or engine.classify]
56
+ K --> L[Hand-format response shape]
57
+ L --> M[Send response over WS]
58
+ ```
59
+
60
+ **Problems with the old flow:**
61
+ - The check at step E was a whitelist. Anything outside the three task types was silently dropped.
62
+ - Step F always used the same ONNX engine. No way to run a GGUF or PyTorch model.
63
+ - Step J had hard-coded branches per task. Adding a new task meant editing the router, the lifecycle, and the response shaping.
64
+ - One engine instance per task type. Two models with the same task type couldn't coexist.
65
+
66
+ ---
67
+
68
+ ## The New Flow
69
+
70
+ ```mermaid
71
+ flowchart TD
72
+ A[Browser tab opens] --> B[initZeroGpuSdk]
73
+ B --> AdapterReg[Adapters self-register:<br/>ONNX, Transformers, GGUF]
74
+ AdapterReg --> C[POST /register with device info]
75
+ C --> D{Model assigned?}
76
+ D -- No --> Stop1[Stop]
77
+ D -- Yes --> E[Look up adapter by<br/>inferenceFramework + taskType]
78
+ E -- Not found --> Skip[Skip model, log warning]
79
+ E -- Found --> F[adapter.load downloads files,<br/>boots framework]
80
+ F --> G[adapter.runSample validates output]
81
+ G --> H[Open WebSocket]
82
+ H --> I[Server sends task batch]
83
+ I --> J[Look up adapter by modelId]
84
+ J --> K[adapter.runInference reads usecase from input,<br/>routes internally]
85
+ K --> L[Adapter returns wire-shape output]
86
+ L --> M[Send response over WS]
87
+ ```
88
+
89
+ **What's better:**
90
+ - Step E asks "do we have an adapter for this combination?" instead of checking a hard-coded list. New task types and new frameworks plug into the same lookup.
91
+ - Step F dispatches to the right loader. ONNX models go through Transformers.js. GLiNER goes through token-classification. LFM2.5 goes through wllama (a WASM build of llama.cpp).
92
+ - Step J looks up by `modelId`, not by `taskType`. Two models with the same task type now coexist fine.
93
+ - Step K hands the input straight to the adapter. The router doesn't need to know what a "gliner" task looks like — the GLiNER adapter does.
94
+
95
+ ---
96
+
97
+ ## What changed inside the SDK
98
+
99
+ ```mermaid
100
+ flowchart LR
101
+ subgraph Old["Before"]
102
+ OldLifecycle[lifecycle.ts]
103
+ OldLoader[model/loader.ts<br/>Transformers.js only]
104
+ OldRouter[router.ts<br/>hard-coded task branches]
105
+ OldRegistry[tasks/registry.ts<br/>3-task whitelist]
106
+ OldLifecycle --> OldLoader
107
+ OldLifecycle --> OldRegistry
108
+ OldRouter --> OldLoader
109
+ end
110
+
111
+ subgraph New["After"]
112
+ NewLifecycle[lifecycle.ts]
113
+ NewRegistry[adapters/registry.ts]
114
+ OnnxA[adapters/onnx]
115
+ TransA[adapters/transformers]
116
+ GgufA[adapters/gguf]
117
+ NewRouter[router.ts<br/>generic dispatch]
118
+ NewLifecycle --> NewRegistry
119
+ NewRegistry --> OnnxA
120
+ NewRegistry --> TransA
121
+ NewRegistry --> GgufA
122
+ NewRouter --> NewRegistry
123
+ end
124
+ ```
125
+
126
+ **Files added:**
127
+ - `sdk/src/adapters/types.ts` — the `ModelAdapter` interface every adapter implements
128
+ - `sdk/src/adapters/registry.ts` — internal lookup `(framework, taskType) → adapter factory`
129
+ - `sdk/src/adapters/onnx/` — wraps the existing Transformers.js path (no behavior change for current production models)
130
+ - `sdk/src/adapters/transformers/` — runs GLiNER token-classification + handles use-case routing (NER, PII, redact, JSON, classification)
131
+ - `sdk/src/adapters/gguf/` — runs `.gguf` files via wllama (WebAssembly llama.cpp)
132
+
133
+ **Files removed:**
134
+ - `sdk/src/model/loader.ts`, `sdk/src/model/types.ts`
135
+ - `sdk/src/tasks/registry.ts`, `sdk/src/tasks/summary/handler.ts`, `sdk/src/tasks/summary/types.ts`
136
+ - `sdk/src/runtime/self-test.ts`
137
+
138
+ **Files changed:**
139
+ - `sdk/src/runtime/lifecycle.ts` — uses adapter factories instead of one ONNX loader
140
+ - `sdk/src/runtime/router.ts` — passes input directly to the adapter; no more task-shape branching
141
+ - `sdk/src/runtime/sdk-state.ts` — engines are now indexed by `modelId` (not task type)
142
+ - `sdk/src/transport/protocol.ts` — WebSocket task input accepts `usecase`, `labels`, `threshold`, `schema`, `mask`, `maxNewTokens`
143
+ - `sdk/src/transport/http.ts` — `/register` response accepts any `taskType` string and richer `sample` shape
144
+ - `sdk/src/config/types.ts` — `TaskType` is now a plain string instead of a 3-value union
145
+
146
+ ---
147
+
148
+ ## How a model gets to a device (full picture)
149
+
150
+ ```mermaid
151
+ sequenceDiagram
152
+ participant Browser
153
+ participant SDK
154
+ participant Orchestrator
155
+ participant ModelHost as Model File Host<br/>(HF / CDN)
156
+ participant WS as WebSocket
157
+
158
+ Browser->>SDK: initZeroGpuSdk()
159
+ SDK->>SDK: Register adapters (ONNX, Transformers, GGUF)
160
+ SDK->>Orchestrator: POST /register (device info, cached models)
161
+ Orchestrator->>SDK: slmConfig[] with inferenceFramework, taskType, requiredFiles
162
+ SDK->>SDK: Look up adapter for each (framework, taskType)
163
+ SDK->>ModelHost: Fetch model files (cached in IndexedDB)
164
+ SDK->>SDK: adapter.load() boots the framework
165
+ SDK->>SDK: adapter.runSample() validates output
166
+ SDK->>WS: open() with hello message
167
+ WS->>SDK: hello_ack
168
+ loop For each incoming task
169
+ WS->>SDK: ServerTaskBatchMessage (modelId + usecase + input)
170
+ SDK->>SDK: adapter.runInference(input)
171
+ SDK->>WS: TaskBatchResponse
172
+ end
173
+ ```
174
+
175
+ ---
176
+
177
+ ## What needs to change in other services
178
+
179
+ The SDK is "dumb on purpose" — it does whatever the registration response and WebSocket tasks tell it to. So all rollout effort sits in two places: the **orchestrator** (the `/register` + WebSocket service) and the **model registry database**.
180
+
181
+ ### 1. Orchestrator: send the new fields in `/register`
182
+
183
+ Today the orchestrator probably echoes the legacy three task types. To unlock new models, the `/register` response's `slmConfig[]` entries must include:
184
+
185
+ | Field | Required? | Notes |
186
+ |---|---|---|
187
+ | `inferenceFramework` | **Yes** | Must be one of `ONNX`, `Transformers`, `GGUF`. SDK picks the adapter from this. |
188
+ | `modelType` | Helpful | Used for prompt formatting in GGUF (e.g. detect `instruct` for chat template). |
189
+ | `taskType` | **Yes** | Any string; no longer restricted to the legacy three. |
190
+ | `requiredFiles` | **Yes** | Must list every file the SDK needs to fetch (and cache). |
191
+ | `sample` | **Yes** | Richer — see below. |
192
+
193
+ ### 2. Orchestrator: send richer `sample` objects
194
+
195
+ After a model loads, the SDK runs a "sample test" using `sample.text`. For new task types the sample needs more fields:
196
+
197
+ ```jsonc
198
+ // GLiNER PII model
199
+ "sample": {
200
+ "text": "Email me at jane@acme.com",
201
+ "labels": ["email", "phone"],
202
+ "threshold": 0.5,
203
+ "usecase": "extract-pii"
204
+ }
205
+
206
+ // GGUF text generation model
207
+ "sample": {
208
+ "text": "Hello, who are you?",
209
+ "usecase": "generate"
210
+ }
211
+ ```
212
+
213
+ ### 3. Orchestrator: send `usecase` on WebSocket task requests
214
+
215
+ Each task pushed over the WebSocket should now include a `usecase` field plus any use-case-specific metadata:
216
+
217
+ ```jsonc
218
+ // GLiNER, redact use case
219
+ {
220
+ "requestId": "...",
221
+ "modelId": "gliner-multi-pii-v1",
222
+ "modelVersion": "1",
223
+ "input": {
224
+ "usecase": "redact",
225
+ "text": "Call me at 415-555-0134",
226
+ "mask": "[REDACTED]"
227
+ }
228
+ }
229
+ ```
230
+
231
+ Use-case values per adapter:
232
+
233
+ | Adapter | Valid `usecase` values |
234
+ |---|---|
235
+ | ONNX | `summary`, `classification`, `iab_classify`, `text_generation` (or match the model's `taskType`) |
236
+ | Transformers (GLiNER) | `ner`, `extract-pii`, `extract-entities`, `redact`, `json`, `classification` |
237
+ | GGUF | `generate` (the only one) |
238
+
239
+ ### 4. Database / model registry rows
240
+
241
+ For each new model row, populate:
242
+ - `inference_framework`
243
+ - `task_type` (any string)
244
+ - `required_files` (JSON array — see below per framework)
245
+ - `model_usecases` (JSON; describes the use cases the orchestrator can route to)
246
+ - `sample` (the validation sample)
247
+
248
+ **Important file conversions:**
249
+ - **GLiNER models** in the registry currently point at `pytorch_model.bin` or `model.safetensors`. These cannot run in a browser. Run them through HuggingFace Optimum to produce ONNX exports and update `required_files` to point at the ONNX bundle (`onnx/model.onnx`, `tokenizer.json`, `tokenizer_config.json`, `config.json`).
250
+ - **GGUF models** should list one `.gguf` file (e.g. `LFM2.5-1.2B-Instruct-Q4_K_M.gguf`) plus nothing else.
251
+
252
+ ### 5. Device gating for big models
253
+
254
+ GGUF models are big. A 1.2B-parameter Q4 quant takes ~750 MB in browser memory; iOS Safari caps tab memory near 1 GB. Before assigning a GGUF model, the orchestrator should check:
255
+
256
+ ```
257
+ device.memoryGb >= 4 AND device.userAgent is not Safari
258
+ ```
259
+
260
+ The SDK already collects both via the `device` payload sent to `/register`. No SDK-side fallback is implemented (per design — the SDK only ever gets on-device assignments).
261
+
262
+ ### 6. File hosting
263
+
264
+ Model files must be reachable from the browser. They need:
265
+ - `Access-Control-Allow-Origin` set (or HuggingFace's `resolve/main/` URLs, which already work)
266
+ - `Content-Type: application/octet-stream` for binary files
267
+ - Support for `Range:` requests (for resumable downloads of large GGUF files)
268
+ - No HTML redirects in the middle (the SDK's fetch interceptor warns when it sees HTML where a model file was expected)
269
+
270
+ ---
271
+
272
+ ## How to test locally in Chrome
273
+
274
+ You'll need: a recent Chrome, an orchestrator endpoint that knows your test device, and credentials (edge operator key + project ID).
275
+
276
+ ### Setup (once)
277
+
278
+ ```bash
279
+ cd sdk
280
+ npm install
281
+ ```
282
+
283
+ ### Each test cycle
284
+
285
+ ```bash
286
+ # 1. Build the SDK bundle (writes sdk/dist/zerogpu-browser-sdk.umd.js)
287
+ npm run build
288
+
289
+ # 2. Start the local demo on http://localhost:8000
290
+ npm run dashboard:dev
291
+ ```
292
+
293
+ Open Chrome → `http://localhost:8000/`. The demo page has fields for **Edge Operator Key** and **Project ID**. Fill those, then click **Initialize SDK**.
294
+
295
+ The page sets the SDK's environment based on the hostname: `localhost` → `local` (calls `http://localhost:8787/register`). To hit the development orchestrator instead, open DevTools console and run:
296
+
297
+ ```js
298
+ // IMPORTANT: the demo loads the UMD bundle lazily, only after you click
299
+ // "Initialize SDK" the first time. Click the button once (any credentials)
300
+ // so the script tag is injected, THEN run this in console:
301
+ await window.ZeroGpuBrowserSdk.initZeroGpuSdk({
302
+ edgeOperatorKey: 'your-key'
303
+ });
304
+ ```
305
+
306
+ If you see `Cannot read properties of undefined (reading 'initZeroGpuSdk')`, the bundle hasn't been loaded into the page yet. Either click the Initialize SDK button first, or inject the script manually:
307
+
308
+ ```js
309
+ await new Promise((resolve, reject) => {
310
+ const s = document.createElement('script');
311
+ s.src = '/dist/zerogpu-browser-sdk.umd.js';
312
+ s.onload = resolve;
313
+ s.onerror = reject;
314
+ document.head.appendChild(s);
315
+ });
316
+ ```
317
+
318
+ If you also get a 404 on `/dist/zerogpu-browser-sdk.umd.js`, you haven't built the SDK yet — run `npm run build` in `sdk/`.
319
+
320
+ ### What to watch in DevTools
321
+
322
+ 1. **Network tab → `/register`** — confirm the response's `slmConfig` includes `inferenceFramework`, `taskType`, `requiredFiles`, and a `sample` matching the model.
323
+ 2. **Application tab → IndexedDB → `zerogpu-slm-cache` → `models`** — after first load, one row per `${modelId}:${version}` with all the model files cached as Blobs.
324
+ 3. **Network tab → WS filter** — watch frames going both ways. Incoming = task batches. Outgoing = responses.
325
+ 4. **Console** — every step logs `[ZeroGPU][Flow]` markers.
326
+
327
+ ### Testing each adapter
328
+
329
+ Below: what to make the orchestrator assign for a clean per-framework probe, and what input to expect over the WebSocket.
330
+
331
+ #### A) ONNX adapter — text classification (deberta-v3-small)
332
+
333
+ Orchestrator response for `/register`:
334
+ ```jsonc
335
+ {
336
+ "slmConfig": [{
337
+ "modelId": "deberta-v3-small",
338
+ "modelVersion": "v1",
339
+ "inferenceFramework": "ONNX",
340
+ "taskType": "classification",
341
+ "modelUrl": "https://models.zerogpu.ai/nli-deberta-v3-small",
342
+ "modelRepoId": "Xenova/nli-debarta-v3-small",
343
+ "quantized": true,
344
+ "requiredFiles": [
345
+ {"name": "tokenizer.json", "type": "tokenizer"},
346
+ {"name": "config.json", "type": "config"},
347
+ {"name": "tokenizer_config.json", "type": "tokenizer_config"},
348
+ {"name": "onnx/model_quantized.onnx", "type": "model"}
349
+ ],
350
+ "sample": {
351
+ "text": "The Lakers defeated the Warriors.",
352
+ "categories": ["Sports", "Politics", "Business"],
353
+ "usecase": "classification"
354
+ }
355
+ }]
356
+ }
357
+ ```
358
+
359
+ Send a task over the WebSocket:
360
+ ```jsonc
361
+ {
362
+ "requests": [{
363
+ "requestId": "probe-onnx",
364
+ "modelId": "deberta-v3-small",
365
+ "modelVersion": "v1",
366
+ "input": {
367
+ "usecase": "classification",
368
+ "text": "Apple released a new iPhone.",
369
+ "categories": ["tech", "sports", "politics"]
370
+ }
371
+ }]
372
+ }
373
+ ```
374
+
375
+ Expected response:
376
+ ```jsonc
377
+ { "requests": [{ "response": { "tech": 0.97, "sports": 0.02, "politics": 0.01 }, "error": false, ... }] }
378
+ ```
379
+
380
+ #### B) Transformers adapter — GLiNER PII extraction
381
+
382
+ > **Precondition:** the orchestrator must serve the ONNX-exported GLiNER (not raw safetensors). Without this the load will fail.
383
+
384
+ Orchestrator response for `/register`:
385
+ ```jsonc
386
+ {
387
+ "slmConfig": [{
388
+ "modelId": "gliner-multi-pii-v1",
389
+ "modelVersion": "1",
390
+ "inferenceFramework": "Transformers",
391
+ "taskType": "gliner",
392
+ "modelUrl": "https://your-cdn.example/gliner-multi-pii-v1",
393
+ "modelRepoId": "urchade/gliner_multi_pii-v1",
394
+ "quantized": false,
395
+ "requiredFiles": [
396
+ {"name": "onnx/model.onnx", "type": "model"},
397
+ {"name": "tokenizer.json", "type": "tokenizer"},
398
+ {"name": "tokenizer_config.json", "type": "tokenizer_config"},
399
+ {"name": "config.json", "type": "config"}
400
+ ],
401
+ "sample": {
402
+ "text": "Email me at jane@acme.com",
403
+ "labels": ["email", "phone"],
404
+ "threshold": 0.5,
405
+ "usecase": "extract-pii"
406
+ }
407
+ }]
408
+ }
409
+ ```
410
+
411
+ Task — PII extraction:
412
+ ```jsonc
413
+ {
414
+ "requests": [{
415
+ "requestId": "probe-pii",
416
+ "modelId": "gliner-multi-pii-v1",
417
+ "modelVersion": "1",
418
+ "input": {
419
+ "usecase": "extract-pii",
420
+ "text": "Call me at 415-555-0134 or john@example.com",
421
+ "labels": ["phone", "email"],
422
+ "threshold": 0.5
423
+ }
424
+ }]
425
+ }
426
+ ```
427
+
428
+ Expected response:
429
+ ```jsonc
430
+ { "requests": [{ "response": { "entities": [
431
+ { "text": "415-555-0134", "label": "phone", "score": 0.9, "start": 11, "end": 23 },
432
+ { "text": "john@example.com", "label": "email", "score": 0.95, "start": 27, "end": 43 }
433
+ ] }, "error": false, ... }] }
434
+ ```
435
+
436
+ Task — redaction (same model, different use case):
437
+ ```jsonc
438
+ {
439
+ "input": {
440
+ "usecase": "redact",
441
+ "text": "Call me at 415-555-0134",
442
+ "labels": ["phone"],
443
+ "mask": "[REDACTED]"
444
+ }
445
+ }
446
+ ```
447
+
448
+ Expected response:
449
+ ```jsonc
450
+ { "response": { "text": "Call me at [REDACTED]", "entities": [...] } }
451
+ ```
452
+
453
+ #### C) GGUF adapter — LFM2.5 text generation
454
+
455
+ > **Precondition:** test device must have `memoryGb >= 4`. Don't try this on iOS Safari.
456
+
457
+ Orchestrator response for `/register`:
458
+ ```jsonc
459
+ {
460
+ "slmConfig": [{
461
+ "modelId": "LFM2.5-1.2B-Instruct",
462
+ "modelVersion": "2.5",
463
+ "inferenceFramework": "GGUF",
464
+ "modelType": "lfm2.5-instruct",
465
+ "taskType": "text_generation",
466
+ "modelUrl": "https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-GGUF/resolve/main",
467
+ "quantized": true,
468
+ "quantization": "Q4_K_M",
469
+ "maxTokens": 800,
470
+ "requiredFiles": [
471
+ {"name": "LFM2.5-1.2B-Instruct-Q4_K_M.gguf", "type": "model"}
472
+ ],
473
+ "sample": {
474
+ "text": "What is 2 + 2?",
475
+ "usecase": "generate"
476
+ }
477
+ }]
478
+ }
479
+ ```
480
+
481
+ Task:
482
+ ```jsonc
483
+ {
484
+ "requests": [{
485
+ "requestId": "probe-gguf",
486
+ "modelId": "LFM2.5-1.2B-Instruct",
487
+ "modelVersion": "2.5",
488
+ "input": {
489
+ "usecase": "generate",
490
+ "text": "Hello, who are you?",
491
+ "maxNewTokens": 64
492
+ }
493
+ }]
494
+ }
495
+ ```
496
+
497
+ Expected response:
498
+ ```jsonc
499
+ { "response": { "text": "I'm an AI assistant..." }, "error": false, ... }
500
+ ```
501
+
502
+ ### Common things to check
503
+
504
+ - **Cache works** — second tab reload should skip download and reuse cached blobs from IndexedDB (look for `[Flow] Cache reuse flow` in console).
505
+ - **Sample test passed** — console shows `Post-register sample test result { ok: true }`. If `ok: false`, the model is loaded but doesn't produce valid output for the given sample; fix the `sample` shape or the model file.
506
+ - **Cache invalidation** — if the orchestrator assigns a different model than what's cached, console shows `[Flow] Server assigned different model; refreshing cache` and IndexedDB is purged before re-download.
507
+ - **Failure path** — if the assigned model has an `inferenceFramework` the SDK doesn't recognize, console shows `No adapter factory for assigned model` and the WS connection still opens but tasks for that model return `model_not_ready`.
508
+
509
+ ### Quick end-to-end test in DevTools (no orchestrator changes)
510
+
511
+ If you want to test inference without changing the orchestrator yet, you can call an adapter directly from the console after the SDK has loaded:
512
+
513
+ ```js
514
+ // After SDK init succeeds:
515
+ const { getAdapter } = window.ZeroGpuBrowserSdk;
516
+ const adapter = getAdapter('deberta-v3-small');
517
+ const result = await adapter.runInference({
518
+ usecase: 'classification',
519
+ text: 'Apple released a new iPhone',
520
+ categories: ['tech', 'sports']
521
+ });
522
+ console.log(result.output);
523
+ ```
524
+
525
+ (Note: `getAdapter` is internal — not part of the public SDK API today. Exposing it on `window.ZeroGpuBrowserSdk` is a one-line dev affordance if you want to lean on this pattern.)
526
+
527
+ ---
528
+
529
+ ## Rollout sequence (recommended)
530
+
531
+ 1. **Stop filtering `taskType` on the orchestrator side.** As soon as the orchestrator sends `inferenceFramework` + any task type, the SDK can route it.
532
+ 2. **Light up ONNX models with new task types** (e.g. `text_generation` for the followup-questions model). These should work with no other changes.
533
+ 3. **Produce ONNX exports for GLiNER** and update `required_files` rows. Light up GLiNER use cases (NER → PII → redact → JSON).
534
+ 4. **Roll GGUF with device gating** (`memoryGb >= 4`, non-Safari). Start with the smallest quant.
535
+ 5. **Stretch:** publish a public adapter API if you want partners to ship their own model types. (Today this is internal-only by design.)
536
+
537
+ Each step is independent — you don't need to do them all at once.
package/package.json ADDED
@@ -0,0 +1,91 @@
1
+ {
2
+ "name": "@zerogpu/browser-extension-sdk",
3
+ "version": "0.1.0",
4
+ "description": "ZeroGPU device-side SLM runtime SDK for browsers and Chrome (MV3) extensions",
5
+ "type": "module",
6
+ "main": "dist/zerogpu-browser-sdk.cjs",
7
+ "module": "dist/zerogpu-browser-sdk.esm.js",
8
+ "bin": {
9
+ "zerogpu": "bin/zerogpu.mjs"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "bin",
14
+ "docs"
15
+ ],
16
+ "workspaces": [
17
+ "dashboard-app"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "import": "./dist/zerogpu-browser-sdk.esm.js",
22
+ "require": "./dist/zerogpu-browser-sdk.cjs"
23
+ },
24
+ "./extension": {
25
+ "types": "./dist/types/extension/offscreen.d.ts",
26
+ "import": "./dist/extension/zerogpu-offscreen.js"
27
+ }
28
+ },
29
+ "types": "dist/types/index.d.ts",
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "scripts": {
34
+ "build": "rimraf dist && rollup -c && node scripts/postbuild.mjs",
35
+ "build:prod": "cross-env ZGPU_ORCHESTRATOR_BASE_URL=https://devices.zerogpu.ai npm run build",
36
+ "prepublishOnly": "npm run build:prod",
37
+ "test": "vitest run",
38
+ "lint": "eslint \"src/**/*.{ts,tsx}\"",
39
+ "dev": "rollup -c -w",
40
+ "dashboard:dev": "npm -w dashboard-app run dev",
41
+ "dashboard:build": "npm -w dashboard-app run build",
42
+ "dashboard:preview": "npm -w dashboard-app run preview",
43
+ "prepare:deploy": "npm run build && npm run dashboard:build && rm -rf public && mkdir -p public && cp -r dashboard-app/dist/* public/ && (cp _headers public/_headers 2>/dev/null || true)",
44
+ "deploy": "npm run prepare:deploy && wrangler pages deploy public",
45
+ "deploy:preview": "npm run prepare:deploy && wrangler pages deploy public --project-name=zerogpu-browser-sdk"
46
+ },
47
+ "keywords": [
48
+ "zerogpu",
49
+ "slm",
50
+ "browser",
51
+ "sdk"
52
+ ],
53
+ "author": "ZeroGPU",
54
+ "license": "MIT",
55
+ "repository": {
56
+ "type": "git",
57
+ "url": "git+https://github.com/zerogpu/zerogpu-browser-sdk.git",
58
+ "directory": "sdk"
59
+ },
60
+ "homepage": "https://github.com/zerogpu/zerogpu-browser-sdk/blob/main/sdk/docs/INTEGRATION.md",
61
+ "bugs": {
62
+ "url": "https://github.com/zerogpu/zerogpu-browser-sdk/issues"
63
+ },
64
+ "devDependencies": {
65
+ "@rollup/plugin-commonjs": "^25.0.7",
66
+ "@rollup/plugin-node-resolve": "^15.2.3",
67
+ "@rollup/plugin-terser": "^0.4.4",
68
+ "@rollup/plugin-typescript": "^11.1.6",
69
+ "@types/node": "^20.10.5",
70
+ "@typescript-eslint/eslint-plugin": "^6.13.1",
71
+ "@typescript-eslint/parser": "^6.13.1",
72
+ "@wllama/wllama": "2.3.5",
73
+ "@xenova/transformers": "2.17.2",
74
+ "cross-env": "^10.1.0",
75
+ "eslint": "^8.54.0",
76
+ "eslint-config-prettier": "^9.0.0",
77
+ "eslint-import-resolver-typescript": "^3.6.1",
78
+ "eslint-plugin-import": "^2.29.0",
79
+ "happy-dom": "^15.11.7",
80
+ "prettier": "^3.1.1",
81
+ "rimraf": "^5.0.5",
82
+ "rollup": "^4.5.2",
83
+ "tslib": "^2.8.1",
84
+ "typescript": "^5.3.3",
85
+ "vitest": "^1.6.1",
86
+ "wrangler": "^4.65.0"
87
+ },
88
+ "dependencies": {
89
+ "idb-keyval": "^6.2.1"
90
+ }
91
+ }