@zerogpu/browser-extension-sdk 0.4.0 → 0.5.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 +75 -0
- package/bin/zerogpu.mjs +6 -0
- package/dist/assets/zerogpu-assets.json +2 -2
- package/dist/assets/zerogpu-worker.js +1 -1
- package/dist/extension/zerogpu-background.js +1 -1
- package/dist/extension/zerogpu-offscreen.js +1 -1
- package/dist/loader.js +1 -1
- package/dist/manifest.json +5 -5
- package/dist/types/adapters/kinds.d.ts +8 -0
- package/dist/types/adapters/onnx/executor.d.ts +26 -1
- package/dist/types/adapters/onnx/runtime.d.ts +10 -4
- package/dist/types/adapters/types.d.ts +15 -1
- package/dist/types/appinference/eligible.d.ts +12 -0
- package/dist/types/appinference/store.d.ts +42 -0
- package/dist/types/appinference/types.d.ts +118 -0
- package/dist/types/config/types.d.ts +1 -0
- package/dist/types/device/telemetry.d.ts +6 -0
- package/dist/types/extension/background.d.ts +36 -0
- package/dist/types/extension/offscreen.d.ts +25 -3
- package/dist/types/loader.d.ts +1 -0
- package/dist/types/public-api.d.ts +41 -7
- package/dist/types/runtime/app-identity.d.ts +24 -0
- package/dist/types/runtime/app-inference.d.ts +60 -0
- package/dist/types/runtime/guardrails.d.ts +10 -0
- package/dist/types/runtime/host-api.d.ts +13 -1
- package/dist/types/runtime/init-guard.d.ts +7 -0
- package/dist/types/runtime/lifecycle-options.d.ts +12 -0
- package/dist/types/runtime/lifecycle.d.ts +21 -8
- package/dist/types/runtime/restart.d.ts +11 -0
- package/dist/types/runtime/router.d.ts +13 -0
- package/dist/types/runtime/sdk-state.d.ts +24 -0
- package/dist/types/runtime/shutdown.d.ts +21 -3
- package/dist/types/storage/cached-model.d.ts +31 -2
- package/dist/types/telemetry/event-reporter.d.ts +1 -0
- package/dist/types/transport/http.d.ts +67 -0
- package/dist/v/zerogpu-browser-sdk.5f140942519b.umd.js +1 -0
- package/dist/zerogpu-browser-sdk.cjs +1 -1
- package/dist/zerogpu-browser-sdk.esm.js +1 -1
- package/dist/zerogpu-browser-sdk.umd.js +1 -1
- package/dist/zerogpu-worker.js +1 -1
- package/docs/APP_INFERENCE_E2E_2026-11-06_DEV.md +855 -0
- package/docs/app-side-inference.md +537 -0
- package/docs/extension-developer-guide.md +31 -0
- package/docs/multi-model-support.md +5 -1
- package/package.json +2 -1
- package/dist/v/zerogpu-browser-sdk.87efe0d8c5ba.umd.js +0 -1
package/README.md
CHANGED
|
@@ -41,6 +41,24 @@ The build produces:
|
|
|
41
41
|
npm run test
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
+
## End-to-end (live environment)
|
|
45
|
+
|
|
46
|
+
`sdk/e2e/` drives this checkout's built bundle in headless Chromium (Playwright) against a
|
|
47
|
+
live ZeroGPU environment — the app-side inference flows, the warm-up gate, the cache cap, a
|
|
48
|
+
network drop and recovery — and the Chrome-extension path through the fixture under
|
|
49
|
+
`e2e/extension/`. Credentials come from the zerogpu copilot skill's `.env`; nothing is printed.
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npm run build
|
|
53
|
+
node --env-file=<copilot .env> e2e/run.mjs # all scenarios, or name some: install default-register eligible …
|
|
54
|
+
node --env-file=<copilot .env> e2e/run-extension.mjs # the chrome-extension surface
|
|
55
|
+
node e2e/report.mjs e2e/results/<run>.json > docs/APP_INFERENCE_E2E_<date>.md
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`ZG_ENV=dev|staging|prod` picks the environment (default dev); `ZG_CATALOG_SCRIPT` points at
|
|
59
|
+
the device-registry dev catalog script for the scenarios that change a list entry behind the
|
|
60
|
+
SDK's back. Results land in `e2e/results/` (the `.json` is committed, logs are not).
|
|
61
|
+
|
|
44
62
|
## Lint
|
|
45
63
|
|
|
46
64
|
```bash
|
|
@@ -129,6 +147,39 @@ receive an untagged branch build. Development builds live on the separate
|
|
|
129
147
|
the `dev`/`main` branches) — point a test page at those to try unreleased
|
|
130
148
|
builds.
|
|
131
149
|
|
|
150
|
+
## App-side inference (0.5.0)
|
|
151
|
+
|
|
152
|
+
The model this device holds for the ZeroGPU network can also serve your own page, and you may
|
|
153
|
+
choose which eligible model that is. The handle `initZeroGpuSdk` returns (or
|
|
154
|
+
`getZeroGpuSdk()`, for pages the script tag started) carries:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
const sdk = await initZeroGpuSdk({ edgeOperatorKey: 'your-edge-operator-key' });
|
|
158
|
+
|
|
159
|
+
sdk.contributionState; // 'stopped' | 'registering' | 'declined' | 'preparing' | 'switching' | 'degraded' | 'contributing'
|
|
160
|
+
sdk.activeModelId; // the model the device holds right now, or null
|
|
161
|
+
const models = await sdk.eligibleModels(); // every model of this surface's list, judged for this device (never downloads)
|
|
162
|
+
const outcome = await sdk.switchModel(models.find((m) => m.eligible && m.inferenceKind === 'zero_shot_classification').modelId);
|
|
163
|
+
if (outcome.granted) {
|
|
164
|
+
const result = await sdk.runLocal({ text: 'Rates rose again.', categories: ['Economy', 'Sports'] });
|
|
165
|
+
result.response; // { Economy: 0.9, Sports: 0.1 } — ran on this device
|
|
166
|
+
}
|
|
167
|
+
sdk.clearModelChoice(); // back to the default assignment on the next register
|
|
168
|
+
sdk.forgetUnfitModel('some-model'); // let a model that failed its warm-up here be tried again
|
|
169
|
+
sdk.on('activeModelChanged', ({ modelId }) => {});
|
|
170
|
+
sdk.on('modelChoiceRefused', ({ modelId, reason }) => {});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Local calls work only while `contributionState` is `contributing`; outside it they throw a
|
|
174
|
+
`NotContributingError` with the state. Every error carries a `code`
|
|
175
|
+
(`not_contributing_<state>`, `model_not_eligible`, `inference_failed`, `input_too_large`, …).
|
|
176
|
+
The full guide, with the input and output of every inference kind, the flows and the
|
|
177
|
+
Chrome-extension helpers, is [docs/app-side-inference.md](docs/app-side-inference.md).
|
|
178
|
+
|
|
179
|
+
Also since 0.5.0: a guardrail shutdown (memory pressure, an allocation failure) is no longer
|
|
180
|
+
terminal for the page — the SDK frees its runtime and registers again on a bounded ladder
|
|
181
|
+
(1, 5, 15, then every 30 minutes); `shutdown()` stays terminal. See the guide's section 8.
|
|
182
|
+
|
|
132
183
|
## Configuration Options
|
|
133
184
|
|
|
134
185
|
### `InitOptions`
|
|
@@ -137,8 +188,13 @@ builds.
|
|
|
137
188
|
| :--- | :--- | :--- | :--- |
|
|
138
189
|
| `appUserId` | `string` | `undefined` | Optional user identifier (e.g. Telegram ID) for telemetry. |
|
|
139
190
|
| `edgeOperatorKey` | `string` | `undefined` | Operator key forwarded to `/register` as `x-edge-operator-key`. The orchestrator resolves the project from this key. |
|
|
191
|
+
| `deviceId` | `string` | `undefined` | Supply your own stable device id; otherwise the SDK generates and persists one. |
|
|
192
|
+
| `resourcePolicy` | `ResourcePolicy` | `{}` | Host hints for the guardrails: `maxModelBytes`, `memoryBudgetFraction`, `maxCachedModels` (most models kept in the download cache, default 3 from the registry, 0 = no cap). `disableGuardrails` is for lab use only. |
|
|
140
193
|
| `overrides` | `Partial<SdkConfig>` | `{}` | Deep merge overrides for internal config. |
|
|
141
194
|
| `customParams` | `{ cust_param1?, cust_param2?, cust_param3? }` | `undefined` | Operator macros attached to every request this device serves. See [Custom macros](#custom-macros-cust_param13). |
|
|
195
|
+
| `appId` | `string` | `undefined` | Your app's ZeroGPU app ID, from the ZeroGPU dashboard. See [App identity](#app-identity). |
|
|
196
|
+
| `appName` | `string` | `undefined` | Your app's display name. |
|
|
197
|
+
| `externalAppId` | `string` | extension ID in a Chrome extension | Your app's native platform ID (e.g. a Telegram bot username). |
|
|
142
198
|
|
|
143
199
|
### Off-main-thread inference (`overrides.inference`)
|
|
144
200
|
|
|
@@ -164,6 +220,25 @@ await initZeroGpuSdk({
|
|
|
164
220
|
});
|
|
165
221
|
```
|
|
166
222
|
|
|
223
|
+
### App identity
|
|
224
|
+
|
|
225
|
+
Attributes the inference your devices serve to your app. Pass the app ID and
|
|
226
|
+
name shown for the app in the ZeroGPU dashboard. Inside a Chrome extension the
|
|
227
|
+
SDK sends the extension ID (`chrome.runtime.id`) as `externalAppId` on its own;
|
|
228
|
+
a Telegram Mini App can pass its bot username. Everything is optional: leaving
|
|
229
|
+
it unset never affects registration or inference.
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
await initZeroGpuSdk({
|
|
233
|
+
edgeOperatorKey: 'your-edge-operator-key',
|
|
234
|
+
appId: 'your-zerogpu-app-id',
|
|
235
|
+
appName: 'Study AI'
|
|
236
|
+
});
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Script tag: `data-app-id`, `data-app-name`, `data-external-app-id`. Extension
|
|
240
|
+
offscreen documents take the same `appId` / `appName` / `externalAppId` options.
|
|
241
|
+
|
|
167
242
|
### Custom macros (`cust_param1..3`)
|
|
168
243
|
|
|
169
244
|
Three opaque slots for your own reporting dimensions — placement, cohort,
|
package/bin/zerogpu.mjs
CHANGED
|
@@ -259,6 +259,12 @@ ZeroGpuBackground.registerZeroGpuConsentBridge({
|
|
|
259
259
|
// await ZeroGpuBackground.getZeroGpuConsent() -> { optedIn, updatedAt, source }
|
|
260
260
|
// await ZeroGpuBackground.setZeroGpuConsent(false) -> stops the SDK now
|
|
261
261
|
// ZeroGpuBackground.buildZeroGpuSettingsUrl({ extensionId: chrome.runtime.id })
|
|
262
|
+
//
|
|
263
|
+
// Use the model the device holds in your own extension (app-side inference, 0.5.0):
|
|
264
|
+
// await ZeroGpuBackground.getZeroGpuEligibleModels() -> every model of the list, judged for this device
|
|
265
|
+
// await ZeroGpuBackground.switchZeroGpuModel(modelId) -> { granted, activeModelId, reason? }
|
|
266
|
+
// await ZeroGpuBackground.runZeroGpuLocal({ text }) -> { response, modelId, location: "device", … }
|
|
267
|
+
// ZeroGpuBackground.onZeroGpuEvent(({ event, detail }) => {})
|
|
262
268
|
`;
|
|
263
269
|
|
|
264
270
|
const OPTIONS_HTML = `<!DOCTYPE html>
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"sdkVersion": "0.
|
|
2
|
+
"sdkVersion": "0.5.0+36fc495",
|
|
3
3
|
"channel": "official",
|
|
4
4
|
"transformersVersion": "2.17.2",
|
|
5
5
|
"wllamaVersion": "2.3.5",
|
|
@@ -17,5 +17,5 @@
|
|
|
17
17
|
"wllama/single-thread/wllama.wasm",
|
|
18
18
|
"wllama/multi-thread/wllama.wasm"
|
|
19
19
|
],
|
|
20
|
-
"builtAt": "2026-
|
|
20
|
+
"builtAt": "2026-11-10T14:39:58.034Z"
|
|
21
21
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={onnx:2,transformersjs:2.5,transformers:2.5,gguf:1.4},r=.7,t=.85,n=.95,o=1e4,s=.6,a=6e4;let i={},c=function(c){const u={},f=Object.fromEntries(Object.entries({}).filter(([,e])=>void 0!==l(e)));return{memoryBudgetFraction:l(i.memoryBudgetFraction)??l(c?.memoryBudgetFraction)??.3,frameworkMultipliers:{...e,...f},minBatteryLevel:l(c?.minBatteryLevel)??.2,storageHeadroom:l(c?.storageHeadroom)??1.2,unknownMemoryGb:l(c?.unknownMemoryGb)??2,watchdog:{warnPct:l(u.warnPct)??r,degradePct:l(u.degradePct)??t,shutdownPct:l(u.shutdownPct)??n,sampleMs:l(u.sampleMs)??o,recoverPct:l(u.recoverPct)??s,recoverHoldMs:l(u.recoverHoldMs)??a},maxMemoryBudgetMb:l(c?.maxMemoryBudgetMb)??0,maxInputTokens:l(c?.maxInputTokens)??0,sampleLatencyBudgetMs:l(c?.sampleLatencyBudgetMs)??0,wasm:{maxThreads:l(c?.wasm?.maxThreads)??4,proxyWorker:!0===c?.wasm?.proxyWorker}}}(null);function l(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}const u=(e=(()=>({isolated:"boolean"==typeof globalThis.crossOriginIsolated&&globalThis.crossOriginIsolated&&"function"==typeof globalThis.SharedArrayBuffer,cores:"undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:1,workerAvailable:"function"==typeof globalThis.Worker,inDocument:"undefined"!=typeof document}))(),r=c.wasm)=>{const t=Number.isFinite(e.cores)&&e.cores>0?Math.floor(e.cores):1;return{numThreads:e.isolated?Math.max(1,Math.min(t-1,r.maxThreads)):1,proxy:r.proxyWorker&&e.workerAvailable&&!1!==e.inDocument}},f="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";let m={...{transformersUrl:f}};const d=()=>m,p=200,g=/(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i,h=new Set(["url","wsurl","baseurl","modelurl","modelrepourl","runtimeurl","requesturl","endpoint","endpointurl","manifesturl","bundleurl","orchestrator"]),w=new Set(["message","errormessage","error","reason"]),y=new Set(["requestid","modelid","modelversion","modelrepoid","modeltype","deviceid","sdkversion","tasktype","framework","inferenceframework","quantization","code","status","type","phase","flow","event","source","name","platform","devicetype","gpurenderer","mime","mode","file","files","requiredfiles","models","cachedmodels","keys","changed","cachedmodelid","assignedmodelid","primarymodelid"]),b=(e,r)=>e.length>r?`${e.slice(0,r)}…`:e,x=e=>{if(e instanceof Error)return b(`${e.name}: ${e.message}`,p);if("string"==typeof e)return b(e,p);if(null==e)return String(e);if("object"==typeof e&&"string"==typeof e.name&&"string"==typeof e.message){const{name:r,message:t}=e;return b(`${r}: ${t}`,p)}return"object"==typeof e?`[${e.constructor?.name??"object"}]`:b(String(e),p)},k=e=>Array.isArray(e)?`[array:${e.length}]`:e&&"object"==typeof e?`[object:${Object.keys(e).length} keys]`:`[${typeof e}]`,_=(e,r)=>{const t=e.toLowerCase();return h.has(t)?(e=>{try{const r=new URL(e);return`${r.origin}${r.pathname}`}catch{return"[invalid-url]"}})(r):w.has(t)?b(r,p):y.has(t)?b(r,256):`[string:${r.length}]`},M=(e,r)=>g.test(e)?"[redacted]":null==r||"boolean"==typeof r?r:"number"==typeof r?Number.isFinite(r)?r:String(r):"string"==typeof r?_(e,r):r instanceof Error?x(r):k(r),v=e=>"string"==typeof e?b(e,p):"[invalid log message]";class T{constructor(e,r){this.enabled=e.enableConsoleLogs,this.sink=r}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}emit(e,r,t,n){this.enabled&&(this.sink?this.sink(e,v(t),n):void 0===n?r("[ZeroGPU]",v(t)):r("[ZeroGPU]",v(t),(e=>{if(e instanceof Error)return{error:x(e)};if(!e||"object"!=typeof e||Array.isArray(e))return{detail:M("detail",e)};const r={};for(const[t,n]of Object.entries(e))Array.isArray(n)?g.test(t)?r[t]="[redacted]":n.every(e=>null===e||"object"!=typeof e)?r[t]=n.slice(0,20).map(e=>M(t,e)):r[t]=k(n):r[t]=M(t,n);return r})(n)))}debug(e,r){this.emit("debug",console.debug,e,r)}info(e,r){this.emit("info",console.debug,e,r)}warn(e,r){this.emit("warn",console.warn,e,r)}error(e,r){this.emit("error",console.error,e,r)}}let S=null;const E=()=>(S||(S=new T({enableConsoleLogs:!1,locationData:!1,events:!0})),S),L=async e=>{const r=performance.now();return{result:await e(),ms:Math.round(performance.now()-r)}},A="sequence_classification",$="seq2seq_generation",P="zero_shot_classification",j=()=>globalThis,q=e=>{e&&"undefined"==typeof caches&&(e.useBrowserCache=!1)};let I=null;const U=()=>{const e=j();if(e.TransformersPipeline)return Promise.resolve();if(!I){const r=E(),t=d().transformersUrl;I=(async()=>{try{r.info("[Runtime] Importing Transformers runtime",{runtimeUrl:t});const n=performance.now(),o=await import(t),s=o?.pipeline,a=o?.env;if("function"!=typeof s||!a)throw new Error("Transformers runtime missing pipeline/env exports");r.info("[Runtime] Transformers runtime ready",{ms:Math.round(performance.now()-n)}),a.allowLocalModels=!0,a.allowRemoteModels=!0,q(a),a?.backends?.onnx?.env&&(a.backends.onnx.env.logLevel="warning"),"logLevel"in a&&(a.logLevel="warning"),e.TransformersPipeline=s,e.TransformersEnv=a,e.TransformersLib=(e=>{if(!e||"object"!=typeof e)return;const r=e,{AutoTokenizer:t,PreTrainedModel:n,Tensor:o}=r,s=e=>Boolean(e)&&"function"==typeof e.from_pretrained;return s(t)&&s(n)&&"function"==typeof o?{AutoTokenizer:t,PreTrainedModel:n,Tensor:o}:void 0})(o)}catch(e){throw I=null,r.error("[SLM] Failed to import Transformers runtime",{runtimeUrl:t,error:x(e)}),e}})()}return I},R=e=>e.replace(/\/$/,""),B=e=>/^https?:\/\//i.test(e.trim()),z=e=>{const r=(e=>{const r=e.trim();if(!r)return"";if(B(r))try{return new URL(r).pathname.replace(/^\/+|\/+$/g,"")}catch{return""}return r.replace(/^\/+|\/+$/g,"")})(e);return r?R(`https://huggingface.co/${r}/resolve/main`):""},N=(e,r)=>{const t=(e||"").trim();if(B(t))return R(t);const n=z(r||t);return n||R(t)},C=e=>e.replace(/^\/+/,"").replace(/^resolve\/main\//,"").split("?")[0],O=(e,r)=>`${e}/${C(r)}`,F=()=>{const e=d().pageOrigin??("undefined"!=typeof location&&location?location.origin:void 0);if(!e||"null"===e)return null;try{return new URL("/onnx-wasm/",e).toString()}catch{return null}},W=[0,97,115,109],H=["ort-wasm-simd-threaded.wasm","ort-wasm-simd.wasm","ort-wasm-threaded.wasm","ort-wasm.wasm"],D=e=>e.endsWith("/")?e:`${e}/`,G=()=>{try{const e=new URL(f),r=e.pathname,t=r.lastIndexOf("/"),n=t>=0?r.slice(0,t+1):"/";return`${e.origin}${n}`}catch{return"https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/"}},Z=e=>e.length>=W.length&&W.every((r,t)=>e[t]===r);let J=null;const K=e=>(J||(J=(async e=>{const r=[d().wasmPaths,F(),G(),"https://unpkg.com/@xenova/transformers@2.17.2/dist/"].filter(e=>"string"==typeof e&&e.length>0).map(D).filter((e,r,t)=>t.indexOf(e)===r);for(const t of r){let r=!1;for(const n of H){const o=(()=>{try{return new URL(n,t).toString()}catch{return`${t}${n}`}})();try{const n=await e(o,{cache:"no-store"});if(!n.ok)continue;const s=new Uint8Array(await n.arrayBuffer());if(Z(s))return t;r=!0;break}catch{}}r&&E().warn("[SLM] ONNX wasm probe got non-wasm payload",{url:t})}return null})(e)),J);let X=Promise.resolve();const Q=async e=>{const r=X;let t=()=>{};X=new Promise(e=>{t=e}),await r;try{return await e()}finally{t()}},V={},Y=(e,r,t,n,o,s)=>{const a=o.map(e=>C(e.trim())).filter(e=>e.length>0),i=new Set(a),c=E(),l=(()=>{try{return new URL(r)}catch{return null}})();return async(o,a)=>{const u="string"==typeof o?o:o instanceof URL?o.toString():o.url,f=(e=>{const r=(()=>{try{return new URL(e).pathname}catch{return e.split("?")[0]||""}})(),t="/resolve/main/",n=r.indexOf(t);if(n>=0){const e=r.slice(n+14);return C(e)}if(!l)return null;const o=l.pathname.replace(/\/$/,"");if(!r.startsWith(`${o}/`))return null;const s=r.slice(o.length+1);return C(s)})(u);if(!f){if(!(/\.wasm(?:\?|$)/i.test(u)||/onnxruntime|ort-wasm/i.test(u)))return s(o,a);try{return await s(o,a)}catch(r){throw c.error("[SLM][fetch] non-model wasm/ort request failed",{modelId:e,requestUrl:u,error:x(r)}),r}}const m=(e=>{const r=C(e);if(!r)return null;if(0===i.size||i.has(r))return r;if(r.startsWith("onnx/")&&r.endsWith(".onnx")&&!r.endsWith("_quantized.onnx")){const e=r.replace(/\.onnx$/,"_quantized.onnx");if(i.has(e))return e}return null})(f);if(!m)return c.warn("[SLM] Unexpected model file request; falling back to original fetch",{file:f,modelId:e}),s(o,a);const d=(e=>{const t=C(e),n=[],o=e=>{n.includes(e)||n.push(e)};try{const e=new URL(r),n=e.toString().endsWith("/")?e.toString():`${e.toString()}/`;r.endsWith("/resolve/main")?o(new URL(t,n).toString()):(o(new URL(t,n).toString()),o(new URL(`resolve/main/${t}`,n).toString()))}catch{r.endsWith("/resolve/main")?o(`${r}/${t}`):(o(`${r}/${t}`),o(`${r}/resolve/main/${t}`))}return n})(m),p=C(m),g=O(e,p);let h=V[g]||t[g]||V[p]||t[p]||t[`onnx/${p}`]||V[`onnx/${p}`];if(!h&&p.startsWith("onnx/")){const r=p.replace("onnx/","");h=t[r]||V[r]||t[O(e,r)]||V[O(e,r)]}if(h)return new Response(h);try{for(const e of d){const r=await s(e,a);if(r.ok){const e=await r.blob();return V[g]=e,n&&n(g,e),new Response(e)}}return new Response("required_file_not_found",{status:404,statusText:"Not Found"})}catch(r){return c.warn("[SLM] Model file fetch failed",{modelId:e,file:m,candidateCount:d.length,error:x(r)}),new Response("model_file_fetch_failed",{status:502,statusText:"Bad Gateway"})}}},ee="zgScoreRecorder",re=e=>({[ee]:e}),te=(e,r,t)=>{let n=-1/0;for(let o=0;o<t;o+=1)n=Math.max(n,e[r+o]);let o=0;for(let s=0;s<t;s+=1)o+=Math.exp(e[r+s]-n);return n+Math.log(o)},ne=e=>{const r=e;if(!r||r.__zgScoreHooks)return Boolean(r?.__zgScoreHooks);const{getStartBeams:t,runBeam:n,updateBeam:o}=r;return"function"==typeof t&&"function"==typeof n&&"function"==typeof o&&(r.getStartBeams=(...e)=>{const n=t.apply(r,e),o=e[1],s=o?.[ee];if(s)for(const e of n)e[ee]=s;return n},r.runBeam=async e=>{const t=await n.call(r,e),o=e[ee];return o&&t?.logits&&((e,r)=>{const{offset:t,size:n}=(e=>{const r=e.dims,t=r[r.length-1];return{offset:((r.length>=2?r[r.length-2]:1)-1)*t,size:t}})(r);e.pending={row:r.data,offset:t,size:n,logSumExp:te(r.data,t,n)}})(o,t.logits),t},r.updateBeam=(e,t)=>{const n=o.call(r,e,t),s=e[ee];return s&&((e,r)=>{const t=e.pending;if(e.pending=void 0,!t||e.sawEos)return;if(e.eosTokenIds.includes(r))return void(e.sawEos=!0);const n=Math.exp(t.row[t.offset+r]-t.logSumExp);e.logProbs.push(Math.log(Math.max(n,1e-9)))})(s,t),n},r.__zgScoreHooks=!0,!0)},oe=e=>{const r=e,t=r?.generation_config?.eos_token_id??r?.config?.eos_token_id;return(Array.isArray(t)?t:[t]).filter(e=>"number"==typeof e)},se=(e,r)=>"sigmoid"===e?(e=>Array.from(e,e=>1/(1+Math.exp(-e))))(r):(e=>{const r=Array.from(e);if(0===r.length)return[];const t=Math.max(...r),n=r.map(e=>Math.exp(e-t)),o=n.reduce((e,r)=>e+r,0);return n.map(e=>e/o)})(r),ae=e=>"number"==typeof e&&Number.isFinite(e)&&e>0&&e<1e6?Math.floor(e):void 0,ie=e=>{const r=new BigInt64Array(e.length);return e.forEach((e,t)=>{r[t]=BigInt(e)}),r},ce=(e,r,t)=>{const n=t.config??{},o=t.session,s="multi_label_classification"===n.problem_type?"sigmoid":"softmax";const a=((e,r)=>{const t=[ae(e.max_position_embeddings),ae(e.n_positions),ae(r.model_max_length)].filter(e=>void 0!==e);return t.length>0?Math.min(...t):512})(n,r),i=r.encode(""),c=i.length>0?i[i.length-1]:void 0,l=o.outputNames.includes("logits")?"logits":o.outputNames[0],u=n.id2label&&"object"==typeof n.id2label?Object.keys(n.id2label).length:0;return{labelCount:u,maxLength:a,activation:s,async classify(t,i){const u=t.slice(0,16*a),f=((e,r,t)=>{if(e.length<=r)return e;const n=e[e.length-1];return void 0!==t&&n===t&&r>=2?[...e.slice(0,r-1),n]:e.slice(0,r)})(r.encode(u),a,c),m=await o.run((r=>{const t=[1,r.length],n={};for(const s of o.inputNames)if("input_ids"===s)n[s]=new e.Tensor("int64",ie(r),t);else if("attention_mask"===s)n[s]=new e.Tensor("int64",ie(r.map(()=>1)),t);else{if("token_type_ids"!==s)throw new Error(`sequence_classification_unsupported_input:${s}`);n[s]=new e.Tensor("int64",ie(r.map(()=>0)),t)}return n})(f)),d=m[l];if(!d||!d.data||0===d.data.length)throw new Error("sequence_classification_empty_logits");const p=se(s,d.data),g=((e,r)=>{const t=e.id2label,n=t&&"object"==typeof t?t:{};return Array.from({length:r},(e,r)=>{const t=n[String(r)];return"string"==typeof t&&t.length>0?t:`LABEL_${r}`})})(n,p.length);return((e,r,t)=>{const n=Math.max(1,Math.min(Math.floor(t),e.length)),o=e.map((e,r)=>({score:e,index:r})).sort((e,r)=>r.score-e.score).slice(0,n),s={};for(const{score:e,index:t}of o)s[r[t]??`LABEL_${t}`]=e;return s})(p,g,"number"==typeof(h=i)&&Number.isFinite(h)&&h>=1?Math.floor(h):50);var h}}},le={summary:"summarization",iab_classify:"text-classification",classification:"zero-shot-classification",text_generation:"text2text-generation"},ue=new Set([A,$,P]),fe=e=>{const r=(e=>{if("string"!=typeof e)return;const r=e.trim().toLowerCase();return r.length>0?r:void 0})(e.inferenceKind);return r&&ue.has(r)?r:"task"},me=e=>"number"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,de=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("input_text_required");return e},pe=e=>{if("string"==typeof e)return e;if(Array.isArray(e)&&e.length){const r=e[0];if(r&&"string"==typeof r.summary_text)return r.summary_text;if(r&&"string"==typeof r.generated_text)return r.generated_text;if(r&&"string"==typeof r.label)return r.label;try{return JSON.stringify(r)}catch{return String(r??"")}}if(e&&"object"==typeof e){const r=e;if("string"==typeof r.summary_text)return r.summary_text;if("string"==typeof r.generated_text)return r.generated_text;if("string"==typeof r.label)return r.label;try{return JSON.stringify(r)}catch{return String(r)}}return""},ge=e=>{if(Array.isArray(e)){const r=e.filter(e=>"string"==typeof e);return r.length>0?r:void 0}if("string"==typeof e&&e.length>0)return[e]},he=(e,r)=>{const t=(e??"").trim();return t?t.slice(0,1024):r},we=async(e,r,t)=>{const{pipeline:n,pipelineTask:o}=e,{result:s,ms:a}=await L(async()=>{if("zero-shot-classification"===o){if(!t?.categories||0===t.categories.length)throw new Error("classification_categories_required");return n(r,t.categories)}return"summarization"===o?n(r,{max_new_tokens:t?.maxNewTokens??64,min_length:1,do_sample:!1}):"text2text-generation"===o?n(r,{max_new_tokens:t?.maxNewTokens??128,do_sample:!1}):n(r)});return{raw:s,ms:a}},ye=async(e,r,t)=>{try{return await we(e,r,t)}catch(n){if(!(e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("invalid array length"))(n)||r.length<=256)throw n;const o=r.slice(0,256);return await we(e,o,t)}};class be{constructor(e,r){this.config=e,this.state=r,this.loadModelMs=r.loadModelMs}async runInference(e){const r=fe(this.config);if(r===A)return this.runSequenceClassification(e);if(r===$)return this.runSeq2Seq(e);if(r===P)return this.runZeroShot(e);const t=this.config.taskType,n=he(e.text,"summarize this text");if("classification"===t)return this.runZeroShot(e);if("iab_classify"===t){const{raw:e,ms:r}=await ye(this.state,n);return{output:e,inferenceMs:r}}if("summary"===t){const{raw:r,ms:t}=await ye(this.state,n,{maxNewTokens:e.maxNewTokens});return{output:{text:pe(r)},inferenceMs:t}}if("text_generation"===t){const{raw:r,ms:t}=await ye(this.state,n,{maxNewTokens:e.maxNewTokens});return{output:{text:pe(r)},inferenceMs:t}}const{raw:o,ms:s}=await ye(this.state,n);return{output:o,inferenceMs:s}}async runZeroShot(e){const r=he(e.text,"summarize this text"),t=ge(e.categories)??ge(e.category),{raw:n,ms:o}=await ye(this.state,r,{categories:t});if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const r=e;return Array.isArray(r.labels)&&Array.isArray(r.scores)})(n)){return{output:(e=>{const r=e.labels,t=e.scores;if(!Array.isArray(r)||!Array.isArray(t))return null;const n=r.flatMap((e,r)=>{const n=t[r];return"string"==typeof e&&"number"==typeof n?[[e,n]]:[]});return n.length>0?Object.fromEntries(n):null})(n)??n,inferenceMs:o}}return{output:n,inferenceMs:o}}async runSequenceClassification(e){const r=this.state.classifier;if(!r)throw new Error("sequence_classifier_not_loaded");const t=de(e.text),n=e.topK??e.top_k,{result:o,ms:s}=await L(()=>r.classify(t,"number"==typeof n?n:void 0));return{output:o,inferenceMs:s}}async runSeq2Seq(e){const r=de(e.text).slice(0,8192),t=me(e.maxNewTokens)??this.state.defaultMaxNewTokens??48,{pipeline:n,scoring:o}=this.state,s=o?{eosTokenIds:o.eosTokenIds,logProbs:[],sawEos:!1}:void 0;const{result:a,ms:i}=await L(()=>n(r,{max_new_tokens:t,do_sample:!1,num_beams:1,...s?re(s):{}})),c=pe(a).trim(),l=s?(e=>{const r=e.logProbs.length;return 0===r?.5:Math.exp(e.logProbs.reduce((e,r)=>e+r,0)/r)})(s):.5;return{output:{text:c,score:l},inferenceMs:i}}async runSample(e){const r=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-r),error:!0,errorMessage:"response from processing sample"};try{const n=await this.runInference({text:e.text,categories:e.categories,category:e.category,usecase:e.usecase}),o=Math.round(performance.now()-r);return null!=(t=n.output)&&("string"==typeof t?t.trim().length>0:Array.isArray(t)?t.length>0:"object"!=typeof t||Object.keys(t).length>0)?{ok:!0,processingTimeMs:o,error:!1}:{ok:!1,processingTimeMs:o,error:!0,errorMessage:"response from processing sample"}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-r),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}var t}}const xe=async(e,r,t,n)=>{const o=fe(e),s=E();try{await U()}catch(e){const r=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${r}`)}const a=R(N(e.modelUrl,e.modelRepoId)),i=(e=>{const r=fe(e);return r===$?"text2text-generation":r===P?"zero-shot-classification":le[e.taskType]??e.taskType})(e),c=B(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!c)throw new Error("[SLM] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const l=await Q(async()=>{const l=j(),f=l.TransformersEnv||{};f.allowRemoteModels=!0,f.allowLocalModels=!0,q(f),f.backends||(f.backends={}),f.backends.onnx||(f.backends.onnx={}),f.backends.onnx.wasm||(f.backends.onnx.wasm={});const m=s.isEnabled()?"error":"fatal";f?.backends?.onnx?.env&&(f.backends.onnx.env.logLevel=m);const p=u(void 0,n?.wasm);f.backends.onnx.wasm.proxy=p.proxy,f.backends.onnx.wasm.numThreads=d().forceSingleThread?1:p.numThreads;const g=globalThis.fetch.bind(globalThis),h=await K(g);if(h)f.backends.onnx.wasm.wasmPaths=h;else try{delete f.backends.onnx.wasm.wasmPaths}catch{f.backends.onnx.wasm.wasmPaths=void 0}"logLevel"in f&&(f.logLevel=m);const w=globalThis.ort;w?.env&&(w.env.logLevel=m),f.fetch=Y(e.modelId,a,r,t,(e.requiredFiles??[]).map(e=>e.name),g),l.TransformersEnv=f,globalThis.fetch=f.fetch;const y={device:"wasm",quantized:e.quantized,progress_callback:()=>{}},b=()=>L(async()=>{if(o===A){const e=(()=>{const e=j().TransformersLib;if(!e)throw new Error("transformers_lib_unavailable");return e})(),[r,t]=await Promise.all([e.AutoTokenizer.from_pretrained(c,y),e.PreTrainedModel.from_pretrained(c,y)]);return{classifier:ce(e,r,t)}}const e=l.TransformersPipeline;if(!e)throw new Error("transformers_pipeline_unavailable");return{pipeline:await e(i,c,y)}});try{return await b()}catch(e){const r=f?.backends?.onnx?.wasm,t=Boolean(r&&"wasmPaths"in r&&r.wasmPaths);let n=e;if(r){const e=r.simd,t=r.numThreads,o=r.proxy;r.simd=!1,r.numThreads=1,r.proxy=!1;try{return await b()}catch(s){n=s,r.simd=e,r.numThreads=t,r.proxy=o}}if(!t||!r){const e=n instanceof Error?n.message:String(n);throw new Error(`pipeline_load_failed:${e}`)}const o=r.wasmPaths;try{delete r.wasmPaths}catch{r.wasmPaths=void 0}try{return await b()}catch(e){const r=e instanceof Error?e.message:String(e);throw new Error(`pipeline_load_failed:${r}`)}finally{r.wasmPaths=o}}finally{globalThis.fetch=g}}),{result:f,ms:m}=l;if(f.classifier){return{pipeline:()=>Promise.reject(new Error("pipeline_not_loaded")),pipelineTask:o,loadModelMs:m,classifier:f.classifier}}const p=f.pipeline,g={pipeline:p,pipelineTask:i,loadModelMs:m};if(o===$){const r=p.model;g.defaultMaxNewTokens=me(r?.generation_config?.max_new_tokens)??48,ne(r)?g.scoring={eosTokenIds:oe(r)}:E().warn("[SLM] seq2seq score hooks unavailable; score defaults to 0.5",{modelId:e.modelId})}return g};class ke{constructor(e){this.state=e,this.loadModelMs=e.loadModelMs}async runInference(e){const r=(e.text??"").trim();if(!r)return{output:{entities:[]},inferenceMs:0};const t="number"==typeof e.threshold&&Number.isFinite(e.threshold)?e.threshold:.4,n=(e.usecase??"ner").toLowerCase(),{result:o,ms:s}=await L(async()=>this.state.pipeline(r));var a,i;const c=((e,r)=>e.filter(e=>e.score>=r))((a=o,i=r,Array.isArray(a)?a.flatMap(e=>{if(!e||"object"!=typeof e)return[];const r=e,t="string"==typeof r.entity_group?r.entity_group:"string"==typeof r.entity?r.entity:"string"==typeof r.label?r.label:null;if(!t)return[];const n="number"==typeof r.score?r.score:0,o="number"==typeof r.start?r.start:-1,s="number"==typeof r.end?r.end:-1,a="string"==typeof r.word?r.word:"string"==typeof r.text?r.text:o>=0&&s>o?i.slice(o,s):"";return a?[{text:a,label:t,score:n,start:o,end:s}]:[]}):[]),t),l=Array.isArray(e.labels)?e.labels:void 0,u=((e,r)=>{if(!r||0===r.length)return e;const t=new Set(r.map(e=>e.toLowerCase()));return e.filter(e=>t.has(e.label.toLowerCase()))})(c,l);if("redact"===n){const t="string"==typeof e.mask&&e.mask.length>0?e.mask:"[REDACTED]",n=((e,r,t)=>{if(0===r.length)return e;const n=[...r].sort((e,r)=>r.start-e.start);let o=e;for(const e of n){if(e.start<0||e.end<=e.start)continue;const r=t.includes("LABEL")?t.replace("LABEL",e.label):t;o=o.slice(0,e.start)+r+o.slice(e.end)}return o})(r,u,t);return{output:{text:n,entities:u},inferenceMs:s}}if("json"===n){const r=((e,r)=>{if(!e||"object"!=typeof e)return{};const t={};for(const[n,o]of Object.entries(e)){const e=Array.isArray(o)?o:[],s={};for(const t of e){if("string"!=typeof t)continue;const e=t.split("::")[0],n=r.find(r=>r.label.toLowerCase()===e.toLowerCase());n&&(s[e]=n.text)}t[n]=s}return t})(e.schema,u);return{output:r,inferenceMs:s}}if("classification"===n){const e=((e,r)=>{const t={};for(const n of r){const r=e.filter(e=>e.label.toLowerCase()===n.toLowerCase()).reduce((e,r)=>Math.max(e,r.score),0);t[n]=r}return t})(c,l??[]);return{output:e,inferenceMs:s}}return{output:{entities:u},inferenceMs:s}}async runSample(e){const r=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-r),error:!0,errorMessage:"response from processing sample"};try{return await this.runInference({text:e.text,labels:e.labels,threshold:e.threshold,usecase:e.usecase??"ner",schema:e.schema,mask:e.mask,categories:e.categories}),{ok:!0,processingTimeMs:Math.round(performance.now()-r),error:!1,errorMessage:void 0}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-r),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}}}const _e=async(e,r,t)=>{const n=E();try{await U()}catch(e){const r=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${r}`)}const o=R(N(e.modelUrl,e.modelRepoId)),s=B(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!s)throw new Error("[Transformers] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const a=await Q(async()=>{const a=j(),i=a.TransformersEnv||{};i.allowRemoteModels=!0,i.allowLocalModels=!0,i.backends||(i.backends={}),i.backends.onnx||(i.backends.onnx={}),i.backends.onnx.wasm||(i.backends.onnx.wasm={}),i.backends.onnx.wasm.proxy=!1,i.backends.onnx.wasm.numThreads=1;const c=globalThis.fetch.bind(globalThis),l=await K(c);l&&(i.backends.onnx.wasm.wasmPaths=l),i.fetch=Y(e.modelId,o,r,t,(e.requiredFiles??[]).map(e=>e.name),c),a.TransformersEnv=i,globalThis.fetch=i.fetch;try{return await L(()=>{const r=a.TransformersPipeline;if(!r)throw new Error("transformers_pipeline_unavailable");return r("token-classification",s,{device:"wasm",quantized:e.quantized,aggregation_strategy:"simple",progress_callback:()=>{}})})}catch(e){const r=e instanceof Error?e.message:String(e);throw n.warn("[Transformers] token-classification pipeline load failed",{message:r}),new Error(`transformers_pipeline_load_failed:${r}`)}finally{globalThis.fetch=c}}),{result:i,ms:c}=a;return{pipeline:i,loadModelMs:c}},Me="transformers_runtime_load_failed",ve=e=>{if(void 0===e)return;if(e instanceof Error)return{error:x(e)};const r={};for(const[t,n]of Object.entries(e))r[t]=n instanceof Error?x(n):n;return r},Te=e=>{const r=e instanceof Error?e.name:"Error",t=e instanceof Error?e.message:String(e),n={name:r,message:t},o=e?.code;return"string"==typeof o?n.code=o:t.startsWith(Me)&&(n.code=Me),n};((e,r)=>{const t=new Map,n=r=>e.postMessage(r),o=e=>{const r=t.get(e);if(!r)throw new Error("worker_model_not_loaded");return r},s=async e=>{switch(e.type){case"init":{const{config:r}=e;return((e,r)=>{S=new T(e,r)})({enableConsoleLogs:r.logging.enabled,locationData:!1,events:!1},(e,r,t)=>n({type:"log",level:e,message:r,fields:ve(t)})),r.logging.enabled||"undefined"!=typeof document||(()=>{const e=()=>{};console.log=e,console.info=e,console.debug=e,console.warn=e,console.error=e})(),(e=>{const r={...m};for(const[t,n]of Object.entries(e))void 0!==n&&(r[t]=n);m=r})(r.runtime),{protocol:1}}case"load":{const n=r[e.framework];if(!n)throw new Error(`worker_framework_unsupported:${e.framework}`);const o={},s=await n(e.slm,e.cachedFiles??{},(e,r)=>{o[e]=r},{wasm:e.wasm});t.set(e.handle,s);return{loadModelMs:s.loadModelMs,downloadedFiles:o}}case"infer":return o(e.handle).runInference(e.input);case"sample":return o(e.handle).runSample(e.sample);case"dispose":{const r=t.get(e.handle);return t.delete(e.handle),await(r?.dispose?.()),!0}default:throw new Error("worker_unknown_message")}};e.onmessage=e=>{const r=e?.data;r&&"object"==typeof r&&"number"==typeof r.id&&s(r).then(e=>n({type:"result",id:r.id,ok:!0,value:e}),e=>n({type:"result",id:r.id,ok:!1,error:Te(e)}))},n({type:"ready",protocol:1})})(self,{ONNX:async(e,r,t,n)=>{const o=await xe(e,r,t,n);return new be(e,o)},Transformers:async(e,r,t)=>{const n=await _e(e,r,t);return new ke(n)}});
|
|
1
|
+
const e={onnx:2,transformersjs:2.5,transformers:2.5,gguf:1.4},t=.7,r=.85,n=.95,o=1e4,s=.6,a=6e4;let i={},l=function(l){const u={},f=Object.fromEntries(Object.entries({}).filter(([,e])=>void 0!==c(e)));return{memoryBudgetFraction:c(i.memoryBudgetFraction)??c(l?.memoryBudgetFraction)??.3,frameworkMultipliers:{...e,...f},minBatteryLevel:c(l?.minBatteryLevel)??.2,storageHeadroom:c(l?.storageHeadroom)??1.2,unknownMemoryGb:c(l?.unknownMemoryGb)??2,watchdog:{warnPct:c(u.warnPct)??t,degradePct:c(u.degradePct)??r,shutdownPct:c(u.shutdownPct)??n,sampleMs:c(u.sampleMs)??o,recoverPct:c(u.recoverPct)??s,recoverHoldMs:c(u.recoverHoldMs)??a},maxMemoryBudgetMb:c(l?.maxMemoryBudgetMb)??0,maxInputTokens:c(l?.maxInputTokens)??0,sampleLatencyBudgetMs:c(l?.sampleLatencyBudgetMs)??0,maxCachedModels:"number"==typeof i.maxCachedModels&&Number.isFinite(i.maxCachedModels)&&i.maxCachedModels>=0?Math.floor(i.maxCachedModels):3,wasm:{maxThreads:c(l?.wasm?.maxThreads)??4,proxyWorker:!0===l?.wasm?.proxyWorker}}}(null);function c(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:void 0}const u=(e=(()=>({isolated:"boolean"==typeof globalThis.crossOriginIsolated&&globalThis.crossOriginIsolated&&"function"==typeof globalThis.SharedArrayBuffer,cores:"undefined"!=typeof navigator&&"number"==typeof navigator.hardwareConcurrency?navigator.hardwareConcurrency:1,workerAvailable:"function"==typeof globalThis.Worker,inDocument:"undefined"!=typeof document}))(),t=l.wasm)=>{const r=Number.isFinite(e.cores)&&e.cores>0?Math.floor(e.cores):1;return{numThreads:e.isolated?Math.max(1,Math.min(r-1,t.maxThreads)):1,proxy:t.proxyWorker&&e.workerAvailable&&!1!==e.inDocument}},f="https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";let m={...{transformersUrl:f}};const d=()=>m,p=200,g=/(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i,h=new Set(["url","wsurl","baseurl","modelurl","modelrepourl","runtimeurl","requesturl","endpoint","endpointurl","manifesturl","bundleurl","orchestrator"]),y=new Set(["message","errormessage","error","reason"]),w=new Set(["requestid","modelid","modelversion","modelrepoid","modeltype","deviceid","sdkversion","tasktype","framework","inferenceframework","quantization","code","status","type","phase","flow","event","source","name","platform","devicetype","gpurenderer","mime","mode","file","files","requiredfiles","models","cachedmodels","keys","changed","cachedmodelid","assignedmodelid","primarymodelid"]),b=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e,x=e=>{if(e instanceof Error)return b(`${e.name}: ${e.message}`,p);if("string"==typeof e)return b(e,p);if(null==e)return String(e);if("object"==typeof e&&"string"==typeof e.name&&"string"==typeof e.message){const{name:t,message:r}=e;return b(`${t}: ${r}`,p)}return"object"==typeof e?`[${e.constructor?.name??"object"}]`:b(String(e),p)},k=e=>Array.isArray(e)?`[array:${e.length}]`:e&&"object"==typeof e?`[object:${Object.keys(e).length} keys]`:`[${typeof e}]`,_=(e,t)=>{const r=e.toLowerCase();return h.has(r)?(e=>{try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return"[invalid-url]"}})(t):y.has(r)?b(t,p):w.has(r)?b(t,256):`[string:${t.length}]`},M=(e,t)=>g.test(e)?"[redacted]":null==t||"boolean"==typeof t?t:"number"==typeof t?Number.isFinite(t)?t:String(t):"string"==typeof t?_(e,t):t instanceof Error?x(t):k(t),v=e=>"string"==typeof e?b(e,p):"[invalid log message]";class T{constructor(e,t){this.enabled=e.enableConsoleLogs,this.sink=t}setEnabled(e){this.enabled=e}isEnabled(){return this.enabled}emit(e,t,r,n){this.enabled&&(this.sink?this.sink(e,v(r),n):void 0===n?t("[ZeroGPU]",v(r)):t("[ZeroGPU]",v(r),(e=>{if(e instanceof Error)return{error:x(e)};if(!e||"object"!=typeof e||Array.isArray(e))return{detail:M("detail",e)};const t={};for(const[r,n]of Object.entries(e))Array.isArray(n)?g.test(r)?t[r]="[redacted]":n.every(e=>null===e||"object"!=typeof e)?t[r]=n.slice(0,20).map(e=>M(r,e)):t[r]=k(n):t[r]=M(r,n);return t})(n)))}debug(e,t){this.emit("debug",console.debug,e,t)}info(e,t){this.emit("info",console.debug,e,t)}warn(e,t){this.emit("warn",console.warn,e,t)}error(e,t){this.emit("error",console.error,e,t)}}let S=null;const E=()=>(S||(S=new T({enableConsoleLogs:!1,locationData:!1,events:!0})),S),A=async e=>{const t=performance.now();return{result:await e(),ms:Math.round(performance.now()-t)}},L="sequence_classification",$="seq2seq_generation",q="zero_shot_classification",P="token_classification",j="question_answering",I="text_embedding",B="fill_mask",U=()=>globalThis,R=e=>{e&&(e.useBrowserCache=!1)};let z=null;const N=()=>{const e=U();if(e.TransformersPipeline)return Promise.resolve();if(!z){const t=E(),r=d().transformersUrl;z=(async()=>{try{t.info("[Runtime] Importing Transformers runtime",{runtimeUrl:r});const n=performance.now(),o=await import(r),s=o?.pipeline,a=o?.env;if("function"!=typeof s||!a)throw new Error("Transformers runtime missing pipeline/env exports");t.info("[Runtime] Transformers runtime ready",{ms:Math.round(performance.now()-n)}),a.allowLocalModels=!0,a.allowRemoteModels=!0,R(a),a?.backends?.onnx?.env&&(a.backends.onnx.env.logLevel="warning"),"logLevel"in a&&(a.logLevel="warning"),e.TransformersPipeline=s,e.TransformersEnv=a,e.TransformersLib=(e=>{if(!e||"object"!=typeof e)return;const t=e,{AutoTokenizer:r,PreTrainedModel:n,Tensor:o}=t,s=e=>Boolean(e)&&"function"==typeof e.from_pretrained;return s(r)&&s(n)&&"function"==typeof o?{AutoTokenizer:r,PreTrainedModel:n,Tensor:o}:void 0})(o)}catch(e){throw z=null,t.error("[SLM] Failed to import Transformers runtime",{runtimeUrl:r,error:x(e)}),e}})()}return z},C=e=>e.replace(/\/$/,""),O=e=>/^https?:\/\//i.test(e.trim()),F=e=>{const t=(e=>{const t=e.trim();if(!t)return"";if(O(t))try{return new URL(t).pathname.replace(/^\/+|\/+$/g,"")}catch{return""}return t.replace(/^\/+|\/+$/g,"")})(e);return t?C(`https://huggingface.co/${t}/resolve/main`):""},W=(e,t)=>{const r=(e||"").trim();if(O(r))return C(r);const n=F(t||r);return n||C(r)},H=e=>e.replace(/^\/+/,"").replace(/^resolve\/main\//,"").split("?")[0],D=(e,t)=>`${e}/${H(t)}`,G=()=>{const e=d().pageOrigin??("undefined"!=typeof location&&location?location.origin:void 0);if(!e||"null"===e)return null;try{return new URL("/onnx-wasm/",e).toString()}catch{return null}},Z=[0,97,115,109],K=["ort-wasm-simd-threaded.wasm","ort-wasm-simd.wasm","ort-wasm-threaded.wasm","ort-wasm.wasm"],J=e=>e.endsWith("/")?e:`${e}/`,Q=()=>{try{const e=new URL(f),t=e.pathname,r=t.lastIndexOf("/"),n=r>=0?t.slice(0,r+1):"/";return`${e.origin}${n}`}catch{return"https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/"}},X=e=>e.length>=Z.length&&Z.every((t,r)=>e[r]===t);let V=null;const Y=e=>(V||(V=(async e=>{const t=[d().wasmPaths,G(),Q(),"https://unpkg.com/@xenova/transformers@2.17.2/dist/"].filter(e=>"string"==typeof e&&e.length>0).map(J).filter((e,t,r)=>r.indexOf(e)===t);for(const r of t){let t=!1;for(const n of K){const o=(()=>{try{return new URL(n,r).toString()}catch{return`${r}${n}`}})();try{const n=await e(o,{cache:"no-store"});if(!n.ok)continue;const s=new Uint8Array(await n.arrayBuffer());if(X(s))return r;t=!0;break}catch{}}t&&E().warn("[SLM] ONNX wasm probe got non-wasm payload",{url:r})}return null})(e)),V);let ee=Promise.resolve();const te=async e=>{const t=ee;let r=()=>{};ee=new Promise(e=>{r=e}),await t;try{return await e()}finally{r()}},re={},ne=(e,t,r,n,o,s)=>{const a=o.map(e=>H(e.trim())).filter(e=>e.length>0),i=new Set(a),l=E(),c=(()=>{try{return new URL(t)}catch{return null}})();return async(o,a)=>{const u="string"==typeof o?o:o instanceof URL?o.toString():o.url,f=(e=>{const t=(()=>{try{return new URL(e).pathname}catch{return e.split("?")[0]||""}})(),r="/resolve/main/",n=t.indexOf(r);if(n>=0){const e=t.slice(n+14);return H(e)}if(!c)return null;const o=c.pathname.replace(/\/$/,"");if(!t.startsWith(`${o}/`))return null;const s=t.slice(o.length+1);return H(s)})(u);if(!f){if(!(/\.wasm(?:\?|$)/i.test(u)||/onnxruntime|ort-wasm/i.test(u)))return s(o,a);try{return await s(o,a)}catch(t){throw l.error("[SLM][fetch] non-model wasm/ort request failed",{modelId:e,requestUrl:u,error:x(t)}),t}}const m=(e=>{const t=H(e);if(!t)return null;if(0===i.size||i.has(t))return t;if(t.startsWith("onnx/")&&t.endsWith(".onnx")&&!t.endsWith("_quantized.onnx")){const e=t.replace(/\.onnx$/,"_quantized.onnx");if(i.has(e))return e}return null})(f);if(!m)return l.warn("[SLM] Unexpected model file request; falling back to original fetch",{file:f,modelId:e}),s(o,a);const d=(e=>{const r=H(e),n=[],o=e=>{n.includes(e)||n.push(e)};try{const e=new URL(t),n=e.toString().endsWith("/")?e.toString():`${e.toString()}/`;t.endsWith("/resolve/main")?o(new URL(r,n).toString()):(o(new URL(r,n).toString()),o(new URL(`resolve/main/${r}`,n).toString()))}catch{t.endsWith("/resolve/main")?o(`${t}/${r}`):(o(`${t}/${r}`),o(`${t}/resolve/main/${r}`))}return n})(m),p=H(m),g=D(e,p);let h=re[g]||r[g]||re[p]||r[p]||r[`onnx/${p}`]||re[`onnx/${p}`];if(!h&&p.startsWith("onnx/")){const t=p.replace("onnx/","");h=r[t]||re[t]||r[D(e,t)]||re[D(e,t)]}if(h)return new Response(h);try{for(const e of d){const t=await s(e,a);if(t.ok){const e=await t.blob();return re[g]=e,n&&n(g,e),new Response(e)}}return new Response("required_file_not_found",{status:404,statusText:"Not Found"})}catch(t){return l.warn("[SLM] Model file fetch failed",{modelId:e,file:m,candidateCount:d.length,error:x(t)}),new Response("model_file_fetch_failed",{status:502,statusText:"Bad Gateway"})}}},oe="zgScoreRecorder",se=e=>({[oe]:e}),ae=(e,t,r)=>{let n=-1/0;for(let o=0;o<r;o+=1)n=Math.max(n,e[t+o]);let o=0;for(let s=0;s<r;s+=1)o+=Math.exp(e[t+s]-n);return n+Math.log(o)},ie=e=>{const t=e;if(!t||t.__zgScoreHooks)return Boolean(t?.__zgScoreHooks);const{getStartBeams:r,runBeam:n,updateBeam:o}=t;return"function"==typeof r&&"function"==typeof n&&"function"==typeof o&&(t.getStartBeams=(...e)=>{const n=r.apply(t,e),o=e[1],s=o?.[oe];if(s)for(const e of n)e[oe]=s;return n},t.runBeam=async e=>{const r=await n.call(t,e),o=e[oe];return o&&r?.logits&&((e,t)=>{const{offset:r,size:n}=(e=>{const t=e.dims,r=t[t.length-1];return{offset:((t.length>=2?t[t.length-2]:1)-1)*r,size:r}})(t);e.pending={row:t.data,offset:r,size:n,logSumExp:ae(t.data,r,n)}})(o,r.logits),r},t.updateBeam=(e,r)=>{const n=o.call(t,e,r),s=e[oe];return s&&((e,t)=>{const r=e.pending;if(e.pending=void 0,!r||e.sawEos)return;if(e.eosTokenIds.includes(t))return void(e.sawEos=!0);const n=Math.exp(r.row[r.offset+t]-r.logSumExp);e.logProbs.push(Math.log(Math.max(n,1e-9)))})(s,r),n},t.__zgScoreHooks=!0,!0)},le=e=>{const t=e,r=t?.generation_config?.eos_token_id??t?.config?.eos_token_id;return(Array.isArray(r)?r:[r]).filter(e=>"number"==typeof e)},ce=(e,t)=>"sigmoid"===e?(e=>Array.from(e,e=>1/(1+Math.exp(-e))))(t):(e=>{const t=Array.from(e);if(0===t.length)return[];const r=Math.max(...t),n=t.map(e=>Math.exp(e-r)),o=n.reduce((e,t)=>e+t,0);return n.map(e=>e/o)})(t),ue=e=>"number"==typeof e&&Number.isFinite(e)&&e>0&&e<1e6?Math.floor(e):void 0,fe=e=>{const t=new BigInt64Array(e.length);return e.forEach((e,r)=>{t[r]=BigInt(e)}),t},me=(e,t,r)=>{const n=r.config??{},o=r.session,s="multi_label_classification"===n.problem_type?"sigmoid":"softmax";const a=((e,t)=>{const r=[ue(e.max_position_embeddings),ue(e.n_positions),ue(t.model_max_length)].filter(e=>void 0!==e);return r.length>0?Math.min(...r):512})(n,t),i=t.encode(""),l=i.length>0?i[i.length-1]:void 0,c=o.outputNames.includes("logits")?"logits":o.outputNames[0],u=n.id2label&&"object"==typeof n.id2label?Object.keys(n.id2label).length:0;return{labelCount:u,maxLength:a,activation:s,async classify(r,i){const u=r.slice(0,16*a),f=((e,t,r)=>{if(e.length<=t)return e;const n=e[e.length-1];return void 0!==r&&n===r&&t>=2?[...e.slice(0,t-1),n]:e.slice(0,t)})(t.encode(u),a,l),m=await o.run((t=>{const r=[1,t.length],n={};for(const s of o.inputNames)if("input_ids"===s)n[s]=new e.Tensor("int64",fe(t),r);else if("attention_mask"===s)n[s]=new e.Tensor("int64",fe(t.map(()=>1)),r);else{if("token_type_ids"!==s)throw new Error(`sequence_classification_unsupported_input:${s}`);n[s]=new e.Tensor("int64",fe(t.map(()=>0)),r)}return n})(f)),d=m[c];if(!d||!d.data||0===d.data.length)throw new Error("sequence_classification_empty_logits");const p=ce(s,d.data),g=((e,t)=>{const r=e.id2label,n=r&&"object"==typeof r?r:{};return Array.from({length:t},(e,t)=>{const r=n[String(t)];return"string"==typeof r&&r.length>0?r:`LABEL_${t}`})})(n,p.length);return((e,t,r)=>{const n=Math.max(1,Math.min(Math.floor(r),e.length)),o=e.map((e,t)=>({score:e,index:t})).sort((e,t)=>t.score-e.score).slice(0,n),s={};for(const{score:e,index:r}of o)s[t[r]??`LABEL_${r}`]=e;return s})(p,g,"number"==typeof(h=i)&&Number.isFinite(h)&&h>=1?Math.floor(h):50);var h}}},de={summary:"summarization",iab_classify:"text-classification",classification:"zero-shot-classification",text_generation:"text2text-generation"},pe=new Set([L,$,q,P,j,I,B]),ge={[$]:"text2text-generation",[q]:"zero-shot-classification",[P]:"token-classification",[j]:"question-answering",[I]:"feature-extraction",[B]:"fill-mask"},he=e=>{const t=(e=>{if("string"!=typeof e)return;const t=e.trim().toLowerCase();return t.length>0?t:void 0})(e.inferenceKind);return t&&pe.has(t)?t:"task"},ye=8192,we=/\[MASK\]|<mask>/g,be=e=>"number"==typeof e&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0,xe=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("input_text_required");return e},ke=e=>{if("string"==typeof e)return e;if(Array.isArray(e)&&e.length){const t=e[0];if(t&&"string"==typeof t.summary_text)return t.summary_text;if(t&&"string"==typeof t.generated_text)return t.generated_text;if(t&&"string"==typeof t.label)return t.label;try{return JSON.stringify(t)}catch{return String(t??"")}}if(e&&"object"==typeof e){const t=e;if("string"==typeof t.summary_text)return t.summary_text;if("string"==typeof t.generated_text)return t.generated_text;if("string"==typeof t.label)return t.label;try{return JSON.stringify(t)}catch{return String(t)}}return""},_e=e=>{if(Array.isArray(e)){const t=e.filter(e=>"string"==typeof e);return t.length>0?t:void 0}if("string"==typeof e&&e.length>0)return[e]},Me=(e,t)=>{const r=(e??"").trim();return r?r.slice(0,1024):t},ve=e=>{const t=/^([BI])-(.+)$/.exec(e);return t?{prefix:t[1],label:t[2]}:{prefix:null,label:e}},Te=(e,t)=>{const r=Array.isArray(t)?t:[],n=[],o=[];let s=null,a=-2;const i=()=>{if(!s)return;const t=s.pieces.join(" "),r=o[o.length-1],{start:n,end:a}=((e,t,r)=>{const n=e.indexOf(t,r);if(n>=0)return{start:n,end:n+t.length};const o=t.split(/\s+/).filter(Boolean).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s*");if(!o)return{start:-1,end:-1};const s=new RegExp(o).exec(e.slice(r));return s?{start:r+s.index,end:r+s.index+s[0].length}:{start:-1,end:-1}})(e,t,r&&r.end>=0?r.end:0),i=s.scores.reduce((e,t)=>e+t,0)/Math.max(1,s.scores.length);o.push({label:s.label,text:t,start:n,end:a,score:Number(i.toFixed(6))}),s=null};for(const e of r){const t="string"==typeof e?.entity?e.entity:"O",r="string"==typeof e?.word?e.word:"",o="number"==typeof e?.score?e.score:0,l="number"==typeof e?.index?e.index:a+1,c=r.startsWith("##")&&l===a+1,u=c?r.slice(2):r;if(a=l,n.push({token:r,label:t,score:Number(o.toFixed(6))}),c&&s){s.pieces[s.pieces.length-1]+=u,s.scores.push(o);continue}const{prefix:f,label:m}=ve(t);"O"!==t&&u?s&&"B"!==f&&s.label===m?(s.pieces.push(u),s.scores.push(o)):(i(),s={label:m,pieces:[u],scores:[o]}):i()}return i(),{entities:o,tokens:n}},Se=e=>{if(Array.isArray(e)){return e.flat(1/0).filter(e=>"number"==typeof e)}const t=e?.data;return t&&"number"==typeof t.length?Array.from(t):[]},Ee=async(e,t,r)=>{const{pipeline:n,pipelineTask:o}=e,{result:s,ms:a}=await A(async()=>{if("zero-shot-classification"===o){if(!r?.categories||0===r.categories.length)throw new Error("classification_categories_required");return n(t,r.categories)}return"summarization"===o?n(t,{max_new_tokens:r?.maxNewTokens??64,min_length:1,do_sample:!1}):"text2text-generation"===o?n(t,{max_new_tokens:r?.maxNewTokens??128,do_sample:!1}):n(t)});return{raw:s,ms:a}},Ae=async(e,t,r)=>{try{return await Ee(e,t,r)}catch(n){if(!(e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("invalid array length"))(n)||t.length<=256)throw n;const o=t.slice(0,256);return await Ee(e,o,r)}};class Le{constructor(e,t){this.config=e,this.state=t,this.loadModelMs=t.loadModelMs}async runInference(e){const t=he(this.config);if(t===L)return this.runSequenceClassification(e);if(t===$)return this.runSeq2Seq(e);if(t===q)return this.runZeroShot(e,!0);if(t===P)return this.runTokenClassification(e);if(t===j)return this.runQuestionAnswering(e);if(t===I)return this.runTextEmbedding(e);if(t===B)return this.runFillMask(e);const r=this.config.taskType,n=Me(e.text,"summarize this text");if("classification"===r)return this.runZeroShot(e);if("iab_classify"===r){const{raw:e,ms:t}=await Ae(this.state,n);return{output:e,inferenceMs:t}}if("summary"===r){const{raw:t,ms:r}=await Ae(this.state,n,{maxNewTokens:e.maxNewTokens});return{output:{text:ke(t)},inferenceMs:r}}if("text_generation"===r){const{raw:t,ms:r}=await Ae(this.state,n,{maxNewTokens:e.maxNewTokens});return{output:{text:ke(t)},inferenceMs:r}}const{raw:o,ms:s}=await Ae(this.state,n);return{output:o,inferenceMs:s}}async runZeroShot(e,t=!1){const r=t?xe(e.text).slice(0,ye):Me(e.text,"summarize this text"),n=_e(e.categories)??_e(e.category),{raw:o,ms:s}=await Ae(this.state,r,{categories:n});if((e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return Array.isArray(t.labels)&&Array.isArray(t.scores)})(o)){return{output:(e=>{const t=e.labels,r=e.scores;if(!Array.isArray(t)||!Array.isArray(r))return null;const n=t.flatMap((e,t)=>{const n=r[t];return"string"==typeof e&&"number"==typeof n?[[e,n]]:[]});return n.length>0?Object.fromEntries(n):null})(o)??o,inferenceMs:s}}return{output:o,inferenceMs:s}}async runSequenceClassification(e){const t=this.state.classifier;if(!t)throw new Error("sequence_classifier_not_loaded");const r=xe(e.text),n=e.topK??e.top_k,{result:o,ms:s}=await A(()=>t.classify(r,"number"==typeof n?n:void 0));return{output:o,inferenceMs:s}}async runSeq2Seq(e){const t=xe(e.text).slice(0,8192),r=be(e.maxNewTokens)??this.state.defaultMaxNewTokens??48,{pipeline:n,scoring:o}=this.state,s=o?{eosTokenIds:o.eosTokenIds,logProbs:[],sawEos:!1}:void 0;const{result:a,ms:i}=await A(()=>n(t,{max_new_tokens:r,do_sample:!1,num_beams:1,...s?se(s):{}})),l=ke(a).trim(),c=s?(e=>{const t=e.logProbs.length;return 0===t?.5:Math.exp(e.logProbs.reduce((e,t)=>e+t,0)/t)})(s):.5;return{output:{text:l,score:c},inferenceMs:i}}async runTokenClassification(e){const t=xe(e.text).slice(0,ye),{result:r,ms:n}=await A(()=>this.state.pipeline(t,{ignore_labels:[]}));return{output:Te(t,r),inferenceMs:n}}async runQuestionAnswering(e){const t="string"==typeof e.question?e.question.trim():"";if(!t)throw new Error("input_question_required");const r=("string"==typeof e.context&&e.context.trim().length>0?e.context:xe(e.text)).slice(0,ye),n=this.state.pipeline,{result:o,ms:s}=await A(()=>n(t,r,{topk:1})),a=Array.isArray(o)?o[0]:o,i="string"==typeof a?.answer?a.answer.trim():"",l="number"==typeof a?.score?a.score:0,c=i?r.indexOf(i):-1;return{output:{answer:i,score:l,start:c,end:c>=0?c+i.length:-1},inferenceMs:s}}async runTextEmbedding(e){const t=xe(e.text).slice(0,ye),{result:r,ms:n}=await A(()=>this.state.pipeline(t,{pooling:"mean",normalize:!0}));return{output:{embedding:Se(r)},inferenceMs:n}}async runFillMask(e){const t=this.state.pipeline.tokenizer?.mask_token,r=((e,t)=>!t||e.includes(t)?e:e.replace(we,t))(xe(e.text).slice(0,ye),"string"==typeof t?t:void 0),n=(e=>be(e.topK)??be(e.top_k))(e)??5,{result:o,ms:s}=await A(()=>this.state.pipeline(r,{topk:n})),a=Array.isArray(o)?o:[],i=a.map(e=>({token:"string"==typeof e?.token_str?e.token_str.trim():"",tokenId:"number"==typeof e?.token?e.token:-1,score:"number"==typeof e?.score?e.score:0})),l=a[0];return{output:{predictions:i,text:"string"==typeof l?.sequence?l.sequence:r},inferenceMs:s}}async runSample(e){const t=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:"response from processing sample"};try{const n=await this.runInference({...e,text:e.text}),o=Math.round(performance.now()-t);return null!=(r=n.output)&&("string"==typeof r?r.trim().length>0:Array.isArray(r)?r.length>0:"object"!=typeof r||Object.keys(r).length>0)?{ok:!0,processingTimeMs:o,error:!1}:{ok:!1,processingTimeMs:o,error:!0,errorMessage:"response from processing sample"}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}var r}}const $e=async(e,t,r,n)=>{const o=he(e),s=E();try{await N()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const a=C(W(e.modelUrl,e.modelRepoId)),i=(e=>{const t=he(e);return ge[t]??de[e.taskType]??e.taskType})(e),l=O(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!l)throw new Error("[SLM] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const c=await te(async()=>{const c=U(),f=c.TransformersEnv||{};f.allowRemoteModels=!0,f.allowLocalModels=!0,R(f),f.backends||(f.backends={}),f.backends.onnx||(f.backends.onnx={}),f.backends.onnx.wasm||(f.backends.onnx.wasm={});const m=s.isEnabled()?"error":"fatal";f?.backends?.onnx?.env&&(f.backends.onnx.env.logLevel=m);const p=u(void 0,n?.wasm);f.backends.onnx.wasm.proxy=p.proxy,f.backends.onnx.wasm.numThreads=d().forceSingleThread?1:p.numThreads;const g=globalThis.fetch.bind(globalThis),h=await Y(g);if(h)f.backends.onnx.wasm.wasmPaths=h;else try{delete f.backends.onnx.wasm.wasmPaths}catch{f.backends.onnx.wasm.wasmPaths=void 0}"logLevel"in f&&(f.logLevel=m);const y=globalThis.ort;y?.env&&(y.env.logLevel=m),f.fetch=ne(e.modelId,a,t,r,(e.requiredFiles??[]).map(e=>e.name),g),c.TransformersEnv=f,globalThis.fetch=f.fetch;const w={device:"wasm",quantized:e.quantized,progress_callback:()=>{}},b=()=>A(async()=>{if(o===L){const e=(()=>{const e=U().TransformersLib;if(!e)throw new Error("transformers_lib_unavailable");return e})(),[t,r]=await Promise.all([e.AutoTokenizer.from_pretrained(l,w),e.PreTrainedModel.from_pretrained(l,w)]);return{classifier:me(e,t,r)}}const e=c.TransformersPipeline;if(!e)throw new Error("transformers_pipeline_unavailable");return{pipeline:await e(i,l,w)}});try{return await b()}catch(e){const t=f?.backends?.onnx?.wasm,r=Boolean(t&&"wasmPaths"in t&&t.wasmPaths);let n=e;if(t){const e=t.simd,r=t.numThreads,o=t.proxy;t.simd=!1,t.numThreads=1,t.proxy=!1;try{return await b()}catch(s){n=s,t.simd=e,t.numThreads=r,t.proxy=o}}if(!r||!t){const e=n instanceof Error?n.message:String(n);throw new Error(`pipeline_load_failed:${e}`)}const o=t.wasmPaths;try{delete t.wasmPaths}catch{t.wasmPaths=void 0}try{return await b()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`pipeline_load_failed:${t}`)}finally{t.wasmPaths=o}}finally{globalThis.fetch=g}}),{result:f,ms:m}=c;if(f.classifier){return{pipeline:()=>Promise.reject(new Error("pipeline_not_loaded")),pipelineTask:o,loadModelMs:m,classifier:f.classifier}}const p=f.pipeline,g={pipeline:p,pipelineTask:i,loadModelMs:m};if(o===$){const t=p.model;g.defaultMaxNewTokens=be(t?.generation_config?.max_new_tokens)??48,ie(t)?g.scoring={eosTokenIds:le(t)}:E().warn("[SLM] seq2seq score hooks unavailable; score defaults to 0.5",{modelId:e.modelId})}return g};class qe{constructor(e){this.state=e,this.loadModelMs=e.loadModelMs}async runInference(e){const t=(e.text??"").trim();if(!t)return{output:{entities:[]},inferenceMs:0};const r="number"==typeof e.threshold&&Number.isFinite(e.threshold)?e.threshold:.4,n=(e.usecase??"ner").toLowerCase(),{result:o,ms:s}=await A(async()=>this.state.pipeline(t));var a,i;const l=((e,t)=>e.filter(e=>e.score>=t))((a=o,i=t,Array.isArray(a)?a.flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e,r="string"==typeof t.entity_group?t.entity_group:"string"==typeof t.entity?t.entity:"string"==typeof t.label?t.label:null;if(!r)return[];const n="number"==typeof t.score?t.score:0,o="number"==typeof t.start?t.start:-1,s="number"==typeof t.end?t.end:-1,a="string"==typeof t.word?t.word:"string"==typeof t.text?t.text:o>=0&&s>o?i.slice(o,s):"";return a?[{text:a,label:r,score:n,start:o,end:s}]:[]}):[]),r),c=Array.isArray(e.labels)?e.labels:void 0,u=((e,t)=>{if(!t||0===t.length)return e;const r=new Set(t.map(e=>e.toLowerCase()));return e.filter(e=>r.has(e.label.toLowerCase()))})(l,c);if("redact"===n){const r="string"==typeof e.mask&&e.mask.length>0?e.mask:"[REDACTED]",n=((e,t,r)=>{if(0===t.length)return e;const n=[...t].sort((e,t)=>t.start-e.start);let o=e;for(const e of n){if(e.start<0||e.end<=e.start)continue;const t=r.includes("LABEL")?r.replace("LABEL",e.label):r;o=o.slice(0,e.start)+t+o.slice(e.end)}return o})(t,u,r);return{output:{text:n,entities:u},inferenceMs:s}}if("json"===n){const t=((e,t)=>{if(!e||"object"!=typeof e)return{};const r={};for(const[n,o]of Object.entries(e)){const e=Array.isArray(o)?o:[],s={};for(const r of e){if("string"!=typeof r)continue;const e=r.split("::")[0],n=t.find(t=>t.label.toLowerCase()===e.toLowerCase());n&&(s[e]=n.text)}r[n]=s}return r})(e.schema,u);return{output:t,inferenceMs:s}}if("classification"===n){const e=((e,t)=>{const r={};for(const n of t){const t=e.filter(e=>e.label.toLowerCase()===n.toLowerCase()).reduce((e,t)=>Math.max(e,t.score),0);r[n]=t}return r})(l,c??[]);return{output:e,inferenceMs:s}}return{output:{entities:u},inferenceMs:s}}async runSample(e){const t=performance.now();if("string"!=typeof e.text)return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:"response from processing sample"};try{return await this.runInference({text:e.text,labels:e.labels,threshold:e.threshold,usecase:e.usecase??"ner",schema:e.schema,mask:e.mask,categories:e.categories}),{ok:!0,processingTimeMs:Math.round(performance.now()-t),error:!1,errorMessage:void 0}}catch(e){return{ok:!1,processingTimeMs:Math.round(performance.now()-t),error:!0,errorMessage:e instanceof Error?e.message:String(e)}}}}const Pe=async(e,t,r)=>{const n=E();try{await N()}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`transformers_runtime_load_failed:${t}`)}const o=C(W(e.modelUrl,e.modelRepoId)),s=O(e.modelUrl||"")?(e.modelUrl||"").trim():(e.modelRepoId||e.modelUrl||"").trim();if(!s)throw new Error("[Transformers] Invalid modelSource: expected non-empty modelRepoId or modelUrl");const a=await te(async()=>{const a=U(),i=a.TransformersEnv||{};i.allowRemoteModels=!0,i.allowLocalModels=!0,i.backends||(i.backends={}),i.backends.onnx||(i.backends.onnx={}),i.backends.onnx.wasm||(i.backends.onnx.wasm={}),i.backends.onnx.wasm.proxy=!1,i.backends.onnx.wasm.numThreads=1;const l=globalThis.fetch.bind(globalThis),c=await Y(l);c&&(i.backends.onnx.wasm.wasmPaths=c),i.fetch=ne(e.modelId,o,t,r,(e.requiredFiles??[]).map(e=>e.name),l),a.TransformersEnv=i,globalThis.fetch=i.fetch;try{return await A(()=>{const t=a.TransformersPipeline;if(!t)throw new Error("transformers_pipeline_unavailable");return t("token-classification",s,{device:"wasm",quantized:e.quantized,aggregation_strategy:"simple",progress_callback:()=>{}})})}catch(e){const t=e instanceof Error?e.message:String(e);throw n.warn("[Transformers] token-classification pipeline load failed",{message:t}),new Error(`transformers_pipeline_load_failed:${t}`)}finally{globalThis.fetch=l}}),{result:i,ms:l}=a;return{pipeline:i,loadModelMs:l}},je="transformers_runtime_load_failed",Ie=e=>{if(void 0===e)return;if(e instanceof Error)return{error:x(e)};const t={};for(const[r,n]of Object.entries(e))t[r]=n instanceof Error?x(n):n;return t},Be=e=>{const t=e instanceof Error?e.name:"Error",r=e instanceof Error?e.message:String(e),n={name:t,message:r},o=e?.code;return"string"==typeof o?n.code=o:r.startsWith(je)&&(n.code=je),n};((e,t)=>{const r=new Map,n=t=>e.postMessage(t),o=e=>{const t=r.get(e);if(!t)throw new Error("worker_model_not_loaded");return t},s=async e=>{switch(e.type){case"init":{const{config:t}=e;return((e,t)=>{S=new T(e,t)})({enableConsoleLogs:t.logging.enabled,locationData:!1,events:!1},(e,t,r)=>n({type:"log",level:e,message:t,fields:Ie(r)})),t.logging.enabled||"undefined"!=typeof document||(()=>{const e=()=>{};console.log=e,console.info=e,console.debug=e,console.warn=e,console.error=e})(),(e=>{const t={...m};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);m=t})(t.runtime),{protocol:1}}case"load":{const n=t[e.framework];if(!n)throw new Error(`worker_framework_unsupported:${e.framework}`);const o={},s=await n(e.slm,e.cachedFiles??{},(e,t)=>{o[e]=t},{wasm:e.wasm});r.set(e.handle,s);return{loadModelMs:s.loadModelMs,downloadedFiles:o}}case"infer":return o(e.handle).runInference(e.input);case"sample":return o(e.handle).runSample(e.sample);case"dispose":{const t=r.get(e.handle);return r.delete(e.handle),await(t?.dispose?.()),!0}default:throw new Error("worker_unknown_message")}};e.onmessage=e=>{const t=e?.data;t&&"object"==typeof t&&"number"==typeof t.id&&s(t).then(e=>n({type:"result",id:t.id,ok:!0,value:e}),e=>n({type:"result",id:t.id,ok:!1,error:Be(e)}))},n({type:"ready",protocol:1})})(self,{ONNX:async(e,t,r,n)=>{const o=await $e(e,t,r,n);return new Le(e,o)},Transformers:async(e,t,r)=>{const n=await Pe(e,t,r);return new qe(n)}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var ZeroGpuBackground=function(e){"use strict";const t="zerogpu:consent",
|
|
1
|
+
var ZeroGpuBackground=function(e){"use strict";const t="zerogpu:consent",r={optedIn:!0,updatedAt:null,source:"default"},n=()=>"undefined"!=typeof chrome?chrome?.storage?.local:void 0,o=e=>{if(!e||"object"!=typeof e)return r;const t=e;return"boolean"!=typeof t.optedIn?r:{optedIn:t.optedIn,updatedAt:"string"==typeof t.updatedAt?t.updatedAt:null,source:"extension"===t.source||"settings-page"===t.source||"default"===t.source?t.source:"default"}},s=async()=>{const e=n();if(!e)return r;try{const r=await e.get(t);return o(r?.[t])}catch{return r}},a=async(e,r)=>{const o={optedIn:e,updatedAt:(new Date).toISOString(),source:r},s=n();if(!s)throw new Error("chrome.storage.local unavailable — consent was not saved");return await s.set({[t]:o}),o};let i=Promise.resolve();const c=(e,t="extension")=>{const r=i.then(()=>a(e,t),()=>a(e,t));return i=r.catch(()=>{}),r},u=e=>{const r="undefined"!=typeof chrome?chrome?.storage?.onChanged:void 0;if(!r?.addListener)return()=>{};const n=(r,n)=>{if("local"!==n)return;const s=r?.[t];s&&e(o(s.newValue))};return r.addListener(n),()=>r.removeListener?.(n)},d="https://zerogpu.ai/extension-settings";class l extends Error{constructor(e,t,r){super(t),this.name="ZeroGpuError",this.code=e,void 0!==r&&(this.cause=r)}}class p extends l{constructor(e,t){super(`not_contributing_${e}`,`not contributing: ${e}${t?` (${t})`:""}`),this.name="NotContributingError",this.state=e,t&&(this.registryReason=t)}}class g extends l{constructor(e,t){super("model_not_eligible",`${e} is not eligible here: ${t}`),this.name="ModelNotEligibleError",this.modelId=e,this.reason=t}}class f extends l{constructor(e,t){super("inference_failed",e,t),this.name="LocalInferenceFailedError"}}const h={ping:"zerogpu:ping",getConsent:"zerogpu:getConsent",setConsent:"zerogpu:setConsent"},m="zerogpu:getContribution",w="zerogpu:eligibleModels",y="zerogpu:switchModel",E="zerogpu:runLocal",b="zerogpu:clearModelChoice",I="zerogpu:forgetUnfitModel",G=["https://zerogpu.ai","https://www.zerogpu.ai"],C="offscreen.html",Z=()=>"undefined"!=typeof chrome?chrome:void 0;let M=null;const L=e=>{const t=Z()?.runtime;return t?.getURL?t.getURL(e):e},v=async e=>{const t=Z()?.runtime;if(!t?.getContexts)return!1;try{const r=await t.getContexts({contextTypes:["OFFSCREEN_DOCUMENT"],documentUrls:[L(e)]});return Array.isArray(r)&&r.length>0}catch{return!1}},S=async(e={})=>{const t=e.offscreenPath??C,r=Z();if(!r?.offscreen?.createDocument)return!1;if(!(await s()).optedIn)return!1;if(await v(t))return!0;M||(M=r.offscreen.createDocument({url:t,reasons:e.offscreenReasons??["WORKERS"],justification:e.justification??"Run the ZeroGPU SDK, which requires a window/DOM context."}).finally(()=>{M=null}));try{return await M,!0}catch{return v(t)}},_=async(e={})=>{const t=e.offscreenPath??C,r=Z();if(r?.offscreen?.closeDocument&&await v(t)){try{await(r.runtime?.sendMessage?.({type:"zerogpu:disable"}))}catch{}try{await r.offscreen.closeDocument()}catch{}}},O=async(e,t)=>{const r=Z()?.runtime;if(!r?.sendMessage)throw new p("stopped");if(!await S(t))throw new p("stopped");let n;try{n=await r.sendMessage(e)}catch{throw new p("stopped")}if(!n)throw new p("stopped");if(n.ok)return n.result;throw"NotContributingError"===(o=n.error).name&&o.state?new p(o.state,o.registryReason):"ModelNotEligibleError"===o.name&&o.modelId?new g(o.modelId,o.reason??"not_eligible"):"LocalInferenceFailedError"===o.name?new f(o.message):new l(o.code||"error",o.message);var o};let x=Promise.resolve();const z=async(e,t)=>{e.optedIn?await S(t):await _(t)},P=(e,t={})=>(x=x.then(()=>z(e,t),()=>z(e,t)),x),R=async(e={})=>{await P(await s(),e)},U=async(e,t,r)=>{switch(e.type){case h.ping:return{ok:!0,installed:!0,extensionId:Z()?.runtime?.id};case h.getConsent:return{ok:!0,consent:await s()};case h.setConsent:{if("boolean"!=typeof e.optedIn)return{ok:!1,error:"optedIn must be a boolean"};const n=await c(e.optedIn,t);return await P(n,r),{ok:!0,consent:n}}default:return{ok:!1,error:"unsupported message"}}};return e.DEFAULT_ALLOWED_ORIGINS=G,e.DEFAULT_CONSENT=r,e.LocalInferenceFailedError=f,e.ModelNotEligibleError=g,e.NotContributingError=p,e.ZEROGPU_BRIDGE_MESSAGES=h,e.ZEROGPU_CONSENT_KEY=t,e.ZEROGPU_SETTINGS_BASE_URL=d,e.ZeroGpuError=l,e.applyZeroGpuConsent=P,e.buildZeroGpuSettingsUrl=({extensionId:e,appName:t,baseUrl:r=d,debug:n=!1})=>{const o=new URL(r);return o.searchParams.set("browser","chrome"),o.searchParams.set("extension_id",e),t&&o.searchParams.set("app_name",t),n&&o.searchParams.set("debug_mode","true"),o.toString()},e.clearZeroGpuModelChoice=(e={})=>O({type:b},e),e.ensureZeroGpuOffscreen=S,e.forgetZeroGpuUnfitModel=(e,t={})=>O({type:I,modelId:e},t),e.getZeroGpuConsent=s,e.getZeroGpuContribution=async(e={})=>{try{return await O({type:m},e)}catch{return{contributionState:"stopped",activeModelId:null,status:"shutdown",deviceId:null}}},e.getZeroGpuEligibleModels=(e={})=>O({type:w},e),e.isZeroGpuError=e=>e instanceof l||e instanceof Error&&"string"==typeof e.code,e.isZeroGpuOptedIn=async()=>(await s()).optedIn,e.onZeroGpuConsentChanged=u,e.onZeroGpuEvent=e=>{const t=Z()?.runtime;t?.onMessage?.addListener(t=>{if(!t||"object"!=typeof t)return;const r=t;if("zerogpu:event"===r.type&&"string"==typeof r.event)try{e({event:r.event,detail:r.detail&&"object"==typeof r.detail?r.detail:{}})}catch{}})},e.registerZeroGpuConsentBridge=(e={})=>{const t=Z(),r=t?.runtime;if(!r)return;const n=e.allowedOrigins??G;r.onMessageExternal?.addListener((t,r,o)=>{if(r?.origin&&n.includes(r.origin)){if(t&&"object"==typeof t)return U(t,"settings-page",e).then(o).catch(e=>o({ok:!1,error:e instanceof Error?e.message:String(e)})),!0;o({ok:!1,error:"bad message"})}else o({ok:!1,error:"origin not allowed"})}),r.onMessage?.addListener((t,r,n)=>{if(!t||"object"!=typeof t)return;const o=t;return Object.values(h).includes(o.type)?(U(o,"extension",e).then(n).catch(e=>n({ok:!1,error:e instanceof Error?e.message:String(e)})),!0):void 0}),u(t=>{P(t,e)}),r.onInstalled?.addListener(()=>{R(e)}),r.onStartup?.addListener(()=>{R(e)})},e.runZeroGpuLocal=(e,t={})=>O({type:E,input:e},t),e.setZeroGpuConsent=c,e.setZeroGpuCustomParams=async(e,t={})=>{const r=t.offscreenPath??C,n=Z()?.runtime;if(!n?.sendMessage||!await v(r))return!1;try{const t=await n.sendMessage({type:"zerogpu:setCustomParams",customParams:e});return!0===t?.ok}catch{return!1}},e.startZeroGpuIfConsented=R,e.stopZeroGpuOffscreen=_,e.switchZeroGpuModel=(e,t={})=>O({type:y,modelId:e},t),e}({});
|