// This file is auto-generated // To re-generate it, run: npm run build:worker export const LIBLLAMA_VERSION = 'b12637-0b51bb2'; export const LLAMA_CPP_WORKER_CODE = "// Start the main llama.cpp\nlet wllamaMalloc;\nlet wllamaStart;\nlet wllamaAction;\nlet wllamaExit;\nlet wllamaDebug;\nlet wllamaRpcServe;\n\nlet Module = null;\nlet lastStack = '';\nlet isAborted = false;\nlet hasMultithread = false;\n\n//////////////////////////////////////////////////////////////\n// UTILS\n//////////////////////////////////////////////////////////////\n\n// send message back to main thread\nconst msg = (data, transfer) => postMessage(data, transfer);\n\n// Convert CPP log into JS log\nconst cppLogToJSLog = (line) => {\n const matched = line.match(/@@(DEBUG|INFO|WARN|ERROR)@@(.*)/);\n return !!matched\n ? {\n level: (matched[1] === 'INFO' ? 'debug' : matched[1]).toLowerCase(),\n text: matched[2],\n }\n : { level: 'log', text: line };\n};\n\nconst getHeapU8 = () => {\n const buffer = Module.wasmMemory.buffer;\n return new Uint8Array(buffer);\n};\n\n// Get module config that forwards stdout/err to main thread\nconst getWModuleConfig = (_argMainScriptBlob, wasmModule) => {\n var pathConfig = RUN_OPTIONS.pathConfig;\n var pthreadPoolSize = RUN_OPTIONS.nbThread;\n var argMainScriptBlob = _argMainScriptBlob;\n\n hasMultithread = pthreadPoolSize > 1;\n\n msg({\n verb: 'console.debug',\n args: [\n `Multithread enabled: ${hasMultithread}, pthreadPoolSize: ${pthreadPoolSize}`,\n ],\n });\n\n if (!pathConfig['wllama.wasm']) {\n throw new Error('\"wllama.wasm\" is missing in pathConfig');\n }\n return {\n noInitialRun: true,\n // wasm is compiled by main thread; onSuccess needs the module to share it with pthreads\n instantiateWasm: function (imports, onSuccess) {\n WebAssembly.instantiate(wasmModule, imports)\n .then((instance) => onSuccess(instance, wasmModule))\n .catch(handleError);\n return {};\n },\n print: function (text) {\n if (arguments.length > 1)\n text = Array.prototype.slice.call(arguments).join(' ');\n msg({ verb: 'console.log', args: [text] });\n },\n printErr: function (text) {\n if (arguments.length > 1)\n text = Array.prototype.slice.call(arguments).join(' ');\n if (text.startsWith('@@STACK@@')) {\n lastStack = text.slice('@@STACK@@'.length);\n return;\n }\n const logLine = cppLogToJSLog(text);\n msg({ verb: 'console.' + logLine.level, args: [logLine.text] });\n },\n locateFile: function (filename, basePath) {\n const p = pathConfig[filename];\n const truncate = (str) =>\n str.length > 128 ? `${str.substr(0, 128)}...` : str;\n if (filename.match(/wllama\\.worker\\.js/)) {\n msg({\n verb: 'console.error',\n args: [\n '\"wllama.worker.js\" is removed from v2.2.1. Hint: make sure to clear browser\\'s cache.',\n ],\n });\n } else {\n msg({\n verb: 'console.debug',\n args: [`Loading \"${filename}\" from \"${truncate(p)}\"`],\n });\n return p;\n }\n },\n mainScriptUrlOrBlob: hasMultithread\n ? argMainScriptBlob\n : 'throw new Error(\"Multithreading is not enabled\")',\n pthreadPoolSize: hasMultithread ? pthreadPoolSize : 0,\n wasmMemory: hasMultithread ? getWasmMemory() : null,\n onAbort: function (reason) {\n isAborted = true;\n rpcFailAll();\n // the reason can be an Error (for example a failed wasm instantiate)\n const message = reason?.message ?? String(reason);\n msg({ verb: 'signal.abort', args: ['abort', message, lastStack, null] });\n },\n onExit: function (code) {\n isAborted = true;\n const callstack = new Error().stack.toString();\n msg({\n verb: 'signal.abort',\n args: ['abort', 'exit(' + code + ')', callstack, null],\n });\n },\n };\n};\n\n// Get the memory to be used by wasm. (Only used in multi-thread mode)\n// Because we have a weird OOM issue on iOS, we need to try some values\n// See: https://github.com/emscripten-core/emscripten/issues/19144\n// https://github.com/godotengine/godot/issues/70621\nconst getWasmMemory = () => {\n let minBytes = 128 * 1024 * 1024;\n let maxBytes = 4096 * 1024 * 1024;\n let stepBytes = 128 * 1024 * 1024;\n while (maxBytes > minBytes) {\n try {\n const wasmMemory = new WebAssembly.Memory({\n initial: minBytes / 65536,\n maximum: maxBytes / 65536,\n shared: true,\n });\n return wasmMemory;\n } catch (e) {\n maxBytes -= stepBytes;\n continue; // retry\n }\n }\n throw new Error('Cannot allocate WebAssembly.Memory');\n};\n\n//////////////////////////////////////////////////////////////\n// HEAPFS PATCH\n//////////////////////////////////////////////////////////////\n\n/**\n * By default, emscripten uses memfs. The way it works is by\n * allocating new Uint8Array in javascript heap. This is not good\n * because it requires files to be copied to wasm heap each time\n * a file is read.\n *\n * HeapFS is an alternative, which resolves this problem by\n * allocating space for file directly inside wasm heap. This\n * allows us to mmap without doing any copy.\n *\n * For llama.cpp, this is great because we use MAP_SHARED\n *\n * Ref: https://github.com/ngxson/wllama/pull/39\n * Ref: https://github.com/emscripten-core/emscripten/blob/main/src/library_memfs.js\n */\n\nconst fsNameToFile = {}; // map Name => File\nconst fsIdToFile = {}; // map ID => File\nlet currFileId = 0;\n\n// Patch and redirect memfs calls to wllama\nconst patchHeapFS = () => {\n const m = Module;\n // save functions\n m.MEMFS.stream_ops._read = m.MEMFS.stream_ops.read;\n m.MEMFS.stream_ops._write = m.MEMFS.stream_ops.write;\n m.MEMFS.stream_ops._llseek = m.MEMFS.stream_ops.llseek;\n m.MEMFS.stream_ops._allocate = m.MEMFS.stream_ops.allocate;\n m.MEMFS.stream_ops._mmap = m.MEMFS.stream_ops.mmap;\n m.MEMFS.stream_ops._msync = m.MEMFS.stream_ops.msync;\n\n const patchStream = (stream) => {\n const name = stream.node.name;\n if (fsNameToFile[name]) {\n const f = fsNameToFile[name];\n const ptr = Number(f.ptr);\n stream.node.contents = getHeapU8().subarray(ptr, ptr + f.size);\n stream.node.usedBytes = f.size;\n }\n };\n\n // replace \"read\" functions\n m.MEMFS.stream_ops.read = function (\n stream,\n buffer,\n offset,\n length,\n position\n ) {\n patchStream(stream);\n return m.MEMFS.stream_ops._read(stream, buffer, offset, length, position);\n };\n m.MEMFS.ops_table.file.stream.read = m.MEMFS.stream_ops.read;\n\n // replace \"llseek\" functions\n m.MEMFS.stream_ops.llseek = function (stream, offset, whence) {\n patchStream(stream);\n return m.MEMFS.stream_ops._llseek(stream, offset, whence);\n };\n m.MEMFS.ops_table.file.stream.llseek = m.MEMFS.stream_ops.llseek;\n\n // replace \"mmap\" functions\n m.MEMFS.stream_ops.mmap = function (stream, length, position, prot, flags) {\n patchStream(stream);\n const name = stream.node.name;\n if (fsNameToFile[name]) {\n const f = fsNameToFile[name];\n const mmapPtr = f.ptr + position;\n return {\n ptr: mmapPtr,\n allocated: false,\n };\n } else {\n return m.MEMFS.stream_ops._mmap(stream, length, position, prot, flags);\n }\n };\n m.MEMFS.ops_table.file.stream.mmap = m.MEMFS.stream_ops.mmap;\n\n // mount FS\n m.FS.mkdir('/models');\n m.FS.mount(m.MEMFS, { root: '.' }, '/models');\n};\n\n// Allocate a new file in wllama heapfs, returns file ID\nconst heapfsAlloc = (name, size, allocBuffer) => {\n if (size < 1) {\n throw new Error('File size must be bigger than 0');\n }\n const m = Module;\n // >>> 0: a wasm32 pointer above 2GB arrives as a negative number\n const ptr = allocBuffer ? m.mmapAlloc(size) >>> 0 : 0;\n const file = {\n ptr: ptr,\n size: size,\n id: currFileId++,\n };\n fsIdToFile[file.id] = file;\n fsNameToFile[name] = file;\n return file.id;\n};\n\n// Add new file to wllama heapfs, return number of written bytes\nconst heapfsWrite = (id, buffer, offset) => {\n if (fsIdToFile[id]) {\n const { ptr, size } = fsIdToFile[id];\n const afterWriteByte = offset + buffer.byteLength;\n if (afterWriteByte > size) {\n throw new Error(\n `File ID ${id} write out of bound, afterWriteByte = ${afterWriteByte} while size = ${size}`\n );\n }\n getHeapU8().set(buffer, Number(ptr) + offset);\n return buffer.byteLength;\n } else {\n throw new Error(`File ID ${id} not found in heapfs`);\n }\n};\n\n//////////////////////////////////////////////////////////////\n// ASYNC FILE READ\n//////////////////////////////////////////////////////////////\n\nlet isAwaitReading = false;\nlet pendingReadPromise = null;\nlet pendingReadResolve = null;\nlet pendingReadReject = null;\n\nconst _stripModelsPrefix = (path) => path.replace(/^\\/?models\\//, '');\n\n// reads are split in chunks of READ_CHUNK at most (postMessage cannot send an ArrayBuffer bigger than 2GB).\n// Each chunk is a new ArrayBuffer, garbage once copied to the heap: small chunks keep that garbage small while loading.\n// llama.cpp uploads the weights to the GPU and to rpc workers in reads of 1MB, one round trip to the main thread each,\n// so sequential reads get a read-ahead that grows (8 times the read, then 4 times more each time) up to READ_CHUNK; other reads (small tensors, the loader jumps between them) get only what they ask for\nconst READ_CHUNK = 32 * 1024 * 1024;\nlet readAhead = null; // { name, offset, bytes }: the rest of the last chunk\nlet seqName = null; // the next sequential read is name at seqNext\nlet seqNext = -1;\nlet seqWindow = 0;\n\n// Files of the OPFS cache are read with a sync access handle, straight into the heap: no Blob, no round trip to the main thread\n// (12-25x faster on Android). It is opened when needed and closed after each wasm call, so the cache can change the file in between\nconst opfsFiles = {}; // name -> { path (in OPFS), size, access, failed }\n\n// returns the number of bytes read, or -1 to read the Blob instead\nconst opfsRead = async (name, offset, req_size, out_ptr) => {\n const f = opfsFiles[name];\n if (!f || f.failed) return -1;\n try {\n if (!f.access) {\n let dir = await navigator.storage.getDirectory();\n for (const d of f.path.slice(0, -1))\n dir = await dir.getDirectoryHandle(d);\n const handle = await dir.getFileHandle(f.path[f.path.length - 1]);\n f.access = await handle.createSyncAccessHandle({ mode: 'read-only' });\n if (f.access.getSize() !== f.size) {\n throw new Error('the file in the cache changed');\n }\n if (!f.used) {\n f.used = true;\n msg({\n verb: 'console.debug',\n args: [`Reading ${name} with an OPFS sync access handle`],\n });\n }\n }\n return f.access.read(getHeapU8().subarray(out_ptr, out_ptr + req_size), {\n at: offset,\n });\n } catch (err) {\n // for example: another tab has the file open, or the browser does not have sync access handles\n f.failed = true;\n msg({\n verb: 'console.warn',\n args: [\n `Cannot read ${name} with an OPFS sync access handle, reading the Blob instead: ${err}`,\n ],\n });\n return -1;\n }\n};\n\nconst opfsCloseAll = () => {\n for (const f of Object.values(opfsFiles)) {\n if (f.access) {\n try {\n f.access.close();\n } catch {}\n f.access = null;\n }\n }\n};\n\n// Called from EM_ASYNC_JS stub in cpp/wllama-patch.cpp (path is already a JS string)\nconst _wllama_js_file_read = async (path, offset, req_size, out_ptr) => {\n const name = _stripModelsPrefix(path);\n const n = await opfsRead(name, offset, req_size, out_ptr);\n if (n >= 0) return n;\n let total = 0;\n while (total < req_size) {\n const pos = offset + total;\n const left = req_size - total;\n const ra = readAhead;\n if (\n ra &&\n ra.name === name &&\n pos >= ra.offset &&\n pos < ra.offset + ra.bytes.length\n ) {\n const start = pos - ra.offset;\n const n = Math.min(left, ra.bytes.length - start);\n getHeapU8().set(ra.bytes.subarray(start, start + n), out_ptr + total);\n total += n;\n seqName = name;\n seqNext = pos + n;\n continue;\n }\n const sequential = name === seqName && pos === seqNext;\n seqWindow = sequential ? Math.max(seqWindow * 4, left * 8) : 0;\n const size = Math.min(READ_CHUNK, Math.max(left, seqWindow));\n const bytes = await readFileBytes(name, pos, size);\n const n = Math.min(left, bytes.length);\n getHeapU8().set(bytes.subarray(0, n), out_ptr + total);\n total += n;\n readAhead = bytes.length > n ? { name, offset: pos, bytes } : null;\n seqName = name;\n seqNext = pos + n;\n if (n < left && bytes.length < size) break; // end of file\n }\n return total;\n};\n\nconst readFileBytes = async (name, offset, req_size) => {\n pendingReadPromise = new Promise((res, rej) => {\n pendingReadResolve = res;\n pendingReadReject = rej;\n });\n isAwaitReading = true;\n\n postMessage({ verb: 'fs.read_req', args: [name, offset, req_size] });\n\n let data;\n try {\n data = await pendingReadPromise;\n } finally {\n isAwaitReading = false;\n pendingReadPromise = null; // do not keep the read buffer alive\n pendingReadResolve = null;\n pendingReadReject = null;\n }\n return new Uint8Array(data);\n};\n\n//////////////////////////////////////////////////////////////\n// MAIN CODE\n//////////////////////////////////////////////////////////////\n\nconst callWrapper = (name, ret, args, isAsync) => {\n const fn = Module.cwrap(\n name,\n ret,\n args,\n isAsync ? { async: true } : undefined\n );\n return async (action, req) => {\n // console.log(`Calling ${name} with action:`, action, 'and req:', req);\n let result;\n try {\n if (args.length === 2) {\n result = isAsync ? await fn(action, req) : fn(action, req);\n } else {\n result = fn();\n }\n } catch (ex) {\n console.error(ex);\n throw ex;\n }\n return result;\n };\n};\n\n// re-entering the wasm while a call is suspended (JSPI / asyncify) corrupts its state, so only one call runs at a time and the rest wait in the queue\nlet wasmCallBusy = false;\nconst wasmCallQueue = [];\n\nconst runWasmCall = async (callbackId, fn) => {\n if (isAborted) {\n // the wasm is dead, fail fast instead of calling into it\n msg({ callbackId, err: 'wllama has crashed, please reload the module' });\n return;\n }\n if (wasmCallBusy) {\n wasmCallQueue.push({ callbackId, fn });\n return;\n }\n wasmCallBusy = true;\n try {\n await fn();\n } finally {\n opfsCloseAll();\n wasmCallBusy = false;\n if (isAborted) {\n // do not touch the wasm again after it aborted; the main thread already rejected the queued tasks\n wasmCallQueue.length = 0;\n } else {\n const next = wasmCallQueue.shift();\n if (next) runWasmCall(next.callbackId, next.fn);\n }\n }\n};\n\nconst runAction = async (data) => {\n const { args, callbackId } = data;\n const argAction = args[0];\n const argEncodedMsg = args[1];\n try {\n // >>> 0: a wasm32 pointer above 2GB arrives as a negative number\n const inputPtr = (await wllamaMalloc(argEncodedMsg.byteLength, 0)) >>> 0;\n // copy data to wasm heap\n const inputBuffer = new Uint8Array(\n getHeapU8().buffer,\n Number(inputPtr),\n argEncodedMsg.byteLength\n );\n inputBuffer.set(argEncodedMsg, 0);\n const outputPtr = (await wllamaAction(argAction, inputPtr)) >>> 0;\n if (!Number(outputPtr)) {\n msg({\n callbackId,\n err: `Action \"${argAction}\" failed, see the native log`,\n });\n return;\n }\n // length of output buffer is written at the first 4 bytes of input buffer\n const outputLen = new Uint32Array(\n getHeapU8().buffer,\n Number(inputPtr),\n 1\n )[0];\n // copy the output buffer to JS heap\n const outputBuffer = new Uint8Array(outputLen);\n const outputSrcView = new Uint8Array(\n getHeapU8().buffer,\n Number(outputPtr),\n outputLen\n );\n outputBuffer.set(outputSrcView, 0); // copy it\n msg({ callbackId, result: outputBuffer }, [outputBuffer.buffer]);\n } catch (err) {\n handleError(err);\n }\n};\n\nfunction handleError(err) {\n // If WASM already aborted, onAbort already sent signal.abort; skip to avoid\n // re-reporting the resulting WebAssembly.RuntimeError as a JS exception.\n if (isAborted) return;\n\n const message = err ? err.message || String(err) : 'Unknown error';\n const stack = err ? err.stack || String(err) : '';\n msg({\n verb: 'signal.abort',\n args: ['exception', message, stack, err],\n });\n}\n\nonmessage = async (e) => {\n if (!e.data) return;\n const { verb, args, callbackId } = e.data;\n\n // fs.read_res arrives while wasm is JSPI-suspended; resolve the pending promise.\n if (verb === 'fs.read_res') {\n if (pendingReadResolve) {\n pendingReadResolve(args[0]);\n }\n return;\n }\n\n // Guard: while awaiting a file read, reject any other incoming task.\n if (isAwaitReading) {\n if (callbackId) {\n msg({\n callbackId,\n err: 'Worker is suspended waiting for file data (JSPI)',\n });\n }\n return;\n }\n\n if (!callbackId) {\n msg({ verb: 'console.error', args: ['callbackId is required', e.data] });\n return;\n }\n\n if (verb === 'module.init') {\n const argMainScriptBlob = args[0];\n const argUseAsyncFile = args[1];\n const argWasmModule = args[2];\n const argRpc = args[3]; // { env, channels } of the rpc workers\n try {\n Module = getWModuleConfig(argMainScriptBlob, argWasmModule);\n if (argRpc) {\n rpcSetChannels(argRpc.channels);\n // ggml-rpc does its I/O in a thread per server: send the channels to the pthread workers, and add one thread per server (the exception to the pool size rule, see README-dev.md)\n const BaseWorker = self.Worker;\n self.Worker = class extends BaseWorker {\n constructor(...a) {\n super(...a);\n this.postMessage({ cmd: 'wllamaRpc', channels: argRpc.channels });\n }\n };\n if (Module.pthreadPoolSize) {\n Module.pthreadPoolSize += argRpc.channels.length;\n }\n }\n Module.preRun = () => {\n if (argUseAsyncFile) {\n Module.ENV['USE_ASYNC_FILE'] = '1';\n }\n Object.assign(Module.ENV, argRpc?.env ?? {});\n };\n Module.onRuntimeInitialized = () => {\n // async call once module is ready\n // init FS\n patchHeapFS();\n // init cwrap\n const pointer = 'number';\n // TODO: note sure why emscripten cannot bind if there is only 1 argument\n wllamaMalloc = callWrapper('wllama_malloc', pointer, [\n 'number',\n pointer,\n ]);\n wllamaStart = callWrapper('wllama_start', 'string', [], true);\n wllamaAction = callWrapper(\n 'wllama_action',\n pointer,\n ['string', pointer],\n true\n );\n wllamaExit = callWrapper('wllama_exit', 'string', []);\n wllamaDebug = callWrapper('wllama_debug', 'string', []);\n wllamaRpcServe = Module.cwrap(\n 'wllama_rpc_serve',\n null,\n ['number', 'number'],\n { async: true }\n );\n msg({ callbackId, result: null });\n };\n wModuleInit();\n } catch (err) {\n handleError(err);\n }\n return;\n }\n\n if (verb === 'fs.alloc') {\n const argFilename = args[0];\n const argSize = args[1];\n const argAllocBuffer = args[2];\n if (args[3]) {\n opfsFiles[argFilename] = {\n path: args[3],\n size: argSize,\n access: null,\n failed: false,\n };\n }\n try {\n // create blank file\n const emptyBuffer = new ArrayBuffer(0);\n Module['FS_createDataFile'](\n '/models',\n argFilename,\n emptyBuffer,\n true,\n true,\n true\n );\n // alloc data on heap\n const fileId = heapfsAlloc(argFilename, argSize, argAllocBuffer);\n msg({ callbackId, result: { fileId } });\n } catch (err) {\n handleError(err);\n }\n return;\n }\n\n if (verb === 'fs.write') {\n const argFileId = args[0];\n const argBuffer = args[1];\n const argOffset = args[2];\n try {\n const writtenBytes = heapfsWrite(argFileId, argBuffer, argOffset);\n msg({ callbackId, result: { writtenBytes } });\n } catch (err) {\n handleError(err);\n }\n return;\n }\n\n // rpc worker: serve the CPU backend to the main wasm, this call never returns\n if (verb === 'rpc.serve') {\n const [port, nThreads] = args;\n msg({ callbackId, result: null });\n wllamaRpcServe(port, nThreads).catch((err) => {\n rpcFailAll();\n handleError(err);\n });\n return;\n }\n\n if (verb === 'wllama.start') {\n await runWasmCall(callbackId, async () => {\n try {\n const result = await wllamaStart();\n msg({ callbackId, result });\n } catch (err) {\n handleError(err);\n }\n });\n return;\n }\n\n if (verb === 'wllama.action') {\n await runWasmCall(callbackId, () => runAction(e.data));\n return;\n }\n\n if (verb === 'wllama.exit') {\n await runWasmCall(callbackId, async () => {\n try {\n const result = await wllamaExit();\n msg({ callbackId, result });\n } catch (err) {\n handleError(err);\n }\n });\n return;\n }\n\n if (verb === 'wllama.debug') {\n await runWasmCall(callbackId, async () => {\n try {\n const result = await wllamaDebug();\n msg({ callbackId, result });\n } catch (err) {\n handleError(err);\n }\n });\n return;\n }\n};\n"; export const OPFS_UTILS_WORKER_CODE = "let accessHandle;\nlet fileHandler;\nlet writePos = 0;\nlet abortController = new AbortController();\n\n// keep the first `offset` bytes, the next writes go after them\nasync function openFile(filename, offset = 0) {\n const opfsRoot = await navigator.storage.getDirectory();\n const cacheDir = await opfsRoot.getDirectoryHandle('cache', { create: true });\n fileHandler = await cacheDir.getFileHandle(filename, { create: true });\n accessHandle = await fileHandler.createSyncAccessHandle();\n accessHandle.truncate(offset);\n writePos = offset;\n}\n\nasync function writeFile(buf) {\n await writeFileAt(buf, writePos);\n writePos += buf.byteLength;\n}\n\nasync function writeFileAt(buf, pos) {\n let n;\n try {\n n = accessHandle.write(buf, { at: pos });\n } catch (e) {\n // iOS Safari can close the handle in the middle of a download, open a new one and try once more\n if (e?.name !== 'InvalidStateError') throw e;\n accessHandle = await fileHandler.createSyncAccessHandle();\n n = accessHandle.write(buf, { at: pos });\n }\n // Chrome stops a file at 2000MB in an incognito window, the write returns a wrong count instead of throwing\n if (n !== buf.byteLength) {\n throw new DOMException(\n `Cannot write past ${pos} bytes, the storage is full`,\n 'QuotaExceededError'\n );\n }\n}\n\nasync function closeFile() {\n accessHandle.flush();\n accessHandle.close();\n}\n\nasync function writeTextFile(filename, str) {\n await openFile(filename);\n await writeFile(new TextEncoder().encode(str));\n await closeFile();\n}\n\nconst throttled = (func, delay) => {\n let lastRun = 0;\n return (...args) => {\n const now = Date.now();\n if (now - lastRun > delay) {\n lastRun = now;\n func.apply(null, args);\n }\n };\n};\n\nconst assertNonNull = (val) => {\n if (val === null || val === undefined) {\n throw new Error('OPFS Worker: Assertion failed');\n }\n};\n\n// respond to main thread\nconst resOK = () => postMessage({ ok: true });\nconst resProgress = (loaded, total) =>\n postMessage({ progress: { loaded, total } });\nconst resErr = (err) => postMessage({ err });\n\nonmessage = async (e) => {\n try {\n if (!e.data) return;\n\n /**\n * @param {Object} e.data\n *\n * Fine-control FS actions:\n * - { action: 'open', filename: 'string', offset: number }\n * - { action: 'write', buf: ArrayBuffer }\n * - { action: 'close' }\n *\n * Simple write API:\n * - { action: 'write-simple', filename: 'string', buf: ArrayBuffer }\n *\n * Download API:\n * - { action: 'download', url: 'string', filename: 'string', options: Object, metadataFileName: 'string' }\n * - { action: 'download-abort' }\n */\n const {\n action,\n filename,\n buf,\n url,\n options,\n metadataFileName,\n metadataAdditional,\n } = e.data;\n\n if (action === 'open') {\n assertNonNull(filename);\n await openFile(filename, e.data.offset ?? 0);\n return resOK();\n } else if (action === 'write') {\n assertNonNull(buf);\n await writeFile(buf);\n return resOK();\n } else if (action === 'write-at') {\n assertNonNull(buf);\n await writeFileAt(buf, e.data.pos);\n return resOK();\n } else if (action === 'close') {\n await closeFile();\n return resOK();\n } else if (action === 'write-simple') {\n assertNonNull(filename);\n assertNonNull(buf);\n await openFile(filename);\n await writeFile(buf);\n await closeFile();\n return resOK();\n } else if (action === 'download') {\n assertNonNull(url);\n assertNonNull(filename);\n assertNonNull(metadataFileName);\n assertNonNull(options);\n assertNonNull(options.aborted);\n abortController = new AbortController();\n if (options.aborted) abortController.abort();\n const response = await fetch(url, {\n ...options,\n signal: abortController.signal,\n });\n const contentLength = response.headers.get('content-length');\n const etag = (response.headers.get('etag') || '').replace(\n /[^A-Za-z0-9]/g,\n ''\n );\n const total = parseInt(contentLength, 10);\n const reader = response.body.getReader();\n await openFile(filename);\n let loaded = 0;\n const throttledProgress = throttled(resProgress, 100);\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n loaded += value.byteLength;\n await writeFile(value);\n throttledProgress(loaded, total);\n }\n resProgress(total, total); // 100% done\n await closeFile();\n // make sure this is in-sync with CacheEntryMetadata\n await writeTextFile(\n metadataFileName,\n JSON.stringify({\n originalURL: url,\n originalSize: total,\n etag,\n ...metadataAdditional,\n })\n );\n return resOK();\n } else if (action === 'download-abort') {\n if (abortController) {\n abortController.abort();\n }\n return;\n }\n\n throw new Error('OPFS Worker: Invalid action', e.data);\n } catch (err) {\n return resErr(err);\n }\n};\n"; export const WEBGPU_POLL_PATCH_CODE = "// Firefox resolves WebGPU promises (onSubmittedWorkDone, mapAsync) only on a 100 ms timer: https://bugzilla.mozilla.org/show_bug.cgi?id=1870699\n// A read back of a WebGPU canvas makes Firefox poll the device at once, and the poll also resolves our pending promises.\n// So after each wait starts, we draw a 1x1 WebGPU canvas into a 2D canvas. See \"Patches\" in README-dev.md\n(() => {\n if (\n typeof GPUAdapter === 'undefined' ||\n !/Firefox\\//.test(navigator.userAgent)\n ) {\n return;\n }\n\n let device = null;\n let gpuCanvas = null;\n let gpuCtx = null;\n let ctx2d = null;\n\n const requestDevice = GPUAdapter.prototype.requestDevice;\n GPUAdapter.prototype.requestDevice = async function (...args) {\n device = await requestDevice.apply(this, args);\n return device;\n };\n\n const poll = () => {\n if (!device) {\n return;\n }\n try {\n if (!gpuCanvas) {\n gpuCanvas = new OffscreenCanvas(1, 1);\n gpuCtx = gpuCanvas.getContext('webgpu');\n gpuCtx.configure({\n device,\n format: navigator.gpu.getPreferredCanvasFormat(),\n alphaMode: 'opaque',\n });\n ctx2d = new OffscreenCanvas(1, 1).getContext('2d');\n }\n // without new work on the canvas, Firefox gives the last frame and does not poll\n const encoder = device.createCommandEncoder();\n encoder\n .beginRenderPass({\n colorAttachments: [\n {\n view: gpuCtx.getCurrentTexture().createView(),\n loadOp: 'clear',\n storeOp: 'store',\n },\n ],\n })\n .end();\n device.queue.submit([encoder.finish()]);\n ctx2d.drawImage(gpuCanvas, 0, 0);\n } catch (e) {\n // stop polling, the waits use the 100 ms timer again\n console.warn('wllama: WebGPU poll patch disabled:', e);\n device = null;\n }\n };\n\n const onSubmittedWorkDone = GPUQueue.prototype.onSubmittedWorkDone;\n GPUQueue.prototype.onSubmittedWorkDone = function (...args) {\n const promise = onSubmittedWorkDone.apply(this, args);\n poll();\n return promise;\n };\n\n const mapAsync = GPUBuffer.prototype.mapAsync;\n GPUBuffer.prototype.mapAsync = function (...args) {\n const promise = mapAsync.apply(this, args);\n poll();\n return promise;\n };\n})();\n"; export const RPC_TRANSPORT_WORKER_CODE = "// transport for ggml-rpc between wasm instances, see cpp/wllama-rpc-transport.cpp\n// this code runs in the main worker and in the pthread workers: on the client, ggml-rpc does its I/O in its own thread\n\n// a channel links the client wasm to one server wasm, see cpp/wllama-rpc-transport.cpp\n// int32 header: connection id, closed connection id, head and tail of the client->server and server->client rings,\n// accepted connection id, and a flag set when the server is gone\nconst RPC_CONN = 0;\nconst RPC_CLOSED = 1;\nconst RPC_RING_IDX = [2, 3, 4, 5];\nconst RPC_ACCEPTED = 6;\nconst RPC_FAILED = 7;\nconst RPC_HEADER_BYTES = 64;\nconst RPC_WAIT_MS = 100;\nconst rpcChannels = {}; // port -> channel\n\n// main worker: Module.wasmMemory; pthread worker: the emscripten global wasmMemory\nconst rpcHeapU8 = () =>\n new Uint8Array(\n (typeof wasmMemory !== 'undefined' ? wasmMemory : Module.wasmMemory).buffer\n );\n\nconst rpcSetChannels = (channels) => {\n for (const { port, sab, role } of channels) {\n const cap = (sab.byteLength - RPC_HEADER_BYTES) / 2; // power of 2\n const c2s = {\n head: 2,\n tail: 3,\n data: new Uint8Array(sab, RPC_HEADER_BYTES, cap),\n };\n const s2c = {\n head: 4,\n tail: 5,\n data: new Uint8Array(sab, RPC_HEADER_BYTES + cap, cap),\n };\n rpcChannels[port] = {\n hdr: new Int32Array(sab, 0, RPC_HEADER_BYTES / 4),\n cap,\n tx: role === 'client' ? c2s : s2c,\n rx: role === 'client' ? s2c : c2s,\n served: 0,\n };\n }\n};\n\nconst rpcIsOpen = (ch, conn) =>\n Atomics.load(ch.hdr, RPC_CONN) === conn &&\n Atomics.load(ch.hdr, RPC_CLOSED) !== conn &&\n Atomics.load(ch.hdr, RPC_FAILED) === 0;\n\nconst rpcWakeAll = (hdr) => {\n for (const i of [RPC_CONN, ...RPC_RING_IDX, RPC_ACCEPTED]) {\n Atomics.notify(hdr, i);\n }\n};\n\nconst _wllama_rpc_has = (port) => (rpcChannels[port] ? 1 : 0);\n\n// server: wait for the next connection from the client\n// the previous connection is done here, so the rings are reset here and not by the client:\n// otherwise the server could still read the new connection's data for the previous one\nconst _wllama_rpc_accept = (port) => {\n const ch = rpcChannels[port];\n if (!ch) return 0;\n while (true) {\n const conn = Atomics.load(ch.hdr, RPC_CONN);\n if (conn > ch.served) {\n ch.served = conn;\n for (const i of RPC_RING_IDX) Atomics.store(ch.hdr, i, 0);\n Atomics.store(ch.hdr, RPC_ACCEPTED, conn);\n Atomics.notify(ch.hdr, RPC_ACCEPTED);\n return conn;\n }\n Atomics.wait(ch.hdr, RPC_CONN, conn, RPC_WAIT_MS);\n }\n};\n\n// client: start a new connection, and wait for the server to accept it (it resets the rings)\nconst _wllama_rpc_connect = (port) => {\n const ch = rpcChannels[port];\n if (!ch) return 0;\n const conn = Atomics.add(ch.hdr, RPC_CONN, 1) + 1;\n // the server can be waiting for data of the previous connection\n rpcWakeAll(ch.hdr);\n while (true) {\n if (Atomics.load(ch.hdr, RPC_FAILED) !== 0) return 0;\n const accepted = Atomics.load(ch.hdr, RPC_ACCEPTED);\n // a newer connection was accepted: this one is already closed\n if (accepted >= conn) return accepted === conn ? conn : 0;\n Atomics.wait(ch.hdr, RPC_ACCEPTED, accepted, RPC_WAIT_MS);\n }\n};\n\n// head and tail count bytes and wrap at 2^31, (head - tail) | 0 is still the used size\nconst _wllama_rpc_send = (port, conn, ptr, size) => {\n const ch = rpcChannels[port];\n const { hdr, cap, tx } = ch;\n let done = 0;\n while (done < size) {\n if (!rpcIsOpen(ch, conn)) return 0;\n const head = Atomics.load(hdr, tx.head);\n const tail = Atomics.load(hdr, tx.tail);\n const free = cap - ((head - tail) | 0);\n if (free === 0) {\n Atomics.wait(hdr, tx.tail, tail, RPC_WAIT_MS);\n continue;\n }\n const pos = head & (cap - 1);\n const n = Math.min(free, size - done, cap - pos);\n tx.data.set(rpcHeapU8().subarray(ptr + done, ptr + done + n), pos);\n Atomics.store(hdr, tx.head, (head + n) | 0);\n Atomics.notify(hdr, tx.head);\n done += n;\n }\n return 1;\n};\n\nconst _wllama_rpc_recv = (port, conn, ptr, size) => {\n const ch = rpcChannels[port];\n const { hdr, cap, rx } = ch;\n let done = 0;\n while (done < size) {\n const head = Atomics.load(hdr, rx.head);\n const tail = Atomics.load(hdr, rx.tail);\n const used = (head - tail) | 0;\n if (used === 0) {\n if (!rpcIsOpen(ch, conn)) return 0;\n Atomics.wait(hdr, rx.head, head, RPC_WAIT_MS);\n continue;\n }\n const pos = tail & (cap - 1);\n const n = Math.min(used, size - done, cap - pos);\n rpcHeapU8().set(rx.data.subarray(pos, pos + n), ptr + done);\n Atomics.store(hdr, rx.tail, (tail + n) | 0);\n Atomics.notify(hdr, rx.tail);\n done += n;\n }\n return 1;\n};\n\nconst _wllama_rpc_close = (port, conn) => {\n const ch = rpcChannels[port];\n if (!ch) return;\n Atomics.store(ch.hdr, RPC_CLOSED, conn);\n rpcWakeAll(ch.hdr);\n};\n\n// server: the wasm failed, so the client fails its pending and next calls instead of waiting forever\nconst rpcFailAll = () => {\n for (const ch of Object.values(rpcChannels)) {\n Atomics.store(ch.hdr, RPC_FAILED, 1);\n rpcWakeAll(ch.hdr);\n }\n};\n\n// pthread workers get the channels as their first message, see the Worker wrapper in llama-cpp.js\nself.addEventListener('message', (e) => {\n if (e.data?.cmd === 'wllamaRpc') {\n rpcSetChannels(e.data.channels);\n e.stopImmediatePropagation();\n }\n});\n";