webslm 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +373 -2
  3. package/dist/ai-sdk/index.d.ts +81 -0
  4. package/dist/ai-sdk/index.js +90 -0
  5. package/dist/ai-sdk/language-model.d.ts +77 -0
  6. package/dist/ai-sdk/language-model.js +422 -0
  7. package/dist/ai-sdk/loader.d.ts +54 -0
  8. package/dist/ai-sdk/loader.js +170 -0
  9. package/dist/ai-sdk/output.d.ts +43 -0
  10. package/dist/ai-sdk/output.js +152 -0
  11. package/dist/ai-sdk/prompt.d.ts +21 -0
  12. package/dist/ai-sdk/prompt.js +111 -0
  13. package/dist/async-queue.d.ts +22 -0
  14. package/dist/async-queue.js +70 -0
  15. package/dist/cache/cache-api.d.ts +29 -0
  16. package/dist/cache/cache-api.js +115 -0
  17. package/dist/cache/index.d.ts +21 -0
  18. package/dist/cache/index.js +42 -0
  19. package/dist/cache/memory.d.ts +12 -0
  20. package/dist/cache/memory.js +61 -0
  21. package/dist/cache/models.d.ts +67 -0
  22. package/dist/cache/models.js +107 -0
  23. package/dist/cache/node-fs.d.ts +21 -0
  24. package/dist/cache/node-fs.js +147 -0
  25. package/dist/cache/opfs.d.ts +69 -0
  26. package/dist/cache/opfs.js +181 -0
  27. package/dist/cache/store.d.ts +53 -0
  28. package/dist/cache/store.js +64 -0
  29. package/dist/cache-management.d.ts +23 -0
  30. package/dist/cache-management.js +58 -0
  31. package/dist/capabilities.d.ts +67 -0
  32. package/dist/capabilities.js +55 -0
  33. package/dist/client.d.ts +61 -0
  34. package/dist/client.js +256 -0
  35. package/dist/curated.d.ts +22 -0
  36. package/dist/curated.js +53 -0
  37. package/dist/download.d.ts +51 -0
  38. package/dist/download.js +289 -0
  39. package/dist/engine.d.ts +54 -0
  40. package/dist/engine.js +510 -0
  41. package/dist/errors.d.ts +81 -0
  42. package/dist/errors.js +89 -0
  43. package/dist/hub.d.ts +185 -0
  44. package/dist/hub.js +409 -0
  45. package/dist/index.d.ts +37 -0
  46. package/dist/index.js +41 -0
  47. package/dist/models.d.ts +225 -0
  48. package/dist/models.js +730 -0
  49. package/dist/node-pool-worker.d.ts +6 -0
  50. package/dist/node-pool-worker.js +32 -0
  51. package/dist/node-web-worker.d.ts +23 -0
  52. package/dist/node-web-worker.js +84 -0
  53. package/dist/node-worker.d.ts +2 -0
  54. package/dist/node-worker.js +9 -0
  55. package/dist/pool-worker.d.ts +36 -0
  56. package/dist/pool-worker.js +30 -0
  57. package/dist/pool.d.ts +17 -0
  58. package/dist/pool.js +41 -0
  59. package/dist/protocol.d.ts +246 -0
  60. package/dist/protocol.js +19 -0
  61. package/dist/runtime.d.ts +21 -0
  62. package/dist/runtime.js +53 -0
  63. package/dist/safetensors.d.ts +20 -0
  64. package/dist/safetensors.js +2 -0
  65. package/dist/simple.d.ts +310 -0
  66. package/dist/simple.js +553 -0
  67. package/dist/types.d.ts +412 -0
  68. package/dist/types.js +2 -0
  69. package/dist/wasm-flavour.d.ts +85 -0
  70. package/dist/wasm-flavour.js +169 -0
  71. package/dist/wasm.d.ts +34 -0
  72. package/dist/wasm.js +38 -0
  73. package/dist/worker.d.ts +6 -0
  74. package/dist/worker.js +11 -0
  75. package/package.json +92 -3
  76. package/wasm/relaxed/webslm_wasm.d.ts +325 -0
  77. package/wasm/relaxed/webslm_wasm.js +1899 -0
  78. package/wasm/relaxed/webslm_wasm_bg.wasm +0 -0
  79. package/wasm/relaxed/webslm_wasm_bg.wasm.d.ts +56 -0
  80. package/wasm/simd/webslm_wasm.d.ts +325 -0
  81. package/wasm/simd/webslm_wasm.js +1899 -0
  82. package/wasm/simd/webslm_wasm_bg.wasm +0 -0
  83. package/wasm/simd/webslm_wasm_bg.wasm.d.ts +56 -0
  84. package/wasm/threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +108 -0
  85. package/wasm/threads/webslm_wasm.d.ts +357 -0
  86. package/wasm/threads/webslm_wasm.js +2100 -0
  87. package/wasm/threads/webslm_wasm_bg.wasm +0 -0
  88. package/wasm/threads/webslm_wasm_bg.wasm.d.ts +66 -0
