lemonteaa commited on
Commit
999eb85
·
1 Parent(s): 24de668

add current repo

Browse files
Files changed (11) hide show
  1. README.md +25 -0
  2. actions.js +29 -0
  3. download.js +115 -0
  4. index.html +1085 -0
  5. llm.js +272 -0
  6. sha256.js +161 -0
  7. storage.js +263 -0
  8. wasm/llm-wasm.build.txt +4 -0
  9. wasm/llm-wasm.js +2 -0
  10. wasm/llm-wasm.wasm +3 -0
  11. worker.js +499 -0
README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Llama Cpp Wasm
3
+ emoji: 🐨
4
+ colorFrom: green
5
+ colorTo: red
6
+ sdk: static
7
+ pinned: false
8
+ ---
9
+
10
+ llm.js lab - static bundle
11
+ build commit: 1ab62ba
12
+ llama.cpp: f7591a6a01f9273de03331732bdc0b39721168be
13
+ built: 2026-11-08
14
+
15
+ Serve this directory with any static server and open index.html:
16
+ python3 -m http.server 8000 --directory .
17
+ Models are not bundled: add a GGUF by URL (e.g. Hugging Face) or pick one
18
+ from your disk. Everything else runs locally in the browser (wasm32, CPU).
19
+ No COOP/COEP headers are needed (single-threaded build).
20
+
21
+ This build adds, over the 0addf13 bundle:
22
+ - tools: paste an OpenAI tools array, replies are split by the model's own
23
+ PEG parser and calls shown as JSON with "Add tool response"
24
+ - chat template params (chat_template_kwargs, e.g. enable_thinking)
25
+ - conversation export as OpenAI JSON or Markdown
actions.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Message protocol between the page, the LLM wrapper and the inference worker.
2
+ // Same event set llm.js had, plus what streaming downloads and a model library
3
+ // need.
4
+ export const action = {
5
+ LOAD: 0,
6
+ INITIALIZED: 1,
7
+ RUN_MAIN: 2,
8
+ WRITE_RESULT: 3,
9
+ RUN_COMPLETED: 4,
10
+ ERROR: 5,
11
+ PROGRESS: 6,
12
+ LOG: 7,
13
+ PAUSE: 8,
14
+ PAUSED: 9,
15
+ RESUME: 10,
16
+ DELETE_MODEL: 11,
17
+ DELETED: 12,
18
+ LIST_MODELS: 13,
19
+ MODELS: 14,
20
+ ADD_URL: 15,
21
+ ADD_FILE: 16,
22
+ MODEL_ADDED: 17,
23
+ MODEL_UPDATED: 18,
24
+ HASH_MODEL: 19,
25
+ PREVIEW_TEMPLATE: 20,
26
+ TEMPLATE_PREVIEW: 21,
27
+ RELOAD_MODEL: 22,
28
+ STOP: 23,
29
+ };
download.js ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Resumable, chunked model download into a keyed store.
2
+ //
3
+ // Pulled out of the worker so it can be tested in node with an in-memory store
4
+ // (see test/download-test.mjs) - the chunking, Range and restart logic is the
5
+ // part that is easy to get wrong.
6
+ //
7
+ // Store interface (default: storage.js / IndexedDB):
8
+ // CHUNK_SIZE
9
+ // getMeta(id) -> record or undefined
10
+ // putMeta(record) -> full replace (in-memory test store)
11
+ // updateMeta(id, patch) -> merge (optional; preferred when present)
12
+ // putChunk(id, index, buffer)
13
+ // clearChunks(id)
14
+ //
15
+ // The record carries the model's identity (id, name, source), so this module
16
+ // only ever touches the fields it owns: total, received and complete.
17
+
18
+ import {
19
+ CHUNK_SIZE, getModel, putModel, updateModel, putChunk, clearChunks,
20
+ } from "./storage.js";
21
+
22
+ const defaultStorage = {
23
+ CHUNK_SIZE, getMeta: getModel, putMeta: putModel, updateMeta: updateModel, putChunk, clearChunks,
24
+ };
25
+
26
+ /**
27
+ * Ensure the whole file is stored, resuming a previous partial download.
28
+ *
29
+ * @param {{ id: string, url: string, total?: number }} target
30
+ * @param {{ signal?: AbortSignal, onProgress?: Function, storage?: object }} options
31
+ * @returns {Promise<object>} the stored model record
32
+ */
33
+ export async function downloadModel(target, options = {}) {
34
+ const { id, url } = target;
35
+ const storage = options.storage || defaultStorage;
36
+ const onProgress = options.onProgress || (() => {});
37
+ const signal = options.signal;
38
+ const chunkSize = storage.CHUNK_SIZE;
39
+
40
+ let meta = await storage.getMeta(id);
41
+
42
+ if (meta && meta.complete) {
43
+ onProgress({ phase: "download", loaded: meta.received, total: meta.total, complete: true });
44
+ return meta;
45
+ }
46
+
47
+ const writeMeta = async (fields) => {
48
+ if (storage.updateMeta) return storage.updateMeta(id, fields);
49
+ return storage.putMeta({ ...(meta || {}), id, url, ...fields });
50
+ };
51
+
52
+ let received = meta ? (meta.received || 0) : 0;
53
+ let total = (meta && meta.total) || target.total || 0;
54
+
55
+ // a partial chunk would not line up with the Range offset - start over
56
+ if (received % chunkSize !== 0) {
57
+ await storage.clearChunks(id);
58
+ received = 0;
59
+ }
60
+
61
+ const headers = received > 0 ? { Range: `bytes=${received}-` } : undefined;
62
+ const res = await fetch(url, { headers, signal });
63
+ if (!res.ok) {
64
+ throw new Error(`model download failed: HTTP ${res.status} ${res.statusText}`);
65
+ }
66
+
67
+ // server ignored the Range header and sent the whole file: discard the partial copy
68
+ if (received > 0 && res.status !== 206) {
69
+ await storage.clearChunks(id);
70
+ received = 0;
71
+ }
72
+
73
+ if (!total) {
74
+ total = received + Number(res.headers.get("content-length") || 0);
75
+ }
76
+
77
+ let index = Math.floor(received / chunkSize);
78
+ await writeMeta({ total, received, complete: false });
79
+ onProgress({ phase: "download", loaded: received, total });
80
+
81
+ const reader = res.body.getReader();
82
+ let pending = new Uint8Array(chunkSize);
83
+ let fill = 0;
84
+
85
+ for (;;) {
86
+ const { done, value } = await reader.read();
87
+ if (done) break;
88
+
89
+ let src = value;
90
+ while (src.length > 0) {
91
+ const take = Math.min(src.length, chunkSize - fill);
92
+ pending.set(src.subarray(0, take), fill);
93
+ fill += take;
94
+ src = src.subarray(take);
95
+
96
+ if (fill === chunkSize) {
97
+ await storage.putChunk(id, index++, pending.buffer);
98
+ received += fill;
99
+ fill = 0;
100
+ pending = new Uint8Array(chunkSize);
101
+ await writeMeta({ total, received, complete: false });
102
+ onProgress({ phase: "download", loaded: received, total });
103
+ }
104
+ }
105
+ }
106
+
107
+ if (fill > 0) {
108
+ await storage.putChunk(id, index++, pending.buffer.slice(0, fill));
109
+ received += fill;
110
+ }
111
+
112
+ await writeMeta({ total: total || received, received, complete: true });
113
+ onProgress({ phase: "download", loaded: received, total: total || received, complete: true });
114
+ return storage.getMeta(id);
115
+ }
index.html ADDED
@@ -0,0 +1,1085 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>llm.js on current llama.cpp — browser demo (WASM, CPU)</title>
7
+ <style>
8
+ :root { color-scheme: dark; }
9
+ body { font: 15px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; background: #14161a; color: #e6e6e6;
10
+ max-width: 1080px; margin: 0 auto; padding: 20px 20px 64px; }
11
+ h1 { font-size: 19px; font-weight: 600; margin: 0 0 4px; }
12
+ h2 { font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacing: .06em;
13
+ color: #9aa1ab; margin: 0 0 10px; }
14
+ h3 { font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: .06em;
15
+ color: #7f8792; margin: 0 0 6px; }
16
+ small, .muted, .hint { color: #8a8f98; }
17
+ .hint { font-size: 12px; margin: 0 0 10px; }
18
+ section.panel { border: 1px solid #2a2f37; border-radius: 10px; margin: 0 0 16px;
19
+ padding: 14px 16px; background: #171a1f; }
20
+ input[type=text], input[type=password], textarea, select {
21
+ width: 100%; box-sizing: border-box; background: #0d0f12; color: #e6e6e6;
22
+ border: 1px solid #2a2f37; border-radius: 6px; padding: 8px 10px; font: inherit; }
23
+ textarea { min-height: 84px; resize: vertical; }
24
+ label.row { display: flex; align-items: center; gap: 8px; margin: 10px 0 0; color: #cfd4da; }
25
+ label.row input[type=number] { width: 90px; background: #0d0f12; color: #e6e6e6; border: 1px solid #2a2f37;
26
+ border-radius: 6px; padding: 6px 8px; font: inherit; }
27
+ .buttons { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 12px; }
28
+ button { background: #2f6fed; color: #fff; border: 0; border-radius: 6px; padding: 8px 14px;
29
+ font: inherit; cursor: pointer; }
30
+ button.secondary { background: #2a2f37; color: #cfd4da; }
31
+ button.danger { background: #5a2530; color: #ffb4c0; }
32
+ button:disabled { opacity: .45; cursor: default; }
33
+ #bar { height: 8px; background: #0d0f12; border: 1px solid #2a2f37; border-radius: 999px; overflow: hidden; margin: 10px 0 8px; }
34
+ #barFill { height: 100%; width: 0%; background: linear-gradient(90deg, #2f6fed, #5aa0ff); transition: width .15s linear; }
35
+ #status { color: #9aa1ab; font-size: 13px; min-height: 20px; }
36
+ #out { white-space: pre-wrap; word-break: break-word; background: #0d0f12; border: 1px solid #2a2f37;
37
+ border-radius: 6px; padding: 12px; min-height: 140px; }
38
+ #stats { color: #8a8f98; font-size: 12px; margin-top: 10px; min-height: 18px; }
39
+ details { margin-top: 12px; }
40
+ summary { cursor: pointer; color: #9aa1ab; font-size: 13px; }
41
+ #log { max-height: 180px; overflow: auto; background: #0d0f12; border: 1px solid #2a2f37; border-radius: 6px;
42
+ padding: 8px 10px; margin-top: 8px; font-size: 12px; color: #8a8f98; white-space: pre-wrap; }
43
+ .pill { display: inline-block; padding: 1px 7px; border-radius: 999px; background: #23303f; color: #9cc3ff;
44
+ font-size: 11px; margin-left: 6px; }
45
+
46
+ /* --- top bar ---------------------------------------------------------- */
47
+ .appbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 12px; }
48
+ .appbar label { font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: #8a8f98; }
49
+ .appbar select { flex: 1 1 260px; width: auto; }
50
+ .appbar button { padding: 7px 12px; font-size: 13px; }
51
+ #currentModel { flex: 1 1 100%; font-size: 12px; }
52
+
53
+ /* --- tabs ------------------------------------------------------------- */
54
+ .tabs { display: flex; flex-wrap: wrap; gap: 4px; margin: 18px 0 0; border-bottom: 1px solid #2a2f37; }
55
+ .tab { background: transparent; color: #9aa1ab; border: 1px solid transparent; border-bottom: 0;
56
+ border-radius: 8px 8px 0 0; padding: 8px 14px; font-size: 13px; }
57
+ .tab.active { background: #171a1f; color: #e6e6e6; border-color: #2a2f37; margin-bottom: -1px; }
58
+ .tab:hover { color: #e6e6e6; }
59
+
60
+ /* --- chat playground -------------------------------------------------- */
61
+ .workspace { display: grid; grid-template-columns: minmax(0, 1fr) 268px; gap: 16px; align-items: start; margin-top: 16px; }
62
+ @media (max-width: 860px) { .workspace { grid-template-columns: minmax(0, 1fr); } }
63
+ .col-main { min-width: 0; }
64
+ .msg { display: grid; grid-template-columns: 96px minmax(0, 1fr) auto; gap: 8px; align-items: start;
65
+ border: 1px solid #232830; border-radius: 8px; padding: 8px; margin-bottom: 8px; background: #14171c; }
66
+ .msg select { padding: 5px 6px; font-size: 12px; }
67
+ .msg textarea { min-height: 62px; font-size: 13px; }
68
+ .msg .rowbtns { display: flex; flex-direction: column; gap: 4px; }
69
+ .msg .rowbtns button { padding: 3px 7px; font-size: 11px; }
70
+ .msg.streaming { border-color: #2f6fed; }
71
+ .msg.streaming textarea { color: #cfd4da; }
72
+ .msg .badge { display: none; }
73
+ .msg.streaming .badge { display: inline; color: #7aa9ff; font-size: 11px; margin-left: 6px; }
74
+ .msg.streaming select { opacity: .6; }
75
+ .pick { width: auto; flex: 0 0 auto; padding: 7px 8px; }
76
+
77
+ /* --- parameters rail -------------------------------------------------- */
78
+ .params { border: 1px solid #2a2f37; border-radius: 10px; padding: 12px 14px; background: #171a1f;
79
+ position: sticky; top: 12px; }
80
+ .params h2 { margin: 0 0 6px; }
81
+ .params h2 + .field { margin-top: 6px; }
82
+ .params h2:not(:first-child) { margin-top: 14px; padding-top: 12px; border-top: 1px solid #232830; }
83
+ .field { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 7px 0;
84
+ color: #bfc5cd; font-size: 12px; }
85
+ .field input[type=number] { width: 82px; background: #0d0f12; color: #e6e6e6; border: 1px solid #2a2f37;
86
+ border-radius: 6px; padding: 5px 7px; font: inherit; font-size: 12px; }
87
+ .field.wide { display: block; }
88
+ .field.wide textarea { margin-top: 5px; min-height: 58px; font-size: 12px; }
89
+
90
+ /* --- models tab ------------------------------------------------------- */
91
+ .add { border: 1px dashed #2a2f37; border-radius: 8px; padding: 10px 12px 4px; margin-bottom: 10px; }
92
+ .addrow { margin-bottom: 8px; }
93
+ .addrow.two { display: flex; gap: 8px; flex-wrap: wrap; }
94
+ .addrow.two > * { flex: 1 1 220px; min-width: 0; }
95
+ input[type=file] { color: #cfd4da; font: inherit; font-size: 13px; }
96
+ input[type=file]::file-selector-button { background: #2a2f37; color: #cfd4da; border: 0; border-radius: 6px;
97
+ padding: 6px 10px; margin-right: 10px; font: inherit; font-size: 13px; cursor: pointer; }
98
+
99
+ ul#models { list-style: none; margin: 12px 0 0; padding: 0; }
100
+ ul#models li.empty { color: #8a8f98; font-size: 13px; }
101
+ ul#models li.model { display: flex; flex-wrap: wrap; align-items: center; gap: 8px;
102
+ padding: 9px 8px; border-top: 1px solid #232830; font-size: 13px; border-radius: 6px; }
103
+ ul#models li.model:first-child { border-top: 0; }
104
+ ul#models li.model.current { background: #1a2129; }
105
+ ul#models input.name { flex: 0 1 200px; background: transparent; border: 1px solid transparent;
106
+ border-radius: 6px; padding: 3px 6px; color: #e6e6e6; font: inherit; font-weight: 600; }
107
+ ul#models input.name:hover, ul#models input.name:focus { border-color: #2a2f37; background: #0d0f12; }
108
+ ul#models .meta { color: #8a8f98; flex: 1 1 190px; }
109
+ ul#models .sha { color: #9cc3ff; font-size: 12px; flex: 0 0 auto; }
110
+ ul#models .sha.unknown { color: #6d747e; }
111
+ ul#models .sha.ok::after { content: " ✓"; color: #7ee2a8; }
112
+ ul#models .sha.bad { color: #ff9db0; }
113
+ ul#models .sha.bad::after { content: " ≠ expected"; }
114
+ ul#models button { padding: 3px 9px; font-size: 12px; }
115
+
116
+ /* --- template tab ----------------------------------------------------- */
117
+ #templateSource { min-height: 170px; font-size: 12px; margin-top: 8px; }
118
+ #templatePreview { white-space: pre-wrap; word-break: break-word; background: #0d0f12;
119
+ border: 1px solid #2a2f37; border-radius: 6px; padding: 10px; font-size: 12px;
120
+ color: #cfd4da; margin: 10px 0 0; max-height: 280px; overflow: auto; }
121
+ #templatePreview:empty { display: none; }
122
+
123
+ /* --- tool calls ------------------------------------------------------- */
124
+ .msg .head { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
125
+ .msg .toolid { font-size: 11px; padding: 3px 5px; }
126
+ .msg .toolcalls { grid-column: 1 / -1; margin-top: 4px; }
127
+ .tc-head { color: #7aa9ff; font-size: 11px; text-transform: uppercase; letter-spacing: .05em;
128
+ margin-bottom: 6px; }
129
+ .tc { border: 1px solid #2a2f37; border-radius: 8px; padding: 8px 10px; background: #12151a;
130
+ margin-bottom: 6px; }
131
+ .tc-title { color: #9cc3ff; font-size: 13px; font-weight: 600; }
132
+ .tc-meta { color: #6d747e; font-size: 11px; }
133
+ .tc-json { font-size: 12px; margin: 6px 0; }
134
+ .tc-json ul { list-style: none; margin: 0; padding-left: 14px; }
135
+ .tc-json .k { color: #9aa1ab; }
136
+ .tc-json .s { color: #9ad7a0; }
137
+ .tc-json .n { color: #ffd28f; }
138
+ .tc-json .b { color: #ff9db0; }
139
+ </style>
140
+ </head>
141
+ <body>
142
+ <h1>llm.js → latest llama.cpp <span class="pill">wasm32 · CPU · no WebGPU</span></h1>
143
+ <small>Same <code>LLM</code> API as llm.js, running current llama.cpp. Models live in a local library:
144
+ downloaded from a URL or read straight off your disk — never both.</small>
145
+
146
+ <div class="appbar">
147
+ <label for="modelSelect">model</label>
148
+ <select id="modelSelect" aria-label="model"></select>
149
+ <button id="loadSelected" disabled>Load</button>
150
+ <button id="reloadEngine" class="secondary" disabled
151
+ title="free the loaded model and the wasm backend, then load it again">Reload engine</button>
152
+ <button id="stop" class="danger" disabled title="stop generating, keeping what has arrived">Stop</button>
153
+ <div id="currentModel" class="muted"></div>
154
+ </div>
155
+ <div id="bar"><div id="barFill"></div></div>
156
+ <div id="status">idle</div>
157
+
158
+ <nav class="tabs" role="tablist">
159
+ <button class="tab active" data-tab="chat" role="tab" aria-selected="true">Chat playground</button>
160
+ <button class="tab" data-tab="completion" role="tab" aria-selected="false">Raw completion</button>
161
+ <button class="tab" data-tab="template" role="tab" aria-selected="false">Chat template</button>
162
+ <button class="tab" data-tab="models" role="tab" aria-selected="false">Models</button>
163
+ </nav>
164
+
165
+ <main>
166
+ <div class="workspace" id="workspace">
167
+ <div class="col-main">
168
+ <section class="panel" id="panel-chat">
169
+ <h2>chat completion</h2>
170
+ <p class="hint">This list <em>is</em> the conversation. Generate appends an assistant turn and streams
171
+ into it; Stop keeps whatever has already arrived and the turn stays editable.</p>
172
+ <div id="messages"></div>
173
+ <div class="buttons">
174
+ <select id="newRole" class="pick" aria-label="role for the new message">
175
+ <option value="user">user</option>
176
+ <option value="system">system</option>
177
+ <option value="assistant">assistant</option>
178
+ <option value="tool">tool</option>
179
+ </select>
180
+ <button id="addMessage" class="secondary">Add message</button>
181
+ <button id="resetConversation" class="secondary">Reset conversation</button>
182
+ </div>
183
+ <div class="buttons">
184
+ <button id="generateChat" disabled>Generate</button>
185
+ <button id="exportJson" class="secondary">Export JSON</button>
186
+ <button id="exportMd" class="secondary">Export Markdown</button>
187
+ </div>
188
+ </section>
189
+
190
+ <section class="panel" id="panel-completion" hidden>
191
+ <h2>raw completion</h2>
192
+ <p class="hint">No chat template: this text is the prompt, tokenized as typed. Completion models
193
+ usually expect a trailing space.</p>
194
+ <textarea id="prompt" class="prompt">Explain in two sentences why WebAssembly is useful for running an LLM in a browser.</textarea>
195
+ <div class="buttons">
196
+ <button id="run" disabled>Generate</button>
197
+ <button id="clear" class="secondary">Clear output</button>
198
+ </div>
199
+ <div id="out" class="out"></div>
200
+ </section>
201
+
202
+ <div id="stats"></div>
203
+ </div>
204
+
205
+ <aside class="params" id="paramsRail">
206
+ <h2>sampling</h2>
207
+ <label class="field">temperature <input type="number" id="temp" value="0.7" step="0.05" min="0" max="2"></label>
208
+ <label class="field">top_p <input type="number" id="topP" value="0.9" step="0.05" min="0" max="1"></label>
209
+ <label class="field">top_k <input type="number" id="topK" value="40" step="1" min="0"></label>
210
+ <label class="field">repetition penalty <input type="number" id="repeatPenalty" value="1.1" step="0.05" min="0" max="3"></label>
211
+ <label class="field">penalty window <input type="number" id="repeatLastN" value="32" step="1" min="0"></label>
212
+ <label class="field">seed <input type="number" id="seed" value="-1" step="1" title="-1 = random"></label>
213
+
214
+ <h2>limits</h2>
215
+ <label class="field">max new tokens <input type="number" id="maxTokens" value="96" step="1" min="1" max="2048"></label>
216
+ <label class="field wide">stop sequences
217
+ <textarea id="stopSequences" spellcheck="false" placeholder="one per line (&#92;n and &#92;t are expanded)"></textarea>
218
+ </label>
219
+ <h2>tools</h2>
220
+ <label class="field wide">tool definitions (OpenAI JSON)
221
+ <textarea id="tools" spellcheck="false" placeholder='[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}]'></textarea>
222
+ </label>
223
+ <p class="hint" style="margin-top:8px">Handed to the chat template. A reply that calls a tool is
224
+ parsed by the model's own parser and shown as JSON next to the assistant turn.</p>
225
+
226
+ <h2>thinking</h2>
227
+ <label class="row"><input type="checkbox" id="enableThinking"> enable_thinking</label>
228
+ <p class="hint" style="margin-top:6px">Writes the <code>enable_thinking</code> template parameter into
229
+ the parameters JSON on the Chat template tab.</p>
230
+ </aside>
231
+ </div>
232
+
233
+ <section class="panel" id="panel-template" hidden>
234
+ <h2>chat template</h2>
235
+ <p class="hint" id="templateInfo"></p>
236
+ <label class="row"><input type="checkbox" id="useModelTemplate" checked>
237
+ use the template shipped in the GGUF (Jinja)</label>
238
+ <textarea id="templateSource" spellcheck="false" placeholder="Jinja chat template source"></textarea>
239
+ <label class="field wide" style="margin-top:12px">template parameters (JSON)
240
+ <textarea id="templateKwargs" spellcheck="false"
241
+ placeholder='{"enable_thinking": true}'></textarea>
242
+ </label>
243
+ <p class="hint" style="margin-top:8px">Passed to the Jinja template as extra variables, e.g.
244
+ <code>enable_thinking</code> for MiniCPM / Qwen-style templates.</p>
245
+ <div class="buttons">
246
+ <button id="previewTemplate" class="secondary">Preview with the playground messages</button>
247
+ <button id="resetTemplate" class="secondary">Reset to the model's template</button>
248
+ </div>
249
+ <pre id="templatePreview"></pre>
250
+ </section>
251
+
252
+ <section class="panel" id="panel-models" hidden>
253
+ <h2>model library</h2>
254
+
255
+ <div class="add">
256
+ <h3>from a URL</h3>
257
+ <div class="addrow">
258
+ <input type="text" id="modelUrl"
259
+ value="https://huggingface.co/LiquidAI/LFM2.5-VL-450M-GGUF/resolve/main/LFM2.5-VL-450M-Q4_K_M.gguf">
260
+ </div>
261
+ <div class="addrow two">
262
+ <input type="text" id="urlName" placeholder="display name (optional — defaults to the file name)">
263
+ <input type="text" id="expectedSha" placeholder="expected sha256 (optional, to check against the publisher)">
264
+ </div>
265
+ <div class="buttons">
266
+ <button id="addUrl">Download &amp; load</button>
267
+ <button id="pause" class="secondary" disabled>Pause</button>
268
+ <button id="resume" class="secondary" disabled>Resume</button>
269
+ </div>
270
+ <p class="hint">Downloaded in 4 MiB chunks into IndexedDB: pausable, resumable, deletable.</p>
271
+ </div>
272
+
273
+ <div class="add">
274
+ <h3>from this computer</h3>
275
+ <div class="addrow two">
276
+ <input type="file" id="fileInput" accept=".gguf,application/octet-stream">
277
+ <input type="text" id="fileLabel" placeholder="display name (optional — defaults to the file name)">
278
+ </div>
279
+ <label class="row"><input type="checkbox" id="keepCopy">
280
+ keep a copy in browser storage</label>
281
+ <p class="hint">Left unchecked the file is read in 4 MiB slices at load time and never duplicated —
282
+ you only re-pick it after a reload. Checked, a copy is written to IndexedDB (one copy in total)
283
+ so the model survives a reload on its own.</p>
284
+ <div class="buttons">
285
+ <button id="addFile" disabled>Add &amp; load</button>
286
+ </div>
287
+ </div>
288
+
289
+ <div class="muted" id="quota" style="font-size:12px;margin-top:6px"></div>
290
+ <ul id="models"><li class="empty">no models yet — add one above</li></ul>
291
+
292
+ <details>
293
+ <summary>llama.cpp log</summary>
294
+ <div id="log"></div>
295
+ </details>
296
+ </section>
297
+ </main>
298
+
299
+ <script type="module">
300
+ import { LLM, MODELS } from "./llm.js";
301
+ import { action } from "./actions.js";
302
+ import { listModels, deleteModel, updateModel, storageEstimate } from "./storage.js";
303
+
304
+ const N_CTX = 512;
305
+ const $ = (id) => document.getElementById(id);
306
+ const fmt = (bytes) => {
307
+ if (!bytes && bytes !== 0) return "?";
308
+ const mib = bytes / 1048576;
309
+ return mib >= 1024 ? (mib / 1024).toFixed(2) + " GiB" : mib.toFixed(1) + " MiB";
310
+ };
311
+ const pct = (loaded, total) => (total ? Math.min(100, (loaded / total) * 100) : 0);
312
+
313
+ const statusText = (t) => { $("status").textContent = t; };
314
+ const log = (t) => {
315
+ const el = $("log");
316
+ el.textContent += t.endsWith("\n") ? t : t + "\n";
317
+ el.scrollTop = el.scrollHeight;
318
+ };
319
+ const setBar = (loaded, total) => { $("barFill").style.width = pct(loaded, total).toFixed(1) + "%"; };
320
+
321
+ let app = null;
322
+ let models = [];
323
+ let loadedId = null; // model currently in the wasm instance
324
+ let currentId = null; // model the user last asked to load
325
+ let pendingFile = null; // file picked for the "add" form
326
+ let reattachFor = null; // model id waiting for its file to be re-picked
327
+ const attached = new Map(); // model id -> File, this session only
328
+ let uiState = "idle";
329
+ let loadedTemplate = ""; // the Jinja source shipped in the loaded GGUF
330
+ let chatRow = null; // the assistant turn currently being streamed into
331
+
332
+ const BUSY = ["starting", "downloading", "copying", "hashing", "loading", "generating"];
333
+
334
+ // --- tabs -----------------------------------------------------------------
335
+
336
+ function showTab(name) {
337
+ for (const btn of document.querySelectorAll(".tab")) {
338
+ const on = btn.dataset.tab === name;
339
+ btn.classList.toggle("active", on);
340
+ btn.setAttribute("aria-selected", on ? "true" : "false");
341
+ }
342
+ const running = name === "chat" || name === "completion";
343
+ $("workspace").hidden = !running;
344
+ $("panel-chat").hidden = name !== "chat";
345
+ $("panel-completion").hidden = name !== "completion";
346
+ $("panel-template").hidden = name !== "template";
347
+ $("panel-models").hidden = name !== "models";
348
+ }
349
+
350
+ for (const btn of document.querySelectorAll(".tab")) {
351
+ btn.onclick = () => showTab(btn.dataset.tab);
352
+ }
353
+
354
+ function setState(state) {
355
+ uiState = state;
356
+ const busy = BUSY.includes(state);
357
+ $("addUrl").disabled = busy;
358
+ $("addFile").disabled = busy || !pendingFile;
359
+ $("pause").disabled = state !== "downloading";
360
+ $("resume").disabled = state !== "paused";
361
+ $("generateChat").disabled = busy || !loadedId;
362
+ $("run").disabled = busy || !loadedId;
363
+ $("stop").disabled = state !== "generating";
364
+ $("modelUrl").disabled = busy;
365
+ $("loadSelected").disabled = busy || !models.length;
366
+ $("reloadEngine").disabled = busy || !loadedId;
367
+ }
368
+
369
+ // --- parameters -----------------------------------------------------------
370
+
371
+ const num = (id, fallback) => {
372
+ const v = Number($(id).value);
373
+ return Number.isFinite(v) ? v : fallback;
374
+ };
375
+
376
+ // one per line; \n, \t and \r let a stop sequence span lines
377
+ function stopList() {
378
+ return $("stopSequences").value.split("\n")
379
+ .filter((line) => line.length > 0)
380
+ .map((line) => line.replace(/\\n/g, "\n").replace(/\\t/g, "\t").replace(/\\r/g, "\r"));
381
+ }
382
+
383
+ function templateOverride() {
384
+ return $("useModelTemplate").checked ? "" : $("templateSource").value;
385
+ }
386
+
387
+ function runParams() {
388
+ return {
389
+ max_token_len: Math.max(1, num("maxTokens", 96)),
390
+ temp: num("temp", 0.7),
391
+ top_p: num("topP", 0.9),
392
+ top_k: num("topK", 40),
393
+ repeat_penalty: num("repeatPenalty", 1.1),
394
+ repeat_last_n: num("repeatLastN", 32),
395
+ seed: num("seed", -1),
396
+ stop: stopList(),
397
+ context_size: N_CTX,
398
+ chat_template_source: templateOverride(),
399
+ tools: $("tools").value.trim(),
400
+ template_kwargs: $("templateKwargs").value.trim() || "{}",
401
+ };
402
+ }
403
+
404
+ // --- worker plumbing ------------------------------------------------------
405
+
406
+ function ensureApp() {
407
+ if (app) return app;
408
+
409
+ app = new LLM(
410
+ MODELS.GGUF_CPU,
411
+ {}, // no model yet: loads are driven by id
412
+ (info) => {
413
+ loadedId = info.model.id;
414
+ currentId = info.model.id;
415
+ const m = info.model;
416
+ loadedTemplate = info.chat_template || "";
417
+ $("currentModel").textContent = `${m.name}` + (m.sha256 ? ` · sha256 ${m.sha256.slice(0, 12)}…` : "");
418
+ $("templateSource").value = m.templateOverride || loadedTemplate;
419
+ $("useModelTemplate").checked = !m.templateOverride;
420
+ syncTemplateUI();
421
+ statusText(`model ready · ${m.name} · n_ctx=${info.n_ctx} · ` +
422
+ (loadedTemplate ? "chat template from the GGUF" : "no chat template"));
423
+ setBar(1, 1);
424
+ setState("ready");
425
+ refreshModels();
426
+ },
427
+ // tokens: into the streaming assistant turn, or into the completion box
428
+ (text) => {
429
+ if (chatRow) {
430
+ const ta = chatRow.querySelector(".content");
431
+ ta.value += text;
432
+ ta.scrollTop = ta.scrollHeight;
433
+ } else {
434
+ $("out").textContent += text;
435
+ }
436
+ },
437
+ (stats) => {
438
+ if (stats.mode === "chat" && chatRow) {
439
+ // the final text is authoritative: it has stop sequences removed and
440
+ // any held-back tail flushed
441
+ const ta = chatRow.querySelector(".content");
442
+ ta.value = stats.output ?? ta.value;
443
+ ta.readOnly = false;
444
+ chatRow.classList.remove("streaming");
445
+
446
+ // tool calls are structured data: the parser built for this prompt
447
+ // already split them out, so show them as JSON, not as text
448
+ const calls = stats.parsed && stats.parsed.tool_calls;
449
+ if (Array.isArray(calls) && calls.length) {
450
+ // the call markup itself is not transcript text: what the model said
451
+ // before calling is, and the call is shown as JSON instead
452
+ const said = stats.parsed.content;
453
+ ta.value = typeof said === "string" ? said.trimEnd() : ta.value;
454
+ chatRow.toolCalls = openAiToolCalls(calls);
455
+ renderToolCalls(chatRow, calls);
456
+ }
457
+ chatRow = null;
458
+ } else if (stats.mode !== "chat") {
459
+ $("out").textContent = stats.output ?? $("out").textContent;
460
+ }
461
+
462
+ const bits = [`${stats.tokens} tokens in ${(stats.ms / 1000).toFixed(2)}s ` +
463
+ `(${stats.tokens_per_second.toFixed(2)} tok/s)`];
464
+ if (stats.template_strategy) bits.push(`template: ${stats.template_strategy}`);
465
+ if (stats.interrupted) bits.push("stopped");
466
+ $("stats").textContent = bits.join(" · ");
467
+ setState("ready");
468
+ },
469
+ (err) => {
470
+ if (chatRow) {
471
+ chatRow.classList.remove("streaming");
472
+ chatRow.querySelector(".content").readOnly = false;
473
+ chatRow = null;
474
+ }
475
+ statusText("error: " + err);
476
+ log("ERROR: " + err);
477
+ setState(loadedId ? "ready" : "idle");
478
+ },
479
+ (p) => {
480
+ if (p.phase === "download") {
481
+ setState("downloading");
482
+ statusText(p.complete ? "downloaded, preparing…"
483
+ : `downloading ${fmt(p.loaded)} / ${fmt(p.total)} (${pct(p.loaded, p.total).toFixed(1)}%)`);
484
+ setBar(p.loaded, p.total);
485
+ } else if (p.phase === "copy") {
486
+ setState("copying");
487
+ statusText(`copying into browser storage ${fmt(p.loaded)} / ${fmt(p.total)}`);
488
+ setBar(p.loaded, p.total);
489
+ } else if (p.phase === "hash") {
490
+ setState("hashing");
491
+ statusText(`sha256 ${pct(p.loaded, p.total).toFixed(0)}% of ${fmt(p.total)}`);
492
+ setBar(p.loaded, p.total);
493
+ } else if (p.phase === "load") {
494
+ setState("loading");
495
+ statusText(`loading into wasm ${fmt(p.loaded)} / ${fmt(p.total)}`);
496
+ setBar(p.loaded, p.total);
497
+ }
498
+ },
499
+ (line) => log(line.trimEnd()),
500
+ );
501
+
502
+ app.on_event = (msg) => {
503
+ switch (msg.event) {
504
+ case action.MODEL_ADDED:
505
+ if (pendingFile && msg.model.source === "file") attached.set(msg.model.id, pendingFile);
506
+ pendingFile = null;
507
+ $("fileInput").value = "";
508
+ $("fileLabel").value = "";
509
+ refreshModels();
510
+ break;
511
+
512
+ case action.MODEL_UPDATED:
513
+ refreshModels();
514
+ break;
515
+
516
+ case action.PAUSED:
517
+ statusText("paused — progress is saved, press Resume to continue");
518
+ setState("paused");
519
+ refreshModels();
520
+ break;
521
+
522
+ case action.TEMPLATE_PREVIEW:
523
+ $("templatePreview").textContent = msg.text;
524
+ break;
525
+
526
+ case action.DELETED:
527
+ if (loadedId === msg.id) {
528
+ loadedId = null;
529
+ loadedTemplate = "";
530
+ $("currentModel").textContent = "";
531
+ $("templateSource").value = "";
532
+ syncTemplateUI();
533
+ }
534
+ if (currentId === msg.id) currentId = null;
535
+ attached.delete(msg.id);
536
+ statusText("deleted from the library");
537
+ refreshModels();
538
+ setState(loadedId ? "ready" : "idle");
539
+ break;
540
+ }
541
+ };
542
+
543
+ app.load_worker({ context_size: N_CTX, autoload: false });
544
+ return app;
545
+ }
546
+
547
+ // --- conversation ---------------------------------------------------------
548
+
549
+ const ROLES = ["system", "user", "assistant", "tool"];
550
+
551
+ function addMessageRow(role = "user", content = "", { streaming = false } = {}) {
552
+ const row = document.createElement("div");
553
+ row.className = "msg" + (streaming ? " streaming" : "");
554
+
555
+ row.toolCalls = null;
556
+
557
+ const sel = document.createElement("select");
558
+ sel.className = "role";
559
+ sel.setAttribute("aria-label", "role");
560
+ for (const r of ROLES) sel.appendChild(new Option(r, r));
561
+ sel.value = role;
562
+
563
+ // a tool result names the call it answers; every other role hides this
564
+ const toolid = document.createElement("input");
565
+ toolid.type = "text";
566
+ toolid.className = "toolid";
567
+ toolid.placeholder = "tool_call_id";
568
+ toolid.title = "which tool call this result answers";
569
+ toolid.hidden = role !== "tool";
570
+ sel.onchange = () => { toolid.hidden = sel.value !== "tool"; };
571
+
572
+ const ta = document.createElement("textarea");
573
+ ta.className = "content";
574
+ ta.spellcheck = false;
575
+ ta.value = content;
576
+ ta.readOnly = streaming;
577
+
578
+ const tools = document.createElement("div");
579
+ tools.className = "rowbtns";
580
+ for (const [act, label, title] of [["up", "↑", "move up"], ["down", "↓", "move down"], ["del", "✕", "remove"]]) {
581
+ const b = document.createElement("button");
582
+ b.className = act === "del" ? "danger" : "secondary";
583
+ b.dataset.act = act;
584
+ b.textContent = label;
585
+ b.title = title;
586
+ tools.appendChild(b);
587
+ }
588
+
589
+ const badge = document.createElement("span");
590
+ badge.className = "badge";
591
+ badge.textContent = "streaming…";
592
+
593
+ const head = document.createElement("div");
594
+ head.className = "head";
595
+ head.append(sel, toolid, badge);
596
+
597
+ row.append(head, ta, tools);
598
+ $("messages").appendChild(row);
599
+ row.scrollIntoView({ block: "nearest" });
600
+ return row;
601
+ }
602
+
603
+ $("messages").addEventListener("click", (e) => {
604
+ const btn = e.target.closest("button[data-act]");
605
+ if (!btn) return;
606
+ const row = btn.closest(".msg");
607
+ const act = btn.dataset.act;
608
+ if (act === "del") row.remove();
609
+ if (act === "up" && row.previousElementSibling) $("messages").insertBefore(row, row.previousElementSibling);
610
+ if (act === "down" && row.nextElementSibling) $("messages").insertBefore(row.nextElementSibling, row);
611
+ });
612
+
613
+ function readMessages() {
614
+ return [...$("messages").querySelectorAll(".msg")]
615
+ .map((row) => {
616
+ const role = row.querySelector(".role").value;
617
+ const content = row.querySelector(".content").value;
618
+ if (role === "tool") {
619
+ const id = (row.querySelector(".toolid")?.value || "").trim();
620
+ return id ? { role, content, tool_call_id: id } : { role, content };
621
+ }
622
+ if (row.toolCalls && row.toolCalls.length) {
623
+ return { role, content, tool_calls: row.toolCalls };
624
+ }
625
+ return { role, content };
626
+ })
627
+ .filter((m) => m.content.length > 0 || (m.tool_calls && m.tool_calls.length));
628
+ }
629
+
630
+ $("addMessage").onclick = () => addMessageRow($("newRole").value, "");
631
+
632
+ $("resetConversation").onclick = () => {
633
+ $("messages").innerHTML = "";
634
+ addMessageRow("user", "");
635
+ $("stats").textContent = "";
636
+ };
637
+
638
+ addMessageRow("user", "Explain in two sentences why WebAssembly is useful for running an LLM in a browser.");
639
+
640
+ // --- run ------------------------------------------------------------------
641
+
642
+ $("generateChat").onclick = () => {
643
+ if (!app) return;
644
+ const messages = readMessages();
645
+ if (!messages.length) { statusText("add a message first"); return; }
646
+
647
+ // the assistant turn is part of the transcript before the first token
648
+ chatRow = addMessageRow("assistant", "", { streaming: true });
649
+ $("stats").textContent = "generating…";
650
+ setState("generating");
651
+ app.run({ mode: "chat", messages, ...runParams() });
652
+ };
653
+
654
+ $("run").onclick = () => {
655
+ if (!app) return;
656
+ $("out").textContent = "";
657
+ $("stats").textContent = "generating…";
658
+ setState("generating");
659
+ app.run({ mode: "completion", prompt: $("prompt").value, ...runParams() });
660
+ };
661
+
662
+ $("stop").onclick = () => {
663
+ if (!app) return;
664
+ statusText("stopping — what arrived stays");
665
+ app.stop();
666
+ };
667
+
668
+ $("clear").onclick = () => { $("out").textContent = ""; $("stats").textContent = ""; };
669
+
670
+ // --- model library --------------------------------------------------------
671
+
672
+ const button = (label, cls, onClick) => {
673
+ const b = document.createElement("button");
674
+ b.textContent = label;
675
+ b.className = cls;
676
+ b.onclick = onClick;
677
+ return b;
678
+ };
679
+
680
+ function renderRow(m) {
681
+ const li = document.createElement("li");
682
+ li.className = "model" + (m.id === loadedId ? " current" : "");
683
+ li.dataset.id = m.id;
684
+
685
+ const name = document.createElement("input");
686
+ name.className = "name";
687
+ name.value = m.name;
688
+ name.title = "display name — edit, then press Enter";
689
+ name.onchange = async () => {
690
+ const value = name.value.trim();
691
+ if (!value || value === m.name) { name.value = m.name; return; }
692
+ await updateModel(m.id, { name: value });
693
+ log(`renamed ${m.name} → ${value}`);
694
+ refreshModels();
695
+ };
696
+
697
+ const meta = document.createElement("span");
698
+ meta.className = "meta";
699
+ const bits = [m.source === "url" ? "url" : "local file", fmt(m.total || m.received || 0)];
700
+ if (m.source === "url" && !m.complete) bits.push("partial");
701
+ if (m.source === "file") {
702
+ bits.push(m.copied ? "copy in browser" : attached.has(m.id) ? "file attached" : "needs file");
703
+ }
704
+ meta.textContent = bits.join(" · ");
705
+ meta.title = m.url || m.fileName || "";
706
+
707
+ const sha = document.createElement("span");
708
+ sha.className = "sha";
709
+ if (m.sha256) {
710
+ sha.textContent = `sha256 ${m.sha256.slice(0, 16)}…`;
711
+ sha.title = m.sha256;
712
+ if (m.expectedSha256) sha.classList.add(m.expectedSha256 === m.sha256 ? "ok" : "bad");
713
+ } else {
714
+ sha.textContent = "sha256 not computed";
715
+ sha.classList.add("unknown");
716
+ }
717
+
718
+ li.append(name, meta, sha);
719
+ li.appendChild(button("load", "", () => startLoad(m)));
720
+ if (m.sha256) li.appendChild(button("copy hash", "secondary", () => copyHash(m)));
721
+ li.appendChild(button("delete", "danger", () => removeModel(m)));
722
+ return li;
723
+ }
724
+
725
+ async function refreshModels() {
726
+ models = await listModels().catch(() => []);
727
+ const ul = $("models");
728
+ ul.innerHTML = "";
729
+ if (!models.length) {
730
+ ul.innerHTML = '<li class="empty">no models yet — add one above</li>';
731
+ } else {
732
+ for (const m of models) ul.appendChild(renderRow(m));
733
+ }
734
+
735
+ const select = $("modelSelect");
736
+ const wanted = currentId || loadedId || "";
737
+ select.innerHTML = "";
738
+ if (!models.length) select.appendChild(new Option("no models yet", ""));
739
+ for (const m of models) {
740
+ const needsFile = m.source === "file" && !m.copied && !attached.has(m.id);
741
+ const label = `${m.name} · ${m.source === "url" ? "url" : "file"} · ` +
742
+ `${fmt(m.total || m.received || 0)}` +
743
+ (m.id === loadedId ? " · loaded" : needsFile ? " · needs file" : "");
744
+ select.appendChild(new Option(label, m.id));
745
+ }
746
+ select.value = wanted;
747
+
748
+ const est = await storageEstimate();
749
+ if (est && est.quota) {
750
+ $("quota").textContent = `browser storage: ${fmt(est.usage || 0)} used of ${fmt(est.quota)}` +
751
+ (models.length ? ` · ${fmt(models.reduce((n, m) => n + (m.source === "url" || m.copied ? m.received || 0 : 0), 0))} in this library` : "");
752
+ }
753
+ }
754
+
755
+ async function copyHash(m) {
756
+ try {
757
+ await navigator.clipboard.writeText(m.sha256);
758
+ statusText(`copied sha256 of ${m.name} to the clipboard`);
759
+ } catch (_) {
760
+ log(`sha256(${m.name}) = ${m.sha256}`);
761
+ statusText("clipboard unavailable — the hash is in the log");
762
+ }
763
+ }
764
+
765
+ async function removeModel(m) {
766
+ if (app) app.post({ event: action.DELETE_MODEL, id: m.id });
767
+ else { await deleteModel(m.id); refreshModels(); }
768
+ }
769
+
770
+ function selectedModel() {
771
+ const id = $("modelSelect").value;
772
+ return models.find((m) => m.id === id) || null;
773
+ }
774
+
775
+ // --- actions --------------------------------------------------------------
776
+
777
+ function startLoad(m) {
778
+ // a local file that was never copied needs its File again after a reload
779
+ if (m.source === "file" && !m.copied && !attached.has(m.id)) {
780
+ reattachFor = m.id;
781
+ statusText(`choose ${m.fileName} again — nothing is re-downloaded, the file stays on your disk`);
782
+ $("fileInput").click();
783
+ return;
784
+ }
785
+ ensureApp();
786
+ currentId = m.id;
787
+ $("out").textContent = "";
788
+ $("stats").textContent = "";
789
+ statusText("starting…");
790
+ setState("starting");
791
+ app.post({
792
+ event: action.LOAD,
793
+ id: m.id,
794
+ file: attached.get(m.id) || null,
795
+ context_size: N_CTX,
796
+ });
797
+ }
798
+
799
+ $("loadSelected").onclick = () => {
800
+ const m = selectedModel();
801
+ if (m) startLoad(m);
802
+ };
803
+
804
+ $("reloadEngine").onclick = () => {
805
+ if (!app || !currentId) return;
806
+ $("out").textContent = "";
807
+ $("stats").textContent = "";
808
+ statusText("freeing the model and reloading the engine…");
809
+ setState("starting");
810
+ app.reload(currentId);
811
+ };
812
+
813
+ $("fileInput").onchange = () => {
814
+ const file = $("fileInput").files[0];
815
+ if (!file) return;
816
+
817
+ if (reattachFor) {
818
+ const id = reattachFor;
819
+ reattachFor = null;
820
+ const m = models.find((x) => x.id === id);
821
+ if (m && file.size !== m.total) log(`note: ${file.name} is ${fmt(file.size)}, the record says ${fmt(m.total)}`);
822
+ attached.set(id, file);
823
+ log(`re-attached ${file.name}`);
824
+ if (m) startLoad(m);
825
+ return;
826
+ }
827
+
828
+ pendingFile = file;
829
+ if (!$("fileLabel").value) $("fileLabel").placeholder = file.name;
830
+ statusText(`${file.name} · ${fmt(file.size)} — press "Add & load"`);
831
+ setState(uiState);
832
+ };
833
+
834
+ $("addFile").onclick = () => {
835
+ const file = pendingFile || $("fileInput").files[0];
836
+ if (!file) return;
837
+ ensureApp();
838
+ $("out").textContent = "";
839
+ $("stats").textContent = "";
840
+ statusText("starting…");
841
+ setState("starting");
842
+ app.post({
843
+ event: action.ADD_FILE,
844
+ file,
845
+ name: $("fileLabel").value.trim(),
846
+ keepCopy: $("keepCopy").checked,
847
+ expectedSha256: $("expectedSha").value.trim().toLowerCase(),
848
+ context_size: N_CTX,
849
+ });
850
+ };
851
+
852
+ $("addUrl").onclick = () => {
853
+ const url = $("modelUrl").value.trim();
854
+ if (!url) return;
855
+ ensureApp();
856
+ $("out").textContent = "";
857
+ $("stats").textContent = "";
858
+ statusText("starting…");
859
+ setState("starting");
860
+ app.post({
861
+ event: action.ADD_URL,
862
+ url,
863
+ name: $("urlName").value.trim(),
864
+ expectedSha256: $("expectedSha").value.trim().toLowerCase(),
865
+ context_size: N_CTX,
866
+ });
867
+ };
868
+
869
+ $("pause").onclick = () => {
870
+ if (app) { app.pause(); statusText("pausing…"); }
871
+ };
872
+
873
+ $("resume").onclick = () => {
874
+ if (!app) return;
875
+ statusText("resuming…");
876
+ setState("downloading");
877
+ app.resume();
878
+ };
879
+
880
+ // --- chat template tab ----------------------------------------------------
881
+
882
+ function syncTemplateUI() {
883
+ const useModel = $("useModelTemplate").checked;
884
+ $("templateSource").readOnly = useModel;
885
+ $("templateSource").style.opacity = useModel ? 0.7 : 1;
886
+ $("templateInfo").textContent = useModel
887
+ ? (loadedTemplate
888
+ ? "chat completion renders the template shipped in this GGUF, through the Jinja engine compiled into the wasm build"
889
+ : "this model carries no chat template — chat completion falls back to a preset, then to plain text")
890
+ : "chat completion renders your override; the model's own template is ignored";
891
+ $("resetTemplate").disabled = !loadedTemplate;
892
+ }
893
+
894
+ $("useModelTemplate").onchange = () => {
895
+ if ($("useModelTemplate").checked && loadedTemplate) $("templateSource").value = loadedTemplate;
896
+ syncTemplateUI();
897
+ };
898
+
899
+ $("resetTemplate").onclick = () => {
900
+ $("templateSource").value = loadedTemplate;
901
+ $("useModelTemplate").checked = true;
902
+ syncTemplateUI();
903
+ };
904
+
905
+ $("previewTemplate").onclick = () => {
906
+ if (!app) { statusText("load a model first"); return; }
907
+ $("templatePreview").textContent = "rendering…";
908
+ app.preview_template({
909
+ messages: readMessages(),
910
+ prompt: $("prompt").value,
911
+ template_source: templateOverride(),
912
+ tools: $("tools").value.trim(),
913
+ template_kwargs: $("templateKwargs").value.trim() || "{}",
914
+ });
915
+ };
916
+
917
+ // --- tool calls, template params, conversation export ---------------------
918
+
919
+ function openAiToolCalls(calls) {
920
+ return calls.map((c, i) => ({
921
+ id: c.id || `call_${i}`,
922
+ type: "function",
923
+ function: {
924
+ name: c.name,
925
+ arguments: typeof c.arguments === "string" ? c.arguments : JSON.stringify(c.arguments ?? {}),
926
+ },
927
+ }));
928
+ }
929
+
930
+ // small local JSON tree: no CDN, the lab keeps working offline
931
+ function renderJson(value, parent) {
932
+ const leaf = (text, cls) => {
933
+ const s = document.createElement("span");
934
+ s.className = cls;
935
+ s.textContent = text;
936
+ parent.appendChild(s);
937
+ };
938
+
939
+ if (value === null) { leaf("null", "b"); return; }
940
+ if (Array.isArray(value)) {
941
+ const list = document.createElement("ul");
942
+ value.forEach((v, i) => {
943
+ const li = document.createElement("li");
944
+ const key = document.createElement("span");
945
+ key.className = "k";
946
+ key.textContent = `${i}: `;
947
+ li.appendChild(key);
948
+ renderJson(v, li);
949
+ list.appendChild(li);
950
+ });
951
+ parent.appendChild(list);
952
+ return;
953
+ }
954
+ if (typeof value === "object") {
955
+ const list = document.createElement("ul");
956
+ for (const [k, v] of Object.entries(value)) {
957
+ const li = document.createElement("li");
958
+ const key = document.createElement("span");
959
+ key.className = "k";
960
+ key.textContent = `${k}: `;
961
+ li.appendChild(key);
962
+ renderJson(v, li);
963
+ list.appendChild(li);
964
+ }
965
+ parent.appendChild(list);
966
+ return;
967
+ }
968
+ if (typeof value === "string") leaf(`"${value}"`, "s");
969
+ else if (typeof value === "number") leaf(String(value), "n");
970
+ else leaf(String(value), "b");
971
+ }
972
+
973
+ function renderToolCalls(row, calls) {
974
+ const box = document.createElement("div");
975
+ box.className = "toolcalls";
976
+
977
+ const head = document.createElement("div");
978
+ head.className = "tc-head";
979
+ head.textContent = `${calls.length} tool call${calls.length > 1 ? "s" : ""} parsed by the model's parser`;
980
+ box.appendChild(head);
981
+
982
+ for (const call of calls) {
983
+ const card = document.createElement("div");
984
+ card.className = "tc";
985
+
986
+ const title = document.createElement("div");
987
+ title.className = "tc-title";
988
+ title.textContent = call.name;
989
+
990
+ const meta = document.createElement("div");
991
+ meta.className = "tc-meta";
992
+ meta.textContent = call.id || "no id from the template";
993
+
994
+ const tree = document.createElement("div");
995
+ tree.className = "tc-json";
996
+ renderJson(call.arguments, tree);
997
+
998
+ const add = document.createElement("button");
999
+ add.className = "secondary";
1000
+ add.textContent = "Add tool response";
1001
+ add.onclick = () => {
1002
+ const toolRow = addMessageRow("tool", "");
1003
+ if (call.id) toolRow.querySelector(".toolid").value = call.id;
1004
+ toolRow.querySelector(".content").focus();
1005
+ toolRow.scrollIntoView({ block: "nearest" });
1006
+ };
1007
+
1008
+ card.append(title, meta, tree, add);
1009
+ box.appendChild(card);
1010
+ }
1011
+ row.appendChild(box);
1012
+ }
1013
+
1014
+ // --- exports --------------------------------------------------------------
1015
+
1016
+ function download(name, text, type) {
1017
+ const url = URL.createObjectURL(new Blob([text], { type }));
1018
+ const a = document.createElement("a");
1019
+ a.href = url;
1020
+ a.download = name;
1021
+ a.click();
1022
+ setTimeout(() => URL.revokeObjectURL(url), 2000);
1023
+ }
1024
+
1025
+ function stamp() {
1026
+ const d = new Date();
1027
+ const p = (n) => String(n).padStart(2, "0");
1028
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-` +
1029
+ `${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
1030
+ }
1031
+
1032
+ function toMarkdown(messages) {
1033
+ const out = [];
1034
+ for (const m of messages) {
1035
+ const suffix = m.role === "tool" && m.tool_call_id ? ` (${m.tool_call_id})` : "";
1036
+ out.push(`### ${m.role.toUpperCase()}${suffix}\n`);
1037
+ if (m.content) out.push(m.content.trimEnd() + "\n");
1038
+ if (m.tool_calls && m.tool_calls.length) {
1039
+ out.push("**Tool calls**\n");
1040
+ out.push("```json\n" + JSON.stringify(m.tool_calls, null, 2) + "\n```\n");
1041
+ }
1042
+ out.push("");
1043
+ }
1044
+ return out.join("\n");
1045
+ }
1046
+
1047
+ $("exportJson").onclick = () => {
1048
+ const messages = readMessages();
1049
+ if (!messages.length) { statusText("nothing to export"); return; }
1050
+ download(`conversation-${stamp()}.json`, JSON.stringify(messages, null, 2), "application/json");
1051
+ statusText(`exported ${messages.length} messages as JSON`);
1052
+ };
1053
+
1054
+ $("exportMd").onclick = () => {
1055
+ const messages = readMessages();
1056
+ if (!messages.length) { statusText("nothing to export"); return; }
1057
+ download(`conversation-${stamp()}.md`, toMarkdown(messages), "text/markdown");
1058
+ statusText(`exported ${messages.length} messages as Markdown`);
1059
+ };
1060
+
1061
+ // --- static template parameters ------------------------------------------
1062
+
1063
+ function readKwargs() {
1064
+ try {
1065
+ const kw = JSON.parse($("templateKwargs").value || "{}");
1066
+ return kw && typeof kw === "object" && !Array.isArray(kw) ? kw : {};
1067
+ } catch (_) {
1068
+ return {};
1069
+ }
1070
+ }
1071
+
1072
+ $("enableThinking").onchange = () => {
1073
+ const kw = readKwargs();
1074
+ if ($("enableThinking").checked) kw.enable_thinking = true;
1075
+ else delete kw.enable_thinking;
1076
+ $("templateKwargs").value = JSON.stringify(kw, null, 2);
1077
+ };
1078
+
1079
+ $("templateKwargs").value = "{}";
1080
+
1081
+ setState("idle");
1082
+ refreshModels();
1083
+ </script>
1084
+ </body>
1085
+ </html>
llm.js ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // llm.js-style wrapper around latest llama.cpp compiled to WASM.
2
+ //
3
+ // The public API is the one from rahuldshetty/llm.js:
4
+ // new LLM(type, url, init_callback, write_result_callback, on_complete_callback)
5
+ // app.load_worker(); app.run({ prompt, ... });
6
+ //
7
+ // Additions (all optional):
8
+ // on_error_callback(err), on_progress_callback({ phase, loaded, total, ... }),
9
+ // on_log_callback(line), on_event(message)
10
+ // app.add_url_model({ url, name, expected_sha256 })
11
+ // app.add_file_model({ file, name, keep_copy })
12
+ // app.pause() / app.resume() / app.delete_model(id) / app.list_models()
13
+ //
14
+ // Deviations from the original: models live in a local library (uuid record per
15
+ // model, see storage.js), so `url` became a target object { id, url, name }. A
16
+ // plain url string is still accepted and treated as `{ url }`.
17
+ //
18
+ // The two ingest paths (url, local file) produce the same record and are loaded
19
+ // by the same code path; only where the bytes come from differs.
20
+
21
+ import { action } from "./actions.js";
22
+
23
+ export const MODELS = {
24
+ GGUF_CPU: "GGUF_CPU",
25
+ };
26
+
27
+ class LLM {
28
+ constructor(
29
+ type,
30
+ target,
31
+ init_callback,
32
+ write_result_callback,
33
+ on_complete_callback,
34
+ on_error_callback,
35
+ on_progress_callback,
36
+ on_log_callback,
37
+ ) {
38
+ this.type = type;
39
+ this.model = typeof target === "string" ? { url: target } : (target || {});
40
+ this.init_callback = init_callback;
41
+ this.write_result_callback = write_result_callback;
42
+ this.on_complete_callback = on_complete_callback;
43
+ this.on_error_callback = on_error_callback;
44
+ this.on_progress_callback = on_progress_callback;
45
+ this.on_log_callback = on_log_callback;
46
+ this.on_event = null; // any message, e.g. PAUSED / DELETED / MODELS
47
+
48
+ this.worker = null;
49
+ this.model_loaded = false;
50
+ this.context_size = 2048;
51
+ this._pending = null;
52
+ }
53
+
54
+ get url() {
55
+ return this.model.url;
56
+ }
57
+
58
+ // autoload: post LOAD for this.model right away (the original behaviour);
59
+ // pass false to only start the worker and drive loads yourself
60
+ load_worker(options = {}) {
61
+ switch (this.type) {
62
+ case MODELS.GGUF_CPU:
63
+ this.worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
64
+ break;
65
+ default:
66
+ throw new Error(`unknown model type: ${this.type}`);
67
+ }
68
+
69
+ this.context_size = options.context_size || 2048;
70
+
71
+ this.worker.onmessage = (event) => {
72
+ const data = event.data;
73
+ if (this.on_event) this.on_event(data);
74
+
75
+ switch (data.event) {
76
+ case action.INITIALIZED:
77
+ this.model_loaded = true;
78
+ if (this.init_callback) this.init_callback(data);
79
+ this._flushPending();
80
+ break;
81
+
82
+ case action.WRITE_RESULT:
83
+ if (this.write_result_callback) this.write_result_callback(data.line);
84
+ break;
85
+
86
+ case action.RUN_COMPLETED:
87
+ if (this.on_complete_callback) this.on_complete_callback(data);
88
+ break;
89
+
90
+ case action.PROGRESS:
91
+ if (this.on_progress_callback) this.on_progress_callback(data);
92
+ break;
93
+
94
+ case action.LOG:
95
+ if (this.on_log_callback) this.on_log_callback(data.line);
96
+ break;
97
+
98
+ case action.ERROR:
99
+ if (this.on_error_callback) this.on_error_callback(data.error);
100
+ else console.error("llm.js:", data.error);
101
+ break;
102
+ }
103
+ };
104
+
105
+ const autoload = options.autoload !== false;
106
+ if (autoload && (this.model.id || this.model.url)) {
107
+ this.worker.postMessage({
108
+ event: action.LOAD,
109
+ id: this.model.id || null,
110
+ url: this.model.url || null,
111
+ context_size: this.context_size,
112
+ });
113
+ }
114
+ }
115
+
116
+ post(message) {
117
+ if (this.worker) this.worker.postMessage(message);
118
+ }
119
+
120
+ // download a GGUF and add it to the library (then load it)
121
+ add_url_model({ url, name = "", expected_sha256 = "", context_size = 0 } = {}) {
122
+ this.post({
123
+ event: action.ADD_URL,
124
+ url,
125
+ name,
126
+ expectedSha256: expected_sha256,
127
+ context_size: context_size || this.context_size,
128
+ });
129
+ }
130
+
131
+ // register a File the user already has; keep_copy decides whether the bytes
132
+ // are duplicated into IndexedDB (default: no, read them in place)
133
+ add_file_model({ file, name = "", keep_copy = false, expected_sha256 = "", context_size = 0 } = {}) {
134
+ this.post({
135
+ event: action.ADD_FILE,
136
+ file,
137
+ name,
138
+ keepCopy: keep_copy,
139
+ expectedSha256: expected_sha256,
140
+ context_size: context_size || this.context_size,
141
+ });
142
+ }
143
+
144
+ // load a model from the library by id
145
+ load(id, file = null) {
146
+ this.post({
147
+ event: action.LOAD,
148
+ id,
149
+ file,
150
+ context_size: this.context_size,
151
+ });
152
+ }
153
+
154
+ // free the engine and load the same model again
155
+ reload(id) {
156
+ this.post({ event: action.RELOAD_MODEL, id: id || this.model.id, context_size: this.context_size });
157
+ }
158
+
159
+ // render a prompt through a chat template without generating; the result
160
+ // arrives as a TEMPLATE_PREVIEW event
161
+ preview_template({ prompt, template_source = "", messages = null,
162
+ tools = "[]", template_kwargs = "{}" } = {}) {
163
+ this.post({
164
+ event: action.PREVIEW_TEMPLATE,
165
+ prompt,
166
+ template_source,
167
+ messages,
168
+ tools,
169
+ template_kwargs,
170
+ });
171
+ }
172
+
173
+ // stop a running generation; the text streamed so far is kept and the run
174
+ // completes with interrupted: true
175
+ stop() {
176
+ this.post({ event: action.STOP });
177
+ }
178
+
179
+ // resume an interrupted download / reload the same model
180
+ resume() {
181
+ this.post({ event: action.RESUME });
182
+ }
183
+
184
+ pause() {
185
+ this.post({ event: action.PAUSE });
186
+ }
187
+
188
+ // drop a model (or the current one) from the library
189
+ delete_model(id) {
190
+ const target = id || this.model.id;
191
+ if (target) this.post({ event: action.DELETE_MODEL, id: target });
192
+ }
193
+
194
+ hash_model(id) {
195
+ this.post({ event: action.HASH_MODEL, id: id || this.model.id });
196
+ }
197
+
198
+ list_models() {
199
+ this.post({ event: action.LIST_MODELS });
200
+ }
201
+
202
+ // mode "chat" runs a full message list through the chat template;
203
+ // mode "completion" sends the prompt text as-is
204
+ run({
205
+ mode = "completion",
206
+ prompt = "",
207
+ messages = null,
208
+ stop = [],
209
+ chat = false,
210
+ seed = -1,
211
+ max_token_len = 64,
212
+ top_k = 40,
213
+ top_p = 0.9,
214
+ temp = 0.7,
215
+ repeat_last_n = 32,
216
+ repeat_penalty = 1.1,
217
+ context_size = 0,
218
+ chat_template = "",
219
+ chat_template_source = "",
220
+ tools = "[]",
221
+ template_kwargs = "{}",
222
+ grammar = "",
223
+ json_schema = "",
224
+ regex = "",
225
+ } = {}) {
226
+ const msg = {
227
+ event: action.RUN_MAIN,
228
+ mode,
229
+ prompt,
230
+ messages,
231
+ stop,
232
+ chat,
233
+ seed,
234
+ max_token_len,
235
+ top_k,
236
+ top_p,
237
+ temp,
238
+ repeat_last_n,
239
+ repeat_penalty,
240
+ context_size,
241
+ chat_template,
242
+ chat_template_source,
243
+ tools,
244
+ template_kwargs,
245
+ grammar,
246
+ json_schema,
247
+ regex,
248
+ };
249
+
250
+ // allowed before the model finished loading, like the original docs suggest
251
+ if (!this.model_loaded) {
252
+ this._pending = msg;
253
+ return;
254
+ }
255
+ this.post(msg);
256
+ }
257
+
258
+ _flushPending() {
259
+ if (!this._pending) return;
260
+ const msg = this._pending;
261
+ this._pending = null;
262
+ this.post(msg);
263
+ }
264
+
265
+ terminate() {
266
+ if (this.worker) this.worker.terminate();
267
+ this.worker = null;
268
+ this.model_loaded = false;
269
+ }
270
+ }
271
+
272
+ export { LLM };
sha256.js ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Incremental SHA-256 (FIPS 180-4).
2
+ //
3
+ // crypto.subtle.digest() is one-shot: it wants the whole input as a single
4
+ // ArrayBuffer. A quantised GGUF is hundreds of MB (and can be several GB), so
5
+ // hashing it that way would mean holding the entire model in JS memory twice.
6
+ // This implementation takes the bytes 4 MiB at a time as they stream out of
7
+ // IndexedDB (or off the user's disk) and keeps a 64 byte block of state.
8
+ //
9
+ // Verified against node's crypto.createHash("sha256") in test/sha256-test.mjs,
10
+ // including every padding boundary and non-block-aligned streaming.
11
+
12
+ const K = new Uint32Array([
13
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
14
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
15
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
16
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
17
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
18
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
19
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
20
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
21
+ ]);
22
+
23
+ export class Sha256 {
24
+ constructor() {
25
+ this.h = new Uint32Array([
26
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
27
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
28
+ ]);
29
+ this.w = new Uint32Array(64);
30
+ this.block = new Uint8Array(64);
31
+ this.blockLen = 0;
32
+ this.bytes = 0;
33
+ this.finished = false;
34
+ }
35
+
36
+ update(data) {
37
+ if (this.finished) throw new Error("Sha256: update() after digest()");
38
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
39
+ const len = bytes.length;
40
+ this.bytes += len;
41
+
42
+ let off = 0;
43
+
44
+ // top up a partially filled block first
45
+ if (this.blockLen > 0) {
46
+ const need = 64 - this.blockLen;
47
+ if (len < need) {
48
+ this.block.set(bytes, this.blockLen);
49
+ this.blockLen += len;
50
+ return this;
51
+ }
52
+ this.block.set(bytes.subarray(0, need), this.blockLen);
53
+ this._compress(this.block, 0);
54
+ this.blockLen = 0;
55
+ off = need;
56
+ }
57
+
58
+ while (off + 64 <= len) {
59
+ this._compress(bytes, off);
60
+ off += 64;
61
+ }
62
+
63
+ if (off < len) {
64
+ this.block.set(bytes.subarray(off), 0);
65
+ this.blockLen = len - off;
66
+ }
67
+ return this;
68
+ }
69
+
70
+ _compress(buf, off) {
71
+ const w = this.w;
72
+ const h = this.h;
73
+
74
+ for (let i = 0; i < 16; i++) {
75
+ const j = off + i * 4;
76
+ w[i] = (buf[j] << 24) | (buf[j + 1] << 16) | (buf[j + 2] << 8) | buf[j + 3];
77
+ }
78
+ for (let i = 16; i < 64; i++) {
79
+ const a = w[i - 15];
80
+ const b = w[i - 2];
81
+ const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3);
82
+ const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10);
83
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
84
+ }
85
+
86
+ let a = h[0], b = h[1], c = h[2], d = h[3];
87
+ let e = h[4], f = h[5], g = h[6], k = h[7];
88
+
89
+ for (let i = 0; i < 64; i++) {
90
+ const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
91
+ const ch = (e & f) ^ (~e & g);
92
+ const t1 = (k + S1 + ch + K[i] + w[i]) | 0;
93
+ const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
94
+ const maj = (a & b) ^ (a & c) ^ (b & c);
95
+ const t2 = (S0 + maj) | 0;
96
+
97
+ k = g; g = f; f = e;
98
+ e = (d + t1) | 0;
99
+ d = c; c = b; b = a;
100
+ a = (t1 + t2) | 0;
101
+ }
102
+
103
+ h[0] = (h[0] + a) | 0;
104
+ h[1] = (h[1] + b) | 0;
105
+ h[2] = (h[2] + c) | 0;
106
+ h[3] = (h[3] + d) | 0;
107
+ h[4] = (h[4] + e) | 0;
108
+ h[5] = (h[5] + f) | 0;
109
+ h[6] = (h[6] + g) | 0;
110
+ h[7] = (h[7] + k) | 0;
111
+ }
112
+
113
+ // 64 hex characters, lowercase; the object is unusable afterwards
114
+ digestHex() {
115
+ if (this.finished) throw new Error("Sha256: digest() twice");
116
+ this.finished = true;
117
+
118
+ const tail = new Uint8Array(this.blockLen < 56 ? 64 : 128);
119
+ tail.set(this.block.subarray(0, this.blockLen));
120
+ tail[this.blockLen] = 0x80;
121
+
122
+ // message length in bits, as a 64-bit big-endian integer
123
+ const bits = this.bytes * 8;
124
+ const hi = Math.floor(bits / 4294967296);
125
+ const lo = bits % 4294967296;
126
+ const end = tail.length;
127
+ tail[end - 8] = (hi >>> 24) & 0xff;
128
+ tail[end - 7] = (hi >>> 16) & 0xff;
129
+ tail[end - 6] = (hi >>> 8) & 0xff;
130
+ tail[end - 5] = hi & 0xff;
131
+ tail[end - 4] = (lo >>> 24) & 0xff;
132
+ tail[end - 3] = (lo >>> 16) & 0xff;
133
+ tail[end - 2] = (lo >>> 8) & 0xff;
134
+ tail[end - 1] = lo & 0xff;
135
+
136
+ for (let off = 0; off < tail.length; off += 64) this._compress(tail, off);
137
+
138
+ let hex = "";
139
+ for (let i = 0; i < 8; i++) hex += (this.h[i] >>> 0).toString(16).padStart(8, "0");
140
+ return hex;
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Hash an async iterable of Uint8Array/ArrayBuffer chunks.
146
+ *
147
+ * @param {AsyncIterable<Uint8Array|ArrayBuffer>} source
148
+ * @param {(done:number)=>void} [onProgress] bytes hashed so far
149
+ * @returns {Promise<string>} lowercase hex digest
150
+ */
151
+ export async function sha256Chunks(source, onProgress) {
152
+ const hasher = new Sha256();
153
+ let done = 0;
154
+ for await (const chunk of source) {
155
+ const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
156
+ hasher.update(bytes);
157
+ done += bytes.length;
158
+ if (onProgress) onProgress(done);
159
+ }
160
+ return hasher.digestHex();
161
+ }
storage.js ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // IndexedDB model library.
2
+ //
3
+ // v2 layout (this file):
4
+ // models store, keyPath "id" -> one record per model, id = uuid
5
+ // modelChunks store, keyPath [modelId, index] -> { modelId, index, data: ArrayBuffer }
6
+ //
7
+ // Why a uuid primary key: one browser should hold many models, the same file may
8
+ // legitimately be registered twice under different names, and records must stay
9
+ // addressable after a rename. Nothing user-visible keys off the id.
10
+ //
11
+ // Why chunks instead of one blob:
12
+ // 1. pause/resume - a Range request continues from meta.received without
13
+ // rewriting hundreds of MB already stored;
14
+ // 2. loading - chunks stream straight into the Emscripten FS, so no second
15
+ // full-size buffer is assembled in JS memory;
16
+ // 3. hashing - the same generator feeds the SHA-256, 4 MiB at a time.
17
+ //
18
+ // A record with source "file" normally has *no* chunks: the bytes stay on the
19
+ // user's disk and are read in slices at load time. `copied` marks the opt-in
20
+ // case where the user asked for a copy to live in the browser instead.
21
+
22
+ export const DB_NAME = "llmjs-models";
23
+ export const DB_VERSION = 2;
24
+ export const CHUNK_SIZE = 4 * 1024 * 1024;
25
+
26
+ const MODEL_STORE = "models";
27
+ const CHUNK_STORE = "modelChunks";
28
+
29
+ let dbPromise = null;
30
+
31
+ export function newModelId() {
32
+ if (globalThis.crypto && typeof crypto.randomUUID === "function") return crypto.randomUUID();
33
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
34
+ return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
35
+ }
36
+
37
+ export function nameFromUrl(url) {
38
+ try {
39
+ const base = new URL(url, "http://localhost/").pathname.split("/").filter(Boolean).pop() || "model";
40
+ return base.replace(/\.gguf$/i, "");
41
+ } catch (_) {
42
+ return "model";
43
+ }
44
+ }
45
+
46
+ // --- v1 -> v2 ---------------------------------------------------------------
47
+ // v1 keyed records by url (out-of-line keys) and chunks by "url|00000000".
48
+ // Migration runs inside the versionchange transaction: copy the old stores into
49
+ // the new ones, then drop the old ones.
50
+ function migrateV1(db, tx, models, chunks) {
51
+ const v1meta = tx.objectStore("meta");
52
+ const v1chunks = tx.objectStore("chunks");
53
+ const ids = new Map();
54
+
55
+ const metaCursor = v1meta.openCursor();
56
+ metaCursor.onsuccess = () => {
57
+ const cursor = metaCursor.result;
58
+ if (cursor) {
59
+ const old = cursor.value || {};
60
+ const id = newModelId();
61
+ if (old.url) ids.set(old.url, id);
62
+ models.put({
63
+ id,
64
+ name: nameFromUrl(old.url || ""),
65
+ source: "url",
66
+ url: old.url || null,
67
+ fileName: null,
68
+ total: old.total || 0,
69
+ received: old.received || 0,
70
+ complete: !!old.complete,
71
+ copied: true, // v1 only ever stored downloaded bytes
72
+ sha256: null,
73
+ expectedSha256: null,
74
+ created: old.updated || Date.now(),
75
+ updated: old.updated || Date.now(),
76
+ });
77
+ cursor.continue();
78
+ return;
79
+ }
80
+
81
+ const chunkCursor = v1chunks.openCursor();
82
+ chunkCursor.onsuccess = () => {
83
+ const c = chunkCursor.result;
84
+ if (c) {
85
+ const key = String(c.key);
86
+ const bar = key.lastIndexOf("|");
87
+ const modelId = ids.get(key.slice(0, bar));
88
+ const index = Number(key.slice(bar + 1));
89
+ if (modelId !== undefined && Number.isFinite(index)) {
90
+ chunks.put({ modelId, index, data: c.value });
91
+ }
92
+ c.continue();
93
+ return;
94
+ }
95
+ db.deleteObjectStore("meta");
96
+ db.deleteObjectStore("chunks");
97
+ };
98
+ };
99
+ }
100
+
101
+ export function openDB() {
102
+ if (!dbPromise) {
103
+ dbPromise = new Promise((resolve, reject) => {
104
+ if (typeof indexedDB === "undefined") {
105
+ reject(new Error("IndexedDB is not available in this context"));
106
+ return;
107
+ }
108
+ const req = indexedDB.open(DB_NAME, DB_VERSION);
109
+ req.onupgradeneeded = (event) => {
110
+ const db = req.result;
111
+ const tx = req.transaction;
112
+ const models = db.objectStoreNames.contains(MODEL_STORE)
113
+ ? tx.objectStore(MODEL_STORE)
114
+ : db.createObjectStore(MODEL_STORE, { keyPath: "id" });
115
+ const chunks = db.objectStoreNames.contains(CHUNK_STORE)
116
+ ? tx.objectStore(CHUNK_STORE)
117
+ : db.createObjectStore(CHUNK_STORE, { keyPath: ["modelId", "index"] });
118
+ if (event.oldVersion === 1) migrateV1(db, tx, models, chunks);
119
+ };
120
+ req.onsuccess = () => resolve(req.result);
121
+ req.onerror = () => reject(req.error);
122
+ });
123
+ }
124
+ return dbPromise;
125
+ }
126
+
127
+ const result = (req) => new Promise((res, rej) => {
128
+ req.onsuccess = () => res(req.result);
129
+ req.onerror = () => rej(req.error);
130
+ });
131
+
132
+ const completed = (tx) => new Promise((res, rej) => {
133
+ tx.oncomplete = () => res();
134
+ tx.onerror = () => rej(tx.error);
135
+ tx.onabort = () => rej(tx.error);
136
+ });
137
+
138
+ const chunkRange = (modelId, from = 0) =>
139
+ IDBKeyRange.bound([modelId, from], [modelId, Number.MAX_SAFE_INTEGER]);
140
+
141
+ // --- models ----------------------------------------------------------------
142
+
143
+ export async function getModel(id) {
144
+ const db = await openDB();
145
+ return result(db.transaction(MODEL_STORE, "readonly").objectStore(MODEL_STORE).get(id));
146
+ }
147
+
148
+ export async function putModel(model) {
149
+ const db = await openDB();
150
+ const record = { ...model, updated: Date.now() };
151
+ const tx = db.transaction(MODEL_STORE, "readwrite");
152
+ tx.objectStore(MODEL_STORE).put(record);
153
+ await completed(tx);
154
+ return record;
155
+ }
156
+
157
+ export async function updateModel(id, patch) {
158
+ const model = await getModel(id);
159
+ if (!model) throw new Error(`unknown model ${id}`);
160
+ return putModel({ ...model, ...patch, id });
161
+ }
162
+
163
+ // most recently touched first
164
+ export async function listModels() {
165
+ const db = await openDB();
166
+ const all = await result(db.transaction(MODEL_STORE, "readonly").objectStore(MODEL_STORE).getAll());
167
+ return all.sort((a, b) => (b.updated || 0) - (a.updated || 0));
168
+ }
169
+
170
+ export async function findModelByUrl(url) {
171
+ const all = await listModels();
172
+ return all.find((m) => m.url === url);
173
+ }
174
+
175
+ // --- chunks ----------------------------------------------------------------
176
+
177
+ export async function putChunk(modelId, index, buffer) {
178
+ const db = await openDB();
179
+ const tx = db.transaction(CHUNK_STORE, "readwrite");
180
+ tx.objectStore(CHUNK_STORE).put({ modelId, index, data: buffer });
181
+ await completed(tx);
182
+ }
183
+
184
+ export async function getChunk(modelId, index) {
185
+ const db = await openDB();
186
+ const row = await result(db.transaction(CHUNK_STORE, "readonly").objectStore(CHUNK_STORE).get([modelId, index]));
187
+ return row ? row.data : undefined;
188
+ }
189
+
190
+ export async function chunkCount(modelId) {
191
+ const db = await openDB();
192
+ return result(db.transaction(CHUNK_STORE, "readonly").objectStore(CHUNK_STORE).count(chunkRange(modelId)));
193
+ }
194
+
195
+ // ascending chunk indexes currently stored for this model
196
+ export async function chunkIndexes(modelId) {
197
+ const db = await openDB();
198
+ const keys = await result(db.transaction(CHUNK_STORE, "readonly").objectStore(CHUNK_STORE).getAllKeys(chunkRange(modelId)));
199
+ return keys.map((k) => (Array.isArray(k) ? k[1] : Number(k))).sort((a, b) => a - b);
200
+ }
201
+
202
+ // Yields the stored bytes in order. Reads in small batches so the transaction
203
+ // is never held open across awaits (which would let it auto-commit) and so a
204
+ // 4 GB model never lands in memory as one buffer.
205
+ export async function* iterateChunks(modelId, batch = 4) {
206
+ let start = 0;
207
+ for (;;) {
208
+ const db = await openDB();
209
+ const rows = await result(
210
+ db.transaction(CHUNK_STORE, "readonly").objectStore(CHUNK_STORE)
211
+ .getAll(chunkRange(modelId, start), batch),
212
+ );
213
+ if (!rows.length) return;
214
+ const from = start;
215
+ for (let i = 0; i < rows.length; i++) {
216
+ yield { index: from + i, data: rows[i].data };
217
+ }
218
+ if (rows.length < batch) return;
219
+ start += rows.length;
220
+ }
221
+ }
222
+
223
+ export async function clearChunks(modelId) {
224
+ const db = await openDB();
225
+ const tx = db.transaction(CHUNK_STORE, "readwrite");
226
+ const store = tx.objectStore(CHUNK_STORE);
227
+ let deleted = 0;
228
+ const req = store.openCursor(chunkRange(modelId));
229
+ req.onsuccess = () => {
230
+ const cursor = req.result;
231
+ if (!cursor) return;
232
+ cursor.delete();
233
+ deleted++;
234
+ cursor.continue();
235
+ };
236
+ await completed(tx);
237
+ return deleted;
238
+ }
239
+
240
+ // --- lifecycle -------------------------------------------------------------
241
+
242
+ // removes the record and everything stored for it (the "delete" button)
243
+ export async function deleteModel(modelId) {
244
+ const chunks = await clearChunks(modelId);
245
+ const db = await openDB();
246
+ const tx = db.transaction(MODEL_STORE, "readwrite");
247
+ tx.objectStore(MODEL_STORE).delete(modelId);
248
+ await completed(tx);
249
+ return chunks;
250
+ }
251
+
252
+ export async function clearAll() {
253
+ const models = await listModels();
254
+ for (const m of models) await deleteModel(m.id);
255
+ return models.length;
256
+ }
257
+
258
+ export async function storageEstimate() {
259
+ if (navigator.storage && navigator.storage.estimate) {
260
+ try { return await navigator.storage.estimate(); } catch (_) { /* ignore */ }
261
+ }
262
+ return null;
263
+ }
wasm/llm-wasm.build.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ llama.cpp commit: f7591a6a01f9273de03331732bdc0b39721168be
2
+ llama.cpp subject: sycl: add f16 support for SWIGLU_OAI (#30857)
3
+ emcc: emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 7.0.0 (777e6e5db7b4990bcaeb1b9998ed642cc84e6629)
4
+ built: 2026-11-08T16:11:27Z
wasm/llm-wasm.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ async function createLLMWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import("node:module"));var require=createRequire(import.meta.url)}var thisProgram="./this.program";var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"])return Module["locateFile"](path,scriptDirectory);return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:"))scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?void 0:"utf8");return ret};if(process.argv.length>1)thisProgram=process.argv[1].replace(/\\/g,"/");process.argv.slice(2);0}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}if(ENVIRONMENT_IS_WORKER)readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)};readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok)return response.arrayBuffer();throw new Error(response.status+" : "+response.url)}}var out=console.log.bind(console);var err=console.error.bind(console);var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class CppException extends EmscriptenEH{constructor(excPtr){super();this.excPtr=excPtr}}function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);HEAPU8=new Uint8Array(b);HEAP32=new Int32Array(b);HEAPU32=new Uint32Array(b);HEAP64=new BigInt64Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun==="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){0;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["za"]();FS.ignorePermissions=false}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun==="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";throw new WebAssembly.RuntimeError(what)}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"])return locateFile("llm-wasm.wasm");return new URL("llm-wasm.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary)return readBinary(file);throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(true)try{return await readAsync(binaryFile)}catch{}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE)try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0)callbacks.shift()(Module)};var onPostRuns=[];var onPreRuns=[];var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var HEAPU8;var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{idx>>>=0;var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder)return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr));var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224)u0=(u0&15)<<12|u1<<6|u2;else u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63;if(u0<65536)str+=String.fromCharCode(u0);else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>{ptr>>>=0;return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):""};var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>>2>>>0]=type}get_type(){return HEAPU32[this.ptr+4>>>2>>>0]}set_destructor(destructor){HEAPU32[this.ptr+8>>>2>>>0]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>>2>>>0]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12>>>0]=caught}get_caught(){return HEAP8[this.ptr+12>>>0]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13>>>0]=rethrown}get_rethrown(){return HEAP8[this.ptr+13>>>0]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>>2>>>0]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>>2>>>0]}}var exceptionCaught=[];var uncaughtExceptionCount=0;var exceptionLast=null;var setTempRet0=val=>__emscripten_tempret_set(val);var findMatchingCatch=args=>{var thrown=exceptionLast?.excPtr;if(!thrown){setTempRet0(0);return 0}var info=new ExceptionInfo(thrown);info.set_adjusted_ptr(thrown);var thrownType=info.get_type();if(!thrownType){setTempRet0(0);return thrown}for(var caughtType of args){if(!caughtType||caughtType===thrownType)break;var adjusted_ptr_addr=info.ptr+16;if(___cxa_can_catch(caughtType,thrownType,adjusted_ptr_addr)){setTempRet0(caughtType);return thrown}}setTempRet0(thrownType);return thrown};var __Unwind_RaiseException=ex=>{throw ex};var __Unwind_Resume=ex=>{throw ex};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!=="undefined")Browser.init();for(var plugin of preloadPlugins)if(plugin["canHandle"](fullname))return plugin["handle"](byteArray,fullname);return byteArray};var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(filename).slice(1),normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last===".")parts.splice(i,1);else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot)for(;up;up--)parts.unshift("..");return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute)path=".";if(path&&trailingSlash)path+="/";return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir)return".";if(dir)dir=dir.slice(0,-1);return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!=="string")throw new TypeError("Arguments to path.resolve must be strings");else if(!path)return"";resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++)if(arr[start]!=="")break;var end=arr.length-1;for(;end>=0;end--)if(arr[end]!=="")break;if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++)if(fromParts[i]!==toParts[i]){samePartsLength=i;break}var outputParts=[];for(i=samePartsLength;i<fromParts.length;i++)outputParts.push("..");outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var dependenciesPromise=null;var dependenciesPromiseResolve=null;var resolveRunDependencies=async()=>dependenciesPromise;var runDependencies=0;var removeRunDependency=()=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(!runDependencies)dependenciesPromiseResolve()};var addRunDependency=()=>{if(!runDependencies)dependenciesPromise=new Promise(resolve=>dependenciesPromiseResolve=resolve);runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var getUniqueRunDependency=id=>id;var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;getUniqueRunDependency(`cp ${fullname}`);addRunDependency();try{var byteArray=url;if(typeof url==="string")byteArray=await asyncLoad(url);byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile)FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}finally{removeRunDependency()}};var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127)len++;else if(u<=2047)len+=2;else if(u<=65535)len+=3;else{len+=4;i++}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{outIdx>>>=0;if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++>>>0]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++>>>0]=192|u>>6;heap[outIdx++>>>0]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++>>>0]=224|u>>12;heap[outIdx++>>>0]=128|u>>6&63;heap[outIdx++>>>0]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++>>>0]=240|u>>18;heap[outIdx++>>>0]=128|u>>12&63;heap[outIdx++>>>0]=128|u>>6&63;heap[outIdx++>>>0]=128|u&63;i++}}heap[outIdx>>>0]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_fileDataToTypedArray=data=>{if(typeof data==="string")data=intArrayFromString(data,true);if(!data.subarray)data=new Uint8Array(data);return data};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=365;if(canWrite)mode|=146;return mode};var FS_modeStringToFlags=str=>{if(typeof str!=="string")return str;var flags={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[str];if(typeof flags==="undefined")throw new Error(`Unknown file open mode: ${str}`);return flags};var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var zeroMemory=(ptr,size)=>HEAPU8.fill(0,ptr,ptr+size);var mmapAlloc=size=>{size=alignMemory(size,65536);var ptr=_emscripten_builtin_memalign(65536,size);if(ptr)zeroMemory(ptr,size);return ptr};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode))throw new FS.ErrnoError(63);MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=MEMFS.emptyFileContents??=new Uint8Array(0)}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){return node.contents.subarray(0,node.usedBytes)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents.length;if(prevCapacity>=newCapacity)return;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<1048576?2:1.125)>>>0);if(prevCapacity)newCapacity=Math.max(newCapacity,256);var oldContents=MEMFS.getFileDataAsTypedArray(node);node.contents=new Uint8Array(newCapacity);node.contents.set(oldContents)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;var oldContents=node.contents;node.contents=new Uint8Array(newSize);node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)));node.usedBytes=newSize},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode))attr.size=4096;else if(FS.isFile(node.mode))attr.size=node.usedBytes;else if(FS.isLink(node.mode))attr.size=node.link.length;else attr.size=0;attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"])if(attr[key]!=null)node[key]=attr[key];if(attr.size!==void 0)MEMFS.resizeFileStorage(node,attr.size)},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node&&FS.isDir(old_node.mode))for(var i in new_node.contents)throw new FS.ErrnoError(55);delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents)throw new FS.ErrnoError(55);delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,41471,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode))throw new FS.ErrnoError(28);return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);buffer.set(contents.subarray(position,position+size),offset);return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer)canOwn=false;if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length}else if(!node.usedBytes&&!position){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length}else{MEMFS.expandFileStorage(node,position+length);node.contents.set(buffer.subarray(offset,offset+length),position);node.usedBytes=Math.max(node.usedBytes,position+length)}return length},llseek(stream,offset,whence){var position=offset;if(whence===1)position+=stream.position;else if(whence===2)if(FS.isFile(stream.node.mode))position+=stream.node.usedBytes;if(position<0)throw new FS.ErrnoError(28);return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode))throw new FS.ErrnoError(43);var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr)throw new FS.ErrnoError(48);if(contents){if(position>0||position+length<contents.length)if(contents.subarray)contents=contents.subarray(position,position+length);else contents=contents.slice(position,position+length);HEAP8.set(contents,ptr>>>0)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_stdin_getChar_buffer=[];var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var buf=Buffer.alloc(256);var bytesRead=0;try{bytesRead=fs.readSync(process.stdin.fd,buf,0,256)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0)result=buf.toString("utf-8",0,bytesRead)}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null)result+="\n"}if(!result)return null;FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty)throw new FS.ErrnoError(43);stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char)throw new FS.ErrnoError(60);var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===void 0&&!bytesRead)throw new FS.ErrnoError(6);if(result===null||result===void 0)break;bytesRead++;buffer[offset+i]=result;if(result===10)break}if(bytesRead)stream.node.atime=Date.now();return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char)throw new FS.ErrnoError(60);try{for(var i=0;i<length;i++)stream.tty.ops.put_char(stream.tty,buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}if(length)stream.node.mtime=stream.node.ctime=Date.now();return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else if(val!=0)tty.output.push(val)},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else if(val!=0)tty.output.push(val)},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>(nodeCrypto.randomFillSync(view),0)}return view=>(crypto.getRandomValues(view),0)};var randomFill=view=>(randomFill=initRandomFill())(view);var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:[],currentPath:"/",initialized:false,ignorePermissions:true,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent)parent=this;this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}addListener(cb,exclusive=false){var entry={cb,exclusive};var listeners=this.listeners??=new Set;listeners.add(entry);return{listeners,entry}}notifyListeners(flags){if(!this.listeners)return;var excl;for(var entry of this.listeners)if(entry.exclusive)(excl||=[]).push(entry);else entry.cb(flags);if(excl){var i=(this.exclTurn||0)%excl.length;this.exclTurn=i+1;excl[i].cb(flags)}}},lookupPath(path,opts={}){if(!path)throw new FS.ErrnoError(44);opts.follow_mount??=true;if(!PATH.isAbs(path))path=FS.cwd()+"/"+path;linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent)break;if(parts[i]===".")continue;if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else current=current.parent;continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay)return{path:current_path};throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount))current=current.mounted.root;if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink)throw new FS.ErrnoError(52);var link=current.node_ops.readlink(current);if(!PATH.isAbs(link))link=PATH.dirname(current_path)+"/"+link;path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++)hash=(hash<<5)-hash+name.charCodeAt(i)|0;return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node)FS.nameTable[hash]=node.name_next;else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode)throw new FS.ErrnoError(errCode);var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name)return node}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512)perms+="w";return perms},nodePermissions(node,perms){if(FS.ignorePermissions)return 0;if(perms.includes("r")&&!(node.mode&292))return 2;if(perms.includes("w")&&!(node.mode&146))return 2;if(perms.includes("x")&&!(node.mode&73))return 2;return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode))return 54;try{FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode)return errCode;if(isdir){if(!FS.isDir(node.mode))return 54;if(FS.isRoot(node)||FS.getPath(node)===FS.cwd())return 10}else if(FS.isDir(node.mode))return 31;return 0},mayOpen(node,flags){if(!node)return 44;if(FS.isLink(node.mode))return 32;var mode=FS.flagsToPermissionString(flags);if(FS.isDir(node.mode))if(mode!=="r"||flags&576)return 31;return FS.nodePermissions(node,mode)},checkOpExists(op,err){if(!op)throw new FS.ErrnoError(err);return op},nextfd(){for(var fd=0;fd<=4096;fd++)if(!FS.streams[fd])return fd;throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream)throw new FS.ErrnoError(8);return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1)fd=FS.nextfd();stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);try{setattr(arg,attr)}catch(e){if(e instanceof RangeError)throw new FS.ErrnoError(22);throw e}},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate==="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1)err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length)doCallback(null)}for(var mount of mounts)if(mount.type.syncfs)mount.type.syncfs(mount,populate,done);else done(null)},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root)throw new FS.ErrnoError(10);else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node))throw new FS.ErrnoError(10);if(!FS.isDir(node.mode))throw new FS.ErrnoError(54)}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root)FS.root=mountRoot;else if(node){node.mounted=mount;if(node.mount)node.mount.mounts.push(mount)}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node))throw new FS.ErrnoError(28);var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable))while(current){var next=current.name_next;if(mounts.includes(current.mount))FS.destroyNode(current);current=next}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name)throw new FS.ErrnoError(28);if(name==="."||name==="..")throw new FS.ErrnoError(20);var errCode=FS.mayCreate(parent,name);if(errCode)throw new FS.ErrnoError(errCode);if(!parent.node_ops.mknod)throw new FS.ErrnoError(63);return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs)Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root));return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=1023;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode=511){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev==="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath))throw new FS.ErrnoError(44);var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent)throw new FS.ErrnoError(44);var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode)throw new FS.ErrnoError(errCode);if(!parent.node_ops.symlink)throw new FS.ErrnoError(63);return parent.node_ops.symlink(parent,newname,oldpath)},link(oldpath,newpath,flags){var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent)throw new FS.ErrnoError(44);var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode)throw new FS.ErrnoError(errCode);if(!parent.node_ops.link)throw new FS.ErrnoError(34);return parent.node_ops.link(parent,newname,oldpath,flags)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount)throw new FS.ErrnoError(75);var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!==".")throw new FS.ErrnoError(28);relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!==".")throw new FS.ErrnoError(55);var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node)return;var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode)throw new FS.ErrnoError(errCode);errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode)throw new FS.ErrnoError(errCode);if(!old_dir.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node))throw new FS.ErrnoError(10);if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode)throw new FS.ErrnoError(errCode)}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);if(new_node)FS.hashRemoveNode(new_node);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode)throw new FS.ErrnoError(errCode);if(!parent.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(node))throw new FS.ErrnoError(10);parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent)throw new FS.ErrnoError(44);var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode)throw new FS.ErrnoError(errCode);if(!parent.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(node))throw new FS.ErrnoError(10);parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link)throw new FS.ErrnoError(44);if(!link.node_ops.readlink)throw new FS.ErrnoError(28);return link.node_ops.readlink(link)},stat(path,dontFollow=false){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow=false){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&-4096,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow=false){var node;if(typeof path==="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else node=path;FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow=false){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow=false){var node;if(typeof path==="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else node=path;FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode))throw new FS.ErrnoError(31);if(!FS.isFile(node.mode))throw new FS.ErrnoError(28);var errCode=FS.nodePermissions(node,"w");if(errCode)throw new FS.ErrnoError(errCode);FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0)throw new FS.ErrnoError(28);var node;if(typeof path==="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else node=path;FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0)throw new FS.ErrnoError(28);FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime,dontFollow=false){var lookup=FS.lookupPath(path,{follow:!dontFollow});FS.doSetAttr(null,lookup.node,{atime,mtime,dontFollow})},open(path,flags,mode=438){if(path==="")throw new FS.ErrnoError(44);flags=FS_modeStringToFlags(flags);if(flags&64)mode=mode&4095|32768;else mode=0;var node;var isDirPath;if(typeof path==="object")node=path;else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64)if(node){if(flags&128)throw new FS.ErrnoError(20)}else if(isDirPath)throw new FS.ErrnoError(31);else{node=FS.mknod(path,mode|511,0);created=true}if(!node)throw new FS.ErrnoError(44);if(FS.isChrdev(node.mode))flags&=-513;if(flags&65536&&!FS.isDir(node.mode))throw new FS.ErrnoError(54);if(!created){var errCode=FS.mayOpen(node,flags);if(errCode)throw new FS.ErrnoError(errCode)}if(flags&512&&!created)FS.truncate(node,0);flags&=-131713;var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open)stream.stream_ops.open(stream);if(created)FS.chmod(node,mode&511);return stream},close(stream){if(FS.isClosed(stream))throw new FS.ErrnoError(8);if(stream.getdents)stream.getdents=null;stream.node?.notifyListeners(32);try{if(stream.stream_ops.close)stream.stream_ops.close(stream)}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream))throw new FS.ErrnoError(8);if(!stream.seekable||!stream.stream_ops.llseek)throw new FS.ErrnoError(70);if(whence!=0&&whence!=1&&whence!=2)throw new FS.ErrnoError(28);stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0)throw new FS.ErrnoError(28);if(FS.isClosed(stream))throw new FS.ErrnoError(8);if((stream.flags&2097155)===1)throw new FS.ErrnoError(8);if(FS.isDir(stream.node.mode))throw new FS.ErrnoError(31);if(!stream.stream_ops.read)throw new FS.ErrnoError(28);var seeking=typeof position!=="undefined";if(!seeking)position=stream.position;else if(!stream.seekable)throw new FS.ErrnoError(70);var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0)throw new FS.ErrnoError(28);if(FS.isClosed(stream))throw new FS.ErrnoError(8);if((stream.flags&2097155)===0)throw new FS.ErrnoError(8);if(FS.isDir(stream.node.mode))throw new FS.ErrnoError(31);if(!stream.stream_ops.write)throw new FS.ErrnoError(28);if(stream.seekable&&stream.flags&1024)FS.llseek(stream,0,2);var seeking=typeof position!=="undefined";if(!seeking)position=stream.position;else if(!stream.seekable)throw new FS.ErrnoError(70);var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if(prot&2&&!(flags&2)&&(stream.flags&2097155)!==2)throw new FS.ErrnoError(2);if((stream.flags&2097155)===1)throw new FS.ErrnoError(2);if(!stream.stream_ops.mmap)throw new FS.ErrnoError(43);if(!length)throw new FS.ErrnoError(28);return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync)return 0;return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl)throw new FS.ErrnoError(59);return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags??=0;opts.encoding??="binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary")abort(`Invalid encoding type "${opts.encoding}"`);var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8")buf=UTF8ArrayToString(buf);FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags??=577;var stream=FS.open(path,opts.flags,opts.mode);data=FS_fileDataToTypedArray(data);FS.write(stream,data,0,data.byteLength,void 0,opts.canOwn);FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null)throw new FS.ErrnoError(44);if(!FS.isDir(lookup.node.mode))throw new FS.ErrnoError(54);var errCode=FS.nodePermissions(lookup.node,"x");if(errCode)throw new FS.ErrnoError(errCode);FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(!randomLeft){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input)FS.createDevice("/dev","stdin",input);else FS.symlink("/dev/tty","/dev/stdin");if(output)FS.createDevice("/dev","stdout",null,output);else FS.symlink("/dev/tty","/dev/stdout");if(error)FS.createDevice("/dev","stderr",null,error);else FS.symlink("/dev/tty1","/dev/stderr");FS.open("/dev/stdin",0);FS.open("/dev/stdout",1);FS.open("/dev/stderr",1)},staticInit(){FS.nameTable.length=4096;FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories()},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams)if(stream)FS.close(stream)},analyzePath(path,dontResolveLastLink=false){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent==="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent==="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent==="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){data=FS_fileDataToTypedArray(data);FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent==="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length)output(10)},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===void 0&&!bytesRead)throw new FS.ErrnoError(6);if(result===null||result===void 0)break;bytesRead++;buffer[offset+i]=result}if(bytesRead)stream.node.atime=Date.now();return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++)try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}if(length)stream.node.mtime=stream.node.ctime=Date.now();return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest)abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");else try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0)return;var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort(`Couldn't load ${url}. Status: ${xhr.status}`);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1048576;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort(`invalid range (${from}, ${to}) or no bytes requested!`);if(to>datalength-1)abort(`only ${datalength} bytes available! programmer error!`);var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range",`bytes=${from}-${to}`);xhr.responseType="arraybuffer";if(xhr.overrideMimeType)xhr.overrideMimeType("text/plain; charset=x-user-defined");xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort(`Couldn't load ${url}. Status: ${xhr.status}`);if(xhr.response!==void 0)return new Uint8Array(xhr.response||[]);return intArrayFromString(xhr.responseText??"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]==="undefined")lazyArray.chunks[chunkNum]=doXHR(start,end);if(typeof lazyArray.chunks[chunkNum]==="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown)this.cacheLength();return this._length}get chunkSize(){if(!this.lengthKnown)this.cacheLength();return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else properties={isDevice:false,url};var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents)node.contents=properties.contents;else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops))stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)};function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice)for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i];else for(i=0;i<size;i++)buffer[offset+i]=contents.get(position+i);return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr)throw new FS.ErrnoError(48);writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var HEAP16;var HEAP32;var HEAP64;var SYSCALLS={currentUmask:18,calculateAt(dirfd,path,allowEmpty=false){if(PATH.isAbs(path))return path;var dir;if(dirfd===-100)dir=FS.cwd();else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty)throw new FS.ErrnoError(44);return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>>2>>>0]=stat.dev;HEAPU32[buf+4>>>2>>>0]=stat.mode;HEAPU32[buf+8>>>2>>>0]=stat.nlink;HEAPU32[buf+12>>>2>>>0]=stat.uid;HEAPU32[buf+16>>>2>>>0]=stat.gid;HEAPU32[buf+20>>>2>>>0]=stat.rdev;HEAP64[buf+24>>>3>>>0]=BigInt(stat.size);HEAP32[buf+32>>>2>>>0]=4096;HEAP32[buf+36>>>2>>>0]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>>3>>>0]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>>2>>>0]=atime%1e3*1e3*1e3;HEAP64[buf+56>>>3>>>0]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>>2>>>0]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>>3>>>0]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>>2>>>0]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>>3>>>0]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>>2>>>0]=stats.bsize;HEAPU32[buf+60>>>2>>>0]=stats.bsize;HEAP64[buf+8>>>3>>>0]=BigInt(stats.blocks);HEAP64[buf+16>>>3>>>0]=BigInt(stats.bfree);HEAP64[buf+24>>>3>>>0]=BigInt(stats.bavail);HEAP64[buf+32>>>3>>>0]=BigInt(stats.files);HEAP64[buf+40>>>3>>>0]=BigInt(stats.ffree);HEAPU32[buf+48>>>2>>>0]=stats.fsid;HEAPU32[buf+64>>>2>>>0]=stats.flags;HEAPU32[buf+56>>>2>>>0]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode))throw new FS.ErrnoError(43);if(flags&2)return 0;var buffer=HEAPU8.subarray(addr>>>0,addr+len>>>0);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:void 0,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>>2>>>0];SYSCALLS.varargs+=4;return ret};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var bigintToI53Checked=num=>num<-9007199254740992||num>9007199254740992?NaN:Number(num);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var _emscripten_date_now=()=>Date.now();var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>4294901760;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var ENV={};var getExecutableName=()=>thisProgram;var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV)if(ENV[x]===void 0)delete env[x];else env[x]=ENV[x];var strings=[];for(var x in env)strings.push(`${x}=${env[x]}`);getEnvStrings.strings=strings}return getEnvStrings.strings};var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>>2>>>0];var len=HEAPU32[iov+4>>>2>>>0];iov+=8;try{var curr=FS.read(stream,HEAP8,ptr,len,offset)}catch(e){if(ret>0&&e instanceof FS.ErrnoError&&(e.errno==6||e.errno==6))break;throw e}if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!=="undefined")offset+=curr}return ret};var doWritev=(stream,iov,iovcnt,offset)=>{if(iovcnt==1)return FS.write(stream,HEAP8,HEAPU32[iov>>>2>>>0],HEAPU32[iov+4>>>2>>>0],offset);var total=0;for(var i=0,p=iov;i<iovcnt;i++,p+=8)total+=HEAPU32[p+4>>>2>>>0];var view=new Uint8Array(total);var voff=0;for(i=0;i<iovcnt;i++,iov+=8){var ptr=HEAPU32[iov>>>2>>>0];var len=HEAPU32[iov+4>>>2>>>0];view.set(HEAPU8.subarray(ptr>>>0,ptr+len>>>0),voff);voff+=len}return FS.write(stream,view,0,total,offset)};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func)wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr);return func};var getCFunc=ident=>{var func=Module["_"+ident];return func};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer>>>0)};var ccall=(ident,returnType,argTypes,args)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==void 0&&str!==0)ret=stringToUTF8OnStack(str);return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string")return UTF8ToString(ret);if(returnType==="pointer")return ret>>>0;if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args)for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(!stack)stack=stackSave();cArgs[i]=converter(args[i])}else cArgs[i]=args[i]}var ret=func(...cArgs);ret=function(ret){if(stack)stackRestore(stack);return convertReturnValue(ret)}(ret);return ret};var syscallGetVarargP=syscallGetVarargI;FS.createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};FS.preloadFile=FS_preloadFile;FS.staticInit();if(Module["noExitRuntime"])Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit==="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0)preInit.shift()()}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts)return getCFunc(ident);return(...args)=>ccall(ident,returnType,argTypes,args)};Module["UTF8ToString"]=UTF8ToString;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=(...args)=>FS.unlink(...args);Module["FS_createPath"]=(...args)=>FS.createPath(...args);Module["FS_createDevice"]=(...args)=>FS.createDevice(...args);Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=(...args)=>FS.createLazyFile(...args);var _emscripten_builtin_memalign,_setThrew,__emscripten_tempret_set,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___cxa_decrement_exception_refcount,___cxa_increment_exception_refcount,___cxa_can_catch,___cxa_get_exception_ptr,wasmMemory,wasmTable;function assignWasmExports(wasmExports){Module["_llmjs_init"]=wasmExports["Aa"];Module["_llmjs_version"]=wasmExports["Ba"];Module["_llmjs_create_context"]=wasmExports["Ca"];Module["_llmjs_load_model"]=wasmExports["Da"];Module["_llmjs_n_ctx"]=wasmExports["Fa"];Module["_llmjs_has_chat_template"]=wasmExports["Ga"];Module["_llmjs_chat_template"]=wasmExports["Ha"];Module["_llmjs_chat_template_name"]=wasmExports["Ia"];Module["_llmjs_set_chat_template_override"]=wasmExports["Ja"];Module["_llmjs_chat_template_effective"]=wasmExports["Ka"];Module["_llmjs_chat_template_strategy"]=wasmExports["La"];Module["_llmjs_last_error"]=wasmExports["Ma"];Module["_llmjs_chat_apply"]=wasmExports["Na"];Module["_llmjs_format_chat"]=wasmExports["Oa"];Module["_llmjs_tokenize_same"]=wasmExports["Pa"];Module["_llmjs_generate"]=wasmExports["Qa"];Module["_llmjs_set_stop_sequences"]=wasmExports["Ra"];Module["_llmjs_gen_begin_raw"]=wasmExports["Sa"];Module["_llmjs_gen_begin_chat"]=wasmExports["Ta"];Module["_llmjs_gen_step"]=wasmExports["Ua"];Module["_llmjs_gen_end"]=wasmExports["Va"];Module["_llmjs_last_output"]=wasmExports["Wa"];Module["_llmjs_parsed_output"]=wasmExports["Xa"];Module["_llmjs_parse_text"]=wasmExports["Ya"];Module["_llmjs_chat_apply_ex"]=wasmExports["Za"];Module["_llmjs_generate_chat"]=wasmExports["_a"];Module["_llmjs_free"]=wasmExports["$a"];Module["_free"]=wasmExports["ab"];Module["_malloc"]=wasmExports["bb"];_emscripten_builtin_memalign=wasmExports["cb"];_setThrew=wasmExports["db"];__emscripten_tempret_set=wasmExports["eb"];__emscripten_stack_restore=wasmExports["fb"];__emscripten_stack_alloc=wasmExports["gb"];_emscripten_stack_get_current=wasmExports["hb"];___cxa_decrement_exception_refcount=wasmExports["ib"];___cxa_increment_exception_refcount=wasmExports["jb"];___cxa_can_catch=wasmExports["kb"];___cxa_get_exception_ptr=wasmExports["lb"];wasmMemory=wasmExports["ya"];wasmTable=wasmExports["Ea"]}var wasmImports={ua:function(condition,filename,line,func){condition>>>=0;filename>>>=0;func>>>=0;return abort(`Assertion failed: ${UTF8ToString(condition)}, at: `+[filename?UTF8ToString(filename):"unknown filename",line,func?UTF8ToString(func):"unknown function"])},q:function(ptr){ptr>>>=0;var info=new ExceptionInfo(ptr);if(!info.get_caught()){info.set_caught(true);uncaughtExceptionCount--}info.set_rethrown(false);exceptionCaught.push(info);return ___cxa_get_exception_ptr(ptr)},G:function(){if(!exceptionCaught.length)return 0;var info=exceptionCaught[exceptionCaught.length-1];___cxa_increment_exception_refcount(info.excPtr);return info.excPtr},x:()=>{_setThrew(0,0);var info=exceptionCaught.pop();___cxa_decrement_exception_refcount(info.excPtr);exceptionLast=null},a:function(){return findMatchingCatch([])},i:function(arg0){arg0>>>=0;return findMatchingCatch([arg0])},J:function(arg0,arg1){arg0>>>=0;arg1>>>=0;return findMatchingCatch([arg0,arg1])},ta:function(arg0,arg1,arg2,arg3,arg4){arg0>>>=0;arg1>>>=0;arg2>>>=0;arg3>>>=0;arg4>>>=0;return findMatchingCatch([arg0,arg1,arg2,arg3,arg4])},W:()=>{if(!exceptionCaught.length)abort("no exception to throw");var info=exceptionCaught.at(-1);var ptr=info.excPtr;info.set_rethrown(true);info.set_caught(false);uncaughtExceptionCount++;___cxa_increment_exception_refcount(ptr);ptr=exceptionLast=new CppException(ptr);__Unwind_RaiseException(ptr)},aa:function(ptr){ptr>>>=0;if(!ptr)return;var info=new ExceptionInfo(ptr);info.set_rethrown(true);info.set_caught(false);uncaughtExceptionCount++;___cxa_increment_exception_refcount(ptr);ptr=exceptionLast=new CppException(ptr);__Unwind_RaiseException(ptr)},l:function(ptr,type,destructor){ptr>>>=0;type>>>=0;destructor>>>=0;var info=new ExceptionInfo(ptr);info.init(type,destructor);___cxa_increment_exception_refcount(ptr);ptr=exceptionLast=new CppException(ptr);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)},ba:()=>uncaughtExceptionCount,f:function(ptr){ptr>>>=0;ptr=exceptionLast??=new CppException(ptr);__Unwind_Resume(ptr)},S:function(fd,cmd,varargs){varargs>>>=0;SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:var arg=syscallGetVarargI();if(arg<0)return-28;while(FS.streams[arg])arg++;var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd;case 1:case 2:return 0;case 3:return stream.flags;case 4:arg=syscallGetVarargI();stream.flags=stream.flags&-289793|arg&289792;return 0;case 12:arg=syscallGetVarargP();HEAP16[arg+0>>>1>>>0]=2;return 0;case 13:case 14:return 0}return-28}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}},_:function(buf,size){buf>>>=0;size>>>=0;try{if(!size)return-28;var cwd=FS.cwd();var cwdLengthInBytes=lengthBytesUTF8(cwd)+1;if(size<cwdLengthInBytes)return-68;stringToUTF8(cwd,buf,size);return cwdLengthInBytes}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}},ca:function(fd,dirp,count){dirp>>>=0;count>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);stream.getdents||=FS.readdir(stream.path);var pos=0;var off=FS.llseek(stream,0,1);var startIdx=Math.floor(off/280);var endIdx=Math.min(stream.getdents.length,startIdx+Math.floor(count/280));for(var idx=startIdx;idx<endIdx;idx++){var id;var type;var name=stream.getdents[idx];if(name==="."){id=stream.node.id;type=4}else if(name===".."){var lookup=FS.lookupPath(stream.path,{parent:true});id=lookup.node.id;type=4}else{var child;try{child=FS.lookupNode(stream.node,name)}catch(e){if(e?.errno===28)continue;throw e}id=child.id;type=FS.isChrdev(child.mode)?2:FS.isDir(child.mode)?4:FS.isLink(child.mode)?10:8}HEAP64[dirp+pos>>>3>>>0]=BigInt(id);HEAP64[dirp+pos+8>>>3>>>0]=BigInt((idx+1)*280);HEAP16[dirp+pos+16>>>1>>>0]=280;HEAP8[dirp+pos+18>>>0]=type;stringToUTF8(name,dirp+pos+19,256);pos+=280}FS.llseek(stream,idx*280,0);return pos}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}},na:function(fd,op,varargs){varargs>>>=0;SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:if(!stream.tty)return-59;return 0;case 21505:if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>>2>>>0]=termios.c_iflag||0;HEAP32[argp+4>>>2>>>0]=termios.c_oflag||0;HEAP32[argp+8>>>2>>>0]=termios.c_cflag||0;HEAP32[argp+12>>>2>>>0]=termios.c_lflag||0;for(var i=0;i<32;i++)HEAP8[argp+i+17>>>0]=termios.c_cc[i]||0;return 0}return 0;case 21510:case 21511:case 21512:if(!stream.tty)return-59;return 0;case 21506:case 21507:case 21508:if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>>2>>>0];var c_oflag=HEAP32[argp+4>>>2>>>0];var c_cflag=HEAP32[argp+8>>>2>>>0];var c_lflag=HEAP32[argp+12>>>2>>>0];var c_cc=[];for(i=0;i<32;i++)c_cc.push(HEAP8[argp+i+17>>>0]);return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0;case 21519:if(!stream.tty)return-59;argp=syscallGetVarargP();HEAP32[argp>>>2>>>0]=0;return 0;case 21520:if(!stream.tty)return-59;return-28;case 21537:case 21531:argp=syscallGetVarargP();return FS.ioctl(stream,op,argp);case 21523:if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);argp=syscallGetVarargP();HEAP16[argp>>>1>>>0]=winsize[0];HEAP16[argp+2>>>1>>>0]=winsize[1]}return 0;case 21524:if(!stream.tty)return-59;return 0;case 21515:if(!stream.tty)return-59;return 0;default:return-28}}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}},T:function(dirfd,path,flags,varargs){path>>>=0;varargs>>>=0;SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;if(flags&64)mode&=~SYSCALLS.currentUmask;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}},Z:function(path,buf){path>>>=0;buf>>>=0;try{path=SYSCALLS.getStr(path);return SYSCALLS.writeStat(buf,FS.stat(path))}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}},qa:()=>abort(""),ha:function(time,tmPtr){time=bigintToI53Checked(time);tmPtr>>>=0;var date=new Date(time*1e3);if(isNaN(date.getTime()))return 1;HEAP32[tmPtr>>>2>>>0]=date.getSeconds();HEAP32[tmPtr+4>>>2>>>0]=date.getMinutes();HEAP32[tmPtr+8>>>2>>>0]=date.getHours();HEAP32[tmPtr+12>>>2>>>0]=date.getDate();HEAP32[tmPtr+16>>>2>>>0]=date.getMonth();HEAP32[tmPtr+20>>>2>>>0]=date.getFullYear()-1900;HEAP32[tmPtr+24>>>2>>>0]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>>2>>>0]=yday;HEAP32[tmPtr+36>>>2>>>0]=-date.getTimezoneOffset()*60;var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>>2>>>0]=dst;return 0},fa:function(len,prot,flags,fd,offset,allocated,addr){len>>>=0;offset=bigintToI53Checked(offset);allocated>>>=0;addr>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);var res=FS.mmap(stream,len,offset,prot,flags);var ptr=res.ptr;HEAP32[allocated>>>2>>>0]=res.allocated;HEAPU32[addr>>>2>>>0]=ptr;return 0}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}},ga:function(addr,len,prot,flags,fd,offset){addr>>>=0;len>>>=0;offset=bigintToI53Checked(offset);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2)SYSCALLS.doMsync(addr,stream,len,flags,offset)}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}},ia:function(timezone,daylight,std_name,dst_name){timezone>>>=0;daylight>>>=0;std_name>>>=0;dst_name>>>=0;var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>>2>>>0]=stdTimezoneOffset*60;HEAP32[daylight>>>2>>>0]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}},pa:function(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);ptime>>>=0;if(!checkWasiClock(clk_id))return 28;var now;if(clk_id===0)now=_emscripten_date_now();else if(1)now=_emscripten_get_now();else return 52;var nsec=Math.round(now*1e6);HEAP64[ptime>>>3>>>0]=BigInt(nsec);return 0},oa:_emscripten_date_now,ea:function(){return getHeapMax()},da:function(requestedSize){requestedSize>>>=0;var oldSize=HEAPU8.length;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize)return false;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement)return true}return false},la:function(__environ,environ_buf){__environ>>>=0;environ_buf>>>=0;var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>>2>>>0]=ptr;bufSize+=stringToUTF8(string,ptr,1/0)+1;envp+=4}return 0},ma:function(penviron_count,penviron_buf_size){penviron_count>>>=0;penviron_buf_size>>>=0;var strings=getEnvStrings();HEAPU32[penviron_count>>>2>>>0]=strings.length;var bufSize=0;for(var string of strings)bufSize+=lengthBytesUTF8(string)+1;HEAPU32[penviron_buf_size>>>2>>>0]=bufSize;return 0},H:function(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}},ka:function(fd,pbuf){pbuf>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);var type=stream.tty?2:FS.isDir(stream.mode)?3:FS.isLink(stream.mode)?7:4;HEAP8[pbuf>>>0]=type;HEAP16[pbuf+2>>>1>>>0]=0;HEAP64[pbuf+8>>>3>>>0]=BigInt(0);HEAP64[pbuf+16>>>3>>>0]=BigInt(0);return 0}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}},Q:function(fd,iov,iovcnt,pnum){iov>>>=0;iovcnt>>>=0;pnum>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>>2>>>0]=num;return 0}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}},ja:function(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);newOffset>>>=0;try{if(isNaN(offset))return 22;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>>3>>>0]=BigInt(stream.position);if(stream.getdents&&!offset&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}},R:function(fd,iov,iovcnt,pnum){iov>>>=0;iovcnt>>>=0;pnum>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>>2>>>0]=num;return 0}catch(e){if(typeof FS==="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}},w:function(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},X:function(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},O:function(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},P:function(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},p:function(index){var sp=stackSave();try{return getWasmTableEntry(index)()}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},va:function(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},wa:function(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},e:function(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},z:function(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},c:function(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},xa:function(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},L:function(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},g:function(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},o:function(index,a1,a2,a3,a4){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},t:function(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},v:function(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},E:function(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},V:function(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},F:function(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},$:function(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},s:function(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0);return 0n}},K:function(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0);return 0n}},I:function(index,a1,a2,a3,a4){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0);return 0n}},j:function(index){var sp=stackSave();try{getWasmTableEntry(index)()}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},m:function(index,a1){var sp=stackSave();try{getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},sa:function(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},d:function(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},b:function(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},h:function(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},k:function(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},n:function(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},u:function(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},U:function(index,a1,a2,a3,a4,a5,a6,a7,a8){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},ra:function(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},C:function(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},A:function(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},M:function(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},D:function(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},B:function(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}},y:function(level,s){var fn=globalThis.llmjs_on_log;if(fn)fn(level,UTF8ToString(s))},N:function(s){var fn=globalThis.llmjs_on_token;if(fn)fn(UTF8ToString(s))},r:function(type){type>>>=0;return type},Y:function(buffer,size){buffer>>>=0;size>>>=0;return randomFill(HEAPU8.subarray(buffer>>>0,buffer+size>>>0))}};function applySignatureConversions(wasmExports){var makeWrapper_pp=f=>a0=>f(a0)>>>0;var origExports=wasmExports;wasmExports={};wasmExports["bb"]=makeWrapper_pp(origExports["bb"]);wasmExports["cb"]=(f=>(a0,a1)=>f(a0,a1)>>>0)(origExports["cb"]);wasmExports["gb"]=makeWrapper_pp(origExports["gb"]);wasmExports["hb"]=(f=>()=>f()>>>0)(origExports["hb"]);wasmExports["lb"]=makeWrapper_pp(origExports["lb"]);Object.setPrototypeOf(wasmExports,origExports);return wasmExports}var wasmExports;wasmExports=await async function(){function receiveInstance(instance){wasmExports=instance.exports;wasmExports=applySignatureConversions(wasmExports);assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm)return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))});wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(void 0,wasmBinaryFile,info);var exports=function(result){return receiveInstance(result["instance"])}(result);return exports}();await async function(){preRun();if(runDependencies)await resolveRunDependencies();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}();
2
+ ;return Module}export default createLLMWasmModule;
wasm/llm-wasm.wasm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5374c9af01631377eee6f0bfd8f9284a4327ef8f85cb8d8e31cd0defc29359b5
3
+ size 5346255
worker.js ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Inference worker.
2
+ //
3
+ // Responsibilities:
4
+ // 1. add models - two ingest paths into one library:
5
+ // url -> resumable, pausable, chunked download
6
+ // file -> the user's own File, read in 4 MiB slices, never copied
7
+ // 2. sha256 each model once, so a human can compare it with the publisher's
8
+ // 3. stream the bytes into the Emscripten FS (from IndexedDB chunks, or
9
+ // straight off the local File)
10
+ // 4. load it with the C API and stream generated tokens back
11
+ //
12
+ // Both ingest paths end in the same kind of record, so loading, hashing,
13
+ // renaming and deleting are one code path (see storage.js for the schema).
14
+
15
+ import createLLMWasmModule from "./wasm/llm-wasm.js";
16
+ import { action } from "./actions.js";
17
+ import { downloadModel } from "./download.js";
18
+ import { sha256Chunks } from "./sha256.js";
19
+ import {
20
+ CHUNK_SIZE, getModel, putModel, updateModel, listModels, newModelId, nameFromUrl,
21
+ putChunk, iterateChunks, clearChunks, deleteModel, findModelByUrl,
22
+ } from "./storage.js";
23
+
24
+ let module = null;
25
+ let loaded = false;
26
+ let loadedId = null;
27
+ let currentNctx = 512;
28
+
29
+ // Files the page handed over in this session, by model id. A "file" model with
30
+ // no copy in IndexedDB needs its File again after a reload - see start().
31
+ const files = new Map();
32
+
33
+ let abort = null; // AbortController for the active download
34
+ let busy = false;
35
+ let lastRequest = null; // { id, context_size } so Resume can continue
36
+
37
+ const post = (msg) => self.postMessage(msg);
38
+ const progress = (p) => post({ event: action.PROGRESS, ...p });
39
+ const log = (line, level = 3) => post({ event: action.LOG, level, line });
40
+ const fail = (err) => post({ event: action.ERROR, error: String((err && err.message) || err) });
41
+
42
+ // --- wasm -> JS callbacks ---------------------------------------------------
43
+ self.llmjs_on_token = (text) => post({ event: action.WRITE_RESULT, line: text });
44
+ self.llmjs_on_log = (level, text) => post({ event: action.LOG, level, line: text });
45
+
46
+ const tick = () => new Promise((r) => setTimeout(r, 0));
47
+
48
+ // storage.js shaped for download.js
49
+ const storage = {
50
+ CHUNK_SIZE, getMeta: getModel, putMeta: putModel, updateMeta: updateModel, putChunk, clearChunks,
51
+ };
52
+
53
+ // Render a message list with llama.cpp's chat stack (GGUF template, tools and
54
+ // chat_template_kwargs), inside the wasm module. Throws with the engine's
55
+ // message; the caller decides whether that is worth showing.
56
+ function renderTemplateEx(messagesJson, tools, source, kwargs) {
57
+ const sig = ["string", "string", "string", "string", "number", "number", "number"];
58
+ const need = module.ccall("llmjs_chat_apply_ex", "number", sig,
59
+ [messagesJson, tools, source, kwargs, 1, 0, 0]);
60
+ if (need < 0) {
61
+ throw new Error(module.UTF8ToString(module._llmjs_last_error()));
62
+ }
63
+ const size = need + 1;
64
+ const ptr = module._malloc(size);
65
+ try {
66
+ module.ccall("llmjs_chat_apply_ex", "number", sig,
67
+ [messagesJson, tools, source, kwargs, 1, ptr, size]);
68
+ return module.UTF8ToString(ptr, need);
69
+ } finally {
70
+ module._free(ptr);
71
+ }
72
+ }
73
+
74
+ async function ensureModule() {
75
+ if (module) return module;
76
+ // No locateFile override: the glue resolves llm-wasm.wasm relative to its
77
+ // own import.meta.url (web/wasm/). Passing one here resolves against *this*
78
+ // module's URL and 404s the .wasm into an HTML page.
79
+ module = await createLLMWasmModule();
80
+ module._llmjs_init();
81
+ log(`llama.cpp ${module.UTF8ToString(module._llmjs_version())}`);
82
+ return module;
83
+ }
84
+
85
+ // --- byte sources -----------------------------------------------------------
86
+
87
+ // 4 MiB slices of a File the user picked. The bytes stay on disk; each slice is
88
+ // read, handed to the FS (or the hash), and dropped again.
89
+ async function* fileSlices(file) {
90
+ for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
91
+ const end = Math.min(offset + CHUNK_SIZE, file.size);
92
+ yield new Uint8Array(await file.slice(offset, end).arrayBuffer());
93
+ }
94
+ }
95
+
96
+ // Single iterator over a model's bytes, wherever they live.
97
+ async function* byteStream(model) {
98
+ if (model.source === "url" || model.copied) {
99
+ for await (const row of iterateChunks(model.id)) yield row.data;
100
+ return;
101
+ }
102
+ const file = files.get(model.id);
103
+ if (!file) throw new Error("the local file is not attached - choose it again");
104
+ yield* fileSlices(file);
105
+ }
106
+
107
+ async function hashModel(model) {
108
+ const total = model.total || 0;
109
+ const sha256 = await sha256Chunks(byteStream(model), (done) =>
110
+ progress({ phase: "hash", loaded: done, total }));
111
+ return updateModel(model.id, { sha256 });
112
+ }
113
+
114
+ // --- ingest ----------------------------------------------------------------
115
+
116
+ async function addUrlModel({ url, name, expectedSha256 }) {
117
+ let model = await findModelByUrl(url);
118
+ if (model) {
119
+ // same URL added again: treat it as "open", but let the name/hash be corrected
120
+ const patch = {};
121
+ if (name) patch.name = name;
122
+ if (expectedSha256) patch.expectedSha256 = expectedSha256;
123
+ if (Object.keys(patch).length) model = await updateModel(model.id, patch);
124
+ } else {
125
+ model = await putModel({
126
+ id: newModelId(),
127
+ name: (name || "").trim() || nameFromUrl(url),
128
+ source: "url",
129
+ url,
130
+ fileName: null,
131
+ total: 0,
132
+ received: 0,
133
+ complete: false,
134
+ copied: true, // url models always live in the browser
135
+ sha256: null,
136
+ expectedSha256: (expectedSha256 || "").trim() || null,
137
+ created: Date.now(),
138
+ });
139
+ }
140
+ post({ event: action.MODEL_ADDED, model });
141
+ return model.id;
142
+ }
143
+
144
+ async function addFileModel({ file, name, keepCopy, expectedSha256 }) {
145
+ if (!file) throw new Error("no file given");
146
+
147
+ const head = new Uint8Array(await file.slice(0, 4).arrayBuffer());
148
+ const magic = String.fromCharCode(...head);
149
+ if (magic !== "GGUF") {
150
+ throw new Error(`${file.name} is not a GGUF file (starts with "${magic}")`);
151
+ }
152
+
153
+ const model = await putModel({
154
+ id: newModelId(),
155
+ name: (name || "").trim() || file.name.replace(/\.gguf$/i, ""),
156
+ source: "file",
157
+ url: null,
158
+ fileName: file.name,
159
+ total: file.size,
160
+ received: keepCopy ? 0 : file.size,
161
+ complete: !keepCopy,
162
+ copied: false, // filled in by copyFileIntoStorage below
163
+ sha256: null,
164
+ expectedSha256: (expectedSha256 || "").trim() || null,
165
+ created: Date.now(),
166
+ });
167
+
168
+ files.set(model.id, file);
169
+ post({ event: action.MODEL_ADDED, model });
170
+
171
+ if (keepCopy) return (await copyFileIntoStorage(model, file)).id;
172
+ return model.id;
173
+ }
174
+
175
+ // opt-in: put the bytes in IndexedDB so the model no longer needs the file
176
+ async function copyFileIntoStorage(model, file) {
177
+ await clearChunks(model.id);
178
+ let index = 0;
179
+ let received = 0;
180
+ for await (const bytes of fileSlices(file)) {
181
+ const copy = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
182
+ await putChunk(model.id, index++, copy);
183
+ received += bytes.length;
184
+ progress({ phase: "copy", loaded: received, total: file.size });
185
+ }
186
+ return updateModel(model.id, { copied: true, received, total: file.size, complete: true });
187
+ }
188
+
189
+ // --- loading ---------------------------------------------------------------
190
+
191
+ async function loadIntoFS(model) {
192
+ try { module.FS.mkdir("/models"); } catch (_) { /* already exists */ }
193
+ try { module.FS.unlink("/models/model.gguf"); } catch (_) { /* not there */ }
194
+
195
+ const stream = module.FS.open("/models/model.gguf", "w+");
196
+ let written = 0;
197
+ try {
198
+ for await (const chunk of byteStream(model)) {
199
+ const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
200
+ module.FS.write(stream, bytes, 0, bytes.length, written);
201
+ written += bytes.length;
202
+ progress({ phase: "load", loaded: written, total: model.total || written });
203
+ await tick();
204
+ }
205
+ } finally {
206
+ module.FS.close(stream);
207
+ }
208
+ return written;
209
+ }
210
+
211
+ async function start({ id, file, context_size }) {
212
+ if (busy) {
213
+ fail(new Error("a load is already running"));
214
+ return;
215
+ }
216
+ if (file) files.set(id, file);
217
+
218
+ busy = true;
219
+ abort = new AbortController();
220
+ lastRequest = { id, context_size };
221
+
222
+ try {
223
+ await ensureModule();
224
+
225
+ let model = await getModel(id);
226
+ if (!model) throw new Error(`unknown model ${id}`);
227
+
228
+ // the wasm instance can only hold one model at a time
229
+ if (loaded && loadedId !== id) {
230
+ module._llmjs_free();
231
+ loaded = false;
232
+ loadedId = null;
233
+ }
234
+
235
+ // 1. get the bytes into the browser (url models only; a local file is
236
+ // already where it needs to be)
237
+ if (model.source === "url" && !model.complete) {
238
+ await downloadModel(
239
+ { id: model.id, url: model.url, total: model.total },
240
+ { signal: abort.signal, onProgress: progress, storage },
241
+ );
242
+ model = await getModel(id);
243
+ }
244
+ if (model.source === "file" && !model.copied && !files.has(model.id)) {
245
+ throw new Error("the local file is not attached - choose it again");
246
+ }
247
+
248
+ // 2. identify the bytes once
249
+ if (!model.sha256) model = await hashModel(model);
250
+
251
+ // 3. into the wasm FS, then load
252
+ const bytes = await loadIntoFS(model);
253
+ if (model.received && bytes !== model.received) {
254
+ log(`stored model size ${bytes} != expected ${model.received}`);
255
+ }
256
+
257
+ currentNctx = context_size || currentNctx;
258
+ const n = module.ccall("llmjs_load_model", "number", ["string", "number"],
259
+ ["/models/model.gguf", currentNctx]);
260
+ if (n < 0) throw new Error(`llmjs_load_model failed (${n})`);
261
+
262
+ loaded = true;
263
+ loadedId = id;
264
+ busy = false;
265
+ post({
266
+ event: action.INITIALIZED,
267
+ model,
268
+ bytes,
269
+ n_ctx: n,
270
+ chat_template_name: module.UTF8ToString(module._llmjs_chat_template_name()),
271
+ // the GGUF's own Jinja template, rendered by the engine inside the wasm build
272
+ chat_template: module.UTF8ToString(module._llmjs_chat_template()),
273
+ has_chat_template: module._llmjs_has_chat_template() !== 0,
274
+ });
275
+ post({ event: action.MODEL_UPDATED, model });
276
+ } catch (err) {
277
+ busy = false;
278
+ if (err && err.name === "AbortError") {
279
+ post({ event: action.PAUSED, id });
280
+ } else {
281
+ fail(err);
282
+ }
283
+ }
284
+ }
285
+
286
+ // Set by a STOP message. The generation loop below checks it between tokens,
287
+ // which is only possible because generation is stepped from JS instead of one
288
+ // long blocking call: inside a single ccall this worker could not read messages.
289
+ let cancelRequested = false;
290
+ let generating = false;
291
+
292
+ // mode "chat": a message list rendered through the chat template.
293
+ // mode "completion": the prompt is the prompt, no template involved.
294
+ // Both honour the same sampling limits and stop sequences.
295
+ async function run(opts) {
296
+ const {
297
+ mode = "completion",
298
+ prompt = "",
299
+ messages = null,
300
+ stop = [],
301
+ seed = -1,
302
+ max_token_len = 64,
303
+ top_k = 40,
304
+ top_p = 0.9,
305
+ temp = 0.7,
306
+ repeat_last_n = 32,
307
+ repeat_penalty = 1.1,
308
+ context_size = 0,
309
+ chat_template = "",
310
+ chat_template_source = "",
311
+ tools = "[]",
312
+ template_kwargs = "{}",
313
+ grammar = "",
314
+ } = opts;
315
+
316
+ if (!loaded || !module) {
317
+ fail(new Error("no model loaded"));
318
+ return;
319
+ }
320
+ if (generating) {
321
+ fail(new Error("a run is already in progress"));
322
+ return;
323
+ }
324
+
325
+ const n = module.ccall("llmjs_create_context", "number", ["number"],
326
+ [context_size || currentNctx]);
327
+ if (n < 0) {
328
+ fail(new Error(`llmjs_create_context failed (${n})`));
329
+ return;
330
+ }
331
+
332
+ // stop sequences are matched in C++ against the decoded text, so a stop
333
+ // string is never streamed to the page
334
+ module.ccall("llmjs_set_stop_sequences", null, ["string"],
335
+ [JSON.stringify(Array.isArray(stop) ? stop : [])]);
336
+
337
+ // arm the engine: everything promised by the parameters goes in here
338
+ let rc;
339
+ if (mode === "chat") {
340
+ const list = Array.isArray(messages) && messages.length
341
+ ? messages
342
+ : [{ role: "user", content: prompt }];
343
+ rc = module.ccall(
344
+ "llmjs_gen_begin_chat",
345
+ "number",
346
+ ["string", "string", "string", "string", "number", "number", "number",
347
+ "number", "number", "number", "number", "string"],
348
+ [JSON.stringify(list), tools || "[]", chat_template_source, template_kwargs || "{}",
349
+ max_token_len, temp, top_k, top_p, repeat_penalty, repeat_last_n, seed, grammar],
350
+ );
351
+ } else {
352
+ rc = module.ccall(
353
+ "llmjs_gen_begin_raw",
354
+ "number",
355
+ ["string", "number", "number", "number", "number", "number",
356
+ "number", "number", "string"],
357
+ [prompt, max_token_len, temp, top_k, top_p, repeat_penalty,
358
+ repeat_last_n, seed, grammar],
359
+ );
360
+ }
361
+ if (rc < 0) {
362
+ fail(new Error(`could not start generation (${rc})`));
363
+ return;
364
+ }
365
+
366
+ generating = true;
367
+ cancelRequested = false;
368
+ const t0 = performance.now();
369
+ let tokens = 0;
370
+ try {
371
+ // one token per turn of the event loop: a STOP message is handled
372
+ // during the await, and the loop then exits with the text so far
373
+ while (!cancelRequested) {
374
+ if (module.ccall("llmjs_gen_step", "number", [], []) <= 0) break;
375
+ await tick();
376
+ }
377
+ tokens = module.ccall("llmjs_gen_end", "number", [], []);
378
+ } finally {
379
+ generating = false;
380
+ }
381
+
382
+ const ms = performance.now() - t0;
383
+ const interrupted = cancelRequested;
384
+ cancelRequested = false;
385
+
386
+ post({
387
+ event: action.RUN_COMPLETED,
388
+ mode,
389
+ tokens,
390
+ ms,
391
+ interrupted,
392
+ tokens_per_second: tokens > 0 ? (tokens * 1000) / ms : 0,
393
+ // the final text, with any stop sequence removed: whatever the page
394
+ // streamed may still contain the beginning of a stop string
395
+ output: module.UTF8ToString(module._llmjs_last_output()),
396
+ // jinja / jinja:override / builtin:<name> / raw
397
+ template_strategy: module.UTF8ToString(module._llmjs_chat_template_strategy()),
398
+ // { content, reasoning_content, tool_calls } when the template's parser
399
+ // recognised the reply, null when it did not
400
+ parsed: (() => {
401
+ const text = module.UTF8ToString(module._llmjs_parsed_output());
402
+ if (!text) return null;
403
+ try { return JSON.parse(text); } catch (_) { return null; }
404
+ })(),
405
+ });
406
+ }
407
+
408
+ self.addEventListener("message", (e) => {
409
+ const msg = e.data;
410
+ switch (msg.event) {
411
+ case action.ADD_URL:
412
+ (async () => {
413
+ const id = await addUrlModel(msg);
414
+ await start({ id, context_size: msg.context_size });
415
+ })().catch(fail);
416
+ break;
417
+
418
+ case action.ADD_FILE:
419
+ (async () => {
420
+ const id = await addFileModel(msg);
421
+ await start({ id, context_size: msg.context_size });
422
+ })().catch(fail);
423
+ break;
424
+
425
+ case action.LOAD:
426
+ start(msg);
427
+ break;
428
+
429
+ case action.PAUSE:
430
+ if (abort) abort.abort();
431
+ break;
432
+
433
+ case action.RESUME:
434
+ if (lastRequest) start(lastRequest);
435
+ else fail(new Error("nothing to resume"));
436
+ break;
437
+
438
+ case action.PREVIEW_TEMPLATE:
439
+ (async () => {
440
+ await ensureModule();
441
+ const messages = JSON.stringify(msg.messages && msg.messages.length
442
+ ? msg.messages
443
+ : [{ role: "user", content: msg.prompt || "" }]);
444
+ const text = renderTemplateEx(messages, msg.tools || "[]",
445
+ msg.template_source || "", msg.template_kwargs || "{}");
446
+ post({ event: action.TEMPLATE_PREVIEW, text });
447
+ })().catch(fail);
448
+ break;
449
+
450
+ case action.RELOAD_MODEL:
451
+ (async () => {
452
+ // a real reload: drop the model and the backend, then load again
453
+ if (module) {
454
+ module._llmjs_free();
455
+ module._llmjs_init();
456
+ }
457
+ loaded = false;
458
+ loadedId = null;
459
+ await start({ id: msg.id, file: files.get(msg.id) || null, context_size: msg.context_size });
460
+ })().catch(fail);
461
+ break;
462
+
463
+ case action.HASH_MODEL:
464
+ (async () => {
465
+ const model = await getModel(msg.id);
466
+ if (!model) throw new Error(`unknown model ${msg.id}`);
467
+ const hashed = await hashModel(model);
468
+ post({ event: action.MODEL_UPDATED, model: hashed });
469
+ })().catch(fail);
470
+ break;
471
+
472
+ case action.DELETE_MODEL:
473
+ (async () => {
474
+ if (loaded && loadedId === msg.id) {
475
+ module._llmjs_free();
476
+ loaded = false;
477
+ loadedId = null;
478
+ }
479
+ files.delete(msg.id);
480
+ const chunks = await deleteModel(msg.id);
481
+ post({ event: action.DELETED, id: msg.id, chunks });
482
+ })().catch(fail);
483
+ break;
484
+
485
+ case action.LIST_MODELS:
486
+ listModels()
487
+ .then((models) => post({ event: action.MODELS, models }))
488
+ .catch(fail);
489
+ break;
490
+
491
+ case action.STOP:
492
+ if (generating) cancelRequested = true;
493
+ break;
494
+
495
+ case action.RUN_MAIN:
496
+ run(msg).catch(fail);
497
+ break;
498
+ }
499
+ }, false);