@zerogpu/browser-extension-sdk 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +75 -0
  2. package/bin/zerogpu.mjs +6 -0
  3. package/dist/assets/zerogpu-assets.json +2 -2
  4. package/dist/assets/zerogpu-worker.js +1 -1
  5. package/dist/extension/zerogpu-background.js +1 -1
  6. package/dist/extension/zerogpu-offscreen.js +1 -1
  7. package/dist/loader.js +1 -1
  8. package/dist/manifest.json +5 -5
  9. package/dist/types/adapters/kinds.d.ts +8 -0
  10. package/dist/types/adapters/onnx/executor.d.ts +26 -1
  11. package/dist/types/adapters/onnx/runtime.d.ts +10 -4
  12. package/dist/types/adapters/types.d.ts +15 -1
  13. package/dist/types/appinference/eligible.d.ts +12 -0
  14. package/dist/types/appinference/store.d.ts +50 -0
  15. package/dist/types/appinference/types.d.ts +118 -0
  16. package/dist/types/config/types.d.ts +1 -0
  17. package/dist/types/device/telemetry.d.ts +6 -0
  18. package/dist/types/extension/background.d.ts +36 -0
  19. package/dist/types/extension/offscreen.d.ts +25 -3
  20. package/dist/types/loader.d.ts +1 -0
  21. package/dist/types/public-api.d.ts +41 -7
  22. package/dist/types/runtime/app-identity.d.ts +24 -0
  23. package/dist/types/runtime/app-inference.d.ts +60 -0
  24. package/dist/types/runtime/guardrails.d.ts +10 -0
  25. package/dist/types/runtime/host-api.d.ts +13 -1
  26. package/dist/types/runtime/init-guard.d.ts +9 -0
  27. package/dist/types/runtime/lifecycle-options.d.ts +12 -0
  28. package/dist/types/runtime/lifecycle.d.ts +21 -8
  29. package/dist/types/runtime/restart.d.ts +11 -0
  30. package/dist/types/runtime/router.d.ts +13 -0
  31. package/dist/types/runtime/sdk-state.d.ts +24 -0
  32. package/dist/types/runtime/shutdown.d.ts +21 -3
  33. package/dist/types/storage/cached-model.d.ts +31 -2
  34. package/dist/types/telemetry/event-reporter.d.ts +1 -0
  35. package/dist/types/transport/http.d.ts +67 -0
  36. package/dist/v/zerogpu-browser-sdk.686affbdf19f.umd.js +1 -0
  37. package/dist/zerogpu-browser-sdk.cjs +1 -1
  38. package/dist/zerogpu-browser-sdk.esm.js +1 -1
  39. package/dist/zerogpu-browser-sdk.umd.js +1 -1
  40. package/dist/zerogpu-worker.js +1 -1
  41. package/docs/APP_INFERENCE_E2E_2026-11-06_DEV.md +855 -0
  42. package/docs/app-side-inference.md +541 -0
  43. package/docs/extension-developer-guide.md +31 -0
  44. package/docs/multi-model-support.md +5 -1
  45. package/package.json +2 -1
  46. package/dist/v/zerogpu-browser-sdk.87efe0d8c5ba.umd.js +0 -1
