@caldrix-ai/caldrix 0.1.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -3,6 +3,47 @@
3
3
  Format after [Keep a Changelog](https://keepachangelog.com/); versions are independent semver, tagged
4
4
  `caldrix-js-v<version>`.
5
5
 
6
+ ## 0.3.0 — 2026-11-02
7
+
8
+ ### Added
9
+
10
+ - `Caldrix.load` takes a Hugging Face repo id, `owner/name[@revision]`, beside the aliases: resolved once to its canonical id and commit sha through the Hub's model API, every file fetched and cached at that sha, a gated repo is refused by name, a private one reads as not found (the Hub answers it as it answers a missing repo), and the caldrix CLI, which reads `HF_TOKEN`, loads both.
11
+ - `Caldrix.load` loads a PEFT LoRA adapter repo, a bitsandbytes nf4 repo and a LoRA adapter over an nf4 base by repo id, densified at import (run in headless Chromium over a loopback hub on the wasm tier only; the WebGPU tier's densified load has run off-browser only, and `loadWebGpu`'s densified branch in no harness); `doctor().provenance` and `doctor().note`, and `repo`, `revision` and `provenance` on progress events.
12
+
13
+ ### Changed
14
+
15
+ - A model's `chat_template.jinja` is fetched beside `tokenizer_config.json` and wins over the config's `chat_template` key, as transformers 5 writes it. With neither, the error reads "the model directory has neither chat_template.jinja nor a chat_template in tokenizer_config.json".
16
+ - The quantized aliases `smollm2-instruct:q4_K_M` and `smollm2-instruct:q8_0` are recognized and both tiers have their kernels: a load reads the GGUF header with a range request, verifies the file against the alias's pinned sha256 before parsing it, and runs the quantized kernels on the tier that serves it; what has actually run is recorded under the README's "What has run, and where". `backend: "auto"` chooses the tier for a quantized alias as for a dense one, and on the WebGPU tier the weights stay in their blocks: `doctor().storage` is `"blocks"`.
17
+ - The README's "What has run, and where" states that the quantized aliases ran on a real adapter: on the operator's Mac through `Caldrix.load` on both tiers, WebGPU on the Mac's own adapter, vendor `apple`, architecture `metal-3`, token-exact (`inferno/WEB-VERIFICATION.md` entry 14).
18
+
19
+ ## 0.2.1 — 2026-10-30
20
+
21
+ ### Fixed
22
+
23
+ - The doctor's `device` on WebGPU names what the browser gives: the adapter's description, else its
24
+ vendor and architecture, else `webgpu (unnamed adapter)`. A browser that blanks all three (Brave's
25
+ fingerprinting protection does) printed `webgpu ( )`. `adapter` still carries the raw strings.
26
+
27
+ ## 0.2.0 — 2026-10-29
28
+
29
+ ### Added
30
+
31
+ - The `constraint` generation option: `{ json: <schema> }` restricts the text to a JSON value matching a
32
+ schema from a documented subset, `{ oneOf: [<string>, ...] }` to exactly one of the strings. Both
33
+ tiers. A refusal (an unsupported schema keyword, an empty `oneOf`) is a `CaldrixError` of kind
34
+ `request`. See "Constrained decoding" in the README.
35
+ - Prefix reuse: a generation starts from the context the previous one on the same engine left when the
36
+ new prompt begins with the same tokens, and `usage.cachedTokens` on the last delta reports how many
37
+ prompt tokens were reused.
38
+ - The `logprobs` generation option (at most 20) and `Delta.logprobs`: the top candidates, as
39
+ `{ token, logprob }`, for each token.
40
+ - `doctor().aliases`: every alias this build loads, each with its `format` (`safetensors` or `gguf`).
41
+
42
+ ### Changed
43
+
44
+ - The quantized aliases `smollm2-instruct:q4_K_M` and `smollm2-instruct:q8_0` are recognized and the wasm tier has their kernels: a load reads the GGUF header with a range request, verifies the file against the alias's pinned sha256 before parsing it, and runs the quantized kernels on the wasm tier; what has actually run is recorded under the README's "What has run, and where". The WebGPU tier has no quantized kernels in this version: `backend: "auto"` runs a quantized alias on the wasm tier and an explicit `backend: "webgpu"` is refused by name.
45
+ - A GGUF alias's file download is capped at the alias's pinned size: a longer body is refused by name before the sha256 check and nothing is cached. Offline, a cached copy that fails the pin is refused naming the pin.
46
+
6
47
  ## 0.1.0 — 2026-10-27
7
48
 
8
49
  ### Added
package/README.md CHANGED
@@ -8,7 +8,7 @@ This page states only what `inferno/WEB-VERIFICATION.md` records (in
8
8
  the Caldrix repository, which is private, so you cannot open it), what the package's own tests run in
9
9
  CI, and what the source does.
10
10
 
11
- <!-- host-commit: 16f90f2ef2c3f43cdb9c2520f8d7b573aa13a4d8 -->
11
+ <!-- host-commit: 9c890a49f6e794c2492312fc0b79d5c134054e8e -->
12
12
 
13
13
  The compiled host in `host/` is built from the `caldrix-web` crate at the commit in the marker above.
14
14
  The release workflow overwrites that marker with the commit it builds; the value in a source checkout
@@ -39,7 +39,7 @@ The API, as the package's declarations have it:
39
39
 
40
40
  ```ts
41
41
  class Caldrix {
42
- static load(alias: string, opts?: LoadOptions): Promise<Engine>;
42
+ static load(model: string, opts?: LoadOptions): Promise<Engine>;
43
43
  }
44
44
  class Engine {
45
45
  chat(messages: ChatMessage[], opts?: GenerateOptions): AsyncIterable<Delta>;
@@ -51,18 +51,28 @@ class Engine {
51
51
  declare function probe(): Promise<Capabilities>;
52
52
  ```
53
53
 
54
- A `Delta` is `{ text, token?, done, finishReason?: "stop" | "length" | "abort", usage? }`. Generation
55
- options are `temperature`, `topK`, `topP`, `minP`, `repetitionPenalty`, `seed` and `maxTokens`, plus a
56
- `signal` (an `AbortSignal`). Errors are `CaldrixError` with a `kind` of `probe`, `fit`, `architecture`,
54
+ `model` is an alias this build ships (`doctor().aliases`) or a Hugging Face repo id, `owner/name` or `owner/name@<revision>`. A repo id is resolved once through the Hub's model API to its canonical id and commit sha, and every file is fetched and cached at that sha; `doctor().model` and `doctor().revision` are the canonical id and the sha, and the doctor line says `(resolved from <id>)` when the canonical id differs from the one asked (a rename, or a different letter case). The browser build sends no token: a gated repo is refused by name, a private one reads as not found (the Hub answers it as it answers a missing repo), and the caldrix CLI, which reads `HF_TOKEN`, loads both. A repo id loads a dense Llama-family checkpoint, a bitsandbytes nf4 checkpoint (dequantized to the plan dtype at import: it runs at its dense size, not its download size; `doctor().note` says both), a PEFT LoRA adapter repo (its base, named by `adapter_config.json`, resolved once through the Hub's model API, and the adapter folded into it tensor by tensor at import), or a LoRA adapter over an nf4 base. `doctor().provenance` is the caldrix CLI's `model:` line, naming both repos and shas; progress events name the repo each file comes from. Folded weights are never cached: a repeat load fetches nothing new and folds again. A gated base, an adapter over an adapter, a pickle-only adapter and a repo carrying both a model and an adapter are refused by name before any weight byte.
55
+
56
+ A `Delta` is `{ text, token?, done, finishReason?: "stop" | "length" | "abort", usage?, logprobs? }`. Generation
57
+ options are `temperature`, `topK`, `topP`, `minP`, `repetitionPenalty`, `seed`, `maxTokens` and
58
+ `constraint` (see "Constrained decoding"), `logprobs`, plus a `signal` (an `AbortSignal`). Errors are `CaldrixError` with a `kind` of `probe`, `fit`, `architecture`,
57
59
  `fetch`, `digest`, `validate`, `lowering`, `backend` or `request`.
58
60
 
61
+ Prefix reuse: a generation starts from the context the previous one on the same engine left whenever
62
+ the new prompt begins with the same tokens, so only the rest is prefilled (a chat that appends a turn,
63
+ when its rendered prompt begins with the same tokens). The last delta's `usage.cachedTokens` is the number of prompt tokens
64
+ that were reused, 0 when none were.
65
+
66
+ `logprobs: n` (an integer, at most 20; more is a `request` error) adds `logprobs: { token, logprob }[]`
67
+ to each token's delta: up to `n` candidates for that step (fewer under a constraint).
68
+
59
69
  ## Options
60
70
 
61
71
  ```ts
62
72
  interface LoadOptions {
63
73
  backend?: "auto" | "webgpu" | "wasm" | "webgl";
64
74
  offline?: boolean;
65
- onProgress?: (p: { file: string; loaded: number; total: number | null }) => void;
75
+ onProgress?: (p: { file: string; loaded: number; total: number | null; repo: string; revision: string; provenance?: string }) => void;
66
76
  hubBaseUrl?: string;
67
77
  dtype?: "f32" | "bf16";
68
78
  maxContext?: number;
@@ -75,19 +85,62 @@ interface LoadOptions {
75
85
  - **`backend`**: `"auto"` (the default) probes the browser and picks WebGPU when an adapter is present
76
86
  and `requestDevice` succeeds, wasm otherwise; a bf16 plan goes to wasm on the page, before the worker starts. `"webgpu"` and `"wasm"` force a tier. `"webgl"` is declared and refused: the backend is
77
87
  not built. Under `"auto"`, a load WebGPU then refuses (a larger explicit context, a limit, a
78
- device that fails to open) is served by the wasm tier, and `doctor().why` says so.
88
+ device that fails to open) is served by the wasm tier, and `doctor().why` says so. A quantized alias
89
+ under `"auto"` is placed as any alias: WebGPU is probed first, and a refusal of the same kinds falls
90
+ back to wasm.
91
+ - **Quantized aliases**: `smollm2-instruct:q4_K_M` and `smollm2-instruct:q8_0` are one GGUF file each.
92
+ A load reads the file's header with a range request first, then verifies the whole file against the
93
+ alias's pinned sha256 before parsing it. Both tiers have their kernels (see "What has run, and where");
94
+ on the WebGPU tier the weights stay in their blocks and `doctor().storage` is `"blocks"`.
79
95
  - **`storage`**: the WebGPU tier's weight storage. `"auto"` stores the block GEMM weights as f16 when the
80
- adapter has `shader-f16`; `"f32"` keeps them f32 on any adapter. `doctor().storage` reports it (`null`
81
- on wasm). `storage: "f32"` with `backend: "wasm"` is refused.
82
- - **`hubBaseUrl`**: where model files are fetched from (default `https://huggingface.co`). `offline`
96
+ adapter has `shader-f16`; `"f32"` keeps them f32 on any adapter. `storage: "f32"` on a quantized alias
97
+ is satisfied: nothing is narrowed, and the weights stay in their blocks. `doctor().storage` reports it
98
+ (`"blocks"` for a quantized alias, `null` on wasm). `storage: "f32"` with `backend: "wasm"` is refused.
99
+ - **`hubBaseUrl`**: where the model files and, for a repo id, the Hub listing (`/api/models/…`) are fetched from (default `https://huggingface.co`); a mirror serving only files loads aliases but not repo ids. `offline`
83
100
  uses only the browser's cache and fails with `fetch` for a file it lacks.
84
101
  - **`assets`**: where the package's own files come from; see "Network" below.
85
102
  - **`doctor()`** reports the tier that runs, `device`, `dtype`, `storage`, `adapter`, on WebGPU only `maxContext` and `contextClamp`, where each model file came from and whether its digest was checked, `assets` (the
86
- source and URL of the worker and the `.wasm`: `bundle`, `cdn` or `page`), and `why`.
103
+ source and URL of the worker and the `.wasm`: `bundle`, `cdn` or `page`), `aliases` (every alias
104
+ this build loads, each with its `format`, `safetensors` or `gguf`), `provenance` (a densified load's `model:` line, `null` for a model read as it lies), `note` (an nf4 repo's 4-bit note, `null` otherwise), and `why`.
105
+
106
+ ## Constrained decoding
107
+
108
+ ```ts
109
+ interface GenerationOptions {
110
+ // temperature, topK, topP, minP, repetitionPenalty, seed, maxTokens as above
111
+ constraint?: { json: Record<string, unknown> } | { oneOf: string[] };
112
+ logprobs?: number;
113
+ }
114
+ ```
115
+
116
+ `constraint` limits what the model may write, on both tiers. `{ oneOf: ["yes", "no"] }` yields exactly
117
+ one of the strings and stops. `{ json: <schema> }` yields a JSON value matching the schema.
118
+
119
+ - **Reachable options.** A `oneOf` option is guaranteed reachable only when it is ASCII.
120
+ - **The schema subset.** `type` is `object` (with `properties`, `required`, and `additionalProperties:
121
+ false`), `array` (`items`), `string` (`maxLength`), `number`, `integer`, `boolean` or `null`; `enum`
122
+ works on any type; `oneOf` and `anyOf` of those mean "any branch may match". The annotation keywords
123
+ `description`, `title`, `default`, `$schema`, `$comment` and `examples` are accepted and ignored. `$ref`
124
+ and every other keyword are refused by name, as is a schema with no `type`, `enum`, `oneOf` or
125
+ `anyOf`, and a schema that is not an object (a bare `true` or `false`). When `additionalProperties` is
126
+ absent, any other key is allowed and its value may be any JSON value; an array with no `items` holds
127
+ any JSON values. `integer` refuses a `.` or an exponent. Keys and `enum` members are matched by their
128
+ JSON text, so an escaped spelling of a key is not that key.
129
+ - **A refusal** (an unsupported keyword, an empty `oneOf`) is a `CaldrixError` of kind `request`
130
+ whose message starts `constraint: `.
131
+ - **The vocabulary** the masks read is built on the first constrained generation per loaded model, so
132
+ that request pays for it.
133
+ - **Stopping.** A JSON value stops when it is complete. Nothing forces a model to finish one: a
134
+ generation can end at `maxTokens` with `finishReason: "length"` and an incomplete value.
135
+ - There is no grammar constraint.
136
+ - What has run: the package's own tests, on a tiny character-vocabulary test model whose output is
137
+ noise, so they check the mask (`oneOf`, an `enum`, a small object schema, a refusal) and not the quality
138
+ of any model's text. `oneOf` also runs in the e2e's `chromium-webgpu` project (SwiftShader in CI).
87
139
 
88
140
  ## What has run, and where
89
141
 
90
- Only these runs are recorded (`inferno/WEB-VERIFICATION.md`, entries 5, 8 and 9); nothing else is claimed.
142
+ Only these model runs are recorded (`inferno/WEB-VERIFICATION.md`, entries 5, 8 and 9, and entries 10,
143
+ 11, 12 and 14 for the quantized aliases); nothing else is claimed.
91
144
 
92
145
  - **Model:** SmolLM2-135M-Instruct, one prompt, 8 greedy tokens. No other model or prompt.
93
146
  - **Browser:** Chromium driven by Playwright, headless only: the headless shell 153.0.8010.12 on Linux and on
@@ -105,6 +158,7 @@ Only these runs are recorded (`inferno/WEB-VERIFICATION.md`, entries 5, 8 and 9)
105
158
  not a GPU. The f32 plan at f32 weight storage, token-exact, logits worst 5.874168e-4 against the same bound.
106
159
  - **Phase 2's exit is closed on the gates** (entry 9), with the run's two process deviations recorded there:
107
160
  the browser stages ran outside the sandbox, and the build's first attempt failed at its install step.
161
+ - quantized aliases: off-browser at the desk on both tiers (`inferno/WEB-VERIFICATION.md` entries 10 and 11); in headless Chromium through `Caldrix.load` on both tiers on the pinned files, WebGPU on Dawn/SwiftShader, a CPU (entry 12); on the operator's Mac through `Caldrix.load` on both tiers, WebGPU on the Mac's own adapter, vendor `apple`, architecture `metal-3`, token-exact (entry 14).
108
162
  - **Not run:** any other adapter or GPU; a headed browser; the browser stages inside a sandbox; the scalar
109
163
  (non-SIMD) wasm spelling in a browser; real-Hub digest behaviour (the runs used a loopback Hub stand-in);
110
164
  any browser other than Playwright's headless Chromium; any other model. No performance figure is recorded
@@ -120,7 +174,7 @@ default context loads at 7282; `doctor()` reports the clamp in `contextClamp` an
120
174
 
121
175
  ## Network
122
176
 
123
- No telemetry. The network is the Hub, for the model files you asked for, and jsdelivr, for the
177
+ No telemetry. The network is the Hub, for the listing (`/api/models/<id>`) and the files of the model you named, and jsdelivr, for the
124
178
  package's own assets when the bundle's copy fails.
125
179
 
126
180
  - **When the fallback fires:** the worker falls back if it fails before it is ready (its script, a chunk
@@ -136,8 +190,12 @@ package's own assets when the bundle's copy fails.
136
190
  worker can fetch your origin with its credentials and read its IndexedDB and caches), and no integrity
137
191
  check is possible for a worker's module import, so a page that cannot accept that sets
138
192
  `assets.fallback: false`.
139
- - **Not yet exercised:** until the package is on npm, the real jsdelivr path has not run; the tests point
140
- `assets.cdn` at a loopback origin.
193
+ - **What has been checked:** jsdelivr serves the published package's worker, glue and WebAssembly files
194
+ byte-identical to the npm tarball, with CORS open to any origin. After the first release was published,
195
+ the browser fallback ran once against jsdelivr itself in headless Chromium, with the default `cdn`: a
196
+ page whose bundle lacked the worker, and one whose bundle lacked the `.wasm`, each chatted to done
197
+ with `doctor()` naming the jsdelivr URLs and one warning on the console. That was a one-off check at
198
+ the desk; the committed tests point `assets.cdn` at a loopback origin and never reach jsdelivr.
141
199
  - **Content-Security-Policy:** a page that uses the fallback needs `worker-src blob:` (a cross-origin
142
200
  worker starts through a same-origin module shim), `script-src` and `connect-src` for the CDN origin,
