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
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Entry point of the `worker_threads` workers started by
3
+ * `node-web-worker.ts`: gives the thread the global scope of a Web Worker,
4
+ * then runs the requested module (`pool-worker.js`).
5
+ */
6
+ export {};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Entry point of the `worker_threads` workers started by
3
+ * `node-web-worker.ts`: gives the thread the global scope of a Web Worker,
4
+ * then runs the requested module (`pool-worker.js`).
5
+ */
6
+ import { importNode } from "./runtime.js";
7
+ const { parentPort, workerData } = await importNode("worker_threads");
8
+ if (parentPort === null)
9
+ throw new Error("webslm/node-pool-worker must run in a worker thread");
10
+ const port = parentPort;
11
+ const listeners = new Map();
12
+ Object.assign(globalThis, {
13
+ self: globalThis,
14
+ postMessage(message) {
15
+ port.postMessage(message);
16
+ },
17
+ addEventListener(type, listener) {
18
+ if (type !== "message" || listeners.has(listener))
19
+ return;
20
+ const wrapped = (data) => listener({ data });
21
+ listeners.set(listener, wrapped);
22
+ port.on("message", wrapped);
23
+ },
24
+ removeEventListener(type, listener) {
25
+ const wrapped = listeners.get(listener);
26
+ if (type !== "message" || wrapped === undefined)
27
+ return;
28
+ port.off("message", wrapped);
29
+ listeners.delete(listener);
30
+ },
31
+ });
32
+ await import(/* @vite-ignore */ /* webpackIgnore: true */ workerData.url);
@@ -0,0 +1,23 @@
1
+ /**
2
+ * A minimal Web `Worker` for Node, on `worker_threads`, so the `threads`
3
+ * wasm flavour can start its pool there: `pool.ts` starts
4
+ * `new Worker(poolWorkerUrl, { type: "module" })` and wasm-bindgen-rayon talks
5
+ * to it with `postMessage` and `message` events only.
6
+ *
7
+ * Each worker runs `node-pool-worker.js`, which gives the thread a
8
+ * worker-like global scope (`self`, `postMessage`, `addEventListener`) and
9
+ * then imports the requested script. Pool workers are `unref`ed: they never
10
+ * keep a Node process alive.
11
+ */
12
+ /**
13
+ * Whether pool workers can start: the compiled bootstrap script sits next to
14
+ * this module (not the case when running from TypeScript sources).
15
+ */
16
+ export declare function nodePoolAvailable(): Promise<boolean>;
17
+ /**
18
+ * Defines `globalThis.Worker` in Node, unless one exists already. Also gives
19
+ * the calling thread the bits of a worker scope that wasm-bindgen-rayon's
20
+ * script touches when it is imported (`self`, `addEventListener`): it waits
21
+ * there for a start message that only pool workers receive.
22
+ */
23
+ export declare function installNodeWebWorker(): Promise<void>;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * A minimal Web `Worker` for Node, on `worker_threads`, so the `threads`
3
+ * wasm flavour can start its pool there: `pool.ts` starts
4
+ * `new Worker(poolWorkerUrl, { type: "module" })` and wasm-bindgen-rayon talks
5
+ * to it with `postMessage` and `message` events only.
6
+ *
7
+ * Each worker runs `node-pool-worker.js`, which gives the thread a
8
+ * worker-like global scope (`self`, `postMessage`, `addEventListener`) and
9
+ * then imports the requested script. Pool workers are `unref`ed: they never
10
+ * keep a Node process alive.
11
+ */
12
+ import { importNode } from "./runtime.js";
13
+ /** The script each pool worker starts with. */
14
+ const BOOTSTRAP = "./node-pool-worker.js";
15
+ /**
16
+ * Where {@link BOOTSTRAP} lives. Not written as `new URL(…, import.meta.url)`:
17
+ * browser bundlers would try to resolve this Node-only file as an asset.
18
+ */
19
+ function bootstrapUrl() {
20
+ const base = import.meta.url;
21
+ return new URL(BOOTSTRAP, base);
22
+ }
23
+ /**
24
+ * Whether pool workers can start: the compiled bootstrap script sits next to
25
+ * this module (not the case when running from TypeScript sources).
26
+ */
27
+ export async function nodePoolAvailable() {
28
+ const fs = await importNode("fs/promises");
29
+ try {
30
+ await fs.access(bootstrapUrl());
31
+ return true;
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ /**
38
+ * Defines `globalThis.Worker` in Node, unless one exists already. Also gives
39
+ * the calling thread the bits of a worker scope that wasm-bindgen-rayon's
40
+ * script touches when it is imported (`self`, `addEventListener`): it waits
41
+ * there for a start message that only pool workers receive.
42
+ */
43
+ export async function installNodeWebWorker() {
44
+ const scope = globalThis;
45
+ scope.self ??= globalThis;
46
+ scope.addEventListener ??= () => { };
47
+ scope.removeEventListener ??= () => { };
48
+ if (typeof scope.Worker === "function")
49
+ return;
50
+ const { Worker } = await importNode("worker_threads");
51
+ const bootstrap = bootstrapUrl();
52
+ class NodeWebWorker {
53
+ #worker;
54
+ #listeners = new Map();
55
+ constructor(url) {
56
+ this.#worker = new Worker(bootstrap, { workerData: { url: String(url) } });
57
+ this.#worker.on("error", (error) => {
58
+ console.error("webslm: a thread pool worker failed", error);
59
+ });
60
+ this.#worker.unref();
61
+ }
62
+ postMessage(message) {
63
+ this.#worker.postMessage(message);
64
+ }
65
+ addEventListener(type, listener) {
66
+ if (type !== "message" || this.#listeners.has(listener))
67
+ return;
68
+ const wrapped = (data) => listener({ data });
69
+ this.#listeners.set(listener, wrapped);
70
+ this.#worker.on("message", wrapped);
71
+ }
72
+ removeEventListener(type, listener) {
73
+ const wrapped = this.#listeners.get(listener);
74
+ if (type !== "message" || wrapped === undefined)
75
+ return;
76
+ this.#worker.off("message", wrapped);
77
+ this.#listeners.delete(listener);
78
+ }
79
+ terminate() {
80
+ void this.#worker.terminate();
81
+ }
82
+ }
83
+ scope.Worker = NodeWebWorker;
84
+ }
@@ -0,0 +1,2 @@
1
+ /** Entry point of the `worker_threads` worker that runs the engine in Node. */
2
+ export {};
@@ -0,0 +1,9 @@
1
+ /** Entry point of the `worker_threads` worker that runs the engine in Node. */
2
+ import { Engine } from "./engine.js";
3
+ import { importNode } from "./runtime.js";
4
+ const { parentPort } = await importNode("worker_threads");
5
+ if (parentPort === null)
6
+ throw new Error("webslm/node-worker must run in a worker thread");
7
+ const port = parentPort;
8
+ const engine = new Engine({ post: (message, transfer) => port.postMessage(message, transfer) });
9
+ port.on("message", (message) => engine.handle(message));
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Entry point of the workers of the `threads` build's pool (see `pool.ts`).
3
+ * Waits for wasm-bindgen-rayon's start message, instantiates the module on
4
+ * the shared memory it carries, and joins the pool.
5
+ *
6
+ * In browsers this runs in a module Worker; in Node, `node-pool-worker.js`
7
+ * gives the worker thread the same global scope, then imports this module.
8
+ */
9
+ interface InitMessage {
10
+ readonly type: "wasm_bindgen_worker_init";
11
+ readonly init: {
12
+ readonly module_or_path: WebAssembly.Module;
13
+ readonly memory: WebAssembly.Memory;
14
+ };
15
+ readonly receiver: number;
16
+ }
17
+ interface PoolWorkerScope {
18
+ postMessage(message: unknown): void;
19
+ addEventListener(type: "message", listener: (event: {
20
+ data: unknown;
21
+ }) => void): void;
22
+ removeEventListener(type: "message", listener: (event: {
23
+ data: unknown;
24
+ }) => void): void;
25
+ }
26
+ declare const scope: PoolWorkerScope;
27
+ declare function isInit(data: unknown): data is InitMessage;
28
+ /** The part of the `threads` bindings a pool worker uses. */
29
+ interface ThreadsBindings {
30
+ default(init: InitMessage["init"]): Promise<unknown>;
31
+ wbg_rayon_start_worker(receiver: number): void;
32
+ }
33
+ declare function join({ init, receiver }: InitMessage): Promise<void>;
34
+ declare function onMessage(event: {
35
+ data: unknown;
36
+ }): void;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ /**
3
+ * Entry point of the workers of the `threads` build's pool (see `pool.ts`).
4
+ * Waits for wasm-bindgen-rayon's start message, instantiates the module on
5
+ * the shared memory it carries, and joins the pool.
6
+ *
7
+ * In browsers this runs in a module Worker; in Node, `node-pool-worker.js`
8
+ * gives the worker thread the same global scope, then imports this module.
9
+ */
10
+ const scope = globalThis;
11
+ function isInit(data) {
12
+ return data?.type === "wasm_bindgen_worker_init";
13
+ }
14
+ async function join({ init, receiver }) {
15
+ // Typed by hand: the `threads` build may be missing when the package is
16
+ // built from source (the pool only starts once it loaded).
17
+ // @ts-ignore: present once built (or as a placeholder).
18
+ const bindings = (await import("../wasm/threads/webslm_wasm.js"));
19
+ await bindings.default(init);
20
+ scope.postMessage({ type: "wasm_bindgen_worker_ready" });
21
+ // Runs the pool's work loop; returns only when the pool shuts down.
22
+ bindings.wbg_rayon_start_worker(receiver);
23
+ }
24
+ function onMessage(event) {
25
+ if (!isInit(event.data))
26
+ return;
27
+ scope.removeEventListener("message", onMessage);
28
+ void join(event.data);
29
+ }
30
+ scope.addEventListener("message", onMessage);
package/dist/pool.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Starts the workers of the `threads` build's pool.
3
+ *
4
+ * wasm-bindgen-rayon's worker script starts copies of itself
5
+ * (`new Worker(new URL("./workerHelpers.js", import.meta.url))`), a worker
6
+ * that references its own module, which Turbopack cannot build (Next.js
7
+ * hangs). `cargo xtask build-wasm` patches the script to call the function
8
+ * {@link installPoolWorkerFactory} registers instead, which starts
9
+ * `pool-worker.js`: no worker script starts itself, and bundlers see a plain
10
+ * `new Worker(new URL(..., import.meta.url))`.
11
+ */
12
+ /**
13
+ * Lets the `threads` bindings start their pool. Call before
14
+ * `startThreadPool`; in Node, after `installNodeWebWorker` (which provides
15
+ * `Worker`).
16
+ */
17
+ export declare function installPoolWorkerFactory(): void;
package/dist/pool.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Starts the workers of the `threads` build's pool.
3
+ *
4
+ * wasm-bindgen-rayon's worker script starts copies of itself
5
+ * (`new Worker(new URL("./workerHelpers.js", import.meta.url))`), a worker
6
+ * that references its own module, which Turbopack cannot build (Next.js
7
+ * hangs). `cargo xtask build-wasm` patches the script to call the function
8
+ * {@link installPoolWorkerFactory} registers instead, which starts
9
+ * `pool-worker.js`: no worker script starts itself, and bundlers see a plain
10
+ * `new Worker(new URL(..., import.meta.url))`.
11
+ */
12
+ import { importingWorkerUrl, isSecurityError } from "./runtime.js";
13
+ /** The global the patched worker script calls (see `xtask/src/wasm.rs`). */
14
+ const FACTORY = "__webslmStartPoolWorker";
15
+ let blobUrl;
16
+ /** Starts one pool worker. */
17
+ function startPoolWorker() {
18
+ try {
19
+ // Bundlers recognize this exact pattern, options included (Vite needs
20
+ // them literal), and emit the pool worker as its own chunk.
21
+ return new Worker(new URL("./pool-worker.js", import.meta.url), { type: "module", name: "webslm-pool" });
22
+ }
23
+ catch (error) {
24
+ // A script from another origin (the package on a CDN): import it from a
25
+ // same-origin worker, one blob: URL for the whole pool.
26
+ if (!isSecurityError(error))
27
+ throw error;
28
+ // Not `new URL(…, import.meta.url)`: bundlers would emit the file twice.
29
+ const base = import.meta.url;
30
+ blobUrl ??= importingWorkerUrl(new URL("./pool-worker.js", base).href);
31
+ return new Worker(blobUrl, { type: "module", name: "webslm-pool" });
32
+ }
33
+ }
34
+ /**
35
+ * Lets the `threads` bindings start their pool. Call before
36
+ * `startThreadPool`; in Node, after `installNodeWebWorker` (which provides
37
+ * `Worker`).
38
+ */
39
+ export function installPoolWorkerFactory() {
40
+ globalThis[FACTORY] ??= startPoolWorker;
41
+ }
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Messages between the page (client) and the engine (worker).
3
+ *
4
+ * Every request carries an `id`; the engine answers with exactly one
5
+ * `result` or `error` for it, possibly preceded by `progress`, `delta` and
6
+ * `read` messages. `abort` and `readResult` get no answer.
7
+ */
8
+ import type { SerializedError } from "./errors.js";
9
+ import type { Activations, FileData, LoadProgress, LoraInfo, ModelInfo } from "./types.js";
10
+ import type { WasmFlavour } from "./wasm-flavour.js";
11
+ /** A model source in a form that can be posted to a worker. */
12
+ export type WireSource = {
13
+ readonly kind: "hub";
14
+ readonly repo: string;
15
+ readonly revision?: string;
16
+ readonly hubUrl?: string;
17
+ readonly token?: string;
18
+ } | {
19
+ readonly kind: "files";
20
+ readonly files: Readonly<Record<string, FileData>>;
21
+ }
22
+ /** Reads are forwarded to the page with `read` messages. */
23
+ | {
24
+ readonly kind: "fetch";
25
+ };
26
+ export interface WireLoadOptions {
27
+ readonly quant: string;
28
+ /** `"auto"`, `"cpu"` or `"webgpu"`; the engine reports what it used. */
29
+ readonly device?: string;
30
+ readonly contextLength?: number;
31
+ /** Scale of the adapter of a `load` request. */
32
+ readonly adapterScale?: number;
33
+ readonly cacheDir?: string;
34
+ readonly deterministic?: boolean;
35
+ readonly activations?: Activations;
36
+ readonly wasmFlavour?: WasmFlavour;
37
+ readonly threads?: number;
38
+ }
39
+ /** Generation options as sent to the engine (no signal). */
40
+ export interface WireGenerateOptions {
41
+ readonly maxTokens?: number;
42
+ readonly temperature?: number;
43
+ readonly topK?: number;
44
+ readonly topP?: number;
45
+ readonly minP?: number;
46
+ readonly repetitionPenalty?: number;
47
+ readonly seed?: number;
48
+ readonly stop?: readonly string[];
49
+ readonly templateKwargs?: Readonly<Record<string, unknown>>;
50
+ readonly ignoreStopTokens?: boolean;
51
+ readonly addSpecialTokens?: boolean;
52
+ readonly presencePenalty?: number;
53
+ readonly frequencyPenalty?: number;
54
+ readonly stopTokenIds?: readonly number[];
55
+ /** Alternatives per token; present: log-probabilities are returned. */
56
+ readonly logprobs?: number;
57
+ readonly json?: boolean;
58
+ readonly schema?: Readonly<Record<string, unknown>> | boolean;
59
+ readonly thinkingBudget?: number;
60
+ readonly loopDetection?: boolean;
61
+ readonly contextShift?: boolean | {
62
+ readonly keep?: number;
63
+ };
64
+ }
65
+ export interface WireMessage {
66
+ readonly role: string;
67
+ readonly content: string;
68
+ }
69
+ type WithId<T> = T & {
70
+ readonly id: number;
71
+ };
72
+ export type Request = WithId<{
73
+ readonly type: "load";
74
+ readonly source: WireSource;
75
+ /** A LoRA adapter merged at load. */
76
+ readonly adapter?: WireSource;
77
+ readonly options: WireLoadOptions;
78
+ } | {
79
+ readonly type: "applyAdapter";
80
+ readonly model: number;
81
+ readonly source: WireSource;
82
+ readonly options: {
83
+ readonly scale?: number;
84
+ readonly cacheDir?: string;
85
+ };
86
+ } | {
87
+ readonly type: "removeAdapter";
88
+ readonly model: number;
89
+ } | {
90
+ readonly type: "chat";
91
+ readonly model: number;
92
+ readonly session?: number;
93
+ readonly messages: readonly WireMessage[];
94
+ readonly options: WireGenerateOptions;
95
+ } | {
96
+ readonly type: "generate";
97
+ readonly model: number;
98
+ readonly session?: number;
99
+ readonly prompt: string;
100
+ readonly options: WireGenerateOptions;
101
+ } | {
102
+ readonly type: "createSession";
103
+ readonly model: number;
104
+ } | {
105
+ readonly type: "forkSession";
106
+ readonly model: number;
107
+ readonly session: number;
108
+ } | {
109
+ readonly type: "scoreContinuations";
110
+ readonly model: number;
111
+ readonly session: number;
112
+ readonly prefix: Uint32Array;
113
+ readonly continuations: readonly (readonly number[])[];
114
+ } | {
115
+ readonly type: "shiftContext";
116
+ readonly model: number;
117
+ readonly session: number;
118
+ readonly keep: number;
119
+ readonly drop: number;
120
+ } | {
121
+ readonly type: "disposeSession";
122
+ readonly model: number;
123
+ readonly session: number;
124
+ } | {
125
+ readonly type: "score";
126
+ readonly model: number;
127
+ readonly session: number;
128
+ readonly ids: Uint32Array;
129
+ readonly options: {
130
+ readonly logits?: string;
131
+ readonly hiddenStates?: readonly number[];
132
+ };
133
+ } | {
134
+ readonly type: "step";
135
+ readonly model: number;
136
+ readonly session: number;
137
+ readonly token: number;
138
+ readonly options: {
139
+ readonly logits?: boolean;
140
+ readonly hiddenStates?: readonly number[];
141
+ };
142
+ } | {
143
+ readonly type: "truncate";
144
+ readonly model: number;
145
+ readonly session: number;
146
+ readonly length: number;
147
+ } | {
148
+ readonly type: "reset";
149
+ readonly model: number;
150
+ readonly session?: number;
151
+ } | {
152
+ readonly type: "tokenize";
153
+ readonly model: number;
154
+ readonly text: string;
155
+ readonly addSpecialTokens: boolean;
156
+ } | {
157
+ readonly type: "detokenize";
158
+ readonly model: number;
159
+ readonly ids: Uint32Array;
160
+ readonly skipSpecialTokens: boolean;
161
+ } | {
162
+ readonly type: "renderChat";
163
+ readonly model: number;
164
+ readonly messages: readonly WireMessage[];
165
+ readonly templateKwargs: Readonly<Record<string, unknown>>;
166
+ } | {
167
+ readonly type: "unload";
168
+ readonly model: number;
169
+ } | {
170
+ readonly type: "abort";
171
+ readonly target: number;
172
+ } | {
173
+ readonly type: "readResult";
174
+ readonly readId: number;
175
+ readonly bytes?: Uint8Array | null;
176
+ readonly error?: SerializedError;
177
+ }>;
178
+ export type RequestType = Request["type"];
179
+ export type Response = {
180
+ readonly type: "result";
181
+ readonly id: number;
182
+ readonly value: unknown;
183
+ } | {
184
+ readonly type: "error";
185
+ readonly id: number;
186
+ readonly error: SerializedError;
187
+ } | {
188
+ readonly type: "progress";
189
+ readonly id: number;
190
+ readonly progress: LoadProgress;
191
+ } | {
192
+ readonly type: "delta";
193
+ readonly id: number;
194
+ readonly text: string;
195
+ readonly token: number;
196
+ readonly logprob?: number;
197
+ /** `[token id, log-probability]` pairs, most likely first. */
198
+ readonly topLogprobs?: readonly (readonly [number, number])[];
199
+ readonly forced?: boolean;
200
+ } | {
201
+ readonly type: "prefill";
202
+ readonly id: number;
203
+ readonly done: number;
204
+ readonly total: number;
205
+ } | {
206
+ readonly type: "read";
207
+ readonly id: number;
208
+ readonly readId: number;
209
+ readonly path: string;
210
+ readonly start?: number;
211
+ readonly end?: number;
212
+ /** `"adapter"` for files of the LoRA adapter, absent for the model's own. */
213
+ readonly target?: "adapter";
214
+ };
215
+ /** Value of an `applyAdapter` result (`removeAdapter` resolves to it or `null`). */
216
+ export type WireLoraResult = LoraInfo;
217
+ /** Value of a `load` result. */
218
+ export interface LoadResult {
219
+ readonly model: number;
220
+ readonly info: ModelInfo;
221
+ }
222
+ /** Value of a `chat` or `generate` result. */
223
+ export interface WireGenerationResult {
224
+ readonly text: string;
225
+ readonly tokens: readonly number[];
226
+ readonly finishReason: "stop" | "stop_string" | "length" | "context_full" | "loop" | "aborted";
227
+ readonly promptTokens: number;
228
+ readonly reusedTokens: number;
229
+ readonly generatedTokens: number;
230
+ readonly droppedTokens: number;
231
+ readonly length: number;
232
+ readonly timeToFirstTokenMs: number;
233
+ readonly tokensPerSecond: number;
234
+ }
235
+ /** Value of a `score` or `step` result. */
236
+ export interface WireScoreResult {
237
+ readonly logits?: Float32Array;
238
+ readonly hidden: Readonly<Record<number, Float32Array>>;
239
+ readonly positions: number;
240
+ readonly vocabSize: number;
241
+ readonly hiddenSize: number;
242
+ readonly length: number;
243
+ }
244
+ /** Buffers to transfer (not copy) along with a score result. */
245
+ export declare function scoreTransferables(result: WireScoreResult): ArrayBuffer[];
246
+ export {};
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Messages between the page (client) and the engine (worker).
3
+ *
4
+ * Every request carries an `id`; the engine answers with exactly one
5
+ * `result` or `error` for it, possibly preceded by `progress`, `delta` and
6
+ * `read` messages. `abort` and `readResult` get no answer.
7
+ */
8
+ /** Buffers to transfer (not copy) along with a score result. */
9
+ export function scoreTransferables(result) {
10
+ const buffers = [];
11
+ const add = (array) => {
12
+ if (array !== undefined && array.buffer instanceof ArrayBuffer)
13
+ buffers.push(array.buffer);
14
+ };
15
+ add(result.logits);
16
+ for (const array of Object.values(result.hidden))
17
+ add(array);
18
+ return buffers;
19
+ }
@@ -0,0 +1,21 @@
1
+ /** Environment helpers shared by the page and the worker. */
2
+ /** Whether the code runs in Node.js (or a Node worker thread). */
3
+ export declare function isNode(): boolean;
4
+ /**
5
+ * Imports a Node built-in module without letting bundlers see the specifier,
6
+ * so browser builds never try to resolve `node:*`.
7
+ */
8
+ export declare function importNode<T>(name: string): Promise<T>;
9
+ /** Whether `error` is the `SecurityError` browsers throw for a cross-origin worker script. */
10
+ export declare function isSecurityError(error: unknown): boolean;
11
+ /**
12
+ * A `blob:` URL (same origin as the page) of a module worker that imports
13
+ * `script`. Browsers refuse worker scripts from another origin, as when the
14
+ * package is imported from a CDN; a same-origin worker may still import them
15
+ * (with CORS).
16
+ */
17
+ export declare function importingWorkerUrl(script: string): string;
18
+ /** Resolves after pending messages and events had a chance to run (a macrotask). */
19
+ export declare function yieldToEventLoop(): Promise<void>;
20
+ /** Current time in milliseconds, with sub-millisecond precision where available. */
21
+ export declare function now(): number;
@@ -0,0 +1,53 @@
1
+ /** Environment helpers shared by the page and the worker. */
2
+ /** Whether the code runs in Node.js (or a Node worker thread). */
3
+ export function isNode() {
4
+ const process = globalThis.process;
5
+ return typeof process?.versions?.node === "string";
6
+ }
7
+ /**
8
+ * Imports a Node built-in module without letting bundlers see the specifier,
9
+ * so browser builds never try to resolve `node:*`.
10
+ */
11
+ export function importNode(name) {
12
+ const specifier = `node:${name}`;
13
+ return import(/* @vite-ignore */ /* webpackIgnore: true */ specifier);
14
+ }
15
+ /** Whether `error` is the `SecurityError` browsers throw for a cross-origin worker script. */
16
+ export function isSecurityError(error) {
17
+ return typeof error === "object" && error !== null && error.name === "SecurityError";
18
+ }
19
+ /**
20
+ * A `blob:` URL (same origin as the page) of a module worker that imports
21
+ * `script`. Browsers refuse worker scripts from another origin, as when the
22
+ * package is imported from a CDN; a same-origin worker may still import them
23
+ * (with CORS).
24
+ */
25
+ export function importingWorkerUrl(script) {
26
+ const source = `import ${JSON.stringify(script)};\n`;
27
+ return URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
28
+ }
29
+ /** Resolves after pending messages and events had a chance to run (a macrotask). */
30
+ export function yieldToEventLoop() {
31
+ const setImmediate = globalThis
32
+ .setImmediate;
33
+ if (typeof setImmediate === "function") {
34
+ return new Promise((resolve) => {
35
+ setImmediate(resolve);
36
+ });
37
+ }
38
+ if (typeof MessageChannel === "function") {
39
+ return new Promise((resolve) => {
40
+ const channel = new MessageChannel();
41
+ channel.port1.onmessage = () => {
42
+ channel.port1.close();
43
+ resolve();
44
+ };
45
+ channel.port2.postMessage(null);
46
+ });
47
+ }
48
+ return new Promise((resolve) => setTimeout(resolve, 0));
49
+ }
50
+ /** Current time in milliseconds, with sub-millisecond precision where available. */
51
+ export function now() {
52
+ return typeof performance === "undefined" ? Date.now() : performance.now();
53
+ }
@@ -0,0 +1,20 @@
1
+ /** Types mirroring the safetensors header returned by the Rust engine. */
2
+ /** Element types defined by the safetensors format. */
3
+ export type Dtype = "BOOL" | "U8" | "I8" | "F8_E5M2" | "F8_E4M3" | "I16" | "U16" | "F16" | "BF16" | "I32" | "U32" | "F32" | "F64" | "I64" | "U64";
4
+ /** Location and layout of one tensor. */
5
+ export interface TensorInfo {
6
+ readonly name: string;
7
+ readonly dtype: Dtype;
8
+ readonly shape: readonly number[];
9
+ /** `[begin, end)` byte offsets relative to the start of the data section. */
10
+ readonly dataOffsets: readonly [number, number];
11
+ }
12
+ /** A parsed safetensors header. */
13
+ export interface SafetensorsHeader {
14
+ /** Length of the JSON header in bytes. */
15
+ readonly headerLen: number;
16
+ /** Absolute file offset where tensor data starts. */
17
+ readonly dataStart: number;
18
+ /** Tensors keyed by name. `__metadata__` is omitted. */
19
+ readonly tensors: Readonly<Record<string, TensorInfo>>;
20
+ }
@@ -0,0 +1,2 @@
1
+ /** Types mirroring the safetensors header returned by the Rust engine. */
2
+ export {};