webslm 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +64 -12
  2. package/dist/ai-sdk/index.d.ts +1 -1
  3. package/dist/ai-sdk/index.js +1 -1
  4. package/dist/cache/models.d.ts +32 -3
  5. package/dist/cache/models.js +106 -11
  6. package/dist/cache/node-fs.d.ts +26 -3
  7. package/dist/cache/node-fs.js +43 -9
  8. package/dist/cache-management.d.ts +1 -1
  9. package/dist/curated.d.ts +31 -1
  10. package/dist/curated.js +49 -5
  11. package/dist/download.d.ts +4 -0
  12. package/dist/download.js +29 -4
  13. package/dist/engine.d.ts +33 -4
  14. package/dist/engine.js +451 -44
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +1 -1
  17. package/dist/models.d.ts +26 -6
  18. package/dist/models.js +63 -7
  19. package/dist/native.d.ts +165 -0
  20. package/dist/native.js +243 -0
  21. package/dist/protocol.d.ts +12 -2
  22. package/dist/recommended-sampling.d.ts +54 -0
  23. package/dist/recommended-sampling.js +73 -0
  24. package/dist/simple.d.ts +22 -8
  25. package/dist/simple.js +35 -9
  26. package/dist/types.d.ts +85 -17
  27. package/native-manifest.json +47 -0
  28. package/package.json +2 -1
  29. package/wasm/relaxed/webslm_wasm.d.ts +26 -4
  30. package/wasm/relaxed/webslm_wasm.js +70 -17
  31. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  32. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +5 -3
  33. package/wasm/simd/webslm_wasm.d.ts +26 -4
  34. package/wasm/simd/webslm_wasm.js +70 -17
  35. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  36. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +5 -3
  37. package/wasm/threads/webslm_wasm.d.ts +26 -4
  38. package/wasm/threads/webslm_wasm.js +75 -22
  39. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  40. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +5 -3
package/README.md CHANGED
@@ -12,14 +12,14 @@ import { ask } from "webslm";
12
12
  console.log(await ask("Write a haiku about the sea"));
13
13
  ```
14
14
 
15
- The first call downloads the default model ([SmolLM2 360M Instruct](https://huggingface.co/HuggingFaceTB/SmolLM2-360M-Instruct), about 720 MB) into a local cache; later runs load it offline. The same code runs in browsers, Node 20+ and Bun, with no bundler or setup in Node.
15
+ The first call downloads the default model ([LFM2.5 350M](https://huggingface.co/LiquidAI/LFM2.5-350M), about 710 MB) into a local cache; later runs load it offline. The same code runs in browsers, Node 20+ and Bun, with no bundler or setup in Node.
16
16
 
17
17
  - Runs in a dedicated module Worker in browsers (`worker_threads` in Node), so the page stays responsive.
18
18
  - Downloads a checkpoint once into the Origin Private File System (a directory in Node), resumes interrupted downloads, checks the Hub's SHA-256 and loads offline afterwards.
19
19
  - Streams answers, keeps conversations, and exposes a low-level session API (teacher-forced scoring, step-wise decoding, logits and hidden states as `Float32Array`s).
20
20
  - Searches the Hub for models it can run.
21
21
 
22
- Supported architectures: Llama-style (SmolLM2, Mistral), Qwen2, Qwen3, Qwen3.5 (language model; Gated DeltaNet hybrid), LFM2 / LFM2.5 and LFM3. Models run on WebGPU or on the CPU through WebAssembly (SIMD, and Web Worker threads where the page allows): with `device: "auto"` (the default), WebGPU for models above ~100M parameters when the browser has an adapter, the CPU otherwise; `ModelInfo.backend` says which one runs. ESM only; browsers with WebAssembly SIMD (every current browser). Demo: <https://maxgfr.github.io/webslm/>.
22
+ Supported architectures: Llama-style (SmolLM2, Mistral), Qwen2, Qwen3, Qwen3.5 (language model; Gated DeltaNet hybrid), LFM2 / LFM2.5 and LFM3. Models run on WebGPU or on the CPU through WebAssembly (SIMD, and Web Worker threads where the page allows): with `device: "auto"` (the default), WebGPU for models above ~100M parameters when the browser has an adapter, the CPU otherwise; `ModelInfo.backend` says which one runs. In Node and Bun, the [native engine](#native-engine-in-node) runs instead (downloaded once from the release, checked, and cached): native SIMD kernels on every core, and the GPU through Metal, Vulkan or DX12. ESM only; browsers with WebAssembly SIMD (every current browser). Demo: <https://maxgfr.github.io/webslm/>.
23
23
 
24
24
  ## Ask
25
25
 
@@ -38,7 +38,7 @@ Options, all optional:
38
38
  | --- | --- | --- |
39
39
  | `model` | `DEFAULT_MODEL` | Hub repository id or a [source](#sources) (module-level calls only) |
40
40
  | `maxTokens` | `512` | Largest number of new tokens (reasoning included) |
41
- | `temperature` | the checkpoint's `generation_config.json`, else `0.7` | `0` is greedy, deterministic decoding |
41
+ | `temperature` | the model card's for the [curated models](#sampling-defaults), else the checkpoint's `generation_config.json`, else `0.7` | `0` is greedy, deterministic decoding |
42
42
  | `system` | | System prompt |
43
43
  | `think` | the template's default | `enable_thinking` for models that reason first (Qwen3, LFM3, and Qwen3.5 when asked); ignored by the others |
44
44
  | `stop` | | Strings that end the answer (never emitted, not even in part) |
@@ -64,7 +64,7 @@ Models such as Qwen3 and LFM3 write their reasoning in a `<think>…</think>` bl
64
64
  const { text, reasoning } = await ask("Is 97 prime?", { model: "Qwen/Qwen3-0.6B", withReasoning: true });
65
65
  ```
66
66
 
67
- The split is generic: a `<think>` block at the start of the output (or one the chat template opens in the prompt) is reasoning, whatever the model. `splitReasoning(output)` applies it to text you already have. A reasoning model can spend its `maxTokens` thinking, leaving an empty answer: raise `maxTokens` or pass `think: false`.
67
+ The split is generic: a `<think>` block at the start of the output (or one the chat template opens in the prompt) is reasoning, whatever the model. `splitReasoning(output, opened?)` applies it to text you already have (`opened`: the prompt opened the block, as Qwen3.5's and LFM3's do when thinking; inferred when left out). A reasoning model can spend its `maxTokens` thinking, leaving an empty answer: raise `maxTokens` or pass `think: false`.
68
68
 
69
69
  ## Stream
70
70
 
