@caldrix-ai/caldrix 0.0.0-stage → 0.2.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.
@@ -0,0 +1 @@
1
+ var o=["probe","fit","architecture","fetch","digest","validate","lowering","backend","request"];function d(n){return typeof n=="string"&&o.includes(n)}var e=class extends Error{kind;missing;constructor(i,t,r){super(t),this.name="CaldrixError",this.kind=i,r!==void 0&&(this.missing=r)}};function s(n){if(n instanceof e)return n;if(typeof n=="object"&&n!==null){let{kind:i,message:t}=n;if(typeof i=="string"&&o.includes(i)&&typeof t=="string")return new e(i,t)}return new e("backend",String(n))}function a(n){return new e("backend",`the WebGPU device failed (${n}); dispose this engine and load the model again`)}export{d as a,e as b,s as c,a as d};
@@ -0,0 +1,252 @@
1
+ /**
2
+ * The generation options, passed to the host as its camelCase JSON. Any other key reaches the host
3
+ * and is refused there by name; `signal` is the page's and never leaves the main thread.
4
+ */
5
+ interface GenerationOptions {
6
+ /**
7
+ * Restricts the text to a JSON value matching a schema (a documented subset; see the README) or to
8
+ * exactly one of some strings. A refusal is a `CaldrixError` of kind `request`.
9
+ */
10
+ constraint?: {
11
+ json: Record<string, unknown>;
12
+ } | {
13
+ oneOf: string[];
14
+ };
15
+ /** The number of top logprobs to return with each token, at most 20. */
16
+ logprobs?: number;
17
+ temperature?: number;
18
+ topK?: number;
19
+ topP?: number;
20
+ minP?: number;
21
+ repetitionPenalty?: number;
22
+ seed?: number;
23
+ maxTokens?: number;
24
+ }
25
+
26
+ /** The nine error kinds of the caldrix.js API (spec §5.4). */
27
+ type Kind = "probe" | "fit" | "architecture" | "fetch" | "digest" | "validate" | "lowering" | "backend" | "request";
28
+ declare class CaldrixError extends Error {
29
+ readonly kind: Kind;
30
+ /** Set by the Hub fetcher when the file is simply absent: not on the Hub (404) or not cached while offline. */
31
+ readonly missing?: "not-found" | "offline-uncached";
32
+ constructor(kind: Kind, message: string, missing?: "not-found" | "offline-uncached");
33
+ }
34
+
35
+ type ChatMessage = {
36
+ role: "system" | "user" | "assistant";
37
+ content: string;
38
+ };
39
+ /**
40
+ * Where one model file came from on this load, and whether its sha256 was checked against the Hub's
41
+ * `X-Linked-Etag` (§5.2): `verified: false` means the Hub sent no such header for it (a cached entry
42
+ * carries what was recorded when it was written).
43
+ */
44
+ interface FileSource {
45
+ source: "cache" | "network";
46
+ verified: boolean;
47
+ }
48
+ /**
49
+ * What the host's `doctor()` returns, plus the worker's facts about the tier it opened; `source` is
50
+ * the page's to fill. `backend` is the tier (`"wasm"` or `"webgpu"`).
51
+ */
52
+ interface HostDoctor {
53
+ backend: string;
54
+ device: string;
55
+ dtype: string | null;
56
+ simd: boolean;
57
+ threads: number | null;
58
+ model: string | null;
59
+ revision: string | null;
60
+ source: null;
61
+ line: string;
62
+ /** WebGPU only, the host's: the context the model was loaded at, and the clamp's line when the default was clamped. */
63
+ maxContext?: number;
64
+ contextClamp?: string | null;
65
+ /** The worker's: the weights' storage form on WebGPU (`null` on wasm). */
66
+ storage: "f16" | "f32" | null;
67
+ /**
68
+ * The worker's: the adapter by its own vendor and architecture strings (`null` on wasm). On
69
+ * WebGPU `device` is the worker's too: `webgpu (<description>)`, with vendor and architecture
70
+ * standing in for the description when the browser leaves it empty.
71
+ */
72
+ adapter: {
73
+ vendor: string;
74
+ architecture: string;
75
+ } | null;
76
+ /** The worker's, from the host's `listAliases`: every alias this build loads, by name and file format. */
77
+ aliases: {
78
+ name: string;
79
+ format: "safetensors" | "gguf";
80
+ }[];
81
+ }
82
+
83
+ interface LoadOptions {
84
+ backend?: "auto" | "webgpu" | "wasm" | "webgl";
85
+ offline?: boolean;
86
+ onProgress?: (p: {
87
+ file: string;
88
+ loaded: number;
89
+ total: number | null;
90
+ }) => void;
91
+ hubBaseUrl?: string;
92
+ dtype?: "f32" | "bf16";
93
+ maxContext?: number;
94
+ /**
95
+ * The WebGPU tier's weight storage: `"auto"` (the default) stores the block GEMM weights f16 when
96
+ * the adapter has `shader-f16`, `"f32"` keeps them f32 on any adapter. Under `backend: "auto"` a
97
+ * load the wasm tier serves ignores it; an explicit `backend: "wasm"` with `"f32"` is refused.
98
+ */
99
+ storage?: "auto" | "f32";
100
+ /**
101
+ * Cancels the load: before the model is loaded, an abort terminates the engine's worker (and every
102
+ * fetch in it) and the load rejects with `fetch`; an already-aborted signal rejects before the
103
+ * worker starts. After the load resolves the signal is ignored.
104
+ */
105
+ signal?: AbortSignal;
106
+ /**
107
+ * Where the package's own files come from. `worker` is the engine's worker script (default:
108
+ * `./worker.js` next to this module, i.e. `dist/worker.js`); `hostWasm` is the browser host's
109
+ * `.wasm` (default: `../host/caldrix_web_bg.wasm` next to the worker, i.e. `host/caldrix_web_bg.wasm`).
110
+ * A string, absolute or relative, is resolved against the page (`location.href`) on the main
111
+ * thread, not against the worker. A worker on another origin than the page's starts through a
112
+ * same-origin module shim that imports it, so that origin must serve the worker, its chunks,
113
+ * `host/` and the `.wasm` with CORS.
114
+ *
115
+ * The CDN fallback, on unless `fallback` is `false`: when the bundle's own copy fails, it is fetched
116
+ * from jsdelivr at this package's installed version (`cdn`, default
117
+ * `https://cdn.jsdelivr.net/npm/@caldrix-ai/caldrix@<version>/`), independently for each asset. The worker
118
+ * falls back when it fails before it is ready (its script, a chunk or the host glue
119
+ * `host/caldrix_web.js` did not load, or the page refused to construct it); a worker from the CDN
120
+ * then fetches its `.wasm` from the CDN as well. The `.wasm` falls back, inside the worker, when its
121
+ * fetch fails (a network error or a non-OK status). Every fallback is reported in `doctor().assets`
122
+ * and once per load on the console; it is never silent. An explicit `worker` or `hostWasm` is used
123
+ * as given, with no fallback for that asset.
124
+ */
125
+ assets?: {
126
+ worker?: string | URL;
127
+ hostWasm?: string | URL;
128
+ fallback?: boolean;
129
+ cdn?: string | URL;
130
+ };
131
+ }
132
+ interface Delta {
133
+ text: string;
134
+ /**
135
+ * The token id this delta carries. Absent only on the single `done` delta a generation yields when
136
+ * its signal was already aborted at the call: nothing reached the worker, so no token exists.
137
+ */
138
+ token?: number;
139
+ done: boolean;
140
+ finishReason?: "stop" | "length" | "abort";
141
+ /** Prompt tokens, generated tokens, and the prompt tokens served from the previous generation's context. */
142
+ usage?: {
143
+ promptTokens: number;
144
+ completionTokens: number;
145
+ cachedTokens: number;
146
+ };
147
+ /** The top logprobs for this token; present only when `logprobs` was asked for. */
148
+ logprobs?: {
149
+ token: number;
150
+ logprob: number;
151
+ }[];
152
+ }
153
+ /**
154
+ * The host's doctor object, with `source` filled per file: where it came from and whether its digest
155
+ * was checked. `backend` is the tier that runs; `why` is how it was chosen (the probe's reason under
156
+ * `"auto"`, so a fallback to wasm says why -- no adapter, a bf16 request, a quantized alias, or
157
+ * `webgpu refused: …` when the WebGPU precheck or device open refused a load the wasm tier then served).
158
+ * `aliases` is every alias this build loads, each with its file format.
159
+ */
160
+ interface DoctorReport extends Omit<HostDoctor, "source"> {
161
+ source: Record<string, FileSource>;
162
+ why: string;
163
+ /** Where the package's own files came from on this load (`LoadOptions.assets`). */
164
+ assets: {
165
+ worker: AssetSource;
166
+ hostWasm: AssetSource;
167
+ };
168
+ }
169
+ /**
170
+ * One of the package's own files: `bundle`, the default beside the bundle that imported caldrix.js;
171
+ * `cdn`, the CDN fallback (`assets.cdn`); `page`, a URL the page gave (`assets.worker` or
172
+ * `assets.hostWasm`, or the default `.wasm` beside a page-given worker). `url` is the one fetched.
173
+ */
174
+ interface AssetSource {
175
+ source: "bundle" | "cdn" | "page";
176
+ url: string;
177
+ }
178
+ type GenerateOptions = GenerationOptions & {
179
+ signal?: AbortSignal;
180
+ };
181
+ declare class Caldrix {
182
+ /** Load a model by alias into its own worker. */
183
+ static load(alias: string, opts?: LoadOptions): Promise<Engine>;
184
+ }
185
+ declare class Engine {
186
+ #private;
187
+ /** Use `Caldrix.load`. */
188
+ constructor(worker: Worker, report: DoctorReport);
189
+ chat(messages: ChatMessage[], opts?: GenerateOptions): AsyncIterable<Delta>;
190
+ complete(input: string | {
191
+ ids: number[];
192
+ }, opts?: GenerateOptions): AsyncIterable<Delta>;
193
+ doctor(): DoctorReport;
194
+ /** Release the worker and everything in it. Every later call throws `request`. */
195
+ dispose(): void;
196
+ }
197
+
198
+ type WasmFeature = "simd" | "relaxedSimd" | "bulkMemory" | "threads" | "memory64" | "tailCall" | "exceptions";
199
+ type WasmFeatures = Record<WasmFeature, boolean>;
200
+
201
+ interface WebGpuAdapter {
202
+ vendor: string;
203
+ architecture: string;
204
+ device: string;
205
+ description: string;
206
+ features: string[];
207
+ /** Every numeric limit as the browser gave it (one past `Number.MAX_SAFE_INTEGER` among them). */
208
+ limits: Record<string, number>;
209
+ /**
210
+ * The limits the host cannot read, each as `name = value (why)`: not a safe integer, or not a
211
+ * number. `hostProbeJson` leaves them out, so the host reports them as missing; `why` names them.
212
+ */
213
+ unrepresentable: string[];
214
+ }
215
+ interface Capabilities {
216
+ wasm: WasmFeatures;
217
+ threads: {
218
+ sharedArrayBuffer: boolean;
219
+ crossOriginIsolated: boolean;
220
+ hardwareConcurrency: number | null;
221
+ };
222
+ webgl: {
223
+ available: boolean;
224
+ maxTextureSize: number | null;
225
+ floatColorBuffer: boolean | null;
226
+ };
227
+ webgpu: WebGpuAdapter | null;
228
+ memory: {
229
+ deviceMemoryGiB: number | null;
230
+ };
231
+ tiers: {
232
+ webgpu: {
233
+ available: boolean;
234
+ built: true;
235
+ reason?: string;
236
+ };
237
+ webgl: {
238
+ available: boolean;
239
+ built: false;
240
+ reason: "not built";
241
+ };
242
+ wasm: {
243
+ available: true;
244
+ built: true;
245
+ };
246
+ };
247
+ chosen: "wasm" | "webgpu";
248
+ why: string;
249
+ }
250
+ declare function probe(): Promise<Capabilities>;
251
+
252
+ export { type AssetSource, Caldrix, CaldrixError, type Capabilities, type ChatMessage, type Delta, type DoctorReport, Engine, type GenerateOptions, type GenerationOptions, type Kind, type LoadOptions, probe };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{a as J,b as i,d as H}from"./chunk-PZGTLL5H.js";function v(e){return typeof e=="object"&&e!==null}function se(e){return v(e)&&typeof e.token=="number"&&typeof e.text=="string"&&typeof e.done=="boolean"&&(e.finishReason===null||e.finishReason==="stop"||e.finishReason==="length"||e.finishReason==="abort")&&typeof e.promptTokens=="number"&&typeof e.completionTokens=="number"&&typeof e.cachedTokens=="number"&&(e.logprobs===void 0||Array.isArray(e.logprobs)&&e.logprobs.every(t=>v(t)&&typeof t.token=="number"&&typeof t.logprob=="number"))}function ae(e){return!v(e)||typeof e.url!="string"?!1:e.failed===void 0||v(e.failed)&&typeof e.failed.url=="string"&&typeof e.failed.reason=="string"}function L(e){if(!v(e)||typeof e.id!="number")return!1;switch(e.type){case"ready":return e.id===0&&typeof e.url=="string";case"host":return ae(e.hostWasm);case"progress":return typeof e.file=="string"&&typeof e.loaded=="number"&&(e.total===null||typeof e.total=="number");case"loaded":return v(e.doctor)&&v(e.sources)&&(e.fallback===void 0||typeof e.fallback=="string")&&Object.values(e.sources).every(t=>v(t)&&(t.source==="cache"||t.source==="network")&&typeof t.verified=="boolean");case"delta":return se(e.delta);case"result":return"value"in e;case"error":return J(e.kind)&&typeof e.message=="string"&&(e.fatal===void 0||typeof e.fatal=="string");default:return!1}}function m(e){let t;try{t=JSON.stringify(e)??String(e)}catch{t=String(e)}return t.length>200&&(t=`${t.slice(0,200)}...`),new i("backend",`the worker sent a malformed message: ${t}`)}var x=(...e)=>new Uint8Array(e),ie={simd:x(0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11),relaxedSimd:x(0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,15,1,13,0,65,1,253,15,65,2,253,15,253,128,2,11),bulkMemory:x(0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11),threads:x(0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11),memory64:x(0,97,115,109,1,0,0,0,5,3,1,4,1),tailCall:x(0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,6,1,4,0,18,0,11),exceptions:x(0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,16,1,14,0,2,105,31,64,1,3,0,0,11,0,11,26,11)};function X(){let e={};for(let[t,r]of Object.entries(ie))e[t]=WebAssembly.validate(r);return e}var le=1e3,E=Symbol("timed out");async function K(e){let t,r=new Promise(n=>{t=setTimeout(()=>n(E),le)});try{return await Promise.race([e,r])}finally{clearTimeout(t)}}var z=e=>e instanceof Error?e.message:String(e);function V(){let e=globalThis.navigator;return typeof e=="object"&&e!==null?e:{}}function D(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ue(){let e={available:!1,maxTextureSize:null,floatColorBuffer:null};try{let t=null;if(typeof OffscreenCanvas<"u"?t=new OffscreenCanvas(1,1):typeof document<"u"&&(t=document.createElement("canvas")),t===null)return e;let r=t,n=r.getContext("webgl2"),o=n??r.getContext("webgl");if(!o)return e;let s=D(o.getParameter(o.MAX_TEXTURE_SIZE)),l=o.getExtension(n?"EXT_color_buffer_float":"WEBGL_color_buffer_float")!==null;return o.getExtension("WEBGL_lose_context")?.loseContext(),{available:!0,maxTextureSize:s,floatColorBuffer:l}}catch{return e}}async function de(e){let t=e.info??{};if(!e.info&&typeof e.requestAdapterInfo=="function")try{t=await e.requestAdapterInfo()}catch{t={}}let r={},n=[];if(e.limits)for(let o in e.limits){let s=e.limits[o];typeof s=="number"?(r[o]=s,Number.isSafeInteger(s)||n.push(`${o} = ${s} (not a safe integer)`)):typeof s!="function"&&n.push(`${o} = ${JSON.stringify(s)??String(s)} (not a number)`)}return{vendor:t.vendor??"",architecture:t.architecture??"",device:t.device??"",description:t.description??"",features:e.features?[...e.features]:[],limits:r,unrepresentable:n}}async function ce(){let e=V().gpu;if(!e||typeof e.requestAdapter!="function")return{webgpu:null,available:!1,reason:"no navigator.gpu"};let t;try{let n=await K(e.requestAdapter());if(n===E)return{webgpu:null,available:!1,reason:"requestAdapter timed out"};t=n}catch(n){return{webgpu:null,available:!1,reason:`requestAdapter failed: ${z(n)}`}}if(!t)return{webgpu:null,available:!1,reason:"requestAdapter returned null"};let r=await de(t);try{let n=await K(t.requestDevice());if(n===E)return{webgpu:r,available:!1,reason:"requestDevice timed out"};n.destroy?.()}catch(n){return{webgpu:r,available:!1,reason:`requestDevice refused: ${z(n)}`}}return{webgpu:r,available:!0}}function fe(e){return e.webgpu.available&&e.webgpu.built?"webgpu":"wasm"}function pe(e,t,r){let n=e.webgpu?.unrepresentable??[],o=n.length>0?`; adapter limits ${n.join(", ")}: the host reads them as missing`:"";return be(e,t,r)+o}function be(e,t,r){if(r==="webgpu"){let o=e.webgpu,s=o.features.includes("shader-f16")?" with shader-f16":"";return`WebGPU adapter present (${o.vendor} ${o.architecture})${s}: webgpu`}let n=e.wasm.simd?"with simd128":"without simd128";return e.webgpu===null?`no WebGPU adapter (${t.reason??"unavailable"}): wasm ${n}`:`WebGPU adapter present but unusable (${t.reason}): wasm ${n}`}async function G(){let e=V(),t=await ce(),r={wasm:X(),threads:{sharedArrayBuffer:typeof SharedArrayBuffer<"u",crossOriginIsolated:globalThis.crossOriginIsolated===!0,hardwareConcurrency:D(e.hardwareConcurrency)},webgl:ue(),webgpu:t.webgpu,memory:{deviceMemoryGiB:D(e.deviceMemory)},tiers:{webgpu:t.available?{available:!0,built:!0}:{available:!1,built:!0,reason:t.reason},webgl:{available:!1,built:!1,reason:"not built"},wasm:{available:!0,built:!0}}};r.tiers.webgl.available=r.webgl.available;let n=fe(r.tiers);return{...r,chosen:n,why:pe(r,t,n)}}function Q(e){let t=e.webgpu===null?null:{vendor:e.webgpu.vendor,architecture:e.webgpu.architecture,device:e.webgpu.device,description:e.webgpu.description,features:e.webgpu.features,limits:Object.fromEntries(Object.entries(e.webgpu.limits).filter(([,r])=>Number.isSafeInteger(r)))};return JSON.stringify({wasm:{simd:e.wasm.simd,relaxedSimd:e.wasm.relaxedSimd,bulkMemory:e.wasm.bulkMemory,threads:e.wasm.threads,memory64:e.wasm.memory64,tailCall:e.wasm.tailCall,exceptions:e.wasm.exceptions},threads:{sharedArrayBuffer:e.threads.sharedArrayBuffer,crossOriginIsolated:e.threads.crossOriginIsolated,hardwareConcurrency:e.threads.hardwareConcurrency},webgpu:t,memory:{deviceMemoryGiB:e.memory.deviceMemoryGiB}})}var me="https://huggingface.co";function ge(e){return typeof location<"u"?new URL(String(e),location.href):new URL(String(e))}var he="https://cdn.jsdelivr.net/npm/@caldrix-ai/caldrix@0.2.0/";function Y(e){return e instanceof Error?e.message:String(e)}function P(e,t){if(t!==void 0){if(typeof t!="string"&&!(t instanceof URL))throw new i("request",`assets.${e} is a string or a URL, not ${typeof t}`);try{return typeof location<"u"?new URL(t,location.href):new URL(t)}catch{throw new i("request",`assets.${e} ${JSON.stringify(String(t))} is not a URL`)}}}function we(e,t){let r=I(e,t),n=null,o=()=>{n!==null&&URL.revokeObjectURL(n),n=null};try{return!r&&!t?{worker:new Worker(new URL("./worker.js",import.meta.url),{type:"module"}),revoke:o,literal:!0}:r?(n=URL.createObjectURL(new Blob([`import ${JSON.stringify(e.href)};`],{type:"text/javascript"})),{worker:new Worker(n,{type:"module"}),revoke:o}):{worker:new Worker(e,{type:"module"}),revoke:o}}catch(s){throw o(),s}}function ye(e){return typeof location<"u"&&e.origin!==location.origin}function I(e,t){return ye(e)&&(t||e.protocol==="http:"||e.protocol==="https:")}function q(e){return!e.chosen&&!I(e.url,!1)?`the package's worker (dist/worker.js as the page's bundler emitted it, or ${e.url.href} unbundled)`:`the engine's worker from ${e.url.href}${I(e.url,e.chosen)?" (through a same-origin shim)":""}`}var C=class{constructor(t){this.reason=t}reason};function ke(e,t,r){return new Promise((n,o)=>{let s;try{s=we(e.url,e.chosen)}catch(d){o(new C(`the page could not construct it: ${Y(d)}`));return}let{worker:l,revoke:f}=s,b=()=>u(r()),u=(d,a=e.url)=>{if(f(),l.onmessage=null,l.onerror=null,t?.removeEventListener("abort",b),d===null)return n({worker:l,url:a});l.terminate(),o(d)};t?.addEventListener("abort",b,{once:!0}),l.onerror=d=>u(new C(d.message||"it did not load")),l.onmessage=d=>{let a=d.data;if(!L(a)||a.id!==0)return u(m(a));if(a.type==="ready")return s.literal?URL.canParse(a.url)?u(null,new URL(a.url)):u(m(a)):u(null);if(a.type==="error")return u(new C(a.message));u(m(a))}})}async function ve(e,t,r,n){let o=[];for(let u of e)try{let{worker:d,url:a}=await ke(u,r,n),g=o[0];return{worker:d,used:u,url:a,...g!==void 0?{failed:{what:q(g.t),reason:g.reason}}:{}}}catch(d){if(!(d instanceof C))throw d;o.push({t:u,reason:d.reason})}let[s,l]=o;if(s!==void 0&&l!==void 0){let u=l.t.url.origin;throw new i("backend",`${q(s.t)} did not start (${s.reason}), nor from the CDN fallback ${l.t.url.href} (${l.reason}); serve dist/ and host/ beside the bundle, set assets.worker to where the page serves them, or allow ${u} in the page's Content-Security-Policy (worker-src blob: for the same-origin shim that starts it, script-src ${u} for the modules it imports, connect-src ${u} for the .wasm)`)}let f=s,b=t&&f.t.source==="bundle"?"; the CDN fallback is off (assets.fallback is false)":"";throw new i("backend",`${q(f.t)} did not start: ${f.reason}${b}; caldrix.js runs inference in a Web Worker and has no main-thread mode`)}function We(e,t,r){let n=r!==void 0?`, and with it the host .wasm from ${r}`:"";return`${e.what} did not start (${e.reason}); it was loaded from the CDN fallback ${t}${n}`}function xe(e){return`the host .wasm could not be fetched from ${e.failed.url} (${e.failed.reason}); it was fetched from the CDN fallback ${e.url}`}function Z(e){console.warn(`caldrix.js: ${e}. Serve dist/ and host/ beside the bundle or set assets.worker/assets.hostWasm; assets.fallback: false turns the fallback off.`)}function Re(e){let t={text:e.text,token:e.token,done:e.done};return e.logprobs!==void 0&&(t.logprobs=e.logprobs),e.done&&(e.finishReason!==null&&(t.finishReason=e.finishReason),t.usage={promptTokens:e.promptTokens,completionTokens:e.completionTokens,cachedTokens:e.cachedTokens}),t}var M=class{static async load(t,r={}){let n=r.backend??"auto";if(n==="webgl")throw new i("backend","the webgl backend is not built");if(n!=="auto"&&n!=="webgpu"&&n!=="wasm")throw new i("request",`backend ${JSON.stringify(n)} is not auto, webgpu, wasm or webgl`);if(typeof t!="string"||t==="")throw new i("request","load takes a model alias, a non-empty string");let o=P("worker",r.assets?.worker),s=P("hostWasm",r.assets?.hostWasm),l=r.assets?.fallback??!0;if(typeof l!="boolean")throw new i("request",`assets.fallback is true or false, not ${JSON.stringify(l)}`);let f=P("cdn",r.assets?.cdn)??new URL(he);f.pathname.endsWith("/")||(f.pathname+="/");let b=[o!==void 0?{url:o,chosen:!0,source:"page"}:{url:ge(new URL("./worker.js",import.meta.url)),chosen:!1,source:"bundle"}];l&&o===void 0&&b.push({url:new URL("dist/worker.js",f),chosen:!0,source:"cdn"});let u=l&&s===void 0?new URL("host/caldrix_web_bg.wasm",f).href:void 0,d=r.storage??"auto";if(d!=="auto"&&d!=="f32")throw new i("request",`storage ${JSON.stringify(d)} is not auto or f32`);if(n==="wasm"&&d==="f32")throw new i("request",`storage "f32" is the WebGPU tier's weight storage; backend "wasm" takes none`);let a=()=>new i("fetch",`loading ${t} was aborted`),g=r.signal;if(g?.aborted)throw a();let p=await G(),W,T;if(n==="auto"&&r.dtype==="bf16"&&p.chosen==="webgpu")W="wasm",T=`bf16 requested: wasm (the WebGPU tier runs the f32 plan only); ${p.why}`;else if(n==="auto")W=p.chosen,T=p.why;else if(n==="webgpu"){if(!p.tiers.webgpu.available)throw new i("backend",`backend "webgpu" was asked for, but the probe found no usable WebGPU adapter: ${p.tiers.webgpu.reason??p.why}`);W="webgpu",T=`backend "webgpu" asked for; ${p.why}`}else W="wasm",T=`backend "wasm" asked for; ${p.why}`;let B=p.webgpu?.unrepresentable??[];if(g?.aborted)throw a();let $=await ve(b,!l,g,a),{worker:y}=$,O=$.url,R=null;$.failed!==void 0&&(R=We($.failed,O.href,s===void 0?u:void 0),Z(R));let F=U=>R===null?U:new i(U.kind,`${U.message} (after a CDN fallback: ${R})`,U.missing);if(g?.aborted)throw y.terminate(),F(a());let _=1,ee={id:_,type:"load",alias:t,probeJson:Q(p),request:{backend:W,...r.dtype!==void 0?{dtype:r.dtype}:{},...r.maxContext!==void 0?{maxContext:r.maxContext}:{},...W==="webgpu"&&d==="f32"?{f16:!1}:{}},...n==="auto"&&W==="webgpu"?{auto:!0}:{},offline:r.offline??!1,hubBaseUrl:r.hubBaseUrl??me,...s!==void 0?{hostWasm:s.href}:{},...u!==void 0?{cdnWasm:u}:{}};return new Promise((U,te)=>{let j=()=>k(a()),N=()=>{y.onmessage=null,y.onerror=null,g?.removeEventListener("abort",j)},k=A=>{N(),y.terminate(),te(F(A))},h=null;g?.addEventListener("abort",j,{once:!0}),y.onerror=A=>k(new i("backend",`the engine's worker from ${O.href} failed: ${A.message||"it did not start"}`)),y.onmessage=A=>{let c=A.data;if(!L(c)||c.id!==_)return k(m(c));switch(c.type){case"host":if(h!==null)return k(m(c));h=c.hostWasm,h.failed!==void 0&&(R=xe({...h,failed:h.failed}),Z(R));return;case"progress":try{r.onProgress?.({file:c.file,loaded:c.loaded,total:c.total})}catch(w){k(w instanceof i?w:new i("request",`onProgress threw: ${Y(w)}`))}return;case"loaded":{if(h===null)return k(m(c));N();let w=$.used.source,re=s!==void 0||w==="page"&&h.failed===void 0?"page":h.failed!==void 0||w==="cdn"?"cdn":"bundle",ne={worker:{source:w,url:O.href},hostWasm:{source:re,url:h.url}},oe={...c.doctor,source:c.sources,why:c.fallback!==void 0?`${c.fallback}; ${p.why}`:T,assets:ne};U(new S(y,oe));return}case"error":{let w=c.kind==="probe"&&B.length>0?`; the browser gave ${B.join(", ")}, which the host reads as missing`:"";return k(new i(c.kind,c.message+w))}default:return k(m(c))}},y.postMessage(ee)})}},S=class{#r;#n;#l=2;#t=!1;#e=null;#i=!1;#o=null;constructor(t,r){this.#r=t,this.#n=r,t.onmessage=n=>this.#d(n.data),t.onerror=n=>this.#a(new i("backend",`the engine's worker failed: ${n.message||"it stopped"}`))}chat(t,r={}){return this.#s(),this.#u({messages:t},r)}complete(t,r={}){this.#s();let n;if(typeof t=="string")n={text:t};else if(typeof t=="object"&&t!==null){let o=t;if(o.text!==void 0&&o.ids!==void 0)throw new i("request","complete takes exactly one of text and ids, not both");if(!Array.isArray(o.ids))throw new i("request","complete takes exactly one of text and ids");n={ids:o.ids}}else throw new i("request","complete takes exactly one of text and ids");return this.#u(n,r)}doctor(){this.#s();let t=Object.fromEntries(Object.entries(this.#n.source).map(([s,l])=>[s,{...l}])),{worker:r,hostWasm:n}=this.#n.assets,o=this.#n.aliases.map(s=>({...s}));return{...this.#n,source:t,aliases:o,assets:{worker:{...r},hostWasm:{...n}}}}dispose(){if(!this.#t){this.#t=!0;try{this.#r.postMessage({id:this.#l++,type:"dispose"})}catch{}this.#r.terminate(),this.#o?.sink(new i("request","the engine was disposed"))}}#s(){if(this.#t)throw new i("request","the engine was disposed; load a new one");if(this.#e)throw this.#e}#a(t){this.#e||this.#t||(this.#e=t,this.#r.terminate(),this.#o?.sink(t))}#d(t){if(this.#t||this.#e)return;if(!L(t))return this.#a(m(t));let r=this.#o;if(r===null||t.id!==r.id)return this.#a(m(t));switch(t.type){case"delta":return r.sink(Re(t.delta));case"error":return t.fatal!==void 0&&(this.#e=H(t.fatal)),r.sink(new i(t.kind,t.message));default:return this.#a(m(t))}}async*#u(t,r){if(this.#s(),this.#i)throw new i("request","a generation is already running on this engine");let{signal:n,...o}=r;if(n?.aborted){yield{text:"",done:!0,finishReason:"abort",usage:{promptTokens:0,completionTokens:0,cachedTokens:0}};return}this.#i=!0;let s=this.#l++,l=[],f=null;this.#o={id:s,sink:a=>{l.push(a),f?.()}};let b=()=>{!this.#t&&!this.#e&&this.#r.postMessage({id:s,type:"abort"})},u=!1,d=async()=>{for(;l.length===0;)await new Promise(a=>f=a);return f=null,l.shift()};try{for(this.#r.postMessage({id:s,type:"generate",prompt:t,options:o}),n?.addEventListener("abort",b,{once:!0});;){let a=await d();if(a instanceof i)throw u=!0,a;if(a.done&&(u=!0),yield a,a.done)return}}finally{if(n?.removeEventListener("abort",b),!u)try{for(b();!(this.#t||this.#e);){let a=await d();if(a instanceof i||a.done)break}}catch{}this.#o=null,this.#i=!1}}};export{M as Caldrix,i as CaldrixError,S as Engine,G as probe};
package/dist/worker.js ADDED
@@ -0,0 +1 @@
1
+ import{b as c,c as E,d as N}from"./chunk-PZGTLL5H.js";var ke="caldrix.js",ee="x-caldrix-verified",J="x-caldrix-absent";function xe(n){return[...new Uint8Array(n)].map(r=>r.toString(16).padStart(2,"0")).join("")}function ve(n){return n.trim().replace(/^W\//,"").replace(/^"|"$/g,"").toLowerCase()}function R(n){return n instanceof Error?n.message:String(n)}function I(n,r){if(r===""||r==="."||r===".."||/[/\\?#]/.test(r)||/%[0-9a-fA-F]{2}/.test(r)||/[\u0000-\u001f\u007f]/.test(r))throw new c("validate",`${n} ${JSON.stringify(r)} is not a single safe path segment`);return encodeURIComponent(r)}function te(n){return new c("backend",`${n} is not available; caldrix.js needs a secure context`)}function re(n,r,s,e){let t=n.split("/").map(u=>I("repo",u)).join("/");return`${e.endsWith("/")?e.slice(0,-1):e}/${t}/resolve/${I("revision",r)}/${I("file",s)}`}async function ne(n){if(typeof caches>"u")throw te("caches");try{return await caches.open(ke)}catch(r){throw new c("backend",`opening the cache for ${n} failed: ${R(r)}`)}}async function z(n){if(typeof crypto>"u"||!crypto.subtle)throw te("crypto.subtle");return xe(await crypto.subtle.digest("SHA-256",n))}function se(n){return new c("fetch",`${n} is not in the cache and offline is set`,"offline-uncached")}async function oe(n,r,s,e){let t=re(n,r,s,e.hubBaseUrl),i=await ne(s),u;try{u=await i.match(t)}catch(w){throw new c("backend",`reading ${s} from the cache failed: ${R(w)}`)}let a=w=>new c("fetch",`fetching ${s} failed: HTTP 404${w}`,"not-found");if(u&&u.headers.get(J)==="1"){if(e.rememberAbsent)throw a(" (remembered from an earlier load)");u=void 0}let l=!1;if(u){let w=new Uint8Array(await u.arrayBuffer());if(e.sha256===void 0)return{bytes:w,source:"cache",verified:u.headers.get(ee)==="1",cached:!0};if(await z(w)===e.sha256)return{bytes:w,source:"cache",verified:!0,cached:!0};l=!0;try{await i.delete(t)}catch{}}if(e.offline&&l)throw new c("fetch",`${s}: the cached copy fails the alias's sha256 pin and offline is set`,"offline-uncached");if(e.offline)throw se(s);let f=(w,S)=>new c("fetch",`fetching ${s} ${w}`,S),y=()=>{if(e.signal?.aborted)throw f("was aborted")},m;try{m=await fetch(t,{signal:e.signal})}catch(w){throw f(e.signal?.aborted?"was aborted":`failed: ${R(w)}`)}if(m.status===404&&e.rememberAbsent){try{await i.put(t,new Response(null,{headers:{[J]:"1"}}))}catch{}throw a("")}if(!m.ok||!m.body)throw f(`failed: HTTP ${m.status}`,m.status===404?"not-found":void 0);let x=m.headers.get("x-linked-etag"),p=m.headers.get("content-length"),o=p!==null&&/^\d+$/.test(p.trim())?Number(p):null,d=[],b=0,h=m.body.getReader();try{for(;;){let w;try{w=await h.read()}catch(S){throw f(e.signal?.aborted?"was aborted":`failed: ${R(S)}`)}if(w.done)break;if(d.push(w.value),b+=w.value.byteLength,e.bytes!==void 0&&b>e.bytes)throw new c("fetch",`${s}: the body passed the alias's ${e.bytes} bytes`);e.onProgress?.({file:s,loaded:b,total:o})}}finally{h.cancel().catch(()=>{})}if(y(),o!==null&&o!==b&&!m.headers.get("content-encoding"))throw f(`failed: Content-Length is ${o} but ${b} bytes arrived`);let g=new Uint8Array(b),W=0;for(let w of d)g.set(w,W),W+=w.byteLength;e.onProgress?.({file:s,loaded:b,total:o});let A=!1,G=null;if(e.sha256!==void 0){if(G=await z(g),G!==e.sha256)throw new c("digest",`${s}: sha256 is ${G} but the alias pins ${e.sha256}`);A=!0}if(x!==null){let w=ve(x);if(G??=await z(g),w!==G)throw new c("digest",`${s}: sha256 is ${G} but the Hub's X-Linked-Etag is ${w}`);A=!0}y();try{await i.put(t,new Response(g,{headers:{[ee]:A?"1":"0"}}))}catch{return{bytes:g,source:"network",verified:A,cached:!1}}return{bytes:g,source:"network",verified:A,cached:!0}}async function ie(n,r,s,e,t){if(!Number.isSafeInteger(e)||e<=0)throw new c("request",`a range of ${e} bytes of ${s} is not a positive integer`);let i=re(n,r,s,t.hubBaseUrl),u=await ne(s),a;try{a=await u.match(i)}catch(p){throw new c("backend",`reading ${s} from the cache failed: ${R(p)}`)}if(a&&a.headers.get(J)!=="1"){let p=new Uint8Array(await a.arrayBuffer());if(p.byteLength>=e)return p.slice(0,e)}if(t.offline)throw se(s);let l=p=>new c("fetch",`fetching the first ${e} bytes of ${s} ${p}`),f;try{f=await fetch(i,{headers:{Range:`bytes=0-${e-1}`},signal:t.signal})}catch(p){throw l(t.signal?.aborted?"was aborted":`failed: ${R(p)}`)}if(f.status!==206&&f.status!==200||!f.body)throw l(`failed: HTTP ${f.status}`);let y=new Uint8Array(e),m=0,x=f.body.getReader();try{for(;;){let p;try{p=await x.read()}catch(d){throw l(t.signal?.aborted?"was aborted":`failed: ${R(d)}`)}if(p.done)break;let o=Math.min(p.value.byteLength,e-m);if(y.set(p.value.subarray(0,o),m),m+=p.value.byteLength,m>e||f.status===200&&m===e)break}}finally{x.cancel().catch(()=>{})}if(t.signal?.aborted)throw l("was aborted");if(m<e)throw l(`failed: the HTTP ${f.status} answer carried ${m} bytes, not the ${e} asked for`);if(f.status===206&&m>e)throw l(`failed: the HTTP 206 answer carried more than the ${e} bytes asked for`);return y}var j=null,T=null;function Y(n){return n instanceof Error?n.message:String(n)}async function K(){return await import("../host/caldrix_web.js")}function Pe(n){let r=globalThis.location?.href;return(r!==void 0?new URL(String(n),r):new URL(String(n))).href}async function ae(n){let r;try{r=await fetch(n)}catch(s){throw new Error(Y(s))}if(!r.ok)throw new Error(`${r.status} ${r.statusText}`.trim());return r}async function Q(n,r){if(j===null){let s=await K(),e=n??Pe(new URL("../host/caldrix_web_bg.wasm",import.meta.url)),t,i;try{t=await ae(e),i={url:e}}catch(u){let a=Y(u);if(r===void 0||r===e)throw new c("backend",`the browser host's .wasm could not be fetched from ${e} (${a}); serve host/ beside dist/ or set assets.hostWasm to where the page serves it`);try{t=await ae(r)}catch(l){let f=new URL(r).origin;throw new c("backend",`the browser host's .wasm could not be fetched from ${e} (${a}) nor from the CDN fallback ${r} (${Y(l)}); serve host/ beside dist/, set assets.hostWasm to where the page serves it, or allow ${f} in the page's Content-Security-Policy (connect-src ${f}, the .wasm is fetched)`)}i={url:r,failed:{url:e,reason:a}}}await s.default({module_or_path:t}),j=s,T=i}return j}async function ue(n,r,s){let e=await Q(r,s);return new e.CaldrixWeb(n)}function le(){if(T===null)throw new c("backend","the browser host is not open");return{...T,...T.failed!==void 0?{failed:{...T.failed}}:{}}}async function ce(){return(await Q()).CaldrixWeb}async function fe(n,r){let s=await Q(),e;try{let{instance:u}=await WebAssembly.instantiate(r,{env:{memory:s.CaldrixWeb.memory()}});e=u.exports}catch(u){throw new c("backend",`instantiating the emitted module failed: ${u instanceof Error?u.message:String(u)}`)}let{step:t,prefill:i}=e;if(typeof t!="function"||typeof i!="function")throw new c("backend","the emitted module does not export step and prefill");if(n.attach(t,i),n.argsPtr()===0)throw new c("backend","the host reports no model loaded after load")}var B={MAP_READ:1,COPY_SRC:4,COPY_DST:8,UNIFORM:64,STORAGE:128},$e=1,We=["maxStorageBufferBindingSize","maxBufferSize","maxComputeWorkgroupsPerDimension","maxStorageBuffersPerShaderStage"],de=(n,r)=>Number.isSafeInteger(n)&&n>=0&&n<r,pe=n=>Number.isSafeInteger(n)&&n>=0;function Ae(n,r){let s=t=>new c("backend",`the host's WebGPU program is malformed: ${t}`),e;try{e=JSON.parse(n)}catch(t){throw s(t instanceof Error?t.message:String(t))}if(typeof e!="object"||e===null||!Array.isArray(e.kernels)||!Array.isArray(e.buffers))throw s("no kernels or buffers");if(e.kernels.forEach((t,i)=>{if(!(typeof t?.symbol=="string"&&typeof t.entry=="string"&&Array.isArray(t.buffers)&&t.buffers.every(a=>a==="f32"||a==="f16")&&pe(t.scalars)))throw s(`kernel ${i}`)}),e.buffers.forEach((t,i)=>{if(!(typeof t?.word=="string"&&pe(t.bytes)&&(t.storage==="f32"||t.storage==="f16")&&typeof t.placed=="boolean"))throw s(`buffer ${i}`)}),!de(e.act,e.buffers.length))throw s("act is no buffer");if(!de(e.logits,e.buffers.length))throw s("logits is no buffer");if(!Array.isArray(r)||r.length!==e.kernels.length||!r.every(t=>typeof t=="string"))throw s(`${e.kernels.length} kernels but ${Array.isArray(r)?r.length:"no"} WGSL sources`);return e}function Ge(n,r){let s=[],e=u=>new c("backend",`the host's launch words are malformed: ${u}`),t=0,i=(u,a)=>{if(t+u>n.length)throw e(`launch ${s.length} ends inside its ${a}`);let l=n.subarray(t,t+u);return t+=u,l};for(;t<n.length;){let u=i(1,"kernel")[0],a=r.kernels[u];if(a===void 0)throw e(`launch ${s.length} names kernel ${u}; the program has ${r.kernels.length}`);let l=Array.from(i(i(1,"buffer count")[0],"buffers"));if(l.length!==a.buffers.length)throw e(`a launch of ${a.symbol} binds ${l.length} buffers; the kernel declares ${a.buffers.length}`);let f=l.find(p=>p>=r.buffers.length);if(f!==void 0)throw e(`a launch of ${a.symbol} binds buffer ${f}; the program has ${r.buffers.length}`);let[y,m]=i(2,"grid"),x=i(i(1,"uniform count")[0],"uniform").slice();if(x.length===0!=(a.scalars===0))throw e(`a launch of ${a.symbol} carries ${x.length} uniform words; the kernel declares ${a.scalars} scalars`);s.push({kernel:u,buffers:l,x:y,y:m,uniform:x})}return s}var D=n=>n instanceof Error?n.message:String(n),V=class{constructor(r,s,e,t,i,u,a,l){this.adapter=r;this.description=s;this.host=e;this.device=t;this.program=i;this.pipelines=u;this.buffers=a;this.staging=l;t.lost.then(f=>{let y=`the WebGPU device was lost: ${f.message||f.reason||"no message"}`;!this.#e&&this.#t===null&&(this.#t=y),this.#r?.(y)})}adapter;description;host;device;program;pipelines;buffers;staging;#t=null;#e=!1;#r=null;#n=new Set;get failure(){return this.#t}get storage(){return this.program.buffers.some(r=>r.storage==="f16")?"f16":"f32"}async run(r,s){if(this.#e)throw new c("request","the WebGPU runtime was destroyed (the engine was disposed)");if(this.failure!==null)throw this.#o(this.failure),N(this.failure);let e;try{e=Ge(r,this.program);let l=this.program.buffers[this.program.act];if(s.byteLength>l.bytes)throw new c("backend",`actIn is ${s.byteLength} bytes; the program's ${l.word} is ${l.bytes}`)}catch(l){throw this.#s(D(l),!1)}let t=this.device,i=[],u,a=new Promise((l,f)=>{this.#r=y=>f(new Error(y))});a.catch(()=>null);try{t.pushErrorScope("validation"),t.pushErrorScope("out-of-memory"),t.pushErrorScope("internal");let l=3,f=async()=>{let o=t.popErrorScope(),d=t.popErrorScope(),b=t.popErrorScope();l=0;let[h,g,W]=await Promise.all([o,d,b]);return g?`out of memory: ${g.message}`:W?`validation: ${W.message}`:h?`an internal error: ${h.message}`:null},y,m;try{s.byteLength>0&&t.queue.writeBuffer(this.buffers[this.program.act],0,s);let o=e.map(g=>{let W=g.buffers.map((A,G)=>({binding:G,resource:{buffer:this.buffers[A]}}));if(g.uniform.length>0){let A=t.createBuffer({size:g.uniform.byteLength,usage:B.UNIFORM|B.COPY_DST});i.push(A),this.#n.add(A),t.queue.writeBuffer(A,0,g.uniform),W.push({binding:g.buffers.length,resource:{buffer:A}})}return t.createBindGroup({layout:this.pipelines[g.kernel].getBindGroupLayout(0),entries:W})}),d=t.createCommandEncoder(),b=d.beginComputePass();e.forEach((g,W)=>{b.setPipeline(this.pipelines[g.kernel]),b.setBindGroup(0,o[W]),b.dispatchWorkgroups(g.x,g.y,1)}),b.end();let h=this.buffers[this.program.logits];d.copyBufferToBuffer(h,0,this.staging,0,h.size),t.queue.submit([d.finish()]),y=f(),m=this.staging.mapAsync($e),y.catch(()=>null),m.catch(()=>null)}finally{for(;l-- >0;)t.popErrorScope().catch(()=>null)}if(this.failure!==null)throw new Error(this.failure);let x=await Promise.race([y,a]);if(this.#e)throw new c("request","the engine was disposed during a WebGPU call");if(x!==null)throw new Error(`the device reported ${x}`);try{await Promise.race([m,a])}catch(o){throw this.#e?new c("request","the engine was disposed during a WebGPU call"):new Error(`mapping the logits readback failed: ${D(o)}`)}if(this.#e)throw new c("request","the engine was disposed during a WebGPU call");let p=this.program.buffers[this.program.logits].bytes;u=new Uint8Array(this.staging.getMappedRange(0,this.staging.size).slice(0,p)),this.staging.unmap()}catch(l){throw l instanceof c&&l.kind==="request"?l:this.#s(D(l))}finally{this.#r=null;for(let l of i)this.#n.delete(l),this.#e||l.destroy()}this.host.writeLogits(u)}#s(r,s=!0){return this.#e?new c("request","the engine was disposed during a WebGPU call"):(s&&(this.#t??=r),this.#o(r)??new c("backend",r))}#o(r){try{this.host.failLaunch(r)}catch(s){let e=E(s);if(e.kind==="backend")return e}return null}destroy(){if(!this.#e){this.#e=!0,this.#r?.("the engine was disposed during a WebGPU call");for(let r of[...this.buffers,this.staging,...this.#n])try{r.destroy()}catch{}this.#n.clear();try{this.device.destroy()}catch{}}}};function Se(n,r){let s=n.limits[r];return typeof s=="number"?s:void 0}function Ee(){return globalThis.navigator?.gpu}async function he(n,r,s=Ee()){let e=f=>new c("backend",f);if(!s)throw e("the worker has no navigator.gpu, though the page's probe found a WebGPU adapter");let t;try{t=await s.requestAdapter()}catch(f){throw e(`the worker's requestAdapter failed: ${D(f)}`)}if(!t)throw e("the worker's requestAdapter returned null, though the page's probe found an adapter");if(r&&!t.features.has("shader-f16"))throw e("the host's precheck chose f16 weight storage, but the worker's adapter has no shader-f16");let i={};for(let f of We){let y=Se(t,f),m=n.webgpu?.limits[f];if(m!==void 0&&(y===void 0||y<m))throw e(`the worker's adapter offers ${f} ${y??"none"}; the host prechecked against the probe's ${m}`);y!==void 0&&(i[f]=y)}let u;try{u=await t.requestDevice({requiredFeatures:r?["shader-f16"]:[],requiredLimits:i})}catch(f){throw e(`requestDevice refused${r?" shader-f16 with":""} the program's limits: ${D(f)}`)}let a=t.info??{};if(!t.info&&typeof t.requestAdapterInfo=="function")try{a=await t.requestAdapterInfo()}catch{a={}}let l=!1;return{device:u,f16:r,adapter:{vendor:a.vendor??"",architecture:a.architecture??""},description:a.description??"",destroy:()=>{if(!l){l=!0;try{u.destroy()}catch{}}}}}async function ge(n,r,s){let e=a=>new c("backend",a),t=r.device,i=[],u=()=>{for(let a of i)a.destroy();r.destroy()};try{let a=Ae(s.program,s.kernels),l=a.buffers.some(x=>x.storage==="f16");if(l!==r.f16)throw e(`the program stores weights ${l?"f16":"f32"}, but the device was opened for ${r.f16?"f16":"f32"} storage`);let f=[];for(let[x,p]of a.kernels.entries()){t.pushErrorScope("validation"),t.pushErrorScope("internal");let o=null,d=null;try{let g=t.createShaderModule({code:s.kernels[x],label:p.symbol});o=t.createComputePipeline({label:p.symbol,layout:"auto",compute:{module:g,entryPoint:p.entry}})}catch(g){d=g}let b=await t.popErrorScope(),h=await t.popErrorScope()??b;if(h)throw e(`kernel ${p.symbol}: creating its pipeline: ${h.message}`);if(o===null)throw e(`kernel ${p.symbol}: creating its pipeline: ${D(d)}`);f.push(o)}for(let[x,p]of a.buffers.entries()){t.pushErrorScope("validation"),t.pushErrorScope("out-of-memory");let o=null;try{let h=t.createBuffer({size:Math.max(4,Math.ceil(p.bytes/4)*4),usage:B.STORAGE|B.COPY_SRC|B.COPY_DST,label:p.word});if(i.push(h),p.placed){let g=n.bufferBytes(x);if(g.byteLength!==p.bytes)throw new c("backend",`buffer ${p.word}: bufferBytes gave ${g.byteLength} bytes; the buffer is ${p.bytes} at ${p.storage} storage`);if(g.byteLength%4!==0)throw new c("backend",`buffer ${p.word}: ${g.byteLength} bytes are not whole 4-byte words`);t.queue.writeBuffer(h,0,g)}}catch(h){o=h}let d=await t.popErrorScope(),b=await t.popErrorScope();if(o!==null)throw o instanceof c?o:E(o);if(d)throw e(`buffer ${p.word} (${p.bytes} bytes): out of memory: ${d.message}`);if(b)throw e(`buffer ${p.word} (${p.bytes} bytes): ${b.message}`)}let y=i[a.logits],m=t.createBuffer({size:y.size,usage:B.MAP_READ|B.COPY_DST,label:"logits readback"});return new V({...r.adapter},r.description,n,t,a,f,i,m)}catch(a){throw u(),a}}var Ce=4194304,Ue="a quantized alias runs on the wasm tier: the WebGPU tier has no quantized kernels in this version",Re=["fit","request","probe"];function be(){return new Promise(n=>{let r=new MessageChannel;r.port1.onmessage=()=>{r.port1.close(),n()},r.port2.postMessage(0)})}async function me(n,r,s){let e,t;try{e=s.kind==="prefill"?n.resolve("prefill",s.n):n.resolve("step",s.pos),t=n.actIn(s.kind==="prefill"?s.n:1)}catch(i){try{n.failLaunch(E(i).message)}catch{}throw i}await r.run(e,t)}async function Be(n,r,s,e){if(await me(n,r,s),!!e.launched())for(n.finishStart();;){if(!await e.between())return;let t=n.beginNext();if("delta"in t){e.delta(JSON.parse(t.delta));return}if(await me(n,r,t.launch),!e.launched())return;let i=JSON.parse(n.finishNext());if(e.delta(i),i.done)return}}function ye(n,r){let s=null,e=null,t=!1,i=null,u=!1,a=[],l=o=>{let d={...o.doctor(),aliases:a.map(A=>({...A}))};if(e===null)return{...d,storage:null,adapter:null};let b=e.adapter,h=`webgpu (${e.description!==""?e.description:`${b.vendor} ${b.architecture}`})`,g=`backend webgpu on ${d.device}`,W=d.line.startsWith(g)?`backend webgpu on ${h}${d.line.slice(g.length)}`:d.line;return{...d,device:h,line:W,storage:e.storage,adapter:{...b}}},f=new c("request","the engine was disposed during its load"),y=()=>{if(u)throw f};async function m(o){if(s!==null||t)throw new c("request","this engine already has a model loaded");t=!0;let d=null;try{d=await n.openHost(o.probeJson,o.hostWasm,o.cdnWasm),r({id:o.id,type:"host",hostWasm:n.wasmUsed()}),y();let b=await n.hostClass(),h=b.resolveAlias(o.alias);a=b.listAliases();let{repo:g,revision:W}=h,A={},G=async(k,v,P)=>{try{let $=await n.fetchFile(g,W,k,{hubBaseUrl:o.hubBaseUrl,offline:o.offline,rememberAbsent:v,...P??{},onProgress:U=>r({id:o.id,type:"progress",file:U.file,loaded:U.loaded,total:U.total})});return y(),A[k]={source:$.source,verified:$.verified},$.bytes}catch($){if(v&&$ instanceof c&&$.missing==="not-found")return null;throw $}},w=async(k,v)=>await G(k,!1,v),S=d,L,q;if(h.format==="gguf"){let k=$=>n.fetchRange(g,W,h.file,$,{hubBaseUrl:o.hubBaseUrl,offline:o.offline}),v=await k(Math.min(Ce,h.bytes));y();for(let $=b.ggufHeaderNeed(v,h.bytes);$!==0;$=b.ggufHeaderNeed(v,h.bytes))v=await k($),y();let P=v;L=$=>S.precheckGguf(P,h.bytes,$),q=async($,U)=>{let H=await w(h.file,{sha256:h.sha256,bytes:h.bytes});return U?S.loadWebGpuGguf(H,$):S.loadGguf(H,$)}}else{let k=await w("config.json"),v=await G("model.safetensors.index.json",!0);L=P=>S.precheck(k,v,P),q=async(P,$)=>{let U=await w("tokenizer.json"),H=await G("tokenizer_config.json",!0),M=[];for(let we of b.weightFiles(v))M.push(await w(we));return $?S.loadWebGpu(k,U,H,M,P):S.load(k,U,H,M,P)}}let C={...o.request,repo:g,revision:W},_,F=null,X=()=>{let k={...C,backend:"wasm"};delete k.f16,C=k},Z=k=>{X();try{L(JSON.stringify(C))}catch(v){let P=E(v);throw new c(P.kind,`${P.message} (backend "auto": WebGPU refused first: ${k.message})`)}_=`webgpu refused: ${k.message}; wasm serves this load`};if(o.auto===!0&&h.format==="gguf")X(),L(JSON.stringify(C)),_=Ue;else if(C.backend==="webgpu"){let k=null;try{k=JSON.parse(L(JSON.stringify(C)))}catch(v){let P=E(v);if(!(o.auto===!0&&Re.includes(P.kind)))throw P;Z(P)}if(k!==null)try{F=await n.openDevice(JSON.parse(o.probeJson),k.f16===!0)}catch(v){let P=E(v);if(o.auto!==!0)throw P;Z(P)}}else L(JSON.stringify(C));try{y();let k=JSON.stringify(C);if(F!==null){let v=await q(k,!0),P=F;F=null,e=await n.openRuntime(S,P,v)}else await n.instantiate(S,await q(k,!1))}finally{F?.destroy()}y(),s=d,r({id:o.id,type:"loaded",doctor:l(d),sources:A,..._!==void 0?{fallback:_}:{}})}catch(b){if(e?.destroy(),e=null,d!==null&&s!==d)try{d.dispose()}catch{}throw b}finally{t=!1}}async function x(o,d,b,h){let g;"messages"in o.prompt?g=d.startChatSplit(JSON.stringify(o.prompt.messages),h):"text"in o.prompt?g=d.startCompleteSplit(o.prompt.text,null,h):g=d.startCompleteSplit(null,Uint32Array.from(o.prompt.ids),h),await Be(d,b,g,{launched:()=>!u,between:async()=>(await be(),!u),delta:W=>r({id:o.id,type:"delta",delta:W})})}async function p(o){if(i!==null)throw new c("request","a generation is already running on this engine");if(s===null)throw new c("request","no model is loaded");let d=s,b=JSON.stringify(o.options);if(e!==null){if(e.failure!==null)throw N(e.failure);i=o.id;try{return await x(o,d,e,b)}catch(h){if(u)return;throw h}finally{i=null}}i=o.id;try{for(("messages"in o.prompt)?d.startChat(JSON.stringify(o.prompt.messages),b):("text"in o.prompt)?d.startComplete(o.prompt.text,null,b):d.startComplete(null,Uint32Array.from(o.prompt.ids),b);;){if(await be(),u)return;let h=JSON.parse(d.next());if(r({id:o.id,type:"delta",delta:h}),h.done)return}}finally{i=null}}return async o=>{try{switch(o.type){case"load":return await m(o);case"generate":return await p(o);case"abort":i===o.id&&s?.abort();return;case"doctor":if(s===null)throw new c("request","no model is loaded");r({id:o.id,type:"result",value:l(s)});return;case"dispose":u=!0,e?.destroy(),e=null,s?.dispose(),s=null,r({id:o.id,type:"result",value:null}),n.close();return}}catch(d){if(u)return;let b=E(d),h=e?.failure??null;r({id:o.id,type:"error",kind:b.kind,message:b.message,...h!==null?{fatal:h}:{}})}}}var O=globalThis,Le=ye({openHost:ue,wasmUsed:le,hostClass:ce,instantiate:fe,openDevice:(n,r)=>he(n,r),openRuntime:ge,fetchFile:oe,fetchRange:ie,close:()=>O.close()},n=>O.postMessage(n));O.onmessage=n=>{Le(n.data)};K().then(()=>O.postMessage({id:0,type:"ready",url:O.location.href}),n=>O.postMessage({id:0,type:"error",kind:"backend",message:`the browser host's glue (host/caldrix_web.js, beside dist/worker.js) did not load (${n instanceof Error?n.message:String(n)})`}));
@@ -0,0 +1,206 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ export class CaldrixWeb {
5
+ free(): void;
6
+ [Symbol.dispose](): void;
7
+ abort(): void;
8
+ /**
9
+ * A copy of the first `rows` activation rows the session gathered into `ActA` (f32), for the
10
+ * runtime to write into the program's `act` buffer before a launch.
11
+ */
12
+ actIn(rows: number): Uint8Array;
13
+ argsPtr(): number;
14
+ /**
15
+ * The module's entries: `step(args)` and `prefill(args, n)`, each returning the status code.
16
+ */
17
+ attach(step: Function, prefill: Function): void;
18
+ /**
19
+ * `{ launch }` (the step to run, then `finishNext`) or `{ delta }` (the last delta, the JSON
20
+ * string `next` returns; nothing to run).
21
+ */
22
+ beginNext(): any;
23
+ /**
24
+ * Program buffer `index`'s bytes for the runtime to upload once: the heap's, a block GEMM
25
+ * weight stored f16 narrowed RNE here (a value past f16 range a `validate` error naming the
26
+ * tensor).
27
+ */
28
+ bufferBytes(index: number): Uint8Array;
29
+ /**
30
+ * Releases the host's heap and everything it holds; every later call (but `dispose` and `abort`,
31
+ * no-ops, and `argsPtr`, then `0`) is a `request` refusal rather than a use of a freed
32
+ * object. The page's object itself is freed by `free()` or its finalizer.
33
+ */
34
+ dispose(): void;
35
+ /**
36
+ * What this host is: `{ backend, device, dtype, simd, threads, model, revision, source, line }`;
37
+ * `source` is the page's to fill.
38
+ */
39
+ doctor(): any;
40
+ /**
41
+ * The runtime's launch failed (a device loss, a validation or out-of-memory error): the
42
+ * generation ends as `next` does on a failed step -- every later split call is the
43
+ * "finished" refusal -- and `message` is thrown back as a `backend` error.
44
+ */
45
+ failLaunch(message: string): void;
46
+ /**
47
+ * After a `beginNext` launch ran and `writeLogits` wrote its row: the delta, as `next`'s JSON.
48
+ */
49
+ finishNext(): any;
50
+ /**
51
+ * After the first launch ran and `writeLogits` wrote its row: picks the first token.
52
+ */
53
+ finishStart(): void;
54
+ /**
55
+ * [`HEADER_FIRST_RANGE`], the page's first range of a GGUF file (the worker's
56
+ * `GGUF_HEADER_FIRST_RANGE` is pinned against it).
57
+ */
58
+ static ggufHeaderFirstRange(): number;
59
+ /**
60
+ * How much of a GGUF file's head the page reads next: `0` when `prefix` holds the whole
61
+ * header, else the next range's length (doubling, capped at `file_bytes`). The page's first
62
+ * range is `HEADER_FIRST_RANGE` (4 MiB) or the whole file when smaller.
63
+ */
64
+ static ggufHeaderNeed(prefix: Uint8Array, file_bytes: number): number;
65
+ /**
66
+ * Every alias the browser build knows: `[{ name, format }]`, `format` `"safetensors"` or
67
+ * `"gguf"` (what `resolveAlias` answers for that name).
68
+ */
69
+ static listAliases(): any;
70
+ /**
71
+ * [`CaldrixWeb::load`] over a GGUF file the page verified against the alias's sha256: the
72
+ * precheck again on the whole file, the import (the tokenizer from the header), the lowering
73
+ * with the file's per-layer kinds (a quantized file lowers to the wasm tier's quantized
74
+ * kernels), and the placement.
75
+ */
76
+ loadGguf(file: Uint8Array, request_json: string): Uint8Array;
77
+ /**
78
+ * [`CaldrixWeb::load_webgpu`] over a GGUF file the page verified (see
79
+ * [`CaldrixWeb::load_gguf`]); returns `{ program, kernels }`.
80
+ */
81
+ loadWebGpuGguf(file: Uint8Array, request_json: string): any;
82
+ /**
83
+ * The WebGPU tier's `load`: prechecks the request (`backend: "webgpu"`) against the adapter
84
+ * again, imports, lowers for WebGPU (plan dtype f32, the block GEMM weights stored f16 when the
85
+ * precheck chose it), places into the host's heap and resolves the program. Returns
86
+ * `{ program, kernels }`: `program` the `WebGpuProgram` JSON (`to_json`), `kernels` the WGSL
87
+ * sources in the same index order. Nothing is attached: the split-phase calls drive it.
88
+ */
89
+ loadWebGpu(config_json: Uint8Array, tokenizer_json: Uint8Array, tokenizer_config: Uint8Array | null | undefined, files: Array<any>, request_json: string): any;
90
+ /**
91
+ * Prechecks again on the real bytes, imports, lowers and places into the host's heap; returns
92
+ * the module bytes for the page to instantiate over [`memory`].
93
+ */
94
+ load(config_json: Uint8Array, tokenizer_json: Uint8Array, tokenizer_config: Uint8Array | null | undefined, files: Array<any>, request_json: string): Uint8Array;
95
+ /**
96
+ * Where the module writes each logits row: [`Placed::logits`], `0` when nothing is loaded. For
97
+ * a test page that reads the row from [`CaldrixWeb::memory`]; the product never reads it.
98
+ */
99
+ logitsPtr(): number;
100
+ /**
101
+ * The host's linear memory, which the page instantiates the module over. A static method, not
102
+ * a free function: a free function's wasm export takes its own name, and `memory` is already
103
+ * the name of the module's memory export, so the module would not compile.
104
+ */
105
+ static memory(): any;
106
+ constructor(probe_json: string);
107
+ /**
108
+ * The next token as JSON: `{ token, text, done, finishReason, promptTokens, cachedTokens, completionTokens }`, plus
109
+ * `logprobs: [{ token, logprob }, ...]` when the options asked for them and the row has a finite entry.
110
+ */
111
+ next(): any;
112
+ /**
113
+ * [`CaldrixWeb::precheck`] over a GGUF file's head: `header` is enough of it for the header
114
+ * to parse ([`CaldrixWeb::gguf_header_need`] answers 0), `file_bytes` the alias's pinned size.
115
+ */
116
+ precheckGguf(header: Uint8Array, file_bytes: number, request_json: string): any;
117
+ precheck(config_json: Uint8Array, index_json: Uint8Array | null | undefined, request_json: string): any;
118
+ static resolveAlias(name: string): any;
119
+ /**
120
+ * The launches of `kind` (`"prefill"` with `n` rows from the argument block's `Pos` word,
121
+ * `"step"` at position `n_or_pos`) as `launches_to_words`' flat list. A call the program
122
+ * refuses is the wasm entry's status as a `backend` error ("prefill returned status 2", "step
123
+ * returned status 1").
124
+ */
125
+ resolve(kind: string, n_or_pos: number): Uint32Array;
126
+ startChatSplit(messages_json: string, options_json: string): any;
127
+ startChat(messages_json: string, options_json: string): number;
128
+ startCompleteSplit(text: string | null | undefined, ids: Uint32Array | null | undefined, options_json: string): any;
129
+ startComplete(text: string | null | undefined, ids: Uint32Array | null | undefined, options_json: string): number;
130
+ /**
131
+ * The logits row's length in f32 ([`Placed::vocab`]), `0` when nothing is loaded.
132
+ */
133
+ vocab(): number;
134
+ static weightFiles(index_json?: Uint8Array | null): any;
135
+ /**
136
+ * The runtime's readback of the `logits` buffer, written into the host's `Logits` row, where
137
+ * `finishStart`/`finishNext` read it; a length other than `vocab` f32 is refused.
138
+ */
139
+ writeLogits(bytes: Uint8Array): void;
140
+ }
141
+
142
+ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
143
+
144
+ export interface InitOutput {
145
+ readonly memory: WebAssembly.Memory;
146
+ readonly __wbg_caldrixweb_free: (a: number, b: number) => void;
147
+ readonly caldrixweb_abort: (a: number) => void;
148
+ readonly caldrixweb_actIn: (a: number, b: number, c: number) => void;
149
+ readonly caldrixweb_argsPtr: (a: number) => number;
150
+ readonly caldrixweb_attach: (a: number, b: number, c: number, d: number) => void;
151
+ readonly caldrixweb_beginNext: (a: number, b: number) => void;
152
+ readonly caldrixweb_bufferBytes: (a: number, b: number, c: number) => void;
153
+ readonly caldrixweb_dispose: (a: number) => void;
154
+ readonly caldrixweb_doctor: (a: number, b: number) => void;
155
+ readonly caldrixweb_failLaunch: (a: number, b: number, c: number, d: number) => void;
156
+ readonly caldrixweb_finishNext: (a: number, b: number) => void;
157
+ readonly caldrixweb_finishStart: (a: number, b: number) => void;
158
+ readonly caldrixweb_ggufHeaderFirstRange: () => number;
159
+ readonly caldrixweb_ggufHeaderNeed: (a: number, b: number, c: number, d: number) => void;
160
+ readonly caldrixweb_listAliases: (a: number) => void;
161
+ readonly caldrixweb_load: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number) => void;
162
+ readonly caldrixweb_loadGguf: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
163
+ readonly caldrixweb_loadWebGpu: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number) => void;
164
+ readonly caldrixweb_loadWebGpuGguf: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
165
+ readonly caldrixweb_logitsPtr: (a: number, b: number) => void;
166
+ readonly caldrixweb_memory: () => number;
167
+ readonly caldrixweb_new: (a: number, b: number, c: number) => void;
168
+ readonly caldrixweb_next: (a: number, b: number) => void;
169
+ readonly caldrixweb_precheck: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
170
+ readonly caldrixweb_precheckGguf: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => void;
171
+ readonly caldrixweb_resolve: (a: number, b: number, c: number, d: number, e: number) => void;
172
+ readonly caldrixweb_resolveAlias: (a: number, b: number, c: number) => void;
173
+ readonly caldrixweb_startChat: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
174
+ readonly caldrixweb_startChatSplit: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
175
+ readonly caldrixweb_startComplete: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
176
+ readonly caldrixweb_startCompleteSplit: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
177
+ readonly caldrixweb_vocab: (a: number, b: number) => void;
178
+ readonly caldrixweb_weightFiles: (a: number, b: number, c: number) => void;
179
+ readonly caldrixweb_writeLogits: (a: number, b: number, c: number, d: number) => void;
180
+ readonly __wbindgen_export: (a: number, b: number) => number;
181
+ readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
182
+ readonly __wbindgen_export3: (a: number) => void;
183
+ readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
184
+ }
185
+
186
+ export type SyncInitInput = BufferSource | WebAssembly.Module;
187
+
188
+ /**
189
+ * Instantiates the given `module`, which can either be bytes or
190
+ * a precompiled `WebAssembly.Module`.
191
+ *
192
+ * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
193
+ *
194
+ * @returns {InitOutput}
195
+ */
196
+ export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
197
+
198
+ /**
199
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
200
+ * for everything else, calls `WebAssembly.instantiate` directly.
201
+ *
202
+ * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
203
+ *
204
+ * @returns {Promise<InitOutput>}
205
+ */
206
+ export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
@@ -0,0 +1 @@
1
+ class G{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,N.unregister(this),e}free(){const e=this.__destroy_into_raw();t.__wbg_caldrixweb_free(e,0)}abort(){t.caldrixweb_abort(this.__wbg_ptr)}actIn(e){try{const s=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_actIn(s,this.__wbg_ptr,e);var n=a().getInt32(s+0,!0),_=a().getInt32(s+4,!0),r=a().getInt32(s+8,!0);if(r)throw c(_);return c(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}argsPtr(){return t.caldrixweb_argsPtr(this.__wbg_ptr)>>>0}attach(e,n){try{const s=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_attach(s,this.__wbg_ptr,y(e),y(n));var _=a().getInt32(s+0,!0),r=a().getInt32(s+4,!0);if(r)throw c(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}beginNext(){try{const r=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_beginNext(r,this.__wbg_ptr);var e=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0),_=a().getInt32(r+8,!0);if(_)throw c(n);return c(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}bufferBytes(e){try{const s=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_bufferBytes(s,this.__wbg_ptr,e);var n=a().getInt32(s+0,!0),_=a().getInt32(s+4,!0),r=a().getInt32(s+8,!0);if(r)throw c(_);return c(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}dispose(){t.caldrixweb_dispose(this.__wbg_ptr)}doctor(){try{const r=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_doctor(r,this.__wbg_ptr);var e=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0),_=a().getInt32(r+8,!0);if(_)throw c(n);return c(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}failLaunch(e){try{const r=t.__wbindgen_add_to_stack_pointer(-16),s=f(e,t.__wbindgen_export,t.__wbindgen_export2),o=g;t.caldrixweb_failLaunch(r,this.__wbg_ptr,s,o);var n=a().getInt32(r+0,!0),_=a().getInt32(r+4,!0);if(_)throw c(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}finishNext(){try{const r=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_finishNext(r,this.__wbg_ptr);var e=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0),_=a().getInt32(r+8,!0);if(_)throw c(n);return c(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}finishStart(){try{const _=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_finishStart(_,this.__wbg_ptr);var e=a().getInt32(_+0,!0),n=a().getInt32(_+4,!0);if(n)throw c(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}static ggufHeaderFirstRange(){return t.caldrixweb_ggufHeaderFirstRange()}static ggufHeaderNeed(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),d=h(e,t.__wbindgen_export),b=g;t.caldrixweb_ggufHeaderNeed(o,d,b,n);var _=a().getFloat64(o+0,!0),r=a().getInt32(o+8,!0),s=a().getInt32(o+12,!0);if(s)throw c(r);return _}finally{t.__wbindgen_add_to_stack_pointer(16)}}static listAliases(){try{const r=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_listAliases(r);var e=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0),_=a().getInt32(r+8,!0);if(_)throw c(n);return c(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}loadGguf(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),d=h(e,t.__wbindgen_export),b=g,u=f(n,t.__wbindgen_export,t.__wbindgen_export2),l=g;t.caldrixweb_loadGguf(o,this.__wbg_ptr,d,b,u,l);var _=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),s=a().getInt32(o+8,!0);if(s)throw c(r);return c(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}loadWebGpuGguf(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),d=h(e,t.__wbindgen_export),b=g,u=f(n,t.__wbindgen_export,t.__wbindgen_export2),l=g;t.caldrixweb_loadWebGpuGguf(o,this.__wbg_ptr,d,b,u,l);var _=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),s=a().getInt32(o+8,!0);if(s)throw c(r);return c(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}loadWebGpu(e,n,_,r,s){try{const w=t.__wbindgen_add_to_stack_pointer(-16),x=h(e,t.__wbindgen_export),I=g,M=h(n,t.__wbindgen_export),T=g;var o=v(_)?0:h(_,t.__wbindgen_export),d=g;const C=f(s,t.__wbindgen_export,t.__wbindgen_export2),j=g;t.caldrixweb_loadWebGpu(w,this.__wbg_ptr,x,I,M,T,o,d,y(r),C,j);var b=a().getInt32(w+0,!0),u=a().getInt32(w+4,!0),l=a().getInt32(w+8,!0);if(l)throw c(u);return c(b)}finally{t.__wbindgen_add_to_stack_pointer(16)}}load(e,n,_,r,s){try{const w=t.__wbindgen_add_to_stack_pointer(-16),x=h(e,t.__wbindgen_export),I=g,M=h(n,t.__wbindgen_export),T=g;var o=v(_)?0:h(_,t.__wbindgen_export),d=g;const C=f(s,t.__wbindgen_export,t.__wbindgen_export2),j=g;t.caldrixweb_load(w,this.__wbg_ptr,x,I,M,T,o,d,y(r),C,j);var b=a().getInt32(w+0,!0),u=a().getInt32(w+4,!0),l=a().getInt32(w+8,!0);if(l)throw c(u);return c(b)}finally{t.__wbindgen_add_to_stack_pointer(16)}}logitsPtr(){try{const r=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_logitsPtr(r,this.__wbg_ptr);var e=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0),_=a().getInt32(r+8,!0);if(_)throw c(n);return e>>>0}finally{t.__wbindgen_add_to_stack_pointer(16)}}static memory(){const e=t.caldrixweb_memory();return c(e)}constructor(e){try{const s=t.__wbindgen_add_to_stack_pointer(-16),o=f(e,t.__wbindgen_export,t.__wbindgen_export2),d=g;t.caldrixweb_new(s,o,d);var n=a().getInt32(s+0,!0),_=a().getInt32(s+4,!0),r=a().getInt32(s+8,!0);if(r)throw c(_);return this.__wbg_ptr=n,N.register(this,this.__wbg_ptr,this),this}finally{t.__wbindgen_add_to_stack_pointer(16)}}next(){try{const r=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_next(r,this.__wbg_ptr);var e=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0),_=a().getInt32(r+8,!0);if(_)throw c(n);return c(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}precheckGguf(e,n,_){try{const d=t.__wbindgen_add_to_stack_pointer(-16),b=h(e,t.__wbindgen_export),u=g,l=f(_,t.__wbindgen_export,t.__wbindgen_export2),w=g;t.caldrixweb_precheckGguf(d,this.__wbg_ptr,b,u,n,l,w);var r=a().getInt32(d+0,!0),s=a().getInt32(d+4,!0),o=a().getInt32(d+8,!0);if(o)throw c(s);return c(r)}finally{t.__wbindgen_add_to_stack_pointer(16)}}precheck(e,n,_){try{const u=t.__wbindgen_add_to_stack_pointer(-16),l=h(e,t.__wbindgen_export),w=g;var r=v(n)?0:h(n,t.__wbindgen_export),s=g;const x=f(_,t.__wbindgen_export,t.__wbindgen_export2),I=g;t.caldrixweb_precheck(u,this.__wbg_ptr,l,w,r,s,x,I);var o=a().getInt32(u+0,!0),d=a().getInt32(u+4,!0),b=a().getInt32(u+8,!0);if(b)throw c(d);return c(o)}finally{t.__wbindgen_add_to_stack_pointer(16)}}static resolveAlias(e){try{const s=t.__wbindgen_add_to_stack_pointer(-16),o=f(e,t.__wbindgen_export,t.__wbindgen_export2),d=g;t.caldrixweb_resolveAlias(s,o,d);var n=a().getInt32(s+0,!0),_=a().getInt32(s+4,!0),r=a().getInt32(s+8,!0);if(r)throw c(_);return c(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}resolve(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),d=f(e,t.__wbindgen_export,t.__wbindgen_export2),b=g;t.caldrixweb_resolve(o,this.__wbg_ptr,d,b,n);var _=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),s=a().getInt32(o+8,!0);if(s)throw c(r);return c(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}startChatSplit(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),d=f(e,t.__wbindgen_export,t.__wbindgen_export2),b=g,u=f(n,t.__wbindgen_export,t.__wbindgen_export2),l=g;t.caldrixweb_startChatSplit(o,this.__wbg_ptr,d,b,u,l);var _=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),s=a().getInt32(o+8,!0);if(s)throw c(r);return c(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}startChat(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),d=f(e,t.__wbindgen_export,t.__wbindgen_export2),b=g,u=f(n,t.__wbindgen_export,t.__wbindgen_export2),l=g;t.caldrixweb_startChat(o,this.__wbg_ptr,d,b,u,l);var _=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),s=a().getInt32(o+8,!0);if(s)throw c(r);return _>>>0}finally{t.__wbindgen_add_to_stack_pointer(16)}}startCompleteSplit(e,n,_){try{const w=t.__wbindgen_add_to_stack_pointer(-16);var r=v(e)?0:f(e,t.__wbindgen_export,t.__wbindgen_export2),s=g,o=v(n)?0:V(n,t.__wbindgen_export),d=g;const x=f(_,t.__wbindgen_export,t.__wbindgen_export2),I=g;t.caldrixweb_startCompleteSplit(w,this.__wbg_ptr,r,s,o,d,x,I);var b=a().getInt32(w+0,!0),u=a().getInt32(w+4,!0),l=a().getInt32(w+8,!0);if(l)throw c(u);return c(b)}finally{t.__wbindgen_add_to_stack_pointer(16)}}startComplete(e,n,_){try{const w=t.__wbindgen_add_to_stack_pointer(-16);var r=v(e)?0:f(e,t.__wbindgen_export,t.__wbindgen_export2),s=g,o=v(n)?0:V(n,t.__wbindgen_export),d=g;const x=f(_,t.__wbindgen_export,t.__wbindgen_export2),I=g;t.caldrixweb_startComplete(w,this.__wbg_ptr,r,s,o,d,x,I);var b=a().getInt32(w+0,!0),u=a().getInt32(w+4,!0),l=a().getInt32(w+8,!0);if(l)throw c(u);return b>>>0}finally{t.__wbindgen_add_to_stack_pointer(16)}}vocab(){try{const r=t.__wbindgen_add_to_stack_pointer(-16);t.caldrixweb_vocab(r,this.__wbg_ptr);var e=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0),_=a().getInt32(r+8,!0);if(_)throw c(n);return e>>>0}finally{t.__wbindgen_add_to_stack_pointer(16)}}static weightFiles(e){try{const d=t.__wbindgen_add_to_stack_pointer(-16);var n=v(e)?0:h(e,t.__wbindgen_export),_=g;t.caldrixweb_weightFiles(d,n,_);var r=a().getInt32(d+0,!0),s=a().getInt32(d+4,!0),o=a().getInt32(d+8,!0);if(o)throw c(s);return c(r)}finally{t.__wbindgen_add_to_stack_pointer(16)}}writeLogits(e){try{const r=t.__wbindgen_add_to_stack_pointer(-16),s=h(e,t.__wbindgen_export),o=g;t.caldrixweb_writeLogits(r,this.__wbg_ptr,s,o);var n=a().getInt32(r+0,!0),_=a().getInt32(r+4,!0);if(_)throw c(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&(G.prototype[Symbol.dispose]=G.prototype.free);function D(){return{__proto__:null,"./caldrix_web_bg.js":{__proto__:null,__wbg___wbindgen_memory_caa4a6165639c8b5:function(){const e=t.memory;return y(e)},__wbg___wbindgen_number_get_2e0e7dee9f701a71:function(e,n){const _=p(n),r=typeof _=="number"?_:void 0;a().setFloat64(e+8,v(r)?0:r,!0),a().setInt32(e+0,!v(r),!0)},__wbg___wbindgen_string_get_0380ccaa2f57f0d9:function(e,n){const _=p(n),r=typeof _=="string"?_:void 0;var s=v(r)?0:f(r,t.__wbindgen_export,t.__wbindgen_export2),o=g;a().setInt32(e+4,o,!0),a().setInt32(e+0,s,!0)},__wbg___wbindgen_throw_41e9ee4f547fc59a:function(e,n){throw new Error(B(e,n))},__wbg_call_1875a20c43a36133:function(){return U(function(e,n,_,r){const s=p(e).call(p(n),p(_),p(r));return y(s)},arguments)},__wbg_call_187d372bd5fdd4aa:function(){return U(function(e,n,_){const r=p(e).call(p(n),p(_));return y(r)},arguments)},__wbg_getRandomValues_a608c4436c19407a:function(){return U(function(e,n){globalThis.crypto.getRandomValues(E(e,n))},arguments)},__wbg_get_unchecked_288889d017702237:function(e,n){const _=p(e)[n>>>0];return y(_)},__wbg_instanceof_Error_80a725f81f2e102d:function(e){let n;try{n=p(e)instanceof Error}catch{n=!1}return n},__wbg_instanceof_Uint8Array_828cef2aaacafc31:function(e){let n;try{n=p(e)instanceof Uint8Array}catch{n=!1}return n},__wbg_length_7f3c00c40364105e:function(e){return p(e).length},__wbg_length_d4bdea10311bd9cf:function(e){return p(e).length},__wbg_message_5f8387f0c32b90a7:function(e){const n=p(e).message;return y(n)},__wbg_new_617a8cdb8bb1130e:function(){const e=new Object;return y(e)},__wbg_new_ee2291f50781bf1d:function(){const e=new Array;return y(e)},__wbg_new_from_slice_37a3c3a194266cb8:function(e,n){const _=new Uint32Array($(e,n));return y(_)},__wbg_new_from_slice_9a868026ffa4208a:function(e,n){const _=new Uint8Array(E(e,n));return y(_)},__wbg_prototypesetcall_bc27214492979395:function(e,n,_){Uint8Array.prototype.set.call(E(e,n),p(_))},__wbg_push_2baf45db356cf468:function(e,n){return p(e).push(p(n))},__wbg_set_145a351398b48c65:function(){return U(function(e,n,_){return Reflect.set(p(e),p(n),p(_))},arguments)},__wbindgen_generic_0000000000000001:function(e){return y(e)},__wbindgen_generic_0000000000000002:function(e,n){const _=B(e,n);return y(_)},__wbindgen_object_drop_ref:function(e){c(e)}}}}const N=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(i=>t.__wbg_caldrixweb_free(i,1));function y(i){S===k.length&&k.push(k.length+1);const e=S;return S=k[e],k[e]=i,e}function z(i){i<1028||(k[i]=S,S=i)}function $(i,e){return i=i>>>0,P().subarray(i/4,i/4+e)}function E(i,e){return i=i>>>0,A().subarray(i/1,i/1+e)}let m=null;function a(){return(m===null||m.buffer.detached===!0||m.buffer.detached===void 0&&m.buffer!==t.memory.buffer)&&(m=new DataView(t.memory.buffer)),m}function B(i,e){return X(i>>>0,e)}let W=null;function P(){return(W===null||W.byteLength===0)&&(W=new Uint32Array(t.memory.buffer)),W}let R=null;function A(){return(R===null||R.byteLength===0)&&(R=new Uint8Array(t.memory.buffer)),R}function p(i){return k[i]}function U(i,e){try{return i.apply(this,e)}catch(n){t.__wbindgen_export3(y(n))}}let k=new Array(1024).fill(void 0);k.push(void 0,null,!0,!1);let S=k.length;function v(i){return i==null}function V(i,e){const n=e(i.length*4,4)>>>0;return P().set(i,n/4),g=i.length,n}function h(i,e){const n=e(i.length*1,1)>>>0;return A().set(i,n/1),g=i.length,n}function f(i,e,n){if(n===void 0){const d=O.encode(i),b=e(d.length,1)>>>0;return A().subarray(b,b+d.length).set(d),g=d.length,b}let _=i.length,r=e(_,1)>>>0;const s=A();let o=0;for(;o<_;o++){const d=i.charCodeAt(o);if(d>127)break;s[r+o]=d}if(o!==_){o!==0&&(i=i.slice(o)),r=n(r,_,_=o+i.length*3,1)>>>0;const d=A().subarray(r+o,r+_),b=O.encodeInto(i,d);o+=b.written,r=n(r,_,o,1)>>>0}return g=o,r}function c(i){const e=p(i);return z(i),e}let F=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});F.decode();const q=2146435072;let L=0;function X(i,e){return L+=e,L>=q&&(F=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),F.decode(),L=e),F.decode(A().subarray(i,i+e))}const O=new TextEncoder;"encodeInto"in O||(O.encodeInto=function(i,e){const n=O.encode(i);return e.set(n),{read:i.length,written:n.length}});let g=0,Y,J,t;function H(i,e){return J=i,t=i.exports,Y=e,m=null,W=null,R=null,t}async function K(i,e){if(typeof Response=="function"&&i instanceof Response){if(!i.ok)throw new Error(`failed to fetch Wasm: ${i.status} ${i.statusText} fetching '${i.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(i,e)}catch(r){if(n(i.type)&&i.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}const _=await i.arrayBuffer();return await WebAssembly.instantiate(_,e)}else{const _=await WebAssembly.instantiate(i,e);return _ instanceof WebAssembly.Instance?{instance:_,module:i}:_}function n(_){switch(_){case"basic":case"cors":case"default":return!0}return!1}}function Q(i){if(t!==void 0)return t;i!==void 0&&(Object.getPrototypeOf(i)===Object.prototype?{module:i}=i:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const e=D();i instanceof WebAssembly.Module||(i=new WebAssembly.Module(i));const n=new WebAssembly.Instance(i,e);return H(n,i)}async function Z(i){if(t!==void 0)return t;i!==void 0&&(Object.getPrototypeOf(i)===Object.prototype?{module_or_path:i}=i:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),i===void 0&&(i=new URL("caldrix_web_bg.wasm",import.meta.url));const e=D();(typeof i=="string"||typeof Request=="function"&&i instanceof Request||typeof URL=="function"&&i instanceof URL)&&(i=fetch(i));const{instance:n,module:_}=await K(await i,e);return H(n,_)}export{G as CaldrixWeb,Z as default,Q as initSync};
Binary file
@@ -0,0 +1,41 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const __wbg_caldrixweb_free: (a: number, b: number) => void;
5
+ export const caldrixweb_abort: (a: number) => void;
6
+ export const caldrixweb_actIn: (a: number, b: number, c: number) => void;
7
+ export const caldrixweb_argsPtr: (a: number) => number;
8
+ export const caldrixweb_attach: (a: number, b: number, c: number, d: number) => void;
9
+ export const caldrixweb_beginNext: (a: number, b: number) => void;
10
+ export const caldrixweb_bufferBytes: (a: number, b: number, c: number) => void;
11
+ export const caldrixweb_dispose: (a: number) => void;
12
+ export const caldrixweb_doctor: (a: number, b: number) => void;
13
+ export const caldrixweb_failLaunch: (a: number, b: number, c: number, d: number) => void;
14
+ export const caldrixweb_finishNext: (a: number, b: number) => void;
15
+ export const caldrixweb_finishStart: (a: number, b: number) => void;
16
+ export const caldrixweb_ggufHeaderFirstRange: () => number;
17
+ export const caldrixweb_ggufHeaderNeed: (a: number, b: number, c: number, d: number) => void;
18
+ export const caldrixweb_listAliases: (a: number) => void;
19
+ export const caldrixweb_load: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number) => void;
20
+ export const caldrixweb_loadGguf: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
21
+ export const caldrixweb_loadWebGpu: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number) => void;
22
+ export const caldrixweb_loadWebGpuGguf: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
23
+ export const caldrixweb_logitsPtr: (a: number, b: number) => void;
24
+ export const caldrixweb_memory: () => number;
25
+ export const caldrixweb_new: (a: number, b: number, c: number) => void;
26
+ export const caldrixweb_next: (a: number, b: number) => void;
27
+ export const caldrixweb_precheck: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
28
+ export const caldrixweb_precheckGguf: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => void;
29
+ export const caldrixweb_resolve: (a: number, b: number, c: number, d: number, e: number) => void;
30
+ export const caldrixweb_resolveAlias: (a: number, b: number, c: number) => void;
31
+ export const caldrixweb_startChat: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
32
+ export const caldrixweb_startChatSplit: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
33
+ export const caldrixweb_startComplete: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
34
+ export const caldrixweb_startCompleteSplit: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
35
+ export const caldrixweb_vocab: (a: number, b: number) => void;
36
+ export const caldrixweb_weightFiles: (a: number, b: number, c: number) => void;
37
+ export const caldrixweb_writeLogits: (a: number, b: number, c: number, d: number) => void;
38
+ export const __wbindgen_export: (a: number, b: number) => number;
39
+ export const __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
40
+ export const __wbindgen_export3: (a: number) => void;
41
+ export const __wbindgen_add_to_stack_pointer: (a: number) => number;