@@ -0,0 +1,541 @@
1
+ # Browser SDK 0.5.0: run the model in your own page or extension
2
+
3
+ 0.5.0 adds **app-side inference**. The model a device already holds for the ZeroGPU network can
4
+ now also answer requests from your own page or Chrome extension, on the device. You can also
5
+ choose which model the device holds. The same feature shipped in the Android SDK 0.4.0; the
6
+ protocol and the registry side are shared.
7
+
8
+ Existing integrations keep working after the upgrade. Nothing changes until you call the new
9
+ methods.
10
+
11
+ 0.5.0 also changes how the SDK recovers from a guardrail stop; see [section 8](#8-recovery-after-a-guardrail-stop).
12
+
13
+ **Contents**
14
+
15
+ 1. [How it works](#1-how-it-works)
16
+ 2. [What you can build with it](#2-what-you-can-build-with-it)
17
+ 3. [Setup](#3-setup)
18
+ 4. [The flows](#4-the-flows)
19
+ 5. [Each call, with examples](#5-each-call-with-examples)
20
+ 6. [Inference kinds, with examples](#6-inference-kinds-with-examples)
21
+ 7. [Errors](#7-errors)
22
+ 8. [Recovery after a guardrail stop](#8-recovery-after-a-guardrail-stop)
23
+ 9. [Limits and tips](#9-limits-and-tips)
24
+
25
+ ---
26
+
27
+ ## 1. How it works
28
+
29
+ Each device running the SDK holds **one model at a time**. Until 0.5.0 only the ZeroGPU network
30
+ sent work to it. Now your own code can send work to the same model:
31
+
32
+ ```mermaid
33
+ flowchart LR
34
+ net["ZeroGPU network"] -- "network tasks" --> model
35
+ app["Your page or extension"] -- "runLocal(input)" --> model
36
+ subgraph device["The device, inside the ZeroGPU SDK"]
37
+ model["Active model<br/>one call at a time"]
38
+ end
39
+ ```
40
+
41
+ - **The input stays on the device.** `runLocal` runs the model in the page (in the SDK's inference
42
+ worker) and returns the result. No request goes to a server for it.
43
+ - **It is not an offline mode.** Local calls work only while the device is *contributing*: registered
44
+ with ZeroGPU, model loaded, session acknowledged. In any other state `runLocal` throws, so keep a
45
+ fallback.
46
+ - **ZeroGPU picks a default model.** You don't know in advance which one a device gets. If your
47
+ feature needs a specific model, switch to it with `switchModel`. The device then also serves
48
+ network tasks for that model.
49
+ - **One model at a time.** Every change is a switch: a few seconds when the model is already
50
+ downloaded, longer when it is not. Pick one model per feature and stay on it.
51
+
52
+ Where the SDK runs decides how you reach it:
53
+
54
+ | Surface | Where the SDK runs | How your code calls it |
55
+ |---|---|---|
56
+ | Website, web app, Telegram mini app | the page | the handle from `initZeroGpuSdk()`, or `getZeroGpuSdk()` |
57
+ | Chrome extension (MV3) | the offscreen document | `ZeroGpuBackground.*` helpers from the service worker, popup or options page (they send `chrome.runtime` messages to the offscreen document) |
58
+
59
+ ## 2. What you can build with it
60
+
61
+ The models production offers to browsers and Chrome extensions today:
62
+
63
+ | You want to… | Model | `inferenceKind` | Size |
64
+ |---|---|---|---|
65
+ | Flag abusive or unsafe text before it is posted | `zlm-v1-moderation-edge` | `sequence_classification` | 186 MB |
66
+ | Tag pages, posts or screens with IAB content and audience categories | `zlm-v1-iab-classify-edge` | `sequence_classification` | 25 MB |
67
+ | Categorize a link or website from its domain | `zlm-v1-iab-domain-classifier` | `sequence_classification` | 153 MB |
68
+ | Pull keywords and the user's intent out of a query or short text | `zlm-v1-signal-extract` | `seq2seq_generation` | 200 MB |
69
+ | Sort text into your own labels with no training | `deberta-v3-small` | `zero_shot_classification` | 193 MB |
70
+
71
+ The list can change. Read it at runtime with `eligibleModels()` instead of hard-coding it.
72
+ [Section 6](#6-inference-kinds-with-examples) also covers the kinds the SDK runs that production
73
+ doesn't offer on these surfaces yet (named entities, question answering, embeddings, fill-mask,
74
+ small chat models), so you know what to send when such a model is added.
75
+
76
+ ## 3. Setup
77
+
78
+ ### Website
79
+
80
+ ```ts
81
+ import { initZeroGpuSdk, getZeroGpuSdk } from '@zerogpu/browser-extension-sdk';
82
+
83
+ const sdk = await initZeroGpuSdk({ edgeOperatorKey: 'zgpu-sdk-your-key' });
84
+
85
+ sdk.on('activeModelChanged', ({ modelId }) => {
86
+ // runLocal works from here (also fires after every switch)
87
+ });
88
+ sdk.on('modelChoiceRefused', ({ modelId, reason }) => {
89
+ // your chosen model was not kept; the device is on the default model
90
+ });
91
+ ```
92
+
93
+ With the loader script tag (auto-init through `edgeOperatorKey` on the tag), get the handle after
94
+ the core bundle loaded:
95
+
96
+ ```html
97
+ <script async src="https://js-sdk.zerogpu.ai/dist/loader.js" edgeOperatorKey="zgpu-sdk-your-key"></script>
98
+ <script>
99
+ ZeroGpuSdk.ready.then(() => {
100
+ const sdk = ZeroGpuSdk.getZeroGpuSdk();
101
+ window.addEventListener('zerogpu:activeModelChanged', (e) => console.log('model', e.detail.modelId));
102
+ });
103
+ </script>
104
+ ```
105
+
106
+ Every event also reaches `window` as `zerogpu:<event>` (`activeModelChanged`, `modelChoiceRefused`,
107
+ `degraded`, `recovered`, `shutdown`).
108
+
109
+ ### Chrome extension
110
+
111
+ Nothing changes in `offscreen.js`; the SDK starts there as before. Your own code talks to it through
112
+ the background bundle you already vendor:
113
+
114
+ ```js
115
+ // background.js (service worker), popup.js or options.js — after
116
+ // importScripts("vendor/zerogpu/zerogpu-background.js") or <script src="…/zerogpu-background.js">
117
+ const { contributionState, activeModelId } = await ZeroGpuBackground.getZeroGpuContribution();
118
+ const models = await ZeroGpuBackground.getZeroGpuEligibleModels();
119
+ const outcome = await ZeroGpuBackground.switchZeroGpuModel('zlm-v1-moderation-edge');
120
+ const result = await ZeroGpuBackground.runZeroGpuLocal({ text: 'some text', top_k: 14 });
121
+
122
+ ZeroGpuBackground.onZeroGpuEvent(({ event, detail }) => {
123
+ // activeModelChanged, modelChoiceRefused, degraded, recovered, shutdown
124
+ });
125
+ ```
126
+
127
+ Each helper makes sure the offscreen document exists (it never creates one for a user who opted
128
+ out) and sends one message. A result or error comes back typed exactly as on a website. Content
129
+ scripts cannot reach the offscreen document directly; relay through the service worker.
130
+
131
+ ## 4. The flows
132
+
133
+ The device moves through these states. Read the current one from `contributionState`; local calls
134
+ work only in `contributing`.
135
+
136
+ ```mermaid
137
+ stateDiagram-v2
138
+ [*] --> stopped
139
+ stopped --> registering: initZeroGpuSdk(), or a guardrail restart
140
+ registering --> declined: ZeroGPU declines the device
141
+ declined --> registering: retry
142
+ registering --> preparing: model assigned
143
+ preparing --> registering: warm-up failed
144
+ preparing --> contributing: warm-up passed, session acknowledged
145
+ contributing --> switching: switchModel()
146
+ switching --> contributing: new model ready, or the default
147
+ contributing --> degraded: low memory
148
+ degraded --> contributing: memory recovered
149
+ contributing --> stopped: guardrail stop, or shutdown()
150
+ ```
151
+
152
+ ### 4.1 From `initZeroGpuSdk` to ready
153
+
154
+ ```mermaid
155
+ flowchart TD
156
+ A["initZeroGpuSdk()"] --> R["Register with ZeroGPU<br/>state registering"]
157
+ R -- declined --> D["state declined<br/>retries later, see 4.5"]
158
+ D -- retry --> R
159
+ R -- "model assigned: your remembered choice<br/>if still allowed, else the default" --> P["Download the model, first time only<br/>state preparing"]
160
+ P --> L["Load it and run a warm-up sample"]
161
+ L -- "warm-up fails" --> U["Files deleted, model marked unfit on this device"]
162
+ U -- "register again for the next model" --> R
163
+ L -- "warm-up passes" --> C["Open the session, wait for the ack<br/>state contributing"]
164
+ C --> E["activeModelChanged(modelId)<br/>runLocal works from here"]
165
+ ```
166
+
167
+ `initZeroGpuSdk` resolves after this whole flow (or after it failed cleanly). The first start
168
+ downloads the model (25–200 MB), so it can take a while on a slow connection; later starts take
169
+ seconds because the files are cached.
170
+
171
+ ### 4.2 Switching to another model
172
+
173
+ ```mermaid
174
+ sequenceDiagram
175
+ participant App as Your code
176
+ participant SDK as ZeroGPU SDK
177
+ participant ZG as ZeroGPU
178
+ App->>SDK: switchModel(modelId)
179
+ SDK->>SDK: check the eligible list
180
+ alt not on the list, or not eligible
181
+ SDK-->>App: throws ModelNotEligibleError, nothing changes
182
+ else eligible
183
+ SDK->>SDK: save the choice (survives reloads), state switching
184
+ SDK->>SDK: let the network task in flight finish, close the session, unload the model
185
+ SDK->>ZG: register, asking for modelId
186
+ alt ZeroGPU refuses it
187
+ ZG-->>SDK: the default model and the reason
188
+ SDK->>SDK: prepare the default model, open the session
189
+ SDK-->>App: granted = false, reason
190
+ else ZeroGPU grants it
191
+ ZG-->>SDK: modelId
192
+ SDK->>SDK: download if not cached, load, warm up
193
+ alt warm-up fails
194
+ SDK->>SDK: delete the files, mark the model unfit on this device
195
+ SDK->>ZG: register again, get the default model
196
+ SDK-->>App: granted = false, reason = warmup_failed
197
+ else warm-up passes
198
+ SDK->>ZG: open the session, hello acknowledged
199
+ SDK-->>App: activeModelChanged(modelId)
200
+ SDK-->>App: granted = true
201
+ end
202
+ end
203
+ end
204
+ ```
205
+
206
+ - `switchModel` resolves when the device is contributing again, on the new model or on the default.
207
+ - If the model is already active and the device is contributing, `switchModel` resolves
208
+ `granted = true` right away.
209
+ - One switch at a time: a newer `switchModel` call replaces an older one, which rejects with code
210
+ `switch_superseded`.
211
+ - A switch leaves the previous model on disk, so switching back is a reload, not a download. By
212
+ default up to 3 models stay cached; the least recently used is deleted first, never the active
213
+ one (`resourcePolicy.maxCachedModels` changes it; 0 = no limit).
214
+
215
+ ### 4.3 A local call
216
+
217
+ ```mermaid
218
+ flowchart TD
219
+ A["runLocal(input)"] --> B{"state contributing?"}
220
+ B -- no --> X1["throws NotContributingError(state)"]
221
+ B -- yes --> K{"text within the model's<br/>catalog cap (maxTokens)?"}
222
+ K -- no --> X3["throws ZeroGpuError(input_too_large)"]
223
+ K -- yes --> Q{"Network task running?"}
224
+ Q -- yes --> W["Wait for it to finish, counted in result.queueWaitMs<br/>new network tasks are declined meanwhile"]
225
+ Q -- no --> M["Run the active model on your input"]
226
+ W --> M
227
+ M -- "model fails" --> X2["throws LocalInferenceFailedError"]
228
+ M -- ok --> R["returns LocalInferenceResult"]
229
+ ```
230
+
231
+ - **Your call goes first.** A network task that is already running finishes, then your call runs.
232
+ Network tasks that arrive meanwhile are declined; the device stays in the network.
233
+ - **Calls run one at a time.** If you start several, they queue.
234
+ - **`runLocal` has no model parameter.** It runs whatever model is active. Check `activeModelId`
235
+ (or `result.modelId`) so you don't send moderation input to an IAB model.
236
+
237
+ ### 4.4 Reloads and restarts
238
+
239
+ | Event | What happens |
240
+ |---|---|
241
+ | Page reload / extension restart | The SDK registers again with your remembered choice. The model is still cached, so it is ready in seconds. |
242
+ | Network drops (the laptop sleeps) | The session closes; the SDK retries on its backoff, and immediately when the browser reports the network is back. |
243
+ | `clearModelChoice()` | The next register takes ZeroGPU's default model again. |
244
+
245
+ ### 4.5 When something goes wrong
246
+
247
+ | Situation | What the SDK does | What you see | What to do |
248
+ |---|---|---|---|
249
+ | ZeroGPU declines the device (low battery while unplugged, not enough memory) | Retries on the served cadence (10 minutes by default) | State `declined`. `runLocal` throws `NotContributingError` with `registryReason`. `eligibleModels()` shows every model not eligible with that reason. | Use your fallback |
250
+ | ZeroGPU refuses your chosen model | Clears the choice, takes the default model | `switchModel` resolves `granted = false` with `reason`. A remembered choice refused on a later register: `modelChoiceRefused` | Pick another model, or use the default |
251
+ | The model fails to load or fails its warm-up on this device | Deletes its files, marks it unfit on this device, registers again at once for the next model | `granted = false`, `reason = "warmup_failed:…"` or `load_failed:…`. The model shows `eligible = false`, `reason = "device_unfit"` | `forgetUnfitModel(id)` to try again later. The mark also clears itself for a new model version or a new SDK version. |
252
+ | Low memory | Stops taking work and frees memory until the pressure drops | State `degraded`, `degraded` event, then `recovered` | Retry later |
253
+ | The model fails on your input | Reports the failure (model, error, duration; not your input) | `LocalInferenceFailedError` | Check the input shape for the model's kind |
254
+ | An allocation failure during a call (a `RangeError`, wasm out of memory) | Frees the runtime, closes the session, comes back with a fresh runtime after a short delay ([section 8](#8-recovery-after-a-guardrail-stop)) | `LocalInferenceFailedError`, then a `shutdown` event with `restartInMs`, state `stopped` until the restart | Use your fallback meanwhile |
255
+
256
+ ## 5. Each call, with examples
257
+
258
+ The examples use the website handle. In an extension, the same calls are
259
+ `ZeroGpuBackground.getZeroGpuEligibleModels()`, `switchZeroGpuModel(id)`, `runZeroGpuLocal(input)`,
260
+ `clearZeroGpuModelChoice()`, `forgetZeroGpuUnfitModel(id)` and `getZeroGpuContribution()`.
261
+
262
+ ### `eligibleModels()`: which models this device may hold
263
+
264
+ Asks ZeroGPU to judge every model of this surface's list for this device, with the same rules it
265
+ uses at register time, then adds what only the device knows (downloaded, active). It downloads
266
+ nothing and works in any state, but it needs a network connection. The answer is a snapshot
267
+ (battery and connection change), so ask again before you show it.
268
+
269
+ ```ts
270
+ const models = await sdk.eligibleModels();
271
+ for (const m of models) {
272
+ const size = m.sizeBytes ? `${Math.round(m.sizeBytes / 1e6)} MB` : 'size unknown';
273
+ const status = m.active ? 'in use'
274
+ : !m.eligible ? `not available: ${m.reason}` // model_too_large_for_memory, low_battery, device_unfit, …
275
+ : m.downloaded ? 'ready to switch'
276
+ : `needs a ${size} download`;
277
+ console.log(`${m.displayName ?? m.modelId} (${m.inferenceKind}): ${status}`);
278
+ }
279
+ ```
280
+
281
+ Each line (`EligibleModel`) has:
282
+
283
+ | Field | Meaning |
284
+ |---|---|
285
+ | `modelId`, `modelVersion`, `displayName`, `taskType` | Which model |
286
+ | `inferenceKind` | What `runLocal` input must look like ([section 6](#6-inference-kinds-with-examples)) |
287
+ | `inferenceFramework` | `onnx` or `gguf` |
288
+ | `sizeBytes` | Download size |
289
+ | `maxTokens` | The model's own input limit (the catalog cap) |
290
+ | `eligible`, `reason`, `rule`, `detail` | Whether this device may hold it, and why not |
291
+ | `downloaded` | Already on the device: switching is a reload, not a download |
292
+ | `active` | The model the device holds right now |
293
+
294
+ Find a model by what it does, not by name:
295
+
296
+ ```ts
297
+ const classifier = models
298
+ .filter((m) => m.eligible && m.inferenceKind === 'zero_shot_classification')
299
+ .sort((a, b) => (a.sizeBytes ?? Infinity) - (b.sizeBytes ?? Infinity))[0];
300
+ ```
301
+
302
+ ### `switchModel(modelId)`: hold a specific model
303
+
304
+ ```ts
305
+ showProgress('Preparing the model. The first time can take a while.');
306
+ try {
307
+ const outcome = await sdk.switchModel('zlm-v1-moderation-edge');
308
+ if (outcome.granted) showMessage(`Ready: ${outcome.activeModelId}`);
309
+ else showMessage(`Refused (${outcome.reason}); the device uses ${outcome.activeModelId}`);
310
+ } catch (error) {
311
+ if (error.code === 'model_not_eligible') showMessage(`Not available here: ${error.reason}`); // not_offered, model_too_large_for_memory, …
312
+ else if (error.code?.startsWith('not_contributing_')) showMessage(`Not contributing (${error.state})`);
313
+ else showMessage(`Switch failed: ${error.code}`); // switch_superseded, network, …
314
+ } finally {
315
+ hideProgress();
316
+ }
317
+ ```
318
+
319
+ `SwitchOutcome` has `requestedModelId`, `activeModelId` (the requested model, or the default when
320
+ refused), `granted` and `reason`.
321
+
322
+ ### `runLocal(input)`: run the active model
323
+
324
+ ```ts
325
+ const MODERATION = 'zlm-v1-moderation-edge';
326
+
327
+ /** True when the message should be blocked. */
328
+ async function isUnsafe(message: string): Promise<boolean> {
329
+ if (sdk.activeModelId !== MODERATION) return isUnsafeInCloud(message); // your own fallback
330
+ try {
331
+ const result = await sdk.runLocal({ text: message, top_k: 14 });
332
+ const unsafe = (result.response as Record<string, number>).unsafe ?? 0;
333
+ return unsafe >= 0.5;
334
+ } catch {
335
+ return isUnsafeInCloud(message); // not contributing, degraded, or the model failed
336
+ }
337
+ }
338
+ ```
339
+
340
+ `LocalInferenceResult` has:
341
+
342
+ | Field | Meaning |
343
+ |---|---|
344
+ | `response` | The model's output ([section 6](#6-inference-kinds-with-examples)). Same shape as a network task result for the same model. |
345
+ | `modelId`, `modelVersion` | The model that ran |
346
+ | `location` | Always `"device"` |
347
+ | `runtime` | `onnx` or `gguf` |
348
+ | `queueWaitMs` | Time spent waiting for a network task to finish |
349
+ | `processingMs` | Time the model took |
350
+
351
+ ### `contributionState`, `activeModelId` and `deviceId`: can I call now?
352
+
353
+ ```ts
354
+ const onDevice = sdk.contributionState === 'contributing' && sdk.activeModelId === MODERATION;
355
+ statusLabel.textContent = onDevice ? 'Checked on this device' : 'Checked in the cloud';
356
+ ```
357
+
358
+ | State | Meaning | `runLocal` |
359
+ |---|---|---|
360
+ | `stopped` | Not started, stopped by `shutdown()`, or parked after a guardrail stop | throws |
361
+ | `registering` | Registering with ZeroGPU, or waiting to retry | throws |
362
+ | `declined` | ZeroGPU declined this device for now | throws (with `registryReason`) |
363
+ | `preparing` | Downloading, loading or warming up the model, or waiting for the session ack | throws |
364
+ | `switching` | A switch is in progress | throws |
365
+ | `degraded` | Low memory, paused | throws |
366
+ | `contributing` | Ready | runs |
367
+
368
+ `sdk.deviceId` is this device's id at the registry (null before the SDK registered), what support
369
+ and the dashboards show for it. None of the three is a stream: read them when you need them, or use
370
+ the events.
371
+
372
+ ### `clearModelChoice()` and `forgetUnfitModel(modelId)`
373
+
374
+ ```ts
375
+ sdk.clearModelChoice(); // the next register takes ZeroGPU's default model
376
+ sdk.forgetUnfitModel('zlm-v1-signal-extract'); // let a model that failed its warm-up here be tried again
377
+ ```
378
+
379
+ Neither changes the model the device holds right now; both apply at the next register (the next
380
+ switch, reload or restart). An unfit mark also expires on its own after 24 hours (0.5.1): a slow
381
+ warm-up or a failed download is a verdict on the device as it was, and the model gets another try
382
+ the next day. A model the SDK refuses before loading (on its crash blocklist, not enough memory or
383
+ storage right now, low battery) is never marked unfit — the SDK reports the block, keeps the files
384
+ and retries on the registry's schedule.
385
+
386
+ ### Events
387
+
388
+ | Event | When |
389
+ |---|---|
390
+ | `activeModelChanged` `{ modelId }` | **New.** A model is ready: after the first register and after every switch. Not repeated on reconnects that keep the same model. |
391
+ | `modelChoiceRefused` `{ modelId, reason }` | **New.** Your remembered choice was not kept (refused by ZeroGPU, or `warmup_failed:<reason>`). The choice is cleared and the device holds the default model. |
392
+ | `degraded` / `recovered` | Low memory pauses work / work resumes |
393
+ | `shutdown` `{ code, restartInMs? }` | The SDK stopped: for good after `shutdown()`, or until `restartInMs` after a guardrail stop ([section 8](#8-recovery-after-a-guardrail-stop)) |
394
+
395
+ ## 6. Inference kinds, with examples
396
+
397
+ `runLocal` takes the same input a network task uses for the model, chosen by the model's
398
+ `inferenceKind`. The outputs below are from the e2e runs of 0.5.0 on dev (headless Chromium, the
399
+ SDK's inference worker, single-threaded wasm).
400
+
401
+ ### `zero_shot_classification`: your own labels, no training
402
+
403
+ Production model: `deberta-v3-small`. The labels go in `categories`; scores across them add up to 1.
404
+
405
+ ```ts
406
+ const result = await sdk.runLocal({
407
+ text: 'The central bank raised interest rates by a quarter point to curb inflation.',
408
+ categories: ['Economy', 'Sports', 'Cooking', 'Travel']
409
+ });
410
+ // result.response: { Economy: 0.50, Travel: 0.26, Sports: 0.13, Cooking: 0.10 }
411
+ ```
412
+
413
+ ### `sequence_classification`: the model's own labels
414
+
415
+ Multi-label models (all three production models) give each label its own score from 0 to 1,
416
+ highest first, as `{label: score}`; `top_k` sets how many come back (default 50). Single-label
417
+ models give `{label, score, scores}`.
418
+
419
+ ```ts
420
+ // IAB content and audience categories
421
+ await sdk.runLocal({ text: 'How to train for your first half marathon in twelve weeks.', top_k: 5 });
422
+ // { "content|Sports": 0.90, "content|Running and Jogging": 0.81, "audience|Sports": 0.77, … }
423
+
424
+ // Moderation: `unsafe` is the overall verdict, the other 13 labels are categories
425
+ await sdk.runLocal({ text: 'I will find where you live and make you regret ever talking to me.', top_k: 14 });
426
+ // { unsafe: 0.999, "harassment/threatening": 0.99, harassment: 0.99, illicit: 0.18, … }
427
+
428
+ // Website categories: the input is "<host> | <words> | tld:<tld>" built from a URL
429
+ await sdk.runLocal({ text: 'indeed.com | job search jobs careers hiring employment | tld:com', top_k: 5 });
430
+ // { "content|Job Search": 0.99, "content|Careers": 0.95, "audience|Career Advice": 0.94, … }
431
+ ```
432
+
433
+ The scores are raw; the ZeroGPU cloud applies tuned thresholds per category to the same scores.
434
+ 0.5 is a reasonable starting point for your own.
435
+
436
+ ### `seq2seq_generation`: text in, text out
437
+
438
+ Input `{text, maxNewTokens?}`; output `{text, score}` (`score` = the model's confidence in what it
439
+ generated). The text goes to the model as is, so add any instruction the model expects. For
440
+ `zlm-v1-signal-extract` the cloud puts `extract keywords and user intent: ` in front of the text;
441
+ do the same to get the same results. The answer is `<keywords> [SEP] <intent> [SEP] <category>`.
442
+
443
+ ```ts
444
+ const r = await sdk.runLocal({ text: 'extract keywords and user intent: Best budget smartphones on sale this week: compare prices and battery life.' });
445
+ const [keywords, intent, category] = (r.response as { text: string }).text.split('[SEP]').map((s) => s.trim());
446
+ ```
447
+
448
+ ### `token_classification`: find names, places, organizations
449
+
450
+ Input `{text}`; output `{entities: [{label, text, start, end, score}], tokens: [{token, label, score}]}`.
451
+ `start`/`end` are character positions in your text (`-1` when a span could not be located).
452
+
453
+ ```ts
454
+ await sdk.runLocal({ text: 'My name is Wolfgang and I live in Berlin.' });
455
+ // { entities: [ { label: 'PER', text: 'Wolfgang', start: 11, end: 19, score: 0.998 }, { label: 'LOC', text: 'Berlin', … } ], tokens: [ … ] }
456
+ ```
457
+
458
+ ### `question_answering`: find the answer in a text
459
+
460
+ Input `{question, context}` (`text` works as the context too); output `{answer, score, start, end}`.
461
+
462
+ ```ts
463
+ await sdk.runLocal({ question: 'When was the Eiffel Tower completed?', context: 'The Eiffel Tower was completed in 1889 and stands 330 metres tall.' });
464
+ // { answer: '1889', score: 0.97, start: 34, end: 38 }
465
+ ```
466
+
467
+ ### `text_embedding`: a vector for search and similarity
468
+
469
+ Input `{text}`; output `{embedding: [...]}` (384 numbers for `all-minilm-l6-v2-edge`), mean-pooled
470
+ and unit length, so the similarity of two texts is their dot product.
471
+
472
+ ### `fill_mask`: guess the missing word
473
+
474
+ Put `[MASK]` (or `<mask>`) where the word is missing; `top_k` sets how many guesses come back
475
+ (default 5). Output `{predictions: [{token, tokenId, score}], text}`.
476
+
477
+ ```ts
478
+ await sdk.runLocal({ text: 'The capital of France is [MASK].', top_k: 5 });
479
+ // { predictions: [ { token: 'paris', tokenId: 3000, score: 0.33 }, … ], text: 'the capital of france is paris.' }
480
+ ```
481
+
482
+ ### `decoder_generation` (GGUF): small chat models
483
+
484
+ Input `{text, maxNewTokens?}`; output `{text}`. Send the full prompt **with the model's chat
485
+ template**; the SDK doesn't add one. Without `maxNewTokens` the answer stops at 128 tokens or at
486
+ the model's end token. These run through wllama (llama.cpp in wasm); in a page that is not
487
+ cross-origin isolated they are single-threaded and slow, so keep prompts and answers short.
488
+
489
+ ```ts
490
+ await sdk.runLocal({ text: '<|im_start|>user\nWhat is the capital of France? Answer in one sentence.<|im_end|>\n<|im_start|>assistant\n', maxNewTokens: 32 });
491
+ // { text: 'The capital of France is Paris.' }
492
+ ```
493
+
494
+ ## 7. Errors
495
+
496
+ Every error of the new calls carries a `code` you can branch on. On a website they are instances
497
+ of the exported classes; across the extension message boundary the background helpers rebuild the
498
+ same classes.
499
+
500
+ | Class | `code` | When |
501
+ |---|---|---|
502
+ | `NotContributingError` | `not_contributing_<state>`, e.g. `not_contributing_stopped` | `runLocal` outside `contributing`; `switchModel` when the device cannot contribute now. Has `state` and, when declined, `registryReason`. |
503
+ | `ModelNotEligibleError` | `model_not_eligible` | `switchModel` on a model that isn't on the list (`reason = "not_offered"`) or isn't eligible (`reason` says why). Nothing changes. |
504
+ | `LocalInferenceFailedError` | `inference_failed` | The model failed on your input |
505
+ | `ZeroGpuError` | `input_too_large` | The text exceeds the model's catalog cap (`maxTokens`); nothing ran |
506
+ | `ZeroGpuError` | `switch_superseded` | A newer `switchModel` call replaced this one |
507
+ | `ZeroGpuError` | `timeout`, `network`, `http_<status>` | `eligibleModels` (or `switchModel`, which calls it) could not reach ZeroGPU |
508
+
509
+ ## 8. Recovery after a guardrail stop
510
+
511
+ Before 0.5.0 a guardrail shutdown (memory pressure, or an allocation failure such as the
512
+ `RangeError: offset is out of bounds` a laptop could wake from sleep into) was terminal for the
513
+ page: the SDK closed the session with code 4002 and refused to start again until the page was
514
+ reloaded or the extension restarted. On 2026-10-28, 53 of 69 production devices with such a close
515
+ never came back.
516
+
517
+ Since 0.5.0 a guardrail stop frees the runtime (the inference worker goes with its last model, so
518
+ the next start gets a fresh wasm heap), closes the session the same way, tells the host
519
+ (`shutdown` with `restartInMs`), and registers again on its own: after 1 minute the first time,
520
+ then 5, then 15, then every 30 minutes while it keeps failing; a healthy half hour resets the
521
+ ladder. `shutdown()` called by the host stays terminal.
522
+
523
+ Two smaller changes support this: a download or load that failed and was handled no longer
524
+ survives as a crash marker (it used to count as a crash and could blocklist the model for a day
525
+ after two failures), and the final `guardrail.shutdown` / `sdk.shutdown` telemetry events get past
526
+ the per-session event cap, so the registry audit always carries the reason a device went away.
527
+
528
+ ## 9. Limits and tips
529
+
530
+ - **No fleet limits on local calls.** The per-model input cap and the dispatch time budget the
531
+ network applies do not apply to your call; only the model's own catalog cap (`maxTokens` on the
532
+ eligible line) does, as a typed error before anything runs.
533
+ - **Keep a fallback.** Local calls fail whenever the device isn't contributing (declined, switching,
534
+ low memory, a guardrail restart). Plan for your server path or for skipping the feature.
535
+ - **Check the active model before each call.** The device can be moved back to the default model (a
536
+ refused choice, a failed warm-up), and `runLocal` runs whatever is active.
537
+ - **Don't switch per request.** Switch once when the feature starts, then call `runLocal` as often
538
+ as you like.
539
+ - **Don't hard-code the model list.** Use `eligibleModels()` and pick by `inferenceKind`.
540
+ - **Telegram mini apps** get the same API (same bundle), but their list is small and memory tight;
541
+ expect `declined` or `model_too_large_for_memory` more often there.
@@ -447,6 +447,37 @@ Values sent this way last as long as the offscreen document. Chrome may tear
447
447
  it down and recreate it (after an opt-out and back in, or a browser restart),
448
448
  so anything that should survive that belongs in `initZeroGpuOffscreen` too.
449
449
 
450
+ ### Use the model in your extension (0.5.0)
451
+
452
+ The model the user's browser holds for the ZeroGPU network can also answer
453
+ requests from your extension, on the device, and you may choose which eligible
454
+ model that is. The SDK runs in the offscreen document; your service worker,
455
+ popup or options page reaches it through the background bundle:
456
+
457
+ ```js
458
+ const { contributionState, activeModelId } = await ZeroGpuBackground.getZeroGpuContribution();
459
+ const models = await ZeroGpuBackground.getZeroGpuEligibleModels(); // judged for this device, never downloads
460
+ const outcome = await ZeroGpuBackground.switchZeroGpuModel("zlm-v1-moderation-edge");
461
+ if (outcome.granted) {
462
+ const result = await ZeroGpuBackground.runZeroGpuLocal({ text: "some text", top_k: 14 });
463
+ result.response; // { unsafe: 0.02, … } — ran on this device
464
+ }
465
+ await ZeroGpuBackground.clearZeroGpuModelChoice();
466
+ await ZeroGpuBackground.forgetZeroGpuUnfitModel("some-model");
467
+ ZeroGpuBackground.onZeroGpuEvent(({ event, detail }) => {
468
+ // activeModelChanged, modelChoiceRefused, degraded, recovered, shutdown
469
+ });
470
+ ```
471
+
472
+ Each helper makes sure the offscreen document exists (never for a user who
473
+ opted out), sends one `chrome.runtime` message (`zerogpu:eligibleModels`,
474
+ `zerogpu:switchModel`, `zerogpu:runLocal`, …) and resolves with the typed
475
+ answer; errors come back as the same classes a website gets
476
+ (`NotContributingError`, `ModelNotEligibleError`, …, each with a `code`).
477
+ Local calls work only while `contributionState` is `contributing`. The
478
+ full guide — flows, every inference kind's input and output, errors — is
479
+ [app-side-inference.md](app-side-inference.md).
480
+
450
481
  ---
451
482
 
452
483
  ## Troubleshooting
@@ -22,7 +22,7 @@ The ZeroGPU model registry contains models across **three different inference fr
22
22
 
23
23
  | Framework | What runs on it | Task types | Example models |
24
24
  |---|---|---|---|
25
- | **ONNX** | Standard ML models compiled to ONNX | classification, summary, iab_classify, text_generation — or any taskType whose recipe carries a supported `inferenceKind` | deberta-v3-small, t5-small, zlm-v1-iab-classify-edge, zlm-v1-moderation-edge, zlm-v1-signal-extract |
25
+ | **ONNX** | Standard ML models compiled to ONNX | classification, summary, iab_classify, text_generation — or any taskType whose recipe carries a supported `inferenceKind`: `sequence_classification`, `seq2seq_generation`, `zero_shot_classification`, `token_classification`, `question_answering`, `text_embedding`, `fill_mask` | deberta-v3-small, t5-small, zlm-v1-iab-classify-edge, zlm-v1-moderation-edge, zlm-v1-signal-extract, bert-base-ner-edge, distilbert-squad-edge, all-minilm-l6-v2-edge, bert-base-uncased-fillmask-edge |
26
26
  | **Transformers** | HuggingFace token-classification models | gliner | gliner-multi-pii-v1, gliner2-base-v1 |
27
27
  | **GGUF** | Quantized small language models | text_generation | LFM2.5-1.2B-Instruct, llama-3.1-8b-instruct-fast |
28
28
 
@@ -199,6 +199,10 @@ Today the orchestrator probably echoes the legacy three task types. To unlock ne
199
199
  | `seq2seq_generation` | ONNX | `text2text-generation` (encoder + merged decoder), greedy; input used verbatim | `{ "text": "…", "score": 0.94 }`; `max_new_tokens` from `generation_config.json` (default 48, `maxNewTokens` overrides). `score` = exp(mean log p) of the greedily chosen tokens (EOS step excluded, 0.5 when nothing was generated), raw — clamp/round server-side |
200
200
  | `zero_shot_classification` | ONNX | zero-shot pipeline over `categories` | `{ "<category>": score, … }` |
201
201
  | `decoder_generation` | GGUF | wllama chat generation | `{ "text": "…" }` |
202
+ | `token_classification` | ONNX | `token-classification` pipeline, every token; word pieces merged into BIO spans with character offsets found in the input | `{ "entities": [{ "label", "text", "start", "end", "score" }], "tokens": [{ "token", "label", "score" }] }` |
203
+ | `question_answering` | ONNX | `question-answering` pipeline over `{ question, context }` (`text` doubles as the context) | `{ "answer", "score", "start", "end" }` — character offsets in the context |
204
+ | `text_embedding` | ONNX | `feature-extraction` pipeline, mean pooling, L2-normalized | `{ "embedding": [ … ] }` |
205
+ | `fill_mask` | ONNX | `fill-mask` pipeline; `[MASK]` / `<mask>` rewritten to the tokenizer's mask token; `top_k` predictions (default 5) | `{ "predictions": [{ "token", "tokenId", "score" }], "text" }` |
202
206
 
203
207
  ### 2. Orchestrator: send richer `sample` objects
204
208
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerogpu/browser-extension-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "ZeroGPU device-side SLM runtime SDK for browsers and Chrome (MV3) extensions",
5
5
  "type": "module",
6
6
  "main": "dist/zerogpu-browser-sdk.cjs",
@@ -87,6 +87,7 @@
87
87
  "eslint-import-resolver-typescript": "^3.6.1",
88
88
  "eslint-plugin-import": "^2.29.0",
89
89
  "happy-dom": "^15.11.7",
90
+ "playwright": "1.61.1",
90
91
  "prettier": "^3.1.1",
91
92
  "rimraf": "^5.0.5",
92
93
  "rollup": "^4.5.2",