@@ -99,7 +99,7 @@ chat.reset();
99
99
  await llm.unload();
100
100
  ```
101
101
 
102
- `load(model?, options?)` takes what `loadModel` takes: a repository id (default `DEFAULT_MODEL`) or a [source](#sources), and options that are all optional: `device` (`"auto"` (default), `"webgpu"` or `"cpu"`; `"webgpu"` falls back to the CPU when no GPU device can be created, and `"auto"` also when the model does not fit in GPU memory or the device fails while loading; `ModelInfo.deviceNote` says why), `quant` (default `"q8"`; `"q4"`, 4-bit blocks of 16 values, is smaller and less accurate, `"f32"` unquantized, `"auto"` picks `"q8"` unless the model does not fit this environment's memory, then `"q4"`, see [`fitModel`](#hub-helpers-and-cache); `ModelInfo.quantNote` says why), `revision`, `token` (gated or private repositories), `contextLength`, `onProgress`, `signal`, `worker` (default `true`), `cacheDir` (Node), `deterministic` (CPU only), and the advanced `wasmFlavour` and `threads` (see [CPU builds](#cpu-builds-and-deterministic-mode)).
102
+ `load(model?, options?)` takes what `loadModel` takes: a repository id (default `DEFAULT_MODEL`) or a [source](#sources), and options that are all optional: `device` (`"auto"` (default), `"webgpu"` or `"cpu"`; `"webgpu"` falls back to the CPU when no GPU device can be created, and `"auto"` also when the model does not fit in GPU memory or the device fails while loading; `ModelInfo.deviceNote` says why), `quant` (default `"q8"`; `"q4"`, 4-bit blocks of 16 values, is smaller and less accurate, `"f32"` unquantized, `"auto"` picks `"q8"` unless the model does not fit this environment's memory, then `"q4"`, see [`fitModel`](#hub-helpers-and-cache); `ModelInfo.quantNote` says why), `revision`, `token` (gated or private repositories), `contextLength`, `onProgress`, `signal`, `worker` (default `true`), `cacheDir` (Node), `weightCache` (default `true`, see [the converted-weight cache](#converted-weight-cache)), `deterministic` (CPU only), and the advanced `wasmFlavour` and `threads` (see [CPU builds](#cpu-builds-and-deterministic-mode)).
103
103
 
104
104
  Each chat keeps its own cache in the engine, so a turn only processes the new message; `chat.dispose()` frees it. Calls on one model, and turns of one chat, run one after the other. `llm.model` is the underlying `Model`, for the advanced API.
105
105
 
@@ -150,7 +150,7 @@ await model.unload(); // or webslm.unloadAll()
150
150
 
151
151
  | AI SDK | webslm |
152
152
  | ------ | ------ |
153
- | `maxOutputTokens`, `temperature`, `topP`, `topK`, `presencePenalty`, `frequencyPenalty`, `seed`, `stopSequences`, `abortSignal` | passed to the engine; unset `temperature` is the checkpoint's, else 0.7 |
153
+ | `maxOutputTokens`, `temperature`, `topP`, `topK`, `presencePenalty`, `frequencyPenalty`, `seed`, `stopSequences`, `abortSignal` | passed to the engine; unset sampling options are the model card's for the [curated models](#sampling-defaults), else the checkpoint's (`temperature` else 0.7) |
154
154
  | `reasoning` | `"none"` turns thinking off (`enable_thinking: false`), any other level on, with a `thinkingBudget` of 128 (`minimal`), 512 (`low`) or 2048 (`medium`) tokens; reasoning comes back as reasoning parts |
155
155
  | `providerOptions.webslm` | `think`, `maxTokens`, `temperature`, `topK`, `topP`, `minP`, `repetitionPenalty`, `thinkingBudget`, `templateKwargs` for one call |
156
156
  | `usage` | prompt tokens (`cacheRead`: tokens served from the KV cache of earlier turns) and generated tokens |
@@ -162,7 +162,7 @@ await model.unload(); // or webslm.unloadAll()
162
162
 
163
163
  Prompts are text: user and assistant text parts, and text documents (`file` parts whose data is text). Other files are refused. Tool calls and results of earlier turns are sent as plain text. Consecutive messages of one role are merged. A multi-turn conversation reuses the KV cache, so each call only processes the new messages.
164
164
 
165
- `CURATED_MODELS` (also exported by `webslm`) lists checkpoints known to run well, for a model picker; `searchModels` finds others on the Hub. `ai` and `@ai-sdk/provider` are optional peer dependencies: the main `webslm` entry does not need them. The demo's [AI SDK page](https://maxgfr.github.io/webslm/ai-sdk.html) (`apps/demo/src/ai-sdk.ts`) is a complete example.
165
+ `CURATED_MODELS` (also exported by `webslm`) lists checkpoints known to run well, with the sampling their model cards recommend, for a model picker; `searchModels` finds others on the Hub. `ai` and `@ai-sdk/provider` are optional peer dependencies: the main `webslm` entry does not need them. The demo's [AI SDK page](https://maxgfr.github.io/webslm/ai-sdk.html) (`apps/demo/src/ai-sdk.ts`) is a complete example.
166
166
 
167
167
  ## Advanced API
168
168
 
@@ -188,7 +188,23 @@ const text = await model.generate("What is the capital of France?"); // whole an
188
188
  await model.unload();
189
189
  ```
190
190
 