143
201
  and `'wasm-unsafe-eval'` for any WebAssembly.
package/dist/index.d.ts CHANGED
@@ -3,6 +3,17 @@
3
3
  * and is refused there by name; `signal` is the page's and never leaves the main thread.
4
4
  */
5
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;
6
17
  temperature?: number;
7
18
  topK?: number;
8
19
  topP?: number;
@@ -44,40 +55,67 @@ interface HostDoctor {
44
55
  dtype: string | null;
45
56
  simd: boolean;
46
57
  threads: number | null;
58
+ /** The repo the files came from: for a Hub repo id, the listing's canonical id (it may differ from the one asked for). */
47
59
  model: string | null;
60
+ /** The revision the files were fetched at: for a Hub repo id, the listing's commit sha. */
48
61
  revision: string | null;
49
62
  source: null;
50
63
  line: string;
51
64
  /** WebGPU only, the host's: the context the model was loaded at, and the clamp's line when the default was clamped. */
52
65
  maxContext?: number;
53
66
  contextClamp?: string | null;
54
- /** The worker's: the weights' storage form on WebGPU (`null` on wasm). */
55
- storage: "f16" | "f32" | null;
67
+ /** The worker's: the weights' storage form on WebGPU (`blocks` for a quantized model; `null` on wasm). */
68
+ storage: "f16" | "f32" | "blocks" | null;
56
69
  /**
57
70
  * The worker's: the adapter by its own vendor and architecture strings (`null` on wasm). On
58
71
  * WebGPU `device` is the worker's too: `webgpu (<description>)`, with vendor and architecture
59
- * standing in for the description when the browser leaves it empty.
72
+ * standing in for the description when the browser leaves it empty, and `unnamed adapter` when it
73
+ * blanks all three.
60
74
  */
61
75
  adapter: {
62
76
  vendor: string;
63
77
  architecture: string;
64
78
  } | null;
79
+ /** The worker's, from the host's `listAliases`: every alias this build loads, by name and file format. */
80
+ aliases: {
81
+ name: string;
82
+ format: "safetensors" | "gguf";
83
+ }[];
84
+ /**
85
+ * The host's: a densified load's `model:` line (an adapter folded into its base, an nf4 repo
86
+ * dequantized), byte for byte the caldrix CLI's; `null` for a model read as it lies.
87
+ */
88
+ provenance: string | null;
89
+ /** The host's: an nf4 repo's 4-bit note (never a QLoRA adapter's); `null` otherwise. */
90
+ note: string | null;
65
91
  }
66
92
 