package/dist/models.js ADDED
@@ -0,0 +1,730 @@
1
+ /** Public model API: {@link loadModel}, {@link Model} and {@link Session}. */
2
+ import { AsyncQueue } from "./async-queue.js";
3
+ import { EngineClient } from "./client.js";
4
+ import { WebslmError, abortError, isAborted, toWebslmError } from "./errors.js";
5
+ import { isNode } from "./runtime.js";
6
+ const QUANTS = ["q8", "q4", "f32"];
7
+ /**
8
+ * An engine (a worker, or the calling thread) that several models can share
9
+ * (see {@link LoadModelOptions.engine}): one WebAssembly instance, its memory
10
+ * and thread pool, for a small helper model next to a larger one.
11
+ */
12
+ export class EngineHandle {
13
+ /** @internal */
14
+ client;
15
+ #terminated = false;
16
+ /** @internal */
17
+ constructor(client) {
18
+ this.client = client;
19
+ }
20
+ /** Stops the engine: every model loaded in it is unloaded. */
21
+ async terminate() {
22
+ if (this.#terminated)
23
+ return;
24
+ this.#terminated = true;
25
+ await this.client.terminate();
26
+ }
27
+ }
28
+ /**
29
+ * Starts an engine to share between models: pass it as `engine` to
30
+ * {@link loadModel}. Unloading a model then frees it but keeps the engine;
31
+ * {@link EngineHandle.terminate} stops it.
32
+ *
33
+ * ```ts
34
+ * const engine = await createEngine();
35
+ * const small = await loadModel("HuggingFaceTB/SmolLM2-135M-Instruct", { engine });
36
+ * const large = await loadModel("Qwen/Qwen3-0.6B", { engine });
37
+ * ```
38
+ */
39
+ export async function createEngine(options = {}) {
40
+ return new EngineHandle(await EngineClient.start(options.worker === false ? { worker: false } : {}));
41
+ }
42
+ /**
43
+ * Validates `device` (default `"auto"`). The engine decides what actually
44
+ * runs: `"auto"` is WebGPU for models above ~100M parameters when an adapter
45
+ * is available, the CPU otherwise; `"webgpu"` falls back to the CPU (with
46
+ * {@link ModelInfo.deviceNote} saying why) when no GPU device can be created.
47
+ */
48
+ export function resolveDevice(device) {
49
+ switch (device ?? "auto") {
50
+ case "auto":
51
+ return "auto";
52
+ case "cpu":
53
+ return "cpu";
54
+ case "webgpu":
55
+ return "webgpu";
56
+ default:
57
+ throw new WebslmError("INVALID_ARGUMENT", `unknown device "${String(device)}"`);
58
+ }
59
+ }
60
+ /** Checks a source and turns a repository id string into a hub source. */
61
+ export function normalizeSource(source, revision) {
62
+ if (typeof source === "string") {
63
+ const repo = source.trim();
64
+ if (repo === "")
65
+ throw new WebslmError("INVALID_ARGUMENT", "the repository id is empty");
66
+ return { kind: "hub", repo, ...(revision === undefined ? {} : { revision }) };
67
+ }
68
+ if (typeof source !== "object" || source === null) {
69
+ throw new WebslmError("INVALID_ARGUMENT", "a model source must be a repository id or an object");
70
+ }
71
+ const keys = ["hub", "files", "fetch"].filter((k) => k in source);
72
+ if (keys.length !== 1) {
73
+ throw new WebslmError("INVALID_ARGUMENT", "a model source must have exactly one of `hub`, `files` or `fetch`");
74
+ }
75
+ if ("hub" in source) {
76
+ if (typeof source.hub !== "string" || source.hub.trim() === "") {
77
+ throw new WebslmError("INVALID_ARGUMENT", "`hub` must be a repository id");
78
+ }
79
+ const rev = source.revision ?? revision;
80
+ return {
81
+ kind: "hub",
82
+ repo: source.hub.trim(),
83
+ ...(rev === undefined ? {} : { revision: rev }),
84
+ ...(source.hubUrl === undefined ? {} : { hubUrl: source.hubUrl }),
85
+ };
86
+ }
87
+ if ("files" in source) {
88
+ const files = source.files;
89
+ if (typeof files !== "object" || files === null) {
90
+ throw new WebslmError("INVALID_ARGUMENT", "`files` must map file names to bytes");
91
+ }
92
+ for (const [name, data] of Object.entries(files)) {
93
+ if (!(data instanceof Blob || data instanceof ArrayBuffer || data instanceof Uint8Array)) {
94
+ throw new WebslmError("INVALID_ARGUMENT", `file "${name}" must be a Blob, an ArrayBuffer or a Uint8Array`);
95
+ }
96
+ }
97
+ if (!("config.json" in files)) {
98
+ throw new WebslmError("INVALID_ARGUMENT", "`files` must include config.json");
99
+ }
100
+ return { kind: "files", files };
101
+ }
102
+ if (typeof source.fetch !== "function") {
103
+ throw new WebslmError("INVALID_ARGUMENT", "`fetch` must be a function");
104
+ }
105
+ return { kind: "fetch", fetch: source.fetch };
106
+ }
107
+ /**
108
+ * Checks a LoRA adapter source: like {@link normalizeSource}, but `files`
109
+ * must hold `adapter_config.json` and `adapter_model.safetensors`.
110
+ */
111
+ export function normalizeAdapterSource(source, revision) {
112
+ if (typeof source === "object" && source !== null && "files" in source) {
113
+ const files = source.files;
114
+ if (typeof files !== "object" || files === null) {
115
+ throw new WebslmError("INVALID_ARGUMENT", "`files` must map file names to bytes");
116
+ }
117
+ for (const name of ["adapter_config.json", "adapter_model.safetensors"]) {
118
+ if (!(name in files))
119
+ throw new WebslmError("INVALID_ARGUMENT", `adapter \`files\` must include ${name}`);
120
+ }
121
+ // Reuse the byte checks, which require a config.json.
122
+ normalizeSource({ files: { ...files, "config.json": new Uint8Array() } });
123
+ return { kind: "files", files };
124
+ }
125
+ return normalizeSource(source, revision);
126
+ }
127
+ /** The form of a normalized source posted to the engine. */
128
+ function toWire(normalized, token) {
129
+ switch (normalized.kind) {
130
+ case "hub":
131
+ return {
132
+ kind: "hub",
133
+ repo: normalized.repo,
134
+ ...(normalized.revision === undefined ? {} : { revision: normalized.revision }),
135
+ ...(normalized.hubUrl === undefined ? {} : { hubUrl: normalized.hubUrl }),
136
+ ...(token === undefined ? {} : { token }),
137
+ };
138
+ case "files":
139
+ return { kind: "files", files: normalized.files };
140
+ case "fetch":
141
+ return { kind: "fetch" };
142
+ }
143
+ }
144
+ function checkScale(scale) {
145
+ if (scale !== undefined && (typeof scale !== "number" || !Number.isFinite(scale))) {
146
+ throw new WebslmError("INVALID_ARGUMENT", "the adapter scale must be a finite number");
147
+ }
148
+ }
149
+ let persistRequested = false;
150
+ /** Asks the browser to keep the cache under storage pressure (once per page). */
151
+ function requestPersistentStorage() {
152
+ if (persistRequested)
153
+ return;
154
+ persistRequested = true;
155
+ const storage = globalThis
156
+ .navigator?.storage;
157
+ storage?.persist?.().catch(() => { });
158
+ }
159
+ /**
160
+ * Loads a model from the Hugging Face Hub, local files or a custom store.
161
+ *
162
+ * ```ts
163
+ * const model = await loadModel("HuggingFaceTB/SmolLM2-135M-Instruct", {
164
+ * onProgress: (p) => console.log(p.phase, p.overallLoadedBytes, p.overallTotalBytes),
165
+ * });
166
+ * for await (const delta of model.chat([{ role: "user", content: "Hi!" }])) console.log(delta);
167
+ * ```
168
+ *
169
+ * Hub checkpoints are downloaded once into the cache (OPFS in browsers,
170
+ * `~/.cache/webslm` in Node) and read from it afterwards, without network.
171
+ */
172
+ export async function loadModel(source, options = {}) {
173
+ const device = resolveDevice(options.device);
174
+ const quant = options.quant ?? "q8";
175
+ if (!QUANTS.includes(quant)) {
176
+ throw new WebslmError("INVALID_ARGUMENT", `quant must be one of ${QUANTS.join(", ")}`);
177
+ }
178
+ const normalized = normalizeSource(source, options.revision);
179
+ const adapter = options.adapter === undefined ? undefined : normalizeAdapterSource(options.adapter);
180
+ checkScale(options.adapterScale);
181
+ if (isAborted(options.signal))
182
+ throw abortError(options.signal);
183
+ if (normalized.kind === "hub" && !isNode())
184
+ requestPersistentStorage();
185
+ const shared = options.engine;
186
+ if (shared !== undefined && !(shared instanceof EngineHandle)) {
187
+ throw new WebslmError("INVALID_ARGUMENT", "`engine` must come from createEngine()");
188
+ }
189
+ const client = shared?.client ?? (await EngineClient.start(options.worker === false ? { worker: false } : {}));
190
+ const wire = toWire(normalized, options.token);
191
+ try {
192
+ const result = await client.request({
193
+ type: "load",
194
+ source: wire,
195
+ ...(adapter === undefined ? {} : { adapter: toWire(adapter, options.token) }),
196
+ options: {
197
+ quant,
198
+ device,
199
+ ...(options.adapterScale === undefined ? {} : { adapterScale: options.adapterScale }),
200
+ ...(options.contextLength === undefined ? {} : { contextLength: options.contextLength }),
201
+ ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
202
+ ...(options.deterministic === true ? { deterministic: true } : {}),
203
+ ...(options.activations === undefined ? {} : { activations: options.activations }),
204
+ ...(options.wasmFlavour === undefined ? {} : { wasmFlavour: options.wasmFlavour }),
205
+ ...(options.threads === undefined ? {} : { threads: options.threads }),
206
+ },
207
+ }, {
208
+ ...(options.onProgress === undefined ? {} : { onProgress: options.onProgress }),
209
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
210
+ ...(normalized.kind === "fetch" ? { onRead: normalized.fetch } : {}),
211
+ ...(adapter?.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
212
+ });
213
+ return new Model(client, result.model, result.info, {
214
+ ...(normalized.kind === "fetch" ? { fetch: normalized.fetch } : {}),
215
+ ...(options.cacheDir === undefined ? {} : { cacheDir: options.cacheDir }),
216
+ }, shared === undefined);
217
+ }
218
+ catch (error) {
219
+ if (shared === undefined)
220
+ await client.terminate().catch(() => { });
221
+ if (isAborted(options.signal))
222
+ throw abortError(options.signal);
223
+ throw toWebslmError(error);
224
+ }
225
+ }
226
+ function wireOptions(options) {
227
+ const out = {};
228
+ if (options.maxTokens !== undefined)
229
+ out.maxTokens = options.maxTokens;
230
+ if (options.temperature !== undefined)
231
+ out.temperature = options.temperature;
232
+ if (options.topK !== undefined)
233
+ out.topK = options.topK;
234
+ if (options.topP !== undefined)
235
+ out.topP = options.topP;
236
+ if (options.minP !== undefined)
237
+ out.minP = options.minP;
238
+ if (options.repetitionPenalty !== undefined)
239
+ out.repetitionPenalty = options.repetitionPenalty;
240
+ if (options.seed !== undefined)
241
+ out.seed = options.seed;
242
+ if (options.stop !== undefined)
243
+ out.stop = [...options.stop];
244
+ if (options.templateKwargs !== undefined)
245
+ out.templateKwargs = options.templateKwargs;
246
+ if (options.ignoreStopTokens !== undefined)
247
+ out.ignoreStopTokens = options.ignoreStopTokens;
248
+ if (options.addSpecialTokens !== undefined)
249
+ out.addSpecialTokens = options.addSpecialTokens;
250
+ if (options.presencePenalty !== undefined)
251
+ out.presencePenalty = options.presencePenalty;
252
+ if (options.frequencyPenalty !== undefined)
253
+ out.frequencyPenalty = options.frequencyPenalty;
254
+ if (options.stopTokens !== undefined)
255
+ out.stopTokenIds = [...options.stopTokens];
256
+ if (options.logprobs !== undefined && options.logprobs !== false) {
257
+ out.logprobs = options.logprobs === true ? 0 : options.logprobs;
258
+ }
259
+ if (options.json !== undefined)
260
+ out.json = options.json;
261
+ if (options.schema !== undefined)
262
+ out.schema = options.schema;
263
+ if (options.thinkingBudget !== undefined)
264
+ out.thinkingBudget = options.thinkingBudget;
265
+ if (options.loopDetection !== undefined)
266
+ out.loopDetection = options.loopDetection;
267
+ if (options.contextShift !== undefined)
268
+ out.contextShift = options.contextShift;
269
+ return out;
270
+ }
271
+ /** A `delta` message as a {@link GeneratedToken}. */
272
+ function generatedToken(delta) {
273
+ return {
274
+ id: delta.token,
275
+ text: delta.text,
276
+ forced: delta.forced === true,
277
+ ...(delta.logprob === undefined ? {} : { logprob: delta.logprob }),
278
+ ...(delta.topLogprobs === undefined
279
+ ? {}
280
+ : { topLogprobs: delta.topLogprobs.map(([id, logprob]) => ({ id, logprob })) }),
281
+ };
282
+ }
283
+ function checkMessages(messages) {
284
+ if (!Array.isArray(messages) || messages.length === 0) {
285
+ throw new WebslmError("INVALID_ARGUMENT", "messages must be a non-empty array");
286
+ }
287
+ return messages.map((m) => {
288
+ if (typeof m?.role !== "string" || typeof m.content !== "string") {
289
+ throw new WebslmError("INVALID_ARGUMENT", "each message needs a string `role` and `content`");
290
+ }
291
+ return { role: m.role, content: m.content };
292
+ });
293
+ }
294
+ /** Shared implementation of a streamed generation. */
295
+ class GenerationStream {
296
+ result;
297
+ #queue = new AsyncQueue();
298
+ #stop;
299
+ constructor(run, stop, signal, onToken) {
300
+ this.#stop = stop;
301
+ const onAbort = () => this.stop();
302
+ if (isAborted(signal))
303
+ queueMicrotask(onAbort);
304
+ signal?.addEventListener("abort", onAbort, { once: true });
305
+ // When `onToken` stops the generation, tokens the engine computed
306
+ // before it heard of it are dropped, so that the output ends exactly
307
+ // at that token.
308
+ let cut;
309
+ let text = "";
310
+ const tokens = [];
311
+ this.result = run((delta) => {
312
+ if (cut !== undefined)
313
+ return;
314
+ text += delta.text;
315
+ tokens.push(delta.token);
316
+ if (delta.text !== "")
317
+ this.#queue.push(delta.text);
318
+ if (onToken !== undefined && onToken(generatedToken(delta)) === false) {
319
+ cut = { text, tokens: [...tokens] };
320
+ this.stop();
321
+ }
322
+ })
323
+ .then((r) => {
324
+ const { length: _length, ...rest } = r;
325
+ void _length;
326
+ if (cut === undefined)
327
+ return rest;
328
+ return {
329
+ ...rest,
330
+ text: cut.text,
331
+ tokens: cut.tokens,
332
+ generatedTokens: cut.tokens.length,
333
+ finishReason: "aborted",
334
+ };
335
+ })
336
+ .catch((error) => {
337
+ const typed = toWebslmError(error);
338
+ this.#queue.fail(typed);
339
+ throw typed;
340
+ })
341
+ .finally(() => {
342
+ signal?.removeEventListener("abort", onAbort);
343
+ this.#queue.end();
344
+ });
345
+ // Iterating is enough: a caller that never awaits `result` must not see
346
+ // an unhandled rejection.
347
+ this.result.catch(() => { });
348
+ }
349
+ stop() {
350
+ if (!this.#queue.done)
351
+ this.#stop();
352
+ }
353
+ [Symbol.asyncIterator]() {
354
+ // `break` out of a for-await loop stops the generation.
355
+ return this.#queue.iterate(() => this.stop());
356
+ }
357
+ }
358
+ /** Operations shared by {@link Model} (its default session) and {@link Session}. */
359
+ class Conversation {
360
+ client;
361
+ modelId;
362
+ constructor(client, modelId) {
363
+ this.client = client;
364
+ this.modelId = modelId;
365
+ }
366
+ /**
367
+ * Answers a conversation, streaming text deltas. Earlier turns already in
368
+ * the session's cache are not recomputed. Stopping (`stop()`, `break`, or
369
+ * the signal) ends the stream normally with `finishReason: "aborted"`.
370
+ */
371
+ chat(messages, options = {}) {
372
+ const checked = checkMessages(messages);
373
+ return this.#stream({ type: "chat", messages: checked }, options);
374
+ }
375
+ /**
376
+ * Generates a whole answer. A string prompt is sent as a user message when
377
+ * the checkpoint has a chat template (pass `raw: true` to complete it as
378
+ * plain text); an array is a conversation. Rejects with `ABORTED` when the
379
+ * signal fires.
380
+ */
381
+ async generate(prompt, options = {}) {
382
+ let stream;
383
+ if (typeof prompt !== "string")
384
+ stream = this.chat(prompt, options);
385
+ else if (options.raw === true || !this.hasChatTemplate) {
386
+ stream = this.#stream({ type: "generate", prompt }, options);
387
+ }
388
+ else {
389
+ stream = this.chat([{ role: "user", content: prompt }], options);
390
+ }
391
+ let text = "";
392
+ for await (const delta of stream) {
393
+ text += delta;
394
+ options.onDelta?.(delta);
395
+ }
396
+ const result = await stream.result;
397
+ if (result.finishReason === "aborted" && isAborted(options.signal)) {
398
+ throw abortError(options.signal);
399
+ }
400
+ return text;
401
+ }
402
+ #stream(body, generateOptions) {
403
+ const options = wireOptions(generateOptions);
404
+ const { onPrefill } = generateOptions;
405
+ const session = this.sessionId === undefined ? {} : { session: this.sessionId };
406
+ // Stopping aborts the request; the engine then ends the generation
407
+ // normally, with `finishReason: "aborted"`.
408
+ const controller = new AbortController();
409
+ return new GenerationStream(async (onDelta) => {
410
+ const result = await this.client.request({ ...body, model: this.modelId, ...session, options }, {
411
+ onDelta,
412
+ signal: controller.signal,
413
+ ...(onPrefill === undefined ? {} : { onPrefill: (done, total) => onPrefill({ done, total }) }),
414
+ });
415
+ this.onLength(result.length);
416
+ return result;
417
+ }, () => controller.abort(), generateOptions.signal, generateOptions.onToken);
418
+ }
419
+ /** Encodes text into token ids. */
420
+ tokenize(text, options = {}) {
421
+ return this.client.request({
422
+ type: "tokenize",
423
+ model: this.modelId,
424
+ text,
425
+ addSpecialTokens: options.addSpecialTokens ?? false,
426
+ });
427
+ }
428
+ /** Decodes token ids into text. */
429
+ detokenize(ids, options = {}) {
430
+ return this.client.request({
431
+ type: "detokenize",
432
+ model: this.modelId,
433
+ ids: Uint32Array.from(ids),
434
+ skipSpecialTokens: options.skipSpecialTokens ?? false,
435
+ });
436
+ }
437
+ /**
438
+ * Renders a conversation with the chat template, ending with the header of
439
+ * a new assistant turn. `templateKwargs` are passed to the template (e.g.
440
+ * `{ enable_thinking: false }`).
441
+ */
442
+ renderChat(messages, templateKwargs = {}) {
443
+ return this.client.request({
444
+ type: "renderChat",
445
+ model: this.modelId,
446
+ messages: checkMessages(messages),
447
+ templateKwargs,
448
+ });
449
+ }
450
+ }
451
+ /** A loaded model. Its own `chat`/`generate` use a default session. */
452
+ export class Model extends Conversation {
453
+ #info;
454
+ #base;
455
+ #sessions = new Set();
456
+ #unloaded = false;
457
+ sessionId = undefined;
458
+ #ownsEngine;
459
+ /**
460
+ * @internal `base` holds what later reads of the model's own files need:
461
+ * the custom store of a `fetch` source and the Node cache directory.
462
+ * `ownsEngine` is false for a model loaded into a shared engine.
463
+ */
464
+ constructor(client, modelId, info, base = {}, ownsEngine = true) {
465
+ super(client, modelId);
466
+ this.#info = info;
467
+ this.#base = base;
468
+ this.#ownsEngine = ownsEngine;
469
+ }
470
+ get hasChatTemplate() {
471
+ return this.#info.hasChatTemplate;
472
+ }
473
+ onLength() { }
474
+ /** Architecture, sizes, quant, backend and the files loaded (with SHA-256). */
475
+ info() {
476
+ return this.#info;
477
+ }
478
+ /** Clears the default session's cache. */
479
+ async reset() {
480
+ await this.client.request({ type: "reset", model: this.modelId });
481
+ }
482
+ /**
483
+ * Merges a PEFT LoRA adapter (`adapter_config.json` and
484
+ * `adapter_model.safetensors`, as published on the Hub) into the weights,
485
+ * replacing the adapter applied before, if any. The affected base
486
+ * matrices are read again from the model's source and merged in f32
487
+ * before quantization: decoding runs at the base model's speed.
488
+ *
489
+ * Rejects with `INVALID_ADAPTER`, leaving the model unchanged, when the
490
+ * adapter does not fit the model (a module it does not have, other
491
+ * shapes, or a target without weights). Every session (the default one
492
+ * included) starts over at its next call.
493
+ *
494
+ * ```ts
495
+ * const lora = await model.applyAdapter("user/my-lora", { scale: 0.8 });
496
+ * console.log(lora.modules.length, "modules adapted");
497
+ * ```
498
+ */
499
+ async applyAdapter(source, options = {}) {
500
+ const adapter = normalizeAdapterSource(source, options.revision);
501
+ checkScale(options.scale);
502
+ const lora = await this.client.request({
503
+ type: "applyAdapter",
504
+ model: this.modelId,
505
+ source: toWire(adapter, options.token),
506
+ options: {
507
+ ...(options.scale === undefined ? {} : { scale: options.scale }),
508
+ ...(this.#base.cacheDir === undefined ? {} : { cacheDir: this.#base.cacheDir }),
509
+ },
510
+ }, {
511
+ ...(options.onProgress === undefined ? {} : { onProgress: options.onProgress }),
512
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
513
+ ...(this.#base.fetch === undefined ? {} : { onRead: this.#base.fetch }),
514
+ ...(adapter.kind === "fetch" ? { onAdapterRead: adapter.fetch } : {}),
515
+ });
516
+ this.#info = { ...this.#info, lora };
517
+ return lora;
518
+ }
519
+ /**
520
+ * Removes the LoRA adapter, restoring the base weights exactly (the
521
+ * logits are bit-identical to those of the base model). Resolves to the
522
+ * adapter removed, or `undefined` when there was none.
523
+ */
524
+ async removeAdapter(options = {}) {
525
+ const removed = await this.client.request({ type: "removeAdapter", model: this.modelId }, {
526
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
527
+ ...(this.#base.fetch === undefined ? {} : { onRead: this.#base.fetch }),
528
+ });
529
+ const { lora: _lora, ...info } = this.#info;
530
+ void _lora;
531
+ this.#info = info;
532
+ return removed ?? undefined;
533
+ }
534
+ /** Starts an independent session (its own KV cache) for low-level use. */
535
+ async session() {
536
+ const id = await this.client.request({ type: "createSession", model: this.modelId });
537
+ const session = new Session(this.client, this.modelId, id, this.#info, () => this.#sessions.delete(session));
538
+ this.#sessions.add(session);
539
+ return session;
540
+ }
541
+ /**
542
+ * Frees the model and stops its worker (unless it runs in a shared
543
+ * {@link EngineHandle}). Every later call rejects with `DISPOSED`.
544
+ */
545
+ async unload() {
546
+ if (this.#unloaded)
547
+ return;
548
+ this.#unloaded = true;
549
+ try {
550
+ await this.client.request({ type: "unload", model: this.modelId });
551
+ }
552
+ catch {
553
+ // The worker may already be gone.
554
+ }
555
+ if (this.#ownsEngine)
556
+ await this.client.terminate();
557
+ }
558
+ }
559
+ /**
560
+ * An independent conversation over a model, with low-level access for
561
+ * callers that pick tokens themselves: teacher-forced `score`, `step`,
562
+ * logits and hidden states.
563
+ */
564
+ export class Session extends Conversation {
565
+ sessionId;
566
+ #info;
567
+ #onDispose;
568
+ #length = 0;
569
+ /** @internal */
570
+ constructor(client, modelId, sessionId, info, onDispose) {
571
+ super(client, modelId);
572
+ this.sessionId = sessionId;
573
+ this.#info = info;
574
+ this.#onDispose = onDispose;
575
+ }
576
+ get hasChatTemplate() {
577
+ return this.#info.hasChatTemplate;
578
+ }
579
+ onLength(length) {
580
+ this.#length = length;
581
+ }
582
+ /** Positions in the cache (as of the last completed call). */
583
+ get length() {
584
+ return this.#length;
585
+ }
586
+ /** Teacher-forced pass: appends `ids` to the cache and returns logits and hidden states. */
587
+ async score(ids, options = {}) {
588
+ const result = await this.client.request({
589
+ type: "score",
590
+ model: this.modelId,
591
+ session: this.sessionId,
592
+ ids: Uint32Array.from(ids),
593
+ options: {
594
+ ...(options.logits === undefined ? {} : { logits: options.logits }),
595
+ ...(options.hiddenStates === undefined ? {} : { hiddenStates: [...options.hiddenStates] }),
596
+ },
597
+ }, options.signal === undefined ? {} : { signal: options.signal });
598
+ this.#length = result.length;
599
+ return result;
600
+ }
601
+ /** One decode step with a token the caller picked. */
602
+ async step(id, options = {}) {
603
+ const result = await this.client.request({
604
+ type: "step",
605
+ model: this.modelId,
606
+ session: this.sessionId,
607
+ token: id,
608
+ options: {
609
+ ...(options.logits === undefined ? {} : { logits: options.logits }),
610
+ ...(options.hiddenStates === undefined ? {} : { hiddenStates: [...options.hiddenStates] }),
611
+ },
612
+ }, options.signal === undefined ? {} : { signal: options.signal });
613
+ this.#length = result.length;
614
+ return result;
615
+ }
616
+ /**
617
+ * A new session holding a copy of this one's cache: both continue from
618
+ * the same computed prefix (generate or score several continuations
619
+ * without recomputing it).
620
+ */
621
+ async fork() {
622
+ const id = await this.client.request({
623
+ type: "forkSession",
624
+ model: this.modelId,
625
+ session: this.sessionId,
626
+ });
627
+ const fork = new Session(this.client, this.modelId, id, this.#info, () => { });
628
+ fork.#length = this.#length;
629
+ return fork;
630
+ }
631
+ /**
632
+ * Log-probabilities of several continuations of one prefix: entry `i`
633
+ * holds one value per token of `continuations[i]`, given the prefix and
634
+ * the tokens before it. The prefix runs through the model once (not at
635
+ * all when the session already holds it, but for its last token); the
636
+ * session then holds the prefix.
637
+ */
638
+ async scoreContinuations(prefix, continuations) {
639
+ const scores = await this.client.request({
640
+ type: "scoreContinuations",
641
+ model: this.modelId,
642
+ session: this.sessionId,
643
+ prefix: Uint32Array.from(prefix),
644
+ continuations: continuations.map((c) => Array.from(c)),
645
+ });
646
+ this.#length = prefix.length;
647
+ return scores;
648
+ }
649
+ /**
650
+ * Context shift: drops `drop` cached positions after the first `keep`
651
+ * and recomputes the rest, so a long conversation keeps going (see also
652
+ * the `contextShift` generation option).
653
+ */
654
+ async shiftContext(keep, drop) {
655
+ this.#length = await this.client.request({
656
+ type: "shiftContext",
657
+ model: this.modelId,
658
+ session: this.sessionId,
659
+ keep,
660
+ drop,
661
+ });
662
+ }
663
+ /**
664
+ * Keeps the first `length` positions. Recurrent models (LFM2, LFM3, Qwen3.5) recompute their
665
+ * state for those positions, which costs a prefill of `length` tokens.
666
+ */
667
+ async truncate(length) {
668
+ this.#length = await this.client.request({
669
+ type: "truncate",
670
+ model: this.modelId,
671
+ session: this.sessionId,
672
+ length,
673
+ });
674
+ }
675
+ /** Empties the cache. */
676
+ async reset() {
677
+ await this.client.request({ type: "reset", model: this.modelId, session: this.sessionId });
678
+ this.#length = 0;
679
+ }
680
+ /** Frees the session's cache. */
681
+ async dispose() {
682
+ this.#onDispose();
683
+ await this.client.request({ type: "disposeSession", model: this.modelId, session: this.sessionId });
684
+ }
685
+ }
686
+ /** Model families: supported today and on the roadmap. */
687
+ export const MODEL_FAMILIES = [
688
+ {
689
+ name: "SmolLM2",
690
+ modelType: "llama",
691
+ modality: "text",
692
+ exampleRepo: "HuggingFaceTB/SmolLM2-135M-Instruct",
693
+ status: "supported",
694
+ },
695
+ {
696
+ name: "Qwen3",
697
+ modelType: "qwen3",
698
+ modality: "text",
699
+ exampleRepo: "Qwen/Qwen3-0.6B",
700
+ status: "supported",
701
+ },
702
+ {
703
+ name: "LFM2 / LFM2.5",
704
+ modelType: "lfm2",
705
+ modality: "text",
706
+ exampleRepo: "LiquidAI/LFM2.5-350M",
707
+ status: "supported",
708
+ },
709
+ {
710
+ name: "Qwen3.5",
711
+ modelType: "qwen3_5",
712
+ modality: "text",
713
+ exampleRepo: "Qwen/Qwen3.5-0.8B",
714
+ status: "supported",
715
+ },
716
+ {
717
+ name: "LFM3",
718
+ modelType: "lfm3",
719
+ modality: "text",
720
+ exampleRepo: "LiquidAI/LFM3-1.7B",
721
+ status: "supported",
722
+ },
723
+ {
724
+ name: "SmolVLM",
725
+ modelType: "idefics3",
726
+ modality: "vision-language",
727
+ exampleRepo: "HuggingFaceTB/SmolVLM-256M-Instruct",
728
+ status: "planned",
729
+ },
730
+ ];