191
- `chat` reuses the session's cache across turns, so a follow-up only processes the new message. Stop a stream with `stream.stop()`, by breaking out of the loop, or with `signal`. Sampling options left unset come from the checkpoint's `generation_config.json` (`model.info().generationConfig`) when it enables sampling, else decoding is greedy; `temperature: 0` is greedy. Chat template variables go through `templateKwargs`, e.g. `{ enable_thinking: false }` for Qwen3. Output is returned as generated, `<think>` blocks included.
191
+ `chat` reuses the session's cache across turns, so a follow-up only processes the new message. Stop a stream with `stream.stop()`, by breaking out of the loop, or with `signal`. Sampling options left unset come from the model card for the [curated models](#sampling-defaults), else from the checkpoint's `generation_config.json` (`model.info().generationConfig`) when it enables sampling, else decoding is greedy; `temperature: 0` is greedy. Chat template variables go through `templateKwargs`, e.g. `{ enable_thinking: false }` for Qwen3. Output is returned as generated, `<think>` blocks included.
192
+
193
+ ### Sampling defaults
194
+
195
+ The checkpoints of SmolLM2, LFM2.5 and Qwen3.5 ship no sampling settings, and Qwen3's are those of its thinking mode, so the curated models (`CURATED_MODELS`) start every generation from what their model cards recommend instead; options a call sets override the matching fields, and `temperature: 0` turns them off (greedy decoding):
196
+
197
+ | Model | Answering directly | Thinking |
198
+ | --- | --- | --- |
199
+ | SmolLM2 135M, 360M | temperature 0.2, top-p 0.9 | |
200
+ | LFM2.5 350M | temperature 0.1, top-k 50, repetition penalty 1.05 | |
201
+ | Qwen3 0.6B | temperature 0.7, top-p 0.8, top-k 20 | temperature 0.6, top-p 0.95, top-k 20 |
202
+ | Qwen3.5 0.8B | temperature 0.7, top-p 0.8, top-k 20, presence penalty 1.5 | temperature 0.6, top-p 0.95, top-k 20, presence penalty 1.5 |
203
+ | LFM3 1.7B | temperature 0.1, top-k 50, repetition penalty 1.1 | |
204
+
205
+ The thinking column applies when `templateKwargs.enable_thinking` (the simple API's `think`) is `true`, or unset for the models that think by default (Qwen3, LFM3). Other checkpoints of these families (`model_type` `qwen3`, `qwen3_5`, `lfm2`, `lfm3`) get their family's settings when their `generation_config.json` does not ask for sampling; any other checkpoint uses its `generation_config.json`. `recommendedSampling(repoOrCheckpoint, think?)` returns the settings (`undefined` when there are none) and `RECOMMENDED_SAMPLING` is the table: the Rust engine's (`crates/webslm-core/src/recommended_sampling.json`), so `webslm run`, `webslm chat` and `webslm serve` pick the same settings.
206
+
207
+ Bigger models use the conversation better: on a three-turn chat ("My name is Ana and I live in Lisbon.", "What is my name?", "Which city do I live in?") decoded greedily, the SmolLM2 checkpoints repeat their first answer, LFM2.5 350M answers "Ana" and "Lisbon", Qwen3.5 0.8B recalls the name; `transformers` gives the same answers, token for token (`test/chat-wasm.test.ts`).
192
208
 
193
209
  ## Generation controls
194
210
 
@@ -308,7 +324,7 @@ await session.reset();
308
324
 
309
325
  Hidden state `i` is the residual stream after layer `i` counted from 1 (`0` is the embedding output), before the final norm: the indexing of `transformers`' `output_hidden_states`. Buffers are transferred from the worker without copies.
310
326
 
311
- Attention caches rewind for free. Models with recurrent layers (LFM2 and LFM3 short convolutions, Qwen3.5 Gated DeltaNet, LFM3's sliding-window ring buffers) cannot rewind their state, so `truncate(n)` recomputes it from the first `n` tokens (a prefill of `n` tokens); chats that diverge inside the cache do the same.
327
+ Attention caches rewind for free. Models with recurrent layers (LFM2 and LFM3 short convolutions, Qwen3.5 Gated DeltaNet, LFM3's sliding-window ring buffers) cannot rewind their state, so `truncate(n)` recomputes it from the latest checkpoint before `n`, or from the start. `chat` checkpoints those layers where the history ends and at the end of the prompt, so the next turn of a conversation resumes there even when the template renders the last answer differently (Qwen3.5 drops reasoning blocks): it only computes the new turn.
312
328
 
313
329
  ## Hub helpers and cache
314
330
 
@@ -332,9 +348,24 @@ await cacheUsage(); // { usedBytes, originUsageBytes, quotaBytes, persisted }
332
348
 
333
349
  `fitModel` estimates the memory of each weight format from `config.json` and the safetensors headers (no weights are downloaded): the weights in their load format, the KV cache layer by layer at `contextLength` (full attention grows with the context, sliding-window layers keep a ring of `2 × window - 1` positions, convolution and Gated DeltaNet layers a fixed state) and the activations of a prefill, the same numbers as the Rust engine's estimate (`estimateModelMemory` gives them for any config and tensor shapes). It compares them with what the environment reports: `navigator.deviceMemory` less a reserve for the browser and the OS, the 4 GiB a WebAssembly memory can address (the CPU engine), the largest buffer of the WebGPU adapter, and `navigator.storage.estimate()` for the download (`getBrowserResources()` reads them, `fitParams(params, resources)` gives a quick verdict from a parameter count, as search results carry no config). A model fits below 80% of the usable memory and is tight up to 100%. Browsers round `deviceMemory` down and cap it (8 GiB in Chromium), and do not report GPU memory, so the verdict is conservative.
334
350
 
351
+ ### Converted-weight cache
352
+
353
+ Loading a hub model in `"q8"` or a 4-bit format converts its BF16 checkpoint as it loads. The converted weights are stored next to the download (`<repo>/<sha>/quantized/<format>/weights.webslmq`, in OPFS or the Node cache directory, in the command-line tool's file format), and later loads read them instead of converting again. In Node (WebAssembly, one thread, Apple M5), from the cache:
354
+
355
+ | Model, Q8_0 | Converting | From the converted weights |
356
+ | --- | --- | --- |
357
+ | SmolLM2 135M | 0.6 to 0.8 s | 0.11 s |
358
+ | LFM2.5 350M | 1.4 to 1.6 s | 0.26 s |
359
+ | Qwen3 0.6B | 2.4 to 2.7 s | 0.51 to 0.54 s |
360
+ | Qwen3.5 0.8B | 3.2 to 3.5 s | 0.62 to 0.77 s |
361
+
362
+ The first load writes the file as it converts (0.1 to 1.8 s more, once). Each weight carries a CRC-32 and the file a versioned header and the repository, commit and format it was converted from: a file that does not match, or that fails a check, is converted again and rewritten. `info().weightCache` says what a load did (`{ status: "hit" | "written" | "failed" | "off", bytes }`); `weightCache: false` in the load options, or `WEBSLM_QUANT_CACHE=0` in Node, turns it off. Float formats (`"f32"`), sources other than the hub and the Cache API (which keeps a file in memory until it is complete) are not cached. `deleteCachedModel` removes the converted weights with the model, and `listCachedModels` counts them in its sizes.
363
+
335
364
  ## Node, Bun and Deno
336
365
 
337
- The same API works in Node 20+ and Bun, as a plain ESM script with no bundler. The cache lives in `WEBSLM_CACHE_DIR` or `~/.cache/webslm` (`cacheDir` in the options overrides it). `WEBSLM_OFFLINE=1` (or `HF_HUB_OFFLINE=1`) forbids network access: models already in the cache load, anything else rejects with `NETWORK`. `HF_ENDPOINT` replaces `https://huggingface.co` (a mirror, or a local stand-in in tests) unless a source gives its own `hubUrl`. The engine runs in a `worker_threads` worker, which does not keep the process alive between calls; pass `worker: false` to run it on the calling thread. Deno 2 runs Hub models as is; for a `files` source of a few hundred megabytes, pass `worker: false` (Deno's `worker_threads` cannot copy buffers that large).
366
+ The same API works in Node 20+ and Bun, as a plain ESM script with no bundler, on the [native engine](#native-engine-in-node) when it is available, else on WebAssembly. The cache is the [command-line tool's](https://github.com/maxgfr/webslm#cache-and-hugging-face-tokens): `WEBSLM_CACHE_DIR`, else `~/Library/Caches/webslm` on macOS, `%LOCALAPPDATA%\webslm\cache` on Windows, `$XDG_CACHE_HOME/webslm` or `~/.cache/webslm` on Linux (`cacheDir` in the options overrides it). It has the same layout, so a model pulled with `webslm pull` loads in Node without a download, and a model downloaded in Node runs with `webslm run`. `WEBSLM_OFFLINE=1` (or `HF_HUB_OFFLINE=1`) forbids network access: models already in the cache load, anything else rejects with `NETWORK`. `HF_ENDPOINT` replaces `https://huggingface.co` (a mirror, or a local stand-in in tests) unless a source gives its own `hubUrl`. The engine runs in a `worker_threads` worker, which does not keep the process alive between calls; pass `worker: false` to run it on the calling thread. Deno 2 runs Hub models as is; for a `files` source of a few hundred megabytes, pass `worker: false` (Deno's `worker_threads` cannot copy buffers that large).
367
+
368
+ Earlier versions kept the Node cache in `~/.cache/webslm` on macOS and in `%USERPROFILE%\.cache\webslm` on Windows (or `$XDG_CACHE_HOME/webslm` when set), apart from the command-line tool's. webslm does not touch that directory: models in it download again into the new one. To keep them, move the directory when the new one does not exist yet (`mv ~/.cache/webslm ~/Library/Caches/webslm` on macOS), or merge it into the new one and delete it (`rsync -a --ignore-existing ~/.cache/webslm/ ~/Library/Caches/webslm/ && rm -rf ~/.cache/webslm`); or just delete it (`rm -rf ~/.cache/webslm`). Its `native/` directory, the native engine, is downloaded again when needed. With `WEBSLM_CACHE_DIR` set nothing changes.
338
369
 
339
370
  ```ts
340
371
  import { readFile } from "node:fs/promises";
@@ -352,6 +383,27 @@ const llm = await load({ files });
352
383
  console.log(await llm.ask("Hello!"));
353
384
  ```
354
385
 
386
+ ## Native engine in Node
387
+
388
+ Each release attaches to its [GitHub Release](https://github.com/maxgfr/webslm/releases) a Node-API addon built from the same Rust engine, for `darwin-arm64`, `darwin-x64`, `linux-x64-gnu`, `linux-arm64-gnu` (glibc 2.28 and later), `linux-x64-musl`, `linux-arm64-musl` (Alpine) and `win32-x64-msvc`: `webslm-node-<version>-<platform>.node.gz`, about 5 MB. The npm package carries the SHA-256 of each (`native-manifest.json`). The first time a model loads in Node or Bun, webslm downloads the addon of its platform and version into the cache directory (`<cache>/native/<version>/`), checks both the download and the uncompressed addon against the manifest, and loads it; later runs load it from the cache, offline. Nothing runs at install time. The addon runs hub models instead of the WebAssembly build:
389
+
390
+ - the native CPU kernels (NEON with dotprod and i8mm, AVX2, AVX-512 VNNI) on every core, capped by the container's CPU quota, instead of WebAssembly SIMD on at most 8 threads;
391
+ - the GPU through Metal (macOS), Vulkan or DX12 (Linux, Windows), with the device rules of the command-line tool: `device: "auto"` runs models above ~100M parameters on a hardware GPU that holds them (software rasterizers such as llvmpipe are skipped; the model is sized against the GPU's memory before anything is uploaded), the CPU otherwise; `device: "gpu"` fails with `UNSUPPORTED_DEVICE` when there is no GPU;
392
+ - `quant: "auto"` decided against the machine's memory and the GPU's (measured with [sift](https://github.com/maxgfr/sift)), not the 4 GiB of WebAssembly;
393
+ - the converted-weight cache in the same file as the command-line tool (`<repo>/<sha>/quantized/<format>/weights.webslmq`), in the same cache directory, so `webslm pull --quant q8` and the package share it.
394
+
395
+ The API is the same (`load`, `ask`, `stream`, `loadModel`, sessions with `score`, `step`, `fork`, LoRA adapters, the AI SDK provider), and so are the results on the CPU: the quantized kernels are bit-identical across builds, so `q8` gives the WebAssembly engine's greedy tokens, and `f32` the `transformers` goldens (both checked in CI).
396
+
397
+ ```ts
398
+ const model = await loadModel("HuggingFaceTB/SmolLM2-360M-Instruct");
399
+ model.info().runtime; // "native" (or "wasm")
400
+ model.info().backend; // "GPU (native, Apple M5 (Metal))", "CPU (native, neon-i8mm, 10 threads)"...
401
+ ```
402
+
403
+ `backend` in the load options picks the engine: `"auto"` (the default) the native one when it is available and the source is a hub model, else WebAssembly, with the reason in `info().runtimeNote`; `"native"` fails with `UNSUPPORTED_DEVICE` when it cannot run; `"wasm"` keeps WebAssembly and downloads nothing. `WEBSLM_BACKEND=native|wasm|auto` sets the default for a whole process (to pin a deployment, or to make an unavailable native engine an error in CI). `files` and `fetch` sources always run on WebAssembly (the native engine reads the cache directory); `files` and `fetch` LoRA adapters work on both. The models run on threads of their own: the JavaScript thread never waits for a token, and several calls on one model interleave token by token. `threads` sizes the CPU pool (default: the available cores, capped by the cgroup CPU quota in a container); the first native load of the process decides it.
404
+
405
+ WebAssembly runs instead, and `info().runtimeNote` says why, when the native engine is not available: no build for the platform, offline mode (`WEBSLM_OFFLINE=1`) without the addon in the cache, a download that fails or takes more than 30 seconds, a checksum that does not match (the file is then discarded), or a package built from source (it has no manifest). The download goes to `https://github.com/maxgfr/webslm/releases/download/v<version>/`; `WEBSLM_NATIVE_URL` replaces that base (a mirror holding the same files), and behind a proxy, Node's `fetch` uses `HTTPS_PROXY` when `NODE_USE_ENV_PROXY=1` (Node 24; Bun reads it by itself). For an air-gapped or locked-down deployment, put the addon in the cache directory beforehand (`<cache>/native/<version>/webslm-node-<version>-<platform>.node`, the uncompressed release asset) or point `WEBSLM_NATIVE_PATH` at a `.node` file (`cargo xtask build-native --release` builds one into `target/native/<platform>/webslm.node`). Bun loads the addon through its Node-API support. Deno runs on WebAssembly under `"auto"`; `backend: "native"` loads the addon there with `--allow-ffi`. Browser bundles never download or load it.
406
+
355
407
  ## CPU builds and deterministic mode
356
408
 
357
409
  The package ships three WebAssembly builds of the engine and each worker picks the fastest one the environment supports (`selectWasmFlavour()`), unless `wasmFlavour` says otherwise:
@@ -360,7 +412,7 @@ The package ships three WebAssembly builds of the engine and each worker picks t
360
412
  - `"relaxed"`: SIMD128 and relaxed SIMD, one thread.
361
413
  - `"simd"`: SIMD128, one thread; runs wherever WebAssembly SIMD does.
362
414
 
363
- `model.info().cpu` reports `{ flavour, kernels, threads, deterministic }`, and `model.info().backend` a readable summary such as `"CPU (wasm, relaxed SIMD, 8 threads)"`. Each worker instantiates one build: the first model loaded in it decides.
415
+ `model.info().cpu` reports `{ flavour, kernels, threads, deterministic }` (`flavour: "native"` on the native engine), and `model.info().backend` a readable summary such as `"CPU (wasm, relaxed SIMD, 8 threads)"`. Each worker instantiates one build: the first model loaded in it decides.
364
416
 
365
417
  `deterministic: true` selects kernels whose results are bit-identical in every build and natively (the `webslm` command-line tool and the Rust crates on x86_64 and aarch64): same weights, prompt and options, same logits, whatever the browser, CPU or thread count. It gives up fused multiply-adds, which costs speed with `f32` weights only; quantized weights run the same kernels either way.
366
418
 
@@ -376,7 +428,7 @@ export default defineConfig({
376
428
  });
377
429
  ```
378
430
 
379
- Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.3.1/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
431
+ Server code that imports webslm must not be bundled: webslm runs from its own files in `node_modules` (Next.js: `serverExternalPackages: ["webslm"]`). Without a bundler, a page can import it from jsDelivr (`https://cdn.jsdelivr.net/npm/webslm@0.4.1/dist/index.js`); webslm starts its workers through same-origin `blob:` workers when its files come from another origin. Guides for Next.js, Vite, webpack, Node servers, Bun, Deno and CDNs, each with a tested example: <https://github.com/maxgfr/webslm#frameworks-bundlers-and-runtimes>.
380
432
 
381
433
  ## Errors
382
434
 
@@ -21,7 +21,7 @@
21
21
  import type { ProviderV4 } from "@ai-sdk/provider";
22
22
  import { WebslmLanguageModel, type WebslmModelSettings } from "./language-model.js";
23
23
  import { type WebslmEngine, type WebslmLoadOptions } from "./loader.js";
24
- export { CURATED_MODELS, type CuratedModel } from "../curated.js";
24
+ export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, type CheckpointTraits, type CuratedModel, type SamplingDefaults, type SamplingSet, } from "../curated.js";
25
25
  export { searchModels, type HubModel, type SearchModelsOptions } from "../hub.js";
26
26
  export { DEFAULT_MODEL } from "../simple.js";
27
27
  export type { LoadModelOptions, LoadProgress, ModelInfo } from "../types.js";
@@ -22,7 +22,7 @@ import { WebslmError } from "../errors.js";
22
22
  import { loadModel } from "../models.js";
23
23
  import { CALL_SETTING_KEYS, WebslmLanguageModel } from "./language-model.js";
24
24
  import { ModelSlot, pickLoadOptions, slotKey, } from "./loader.js";
25
- export { CURATED_MODELS } from "../curated.js";
25
+ export { CURATED_MODELS, curatedModel, RECOMMENDED_SAMPLING, recommendedSampling, } from "../curated.js";
26
26
  export { searchModels } from "../hub.js";
27
27
  export { DEFAULT_MODEL } from "../simple.js";
28
28
  export { WebslmLanguageModel, } from "./language-model.js";
@@ -2,10 +2,18 @@
2
2
  * Layout of cached checkpoints inside a {@link CacheStore}:
3
3
  *
4
4
  * ```text
5
- * {repo}/refs/{revision} commit sha a revision resolved to
6
- * {repo}/{sha}/.webslm.json manifest: files, sizes, hashes, completeness
7
- * {repo}/{sha}/{file} checkpoint files
5
+ * {repo}/refs/{revision} commit sha a revision resolved to
6
+ * {repo}/{sha}/.webslm.json manifest: files, sizes, hashes, completeness
7
+ * {repo}/{sha}/.webslm-manifest.json the command-line tool's manifest (complete snapshots)
8
+ * {repo}/{sha}/{file} checkpoint files
9
+ * {repo}/{sha}/quantized/{format}/weights.webslmq converted weights
8
10
  * ```
11
+ *
12
+ * In Node this is the command-line tool's cache layout
13
+ * (crates/webslm-hub/src/cache.rs) in the same directory, so a model pulled
14
+ * by `webslm pull` loads without a download and the reverse: each side reads
15
+ * the other's manifest, and a completed download in a directory store writes
16
+ * the command-line tool's manifest too.
9
17
  */
10
18
  import { type CacheStore } from "./store.js";
11
19
  /** Manifest of one cached revision. */
@@ -49,16 +57,37 @@ export interface CachedModel {
49
57
  readonly storage: string;
50
58
  }
51
59
  export declare const MANIFEST_FILE = ".webslm.json";
60
+ /** The command-line tool's manifest of a complete snapshot (`MANIFEST_FILE` in crates/webslm-hub/src/cache.rs). */
61
+ export declare const CLI_MANIFEST_FILE = ".webslm-manifest.json";
52
62
  /** Checks a repository id and returns it normalized. */
53
63
  export declare function checkRepoId(repo: string): string;
54
64
  export declare function refPath(repo: string, revision: string): string;
55
65
  export declare function revisionDir(repo: string, sha: string): string;
56
66
  export declare function filePath(repo: string, sha: string, file: string): string;
67
+ /**
68
+ * The converted weights of a snapshot in load format `quant`:
69
+ * `{repo}/{sha}/quantized/{format}/weights.webslmq`, the command-line tool's
70
+ * layout (and file format).
71
+ */
72
+ export declare function weightCachePath(repo: string, sha: string, quant: string): string;
57
73
  export declare function manifestPath(repo: string, sha: string): string;
74
+ export declare function cliManifestPath(repo: string, sha: string): string;
58
75
  export declare function readRef(store: CacheStore, repo: string, revision: string): Promise<string | undefined>;
59
76
  export declare function writeRef(store: CacheStore, repo: string, revision: string, sha: string): Promise<void>;
60
77
  export declare function readManifest(store: CacheStore, repo: string, sha: string): Promise<CacheManifest | undefined>;
61
78
  export declare function writeManifest(store: CacheStore, manifest: CacheManifest): Promise<void>;
79
+ /**
80
+ * The snapshot `repo@sha` the command-line tool pulled, as a complete
81
+ * {@link CacheManifest}: `undefined` without its manifest or when a file of
82
+ * it is missing or has another size.
83
+ */
84
+ export declare function readCliManifest(store: CacheStore, repo: string, sha: string): Promise<CacheManifest | undefined>;
85
+ /**
86
+ * Writes the command-line tool's manifest of a complete snapshot, unless it
87
+ * has one, so that `webslm` (the command-line tool) uses the files without
88
+ * pulling them again.
89
+ */
90
+ export declare function writeCliManifest(store: CacheStore, manifest: CacheManifest, revision: string): Promise<void>;
62
91
  /** Every cached repository of `store`. */
63
92
  export declare function listCachedModelsIn(store: CacheStore): Promise<CachedModel[]>;
64
93
  /** Removes a cached repository (every revision) from `store`. */
@@ -2,13 +2,23 @@
2
2
  * Layout of cached checkpoints inside a {@link CacheStore}:
3
3
  *
4
4
  * ```text
5
- * {repo}/refs/{revision} commit sha a revision resolved to
6
- * {repo}/{sha}/.webslm.json manifest: files, sizes, hashes, completeness
7
- * {repo}/{sha}/{file} checkpoint files
5
+ * {repo}/refs/{revision} commit sha a revision resolved to
6
+ * {repo}/{sha}/.webslm.json manifest: files, sizes, hashes, completeness
7
+ * {repo}/{sha}/.webslm-manifest.json the command-line tool's manifest (complete snapshots)
8
+ * {repo}/{sha}/{file} checkpoint files
9
+ * {repo}/{sha}/quantized/{format}/weights.webslmq converted weights
8
10
  * ```
11
+ *
12
+ * In Node this is the command-line tool's cache layout
13
+ * (crates/webslm-hub/src/cache.rs) in the same directory, so a model pulled
14
+ * by `webslm pull` loads without a download and the reverse: each side reads
15
+ * the other's manifest, and a completed download in a directory store writes
16
+ * the command-line tool's manifest too.
9
17
  */
10
18
  import { joinPath, readText, writeText } from "./store.js";
11
19
  export const MANIFEST_FILE = ".webslm.json";
20
+ /** The command-line tool's manifest of a complete snapshot (`MANIFEST_FILE` in crates/webslm-hub/src/cache.rs). */
21
+ export const CLI_MANIFEST_FILE = ".webslm-manifest.json";
12
22
  /** Checks a repository id and returns it normalized. */
13
23
  export function checkRepoId(repo) {
14
24
  const trimmed = repo.trim().replace(/^\/+|\/+$/g, "");
@@ -20,17 +30,39 @@ export function checkRepoId(repo) {
20
30
  export function refPath(repo, revision) {
21
31
  return joinPath(repo, "refs", encodeURIComponent(revision));
22
32
  }
33
+ /** Where the command-line tool keeps a ref: one directory per `/` of the revision. */
34
+ function cliRefPath(repo, revision) {
35
+ return joinPath(repo, "refs", ...revision.split("/").map(encodeURIComponent));
36
+ }
23
37
  export function revisionDir(repo, sha) {
24
38
  return joinPath(repo, sha);
25
39
  }
26
40
  export function filePath(repo, sha, file) {
27
41
  return joinPath(repo, sha, file);
28
42
  }
43
+ /** Directory names of the weight formats, as the command-line tool names them. */
44
+ const FORMAT_DIRS = { q8: "q8_0", q4: "q4_0_16" };
45
+ /**
46
+ * The converted weights of a snapshot in load format `quant`:
47
+ * `{repo}/{sha}/quantized/{format}/weights.webslmq`, the command-line tool's
48
+ * layout (and file format).
49
+ */
50
+ export function weightCachePath(repo, sha, quant) {
51
+ const format = FORMAT_DIRS[quant] ?? quant;
52
+ return joinPath(repo, sha, "quantized", encodeURIComponent(format), "weights.webslmq");
53
+ }
29
54
  export function manifestPath(repo, sha) {
30
55
  return joinPath(repo, sha, MANIFEST_FILE);
31
56
  }
57
+ export function cliManifestPath(repo, sha) {
58
+ return joinPath(repo, sha, CLI_MANIFEST_FILE);
59
+ }
32
60
  export async function readRef(store, repo, revision) {
33
- const sha = (await readText(store, refPath(repo, revision)))?.trim();
61
+ let text = await readText(store, refPath(repo, revision));
62
+ // A branch with `/` pulled by the command-line tool.
63
+ if (text === undefined && revision.includes("/"))
64
+ text = await readText(store, cliRefPath(repo, revision));
65
+ const sha = text?.trim();
34
66
  return sha === undefined || sha === "" ? undefined : sha;
35
67
  }
36
68
  export async function writeRef(store, repo, revision, sha) {
@@ -51,21 +83,84 @@ export async function readManifest(store, repo, sha) {
51
83
  export async function writeManifest(store, manifest) {
52
84
  await writeText(store, manifestPath(manifest.repo, manifest.sha), JSON.stringify(manifest, null, 2));
53
85
  }
86
+ /**
87
+ * The snapshot `repo@sha` the command-line tool pulled, as a complete
88
+ * {@link CacheManifest}: `undefined` without its manifest or when a file of
89
+ * it is missing or has another size.
90
+ */
91
+ export async function readCliManifest(store, repo, sha) {
92
+ const text = await readText(store, cliManifestPath(repo, sha));
93
+ if (text === undefined)
94
+ return undefined;
95
+ let parsed;
96
+ try {
97
+ parsed = JSON.parse(text);
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ if (parsed?.sha !== sha || !Array.isArray(parsed.files))
103
+ return undefined;
104
+ const files = {};
105
+ for (const file of parsed.files) {
106
+ if (typeof file?.name !== "string")
107
+ return undefined;
108
+ let size;
109
+ try {
110
+ size = await store.size(filePath(repo, sha, file.name));
111
+ }
112
+ catch {
113
+ return undefined; // a name the store refuses
114
+ }
115
+ if (size === undefined || (typeof file.size === "number" && file.size !== size))
116
+ return undefined;
117
+ files[file.name] =
118
+ typeof file.sha256 === "string" ? { size, sha256: file.sha256, complete: true } : { size, complete: true };
119
+ }
120
+ const created = typeof parsed.created_unix === "number" ? parsed.created_unix * 1000 : 0;
121
+ return { version: 1, repo, sha, files, complete: true, updatedAt: new Date(created).toISOString() };
122
+ }
123
+ /**
124
+ * Writes the command-line tool's manifest of a complete snapshot, unless it
125
+ * has one, so that `webslm` (the command-line tool) uses the files without
126
+ * pulling them again.
127
+ */
128
+ export async function writeCliManifest(store, manifest, revision) {
129
+ const path = cliManifestPath(manifest.repo, manifest.sha);
130
+ if (!manifest.complete || (await store.size(path)) !== undefined)
131
+ return;
132
+ const cli = {
133
+ repo: manifest.repo,
134
+ revision,
135
+ sha: manifest.sha,
136
+ files: Object.entries(manifest.files).map(([name, info]) => ({
137
+ name,
138
+ size: info.size,
139
+ sha256: info.sha256 ?? null,
140
+ blob_id: null,
141
+ })),
142
+ created_unix: Math.floor(Date.now() / 1000),
143
+ };
144
+ await writeText(store, path, JSON.stringify(cli, null, 2));
145
+ }
54
146
  /** Every cached repository of `store`. */
55
147
  export async function listCachedModelsIn(store) {
56
148
  const entries = await store.list("");
57
- const manifests = entries.filter((e) => e.path.endsWith(`/${MANIFEST_FILE}`));
149
+ const isManifest = (path) => path.endsWith(`/${MANIFEST_FILE}`) || path.endsWith(`/${CLI_MANIFEST_FILE}`);
150
+ // Revisions with either manifest (ours, or the command-line tool's), once each.
151
+ const revisionDirs = new Set(entries.filter((e) => isManifest(e.path)).map((e) => e.path.slice(0, e.path.lastIndexOf("/"))));
58
152
  const byRepo = new Map();
59
- for (const entry of manifests) {
60
- const parts = entry.path.split("/");
61
- const sha = parts[parts.length - 2];
62
- const repo = parts.slice(0, -2).join("/");
153
+ for (const revision of [...revisionDirs].sort()) {
154
+ const parts = revision.split("/");
155
+ const sha = parts[parts.length - 1];
156
+ const repo = parts.slice(0, -1).join("/");
63
157
  if (sha === undefined || repo === "")
64
158
  continue;
65
159
  const manifest = await readManifest(store, repo, sha);
160
+ const complete = manifest?.complete === true || (await readCliManifest(store, repo, sha)) !== undefined;
66
161
  const dir = `${revisionDir(repo, sha)}/`;
67
162
  const files = entries
68
- .filter((e) => e.path.startsWith(dir) && !e.path.endsWith(`/${MANIFEST_FILE}`))
163
+ .filter((e) => e.path.startsWith(dir) && !isManifest(e.path))
69
164
  .map((e) => ({ name: e.path.slice(dir.length), sizeBytes: e.size }));
70
165
  const refs = [];
71
166
  const refDir = `${repo}/refs/`;
@@ -80,7 +175,7 @@ export async function listCachedModelsIn(store) {
80
175
  refs,
81
176
  files,
82
177
  sizeBytes: files.reduce((n, f) => n + f.sizeBytes, 0),
83
- complete: manifest?.complete === true,
178
+ complete,
84
179
  });
85
180
  byRepo.set(repo, revisions);
86
181
  }
@@ -1,9 +1,31 @@
1
1
  /**
2
- * Directory store for Node.js: `WEBSLM_CACHE_DIR`, or `~/.cache/webslm`
3
- * (`$XDG_CACHE_HOME/webslm` when set).
2
+ * Directory store for Node.js, in the command-line tool's cache directory
3
+ * (see {@link resolveCacheDir}).
4
4
  */
5
5
  import { type CacheEntry, type CacheStore, type CacheWriter } from "./store.js";
6
- /** The default cache directory in Node. */
6
+ interface PathModule {
7
+ join(...parts: string[]): string;
8
+ dirname(path: string): string;
9
+ isAbsolute(path: string): boolean;
10
+ }
11
+ /** What the default cache directory depends on. */
12
+ export interface CacheDirEnvironment {
13
+ /** `process.platform`: `"darwin"`, `"win32"`, `"linux"`... */
14
+ readonly platform: string;
15
+ readonly env: Readonly<Record<string, string | undefined>>;
16
+ /** The home directory; `undefined` or `""` when unknown. */
17
+ readonly homedir: string | undefined;
18
+ }
19
+ /**
20
+ * The cache directory, by the command-line tool's rules (`Cache::from_env`
21
+ * in crates/webslm-hub/src/cache.rs), so that both share one cache:
22
+ * `$WEBSLM_CACHE_DIR`, else `~/Library/Caches/webslm` on macOS,
23
+ * `%LOCALAPPDATA%\webslm\cache` on Windows, `$XDG_CACHE_HOME/webslm` (an
24
+ * absolute `XDG_CACHE_HOME`) or `~/.cache/webslm` elsewhere. `path` is the
25
+ * platform's path module (`node:path`, or its `win32`/`posix` flavour).
26
+ */
27
+ export declare function resolveCacheDir(environment: CacheDirEnvironment, path: Pick<PathModule, "join" | "isAbsolute">): string;
28
+ /** The default cache directory in Node (see {@link resolveCacheDir}). */
7
29
  export declare function defaultCacheDir(): Promise<string>;
8
30
  export declare class NodeFsStore implements CacheStore {
9
31
  #private;
@@ -19,3 +41,4 @@ export declare class NodeFsStore implements CacheStore {
19
41
  list(prefix: string): Promise<CacheEntry[]>;
20
42
  remove(path: string): Promise<void>;
21
43
  }
44
+ export {};
@@ -1,20 +1,54 @@
1
1
  /**
2
- * Directory store for Node.js: `WEBSLM_CACHE_DIR`, or `~/.cache/webslm`
3
- * (`$XDG_CACHE_HOME/webslm` when set).
2
+ * Directory store for Node.js, in the command-line tool's cache directory
3
+ * (see {@link resolveCacheDir}).
4
4
  */
5
5
  import { importNode } from "../runtime.js";
6
6
  import { pathSegments, resolveRange, } from "./store.js";
7
- /** The default cache directory in Node. */
7
+ /**
8
+ * The cache directory, by the command-line tool's rules (`Cache::from_env`
9
+ * in crates/webslm-hub/src/cache.rs), so that both share one cache:
10
+ * `$WEBSLM_CACHE_DIR`, else `~/Library/Caches/webslm` on macOS,
11
+ * `%LOCALAPPDATA%\webslm\cache` on Windows, `$XDG_CACHE_HOME/webslm` (an
12
+ * absolute `XDG_CACHE_HOME`) or `~/.cache/webslm` elsewhere. `path` is the
13
+ * platform's path module (`node:path`, or its `win32`/`posix` flavour).
14
+ */
15
+ export function resolveCacheDir(environment, path) {
16
+ const { platform, env } = environment;
17
+ const custom = env.WEBSLM_CACHE_DIR;
18
+ if (custom)
19
+ return custom;
20
+ const home = environment.homedir || undefined;
21
+ const noHome = () => new Error("cannot find the home directory; set WEBSLM_CACHE_DIR");
22
+ if (platform === "darwin") {
23
+ if (home === undefined)
24
+ throw noHome();
25
+ return path.join(home, "Library", "Caches", "webslm");
26
+ }
27
+ const localAppData = env.LOCALAPPDATA;
28
+ if (platform === "win32" && localAppData)
29
+ return path.join(localAppData, "webslm", "cache");
30
+ const xdg = env.XDG_CACHE_HOME;
31
+ if (xdg && path.isAbsolute(xdg))
32
+ return path.join(xdg, "webslm");
33
+ if (home === undefined)
34
+ throw noHome();
35
+ return path.join(home, ".cache", "webslm");
36
+ }
37
+ /** The default cache directory in Node (see {@link resolveCacheDir}). */
8
38
  export async function defaultCacheDir() {
9
- const env = globalThis.process
10
- ?.env;
39
+ const env = globalThis.process?.env ?? {};
11
40
  const path = await importNode("path");
12
- if (env?.WEBSLM_CACHE_DIR)
41
+ if (env.WEBSLM_CACHE_DIR)
13
42
  return env.WEBSLM_CACHE_DIR;
14
- if (env?.XDG_CACHE_HOME)
15
- return path.join(env.XDG_CACHE_HOME, "webslm");
16
43
  const os = await importNode("os");
17
- return path.join(os.homedir(), ".cache", "webslm");
44
+ let homedir;
45
+ try {
46
+ homedir = os.homedir();
47
+ }
48
+ catch {
49
+ homedir = undefined;
50
+ }
51
+ return resolveCacheDir({ platform: os.platform(), env, homedir }, path);
18
52
  }
19
53
  export class NodeFsStore {
20
54
  kind = "fs";
@@ -2,7 +2,7 @@
2
2
  import { type CachedModel } from "./cache/models.js";
3
3
  export type { CachedModel, CachedRevision } from "./cache/models.js";
4
4
  export interface CacheOptions {
5
- /** Cache directory in Node (default `WEBSLM_CACHE_DIR` or `~/.cache/webslm`). */
5
+ /** Cache directory in Node (default `WEBSLM_CACHE_DIR`, else the command-line tool's: `~/Library/Caches/webslm` on macOS, `~/.cache/webslm` on Linux). */
6
6
  readonly cacheDir?: string;
7
7
  }
8
8
  /** Models downloaded into the cache (OPFS and Cache API in browsers, the cache directory in Node). */
package/dist/curated.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  /** A short list of checkpoints known to run well, for model pickers. */
2
+ import { type CheckpointTraits, type SamplingDefaults, type SamplingSet } from "./recommended-sampling.js";
3
+ export type { CheckpointTraits, SamplingDefaults, SamplingSet } from "./recommended-sampling.js";
4
+ export { RECOMMENDED_SAMPLING } from "./recommended-sampling.js";
2
5
  /** A checkpoint of {@link CURATED_MODELS}. */
3
6
  export interface CuratedModel {
4
7
  /** Hugging Face repository id, to pass to `load`, `loadModel` or `webslm()`. */
@@ -13,10 +16,37 @@ export interface CuratedModel {
13
16
  readonly note: string;
14
17
  /** Whether it can reason before answering (`think`, the AI SDK's `reasoning`). */
15
18
  readonly thinking?: boolean;
19
+ /** Whether it reasons when `think` (the template's `enable_thinking`) is not set. */
20
+ readonly thinksByDefault?: boolean;
21
+ /**
22
+ * The sampling its model card recommends, applied by default to every
23
+ * generation of this repository (see {@link recommendedSampling}):
24
+ * `answer` when it answers directly, `thinking` when it reasons first.
25
+ */
26
+ readonly sampling: SamplingSet;
16
27
  }
17
28
  /**
18
29
  * Checkpoints validated against `transformers`, smallest first: the first
19
30
  * ones are quick on a laptop CPU, the largest (LFM3 1.7B) wants WebGPU. Any supported repository works too: see
20
- * `searchModels` and `checkModel` for the others.
31
+ * `searchModels` and `checkModel` for the others. Larger models answer
32
+ * better: the 135M and 360M SmolLM2 checkpoints lose track of a
33
+ * conversation after a turn or two, while LFM2.5 350M and the Qwen
34
+ * checkpoints recall what was said earlier.
21
35
  */
22
36
  export declare const CURATED_MODELS: readonly CuratedModel[];
37
+ /** The entry of {@link CURATED_MODELS} for a repository id (case-insensitive), if any. */
38
+ export declare function curatedModel(repo: string | undefined): CuratedModel | undefined;
39
+ /**
40
+ * The sampling a model card recommends for a checkpoint, with or without
41
+ * reasoning (`think` unset: the model's default), or `undefined` when there
42
+ * is none (its `generation_config.json` then applies). `checkpoint` is a
43
+ * repository id, or what identifies a checkpoint: the curated repositories
44
+ * use their card's settings whatever their `generation_config.json` says;
45
+ * other checkpoints of the same families (`model_type` `qwen3`, `qwen3_5`,
46
+ * `lfm2`, `lfm3`) use their family's when their `generation_config.json`
47
+ * does not ask for sampling. The table is the Rust engine's, so the
48
+ * command-line tool and the server pick the same settings. Generations
49
+ * start from it: options a call sets override the matching fields, and
50
+ * `temperature: 0` (greedy decoding) turns it off.
51
+ */
52
+ export declare function recommendedSampling(checkpoint: string | CheckpointTraits | undefined, think?: boolean): SamplingDefaults | undefined;