67
93
  interface LoadOptions {
68
94
  backend?: "auto" | "webgpu" | "wasm" | "webgl";
69
95
  offline?: boolean;
96
+ /**
97
+ * Each model file's download progress. `repo` and `revision` are the repo and commit the file is
98
+ * fetched from: for a LoRA adapter, the adapter's for its own files and its base's (by the
99
+ * canonical id the Hub's listing returns) for the base's. `provenance` is the `model:` line of a
100
+ * densified load (an adapter folded into its base, a bitsandbytes nf4 repo dequantized), naming
101
+ * the dtype of the tier that serves; it is set on every event once that tier is settled, and
102
+ * absent before then and for a model read as it lies.
103
+ */
70
104
  onProgress?: (p: {
71
105
  file: string;
72
106
  loaded: number;
73
107
  total: number | null;
108
+ repo: string;
109
+ revision: string;
110
+ provenance?: string;
74
111
  }) => void;
75
112
  hubBaseUrl?: string;
76
113
  dtype?: "f32" | "bf16";
77
114
  maxContext?: number;
78
115
  /**
79
116
  * The WebGPU tier's weight storage: `"auto"` (the default) stores the block GEMM weights f16 when
80
- * the adapter has `shader-f16`, `"f32"` keeps them f32 on any adapter. Under `backend: "auto"` a
117
+ * the adapter has `shader-f16`, `"f32"` keeps them f32 on any adapter; a quantized alias's weights
118
+ * stay in their blocks, so `"f32"` on one is satisfied and nothing is narrowed. Under `backend: "auto"` a
81
119
  * load the wasm tier serves ignores it; an explicit `backend: "wasm"` with `"f32"` is refused.
82
120
  */
83
121
  storage?: "auto" | "f32";
@@ -122,16 +160,24 @@ interface Delta {
122
160
  token?: number;
123
161
  done: boolean;
124
162
  finishReason?: "stop" | "length" | "abort";
163
+ /** Prompt tokens, generated tokens, and the prompt tokens served from the previous generation's context. */
125
164
  usage?: {
126
165
  promptTokens: number;
127
166
  completionTokens: number;
167
+ cachedTokens: number;
128
168
  };
169
+ /** The top logprobs for this token; present only when `logprobs` was asked for. */
170
+ logprobs?: {
171
+ token: number;
172
+ logprob: number;
173
+ }[];
129
174
  }
130
175
  /**
131
176
  * The host's doctor object, with `source` filled per file: where it came from and whether its digest
132
177
  * was checked. `backend` is the tier that runs; `why` is how it was chosen (the probe's reason under
133
- * `"auto"`, so a fallback to wasm says why -- no adapter, a bf16 request, or `webgpu refused: …`
134
- * when the WebGPU precheck or device open refused a load the wasm tier then served).
178
+ * `"auto"`, so a fallback to wasm says why -- no adapter, a bf16 request, or
179
+ * `webgpu refused: …` when the WebGPU precheck or device open refused a load the wasm tier then served).
180
+ * `aliases` is every alias this build loads, each with its file format.
135
181
  */
136
182
  interface DoctorReport extends Omit<HostDoctor, "source"> {
137
183
  source: Record<string, FileSource>;
@@ -155,8 +201,8 @@ type GenerateOptions = GenerationOptions & {
155
201
  signal?: AbortSignal;
156
202
  };
157
203
  declare class Caldrix {
158
- /** Load a model by alias into its own worker. */
159
- static load(alias: string, opts?: LoadOptions): Promise<Engine>;
204
+ /** Load a model, a built-in alias or a Hub repo id (`owner/name[@revision]`), into its own worker. */
205
+ static load(model: string, opts?: LoadOptions): Promise<Engine>;
160
206
  }
161
207
  declare class Engine {
162
208
  #private;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as J,b as i,d as H}from"./chunk-PZGTLL5H.js";function W(e){return typeof e=="object"&&e!==null}function se(e){return W(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"}function ae(e){return!W(e)||typeof e.url!="string"?!1:e.failed===void 0||W(e.failed)&&typeof e.failed.url=="string"&&typeof e.failed.reason=="string"}function T(e){if(!W(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 W(e.doctor)&&W(e.sources)&&(e.fallback===void 0||typeof e.fallback=="string")&&Object.values(e.sources).every(t=>W(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)),u=o.getExtension(n?"EXT_color_buffer_float":"WEBGL_color_buffer_float")!==null;return o.getExtension("WEBGL_lose_context")?.loseContext(),{available:!0,maxTextureSize:s,floatColorBuffer:u}}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.1.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:u,revoke:f}=s,b=()=>l(r()),l=(d,a=e.url)=>{if(f(),u.onmessage=null,u.onerror=null,t?.removeEventListener("abort",b),d===null)return n({worker:u,url:a});u.terminate(),o(d)};t?.addEventListener("abort",b,{once:!0}),u.onerror=d=>l(new C(d.message||"it did not load")),u.onmessage=d=>{let a=d.data;if(!T(a)||a.id!==0)return l(m(a));if(a.type==="ready")return s.literal?URL.canParse(a.url)?l(null,new URL(a.url)):l(m(a)):l(null);if(a.type==="error")return l(new C(a.message));l(m(a))}})}async function ve(e,t,r,n){let o=[];for(let l of e)try{let{worker:d,url:a}=await ke(l,r,n),g=o[0];return{worker:d,used:l,url:a,...g!==void 0?{failed:{what:q(g.t),reason:g.reason}}:{}}}catch(d){if(!(d instanceof C))throw d;o.push({t:l,reason:d.reason})}let[s,u]=o;if(s!==void 0&&u!==void 0){let l=u.t.url.origin;throw new i("backend",`${q(s.t)} did not start (${s.reason}), nor from the CDN fallback ${u.t.url.href} (${u.reason}); serve dist/ and host/ beside the bundle, set assets.worker to where the page serves them, or allow ${l} in the page's Content-Security-Policy (worker-src blob: for the same-origin shim that starts it, script-src ${l} for the modules it imports, connect-src ${l} 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.done&&(e.finishReason!==null&&(t.finishReason=e.finishReason),t.usage={promptTokens:e.promptTokens,completionTokens:e.completionTokens}),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),u=r.assets?.fallback??!0;if(typeof u!="boolean")throw new i("request",`assets.fallback is true or false, not ${JSON.stringify(u)}`);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"}];u&&o===void 0&&b.push({url:new URL("dist/worker.js",f),chosen:!0,source:"cdn"});let l=u&&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(),v,$;if(n==="auto"&&r.dtype==="bf16"&&p.chosen==="webgpu")v="wasm",$=`bf16 requested: wasm (the WebGPU tier runs the f32 plan only); ${p.why}`;else if(n==="auto")v=p.chosen,$=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}`);v="webgpu",$=`backend "webgpu" asked for; ${p.why}`}else v="wasm",$=`backend "wasm" asked for; ${p.why}`;let B=p.webgpu?.unrepresentable??[];if(g?.aborted)throw a();let L=await ve(b,!u,g,a),{worker:y}=L,O=L.url,R=null;L.failed!==void 0&&(R=We(L.failed,O.href,s===void 0?l: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:v,...r.dtype!==void 0?{dtype:r.dtype}:{},...r.maxContext!==void 0?{maxContext:r.maxContext}:{},...v==="webgpu"&&d==="f32"?{f16:!1}:{}},...n==="auto"&&v==="webgpu"?{auto:!0}:{},offline:r.offline??!1,hubBaseUrl:r.hubBaseUrl??me,...s!==void 0?{hostWasm:s.href}:{},...l!==void 0?{cdnWasm:l}:{}};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(!T(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=L.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}`:$,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;#o;#l=2;#t=!1;#e=null;#i=!1;#n=null;constructor(t,r){this.#r=t,this.#o=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.#o.source).map(([o,s])=>[o,{...s}])),{worker:r,hostWasm:n}=this.#o.assets;return{...this.#o,source:t,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.#n?.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.#n?.sink(t))}#d(t){if(this.#t||this.#e)return;if(!T(t))return this.#a(m(t));let r=this.#n;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}};return}this.#i=!0;let s=this.#l++,u=[],f=null;this.#n={id:s,sink:a=>{u.push(a),f?.()}};let b=()=>{!this.#t&&!this.#e&&this.#r.postMessage({id:s,type:"abort"})},l=!1,d=async()=>{for(;u.length===0;)await new Promise(a=>f=a);return f=null,u.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 l=!0,a;if(a.done&&(l=!0),yield a,a.done)return}}finally{if(n?.removeEventListener("abort",b),!l)try{for(b();!(this.#t||this.#e);){let a=await d();if(a instanceof i||a.done)break}}catch{}this.#n=null,this.#i=!1}}};export{M as Caldrix,i as CaldrixError,S as Engine,G as probe};
1
+ import{a as H,b as i,d as X}from"./chunk-PZGTLL5H.js";function W(e){return typeof e=="object"&&e!==null}function se(e){return W(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=>W(t)&&typeof t.token=="number"&&typeof t.logprob=="number"))}function ae(e){return!W(e)||typeof e.url!="string"?!1:e.failed===void 0||W(e.failed)&&typeof e.failed.url=="string"&&typeof e.failed.reason=="string"}function O(e){if(!W(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")&&typeof e.repo=="string"&&typeof e.revision=="string"&&(e.provenance===void 0||typeof e.provenance=="string");case"loaded":return W(e.doctor)&&W(e.sources)&&(e.fallback===void 0||typeof e.fallback=="string")&&Object.values(e.sources).every(t=>W(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 H(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 U=(...e)=>new Uint8Array(e),ie={simd:U(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:U(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:U(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:U(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:U(0,97,115,109,1,0,0,0,5,3,1,4,1),tailCall:U(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:U(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 K(){let e={};for(let[t,r]of Object.entries(ie))e[t]=WebAssembly.validate(r);return e}var le=1e3,G=Symbol("timed out");async function z(e){let t,r=new Promise(n=>{t=setTimeout(()=>n(G),le)});try{return await Promise.race([e,r])}finally{clearTimeout(t)}}var V=e=>e instanceof Error?e.message:String(e);function Q(){let e=globalThis.navigator;return typeof e=="object"&&e!==null?e:{}}function P(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=P(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=Q().gpu;if(!e||typeof e.requestAdapter!="function")return{webgpu:null,available:!1,reason:"no navigator.gpu"};let t;try{let n=await z(e.requestAdapter());if(n===G)return{webgpu:null,available:!1,reason:"requestAdapter timed out"};t=n}catch(n){return{webgpu:null,available:!1,reason:`requestAdapter failed: ${V(n)}`}}if(!t)return{webgpu:null,available:!1,reason:"requestAdapter returned null"};let r=await de(t);try{let n=await z(t.requestDevice());if(n===G)return{webgpu:r,available:!1,reason:"requestDevice timed out"};n.destroy?.()}catch(n){return{webgpu:r,available:!1,reason:`requestDevice refused: ${V(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 q(){let e=Q(),t=await ce(),r={wasm:K(),threads:{sharedArrayBuffer:typeof SharedArrayBuffer<"u",crossOriginIsolated:globalThis.crossOriginIsolated===!0,hardwareConcurrency:P(e.hardwareConcurrency)},webgl:ue(),webgpu:t.webgpu,memory:{deviceMemoryGiB:P(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 Z(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.3.0/";function ee(e){return e instanceof Error?e.message:String(e)}function B(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=M(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 M(e,t){return ye(e)&&(t||e.protocol==="http:"||e.protocol==="https:")}function I(e){return!e.chosen&&!M(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}${M(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: ${ee(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(!O(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:I(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",`${I(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",`${I(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 Re(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 Y(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 Ue(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 F=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 or a Hub repo id (owner/name[@revision]), a non-empty string");let o=B("worker",r.assets?.worker),s=B("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=B("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`);if(r.hubBaseUrl!==void 0){let h=r.hubBaseUrl,L=!1;if(typeof h=="string")try{let A=new URL(h);L=A.protocol==="http:"||A.protocol==="https:"}catch{L=!1}if(!L)throw new i("request",`hubBaseUrl must be an absolute http(s) URL, not ${JSON.stringify(h).slice(0,80)}`)}let a=()=>new i("fetch",`loading ${t} was aborted`),g=r.signal;if(g?.aborted)throw a();let p=await q(),R,T;if(n==="auto"&&r.dtype==="bf16"&&p.chosen==="webgpu")R="wasm",T=`bf16 requested: wasm (the WebGPU tier runs the f32 plan only); ${p.why}`;else if(n==="auto")R=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}`);R="webgpu",T=`backend "webgpu" asked for; ${p.why}`}else R="wasm",T=`backend "wasm" asked for; ${p.why}`;let _=p.webgpu?.unrepresentable??[];if(g?.aborted)throw a();let $=await ve(b,!l,g,a),{worker:k}=$,D=$.url,x=null;$.failed!==void 0&&(x=We($.failed,D.href,s===void 0?u:void 0),Y(x));let j=h=>x===null?h:new i(h.kind,`${h.message} (after a CDN fallback: ${x})`,h.missing);if(g?.aborted)throw k.terminate(),j(a());let N=1,te={id:N,type:"load",model:t,probeJson:Z(p),request:{backend:R,...r.dtype!==void 0?{dtype:r.dtype}:{},...r.maxContext!==void 0?{maxContext:r.maxContext}:{},...R==="webgpu"&&d==="f32"?{f16:!1}:{}},...n==="auto"&&R==="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((h,L)=>{let A=()=>v(a()),J=()=>{k.onmessage=null,k.onerror=null,g?.removeEventListener("abort",A)},v=S=>{J(),k.terminate(),L(j(S))},w=null;g?.addEventListener("abort",A,{once:!0}),k.onerror=S=>v(new i("backend",`the engine's worker from ${D.href} failed: ${S.message||"it did not start"}`)),k.onmessage=S=>{let c=S.data;if(!O(c)||c.id!==N)return v(m(c));switch(c.type){case"host":if(w!==null)return v(m(c));w=c.hostWasm,w.failed!==void 0&&(x=Re({...w,failed:w.failed}),Y(x));return;case"progress":try{r.onProgress?.({file:c.file,loaded:c.loaded,total:c.total,repo:c.repo,revision:c.revision,...c.provenance!==void 0?{provenance:c.provenance}:{}})}catch(y){v(y instanceof i?y:new i("request",`onProgress threw: ${ee(y)}`))}return;case"loaded":{if(w===null)return v(m(c));J();let y=$.used.source,re=s!==void 0||y==="page"&&w.failed===void 0?"page":w.failed!==void 0||y==="cdn"?"cdn":"bundle",ne={worker:{source:y,url:D.href},hostWasm:{source:re,url:w.url}},oe={...c.doctor,source:c.sources,why:c.fallback!==void 0?`${c.fallback}; ${p.why}`:T,assets:ne};h(new E(k,oe));return}case"error":{let y=c.kind==="probe"&&_.length>0?`; the browser gave ${_.join(", ")}, which the host reads as missing`:"";return v(new i(c.kind,c.message+y))}default:return v(m(c))}},k.postMessage(te)})}},E=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(!O(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(Ue(t.delta));case"error":return t.fatal!==void 0&&(this.#e=X(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{F as Caldrix,i as CaldrixError,E as Engine,q as probe};
package/dist/worker.js CHANGED
@@ -1 +1 @@
1
- import{b as f,c as C,d as F}from"./chunk-PZGTLL5H.js";var ce="caldrix.js",J="x-caldrix-verified",Y="x-caldrix-absent";function fe(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function de(t){return t.trim().replace(/^W\//,"").replace(/^"|"$/g,"").toLowerCase()}function q(t){return t instanceof Error?t.message:String(t)}function T(t,e){if(e===""||e==="."||e===".."||/[/\\?#]/.test(e)||/%[0-9a-fA-F]{2}/.test(e)||/[\u0000-\u001f\u007f]/.test(e))throw new f("validate",`${t} ${JSON.stringify(e)} is not a single safe path segment`);return encodeURIComponent(e)}function K(t){return new f("backend",`${t} is not available; caldrix.js needs a secure context`)}async function V(t,e,o,r){let n=t.split("/").map(b=>T("repo",b)).join("/"),c=`${r.hubBaseUrl.endsWith("/")?r.hubBaseUrl.slice(0,-1):r.hubBaseUrl}/${n}/resolve/${T("revision",e)}/${T("file",o)}`;if(typeof caches>"u")throw K("caches");let i;try{i=await caches.open(ce)}catch(b){throw new f("backend",`opening the cache for ${o} failed: ${q(b)}`)}let u;try{u=await i.match(c)}catch(b){throw new f("backend",`reading ${o} from the cache failed: ${q(b)}`)}let p=b=>new f("fetch",`fetching ${o} failed: HTTP 404${b}`,"not-found");if(u&&u.headers.get(Y)==="1"){if(r.rememberAbsent)throw p(" (remembered from an earlier load)");u=void 0}if(u)return{bytes:new Uint8Array(await u.arrayBuffer()),source:"cache",verified:u.headers.get(J)==="1",cached:!0};if(r.offline)throw new f("fetch",`${o} is not in the cache and offline is set`,"offline-uncached");let y=(b,P)=>new f("fetch",`fetching ${o} ${b}`,P),v=()=>{if(r.signal?.aborted)throw y("was aborted")},w;try{w=await fetch(c,{signal:r.signal})}catch(b){throw y(r.signal?.aborted?"was aborted":`failed: ${q(b)}`)}if(w.status===404&&r.rememberAbsent){try{await i.put(c,new Response(null,{headers:{[Y]:"1"}}))}catch{}throw p("")}if(!w.ok||!w.body)throw y(`failed: HTTP ${w.status}`,w.status===404?"not-found":void 0);let s=w.headers.get("x-linked-etag"),a=w.headers.get("content-length"),d=a!==null&&/^\d+$/.test(a.trim())?Number(a):null,g=[],m=0,h=w.body.getReader();try{for(;;){let b;try{b=await h.read()}catch(P){throw y(r.signal?.aborted?"was aborted":`failed: ${q(P)}`)}if(b.done)break;g.push(b.value),m+=b.value.byteLength,r.onProgress?.({file:o,loaded:m,total:d})}}finally{h.cancel().catch(()=>{})}if(v(),d!==null&&d!==m&&!w.headers.get("content-encoding"))throw y(`failed: Content-Length is ${d} but ${m} bytes arrived`);let x=new Uint8Array(m),$=0;for(let b of g)x.set(b,$),$+=b.byteLength;r.onProgress?.({file:o,loaded:m,total:d});let A=!1;if(s!==null){if(typeof crypto>"u"||!crypto.subtle)throw K("crypto.subtle");let b=de(s),P=fe(await crypto.subtle.digest("SHA-256",x));if(b!==P)throw new f("digest",`${o}: sha256 is ${P} but the Hub's X-Linked-Etag is ${b}`);A=!0}v();try{await i.put(c,new Response(x,{headers:{[J]:A?"1":"0"}}))}catch{return{bytes:x,source:"network",verified:A,cached:!1}}return{bytes:x,source:"network",verified:A,cached:!0}}var _=null,O=null;function N(t){return t instanceof Error?t.message:String(t)}async function M(){return await import("../host/caldrix_web.js")}function pe(t){let e=globalThis.location?.href;return(e!==void 0?new URL(String(t),e):new URL(String(t))).href}async function X(t){let e;try{e=await fetch(t)}catch(o){throw new Error(N(o))}if(!e.ok)throw new Error(`${e.status} ${e.statusText}`.trim());return e}async function I(t,e){if(_===null){let o=await M(),r=t??pe(new URL("../host/caldrix_web_bg.wasm",import.meta.url)),n,l;try{n=await X(r),l={url:r}}catch(c){let i=N(c);if(e===void 0||e===r)throw new f("backend",`the browser host's .wasm could not be fetched from ${r} (${i}); serve host/ beside dist/ or set assets.hostWasm to where the page serves it`);try{n=await X(e)}catch(u){let p=new URL(e).origin;throw new f("backend",`the browser host's .wasm could not be fetched from ${r} (${i}) nor from the CDN fallback ${e} (${N(u)}); serve host/ beside dist/, set assets.hostWasm to where the page serves it, or allow ${p} in the page's Content-Security-Policy (connect-src ${p}, the .wasm is fetched)`)}l={url:e,failed:{url:r,reason:i}}}await o.default({module_or_path:n}),_=o,O=l}return _}async function Q(t,e,o){let r=await I(e,o);return new r.CaldrixWeb(t)}function Z(){if(O===null)throw new f("backend","the browser host is not open");return{...O,...O.failed!==void 0?{failed:{...O.failed}}:{}}}async function ee(){return(await I()).CaldrixWeb}async function re(t,e){let o=await I(),r;try{let{instance:c}=await WebAssembly.instantiate(e,{env:{memory:o.CaldrixWeb.memory()}});r=c.exports}catch(c){throw new f("backend",`instantiating the emitted module failed: ${c instanceof Error?c.message:String(c)}`)}let{step:n,prefill:l}=r;if(typeof n!="function"||typeof l!="function")throw new f("backend","the emitted module does not export step and prefill");if(t.attach(n,l),t.argsPtr()===0)throw new f("backend","the host reports no model loaded after load")}var U={MAP_READ:1,COPY_SRC:4,COPY_DST:8,UNIFORM:64,STORAGE:128},he=1,ge=["maxStorageBufferBindingSize","maxBufferSize","maxComputeWorkgroupsPerDimension","maxStorageBuffersPerShaderStage"],te=(t,e)=>Number.isSafeInteger(t)&&t>=0&&t<e,ne=t=>Number.isSafeInteger(t)&&t>=0;function me(t,e){let o=n=>new f("backend",`the host's WebGPU program is malformed: ${n}`),r;try{r=JSON.parse(t)}catch(n){throw o(n instanceof Error?n.message:String(n))}if(typeof r!="object"||r===null||!Array.isArray(r.kernels)||!Array.isArray(r.buffers))throw o("no kernels or buffers");if(r.kernels.forEach((n,l)=>{if(!(typeof n?.symbol=="string"&&typeof n.entry=="string"&&Array.isArray(n.buffers)&&n.buffers.every(i=>i==="f32"||i==="f16")&&ne(n.scalars)))throw o(`kernel ${l}`)}),r.buffers.forEach((n,l)=>{if(!(typeof n?.word=="string"&&ne(n.bytes)&&(n.storage==="f32"||n.storage==="f16")&&typeof n.placed=="boolean"))throw o(`buffer ${l}`)}),!te(r.act,r.buffers.length))throw o("act is no buffer");if(!te(r.logits,r.buffers.length))throw o("logits is no buffer");if(!Array.isArray(e)||e.length!==r.kernels.length||!e.every(n=>typeof n=="string"))throw o(`${r.kernels.length} kernels but ${Array.isArray(e)?e.length:"no"} WGSL sources`);return r}function be(t,e){let o=[],r=c=>new f("backend",`the host's launch words are malformed: ${c}`),n=0,l=(c,i)=>{if(n+c>t.length)throw r(`launch ${o.length} ends inside its ${i}`);let u=t.subarray(n,n+c);return n+=c,u};for(;n<t.length;){let c=l(1,"kernel")[0],i=e.kernels[c];if(i===void 0)throw r(`launch ${o.length} names kernel ${c}; the program has ${e.kernels.length}`);let u=Array.from(l(l(1,"buffer count")[0],"buffers"));if(u.length!==i.buffers.length)throw r(`a launch of ${i.symbol} binds ${u.length} buffers; the kernel declares ${i.buffers.length}`);let p=u.find(s=>s>=e.buffers.length);if(p!==void 0)throw r(`a launch of ${i.symbol} binds buffer ${p}; the program has ${e.buffers.length}`);let[y,v]=l(2,"grid"),w=l(l(1,"uniform count")[0],"uniform").slice();if(w.length===0!=(i.scalars===0))throw r(`a launch of ${i.symbol} carries ${w.length} uniform words; the kernel declares ${i.scalars} scalars`);o.push({kernel:c,buffers:u,x:y,y:v,uniform:w})}return o}var B=t=>t instanceof Error?t.message:String(t),z=class{constructor(e,o,r,n,l,c,i,u){this.adapter=e;this.description=o;this.host=r;this.device=n;this.program=l;this.pipelines=c;this.buffers=i;this.staging=u;n.lost.then(p=>{let y=`the WebGPU device was lost: ${p.message||p.reason||"no message"}`;!this.#e&&this.#r===null&&(this.#r=y),this.#t?.(y)})}adapter;description;host;device;program;pipelines;buffers;staging;#r=null;#e=!1;#t=null;#n=new Set;get failure(){return this.#r}get storage(){return this.program.buffers.some(e=>e.storage==="f16")?"f16":"f32"}async run(e,o){if(this.#e)throw new f("request","the WebGPU runtime was destroyed (the engine was disposed)");if(this.failure!==null)throw this.#s(this.failure),F(this.failure);let r;try{r=be(e,this.program);let u=this.program.buffers[this.program.act];if(o.byteLength>u.bytes)throw new f("backend",`actIn is ${o.byteLength} bytes; the program's ${u.word} is ${u.bytes}`)}catch(u){throw this.#o(B(u),!1)}let n=this.device,l=[],c,i=new Promise((u,p)=>{this.#t=y=>p(new Error(y))});i.catch(()=>null);try{n.pushErrorScope("validation"),n.pushErrorScope("out-of-memory"),n.pushErrorScope("internal");let u=3,p=async()=>{let a=n.popErrorScope(),d=n.popErrorScope(),g=n.popErrorScope();u=0;let[m,h,x]=await Promise.all([a,d,g]);return h?`out of memory: ${h.message}`:x?`validation: ${x.message}`:m?`an internal error: ${m.message}`:null},y,v;try{o.byteLength>0&&n.queue.writeBuffer(this.buffers[this.program.act],0,o);let a=r.map(h=>{let x=h.buffers.map(($,A)=>({binding:A,resource:{buffer:this.buffers[$]}}));if(h.uniform.length>0){let $=n.createBuffer({size:h.uniform.byteLength,usage:U.UNIFORM|U.COPY_DST});l.push($),this.#n.add($),n.queue.writeBuffer($,0,h.uniform),x.push({binding:h.buffers.length,resource:{buffer:$}})}return n.createBindGroup({layout:this.pipelines[h.kernel].getBindGroupLayout(0),entries:x})}),d=n.createCommandEncoder(),g=d.beginComputePass();r.forEach((h,x)=>{g.setPipeline(this.pipelines[h.kernel]),g.setBindGroup(0,a[x]),g.dispatchWorkgroups(h.x,h.y,1)}),g.end();let m=this.buffers[this.program.logits];d.copyBufferToBuffer(m,0,this.staging,0,m.size),n.queue.submit([d.finish()]),y=p(),v=this.staging.mapAsync(he),y.catch(()=>null),v.catch(()=>null)}finally{for(;u-- >0;)n.popErrorScope().catch(()=>null)}if(this.failure!==null)throw new Error(this.failure);let w=await Promise.race([y,i]);if(this.#e)throw new f("request","the engine was disposed during a WebGPU call");if(w!==null)throw new Error(`the device reported ${w}`);try{await Promise.race([v,i])}catch(a){throw this.#e?new f("request","the engine was disposed during a WebGPU call"):new Error(`mapping the logits readback failed: ${B(a)}`)}if(this.#e)throw new f("request","the engine was disposed during a WebGPU call");let s=this.program.buffers[this.program.logits].bytes;c=new Uint8Array(this.staging.getMappedRange(0,this.staging.size).slice(0,s)),this.staging.unmap()}catch(u){throw u instanceof f&&u.kind==="request"?u:this.#o(B(u))}finally{this.#t=null;for(let u of l)this.#n.delete(u),this.#e||u.destroy()}this.host.writeLogits(c)}#o(e,o=!0){return this.#e?new f("request","the engine was disposed during a WebGPU call"):(o&&(this.#r??=e),this.#s(e)??new f("backend",e))}#s(e){try{this.host.failLaunch(e)}catch(o){let r=C(o);if(r.kind==="backend")return r}return null}destroy(){if(!this.#e){this.#e=!0,this.#t?.("the engine was disposed during a WebGPU call");for(let e of[...this.buffers,this.staging,...this.#n])try{e.destroy()}catch{}this.#n.clear();try{this.device.destroy()}catch{}}}};function ye(t,e){let o=t.limits[e];return typeof o=="number"?o:void 0}function we(){return globalThis.navigator?.gpu}async function oe(t,e,o=we()){let r=p=>new f("backend",p);if(!o)throw r("the worker has no navigator.gpu, though the page's probe found a WebGPU adapter");let n;try{n=await o.requestAdapter()}catch(p){throw r(`the worker's requestAdapter failed: ${B(p)}`)}if(!n)throw r("the worker's requestAdapter returned null, though the page's probe found an adapter");if(e&&!n.features.has("shader-f16"))throw r("the host's precheck chose f16 weight storage, but the worker's adapter has no shader-f16");let l={};for(let p of ge){let y=ye(n,p),v=t.webgpu?.limits[p];if(v!==void 0&&(y===void 0||y<v))throw r(`the worker's adapter offers ${p} ${y??"none"}; the host prechecked against the probe's ${v}`);y!==void 0&&(l[p]=y)}let c;try{c=await n.requestDevice({requiredFeatures:e?["shader-f16"]:[],requiredLimits:l})}catch(p){throw r(`requestDevice refused${e?" shader-f16 with":""} the program's limits: ${B(p)}`)}let i=n.info??{};if(!n.info&&typeof n.requestAdapterInfo=="function")try{i=await n.requestAdapterInfo()}catch{i={}}let u=!1;return{device:c,f16:e,adapter:{vendor:i.vendor??"",architecture:i.architecture??""},description:i.description??"",destroy:()=>{if(!u){u=!0;try{c.destroy()}catch{}}}}}async function se(t,e,o){let r=i=>new f("backend",i),n=e.device,l=[],c=()=>{for(let i of l)i.destroy();e.destroy()};try{let i=me(o.program,o.kernels),u=i.buffers.some(w=>w.storage==="f16");if(u!==e.f16)throw r(`the program stores weights ${u?"f16":"f32"}, but the device was opened for ${e.f16?"f16":"f32"} storage`);let p=[];for(let[w,s]of i.kernels.entries()){n.pushErrorScope("validation"),n.pushErrorScope("internal");let a=null,d=null;try{let h=n.createShaderModule({code:o.kernels[w],label:s.symbol});a=n.createComputePipeline({label:s.symbol,layout:"auto",compute:{module:h,entryPoint:s.entry}})}catch(h){d=h}let g=await n.popErrorScope(),m=await n.popErrorScope()??g;if(m)throw r(`kernel ${s.symbol}: creating its pipeline: ${m.message}`);if(a===null)throw r(`kernel ${s.symbol}: creating its pipeline: ${B(d)}`);p.push(a)}for(let[w,s]of i.buffers.entries()){n.pushErrorScope("validation"),n.pushErrorScope("out-of-memory");let a=null;try{let m=n.createBuffer({size:Math.max(4,Math.ceil(s.bytes/4)*4),usage:U.STORAGE|U.COPY_SRC|U.COPY_DST,label:s.word});if(l.push(m),s.placed){let h=t.bufferBytes(w);if(h.byteLength!==s.bytes)throw new f("backend",`buffer ${s.word}: bufferBytes gave ${h.byteLength} bytes; the buffer is ${s.bytes} at ${s.storage} storage`);if(h.byteLength%4!==0)throw new f("backend",`buffer ${s.word}: ${h.byteLength} bytes are not whole 4-byte words`);n.queue.writeBuffer(m,0,h)}}catch(m){a=m}let d=await n.popErrorScope(),g=await n.popErrorScope();if(a!==null)throw a instanceof f?a:C(a);if(d)throw r(`buffer ${s.word} (${s.bytes} bytes): out of memory: ${d.message}`);if(g)throw r(`buffer ${s.word} (${s.bytes} bytes): ${g.message}`)}let y=l[i.logits],v=n.createBuffer({size:y.size,usage:U.MAP_READ|U.COPY_DST,label:"logits readback"});return new z({...e.adapter},e.description,t,n,i,p,l,v)}catch(i){throw c(),i}}var ke=["fit","request","probe"];function ie(){return new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=()=>{e.port1.close(),t()},e.port2.postMessage(0)})}async function ae(t,e,o){let r,n;try{r=o.kind==="prefill"?t.resolve("prefill",o.n):t.resolve("step",o.pos),n=t.actIn(o.kind==="prefill"?o.n:1)}catch(l){try{t.failLaunch(C(l).message)}catch{}throw l}await e.run(r,n)}async function xe(t,e,o,r){if(await ae(t,e,o),!!r.launched())for(t.finishStart();;){if(!await r.between())return;let n=t.beginNext();if("delta"in n){r.delta(JSON.parse(n.delta));return}if(await ae(t,e,n.launch),!r.launched())return;let l=JSON.parse(t.finishNext());if(r.delta(l),l.done)return}}function le(t,e){let o=null,r=null,n=!1,l=null,c=!1,i=s=>{let a=s.doctor();if(r===null)return{...a,storage:null,adapter:null};let d=r.adapter,g=`webgpu (${r.description!==""?r.description:`${d.vendor} ${d.architecture}`})`,m=`backend webgpu on ${a.device}`,h=a.line.startsWith(m)?`backend webgpu on ${g}${a.line.slice(m.length)}`:a.line;return{...a,device:g,line:h,storage:r.storage,adapter:{...d}}},u=new f("request","the engine was disposed during its load"),p=()=>{if(c)throw u};async function y(s){if(o!==null||n)throw new f("request","this engine already has a model loaded");n=!0;let a=null;try{a=await t.openHost(s.probeJson,s.hostWasm,s.cdnWasm),e({id:s.id,type:"host",hostWasm:t.wasmUsed()}),p();let d=await t.hostClass(),{repo:g,revision:m}=d.resolveAlias(s.alias),h={},x=async(W,G)=>{try{let k=await t.fetchFile(g,m,W,{hubBaseUrl:s.hubBaseUrl,offline:s.offline,rememberAbsent:G,onProgress:S=>e({id:s.id,type:"progress",file:S.file,loaded:S.loaded,total:S.total})});return p(),h[W]={source:k.source,verified:k.verified},k.bytes}catch(k){if(G&&k instanceof f&&k.missing==="not-found")return null;throw k}},$=async W=>await x(W,!1),A=await $("config.json"),b=await x("model.safetensors.index.json",!0),P=a,E={...s.request,repo:g,revision:m},H,D=null,j=W=>{let G={...E,backend:"wasm"};delete G.f16,E=G;try{P.precheck(A,b,JSON.stringify(E))}catch(k){let S=C(k);throw new f(S.kind,`${S.message} (backend "auto": WebGPU refused first: ${W.message})`)}H=`webgpu refused: ${W.message}; wasm serves this load`};if(E.backend==="webgpu"){let W=null;try{W=JSON.parse(P.precheck(A,b,JSON.stringify(E)))}catch(G){let k=C(G);if(!(s.auto===!0&&ke.includes(k.kind)))throw k;j(k)}if(W!==null)try{D=await t.openDevice(JSON.parse(s.probeJson),W.f16===!0)}catch(G){let k=C(G);if(s.auto!==!0)throw k;j(k)}}else P.precheck(A,b,JSON.stringify(E));try{p();let W=JSON.stringify(E),G=await $("tokenizer.json"),k=await x("tokenizer_config.json",!0),S=[];for(let L of d.weightFiles(b))S.push(await $(L));if(D!==null){let L=P.loadWebGpu(A,G,k,S,W);S.length=0;let ue=D;D=null,r=await t.openRuntime(P,ue,L)}else{let L=P.load(A,G,k,S,W);S.length=0,await t.instantiate(P,L)}}finally{D?.destroy()}p(),o=a,e({id:s.id,type:"loaded",doctor:i(a),sources:h,...H!==void 0?{fallback:H}:{}})}catch(d){if(r?.destroy(),r=null,a!==null&&o!==a)try{a.dispose()}catch{}throw d}finally{n=!1}}async function v(s,a,d,g){let m;"messages"in s.prompt?m=a.startChatSplit(JSON.stringify(s.prompt.messages),g):"text"in s.prompt?m=a.startCompleteSplit(s.prompt.text,null,g):m=a.startCompleteSplit(null,Uint32Array.from(s.prompt.ids),g),await xe(a,d,m,{launched:()=>!c,between:async()=>(await ie(),!c),delta:h=>e({id:s.id,type:"delta",delta:h})})}async function w(s){if(l!==null)throw new f("request","a generation is already running on this engine");if(o===null)throw new f("request","no model is loaded");let a=o,d=JSON.stringify(s.options);if(r!==null){if(r.failure!==null)throw F(r.failure);l=s.id;try{return await v(s,a,r,d)}catch(g){if(c)return;throw g}finally{l=null}}l=s.id;try{for(("messages"in s.prompt)?a.startChat(JSON.stringify(s.prompt.messages),d):("text"in s.prompt)?a.startComplete(s.prompt.text,null,d):a.startComplete(null,Uint32Array.from(s.prompt.ids),d);;){if(await ie(),c)return;let g=JSON.parse(a.next());if(e({id:s.id,type:"delta",delta:g}),g.done)return}}finally{l=null}}return async s=>{try{switch(s.type){case"load":return await y(s);case"generate":return await w(s);case"abort":l===s.id&&o?.abort();return;case"doctor":if(o===null)throw new f("request","no model is loaded");e({id:s.id,type:"result",value:i(o)});return;case"dispose":c=!0,r?.destroy(),r=null,o?.dispose(),o=null,e({id:s.id,type:"result",value:null}),t.close();return}}catch(a){if(c)return;let d=C(a),g=r?.failure??null;e({id:s.id,type:"error",kind:d.kind,message:d.message,...g!==null?{fatal:g}:{}})}}}var R=globalThis,ve=le({openHost:Q,wasmUsed:Z,hostClass:ee,instantiate:re,openDevice:(t,e)=>oe(t,e),openRuntime:se,fetchFile:V,close:()=>R.close()},t=>R.postMessage(t));R.onmessage=t=>{ve(t.data)};M().then(()=>R.postMessage({id:0,type:"ready",url:R.location.href}),t=>R.postMessage({id:0,type:"error",kind:"backend",message:`the browser host's glue (host/caldrix_web.js, beside dist/worker.js) did not load (${t instanceof Error?t.message:String(t)})`}));
1
+ import{b as c,c as C,d as te}from"./chunk-PZGTLL5H.js";var ze="caldrix.js",$e="x-caldrix-verified",ce="x-caldrix-absent";function Je(r){return[...new Uint8Array(r)].map(t=>t.toString(16).padStart(2,"0")).join("")}function Ke(r){return r.trim().replace(/^W\//,"").replace(/^"|"$/g,"").toLowerCase()}function U(r){return r instanceof Error?r.message:String(r)}function Y(r,t){if(t===""||t==="."||t===".."||/[/\\?#]/.test(t)||/%[0-9a-fA-F]{2}/.test(t)||/[\u0000-\u001f\u007f]/.test(t))throw new c("validate",`${r} ${JSON.stringify(t)} is not a single safe path segment`);return encodeURIComponent(t)}function Pe(r){return new c("backend",`${r} is not available; caldrix.js needs a secure context`)}function Ae(r,t,s,e){let n=r.split("/").map(l=>Y("repo",l)).join("/");return`${e.endsWith("/")?e.slice(0,-1):e}/${n}/resolve/${Y("revision",t)}/${Y("file",s)}`}function Ye(r,t,s){let e=r.split("/").map(l=>Y("repo",l)).join("/"),n=s.endsWith("/")?s.slice(0,-1):s,u=t===null?"":`/revision/${t.split("/").map(l=>Y("revision",l)).join("%2F")}`;return`${n}/api/models/${e}${u}?blobs=true`}async function ue(r){if(typeof caches>"u")throw Pe("caches");try{return await caches.open(ze)}catch(t){throw new c("backend",`opening the cache for ${r} failed: ${U(t)}`)}}async function le(r){if(typeof crypto>"u"||!crypto.subtle)throw Pe("crypto.subtle");return Je(await crypto.subtle.digest("SHA-256",r))}function We(r){return new c("fetch",`${r} is not in the cache and offline is set`,"offline-uncached")}async function Se(r,t,s,e){let n=Ae(r,t,s,e.hubBaseUrl),u=await ue(s),l;try{l=await u.match(n)}catch(x){throw new c("backend",`reading ${s} from the cache failed: ${U(x)}`)}let i=x=>new c("fetch",`fetching ${s} failed: HTTP 404${x}`,"not-found");if(l&&l.headers.get(ce)==="1"){if(e.rememberAbsent)throw i(" (remembered from an earlier load)");l=void 0}let d=!1;if(l){let x=new Uint8Array(await l.arrayBuffer());if(e.sha256===void 0)return{bytes:x,source:"cache",verified:l.headers.get($e)==="1",cached:!0};if(await le(x)===e.sha256)return{bytes:x,source:"cache",verified:!0,cached:!0};d=!0;try{await u.delete(n)}catch{}}if(e.offline&&d)throw new c("fetch",`${s}: the cached copy fails the alias's sha256 pin and offline is set`,"offline-uncached");if(e.offline)throw We(s);let h=(x,D)=>new c("fetch",`fetching ${s} ${x}`,D),y=()=>{if(e.signal?.aborted)throw h("was aborted")},w;try{w=await fetch(n,{signal:e.signal})}catch(x){throw h(e.signal?.aborted?"was aborted":`failed: ${U(x)}`)}if(w.status===404&&e.rememberAbsent){try{await u.put(n,new Response(null,{headers:{[ce]:"1"}}))}catch{}throw i("")}if(!w.ok||!w.body)throw h(`failed: HTTP ${w.status}`,w.status===404?"not-found":void 0);let A=w.headers.get("x-linked-etag"),b=w.headers.get("content-length"),o=b!==null&&/^\d+$/.test(b.trim())?Number(b):null,a=[],g=0,m=w.body.getReader();try{for(;;){let x;try{x=await m.read()}catch(D){throw h(e.signal?.aborted?"was aborted":`failed: ${U(D)}`)}if(x.done)break;if(a.push(x.value),g+=x.value.byteLength,e.bytes!==void 0&&g>e.bytes)throw new c("fetch",`${s}: the body passed its pinned size, ${e.bytes} bytes`);e.onProgress?.({file:s,loaded:g,total:o})}}finally{m.cancel().catch(()=>{})}if(y(),o!==null&&o!==g&&!w.headers.get("content-encoding"))throw h(`failed: Content-Length is ${o} but ${g} bytes arrived`);let p=new Uint8Array(g),v=0;for(let x of a)p.set(x,v),v+=x.byteLength;e.onProgress?.({file:s,loaded:g,total:o});let W=!1,G=null;if(e.sha256!==void 0){if(G=await le(p),G!==e.sha256)throw new c("digest",`${s}: sha256 is ${G} but the alias pins ${e.sha256}`);W=!0}if(A!==null){let x=Ke(A);if(G??=await le(p),x!==G)throw new c("digest",`${s}: sha256 is ${G} but the Hub's X-Linked-Etag is ${x}`);W=!0}y();try{await u.put(n,new Response(p,{headers:{[$e]:W?"1":"0"}}))}catch{return{bytes:p,source:"network",verified:W,cached:!1}}return{bytes:p,source:"network",verified:W,cached:!0}}async function Ee(r,t,s,e,n){if(!Number.isSafeInteger(e)||e<=0)throw new c("request",`a range of ${e} bytes of ${s} is not a positive integer`);let u=Ae(r,t,s,n.hubBaseUrl),l=await ue(s),i;try{i=await l.match(u)}catch(b){throw new c("backend",`reading ${s} from the cache failed: ${U(b)}`)}if(i&&i.headers.get(ce)!=="1"){let b=new Uint8Array(await i.arrayBuffer());if(b.byteLength>=e)return b.slice(0,e)}if(n.offline)throw We(s);let d=b=>new c("fetch",`fetching the first ${e} bytes of ${s} ${b}`),h;try{h=await fetch(u,{headers:{Range:`bytes=0-${e-1}`},signal:n.signal})}catch(b){throw d(n.signal?.aborted?"was aborted":`failed: ${U(b)}`)}if(h.status!==206&&h.status!==200||!h.body)throw d(`failed: HTTP ${h.status}`);let y=new Uint8Array(e),w=0,A=h.body.getReader();try{for(;;){let b;try{b=await A.read()}catch(a){throw d(n.signal?.aborted?"was aborted":`failed: ${U(a)}`)}if(b.done)break;let o=Math.min(b.value.byteLength,e-w);if(y.set(b.value.subarray(0,o),w),w+=b.value.byteLength,w>e||h.status===200&&w===e)break}}finally{A.cancel().catch(()=>{})}if(n.signal?.aborted)throw d("was aborted");if(w<e)throw d(`failed: the HTTP ${h.status} answer carried ${w} bytes, not the ${e} asked for`);if(h.status===206&&w>e)throw d(`failed: the HTTP 206 answer carried more than the ${e} bytes asked for`);return y}var xe=262144;async function Ge(r,t,s){let e=Ye(r,t,s.hubBaseUrl),n=`the Hub listing of ${r}`,u=await ue(n);if(s.offline){let a;try{a=await u.match(e)}catch(g){throw new c("backend",`reading ${n} from the cache failed: ${U(g)}`)}if(!a)throw new c("fetch",`${n} is not in the cache and offline is set`,"offline-uncached");return{bytes:new Uint8Array(await a.arrayBuffer()),source:"cache"}}let l=a=>new c("fetch",`fetching ${n} ${a}`),i;try{i=await fetch(e,{signal:s.signal})}catch(a){throw l(s.signal?.aborted?"was aborted":`failed: ${U(a)}`)}let d=a=>{throw i.body?.cancel().catch(()=>{}),a},h=new URL(s.hubBaseUrl).origin;i.url&&new URL(i.url).origin!==h&&d(new c("fetch",`${n} was redirected off ${h} (to ${i.url})`)),i.status===401&&d(new c("fetch",`${r}: the Hub answered HTTP 401 for its listing: the repo does not exist, or it is private (the browser build sends no token; the caldrix CLI reads HF_TOKEN)`,"not-found")),i.status===404&&d(new c("fetch",`${r}${t?"@"+t:""}: no such repo or revision on the Hub (HTTP 404)`,"not-found")),(!i.ok||!i.body)&&d(l(`failed: HTTP ${i.status}`));let y=[],w=0,A=i.body.getReader();try{for(;;){let a;try{a=await A.read()}catch(g){throw l(s.signal?.aborted?"was aborted":`failed: ${U(g)}`)}if(a.done)break;if(w+=a.value.byteLength,w>xe)throw new c("validate",`${n} passed the 256 KiB (${xe}-byte) cap`);y.push(a.value)}}finally{A.cancel().catch(()=>{})}if(s.signal?.aborted)throw l("was aborted");let b=new Uint8Array(w),o=0;for(let a of y)b.set(a,o),o+=a.byteLength;try{await u.put(e,new Response(b))}catch{}return{bytes:b,source:"network"}}var fe=null,Z=null;function de(r){return r instanceof Error?r.message:String(r)}async function pe(){return await import("../host/caldrix_web.js")}function Ze(r){let t=globalThis.location?.href;return(t!==void 0?new URL(String(r),t):new URL(String(r))).href}async function Re(r){let t;try{t=await fetch(r)}catch(s){throw new Error(de(s))}if(!t.ok)throw new Error(`${t.status} ${t.statusText}`.trim());return t}async function he(r,t){if(fe===null){let s=await pe(),e=r??Ze(new URL("../host/caldrix_web_bg.wasm",import.meta.url)),n,u;try{n=await Re(e),u={url:e}}catch(l){let i=de(l);if(t===void 0||t===e)throw new c("backend",`the browser host's .wasm could not be fetched from ${e} (${i}); serve host/ beside dist/ or set assets.hostWasm to where the page serves it`);try{n=await Re(t)}catch(d){let h=new URL(t).origin;throw new c("backend",`the browser host's .wasm could not be fetched from ${e} (${i}) nor from the CDN fallback ${t} (${de(d)}); serve host/ beside dist/, set assets.hostWasm to where the page serves it, or allow ${h} in the page's Content-Security-Policy (connect-src ${h}, the .wasm is fetched)`)}u={url:t,failed:{url:e,reason:i}}}await s.default({module_or_path:n}),fe=s,Z=u}return fe}async function Le(r,t,s){let e=await he(t,s);return new e.CaldrixWeb(r)}function Ce(){if(Z===null)throw new c("backend","the browser host is not open");return{...Z,...Z.failed!==void 0?{failed:{...Z.failed}}:{}}}async function Ue(){return(await he()).CaldrixWeb}async function Be(r,t){let s=await he(),e;try{let{instance:l}=await WebAssembly.instantiate(t,{env:{memory:s.CaldrixWeb.memory()}});e=l.exports}catch(l){throw new c("backend",`instantiating the emitted module failed: ${l instanceof Error?l.message:String(l)}`)}let{step:n,prefill:u}=e;if(typeof n!="function"||typeof u!="function")throw new c("backend","the emitted module does not export step and prefill");if(r.attach(n,u),r.argsPtr()===0)throw new c("backend","the host reports no model loaded after load")}var q={MAP_READ:1,COPY_SRC:4,COPY_DST:8,UNIFORM:64,STORAGE:128},Ve=1,Xe=["maxStorageBufferBindingSize","maxBufferSize","maxComputeWorkgroupsPerDimension","maxStorageBuffersPerShaderStage"],Fe=(r,t)=>Number.isSafeInteger(r)&&r>=0&&r<t,Te=r=>Number.isSafeInteger(r)&&r>=0;function Qe(r,t){let s=n=>new c("backend",`the host's WebGPU program is malformed: ${n}`),e;try{e=JSON.parse(r)}catch(n){throw s(n instanceof Error?n.message:String(n))}if(typeof e!="object"||e===null||!Array.isArray(e.kernels)||!Array.isArray(e.buffers))throw s("no kernels or buffers");if(e.kernels.forEach((n,u)=>{if(!(typeof n?.symbol=="string"&&typeof n.entry=="string"&&Array.isArray(n.buffers)&&n.buffers.every(i=>i==="f32"||i==="f16"||i==="u32")&&Te(n.scalars)))throw s(`kernel ${u}`)}),e.buffers.forEach((n,u)=>{if(!(typeof n?.word=="string"&&Te(n.bytes)&&(n.storage==="f32"||n.storage==="f16"||n.storage==="blocks")&&typeof n.placed=="boolean"))throw s(`buffer ${u}`)}),!Fe(e.act,e.buffers.length))throw s("act is no buffer");if(!Fe(e.logits,e.buffers.length))throw s("logits is no buffer");if(!Array.isArray(t)||t.length!==e.kernels.length||!t.every(n=>typeof n=="string"))throw s(`${e.kernels.length} kernels but ${Array.isArray(t)?t.length:"no"} WGSL sources`);return e}function et(r,t){let s=[],e=l=>new c("backend",`the host's launch words are malformed: ${l}`),n=0,u=(l,i)=>{if(n+l>r.length)throw e(`launch ${s.length} ends inside its ${i}`);let d=r.subarray(n,n+l);return n+=l,d};for(;n<r.length;){let l=u(1,"kernel")[0],i=t.kernels[l];if(i===void 0)throw e(`launch ${s.length} names kernel ${l}; the program has ${t.kernels.length}`);let d=Array.from(u(u(1,"buffer count")[0],"buffers"));if(d.length!==i.buffers.length)throw e(`a launch of ${i.symbol} binds ${d.length} buffers; the kernel declares ${i.buffers.length}`);let h=d.find(b=>b>=t.buffers.length);if(h!==void 0)throw e(`a launch of ${i.symbol} binds buffer ${h}; the program has ${t.buffers.length}`);let[y,w]=u(2,"grid"),A=u(u(1,"uniform count")[0],"uniform").slice();if(A.length===0!=(i.scalars===0))throw e(`a launch of ${i.symbol} carries ${A.length} uniform words; the kernel declares ${i.scalars} scalars`);s.push({kernel:l,buffers:d,x:y,y:w,uniform:A})}return s}var M=r=>r instanceof Error?r.message:String(r),ge=class{constructor(t,s,e,n,u,l,i,d){this.adapter=t;this.description=s;this.host=e;this.device=n;this.program=u;this.pipelines=l;this.buffers=i;this.staging=d;n.lost.then(h=>{let y=`the WebGPU device was lost: ${h.message||h.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(){let t=s=>this.program.buffers.some(e=>e.storage===s);return t("f16")?"f16":t("blocks")?"blocks":"f32"}async run(t,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),te(this.failure);let e;try{e=et(t,this.program);let d=this.program.buffers[this.program.act];if(s.byteLength>d.bytes)throw new c("backend",`actIn is ${s.byteLength} bytes; the program's ${d.word} is ${d.bytes}`)}catch(d){throw this.#s(M(d),!1)}let n=this.device,u=[],l,i=new Promise((d,h)=>{this.#r=y=>h(new Error(y))});i.catch(()=>null);try{n.pushErrorScope("validation"),n.pushErrorScope("out-of-memory"),n.pushErrorScope("internal");let d=3,h=async()=>{let o=n.popErrorScope(),a=n.popErrorScope(),g=n.popErrorScope();d=0;let[m,p,v]=await Promise.all([o,a,g]);return p?`out of memory: ${p.message}`:v?`validation: ${v.message}`:m?`an internal error: ${m.message}`:null},y,w;try{s.byteLength>0&&n.queue.writeBuffer(this.buffers[this.program.act],0,s);let o=e.map(p=>{let v=p.buffers.map((W,G)=>({binding:G,resource:{buffer:this.buffers[W]}}));if(p.uniform.length>0){let W=n.createBuffer({size:p.uniform.byteLength,usage:q.UNIFORM|q.COPY_DST});u.push(W),this.#n.add(W),n.queue.writeBuffer(W,0,p.uniform),v.push({binding:p.buffers.length,resource:{buffer:W}})}return n.createBindGroup({layout:this.pipelines[p.kernel].getBindGroupLayout(0),entries:v})}),a=n.createCommandEncoder(),g=a.beginComputePass();e.forEach((p,v)=>{g.setPipeline(this.pipelines[p.kernel]),g.setBindGroup(0,o[v]),g.dispatchWorkgroups(p.x,p.y,1)}),g.end();let m=this.buffers[this.program.logits];a.copyBufferToBuffer(m,0,this.staging,0,m.size),n.queue.submit([a.finish()]),y=h(),w=this.staging.mapAsync(Ve),y.catch(()=>null),w.catch(()=>null)}finally{for(;d-- >0;)n.popErrorScope().catch(()=>null)}if(this.failure!==null)throw new Error(this.failure);let A=await Promise.race([y,i]);if(this.#e)throw new c("request","the engine was disposed during a WebGPU call");if(A!==null)throw new Error(`the device reported ${A}`);try{await Promise.race([w,i])}catch(o){throw this.#e?new c("request","the engine was disposed during a WebGPU call"):new Error(`mapping the logits readback failed: ${M(o)}`)}if(this.#e)throw new c("request","the engine was disposed during a WebGPU call");let b=this.program.buffers[this.program.logits].bytes;l=new Uint8Array(this.staging.getMappedRange(0,this.staging.size).slice(0,b)),this.staging.unmap()}catch(d){throw d instanceof c&&d.kind==="request"?d:this.#s(M(d))}finally{this.#r=null;for(let d of u)this.#n.delete(d),this.#e||d.destroy()}this.host.writeLogits(l)}#s(t,s=!0){return this.#e?new c("request","the engine was disposed during a WebGPU call"):(s&&(this.#t??=t),this.#o(t)??new c("backend",t))}#o(t){try{this.host.failLaunch(t)}catch(s){let e=C(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 t of[...this.buffers,this.staging,...this.#n])try{t.destroy()}catch{}this.#n.clear();try{this.device.destroy()}catch{}}}};function tt(r,t){let s=r.limits[t];return typeof s=="number"?s:void 0}function rt(){return globalThis.navigator?.gpu}async function Oe(r,t,s=rt()){let e=h=>new c("backend",h);if(!s)throw e("the worker has no navigator.gpu, though the page's probe found a WebGPU adapter");let n;try{n=await s.requestAdapter()}catch(h){throw e(`the worker's requestAdapter failed: ${M(h)}`)}if(!n)throw e("the worker's requestAdapter returned null, though the page's probe found an adapter");if(t&&!n.features.has("shader-f16"))throw e("the host's precheck chose f16 weight storage, but the worker's adapter has no shader-f16");let u={};for(let h of Xe){let y=tt(n,h),w=r.webgpu?.limits[h];if(w!==void 0&&(y===void 0||y<w))throw e(`the worker's adapter offers ${h} ${y??"none"}; the host prechecked against the probe's ${w}`);y!==void 0&&(u[h]=y)}let l;try{l=await n.requestDevice({requiredFeatures:t?["shader-f16"]:[],requiredLimits:u})}catch(h){throw e(`requestDevice refused${t?" shader-f16 with":""} the program's limits: ${M(h)}`)}let i=n.info??{};if(!n.info&&typeof n.requestAdapterInfo=="function")try{i=await n.requestAdapterInfo()}catch{i={}}let d=!1;return{device:l,f16:t,adapter:{vendor:i.vendor??"",architecture:i.architecture??""},description:i.description??"",destroy:()=>{if(!d){d=!0;try{l.destroy()}catch{}}}}}async function De(r,t,s){let e=i=>new c("backend",i),n=t.device,u=[],l=()=>{for(let i of u)i.destroy();t.destroy()};try{let i=Qe(s.program,s.kernels),d=i.buffers.some(A=>A.storage==="f16");if(d!==t.f16)throw e(`the program stores weights ${d?"f16":"f32"}, but the device was opened for ${t.f16?"f16":"f32"} storage`);let h=[];for(let[A,b]of i.kernels.entries()){n.pushErrorScope("validation"),n.pushErrorScope("internal");let o=null,a=null;try{let p=n.createShaderModule({code:s.kernels[A],label:b.symbol});o=n.createComputePipeline({label:b.symbol,layout:"auto",compute:{module:p,entryPoint:b.entry}})}catch(p){a=p}let g=await n.popErrorScope(),m=await n.popErrorScope()??g;if(m)throw e(`kernel ${b.symbol}: creating its pipeline: ${m.message}`);if(o===null)throw e(`kernel ${b.symbol}: creating its pipeline: ${M(a)}`);h.push(o)}for(let[A,b]of i.buffers.entries()){n.pushErrorScope("validation"),n.pushErrorScope("out-of-memory");let o=null;try{let m=n.createBuffer({size:Math.max(4,Math.ceil(b.bytes/4)*4),usage:q.STORAGE|q.COPY_SRC|q.COPY_DST,label:b.word});if(u.push(m),b.placed){let p=r.bufferBytes(A);if(p.byteLength!==b.bytes)throw new c("backend",`buffer ${b.word}: bufferBytes gave ${p.byteLength} bytes; the buffer is ${b.bytes} at ${b.storage} storage`);if(p.byteLength%4!==0)throw new c("backend",`buffer ${b.word}: ${p.byteLength} bytes are not whole 4-byte words`);n.queue.writeBuffer(m,0,p)}}catch(m){o=m}let a=await n.popErrorScope(),g=await n.popErrorScope();if(o!==null)throw o instanceof c?o:C(o);if(a)throw e(`buffer ${b.word} (${b.bytes} bytes): out of memory: ${a.message}`);if(g)throw e(`buffer ${b.word} (${b.bytes} bytes): ${g.message}`)}let y=u[i.logits],w=n.createBuffer({size:y.size,usage:q.MAP_READ|q.COPY_DST,label:"logits readback"});return new ge({...t.adapter},t.description,r,n,i,h,u,w)}catch(i){throw l(),i}}var nt=4194304,me=["tokenizer.json","tokenizer_config.json","chat_template.jinja"],[V,He,_e]=me;function re(r,t,s){return t!==null&&t.siblings.some(e=>e.name===r)?t:s}var be="adapter_model.safetensors",st=["fit","request","probe"];function Ne(){return new Promise(r=>{let t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),r()},t.port2.postMessage(0)})}function ot(r,t,s){if(r!=="")return r;let e=[t,s].filter(n=>n!=="");return e.length>0?e.join(" "):"unnamed adapter"}async function qe(r,t,s){let e,n;try{e=s.kind==="prefill"?r.resolve("prefill",s.n):r.resolve("step",s.pos),n=r.actIn(s.kind==="prefill"?s.n:1)}catch(u){try{r.failLaunch(C(u).message)}catch{}throw u}await t.run(e,n)}async function it(r,t,s,e){if(await qe(r,t,s),!!e.launched())for(r.finishStart();;){if(!await e.between())return;let n=r.beginNext();if("delta"in n){e.delta(JSON.parse(n.delta));return}if(await qe(r,t,n.launch),!e.launched())return;let u=JSON.parse(r.finishNext());if(e.delta(u),u.done)return}}function Ie(r,t){let s=null,e=null,n=!1,u=null,l=!1,i=[],d=o=>{let a={...o.doctor(),aliases:i.map(W=>({...W}))};if(e===null)return{...a,storage:null,adapter:null};let g=e.adapter,m=`webgpu (${ot(e.description,g.vendor,g.architecture)})`,p=`backend webgpu on ${a.device}`,v=a.line.startsWith(p)?`backend webgpu on ${m}${a.line.slice(p.length)}`:a.line;return{...a,device:m,line:v,storage:e.storage,adapter:{...g}}},h=new c("request","the engine was disposed during its load"),y=()=>{if(l)throw h};async function w(o){if(s!==null||n)throw new c("request","this engine already has a model loaded");n=!0;let a=null;try{a=await r.openHost(o.probeJson,o.hostWasm,o.cdnWasm),t({id:o.id,type:"host",hostWasm:r.wasmUsed()}),y();let g=await r.hostClass(),m=g.resolveModel(o.model);i=g.listAliases();let p=m.kind==="alias"?m:null,v=null;if(m.kind==="repo"){let f=await r.fetchListing(m.repo,m.revision,{hubBaseUrl:o.hubBaseUrl,offline:o.offline});y(),v=JSON.parse(g.parseListing(f.bytes))}let W=v!==null?v.id:m.repo,G;if(v!==null)G=v.sha;else if(p!==null)G=p.revision;else throw new c("backend","internal invariant broken: a repo id reached the file fetches without its Hub listing");let x={},D,ne={repo:W,revision:G,listing:v},se=f=>({repo:f.id,revision:f.sha,listing:f}),X=(f,$)=>{let k=f.siblings.find(P=>P.name===$);if(k===void 0)throw new c("validate",`${f.id}@${f.sha} has no ${$}`);return k.size},z=async(f,$,k,P)=>{let T;if(f.listing!==null){if(k&&!f.listing.siblings.some(E=>E.name===$))return null;T={bytes:X(f.listing,$)}}try{let E=await r.fetchFile(f.repo,f.revision,$,{hubBaseUrl:o.hubBaseUrl,offline:o.offline,rememberAbsent:f.listing===null&&k,...T??{},...P??{},onProgress:_=>t({id:o.id,type:"progress",file:_.file,loaded:_.loaded,total:_.total,repo:f.repo,revision:f.revision,...D!==void 0?{provenance:D}:{}})});return y(),x[$]={source:E.source,verified:E.verified},E.bytes}catch(E){if(k&&E instanceof c&&E.missing==="not-found")return null;throw E}},Q=async(f,$,k)=>await z(f,$,!1,k),we=(f,$,k)=>z(se(f),$,k),ye={},F=a,J,ee;if(p!==null&&p.format==="gguf"){let f=P=>r.fetchRange(W,G,p.file,P,{hubBaseUrl:o.hubBaseUrl,offline:o.offline}),$=await f(Math.min(nt,p.bytes));y();for(let P=g.ggufHeaderNeed($,p.bytes);P!==0;P=g.ggufHeaderNeed($,p.bytes))$=await f(P),y();let k=$;J=P=>F.precheckGguf(k,p.bytes,P),ee=async(P,T)=>{let E=await Q(ne,p.file,{sha256:p.sha256,bytes:p.bytes});return T?F.loadWebGpuGguf(E,P):F.loadGguf(E,P)}}else{let f=null,$=v;if(v!==null&&v.shape==="adapter"){let R=`${v.id}@${v.sha}`,L=await we(v,"adapter_config.json",!1),O=JSON.parse(g.adapterBase(L,R)),K=S=>{let B=C(S);return B===h||B.message.startsWith(R)?B:new c(B.kind,`${R} names base ${O.repo}: ${B.message}`,B.missing)},N=v.siblings.some(S=>S.name===V);try{let S=await r.fetchListing(O.repo,O.revision,{hubBaseUrl:o.hubBaseUrl,offline:o.offline});y(),$=JSON.parse(g.parseBaseListing(S.bytes,R,N))}catch(S){throw K(S)}f={listing:v,config:L,bytes:X(v,be)}}let k=$,P=k!==null?se(k):ne,T=R=>k!==null?se(re(R,f?.listing??null,k)):ne,E=await Q(P,"config.json"),_=await z(P,"model.safetensors.index.json",!0),ae=g.weightFiles(_);if(k!==null){if(X(re(V,f?.listing??null,k),V),f!==null){let L=f.listing,O=new Set(["adapter_config.json",be,...me.filter(S=>re(S,L,k)===L)]),N=["config.json",..._!==null?["model.safetensors.index.json"]:[],...ae,...me.filter(S=>re(S,L,k)===k)].find(S=>O.has(S));if(N!==void 0)throw new c("validate",`${N} is required from both ${L.id}@${L.sha} (the adapter) and ${k.id}@${k.sha} (its base); a file is fetched from one repo only`)}let R=0;for(let L of ae)R+=X(k,L);ye={weightBytes:R,...f!==null?{adapterBytes:f.bytes,baseRepo:k.id,baseRevision:k.sha}:{}}}J=R=>F.precheck(E,_,R,f?.config),ee=async(R,L)=>{let O=await Q(T(V),V),K=await z(T(He),He,!0),N=await z(T(_e),_e,!0),S=[];for(let je of ae)S.push(await Q(P,je));let B=f!==null?[await we(f.listing,be,!1)]:void 0,ve=f?.config;return L?F.loadWebGpu(E,O,K,N,S,R,ve,B):F.load(E,O,K,N,S,R,ve,B)}}let H={...o.request,repo:W,revision:G,...v!==null&&v.id!==m.repo?{resolvedFrom:m.repo}:{},...ye},oe,I=null,Me=()=>{let f={...H,backend:"wasm"};delete f.f16,H=f},ie=f=>{let $=JSON.parse(f).provenance;D=typeof $=="string"?$:void 0},ke=f=>{Me();try{ie(J(JSON.stringify(H)))}catch($){let k=C($);throw new c(k.kind,`${k.message} (backend "auto": WebGPU refused first: ${f.message})`)}oe=`webgpu refused: ${f.message}; wasm serves this load`};if(H.backend==="webgpu"){let f=null,$=null;try{f=J(JSON.stringify(H)),$=JSON.parse(f)}catch(k){let P=C(k);if(!(o.auto===!0&&st.includes(P.kind)))throw P;ke(P)}if($!==null){try{I=await r.openDevice(JSON.parse(o.probeJson),$.f16===!0)}catch(k){let P=C(k);if(o.auto!==!0)throw P;ke(P)}I!==null&&ie(f)}}else ie(J(JSON.stringify(H)));try{y();let f=JSON.stringify(H);if(I!==null){let $=await ee(f,!0),k=I;I=null,e=await r.openRuntime(F,k,$)}else await r.instantiate(F,await ee(f,!1))}finally{I?.destroy()}y(),s=a,t({id:o.id,type:"loaded",doctor:d(a),sources:x,...oe!==void 0?{fallback:oe}:{}})}catch(g){if(e?.destroy(),e=null,a!==null&&s!==a)try{a.dispose()}catch{}throw g}finally{n=!1}}async function A(o,a,g,m){let p;"messages"in o.prompt?p=a.startChatSplit(JSON.stringify(o.prompt.messages),m):"text"in o.prompt?p=a.startCompleteSplit(o.prompt.text,null,m):p=a.startCompleteSplit(null,Uint32Array.from(o.prompt.ids),m),await it(a,g,p,{launched:()=>!l,between:async()=>(await Ne(),!l),delta:v=>t({id:o.id,type:"delta",delta:v})})}async function b(o){if(u!==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 a=s,g=JSON.stringify(o.options);if(e!==null){if(e.failure!==null)throw te(e.failure);u=o.id;try{return await A(o,a,e,g)}catch(m){if(l)return;throw m}finally{u=null}}u=o.id;try{for(("messages"in o.prompt)?a.startChat(JSON.stringify(o.prompt.messages),g):("text"in o.prompt)?a.startComplete(o.prompt.text,null,g):a.startComplete(null,Uint32Array.from(o.prompt.ids),g);;){if(await Ne(),l)return;let m=JSON.parse(a.next());if(t({id:o.id,type:"delta",delta:m}),m.done)return}}finally{u=null}}return async o=>{try{switch(o.type){case"load":return await w(o);case"generate":return await b(o);case"abort":u===o.id&&s?.abort();return;case"doctor":if(s===null)throw new c("request","no model is loaded");t({id:o.id,type:"result",value:d(s)});return;case"dispose":l=!0,e?.destroy(),e=null,s?.dispose(),s=null,t({id:o.id,type:"result",value:null}),r.close();return}}catch(a){if(l)return;let g=C(a),m=e?.failure??null;t({id:o.id,type:"error",kind:g.kind,message:g.message,...m!==null?{fatal:m}:{}})}}}var j=globalThis,at=Ie({openHost:Le,wasmUsed:Ce,hostClass:Ue,instantiate:Be,openDevice:(r,t)=>Oe(r,t),openRuntime:De,fetchFile:Se,fetchListing:Ge,fetchRange:Ee,close:()=>j.close()},r=>j.postMessage(r));j.onmessage=r=>{at(r.data)};pe().then(()=>j.postMessage({id:0,type:"ready",url:j.location.href}),r=>j.postMessage({id:0,type:"error",kind:"backend",message:`the browser host's glue (host/caldrix_web.js, beside dist/worker.js) did not load (${r instanceof Error?r.message:String(r)})`}));
@@ -10,6 +10,10 @@ export class CaldrixWeb {
10
10
  * runtime to write into the program's `act` buffer before a launch.
11
11
  */
12
12
  actIn(rows: number): Uint8Array;
13
+ /**
14
+ * The base an `adapter_config.json` declares: `{ repo, revision: string | null }`.
15
+ */
16
+ static adapterBase(bytes: Uint8Array, adapter_at: string): string;
13
17
  argsPtr(): number;
14
18
  /**
15
19
  * The module's entries: `step(args)` and `prefill(args, n)`, each returning the status code.
@@ -33,8 +37,9 @@ export class CaldrixWeb {
33
37
  */
34
38
  dispose(): void;
35
39
  /**
36
- * What this host is: `{ backend, device, dtype, simd, threads, model, revision, source, line }`;
37
- * `source` is the page's to fill.
40
+ * What this host is: `{ backend, device, dtype, simd, threads, model, revision, provenance,
41
+ * note, source, line }`; `provenance` (a densified load's `model:` line) and `note` (an nf4
42
+ * repo's 4-bit note) are `null` otherwise; `source` is the page's to fill.
38
43
  */
39
44
  doctor(): any;
40
45
  /**
@@ -51,19 +56,57 @@ export class CaldrixWeb {
51
56
  * After the first launch ran and `writeLogits` wrote its row: picks the first token.
52
57
  */
53
58
  finishStart(): void;
59
+ /**
60
+ * [`HEADER_FIRST_RANGE`], the page's first range of a GGUF file (the worker's
61
+ * `GGUF_HEADER_FIRST_RANGE` is pinned against it).
62
+ */
63
+ static ggufHeaderFirstRange(): number;
64
+ /**
65
+ * How much of a GGUF file's head the page reads next: `0` when `prefix` holds the whole
66
+ * header, else the next range's length (doubling, capped at `file_bytes`). The page's first
67
+ * range is `HEADER_FIRST_RANGE` (4 MiB) or the whole file when smaller.
68
+ */
69
+ static ggufHeaderNeed(prefix: Uint8Array, file_bytes: number): number;
70
+ /**
71
+ * Every alias the browser build knows: `[{ name, format }]`, `format` `"safetensors"` or
72
+ * `"gguf"` (what `resolveAlias` answers for that name).
73
+ */
74
+ static listAliases(): any;
75
+ /**
76
+ * [`listing::LISTING_CAP`], the most listing bytes the host parses (the page's `LISTING_CAP`
77
+ * is pinned against it).
78
+ */
79
+ static listingCap(): number;
80
+ /**
81
+ * [`CaldrixWeb::load`] over a GGUF file the page verified against the alias's sha256: the
82
+ * precheck again on the whole file, the import (the tokenizer from the header), the lowering
83
+ * with the file's per-layer kinds (a quantized file lowers to the wasm tier's quantized
84
+ * kernels), and the placement.
85
+ */
86
+ loadGguf(file: Uint8Array, request_json: string): Uint8Array;
87
+ /**
88
+ * [`CaldrixWeb::load_webgpu`] over a GGUF file the page verified (see
89
+ * [`CaldrixWeb::load_gguf`]); returns `{ program, kernels }`.
90
+ */
91
+ loadWebGpuGguf(file: Uint8Array, request_json: string): any;
54
92
  /**
55
93
  * The WebGPU tier's `load`: prechecks the request (`backend: "webgpu"`) against the adapter
56
94
  * again, imports, lowers for WebGPU (plan dtype f32, the block GEMM weights stored f16 when the
57
95
  * precheck chose it), places into the host's heap and resolves the program. Returns
58
96
  * `{ program, kernels }`: `program` the `WebGpuProgram` JSON (`to_json`), `kernels` the WGSL
59
- * sources in the same index order. Nothing is attached: the split-phase calls drive it.
97
+ * sources in the same index order. Nothing is attached: the split-phase calls drive it. The
98
+ * adapter arguments and the densified path are [`CaldrixWeb::load`]'s, at the plan dtype f32.
60
99
  */
61
- loadWebGpu(config_json: Uint8Array, tokenizer_json: Uint8Array, tokenizer_config: Uint8Array | null | undefined, files: Array<any>, request_json: string): any;
100
+ loadWebGpu(config_json: Uint8Array, tokenizer_json: Uint8Array, tokenizer_config: Uint8Array | null | undefined, chat_template: Uint8Array | null | undefined, files: Array<any>, request_json: string, adapter_config?: Uint8Array | null, adapter_files?: Array<any> | null): any;
62
101
  /**
63
102
  * Prechecks again on the real bytes, imports, lowers and places into the host's heap; returns
64
- * the module bytes for the page to instantiate over [`memory`].
103
+ * the module bytes for the page to instantiate over [`memory`]. With `adapter_config` and
104
+ * `adapter_files` (a LoRA adapter repo), or a config carrying a `quantization_config` (a
105
+ * bitsandbytes nf4 repo), the model is imported densified at the request's plan dtype, then
106
+ * prechecked over the imported dense descriptor and the files' real lengths, lowered and
107
+ * placed tensor by tensor; the base's files and the adapter's are freed before this returns.
65
108
  */
66
- load(config_json: Uint8Array, tokenizer_json: Uint8Array, tokenizer_config: Uint8Array | null | undefined, files: Array<any>, request_json: string): Uint8Array;
109
+ load(config_json: Uint8Array, tokenizer_json: Uint8Array, tokenizer_config: Uint8Array | null | undefined, chat_template: Uint8Array | null | undefined, files: Array<any>, request_json: string, adapter_config?: Uint8Array | null, adapter_files?: Array<any> | null): Uint8Array;
67
110
  /**
68
111
  * Where the module writes each logits row: [`Placed::logits`], `0` when nothing is loaded. For
69
112
  * a test page that reads the row from [`CaldrixWeb::memory`]; the product never reads it.
@@ -77,15 +120,42 @@ export class CaldrixWeb {
77
120
  static memory(): any;
78
121
  constructor(probe_json: string);
79
122
  /**
80
- * The next token as JSON: `{ token, text, done, finishReason, promptTokens, completionTokens }`.
123
+ * The next token as JSON: `{ token, text, done, finishReason, promptTokens, cachedTokens, completionTokens }`, plus
124
+ * `logprobs: [{ token, logprob }, ...]` when the options asked for them and the row has a finite entry.
81
125
  */
82
126
  next(): any;
83
- precheck(config_json: Uint8Array, index_json: Uint8Array | null | undefined, request_json: string): any;
127
+ /**
128
+ * An adapter's base listing bytes, parsed and checked against the adapter (`adapterAt` is
129
+ * `id@sha`); answers `{"id","sha","siblings"}`.
130
+ */
131
+ static parseBaseListing(bytes: Uint8Array, adapter_at: string, adapter_has_tokenizer: boolean): string;
132
+ /**
133
+ * The Hub's listing bytes, parsed, gated refused and the shape decided; answers the JSON
134
+ * `{"id","sha","shape":"model"|"adapter","siblings":[{"name","size"}]}` (never gated).
135
+ */
136
+ static parseListing(bytes: Uint8Array): string;
137
+ /**
138
+ * [`CaldrixWeb::precheck`] over a GGUF file's head: `header` is enough of it for the header
139
+ * to parse ([`CaldrixWeb::gguf_header_need`] answers 0), `file_bytes` the alias's pinned size.
140
+ */
141
+ precheckGguf(header: Uint8Array, file_bytes: number, request_json: string): any;
142
+ /**
143
+ * Checks a model before any download. `adapter_config` is an adapter repo's
144
+ * `adapter_config.json` (then the request names `weightBytes` and `adapterBytes`); with it, or
145
+ * with `weightBytes` alone (a repo id's listing), the precheck is over the repo's files.
146
+ */
147
+ precheck(config_json: Uint8Array, index_json: Uint8Array | null | undefined, request_json: string, adapter_config?: Uint8Array | null): any;
84
148
  static resolveAlias(name: string): any;
85
149
  /**
86
- * The launches of `kind` (`"prefill"` with `n` rows, `"step"` at position `n_or_pos`) as
87
- * `launches_to_words`' flat list. A call the program refuses is the wasm entry's status as a
88
- * `backend` error ("prefill returned status 2", "step returned status 1").
150
+ * An alias (`resolveAlias`'s object plus `kind: "alias"`), else a Hub repo id
151
+ * `owner/name[@revision]` as `{ kind: "repo", repo, revision: string | null }`.
152
+ */
153
+ static resolveModel(name: string): any;
154
+ /**
155
+ * The launches of `kind` (`"prefill"` with `n` rows from the argument block's `Pos` word,
156
+ * `"step"` at position `n_or_pos`) as `launches_to_words`' flat list. A call the program
157
+ * refuses is the wasm entry's status as a `backend` error ("prefill returned status 2", "step
158
+ * returned status 1").
89
159
  */
90
160
  resolve(kind: string, n_or_pos: number): Uint32Array;
91
161
  startChatSplit(messages_json: string, options_json: string): any;
@@ -111,6 +181,7 @@ export interface InitOutput {
111
181
  readonly __wbg_caldrixweb_free: (a: number, b: number) => void;
112
182
  readonly caldrixweb_abort: (a: number) => void;
113
183
  readonly caldrixweb_actIn: (a: number, b: number, c: number) => void;
184
+ readonly caldrixweb_adapterBase: (a: number, b: number, c: number, d: number, e: number) => void;
114
185
  readonly caldrixweb_argsPtr: (a: number) => number;
115
186
  readonly caldrixweb_attach: (a: number, b: number, c: number, d: number) => void;
116
187
  readonly caldrixweb_beginNext: (a: number, b: number) => void;
@@ -120,15 +191,25 @@ export interface InitOutput {
120
191
  readonly caldrixweb_failLaunch: (a: number, b: number, c: number, d: number) => void;
121
192
  readonly caldrixweb_finishNext: (a: number, b: number) => void;
122
193
  readonly caldrixweb_finishStart: (a: number, b: number) => void;
123
- 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;
124
- 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;
194
+ readonly caldrixweb_ggufHeaderFirstRange: () => number;
195
+ readonly caldrixweb_ggufHeaderNeed: (a: number, b: number, c: number, d: number) => void;
196
+ readonly caldrixweb_listAliases: (a: number) => void;
197
+ readonly caldrixweb_listingCap: () => number;
198
+ 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, l: number, m: number, n: number, o: number, p: number) => void;
199
+ readonly caldrixweb_loadGguf: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
200
+ 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, l: number, m: number, n: number, o: number, p: number) => void;
201
+ readonly caldrixweb_loadWebGpuGguf: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
125
202
  readonly caldrixweb_logitsPtr: (a: number, b: number) => void;
126
203
  readonly caldrixweb_memory: () => number;
127
204
  readonly caldrixweb_new: (a: number, b: number, c: number) => void;
128
205
  readonly caldrixweb_next: (a: number, b: number) => void;
129
- readonly caldrixweb_precheck: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
206
+ readonly caldrixweb_parseBaseListing: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
207
+ readonly caldrixweb_parseListing: (a: number, b: number, c: number) => void;
208
+ readonly caldrixweb_precheck: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number) => void;
209
+ readonly caldrixweb_precheckGguf: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => void;
130
210
  readonly caldrixweb_resolve: (a: number, b: number, c: number, d: number, e: number) => void;
131
211
  readonly caldrixweb_resolveAlias: (a: number, b: number, c: number) => void;
212
+ readonly caldrixweb_resolveModel: (a: number, b: number, c: number) => void;
132
213
  readonly caldrixweb_startChat: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
133
214
  readonly caldrixweb_startChatSplit: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
134
215
  readonly caldrixweb_startComplete: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
@@ -140,6 +221,7 @@ export interface InitOutput {
140
221
  readonly __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
141
222
  readonly __wbindgen_export3: (a: number) => void;
142
223
  readonly __wbindgen_add_to_stack_pointer: (a: number) => number;
224
+ readonly __wbindgen_export4: (a: number, b: number, c: number) => void;
143
225
  }
144
226
 
145
227
  export type SyncInitInput = BufferSource | WebAssembly.Module;
@@ -1 +1 @@
1
- class D{__destroy_into_raw(){const t=this.__wbg_ptr;return this.__wbg_ptr=0,N.unregister(this),t}free(){const t=this.__destroy_into_raw();e.__wbg_caldrixweb_free(t,0)}abort(){e.caldrixweb_abort(this.__wbg_ptr)}actIn(t){try{const o=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_actIn(o,this.__wbg_ptr,t);var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),i=a().getInt32(o+8,!0);if(i)throw c(r);return c(n)}finally{e.__wbindgen_add_to_stack_pointer(16)}}argsPtr(){return e.caldrixweb_argsPtr(this.__wbg_ptr)>>>0}attach(t,n){try{const o=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_attach(o,this.__wbg_ptr,p(t),p(n));var r=a().getInt32(o+0,!0),i=a().getInt32(o+4,!0);if(i)throw c(r)}finally{e.__wbindgen_add_to_stack_pointer(16)}}beginNext(){try{const i=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_beginNext(i,this.__wbg_ptr);var t=a().getInt32(i+0,!0),n=a().getInt32(i+4,!0),r=a().getInt32(i+8,!0);if(r)throw c(n);return c(t)}finally{e.__wbindgen_add_to_stack_pointer(16)}}bufferBytes(t){try{const o=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_bufferBytes(o,this.__wbg_ptr,t);var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),i=a().getInt32(o+8,!0);if(i)throw c(r);return c(n)}finally{e.__wbindgen_add_to_stack_pointer(16)}}dispose(){e.caldrixweb_dispose(this.__wbg_ptr)}doctor(){try{const i=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_doctor(i,this.__wbg_ptr);var t=a().getInt32(i+0,!0),n=a().getInt32(i+4,!0),r=a().getInt32(i+8,!0);if(r)throw c(n);return c(t)}finally{e.__wbindgen_add_to_stack_pointer(16)}}failLaunch(t){try{const i=e.__wbindgen_add_to_stack_pointer(-16),o=l(t,e.__wbindgen_export,e.__wbindgen_export2),s=g;e.caldrixweb_failLaunch(i,this.__wbg_ptr,o,s);var n=a().getInt32(i+0,!0),r=a().getInt32(i+4,!0);if(r)throw c(n)}finally{e.__wbindgen_add_to_stack_pointer(16)}}finishNext(){try{const i=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_finishNext(i,this.__wbg_ptr);var t=a().getInt32(i+0,!0),n=a().getInt32(i+4,!0),r=a().getInt32(i+8,!0);if(r)throw c(n);return c(t)}finally{e.__wbindgen_add_to_stack_pointer(16)}}finishStart(){try{const r=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_finishStart(r,this.__wbg_ptr);var t=a().getInt32(r+0,!0),n=a().getInt32(r+4,!0);if(n)throw c(t)}finally{e.__wbindgen_add_to_stack_pointer(16)}}loadWebGpu(t,n,r,i,o){try{const u=e.__wbindgen_add_to_stack_pointer(-16),x=v(t,e.__wbindgen_export),I=g,T=v(n,e.__wbindgen_export),C=g;var s=h(r)?0:v(r,e.__wbindgen_export),d=g;const j=l(o,e.__wbindgen_export,e.__wbindgen_export2),E=g;e.caldrixweb_loadWebGpu(u,this.__wbg_ptr,x,I,T,C,s,d,p(i),j,E);var w=a().getInt32(u+0,!0),f=a().getInt32(u+4,!0),y=a().getInt32(u+8,!0);if(y)throw c(f);return c(w)}finally{e.__wbindgen_add_to_stack_pointer(16)}}load(t,n,r,i,o){try{const u=e.__wbindgen_add_to_stack_pointer(-16),x=v(t,e.__wbindgen_export),I=g,T=v(n,e.__wbindgen_export),C=g;var s=h(r)?0:v(r,e.__wbindgen_export),d=g;const j=l(o,e.__wbindgen_export,e.__wbindgen_export2),E=g;e.caldrixweb_load(u,this.__wbg_ptr,x,I,T,C,s,d,p(i),j,E);var w=a().getInt32(u+0,!0),f=a().getInt32(u+4,!0),y=a().getInt32(u+8,!0);if(y)throw c(f);return c(w)}finally{e.__wbindgen_add_to_stack_pointer(16)}}logitsPtr(){try{const i=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_logitsPtr(i,this.__wbg_ptr);var t=a().getInt32(i+0,!0),n=a().getInt32(i+4,!0),r=a().getInt32(i+8,!0);if(r)throw c(n);return t>>>0}finally{e.__wbindgen_add_to_stack_pointer(16)}}static memory(){const t=e.caldrixweb_memory();return c(t)}constructor(t){try{const o=e.__wbindgen_add_to_stack_pointer(-16),s=l(t,e.__wbindgen_export,e.__wbindgen_export2),d=g;e.caldrixweb_new(o,s,d);var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),i=a().getInt32(o+8,!0);if(i)throw c(r);return this.__wbg_ptr=n,N.register(this,this.__wbg_ptr,this),this}finally{e.__wbindgen_add_to_stack_pointer(16)}}next(){try{const i=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_next(i,this.__wbg_ptr);var t=a().getInt32(i+0,!0),n=a().getInt32(i+4,!0),r=a().getInt32(i+8,!0);if(r)throw c(n);return c(t)}finally{e.__wbindgen_add_to_stack_pointer(16)}}precheck(t,n,r){try{const f=e.__wbindgen_add_to_stack_pointer(-16),y=v(t,e.__wbindgen_export),u=g;var i=h(n)?0:v(n,e.__wbindgen_export),o=g;const x=l(r,e.__wbindgen_export,e.__wbindgen_export2),I=g;e.caldrixweb_precheck(f,this.__wbg_ptr,y,u,i,o,x,I);var s=a().getInt32(f+0,!0),d=a().getInt32(f+4,!0),w=a().getInt32(f+8,!0);if(w)throw c(d);return c(s)}finally{e.__wbindgen_add_to_stack_pointer(16)}}static resolveAlias(t){try{const o=e.__wbindgen_add_to_stack_pointer(-16),s=l(t,e.__wbindgen_export,e.__wbindgen_export2),d=g;e.caldrixweb_resolveAlias(o,s,d);var n=a().getInt32(o+0,!0),r=a().getInt32(o+4,!0),i=a().getInt32(o+8,!0);if(i)throw c(r);return c(n)}finally{e.__wbindgen_add_to_stack_pointer(16)}}resolve(t,n){try{const s=e.__wbindgen_add_to_stack_pointer(-16),d=l(t,e.__wbindgen_export,e.__wbindgen_export2),w=g;e.caldrixweb_resolve(s,this.__wbg_ptr,d,w,n);var r=a().getInt32(s+0,!0),i=a().getInt32(s+4,!0),o=a().getInt32(s+8,!0);if(o)throw c(i);return c(r)}finally{e.__wbindgen_add_to_stack_pointer(16)}}startChatSplit(t,n){try{const s=e.__wbindgen_add_to_stack_pointer(-16),d=l(t,e.__wbindgen_export,e.__wbindgen_export2),w=g,f=l(n,e.__wbindgen_export,e.__wbindgen_export2),y=g;e.caldrixweb_startChatSplit(s,this.__wbg_ptr,d,w,f,y);var r=a().getInt32(s+0,!0),i=a().getInt32(s+4,!0),o=a().getInt32(s+8,!0);if(o)throw c(i);return c(r)}finally{e.__wbindgen_add_to_stack_pointer(16)}}startChat(t,n){try{const s=e.__wbindgen_add_to_stack_pointer(-16),d=l(t,e.__wbindgen_export,e.__wbindgen_export2),w=g,f=l(n,e.__wbindgen_export,e.__wbindgen_export2),y=g;e.caldrixweb_startChat(s,this.__wbg_ptr,d,w,f,y);var r=a().getInt32(s+0,!0),i=a().getInt32(s+4,!0),o=a().getInt32(s+8,!0);if(o)throw c(i);return r>>>0}finally{e.__wbindgen_add_to_stack_pointer(16)}}startCompleteSplit(t,n,r){try{const u=e.__wbindgen_add_to_stack_pointer(-16);var i=h(t)?0:l(t,e.__wbindgen_export,e.__wbindgen_export2),o=g,s=h(n)?0:z(n,e.__wbindgen_export),d=g;const x=l(r,e.__wbindgen_export,e.__wbindgen_export2),I=g;e.caldrixweb_startCompleteSplit(u,this.__wbg_ptr,i,o,s,d,x,I);var w=a().getInt32(u+0,!0),f=a().getInt32(u+4,!0),y=a().getInt32(u+8,!0);if(y)throw c(f);return c(w)}finally{e.__wbindgen_add_to_stack_pointer(16)}}startComplete(t,n,r){try{const u=e.__wbindgen_add_to_stack_pointer(-16);var i=h(t)?0:l(t,e.__wbindgen_export,e.__wbindgen_export2),o=g,s=h(n)?0:z(n,e.__wbindgen_export),d=g;const x=l(r,e.__wbindgen_export,e.__wbindgen_export2),I=g;e.caldrixweb_startComplete(u,this.__wbg_ptr,i,o,s,d,x,I);var w=a().getInt32(u+0,!0),f=a().getInt32(u+4,!0),y=a().getInt32(u+8,!0);if(y)throw c(f);return w>>>0}finally{e.__wbindgen_add_to_stack_pointer(16)}}vocab(){try{const i=e.__wbindgen_add_to_stack_pointer(-16);e.caldrixweb_vocab(i,this.__wbg_ptr);var t=a().getInt32(i+0,!0),n=a().getInt32(i+4,!0),r=a().getInt32(i+8,!0);if(r)throw c(n);return t>>>0}finally{e.__wbindgen_add_to_stack_pointer(16)}}static weightFiles(t){try{const d=e.__wbindgen_add_to_stack_pointer(-16);var n=h(t)?0:v(t,e.__wbindgen_export),r=g;e.caldrixweb_weightFiles(d,n,r);var i=a().getInt32(d+0,!0),o=a().getInt32(d+4,!0),s=a().getInt32(d+8,!0);if(s)throw c(o);return c(i)}finally{e.__wbindgen_add_to_stack_pointer(16)}}writeLogits(t){try{const i=e.__wbindgen_add_to_stack_pointer(-16),o=v(t,e.__wbindgen_export),s=g;e.caldrixweb_writeLogits(i,this.__wbg_ptr,o,s);var n=a().getInt32(i+0,!0),r=a().getInt32(i+4,!0);if(r)throw c(n)}finally{e.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&(D.prototype[Symbol.dispose]=D.prototype.free);function B(){return{__proto__:null,"./caldrix_web_bg.js":{__proto__:null,__wbg___wbindgen_memory_caa4a6165639c8b5:function(){const t=e.memory;return p(t)},__wbg___wbindgen_number_get_2e0e7dee9f701a71:function(t,n){const r=b(n),i=typeof r=="number"?r:void 0;a().setFloat64(t+8,h(i)?0:i,!0),a().setInt32(t+0,!h(i),!0)},__wbg___wbindgen_string_get_0380ccaa2f57f0d9:function(t,n){const r=b(n),i=typeof r=="string"?r:void 0;var o=h(i)?0:l(i,e.__wbindgen_export,e.__wbindgen_export2),s=g;a().setInt32(t+4,s,!0),a().setInt32(t+0,o,!0)},__wbg___wbindgen_throw_41e9ee4f547fc59a:function(t,n){throw new Error(P(t,n))},__wbg_call_1875a20c43a36133:function(){return U(function(t,n,r,i){const o=b(t).call(b(n),b(r),b(i));return p(o)},arguments)},__wbg_call_187d372bd5fdd4aa:function(){return U(function(t,n,r){const i=b(t).call(b(n),b(r));return p(i)},arguments)},__wbg_getRandomValues_a608c4436c19407a:function(){return U(function(t,n){globalThis.crypto.getRandomValues(F(t,n))},arguments)},__wbg_get_unchecked_288889d017702237:function(t,n){const r=b(t)[n>>>0];return p(r)},__wbg_instanceof_Error_80a725f81f2e102d:function(t){let n;try{n=b(t)instanceof Error}catch{n=!1}return n},__wbg_instanceof_Uint8Array_828cef2aaacafc31:function(t){let n;try{n=b(t)instanceof Uint8Array}catch{n=!1}return n},__wbg_length_7f3c00c40364105e:function(t){return b(t).length},__wbg_length_d4bdea10311bd9cf:function(t){return b(t).length},__wbg_message_5f8387f0c32b90a7:function(t){const n=b(t).message;return p(n)},__wbg_new_617a8cdb8bb1130e:function(){const t=new Object;return p(t)},__wbg_new_ee2291f50781bf1d:function(){const t=new Array;return p(t)},__wbg_new_from_slice_37a3c3a194266cb8:function(t,n){const r=new Uint32Array(G(t,n));return p(r)},__wbg_new_from_slice_9a868026ffa4208a:function(t,n){const r=new Uint8Array(F(t,n));return p(r)},__wbg_prototypesetcall_bc27214492979395:function(t,n,r){Uint8Array.prototype.set.call(F(t,n),b(r))},__wbg_push_2baf45db356cf468:function(t,n){return b(t).push(b(n))},__wbg_set_145a351398b48c65:function(){return U(function(t,n,r){return Reflect.set(b(t),b(n),b(r))},arguments)},__wbindgen_generic_0000000000000001:function(t){return p(t)},__wbindgen_generic_0000000000000002:function(t,n){const r=P(t,n);return p(r)},__wbindgen_object_drop_ref:function(t){c(t)}}}}const N=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(_=>e.__wbg_caldrixweb_free(_,1));function p(_){R===k.length&&k.push(k.length+1);const t=R;return R=k[t],k[t]=_,t}function q(_){_<1028||(k[_]=R,R=_)}function G(_,t){return _=_>>>0,V().subarray(_/4,_/4+t)}function F(_,t){return _=_>>>0,A().subarray(_/1,_/1+t)}let m=null;function a(){return(m===null||m.buffer.detached===!0||m.buffer.detached===void 0&&m.buffer!==e.memory.buffer)&&(m=new DataView(e.memory.buffer)),m}function P(_,t){return X(_>>>0,t)}let W=null;function V(){return(W===null||W.byteLength===0)&&(W=new Uint32Array(e.memory.buffer)),W}let S=null;function A(){return(S===null||S.byteLength===0)&&(S=new Uint8Array(e.memory.buffer)),S}function b(_){return k[_]}function U(_,t){try{return _.apply(this,t)}catch(n){e.__wbindgen_export3(p(n))}}let k=new Array(1024).fill(void 0);k.push(void 0,null,!0,!1);let R=k.length;function h(_){return _==null}function z(_,t){const n=t(_.length*4,4)>>>0;return V().set(_,n/4),g=_.length,n}function v(_,t){const n=t(_.length*1,1)>>>0;return A().set(_,n/1),g=_.length,n}function l(_,t,n){if(n===void 0){const d=O.encode(_),w=t(d.length,1)>>>0;return A().subarray(w,w+d.length).set(d),g=d.length,w}let r=_.length,i=t(r,1)>>>0;const o=A();let s=0;for(;s<r;s++){const d=_.charCodeAt(s);if(d>127)break;o[i+s]=d}if(s!==r){s!==0&&(_=_.slice(s)),i=n(i,r,r=s+_.length*3,1)>>>0;const d=A().subarray(i+s,i+r),w=O.encodeInto(_,d);s+=w.written,i=n(i,r,s,1)>>>0}return g=s,i}function c(_){const t=b(_);return q(_),t}let M=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});M.decode();const H=2146435072;let L=0;function X(_,t){return L+=t,L>=H&&(M=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),M.decode(),L=t),M.decode(A().subarray(_,_+t))}const O=new TextEncoder;"encodeInto"in O||(O.encodeInto=function(_,t){const n=O.encode(_);return t.set(n),{read:_.length,written:n.length}});let g=0,Y,J,e;function $(_,t){return J=_,e=_.exports,Y=t,m=null,W=null,S=null,e}async function K(_,t){if(typeof Response=="function"&&_ instanceof Response){if(!_.ok)throw new Error(`failed to fetch Wasm: ${_.status} ${_.statusText} fetching '${_.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(_,t)}catch(i){if(n(_.type)&&_.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",i);else throw i}const r=await _.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{const r=await WebAssembly.instantiate(_,t);return r instanceof WebAssembly.Instance?{instance:r,module:_}:r}function n(r){switch(r){case"basic":case"cors":case"default":return!0}return!1}}function Q(_){if(e!==void 0)return e;_!==void 0&&(Object.getPrototypeOf(_)===Object.prototype?{module:_}=_:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const t=B();_ instanceof WebAssembly.Module||(_=new WebAssembly.Module(_));const n=new WebAssembly.Instance(_,t);return $(n,_)}async function Z(_){if(e!==void 0)return e;_!==void 0&&(Object.getPrototypeOf(_)===Object.prototype?{module_or_path:_}=_:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),_===void 0&&(_=new URL("caldrix_web_bg.wasm",import.meta.url));const t=B();(typeof _=="string"||typeof Request=="function"&&_ instanceof Request||typeof URL=="function"&&_ instanceof URL)&&(_=fetch(_));const{instance:n,module:r}=await K(await _,t);return $(n,r)}export{D as CaldrixWeb,Z as default,Q as initSync};
1
+ class ${__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,X.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=i().getInt32(s+0,!0),_=i().getInt32(s+4,!0),r=i().getInt32(s+8,!0);if(r)throw d(_);return d(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}static adapterBase(e,n){let _,r;try{const p=t.__wbindgen_add_to_stack_pointer(-16),l=y(e,t.__wbindgen_export),I=g,k=v(n,t.__wbindgen_export,t.__wbindgen_export2),m=g;t.caldrixweb_adapterBase(p,l,I,k,m);var s=i().getInt32(p+0,!0),o=i().getInt32(p+4,!0),c=i().getInt32(p+8,!0),b=i().getInt32(p+12,!0),u=s,w=o;if(b)throw u=0,w=0,d(c);return _=u,r=w,C(u,w)}finally{t.__wbindgen_add_to_stack_pointer(16),t.__wbindgen_export4(_,r,1)}}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,x(e),x(n));var _=i().getInt32(s+0,!0),r=i().getInt32(s+4,!0);if(r)throw d(_)}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=i().getInt32(r+0,!0),n=i().getInt32(r+4,!0),_=i().getInt32(r+8,!0);if(_)throw d(n);return d(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=i().getInt32(s+0,!0),_=i().getInt32(s+4,!0),r=i().getInt32(s+8,!0);if(r)throw d(_);return d(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=i().getInt32(r+0,!0),n=i().getInt32(r+4,!0),_=i().getInt32(r+8,!0);if(_)throw d(n);return d(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}failLaunch(e){try{const r=t.__wbindgen_add_to_stack_pointer(-16),s=v(e,t.__wbindgen_export,t.__wbindgen_export2),o=g;t.caldrixweb_failLaunch(r,this.__wbg_ptr,s,o);var n=i().getInt32(r+0,!0),_=i().getInt32(r+4,!0);if(_)throw d(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=i().getInt32(r+0,!0),n=i().getInt32(r+4,!0),_=i().getInt32(r+8,!0);if(_)throw d(n);return d(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=i().getInt32(_+0,!0),n=i().getInt32(_+4,!0);if(n)throw d(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),c=y(e,t.__wbindgen_export),b=g;t.caldrixweb_ggufHeaderNeed(o,c,b,n);var _=i().getFloat64(o+0,!0),r=i().getInt32(o+8,!0),s=i().getInt32(o+12,!0);if(s)throw d(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=i().getInt32(r+0,!0),n=i().getInt32(r+4,!0),_=i().getInt32(r+8,!0);if(_)throw d(n);return d(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}static listingCap(){return t.caldrixweb_listingCap()}loadGguf(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),c=y(e,t.__wbindgen_export),b=g,u=v(n,t.__wbindgen_export,t.__wbindgen_export2),w=g;t.caldrixweb_loadGguf(o,this.__wbg_ptr,c,b,u,w);var _=i().getInt32(o+0,!0),r=i().getInt32(o+4,!0),s=i().getInt32(o+8,!0);if(s)throw d(r);return d(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}loadWebGpuGguf(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),c=y(e,t.__wbindgen_export),b=g,u=v(n,t.__wbindgen_export,t.__wbindgen_export2),w=g;t.caldrixweb_loadWebGpuGguf(o,this.__wbg_ptr,c,b,u,w);var _=i().getInt32(o+0,!0),r=i().getInt32(o+4,!0),s=i().getInt32(o+8,!0);if(s)throw d(r);return d(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}loadWebGpu(e,n,_,r,s,o,c,b){try{const A=t.__wbindgen_add_to_stack_pointer(-16),B=y(e,t.__wbindgen_export),G=g,D=y(n,t.__wbindgen_export),N=g;var u=h(_)?0:y(_,t.__wbindgen_export),w=g,p=h(r)?0:y(r,t.__wbindgen_export),l=g;const P=v(o,t.__wbindgen_export,t.__wbindgen_export2),V=g;var I=h(c)?0:y(c,t.__wbindgen_export),k=g;t.caldrixweb_loadWebGpu(A,this.__wbg_ptr,B,G,D,N,u,w,p,l,x(s),P,V,I,k,h(b)?0:x(b));var m=i().getInt32(A+0,!0),R=i().getInt32(A+4,!0),E=i().getInt32(A+8,!0);if(E)throw d(R);return d(m)}finally{t.__wbindgen_add_to_stack_pointer(16)}}load(e,n,_,r,s,o,c,b){try{const A=t.__wbindgen_add_to_stack_pointer(-16),B=y(e,t.__wbindgen_export),G=g,D=y(n,t.__wbindgen_export),N=g;var u=h(_)?0:y(_,t.__wbindgen_export),w=g,p=h(r)?0:y(r,t.__wbindgen_export),l=g;const P=v(o,t.__wbindgen_export,t.__wbindgen_export2),V=g;var I=h(c)?0:y(c,t.__wbindgen_export),k=g;t.caldrixweb_load(A,this.__wbg_ptr,B,G,D,N,u,w,p,l,x(s),P,V,I,k,h(b)?0:x(b));var m=i().getInt32(A+0,!0),R=i().getInt32(A+4,!0),E=i().getInt32(A+8,!0);if(E)throw d(R);return d(m)}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=i().getInt32(r+0,!0),n=i().getInt32(r+4,!0),_=i().getInt32(r+8,!0);if(_)throw d(n);return e>>>0}finally{t.__wbindgen_add_to_stack_pointer(16)}}static memory(){const e=t.caldrixweb_memory();return d(e)}constructor(e){try{const s=t.__wbindgen_add_to_stack_pointer(-16),o=v(e,t.__wbindgen_export,t.__wbindgen_export2),c=g;t.caldrixweb_new(s,o,c);var n=i().getInt32(s+0,!0),_=i().getInt32(s+4,!0),r=i().getInt32(s+8,!0);if(r)throw d(_);return this.__wbg_ptr=n,X.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=i().getInt32(r+0,!0),n=i().getInt32(r+4,!0),_=i().getInt32(r+8,!0);if(_)throw d(n);return d(e)}finally{t.__wbindgen_add_to_stack_pointer(16)}}static parseBaseListing(e,n,_){let r,s;try{const l=t.__wbindgen_add_to_stack_pointer(-16),I=y(e,t.__wbindgen_export),k=g,m=v(n,t.__wbindgen_export,t.__wbindgen_export2),R=g;t.caldrixweb_parseBaseListing(l,I,k,m,R,_);var o=i().getInt32(l+0,!0),c=i().getInt32(l+4,!0),b=i().getInt32(l+8,!0),u=i().getInt32(l+12,!0),w=o,p=c;if(u)throw w=0,p=0,d(b);return r=w,s=p,C(w,p)}finally{t.__wbindgen_add_to_stack_pointer(16),t.__wbindgen_export4(r,s,1)}}static parseListing(e){let n,_;try{const w=t.__wbindgen_add_to_stack_pointer(-16),p=y(e,t.__wbindgen_export),l=g;t.caldrixweb_parseListing(w,p,l);var r=i().getInt32(w+0,!0),s=i().getInt32(w+4,!0),o=i().getInt32(w+8,!0),c=i().getInt32(w+12,!0),b=r,u=s;if(c)throw b=0,u=0,d(o);return n=b,_=u,C(b,u)}finally{t.__wbindgen_add_to_stack_pointer(16),t.__wbindgen_export4(n,_,1)}}precheckGguf(e,n,_){try{const c=t.__wbindgen_add_to_stack_pointer(-16),b=y(e,t.__wbindgen_export),u=g,w=v(_,t.__wbindgen_export,t.__wbindgen_export2),p=g;t.caldrixweb_precheckGguf(c,this.__wbg_ptr,b,u,n,w,p);var r=i().getInt32(c+0,!0),s=i().getInt32(c+4,!0),o=i().getInt32(c+8,!0);if(o)throw d(s);return d(r)}finally{t.__wbindgen_add_to_stack_pointer(16)}}precheck(e,n,_,r){try{const l=t.__wbindgen_add_to_stack_pointer(-16),I=y(e,t.__wbindgen_export),k=g;var s=h(n)?0:y(n,t.__wbindgen_export),o=g;const m=v(_,t.__wbindgen_export,t.__wbindgen_export2),R=g;var c=h(r)?0:y(r,t.__wbindgen_export),b=g;t.caldrixweb_precheck(l,this.__wbg_ptr,I,k,s,o,m,R,c,b);var u=i().getInt32(l+0,!0),w=i().getInt32(l+4,!0),p=i().getInt32(l+8,!0);if(p)throw d(w);return d(u)}finally{t.__wbindgen_add_to_stack_pointer(16)}}static resolveAlias(e){try{const s=t.__wbindgen_add_to_stack_pointer(-16),o=v(e,t.__wbindgen_export,t.__wbindgen_export2),c=g;t.caldrixweb_resolveAlias(s,o,c);var n=i().getInt32(s+0,!0),_=i().getInt32(s+4,!0),r=i().getInt32(s+8,!0);if(r)throw d(_);return d(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}static resolveModel(e){try{const s=t.__wbindgen_add_to_stack_pointer(-16),o=v(e,t.__wbindgen_export,t.__wbindgen_export2),c=g;t.caldrixweb_resolveModel(s,o,c);var n=i().getInt32(s+0,!0),_=i().getInt32(s+4,!0),r=i().getInt32(s+8,!0);if(r)throw d(_);return d(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}resolve(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),c=v(e,t.__wbindgen_export,t.__wbindgen_export2),b=g;t.caldrixweb_resolve(o,this.__wbg_ptr,c,b,n);var _=i().getInt32(o+0,!0),r=i().getInt32(o+4,!0),s=i().getInt32(o+8,!0);if(s)throw d(r);return d(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}startChatSplit(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),c=v(e,t.__wbindgen_export,t.__wbindgen_export2),b=g,u=v(n,t.__wbindgen_export,t.__wbindgen_export2),w=g;t.caldrixweb_startChatSplit(o,this.__wbg_ptr,c,b,u,w);var _=i().getInt32(o+0,!0),r=i().getInt32(o+4,!0),s=i().getInt32(o+8,!0);if(s)throw d(r);return d(_)}finally{t.__wbindgen_add_to_stack_pointer(16)}}startChat(e,n){try{const o=t.__wbindgen_add_to_stack_pointer(-16),c=v(e,t.__wbindgen_export,t.__wbindgen_export2),b=g,u=v(n,t.__wbindgen_export,t.__wbindgen_export2),w=g;t.caldrixweb_startChat(o,this.__wbg_ptr,c,b,u,w);var _=i().getInt32(o+0,!0),r=i().getInt32(o+4,!0),s=i().getInt32(o+8,!0);if(s)throw d(r);return _>>>0}finally{t.__wbindgen_add_to_stack_pointer(16)}}startCompleteSplit(e,n,_){try{const p=t.__wbindgen_add_to_stack_pointer(-16);var r=h(e)?0:v(e,t.__wbindgen_export,t.__wbindgen_export2),s=g,o=h(n)?0:J(n,t.__wbindgen_export),c=g;const l=v(_,t.__wbindgen_export,t.__wbindgen_export2),I=g;t.caldrixweb_startCompleteSplit(p,this.__wbg_ptr,r,s,o,c,l,I);var b=i().getInt32(p+0,!0),u=i().getInt32(p+4,!0),w=i().getInt32(p+8,!0);if(w)throw d(u);return d(b)}finally{t.__wbindgen_add_to_stack_pointer(16)}}startComplete(e,n,_){try{const p=t.__wbindgen_add_to_stack_pointer(-16);var r=h(e)?0:v(e,t.__wbindgen_export,t.__wbindgen_export2),s=g,o=h(n)?0:J(n,t.__wbindgen_export),c=g;const l=v(_,t.__wbindgen_export,t.__wbindgen_export2),I=g;t.caldrixweb_startComplete(p,this.__wbg_ptr,r,s,o,c,l,I);var b=i().getInt32(p+0,!0),u=i().getInt32(p+4,!0),w=i().getInt32(p+8,!0);if(w)throw d(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=i().getInt32(r+0,!0),n=i().getInt32(r+4,!0),_=i().getInt32(r+8,!0);if(_)throw d(n);return e>>>0}finally{t.__wbindgen_add_to_stack_pointer(16)}}static weightFiles(e){try{const c=t.__wbindgen_add_to_stack_pointer(-16);var n=h(e)?0:y(e,t.__wbindgen_export),_=g;t.caldrixweb_weightFiles(c,n,_);var r=i().getInt32(c+0,!0),s=i().getInt32(c+4,!0),o=i().getInt32(c+8,!0);if(o)throw d(s);return d(r)}finally{t.__wbindgen_add_to_stack_pointer(16)}}writeLogits(e){try{const r=t.__wbindgen_add_to_stack_pointer(-16),s=y(e,t.__wbindgen_export),o=g;t.caldrixweb_writeLogits(r,this.__wbg_ptr,s,o);var n=i().getInt32(r+0,!0),_=i().getInt32(r+4,!0);if(_)throw d(n)}finally{t.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&($.prototype[Symbol.dispose]=$.prototype.free);function q(){return{__proto__:null,"./caldrix_web_bg.js":{__proto__:null,__wbg___wbindgen_memory_caa4a6165639c8b5:function(){const e=t.memory;return x(e)},__wbg___wbindgen_number_get_2e0e7dee9f701a71:function(e,n){const _=f(n),r=typeof _=="number"?_:void 0;i().setFloat64(e+8,h(r)?0:r,!0),i().setInt32(e+0,!h(r),!0)},__wbg___wbindgen_string_get_0380ccaa2f57f0d9:function(e,n){const _=f(n),r=typeof _=="string"?_:void 0;var s=h(r)?0:v(r,t.__wbindgen_export,t.__wbindgen_export2),o=g;i().setInt32(e+4,o,!0),i().setInt32(e+0,s,!0)},__wbg___wbindgen_throw_41e9ee4f547fc59a:function(e,n){throw new Error(C(e,n))},__wbg_call_1875a20c43a36133:function(){return T(function(e,n,_,r){const s=f(e).call(f(n),f(_),f(r));return x(s)},arguments)},__wbg_call_187d372bd5fdd4aa:function(){return T(function(e,n,_){const r=f(e).call(f(n),f(_));return x(r)},arguments)},__wbg_getRandomValues_a608c4436c19407a:function(){return T(function(e,n){globalThis.crypto.getRandomValues(H(e,n))},arguments)},__wbg_get_unchecked_288889d017702237:function(e,n){const _=f(e)[n>>>0];return x(_)},__wbg_instanceof_Error_80a725f81f2e102d:function(e){let n;try{n=f(e)instanceof Error}catch{n=!1}return n},__wbg_instanceof_Uint8Array_828cef2aaacafc31:function(e){let n;try{n=f(e)instanceof Uint8Array}catch{n=!1}return n},__wbg_length_7f3c00c40364105e:function(e){return f(e).length},__wbg_length_d4bdea10311bd9cf:function(e){return f(e).length},__wbg_message_5f8387f0c32b90a7:function(e){const n=f(e).message;return x(n)},__wbg_new_617a8cdb8bb1130e:function(){const e=new Object;return x(e)},__wbg_new_ee2291f50781bf1d:function(){const e=new Array;return x(e)},__wbg_new_from_slice_37a3c3a194266cb8:function(e,n){const _=new Uint32Array(Z(e,n));return x(_)},__wbg_new_from_slice_9a868026ffa4208a:function(e,n){const _=new Uint8Array(H(e,n));return x(_)},__wbg_prototypesetcall_bc27214492979395:function(e,n,_){Uint8Array.prototype.set.call(H(e,n),f(_))},__wbg_push_2baf45db356cf468:function(e,n){return f(e).push(f(n))},__wbg_set_145a351398b48c65:function(){return T(function(e,n,_){return Reflect.set(f(e),f(n),f(_))},arguments)},__wbindgen_generic_0000000000000001:function(e){return x(e)},__wbindgen_generic_0000000000000002:function(e,n){const _=C(e,n);return x(_)},__wbindgen_object_drop_ref:function(e){d(e)}}}}const X=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(a=>t.__wbg_caldrixweb_free(a,1));function x(a){F===W.length&&W.push(W.length+1);const e=F;return F=W[e],W[e]=a,e}function Q(a){a<1028||(W[a]=F,F=a)}function Z(a,e){return a=a>>>0,Y().subarray(a/4,a/4+e)}function H(a,e){return a=a>>>0,M().subarray(a/1,a/1+e)}let S=null;function i(){return(S===null||S.buffer.detached===!0||S.buffer.detached===void 0&&S.buffer!==t.memory.buffer)&&(S=new DataView(t.memory.buffer)),S}function C(a,e){return et(a>>>0,e)}let O=null;function Y(){return(O===null||O.byteLength===0)&&(O=new Uint32Array(t.memory.buffer)),O}let U=null;function M(){return(U===null||U.byteLength===0)&&(U=new Uint8Array(t.memory.buffer)),U}function f(a){return W[a]}function T(a,e){try{return a.apply(this,e)}catch(n){t.__wbindgen_export3(x(n))}}let W=new Array(1024).fill(void 0);W.push(void 0,null,!0,!1);let F=W.length;function h(a){return a==null}function J(a,e){const n=e(a.length*4,4)>>>0;return Y().set(a,n/4),g=a.length,n}function y(a,e){const n=e(a.length*1,1)>>>0;return M().set(a,n/1),g=a.length,n}function v(a,e,n){if(n===void 0){const c=L.encode(a),b=e(c.length,1)>>>0;return M().subarray(b,b+c.length).set(c),g=c.length,b}let _=a.length,r=e(_,1)>>>0;const s=M();let o=0;for(;o<_;o++){const c=a.charCodeAt(o);if(c>127)break;s[r+o]=c}if(o!==_){o!==0&&(a=a.slice(o)),r=n(r,_,_=o+a.length*3,1)>>>0;const c=M().subarray(r+o,r+_),b=L.encodeInto(a,c);o+=b.written,r=n(r,_,o,1)>>>0}return g=o,r}function d(a){const e=f(a);return Q(a),e}let j=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});j.decode();const tt=2146435072;let z=0;function et(a,e){return z+=e,z>=tt&&(j=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),j.decode(),z=e),j.decode(M().subarray(a,a+e))}const L=new TextEncoder;"encodeInto"in L||(L.encodeInto=function(a,e){const n=L.encode(a);return e.set(n),{read:a.length,written:n.length}});let g=0,nt,rt,t;function K(a,e){return rt=a,t=a.exports,nt=e,S=null,O=null,U=null,t}async function _t(a,e){if(typeof Response=="function"&&a instanceof Response){if(!a.ok)throw new Error(`failed to fetch Wasm: ${a.status} ${a.statusText} fetching '${a.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(a,e)}catch(r){if(n(a.type)&&a.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 a.arrayBuffer();return await WebAssembly.instantiate(_,e)}else{const _=await WebAssembly.instantiate(a,e);return _ instanceof WebAssembly.Instance?{instance:_,module:a}:_}function n(_){switch(_){case"basic":case"cors":case"default":return!0}return!1}}function it(a){if(t!==void 0)return t;a!==void 0&&(Object.getPrototypeOf(a)===Object.prototype?{module:a}=a:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const e=q();a instanceof WebAssembly.Module||(a=new WebAssembly.Module(a));const n=new WebAssembly.Instance(a,e);return K(n,a)}async function at(a){if(t!==void 0)return t;a!==void 0&&(Object.getPrototypeOf(a)===Object.prototype?{module_or_path:a}=a:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),a===void 0&&(a=new URL("caldrix_web_bg.wasm",import.meta.url));const e=q();(typeof a=="string"||typeof Request=="function"&&a instanceof Request||typeof URL=="function"&&a instanceof URL)&&(a=fetch(a));const{instance:n,module:_}=await _t(await a,e);return K(n,_)}export{$ as CaldrixWeb,at as default,it as initSync};
Binary file
@@ -4,6 +4,7 @@ export const memory: WebAssembly.Memory;
4
4
  export const __wbg_caldrixweb_free: (a: number, b: number) => void;
5
5
  export const caldrixweb_abort: (a: number) => void;
6
6
  export const caldrixweb_actIn: (a: number, b: number, c: number) => void;
7
+ export const caldrixweb_adapterBase: (a: number, b: number, c: number, d: number, e: number) => void;
7
8
  export const caldrixweb_argsPtr: (a: number) => number;
8
9
  export const caldrixweb_attach: (a: number, b: number, c: number, d: number) => void;
9
10
  export const caldrixweb_beginNext: (a: number, b: number) => void;
@@ -13,15 +14,25 @@ export const caldrixweb_doctor: (a: number, b: number) => void;
13
14
  export const caldrixweb_failLaunch: (a: number, b: number, c: number, d: number) => void;
14
15
  export const caldrixweb_finishNext: (a: number, b: number) => void;
15
16
  export const caldrixweb_finishStart: (a: number, b: number) => void;
16
- 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;
17
- 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;
17
+ export const caldrixweb_ggufHeaderFirstRange: () => number;
18
+ export const caldrixweb_ggufHeaderNeed: (a: number, b: number, c: number, d: number) => void;
19
+ export const caldrixweb_listAliases: (a: number) => void;
20
+ export const caldrixweb_listingCap: () => number;
21
+ 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, l: number, m: number, n: number, o: number, p: number) => void;
22
+ export const caldrixweb_loadGguf: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
23
+ 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, l: number, m: number, n: number, o: number, p: number) => void;
24
+ export const caldrixweb_loadWebGpuGguf: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
18
25
  export const caldrixweb_logitsPtr: (a: number, b: number) => void;
19
26
  export const caldrixweb_memory: () => number;
20
27
  export const caldrixweb_new: (a: number, b: number, c: number) => void;
21
28
  export const caldrixweb_next: (a: number, b: number) => void;
22
- export const caldrixweb_precheck: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
29
+ export const caldrixweb_parseBaseListing: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
30
+ export const caldrixweb_parseListing: (a: number, b: number, c: number) => void;
31
+ export const caldrixweb_precheck: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number) => void;
32
+ export const caldrixweb_precheckGguf: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => void;
23
33
  export const caldrixweb_resolve: (a: number, b: number, c: number, d: number, e: number) => void;
24
34
  export const caldrixweb_resolveAlias: (a: number, b: number, c: number) => void;
35
+ export const caldrixweb_resolveModel: (a: number, b: number, c: number) => void;
25
36
  export const caldrixweb_startChat: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
26
37
  export const caldrixweb_startChatSplit: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
27
38
  export const caldrixweb_startComplete: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
@@ -33,3 +44,4 @@ export const __wbindgen_export: (a: number, b: number) => number;
33
44
  export const __wbindgen_export2: (a: number, b: number, c: number, d: number) => number;
34
45
  export const __wbindgen_export3: (a: number) => void;
35
46
  export const __wbindgen_add_to_stack_pointer: (a: number) => number;
47
+ export const __wbindgen_export4: (a: number, b: number, c: number) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caldrix-ai/caldrix",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "description": "Run a language model in the browser, in a worker, on WebAssembly or WebGPU; see the README for what has run.",
6
6
  "license": "Apache-2.0",