@zerogpu/browser-extension-sdk 0.5.1 → 0.6.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 +99 -41
- package/bin/browser-extension-sdk.mjs +23 -0
- package/bin/cli.mjs +781 -0
- package/bin/herogpu.mjs +6 -0
- package/bin/zerogpu.mjs +6 -585
- package/dist/assets/herogpu-assets.json +21 -0
- package/dist/assets/herogpu-worker.js +1 -0
- package/dist/assets/zerogpu-assets.json +2 -2
- package/dist/assets/zerogpu-worker.js +1 -1
- package/dist/extension/herogpu-background.js +1 -0
- package/dist/extension/herogpu-offscreen.js +1 -0
- package/dist/extension/herogpu-settings-link.js +1 -0
- package/dist/extension/zerogpu-background.js +1 -1
- package/dist/extension/zerogpu-offscreen.js +1 -1
- package/dist/extension/zerogpu-settings-link.js +1 -1
- package/dist/herogpu-browser-sdk.cjs +1 -0
- package/dist/herogpu-browser-sdk.esm.js +1 -0
- package/dist/herogpu-browser-sdk.umd.js +1 -0
- package/dist/herogpu-worker.js +1 -0
- package/dist/loader.js +1 -1
- package/dist/manifest.json +5 -5
- package/dist/types/appinference/store.d.ts +6 -2
- package/dist/types/appinference/types.d.ts +29 -10
- package/dist/types/branding.d.ts +27 -0
- package/dist/types/config/types.d.ts +1 -1
- package/dist/types/extension/background.d.ts +68 -19
- package/dist/types/extension/consent.d.ts +61 -10
- package/dist/types/extension/offscreen.d.ts +64 -23
- package/dist/types/extension/settings-link.d.ts +12 -1
- package/dist/types/inference/runtime-locator.d.ts +1 -1
- package/dist/types/inference/worker-host.d.ts +1 -1
- package/dist/types/loader.d.ts +15 -3
- package/dist/types/public-api.d.ts +16 -10
- package/dist/types/runtime/app-identity.d.ts +2 -2
- package/dist/types/runtime/app-inference.d.ts +1 -1
- package/dist/types/runtime/custom-params.d.ts +1 -1
- package/dist/types/runtime/host-api.d.ts +2 -1
- package/dist/types/runtime/init-guard.d.ts +2 -1
- package/dist/types/runtime/tracking-script.d.ts +1 -1
- package/dist/types/storage/adopted-key.d.ts +23 -0
- package/dist/types/storage/cached-model.d.ts +4 -1
- package/dist/types/storage/model-store.d.ts +6 -0
- package/dist/types/transport/protocol.d.ts +1 -1
- package/dist/v/herogpu-browser-sdk.a957716b164a.umd.js +1 -0
- package/dist/v/zerogpu-browser-sdk.a957716b164a.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-side-inference.md +55 -45
- package/docs/auto-update-loader.md +33 -19
- package/docs/extension-developer-guide.md +158 -75
- package/docs/multi-model-support.md +14 -14
- package/package.json +13 -10
- package/dist/v/zerogpu-browser-sdk.686affbdf19f.umd.js +0 -1
package/dist/zerogpu-worker.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
+
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("[herogpu]",v(r)):t("[herogpu]",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",R=()=>globalThis,z=e=>{e&&(e.useBrowserCache=!1)};let N=null;const U=()=>{const e=R();if(e.TransformersPipeline)return Promise.resolve();if(!N){const t=E(),r=d().transformersUrl;N=(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,z(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 N=null,t.error("[SLM] Failed to import Transformers runtime",{runtimeUrl:r,error:x(e)}),e}})()}return N},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)}`,K=()=>{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}},G=[0,97,115,109],Z=["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>=G.length&&G.every((t,r)=>e[r]===t);let V=null;const Y=e=>(V||(V=(async e=>{const t=[d().wasmPaths,K(),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 Z){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 U()}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=R(),f=c.TransformersEnv||{};f.allowRemoteModels=!0,f.allowLocalModels=!0,z(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=R().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 U()}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=R(),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,6 +1,6 @@
|
|
|
1
1
|
# Browser SDK 0.5.0: run the model in your own page or extension
|
|
2
2
|
|
|
3
|
-
0.5.0 adds **app-side inference**. The model a device already holds for the
|
|
3
|
+
0.5.0 adds **app-side inference**. The model a device already holds for the herogpu network can
|
|
4
4
|
now also answer requests from your own page or Chrome extension, on the device. You can also
|
|
5
5
|
choose which model the device holds. The same feature shipped in the Android SDK 0.4.0; the
|
|
6
6
|
protocol and the registry side are shared.
|
|
@@ -10,6 +10,11 @@ methods.
|
|
|
10
10
|
|
|
11
11
|
0.5.0 also changes how the SDK recovers from a guardrail stop; see [section 8](#8-recovery-after-a-guardrail-stop).
|
|
12
12
|
|
|
13
|
+
herogpu is the new name of ZeroGPU. This guide uses the herogpu names. Every name it had under
|
|
14
|
+
ZeroGPU (`initZeroGpuSdk`, `ZeroGpuBackground.runZeroGpuLocal`, `zerogpu:activeModelChanged`, …)
|
|
15
|
+
still works and means the same thing; the list is in
|
|
16
|
+
[Coming from ZeroGPU](../README.md#coming-from-zerogpu).
|
|
17
|
+
|
|
13
18
|
**Contents**
|
|
14
19
|
|
|
15
20
|
1. [How it works](#1-how-it-works)
|
|
@@ -26,14 +31,14 @@ methods.
|
|
|
26
31
|
|
|
27
32
|
## 1. How it works
|
|
28
33
|
|
|
29
|
-
Each device running the SDK holds **one model at a time**. Until 0.5.0 only the
|
|
34
|
+
Each device running the SDK holds **one model at a time**. Until 0.5.0 only the herogpu network
|
|
30
35
|
sent work to it. Now your own code can send work to the same model:
|
|
31
36
|
|
|
32
37
|
```mermaid
|
|
33
38
|
flowchart LR
|
|
34
|
-
net["
|
|
39
|
+
net["herogpu network"] -- "network tasks" --> model
|
|
35
40
|
app["Your page or extension"] -- "runLocal(input)" --> model
|
|
36
|
-
subgraph device["The device, inside the
|
|
41
|
+
subgraph device["The device, inside the herogpu SDK"]
|
|
37
42
|
model["Active model<br/>one call at a time"]
|
|
38
43
|
end
|
|
39
44
|
```
|
|
@@ -41,9 +46,9 @@ flowchart LR
|
|
|
41
46
|
- **The input stays on the device.** `runLocal` runs the model in the page (in the SDK's inference
|
|
42
47
|
worker) and returns the result. No request goes to a server for it.
|
|
43
48
|
- **It is not an offline mode.** Local calls work only while the device is *contributing*: registered
|
|
44
|
-
with
|
|
49
|
+
with herogpu, model loaded, session acknowledged. In any other state `runLocal` throws, so keep a
|
|
45
50
|
fallback.
|
|
46
|
-
- **
|
|
51
|
+
- **herogpu picks a default model.** You don't know in advance which one a device gets. If your
|
|
47
52
|
feature needs a specific model, switch to it with `switchModel`. The device then also serves
|
|
48
53
|
network tasks for that model.
|
|
49
54
|
- **One model at a time.** Every change is a switch: a few seconds when the model is already
|
|
@@ -53,8 +58,8 @@ Where the SDK runs decides how you reach it:
|
|
|
53
58
|
|
|
54
59
|
| Surface | Where the SDK runs | How your code calls it |
|
|
55
60
|
|---|---|---|
|
|
56
|
-
| Website, web app, Telegram mini app | the page | the handle from `
|
|
57
|
-
| Chrome extension (MV3) | the offscreen document | `
|
|
61
|
+
| Website, web app, Telegram mini app | the page | the handle from `initHeroGpuSdk()`, or `getHeroGpuSdk()` |
|
|
62
|
+
| Chrome extension (MV3) | the offscreen document | `HeroGpuBackground.*` helpers from the service worker, popup or options page (they send `chrome.runtime` messages to the offscreen document) |
|
|
58
63
|
|
|
59
64
|
## 2. What you can build with it
|
|
60
65
|
|
|
@@ -78,9 +83,9 @@ small chat models), so you know what to send when such a model is added.
|
|
|
78
83
|
### Website
|
|
79
84
|
|
|
80
85
|
```ts
|
|
81
|
-
import {
|
|
86
|
+
import { initHeroGpuSdk, getHeroGpuSdk } from '@herogpu/browser-extension-sdk';
|
|
82
87
|
|
|
83
|
-
const sdk = await
|
|
88
|
+
const sdk = await initHeroGpuSdk({ edgeOperatorKey: 'zgpu-sdk-your-key' });
|
|
84
89
|
|
|
85
90
|
sdk.on('activeModelChanged', ({ modelId }) => {
|
|
86
91
|
// runLocal works from here (also fires after every switch)
|
|
@@ -96,15 +101,16 @@ the core bundle loaded:
|
|
|
96
101
|
```html
|
|
97
102
|
<script async src="https://js-sdk.zerogpu.ai/dist/loader.js" edgeOperatorKey="zgpu-sdk-your-key"></script>
|
|
98
103
|
<script>
|
|
99
|
-
|
|
100
|
-
const sdk =
|
|
101
|
-
window.addEventListener('
|
|
104
|
+
HeroGpuSdk.ready.then(() => {
|
|
105
|
+
const sdk = HeroGpuSdk.getHeroGpuSdk();
|
|
106
|
+
window.addEventListener('herogpu:activeModelChanged', (e) => console.log('model', e.detail.modelId));
|
|
102
107
|
});
|
|
103
108
|
</script>
|
|
104
109
|
```
|
|
105
110
|
|
|
106
|
-
Every event also reaches `window` as `
|
|
107
|
-
`degraded`, `recovered`, `shutdown`).
|
|
111
|
+
Every event also reaches `window` as `herogpu:<event>` (`activeModelChanged`, `modelChoiceRefused`,
|
|
112
|
+
`degraded`, `recovered`, `shutdown`). The same event is dispatched as `zerogpu:<event>` too, for
|
|
113
|
+
pages written before the rename, so listen under one prefix only.
|
|
108
114
|
|
|
109
115
|
### Chrome extension
|
|
110
116
|
|
|
@@ -113,13 +119,13 @@ the background bundle you already vendor:
|
|
|
113
119
|
|
|
114
120
|
```js
|
|
115
121
|
// background.js (service worker), popup.js or options.js — after
|
|
116
|
-
// importScripts("vendor/
|
|
117
|
-
const { contributionState, activeModelId } = await
|
|
118
|
-
const models = await
|
|
119
|
-
const outcome = await
|
|
120
|
-
const result = await
|
|
122
|
+
// importScripts("vendor/herogpu/herogpu-background.js") or <script src="…/herogpu-background.js">
|
|
123
|
+
const { contributionState, activeModelId } = await HeroGpuBackground.getHeroGpuContribution();
|
|
124
|
+
const models = await HeroGpuBackground.getHeroGpuEligibleModels();
|
|
125
|
+
const outcome = await HeroGpuBackground.switchHeroGpuModel('zlm-v1-moderation-edge');
|
|
126
|
+
const result = await HeroGpuBackground.runHeroGpuLocal({ text: 'some text', top_k: 14 });
|
|
121
127
|
|
|
122
|
-
|
|
128
|
+
HeroGpuBackground.onHeroGpuEvent(({ event, detail }) => {
|
|
123
129
|
// activeModelChanged, modelChoiceRefused, degraded, recovered, shutdown
|
|
124
130
|
});
|
|
125
131
|
```
|
|
@@ -136,8 +142,8 @@ work only in `contributing`.
|
|
|
136
142
|
```mermaid
|
|
137
143
|
stateDiagram-v2
|
|
138
144
|
[*] --> stopped
|
|
139
|
-
stopped --> registering:
|
|
140
|
-
registering --> declined:
|
|
145
|
+
stopped --> registering: initHeroGpuSdk(), or a guardrail restart
|
|
146
|
+
registering --> declined: herogpu declines the device
|
|
141
147
|
declined --> registering: retry
|
|
142
148
|
registering --> preparing: model assigned
|
|
143
149
|
preparing --> registering: warm-up failed
|
|
@@ -149,11 +155,11 @@ stateDiagram-v2
|
|
|
149
155
|
contributing --> stopped: guardrail stop, or shutdown()
|
|
150
156
|
```
|
|
151
157
|
|
|
152
|
-
### 4.1 From `
|
|
158
|
+
### 4.1 From `initHeroGpuSdk` to ready
|
|
153
159
|
|
|
154
160
|
```mermaid
|
|
155
161
|
flowchart TD
|
|
156
|
-
A["
|
|
162
|
+
A["initHeroGpuSdk()"] --> R["Register with herogpu<br/>state registering"]
|
|
157
163
|
R -- declined --> D["state declined<br/>retries later, see 4.5"]
|
|
158
164
|
D -- retry --> R
|
|
159
165
|
R -- "model assigned: your remembered choice<br/>if still allowed, else the default" --> P["Download the model, first time only<br/>state preparing"]
|
|
@@ -164,7 +170,7 @@ flowchart TD
|
|
|
164
170
|
C --> E["activeModelChanged(modelId)<br/>runLocal works from here"]
|
|
165
171
|
```
|
|
166
172
|
|
|
167
|
-
`
|
|
173
|
+
`initHeroGpuSdk` resolves after this whole flow (or after it failed cleanly). The first start
|
|
168
174
|
downloads the model (25–200 MB), so it can take a while on a slow connection; later starts take
|
|
169
175
|
seconds because the files are cached.
|
|
170
176
|
|
|
@@ -173,8 +179,8 @@ seconds because the files are cached.
|
|
|
173
179
|
```mermaid
|
|
174
180
|
sequenceDiagram
|
|
175
181
|
participant App as Your code
|
|
176
|
-
participant SDK as
|
|
177
|
-
participant ZG as
|
|
182
|
+
participant SDK as herogpu SDK
|
|
183
|
+
participant ZG as herogpu
|
|
178
184
|
App->>SDK: switchModel(modelId)
|
|
179
185
|
SDK->>SDK: check the eligible list
|
|
180
186
|
alt not on the list, or not eligible
|
|
@@ -183,11 +189,11 @@ sequenceDiagram
|
|
|
183
189
|
SDK->>SDK: save the choice (survives reloads), state switching
|
|
184
190
|
SDK->>SDK: let the network task in flight finish, close the session, unload the model
|
|
185
191
|
SDK->>ZG: register, asking for modelId
|
|
186
|
-
alt
|
|
192
|
+
alt herogpu refuses it
|
|
187
193
|
ZG-->>SDK: the default model and the reason
|
|
188
194
|
SDK->>SDK: prepare the default model, open the session
|
|
189
195
|
SDK-->>App: granted = false, reason
|
|
190
|
-
else
|
|
196
|
+
else herogpu grants it
|
|
191
197
|
ZG-->>SDK: modelId
|
|
192
198
|
SDK->>SDK: download if not cached, load, warm up
|
|
193
199
|
alt warm-up fails
|
|
@@ -219,7 +225,7 @@ flowchart TD
|
|
|
219
225
|
A["runLocal(input)"] --> B{"state contributing?"}
|
|
220
226
|
B -- no --> X1["throws NotContributingError(state)"]
|
|
221
227
|
B -- yes --> K{"text within the model's<br/>catalog cap (maxTokens)?"}
|
|
222
|
-
K -- no --> X3["throws
|
|
228
|
+
K -- no --> X3["throws HeroGpuError(input_too_large)"]
|
|
223
229
|
K -- yes --> Q{"Network task running?"}
|
|
224
230
|
Q -- yes --> W["Wait for it to finish, counted in result.queueWaitMs<br/>new network tasks are declined meanwhile"]
|
|
225
231
|
Q -- no --> M["Run the active model on your input"]
|
|
@@ -240,14 +246,14 @@ flowchart TD
|
|
|
240
246
|
|---|---|
|
|
241
247
|
| Page reload / extension restart | The SDK registers again with your remembered choice. The model is still cached, so it is ready in seconds. |
|
|
242
248
|
| 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
|
|
249
|
+
| `clearModelChoice()` | The next register takes herogpu's default model again. |
|
|
244
250
|
|
|
245
251
|
### 4.5 When something goes wrong
|
|
246
252
|
|
|
247
253
|
| Situation | What the SDK does | What you see | What to do |
|
|
248
254
|
|---|---|---|---|
|
|
249
|
-
|
|
|
250
|
-
|
|
|
255
|
+
| herogpu 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 |
|
|
256
|
+
| herogpu 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
257
|
| 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
258
|
| Low memory | Stops taking work and frees memory until the pressure drops | State `degraded`, `degraded` event, then `recovered` | Retry later |
|
|
253
259
|
| 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 |
|
|
@@ -256,12 +262,12 @@ flowchart TD
|
|
|
256
262
|
## 5. Each call, with examples
|
|
257
263
|
|
|
258
264
|
The examples use the website handle. In an extension, the same calls are
|
|
259
|
-
`
|
|
260
|
-
`
|
|
265
|
+
`HeroGpuBackground.getHeroGpuEligibleModels()`, `switchHeroGpuModel(id)`, `runHeroGpuLocal(input)`,
|
|
266
|
+
`clearHeroGpuModelChoice()`, `forgetHeroGpuUnfitModel(id)` and `getHeroGpuContribution()`.
|
|
261
267
|
|
|
262
268
|
### `eligibleModels()`: which models this device may hold
|
|
263
269
|
|
|
264
|
-
Asks
|
|
270
|
+
Asks herogpu to judge every model of this surface's list for this device, with the same rules it
|
|
265
271
|
uses at register time, then adds what only the device knows (downloaded, active). It downloads
|
|
266
272
|
nothing and works in any state, but it needs a network connection. The answer is a snapshot
|
|
267
273
|
(battery and connection change), so ask again before you show it.
|
|
@@ -358,8 +364,8 @@ statusLabel.textContent = onDevice ? 'Checked on this device' : 'Checked in the
|
|
|
358
364
|
| State | Meaning | `runLocal` |
|
|
359
365
|
|---|---|---|
|
|
360
366
|
| `stopped` | Not started, stopped by `shutdown()`, or parked after a guardrail stop | throws |
|
|
361
|
-
| `registering` | Registering with
|
|
362
|
-
| `declined` |
|
|
367
|
+
| `registering` | Registering with herogpu, or waiting to retry | throws |
|
|
368
|
+
| `declined` | herogpu declined this device for now | throws (with `registryReason`) |
|
|
363
369
|
| `preparing` | Downloading, loading or warming up the model, or waiting for the session ack | throws |
|
|
364
370
|
| `switching` | A switch is in progress | throws |
|
|
365
371
|
| `degraded` | Low memory, paused | throws |
|
|
@@ -372,7 +378,7 @@ the events.
|
|
|
372
378
|
### `clearModelChoice()` and `forgetUnfitModel(modelId)`
|
|
373
379
|
|
|
374
380
|
```ts
|
|
375
|
-
sdk.clearModelChoice(); // the next register takes
|
|
381
|
+
sdk.clearModelChoice(); // the next register takes herogpu's default model
|
|
376
382
|
sdk.forgetUnfitModel('zlm-v1-signal-extract'); // let a model that failed its warm-up here be tried again
|
|
377
383
|
```
|
|
378
384
|
|
|
@@ -388,7 +394,7 @@ and retries on the registry's schedule.
|
|
|
388
394
|
| Event | When |
|
|
389
395
|
|---|---|
|
|
390
396
|
| `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
|
|
397
|
+
| `modelChoiceRefused` `{ modelId, reason }` | **New.** Your remembered choice was not kept (refused by herogpu, or `warmup_failed:<reason>`). The choice is cleared and the device holds the default model. |
|
|
392
398
|
| `degraded` / `recovered` | Low memory pauses work / work resumes |
|
|
393
399
|
| `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
400
|
|
|
@@ -430,7 +436,7 @@ await sdk.runLocal({ text: 'indeed.com | job search jobs careers hiring employme
|
|
|
430
436
|
// { "content|Job Search": 0.99, "content|Careers": 0.95, "audience|Career Advice": 0.94, … }
|
|
431
437
|
```
|
|
432
438
|
|
|
433
|
-
The scores are raw; the
|
|
439
|
+
The scores are raw; the herogpu cloud applies tuned thresholds per category to the same scores.
|
|
434
440
|
0.5 is a reasonable starting point for your own.
|
|
435
441
|
|
|
436
442
|
### `seq2seq_generation`: text in, text out
|
|
@@ -502,9 +508,13 @@ same classes.
|
|
|
502
508
|
| `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
509
|
| `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
510
|
| `LocalInferenceFailedError` | `inference_failed` | The model failed on your input |
|
|
505
|
-
| `
|
|
506
|
-
| `
|
|
507
|
-
| `
|
|
511
|
+
| `HeroGpuError` | `input_too_large` | The text exceeds the model's catalog cap (`maxTokens`); nothing ran |
|
|
512
|
+
| `HeroGpuError` | `switch_superseded` | A newer `switchModel` call replaced this one |
|
|
513
|
+
| `HeroGpuError` | `timeout`, `network`, `http_<status>` | `eligibleModels` (or `switchModel`, which calls it) could not reach herogpu |
|
|
514
|
+
|
|
515
|
+
`HeroGpuError` is the base class of all of them (also exported as `ZeroGpuError`, the same class).
|
|
516
|
+
Its `name` is still the string `'ZeroGpuError'`: branch on `code`, or test with
|
|
517
|
+
`isHeroGpuError(error)` or `instanceof`, rather than on `name`.
|
|
508
518
|
|
|
509
519
|
## 8. Recovery after a guardrail stop
|
|
510
520
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Always‑Latest SDK Delivery (Auto‑Update Loader)
|
|
2
2
|
|
|
3
|
-
This document explains a change that makes apps using the
|
|
3
|
+
This document explains a change that makes apps using the herogpu Browser SDK
|
|
4
4
|
**always run the latest version automatically**, with zero ongoing effort from
|
|
5
5
|
the app's developers.
|
|
6
6
|
|
|
@@ -16,7 +16,7 @@ It is written in three parts:
|
|
|
16
16
|
|
|
17
17
|
### What is this SDK, in one paragraph?
|
|
18
18
|
|
|
19
|
-
The
|
|
19
|
+
The herogpu Browser SDK is a small piece of JavaScript that other companies
|
|
20
20
|
("apps") drop into their website. Once it's on a page, it quietly turns the
|
|
21
21
|
visitor's browser into a tiny AI worker that can run small tasks (like
|
|
22
22
|
summarizing text) on the visitor's own device. Apps add it with a single
|
|
@@ -151,13 +151,13 @@ App page ──embeds once──► /dist/loader.js (tiny, served fresh: sho
|
|
|
151
151
|
│ fetch
|
|
152
152
|
▼
|
|
153
153
|
/dist/manifest.json (tiny, served fresh)
|
|
154
|
-
│ { coreBundleUrl: "v/
|
|
154
|
+
│ { coreBundleUrl: "v/herogpu-browser-sdk.<hash>.umd.js", ... }
|
|
155
155
|
│ inject <script>
|
|
156
156
|
▼
|
|
157
|
-
/dist/v/
|
|
157
|
+
/dist/v/herogpu-browser-sdk.<hash>.umd.js (immutable, cached 1 year)
|
|
158
158
|
│
|
|
159
159
|
▼
|
|
160
|
-
autoInitFromScriptTag() →
|
|
160
|
+
autoInitFromScriptTag() → initHeroGpuSdk(...)
|
|
161
161
|
```
|
|
162
162
|
|
|
163
163
|
- **Entry points** (`loader.js`, `manifest.json`, unhashed alias) are served
|
|
@@ -179,15 +179,25 @@ The bootstrap stub. Dependency‑free and minified. Responsibilities:
|
|
|
179
179
|
`appUserId`, `deviceId`, `enableConsoleLogs`, …) from the loader tag
|
|
180
180
|
onto the injected core tag, so the existing `autoInitFromScriptTag()` path
|
|
181
181
|
works unchanged.
|
|
182
|
-
- Installs a **queueing stub** at `window.
|
|
183
|
-
programmatic `
|
|
182
|
+
- Installs a **queueing stub** at `window.HeroGpuSdk` (Segment‑style) so
|
|
183
|
+
programmatic `initHeroGpuSdk(...)` calls made before the core bundle loads are
|
|
184
184
|
replayed afterward, and exposes a `ready` promise.
|
|
185
185
|
- **Fallbacks / guards:** if a real SDK global is already present it does
|
|
186
186
|
nothing; if the manifest fetch fails it injects the stable unhashed bundle
|
|
187
|
-
(`
|
|
187
|
+
(`herogpu-browser-sdk.umd.js`); supports an optional per‑build `integrity`
|
|
188
188
|
(SRI) hash from the manifest.
|
|
189
|
-
- Exports `
|
|
189
|
+
- Exports `bootHeroGpuLoader(env)` (with injected `document`/`window`/`fetch`)
|
|
190
190
|
for unit testing, and auto‑runs against the real DOM when loaded as a script.
|
|
191
|
+
- **Both name spaces.** The SDK was called ZeroGPU until 0.5.1, and pages
|
|
192
|
+
written then use `window.ZeroGpuSdk`, `initZeroGpuSdk` and
|
|
193
|
+
`window.ZeroGpuBrowserSdk`. The loader installs the same stub under both
|
|
194
|
+
`HeroGpuSdk` and `ZeroGpuSdk`, with both method spellings, and the core
|
|
195
|
+
bundle sets both `HeroGpuBrowserSdk` and `ZeroGpuBrowserSdk` to one object.
|
|
196
|
+
A loader and a bundle of different releases also work together in either
|
|
197
|
+
combination: the loader takes the bundle address from the manifest, finds the
|
|
198
|
+
API under whichever global the bundle set, and replays a queued call under the
|
|
199
|
+
name that bundle has. If the manifest is unreachable it tries
|
|
200
|
+
`herogpu-browser-sdk.umd.js` and then `zerogpu-browser-sdk.umd.js`.
|
|
191
201
|
|
|
192
202
|
#### New: `sdk/src/sdk-version.ts`
|
|
193
203
|
|
|
@@ -212,9 +222,13 @@ flows to the orchestrator via the `/register` HTTP body and the WebSocket
|
|
|
212
222
|
|
|
213
223
|
Runs after Rollup. It:
|
|
214
224
|
|
|
215
|
-
- SHA‑256 hashes `dist/
|
|
216
|
-
- Writes the hashed copy to `dist/v/
|
|
225
|
+
- SHA‑256 hashes `dist/herogpu-browser-sdk.umd.js`, takes the first 12 hex chars.
|
|
226
|
+
- Writes the hashed copy to `dist/v/herogpu-browser-sdk.<hash>.umd.js` (with its
|
|
217
227
|
`sourceMappingURL` rewritten to the hashed map) plus the hashed `.map`.
|
|
228
|
+
- Writes every bundle a second time under the file name it had before the
|
|
229
|
+
rename (`dist/zerogpu-browser-sdk.*`, `dist/v/zerogpu-browser-sdk.<hash>.umd.js`):
|
|
230
|
+
identical bytes, so an embed or a download that names the earlier file keeps
|
|
231
|
+
working.
|
|
218
232
|
- Computes an SRI (`sha384-…`) over the served bytes.
|
|
219
233
|
- Writes `dist/manifest.json`:
|
|
220
234
|
`{ version, buildId, coreBundleUrl, integrity, builtAt }`.
|
|
@@ -228,7 +242,7 @@ Runs after Rollup. It:
|
|
|
228
242
|
Replaced the blanket `no-store` rule with tiered caching:
|
|
229
243
|
|
|
230
244
|
- `/dist/v/*` → `Cache-Control: public, max-age=31536000, immutable`.
|
|
231
|
-
- `/dist/loader.js`, `/dist/manifest.json`, `/dist/
|
|
245
|
+
- `/dist/loader.js`, `/dist/manifest.json`, `/dist/herogpu-browser-sdk.umd.js` →
|
|
232
246
|
`Cache-Control: public, max-age=0, s-maxage=30, stale-while-revalidate=300,
|
|
233
247
|
stale-if-error=86400`.
|
|
234
248
|
- Existing CORS + `Content-Type` rules preserved; `manifest.json` also gets CORS
|
|
@@ -311,7 +325,7 @@ cat dist/manifest.json
|
|
|
311
325
|
|
|
312
326
|
- `dist/` contains `loader.js`, `loader.js.map`, `manifest.json`, the three core
|
|
313
327
|
bundles (`.esm.js` / `.umd.js` / `.cjs`) and their maps, and a `v/` folder.
|
|
314
|
-
- `dist/v/` contains exactly one `
|
|
328
|
+
- `dist/v/` contains exactly one `herogpu-browser-sdk.<hash>.umd.js` and its
|
|
315
329
|
`.map`.
|
|
316
330
|
- `dist/manifest.json` looks like:
|
|
317
331
|
|
|
@@ -319,7 +333,7 @@ cat dist/manifest.json
|
|
|
319
333
|
{
|
|
320
334
|
"version": "0.1.0+<gitsha>",
|
|
321
335
|
"buildId": "<hash>",
|
|
322
|
-
"coreBundleUrl": "v/
|
|
336
|
+
"coreBundleUrl": "v/herogpu-browser-sdk.<hash>.umd.js",
|
|
323
337
|
"integrity": "sha384-...",
|
|
324
338
|
"builtAt": "..."
|
|
325
339
|
}
|
|
@@ -331,7 +345,7 @@ cat dist/manifest.json
|
|
|
331
345
|
**Confirm the version token was really injected** (not left as a placeholder):
|
|
332
346
|
|
|
333
347
|
```bash
|
|
334
|
-
grep -c "__SDK_VERSION__" dist/
|
|
348
|
+
grep -c "__SDK_VERSION__" dist/herogpu-browser-sdk.umd.js # expect 0
|
|
335
349
|
```
|
|
336
350
|
|
|
337
351
|
### B. Run the automated tests and lint
|
|
@@ -375,8 +389,8 @@ Open Chrome at **http://localhost:8000/** and open **DevTools → Network**
|
|
|
375
389
|
|
|
376
390
|
1. A request for **`loader.js`** succeeds.
|
|
377
391
|
2. A request for **`manifest.json`** succeeds and returns JSON pointing at
|
|
378
|
-
`v/
|
|
379
|
-
3. A request for **`/dist/v/
|
|
392
|
+
`v/herogpu-browser-sdk.<hash>.umd.js`.
|
|
393
|
+
3. A request for **`/dist/v/herogpu-browser-sdk.<hash>.umd.js`** succeeds — this
|
|
380
394
|
is the real SDK being injected by the loader.
|
|
381
395
|
4. The demo initializes and behaves exactly as before (use the page's UI to init
|
|
382
396
|
the SDK; watch the console logs and the `POST /register` request).
|
|
@@ -418,7 +432,7 @@ already‑loaded page pick it up **without editing the page**.
|
|
|
418
432
|
1. Stop the dev server (or rename `dist/manifest.json` so it 404s).
|
|
419
433
|
2. Reload the page.
|
|
420
434
|
3. **Expected:** the loader logs a warning that the manifest is unavailable and
|
|
421
|
-
falls back to loading `/dist/
|
|
435
|
+
falls back to loading `/dist/herogpu-browser-sdk.umd.js` directly — the app
|
|
422
436
|
still initializes. ✅ *Resilient to manifest outages.*
|
|
423
437
|
|
|
424
438
|
### F. (Optional) Verify production‑style caching headers
|
|
@@ -437,7 +451,7 @@ Then in DevTools → Network, click each asset and check **Response Headers →
|
|
|
437
451
|
|
|
438
452
|
- `loader.js` and `manifest.json` → `max-age=0, s-maxage=30,
|
|
439
453
|
stale-while-revalidate=300, stale-if-error=86400` (always fresh).
|
|
440
|
-
- `dist/v/
|
|
454
|
+
- `dist/v/herogpu-browser-sdk.<hash>.umd.js` → `max-age=31536000, immutable`
|
|
441
455
|
(cached hard; on a second reload it should be served "(from cache)").
|
|
442
456
|
|
|
443
457
|
---
|