From ebddf0dbecef3ef5ba44fceedf9936f8e5f12ca9 Mon Sep 17 00:00:00 2001 From: Georgy Date: Thu, 27 Aug 2026 23:13:47 +0300 Subject: [PATCH] feat: add local WebGPU LLM playground --- .ai/ARCHITECTURE.md | 19 + .ai/FEATURES.md | 18 +- .ai/FIXES.md | 9 +- .ai/HANDOFF.md | 40 +- .ai/PERFORMANCE.md | 25 +- .ai/PERSISTENCE.md | 9 + .ai/TODO.md | 16 +- .ai/baselines/build-budgets.json | 16 +- .gitignore | 4 + components.d.ts | 1 + locales/en.yml | 3 + package.json | 6 + pnpm-lock.yaml | 557 +++++++++++++++++- public/assets/local-llm-models/README.md | 10 + scripts/build-stats.mjs | 5 +- scripts/build-stats.test.mjs | 2 + scripts/download-local-llm-models.mjs | 158 +++++ scripts/standalone-build-config.mjs | 1 + scripts/standalone-build.test.mjs | 1 + src/tools/all-tools-smoke.e2e.spec.ts | 2 +- src/tools/index.ts | 34 +- src/tools/local-llm-playground/index.ts | 18 + .../local-llm-cache.test.ts | 84 +++ .../local-llm-playground/local-llm-cache.ts | 122 ++++ .../local-llm-model-assets.json | 54 ++ .../local-llm-playground.e2e.spec.ts | 88 +++ .../local-llm-playground.vue | 550 +++++++++++++++++ .../local-llm-progress.test.ts | 34 ++ .../local-llm-progress.ts | 61 ++ .../local-llm.models.test.ts | 23 + .../local-llm-playground/local-llm.models.ts | 88 +++ .../local-llm.protocol.test.ts | 73 +++ .../local-llm.protocol.ts | 230 ++++++++ .../local-llm.worker-client.test.ts | 123 ++++ .../local-llm.worker-client.ts | 303 ++++++++++ .../local-llm-playground/local-llm.worker.ts | 286 +++++++++ .../shell-existing-route-wave.e2e.spec.ts | 2 +- vite.config.ts | 6 +- 38 files changed, 3024 insertions(+), 57 deletions(-) create mode 100644 public/assets/local-llm-models/README.md create mode 100644 scripts/download-local-llm-models.mjs create mode 100644 src/tools/local-llm-playground/index.ts create mode 100644 src/tools/local-llm-playground/local-llm-cache.test.ts create mode 100644 src/tools/local-llm-playground/local-llm-cache.ts create mode 100644 src/tools/local-llm-playground/local-llm-model-assets.json create mode 100644 src/tools/local-llm-playground/local-llm-playground.e2e.spec.ts create mode 100644 src/tools/local-llm-playground/local-llm-playground.vue create mode 100644 src/tools/local-llm-playground/local-llm-progress.test.ts create mode 100644 src/tools/local-llm-playground/local-llm-progress.ts create mode 100644 src/tools/local-llm-playground/local-llm.models.test.ts create mode 100644 src/tools/local-llm-playground/local-llm.models.ts create mode 100644 src/tools/local-llm-playground/local-llm.protocol.test.ts create mode 100644 src/tools/local-llm-playground/local-llm.protocol.ts create mode 100644 src/tools/local-llm-playground/local-llm.worker-client.test.ts create mode 100644 src/tools/local-llm-playground/local-llm.worker-client.ts create mode 100644 src/tools/local-llm-playground/local-llm.worker.ts diff --git a/.ai/ARCHITECTURE.md b/.ai/ARCHITECTURE.md index 94e6c22d96..a82fb0cc76 100644 --- a/.ai/ARCHITECTURE.md +++ b/.ai/ARCHITECTURE.md @@ -33,6 +33,17 @@ The common worker lifecycle is implemented by `src/utils/worker-protocol.ts`, both request and response envelopes; replacement, cancellation, timeout, and unmount terminate the physical worker. +Local LLM Playground is a narrow route-owned exception to the shared worker +helpers because Transformers.js owns streaming callbacks and interruption. Its +typed client still validates every envelope, permits one operation, applies +timeouts and physical replacement, and creates the 4.2.0 runtime worker only +after explicit Load. The worker accepts three fixed Qwen3.5 model IDs, loads q4 +text-only decoder/embed artifacts on WebGPU, and never loads the vision encoder. +Each tier is pinned to a reviewed upstream commit and fetched exclusively from +the same-origin `assets/local-llm-models//` mirror. Remote model +fallback is disabled. `pnpm models:download` materializes the untracked mirror; +`pnpm models:check` is the pre-deployment completeness/size gate. + Production caches the shell and demand-caches opened lazy assets. Development does not register a service worker and removes only IT Tools-owned stale PWA state. Storage and privacy rules are in `PERSISTENCE.md`. @@ -54,6 +65,14 @@ in memory, and sends downloads and external links to the parent through `EXPORT` and `OPEN_URL` messages. None of these choices affect the normal `dist/` build. +The normal generated registry contains 134 tools. Local LLM Playground is +excluded from standalone because DataLens denies workers and network access and +because the inference runtime alone exceeds the single-file budget. Its worker, +ONNX Runtime WASM, and model files are also absent from mandatory PWA precache. +Normal builds copy an available 4.98 GiB server-side model mirror into `dist/`, +but build statistics intentionally exclude that separately versioned static +payload from JavaScript/shell budgets. + Standalone worker compatibility is executable policy: the CSP sandbox test runs a valid operation through all 48 included worker clients in Chromium, Firefox, and WebKit, while a source-inventory test requires exact case coverage. diff --git a/.ai/FEATURES.md b/.ai/FEATURES.md index c8779df183..ff9b567f52 100644 --- a/.ai/FEATURES.md +++ b/.ai/FEATURES.md @@ -1,7 +1,7 @@ # Feature State The approved browser-only catalog is implemented. The generated registry -currently contains 133 lazy tools across Crypto, Converter, Web, Images and +currently contains 134 lazy tools across Crypto, Converter, Web, Images and videos, Development, Network, Math, Measurement, Text, and Data. The catalog includes the final approved additions: local mock data, IPv6/CIDR, @@ -10,16 +10,22 @@ cron schedules, barcode workflows, JWK/JWKS and asymmetric JWT verification, OpenAPI inspection, PKCS#12/public PEM inspection, offline GeoIP, and the local encrypted OTP vault. +Local LLM Playground is the only model-inference tool. It offers fixed +text-only Qwen3.5 Lite 0.8B, Standard 2B, and Quality 4B tiers through local +WebGPU inference with explicit same-origin downloads, per-file parallel +progress, streaming stop, and removable cache. Runtime model traffic never +falls back to Hugging Face or a model API. + The definitive inventory is generated from `src/tools/*/index.ts`; do not keep a second hand-maintained list here. Every tool keeps its own icon and lazy route component. The optional single-file build contains 126 tools. Its reviewed exclusions are -Camera Recorder, DNS over HTTPS Query, Local Encrypted OTP Vault, Mermaid -Diagram, Offline GeoIP Inspector, PDF Signature Checker, and Text Diff. The -reasons are sandbox permissions/network policy, unavailable opaque-origin -storage, or the strict 10 MiB artifact budget. These tools remain present in -the normal 133-tool application. +Camera Recorder, DNS over HTTPS Query, Local Encrypted OTP Vault, Local LLM +Playground, Mermaid Diagram, Offline GeoIP Inspector, PDF Signature Checker, +and Text Diff. The reasons are sandbox permissions/network policy, unavailable +opaque-origin storage, unsupported workers, or the strict 10 MiB artifact +budget. These tools remain present in the normal 134-tool application. No new feature backlog is approved. Server-dependent products, account/cloud features, network scanning, remote GeoIP/API services, heavy OCR/PDF workspaces, diff --git a/.ai/FIXES.md b/.ai/FIXES.md index 64abf737aa..ac129d3b54 100644 --- a/.ai/FIXES.md +++ b/.ai/FIXES.md @@ -1,14 +1,21 @@ # Resolved Engineering State The approved correctness, security, delivery, persistence, and performance -work is complete as of 2026-08-16. +work is complete as of 2026-08-27. - Production dependency audit has no known advisory in the approved graph. +- Scoped transitive overrides keep the browser-only Transformers dependency's + unused Node branches on `sharp` 0.35.0 and `adm-zip` 0.6.0; composerize uses + security-fixed `deepmerge-ts` 8.0.2 with its conversion tests retained. - Crypto, YAML, i18n, Ajv, forge/PKI, nginx, and container concerns were fixed or replaced with bounded browser-local implementations and executable gates. - Registry generation keeps routes lazy and preserves each tool's individual icon; category-wide icon substitution is explicitly a regression. - Large transforms and sensitive operations have bounded worker lifecycles. +- Local LLM parallel downloads render one monotonic bar per file instead of + interleaving aggregate and per-file percentages. Its pinned q4 artifacts are + served same-origin only; Transformers.js remote fallback is disabled and a + focused browser regression rejects Hugging Face runtime traffic. - Root, subpath, reverse-proxy, security-header, PWA, Firefox, WebKit, Chromium, and Long Task coverage exists in the repository. - Storage migrations, quota failure, rollback, and stale-cache cleanup are diff --git a/.ai/HANDOFF.md b/.ai/HANDOFF.md index 37259995aa..3c14377403 100644 --- a/.ai/HANDOFF.md +++ b/.ai/HANDOFF.md @@ -3,7 +3,7 @@ ## State The final approved product package is implemented. There is no remaining -feature plan. The application is a browser-only static SPA/PWA with 133 lazy +feature plan. The application is a browser-only static SPA/PWA with 134 lazy tool routes, generated from per-tool typed metadata. Unique tool icons are a product requirement and are preserved by the registry generator. @@ -11,10 +11,11 @@ The repository may be intentionally dirty; inspect `git status` and never overwrite unrelated local-fork work. Do not merge, rebase, or cherry-pick upstream automatically. -Current checkpoint: branch `feat-ai-research`, base commit -`2530780ffb46bd309172aa21ff38d0881cd45cd1`. The 2026-08-24 standalone worker -compatibility audit is present as uncommitted local work at handoff time; keep -the whole worktree together when committing or transferring it. +Current checkpoint: branch `feat/ai-tools-local-llm-1842`, based on commit +`5395615c0c9537ebf78b20e6c7b275f4ab3fa794`. The branch tip packages the final +approved browser-tool catalog, persistence/UI/performance work, standalone +delivery, and the 2026-08-27 Local LLM same-origin model mirror. Keep the whole +branch together when reviewing or transferring it. ## Resume @@ -38,8 +39,8 @@ the touched surface. ## Standalone/DataLens -The final artifact is `dist-standalone/it-tools.html`: one 7,989,122-byte file -(7.62 MiB; 7,991,173-byte JSON upload envelope) with 126 tools and no runtime +The final artifact is `dist-standalone/it-tools.html`: one 7,994,866-byte file +(7.62 MiB; 7,996,917-byte JSON upload envelope) with 126 tools and no runtime network resources. `pnpm test:standalone` rebuilds it from current sources and runs Chromium, Firefox, and WebKit serially. @@ -62,11 +63,26 @@ plain router-link menu is intentional; the normal application still uses `NMenu`. Do not add intermediate-reuse flags to the build—the fresh build and unconditional cleanup are part of the stale-cache defense. -Green gates for the 2026-08-24 audit: `pnpm test:standalone` (4 Node tests and -6 Playwright tests; 48/48 worker operations in Chromium, Firefox, and WebKit), -`pnpm lint`, `pnpm test:unit` (262 files / 1,466 tests), and `pnpm build`. -The final normal build restored full generated component declarations, including -the camera-specific icons excluded only from standalone. +Local LLM Playground is normal-build-only. It provides fixed Qwen3.5 Lite 0.8B, +Standard 2B, and Quality 4B q4 text models through a lazy Transformers.js 4.2.0 +WebGPU worker with explicit download, storage/hardware preflight, streaming, +cancellation, bounds, unload, and scoped cache deletion. Prompts and output are +ephemeral. The 23.6 MB raw inference WASM and 4.98 GiB pinned q4 mirror are +absent from shell, Workbox, and standalone. Runtime requests use only the +same-origin revision path; Hugging Face fallback is disabled. The generated +mirror is intentionally untracked: run `pnpm models:download`, then +`pnpm models:check`, before publishing the normal build. Actual GPU/model +acceptance remains a hardware-manual non-claim. + +Green focused gates on 2026-08-27: lint, typecheck, 267 Vitest files / 1,482 +tests, production build, all 430 build budgets, 28-file / 4.98 GiB model mirror +completeness check, and four Chromium Local LLM route/privacy/same-origin +smokes. The 2026-08-25 release gates also include a clean production dependency +audit, Docker converter compatibility after security overrides, Firefox/WebKit +route coverage, strict dev runtime, and standalone (4 Node + 6 browser tests; +48/48 included worker paths). +The Orca desktop runtime was unavailable after the documented open retry, so +interactive visual/model acceptance was not claimed. ## Invariants diff --git a/.ai/PERFORMANCE.md b/.ai/PERFORMANCE.md index 74b1d7f7fa..157bf28d51 100644 --- a/.ai/PERFORMANCE.md +++ b/.ai/PERFORMANCE.md @@ -2,15 +2,14 @@ ## Current baseline -The generated registry contains 133 lazy routes. The accepted normal build on -2026-08-17 measured a 687,421-byte raw / 186,417-byte gzip main entry, a -716,733-byte raw / 192,710-byte gzip shell including the document, and a -53-file, 970,294-byte raw / 313,252-byte gzip Workbox payload. All 426 build -budget checks passed with unique tool icons preserved. +The generated registry contains 134 lazy routes. The accepted normal build on +2026-08-25 measured a 719,149-byte raw / 193,054-byte gzip shell including the +document and a 53-file, 972,710-byte raw / 313,568-byte gzip Workbox payload. +All 430 build budget checks passed with unique tool icons preserved. The accepted standalone artifact contains 126 tools in one HTML file. It is -7,989,122 bytes (7.62 MiB); the JSON upload envelope `{ "html": ... }` is -7,991,173 bytes. Both are below the strict 10 MiB limit. The build fails if +7,994,866 bytes (7.62 MiB); the JSON upload envelope `{ "html": ... }` is +7,996,917 bytes. Both are below the strict 10 MiB limit. The build fails if either measurement exceeds that limit and always removes its intermediate directory to prevent stale-build reuse. The increase records the exhaustive standalone-only 48-client compatibility audit and its small XLSX fixture; it @@ -23,6 +22,18 @@ Emoji search is worker-backed and virtualized. Monaco remains accepted for Text Diff: the smaller CodeMirror spike lost focus, undo, and history when publishing async diff results. +Local LLM Playground adds a 23,351-byte raw / 7,960-byte gzip route UI and a +503,343-byte raw / 147,220-byte gzip explicit-action worker; its measured +additional route closure is 607,745/182,692 bytes raw/gzip. Its separate ONNX +Runtime WASM is 23,567,050 bytes raw / 5,699,349 bytes gzip. Neither runtime +asset enters the shell, Workbox precache, or standalone build. The pinned +same-origin q4 mirror is 4.98 GiB total (0.62/1.45/2.91 GiB); one selected tier +downloads only after Load and parallel files render as independent progress +bars. The mirror is copied as separately versioned static delivery data and is +excluded from JS/shell build statistics. On the 2026-08-25 +production Chromium run, first client-side route readiness was 171 ms with a +0.0 ms longest observed task and no worker/model request before Load. + ## Gates `.ai/baselines/build-budgets.json` is the sole detailed budget source. It diff --git a/.ai/PERSISTENCE.md b/.ai/PERSISTENCE.md index 3bf18ede78..5d1d1bb4b6 100644 --- a/.ai/PERSISTENCE.md +++ b/.ai/PERSISTENCE.md @@ -16,6 +16,15 @@ in memory only while unlocked, and there are no accounts or synchronization. Locking, timeout, close, migration failure, or cryptographic failure clears decrypted state. +Local LLM Playground has a separate non-content cache exception. After an +explicit Load, Transformers.js may store only fixed public model/runtime +responses plus a completion marker in `it-tools-local-llm-models-v1`. The user +can remove the selected model from the tool. Prompts, system instructions, +generated text, model selection, and generation options remain memory-only; +unmount terminates the worker and clears text state. Model responses originate +only from the same-origin pinned static mirror; no tool content or model request +is sent to Hugging Face at runtime. + Development PWA cleanup may unregister only the root IT Tools `sw.js` and delete only `workbox-precache-*`, `it-tools-lazy-assets-*`, and `figlet-fonts-*`. It must not clear local/session content or unrelated origins/caches. diff --git a/.ai/TODO.md b/.ai/TODO.md index 0b73a0b244..9907b8e6cb 100644 --- a/.ai/TODO.md +++ b/.ai/TODO.md @@ -1,7 +1,14 @@ # Approved Work -There is no remaining approved feature backlog. Do not invent additional tools -or revive removed upstream lists. +## Active approved work + +There is no active feature backlog. The approved Local LLM Playground is +implemented in the normal build with Lite 0.8B, Standard 2B, and Quality 4B; +Max, vision, automatic downloads, PWA precaching, and standalone inclusion are +deliberately absent. The three approved q4 tiers are mirrored same-origin from +pinned revisions; runtime Hugging Face fallback is prohibited. + +Do not invent additional tools or revive removed upstream lists. Future work begins only from an explicit user request or a locally reproduced regression. Before implementation, record the narrow scope here, including any @@ -24,4 +31,7 @@ privacy defaults, worker limits/cancellation, and build budgets intact. ## Upstream adaptations -None are currently approved or pending. +No upstream application code or design is approved for adaptation. The local +implementation consumes exact Apache-2.0 `@huggingface/transformers` 4.2.0 and +the three fixed Qwen3.5 ONNX model repositories; integration code and UI remain +local-fork work. diff --git a/.ai/baselines/build-budgets.json b/.ai/baselines/build-budgets.json index 1994592e77..566aeb9402 100644 --- a/.ai/baselines/build-budgets.json +++ b/.ai/baselines/build-budgets.json @@ -45,9 +45,9 @@ "rationale": "The measured 466,920 B raw / 85,086 B gzip demand-loaded search worker owns Fuse plus the updated 1,914-entry Unicode Emoji 16.0 and emojilib 4.0.3 keyword catalogs. It remains below the 500 kB chunk gate, is fetched only after a query, and feeds a truly windowed grid with physical replacement, cancellation, a three-second deadline, exact query/result bounds, and a strict 4x-CPU sub-50-ms Long Task gate." }, "assets/docker-converter.worker-.js": { - "rawBytes": 215000, - "gzipBytes": 66000, - "rationale": "The measured 206,522 B raw / 63,261 B gzip route-owned worker contains the existing composerize-ts path plus YAML parsing for the new reverse Compose-to-run direction. Both directions share strict 16 KiB live, 256 KiB input, 512 KiB output, message-count/size, four-second, cancellation, stale-result, and disposal bounds; the worker remains demand-loaded and below the 500 kB chunk gate." + "rawBytes": 220000, + "gzipBytes": 68000, + "rationale": "The measured 215,146 B raw / 66,380 B gzip route-owned worker contains the existing composerize-ts path plus YAML parsing for the reverse Compose-to-run direction. Its small increase records the scoped deepmerge-ts 8.0.2 security override that closes GHSA-ggr8-5vv4-36mx. Both directions share strict 16 KiB live, 256 KiB input, 512 KiB output, message-count/size, four-second, cancellation, stale-result, and disposal bounds; the worker remains demand-loaded and below the 500 kB chunk gate." }, "assets/devops-config-workspace.worker-.js": { "rawBytes": 155000, @@ -134,6 +134,11 @@ "gzipBytes": 3000, "rationale": "The measured 5,074 B raw / 2,171 B gzip route-owned worker reads bounded 4 MiB file windows, detects common magic signatures, streams CRC-32, and emits only a 4 KiB hex preview. It never buffers the whole file and is terminated on completion, cancellation, timeout, replacement, or disposal." }, + "assets/local-llm.worker-.js": { + "rawBytes": 520000, + "gzipBytes": 155000, + "rationale": "The measured 503,343 B raw / 147,220 B gzip explicit-action worker contains exact Transformers.js 4.2.0 and the bounded Qwen3.5 text-only WebGPU runtime. It accepts only the three fixed 0.8B/2B/4B q4 model IDs, loads no vision encoder, streams bounded output, validates cumulative transport bounds, supports interruption and physical replacement, keeps prompts ephemeral, and uses a dedicated removable Cache Storage namespace. Pinned model files are same-origin-only with remote fallback disabled. The runtime is absent from the initial shell, mandatory Workbox precache, and standalone build; its separately emitted 23,567,050 B raw / 5,699,349 B gzip ONNX Runtime WASM is fetched only after Load." + }, "assets/mock-data-generator.worker-.js": { "rawBytes": 8000, "gzipBytes": 4000, @@ -266,6 +271,11 @@ "gzipBytes": 80000, "rationale": "The measured 168,815 B raw / 71,948 B gzip additional closure includes the 4,927/2,021 B diff worker plus existing markdown-it and patched DOMPurify 3.4.13 loaded only with this route. Preview is explicit-result-only, limited to 64 KiB per side, disables raw HTML/linkification/active links/images, and uses a static HTML-only no-attribute sanitizer allow-list. No Monaco, CodeMirror, second Markdown parser, or new diff dependency is included." }, + "src/tools/local-llm-playground/local-llm-playground.vue": { + "rawBytes": 625000, + "gzipBytes": 190000, + "rationale": "The measured 607,745 B raw / 182,692 B gzip additional closure consists primarily of the separately budgeted 503,343/147,220 B route worker plus a 23,351/7,960 B route UI and shared dependencies. The ONNX Runtime WASM is a separate 23,567,050/5,699,349 B demand asset. Pinned q4 model files are served only from a same-origin 4.98 GiB static mirror after explicit confirmation; remote fallback is disabled. Runtime and weights remain outside the initial shell, mandatory Workbox precache, standalone build, and JavaScript build statistics. The narrow exception records the unavoidable browser inference runtime instead of weakening the global 500 kB route gate." + }, "src/tools/openapi-inspector/openapi-inspector.vue": { "rawBytes": 130000, "gzipBytes": 45000, diff --git a/.gitignore b/.gitignore index 888bf1c20c..2bbf492ed2 100644 --- a/.gitignore +++ b/.gitignore @@ -34,5 +34,9 @@ coverage /test-results/ /playwright-report/ /playwright/.cache/ +# Generated, pinned Local LLM weights; keep the small tracked README only. +/public/assets/local-llm-models/*/ +/public/assets/local-llm-models/.download-manifest.json +/public/assets/local-llm-models/*.part # Webkit with playwright creates a salt file salt diff --git a/components.d.ts b/components.d.ts index 9ffd51b0ad..4f71b794db 100644 --- a/components.d.ts +++ b/components.d.ts @@ -157,6 +157,7 @@ declare module '@vue/runtime-core' { LocalEncryptedOtpVault: typeof import('./src/tools/local-encrypted-otp-vault/local-encrypted-otp-vault.vue')['default'] LocaleSelector: typeof import('./src/modules/i18n/components/locale-selector.vue')['default'] LocalFileInspector: typeof import('./src/tools/local-file-inspector/local-file-inspector.vue')['default'] + LocalLlmPlayground: typeof import('./src/tools/local-llm-playground/local-llm-playground.vue')['default'] LoremIpsumGenerator: typeof import('./src/tools/lorem-ipsum-generator/lorem-ipsum-generator.vue')['default'] MacAddressGenerator: typeof import('./src/tools/mac-address-generator/mac-address-generator.vue')['default'] MacAddressLookup: typeof import('./src/tools/mac-address-lookup/mac-address-lookup.vue')['default'] diff --git a/locales/en.yml b/locales/en.yml index 7909ec1dd0..49499f8b37 100644 --- a/locales/en.yml +++ b/locales/en.yml @@ -259,6 +259,9 @@ tools: mock-data-generator: title: Mock data generator description: Generate reproducible people, addresses, dates, internet values, identifiers, and JSON or CSV fixtures locally in your browser. + local-llm-playground: + title: Local LLM playground + description: Run Qwen3.5 Lite, Standard, or Quality entirely in your browser with WebGPU, streaming output, and removable local model caches. percentage-calculator: title: Percentage calculator description: Easily calculate percentages from a value to another value, or from a percentage to a value. diff --git a/package.json b/package.json index bbbec27edb..7eb256025b 100644 --- a/package.json +++ b/package.json @@ -15,11 +15,14 @@ "@babel/core": "7.29.7", "@babel/helpers": "7.29.7", "@babel/runtime": "7.29.7", + "@huggingface/transformers>sharp": "0.35.0", "brace-expansion": "1.1.18", + "composerize-ts>deepmerge-ts": "8.0.2", "fast-uri": "3.1.5", "ip-address": "10.5.0", "linkify-it": "5.0.2", "node-forge": "1.4.0", + "onnxruntime-node>adm-zip": "0.6.0", "lodash-es": "4.18.1", "minimatch@<3.1.3": "3.1.5", "nanoid": "3.3.18", @@ -71,11 +74,14 @@ "lint": "eslint src --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --ignore-path .gitignore --ignore-pattern 'src/tools/mac-address-lookup/data/**/*.json'", "generate:oui-data": "node scripts/generate-oui-data.mjs", "generate:tool-registry": "node scripts/generate-tool-registry.mjs", + "models:download": "node scripts/download-local-llm-models.mjs", + "models:check": "node scripts/download-local-llm-models.mjs --check", "script:create:tool": "node scripts/create-tool.mjs", "script:create:ui": "hygen generator ui-component", "release": "node ./scripts/release.mjs" }, "dependencies": { + "@huggingface/transformers": "4.2.0", "@it-tools/bip39": "^0.0.4", "@it-tools/oggen": "^1.3.0", "@noble/hashes": "2.2.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b1e0718dd4..0de1579e09 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,11 +8,14 @@ overrides: '@babel/core': 7.29.7 '@babel/helpers': 7.29.7 '@babel/runtime': 7.29.7 + '@huggingface/transformers>sharp': 0.35.0 brace-expansion: 1.1.18 + composerize-ts>deepmerge-ts: 8.0.2 fast-uri: 3.1.5 ip-address: 10.5.0 linkify-it: 5.0.2 node-forge: 1.4.0 + onnxruntime-node>adm-zip: 0.6.0 lodash-es: 4.18.1 minimatch@<3.1.3: 3.1.5 nanoid: 3.3.18 @@ -24,6 +27,9 @@ importers: .: dependencies: + '@huggingface/transformers': + specifier: 4.2.0 + version: 4.2.0 '@it-tools/bip39': specifier: ^0.0.4 version: 0.0.4 @@ -1141,6 +1147,9 @@ packages: peerDependencies: vue: ^3.0.11 + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} + '@emotion/hash@0.8.0': resolution: {integrity: sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow==} @@ -1438,6 +1447,16 @@ packages: resolution: {integrity: sha512-P6omY1zv5MItm93kLM8s2vr1HICJH8v0dvddDhysbIuZ+vcjOHg5Zbkf1mTkcmi2JA9oBG2anOkRnW8WJTS8Og==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + '@huggingface/jinja@0.5.9': + resolution: {integrity: sha512-uWTG+l3VJRsl7EXxYizuL3P+cCPoc3cRqbWWRcQN0FhejRfbdq0RNhCmbY/YDtnTcz9icdLYuLDjsnz4d8JMuw==} + engines: {node: '>=18'} + + '@huggingface/tokenizers@0.1.3': + resolution: {integrity: sha512-8rF/RRT10u+kn7YuUbUg0OF30K8rjTc78aHpxT+qJ1uWSqxT1MHi8+9ltwYfkFYJzT/oS+qw3JVfHtNMGAdqyA==} + + '@huggingface/transformers@4.2.0': + resolution: {integrity: sha512-8BRCoBMH0XsWaEIamuR0LrJGAfftgHAfb2Vrffy0VKlSAE/MnUJ5/h/zTfEP3fDIft+nk7TqB8xXEyABGitBjQ==} + '@humanwhocodes/config-array@0.11.10': resolution: {integrity: sha512-KVVjQmNUepDVGXNuoRRdmmEjruj0KfiGSbS8LVc12LMsWDQzRXJ0qdhN8L8uUigKpfEHRhlaQFY0ib1tnUbNeQ==} engines: {node: '>=10.10.0'} @@ -1463,6 +1482,152 @@ packages: '@iconify/utils@2.2.0': resolution: {integrity: sha512-9A5eZQV9eKlNCXlI/SgYsGRS7YmGmB1oAsRpNVIYBmIzGJRgH+hfG+lo4069s+GFWFNnBAtDg10c53vQZBLfnA==} + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.35.0': + resolution: {integrity: sha512-ZgaYEwaj+lx/5n4W8GmZ2IYz0PQHjN5eqRcfijWGB+2Aq7ZInZGa0qJyAn6DEtyLuWHRSrmWOqT9q3qqTBvmUQ==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [darwin] + + '@img/sharp-darwin-x64@0.35.0': + resolution: {integrity: sha512-c1z9LFpKB0slQW3RchwBE8iSVzGp70TNjUUO9k4BZwwW4HH7JBGHeIy4b+kk4n/kcBASb9evKCE3/7Slmslgiw==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [darwin] + + '@img/sharp-freebsd-wasm32@0.35.0': + resolution: {integrity: sha512-Li2KTev0H90kEtnJHkI9xQojXt1AqWmFBMXiPw5kqd1jQgP7gi5HVK/qC5Rmh/59NuAwUuPzzPITmX22NomYYQ==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.0': + resolution: {integrity: sha512-EKbmBKtyTH+GPFDRw2TgK2oV6hyxxlJVIar4hoTYSNmIwipgMFdxPQqR392GmfdsPGWga0mCFN1cCKjRb9cljw==} + cpu: [arm64] + os: [darwin] + + '@img/sharp-libvips-darwin-x64@1.3.0': + resolution: {integrity: sha512-Pl2OmOvrJ42adUllESxBsG54PfXLo1OYg9i3c5/5Ln/qJ0gZuTM9YMhQJPIbXqwidLRc/c2zuHt4RsrymmNv7A==} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-linux-arm64@1.3.0': + resolution: {integrity: sha512-C0SqjoFKnszqa44EQ7xoaT48nnO0lOyXEULfXMWi8krrjOPGYkeK30Okzla6ATbBYsyZ0ySinK0FVkpv3DwzfQ==} + cpu: [arm64] + os: [linux] + + '@img/sharp-libvips-linux-arm@1.3.0': + resolution: {integrity: sha512-A8UpHoUDW4DwnXoV6+q3C1s7QLRAHtPDEjWuNZjwHMyoCNZnm0GeNN8ls9f/bsEYTRQRW96C/n34XJQHJ2fT7A==} + cpu: [arm] + os: [linux] + + '@img/sharp-libvips-linux-ppc64@1.3.0': + resolution: {integrity: sha512-WOpkVxAjFd369iaIzEgNRreFD+gWdUMIGD5zplhNKNeqS6mm5dac3q2AFyCBmzYoAdouzZvRBgxy4z8QHZb4/A==} + cpu: [ppc64] + os: [linux] + + '@img/sharp-libvips-linux-riscv64@1.3.0': + resolution: {integrity: sha512-DRWw0mOHusrCCuw2rqP87oLg6PGlkomVDFqw2hIwsSfwWpu4k3XLcBPaKKl6ct/GtL/cwNkgwjV/tc0Mqht3VA==} + cpu: [riscv64] + os: [linux] + + '@img/sharp-libvips-linux-s390x@1.3.0': + resolution: {integrity: sha512-9APy+nFWhHS+kzLgWZfLcyrUd7YqnAQVa4BPOo4xkoHpdoktOAPG4cEr9+Jpl0TtqfVmcMJimNL5qNTyyOHZNA==} + cpu: [s390x] + os: [linux] + + '@img/sharp-libvips-linux-x64@1.3.0': + resolution: {integrity: sha512-y9RNUYDe2A1UAdhLyfeOodGRszQdaEoe4nfOpp/sNVPl2CWIcUyFaDoCh4vPLPxu19803j2naLqZup2WxDXCLA==} + cpu: [x64] + os: [linux] + + '@img/sharp-libvips-linuxmusl-arm64@1.3.0': + resolution: {integrity: sha512-cC1wkC0Mlucd0KSiGrLkJnB/ZqPvZCntc/Lk7ZnYO5ZSbF2euNek4Xvxafojq+wN1q/W0eprdpUIjUr/EV2PBg==} + cpu: [arm64] + os: [linux] + + '@img/sharp-libvips-linuxmusl-x64@1.3.0': + resolution: {integrity: sha512-LiYMhUZicB1QG//+RvmYZpXJO8fYRENfp+MZUCnG9aw+AKvGAy9gPaCnuwsPcBFs8EV66M0NNxj9VHcNklE8zw==} + cpu: [x64] + os: [linux] + + '@img/sharp-linux-arm64@0.35.0': + resolution: {integrity: sha512-4+4XHLNT5wDT0roYlHTEmH9lDKt0acf9Tv+3hM3iceOirkxrR404/3WjAYZ9F9CkHrxeRcGLJXbi4vluMZ9O+A==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + + '@img/sharp-linux-arm@0.35.0': + resolution: {integrity: sha512-VVlpEWwizEFIOom0zdoeKuO5nuTswzVE5uHcBNvHzmeHUpNFajY3HFfbQ+zIH4E2kVaZ/yVxmsShW56TtEy4uA==} + engines: {node: '>=20.9.0'} + cpu: [arm] + os: [linux] + + '@img/sharp-linux-ppc64@0.35.0': + resolution: {integrity: sha512-N3hzbEpUTJC8pWpPVJvgzGxM+so/MAXc8O2s/53B0LL9ZGpfXpME7Wizkc5d/8fRBlBtkDjzoZGDCqqNDHqLEw==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + + '@img/sharp-linux-riscv64@0.35.0': + resolution: {integrity: sha512-l6vmKVPnbS0RhVMbyxP5meAARsbhCnBN4fy31qz0+3a6Rv4jEqfzDrT89y6ZPkCi0AJGnwp2En528yXo401Hpw==} + engines: {node: '>=20.9.0'} + cpu: [riscv64] + os: [linux] + + '@img/sharp-linux-s390x@0.35.0': + resolution: {integrity: sha512-MYlMiPFiv/EKPAHnp3yNZ9AAWFsxga9c5Bkc6wkar6bqzHLlkGVJHRm0u1ei+VXnZxp3Mz9MG9ZIsI8vSOf3sQ==} + engines: {node: '>=20.9.0'} + cpu: [s390x] + os: [linux] + + '@img/sharp-linux-x64@0.35.0': + resolution: {integrity: sha512-TYaItB5oj1ioXjhyn2xrR208vf+YuIIcHptQWRRaBmFhvIvL9D72DXN8w75xup0KXA8UdEAhQ9Qb2S49FD/9Cw==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + + '@img/sharp-linuxmusl-arm64@0.35.0': + resolution: {integrity: sha512-DSTb6ijQzqe6DdAaOBVqJ/SYf1vO8EW5bK6X6LRXufEBebf2722VCdvBUtZ3rtV0x2ApfPNDy/p7LrrjaWjiyQ==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [linux] + + '@img/sharp-linuxmusl-x64@0.35.0': + resolution: {integrity: sha512-K7ykQ+26Rt6+4BTU80AuGgTPIYX86UxiAKT4rcXX/WNTo7k1ZxpKz+TguHnwVpCqQK3B5PK0vZ0ZBe6nz/ib1w==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [linux] + + '@img/sharp-wasm32@0.35.0': + resolution: {integrity: sha512-9woLIFORERCr+6cWu87dQ22J34EExkhc73U1kZW0c+RclQqWetoodByp4dWZ/hN8/KVmTRAx2HOnUwib8AwZdA==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.0': + resolution: {integrity: sha512-t+kie1TOyaDM6Dho+f+y0VqIUNhYQaKCUahuZVi0E0frgdiaOaPsDxDW3wfKacUdaNBCnK/ZDBMg33ydvHj8uA==} + engines: {node: '>=20.9.0'} + cpu: [wasm32] + + '@img/sharp-win32-arm64@0.35.0': + resolution: {integrity: sha512-M5eKxug0dabbaWgFKvPa3odNs2OpaP+81NASfGKkt4GcYXpNhSu7CaeYxWkLNV6vHmUp4hnCxnxrUyhUJhXbKA==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.0': + resolution: {integrity: sha512-z0+pZ03QCDvdVN0Ez9IX/yjWC19ikMlXrmdYMwYNLTh2BLPx3hXWPvyqWfquZ0BTO9O6GVOjIVoTcyyacMnWlQ==} + engines: {node: ^20.9.0} + cpu: [ia32] + os: [win32] + + '@img/sharp-win32-x64@0.35.0': + resolution: {integrity: sha512-feNnlz5ZHKr0MY1LPHvZQyJeBkbo4ctsn0D8FvA53VTw5TC63rfEL2UrWbkSBR19htSE7Mw78xYVwdJqoMWVHw==} + engines: {node: '>=20.9.0'} + cpu: [x64] + os: [win32] + '@intlify/bundle-utils@7.5.0': resolution: {integrity: sha512-6DymqusddBQ8kVtVBsVFFF7arNfIhuLacOmmsqayT2vl427j9m0VX12mMC+cgoVIodSpRfzYPaPTdPuJq7mK0Q==} engines: {node: '>= 14.16'} @@ -1637,6 +1802,33 @@ packages: '@popperjs/core@2.11.8': resolution: {integrity: sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==} + '@protobufjs/aspromise@1.1.2': + resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} + + '@protobufjs/base64@1.1.2': + resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==} + + '@protobufjs/codegen@2.0.5': + resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==} + + '@protobufjs/eventemitter@1.1.1': + resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==} + + '@protobufjs/fetch@1.1.1': + resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==} + + '@protobufjs/float@1.0.2': + resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==} + + '@protobufjs/path@1.1.2': + resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==} + + '@protobufjs/pool@1.1.0': + resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==} + + '@protobufjs/utf8@1.1.2': + resolution: {integrity: sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==} + '@regexper/parser@1.0.0': resolution: {integrity: sha512-S8AWIGpCNdl9PNHdbhI6TpXZsPk6FDU/RTZI+6UFF4rVFqDQKjCIbZSgFu7NihoEZKq57wKFPbbT1EzrjVvPHA==} @@ -2434,6 +2626,10 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + adm-zip@0.6.0: + resolution: {integrity: sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg==} + engines: {node: '>=14.0'} + agent-base@6.0.2: resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} engines: {node: '>= 6.0.0'} @@ -2553,6 +2749,10 @@ packages: boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} + boolean@3.2.0: + resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. + brace-expansion@1.1.18: resolution: {integrity: sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==} @@ -3089,9 +3289,9 @@ packages: deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} - deepmerge-ts@5.1.0: - resolution: {integrity: sha512-eS8dRJOckyo9maw9Tu5O5RUi/4inFLrnoLkBe3cPfDMx3WZioXtmOew4TXQaxq7Rhl4xjDtR7c6x8nNTxOvbFw==} - engines: {node: '>=16.0.0'} + deepmerge-ts@8.0.2: + resolution: {integrity: sha512-uqbvqLUMrc6p0MO+WBRtTxY55hmyh94WRwI5a++PZe54X+bfVh59FSN7uWCBCW1CCVjzjnrwzfI8zidE2obMMw==} + engines: {node: '>=16.9.0'} deepmerge@2.2.1: resolution: {integrity: sha512-R9hc1Xa/NOBi9WRVUWg19rl1UB7Tt4kuPd+thNJgFZoxXsTz7ncaPaeIm+40oSGuP33DfMb4sZt1QIGiJzC4EA==} @@ -3141,6 +3341,13 @@ packages: destr@2.0.3: resolution: {integrity: sha512-2N3BOUU4gYMpTP24s5rF5iP7BDr7uNTCs4ozw3kf/eKfvWSIu93GEBi5m427YoyJoeOzQ5smuu4nNAPGb8idSQ==} + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + detect-node@2.1.0: + resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==} + diff-sequences@29.4.3: resolution: {integrity: sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -3283,6 +3490,9 @@ packages: resolution: {integrity: sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==} engines: {node: '>= 0.4'} + es6-error@4.1.1: + resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==} + esbuild@0.18.20: resolution: {integrity: sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==} engines: {node: '>=12'} @@ -3581,6 +3791,9 @@ packages: resolution: {integrity: sha512-dm9s5Pw7Jc0GvMYbshN6zchCA9RgQlzzEZX3vylR9IqFfS8XciblUXOKfW6SiuJ0e13eDYZoZV5wdrev7P3Nwg==} engines: {node: ^10.12.0 || >=12.0.0} + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} + flatted@3.2.7: resolution: {integrity: sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==} @@ -3696,6 +3909,10 @@ packages: engines: {node: '>=12'} deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + global-agent@3.0.0: + resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==} + engines: {node: '>=10.0'} + globals@11.12.0: resolution: {integrity: sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==} engines: {node: '>=4'} @@ -3740,6 +3957,9 @@ packages: resolution: {integrity: sha512-5v6yZd4JK3eMI3FqqCouswVqwugaA9r4dNZB1wwcmrD02QkV5H0y7XBQW8QwQqEaZY1pM9aqORSORhJRdNK44Q==} engines: {node: '>=6.0'} + guid-typescript@1.0.9: + resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==} + gzip-size@6.0.0: resolution: {integrity: sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q==} engines: {node: '>=10'} @@ -4209,6 +4429,9 @@ packages: json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + json-stringify-safe@5.0.1: + resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==} + json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} @@ -4313,6 +4536,9 @@ packages: resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} engines: {node: '>=10'} + long@5.3.2: + resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==} + loupe@2.3.6: resolution: {integrity: sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==} deprecated: Please upgrade to 2.3.7 which fixes GHSA-4q6p-r6v2-jvc5 @@ -4376,6 +4602,10 @@ packages: engines: {node: '>= 18'} hasBin: true + matcher@3.0.0: + resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==} + engines: {node: '>=10'} + math-intrinsics@1.0.0: resolution: {integrity: sha512-4MqMiKP90ybymYvsut0CH2g4XWbfLtmlCkXmtmdcDCxNB+mQcu1w/1+L/VD7vi/PSv7X2JYV7SCcR+jiPXnQtA==} engines: {node: '>= 0.4'} @@ -4662,6 +4892,19 @@ packages: resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} engines: {node: '>=6'} + onnxruntime-common@1.24.0-dev.20251116-b39e144322: + resolution: {integrity: sha512-BOoomdHYmNRL5r4iQ4bMvsl2t0/hzVQ3OM3PHD0gxeXu1PmggqBv3puZicEUVOA3AtHHYmqZtjMj9FOfGrATTw==} + + onnxruntime-common@1.24.3: + resolution: {integrity: sha512-GeuPZO6U/LBJXvwdaqHbuUmoXiEdeCjWi/EG7Y1HNnDwJYuk6WUbNXpF6luSUY8yASul3cmUlLGrCCL1ZgVXqA==} + + onnxruntime-node@1.24.3: + resolution: {integrity: sha512-JH7+czbc8ALA819vlTgcV+Q214/+VjGeBHDjX81+ZCD0PCVCIFGFNtT0V4sXG/1JXypKPgScQcB3ij/hk3YnTg==} + os: [win32, darwin, linux] + + onnxruntime-web@1.26.0-dev.20260416-b7804b056c: + resolution: {integrity: sha512-MD6Ss4GSpQBo6zqoJzyT9LRbKYs7x/JVN23FT24EcEvlqF4VuzPOeH6X38orZPKHQDbprn7K+SBpu0/mj2CQiw==} + open@8.4.2: resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==} engines: {node: '>=12'} @@ -4827,6 +5070,9 @@ packages: resolution: {integrity: sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw==} engines: {node: '>=16.0.0'} + platform@1.3.6: + resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==} + plausible-tracker@0.3.8: resolution: {integrity: sha512-lmOWYQ7s9KOUJ1R+YTOR3HrjdbxIS2Z4de0P/Jx2dQPteznJl2eX3tXxKClpvbfyGP59B5bbhW8ftN59HbbFSg==} engines: {node: '>=10'} @@ -4947,6 +5193,10 @@ packages: proto-list@1.2.4: resolution: {integrity: sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA==} + protobufjs@7.6.5: + resolution: {integrity: sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==} + engines: {node: '>=12.0.0'} + prr@1.0.1: resolution: {integrity: sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==} @@ -5115,6 +5365,10 @@ packages: deprecated: Rimraf versions prior to v4 are no longer supported hasBin: true + roarr@2.15.4: + resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==} + engines: {node: '>=8.0'} + robust-predicates@3.0.3: resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} @@ -5182,6 +5436,9 @@ packages: seemly@0.3.6: resolution: {integrity: sha512-lEV5VB8BUKTo/AfktXJcy+JeXns26ylbMkIUco8CYREsQijuz4mrXres2Q+vMLdwkuLxJdIPQ8IlCIxLYm71Yw==} + semver-compare@1.0.0: + resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==} + semver@5.7.2: resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==} hasBin: true @@ -5205,12 +5462,21 @@ packages: engines: {node: '>=10'} hasBin: true + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + sentence-case@2.1.1: resolution: {integrity: sha512-ENl7cYHaK/Ktwk5OTD+aDbQ3uC8IByu/6Bkg+HDv8Mm+XnBnppVNalcfJTNsp1ibstKh030/JKQQWglDvtKwEQ==} sentence-case@3.0.4: resolution: {integrity: sha512-8LS0JInaQMCRoQ7YUytAo/xUu5W2XnQxV2HI/6uM6U7CITS1RqPElr30V6uIqyMKM9lJGRVFy5/4CuzcixNYSg==} + serialize-error@7.0.1: + resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==} + engines: {node: '>=10'} + serialize-javascript@6.0.2: resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==} @@ -5229,6 +5495,10 @@ packages: resolution: {integrity: sha512-zTEg4HL0RwVrqcWs3ztF+x1vkxfm0lP+MQQFPiMJTKVceBwEV0A569Ou8l9IYQG8jOZdMVI1hGsc0tmeD2o/Lw==} engines: {node: '>=11.0'} + sharp@0.35.0: + resolution: {integrity: sha512-BqvG5XbwPZ4NV0DK90d86leEECMsoa8bO0nqnKWlBDYxri4GJ7c4EDInaF6q20lTh/mATmnDIKWJFfXnoVfH5g==} + engines: {node: '>=20.9.0'} + shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} @@ -5325,6 +5595,9 @@ packages: sprintf-js@1.0.3: resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==} + sprintf-js@1.1.3: + resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==} + sql-formatter@13.0.0: resolution: {integrity: sha512-V21cVvge4rhn9Fa7K/fTKcmPM+x1yee6Vhq8ZwgaWh3VPBqApgsaoFB5kLAhiqRo5AmSaRyLU7LIdgnNwH01/w==} hasBin: true @@ -5545,6 +5818,10 @@ packages: resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==} engines: {node: '>=4'} + type-fest@0.13.1: + resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==} + engines: {node: '>=10'} + type-fest@0.16.0: resolution: {integrity: sha512-eaBzG6MxNzEn9kiwvtre90cXaNLkmadMWa1zQMs3XORCXNbsH/OewwbxC5ia9dCxIxnTAsSxXJaa/p5y8DlvJg==} engines: {node: '>=10'} @@ -7226,6 +7503,11 @@ snapshots: dependencies: vue: 3.3.4 + '@emnapi/runtime@1.11.3': + dependencies: + tslib: 2.8.1 + optional: true + '@emotion/hash@0.8.0': {} '@esbuild/aix-ppc64@0.23.1': @@ -7389,6 +7671,18 @@ snapshots: '@eslint/js@8.47.0': {} + '@huggingface/jinja@0.5.9': {} + + '@huggingface/tokenizers@0.1.3': {} + + '@huggingface/transformers@4.2.0': + dependencies: + '@huggingface/jinja': 0.5.9 + '@huggingface/tokenizers': 0.1.3 + onnxruntime-node: 1.24.3 + onnxruntime-web: 1.26.0-dev.20260416-b7804b056c + sharp: 0.35.0 + '@humanwhocodes/config-array@0.11.10': dependencies: '@humanwhocodes/object-schema': 1.2.1 @@ -7431,6 +7725,112 @@ snapshots: transitivePeerDependencies: - supports-color + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.35.0': + optionalDependencies: + '@img/sharp-libvips-darwin-arm64': 1.3.0 + optional: true + + '@img/sharp-darwin-x64@0.35.0': + optionalDependencies: + '@img/sharp-libvips-darwin-x64': 1.3.0 + optional: true + + '@img/sharp-freebsd-wasm32@0.35.0': + dependencies: + '@img/sharp-wasm32': 0.35.0 + optional: true + + '@img/sharp-libvips-darwin-arm64@1.3.0': + optional: true + + '@img/sharp-libvips-darwin-x64@1.3.0': + optional: true + + '@img/sharp-libvips-linux-arm64@1.3.0': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.0': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.0': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.0': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.0': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.0': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.0': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.0': + optional: true + + '@img/sharp-linux-arm64@0.35.0': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.0 + optional: true + + '@img/sharp-linux-arm@0.35.0': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.0 + optional: true + + '@img/sharp-linux-ppc64@0.35.0': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.0 + optional: true + + '@img/sharp-linux-riscv64@0.35.0': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.0 + optional: true + + '@img/sharp-linux-s390x@0.35.0': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.0 + optional: true + + '@img/sharp-linux-x64@0.35.0': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.0 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.0': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.0 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.0': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.0 + optional: true + + '@img/sharp-wasm32@0.35.0': + dependencies: + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.0': + dependencies: + '@img/sharp-wasm32': 0.35.0 + optional: true + + '@img/sharp-win32-arm64@0.35.0': + optional: true + + '@img/sharp-win32-ia32@0.35.0': + optional: true + + '@img/sharp-win32-x64@0.35.0': + optional: true + '@intlify/bundle-utils@7.5.0(vue-i18n@9.14.5(vue@3.3.4))': dependencies: '@intlify/message-compiler': 9.9.1 @@ -7637,6 +8037,26 @@ snapshots: '@popperjs/core@2.11.8': {} + '@protobufjs/aspromise@1.1.2': {} + + '@protobufjs/base64@1.1.2': {} + + '@protobufjs/codegen@2.0.5': {} + + '@protobufjs/eventemitter@1.1.1': {} + + '@protobufjs/fetch@1.1.1': + dependencies: + '@protobufjs/aspromise': 1.1.2 + + '@protobufjs/float@1.0.2': {} + + '@protobufjs/path@1.1.2': {} + + '@protobufjs/pool@1.1.0': {} + + '@protobufjs/utf8@1.1.2': {} + '@regexper/parser@1.0.0': {} '@regexper/render@1.0.0': @@ -8117,7 +8537,7 @@ snapshots: debug: 4.4.0 globby: 11.1.0 is-glob: 4.0.3 - semver: 7.6.3 + semver: 7.8.5 tsutils: 3.21.0(typescript@5.2.2) optionalDependencies: typescript: 5.2.2 @@ -8145,7 +8565,7 @@ snapshots: debug: 4.4.0 globby: 11.1.0 is-glob: 4.0.3 - semver: 7.6.3 + semver: 7.8.5 ts-api-utils: 1.0.1(typescript@5.2.2) optionalDependencies: typescript: 5.2.2 @@ -8162,7 +8582,7 @@ snapshots: '@typescript-eslint/typescript-estree': 5.60.0(typescript@5.2.2) eslint: 8.47.0 eslint-scope: 5.1.1 - semver: 7.6.3 + semver: 7.8.5 transitivePeerDependencies: - supports-color - typescript @@ -8686,6 +9106,8 @@ snapshots: acorn@8.9.0: {} + adm-zip@0.6.0: {} + agent-base@6.0.2: dependencies: debug: 4.4.0 @@ -8817,6 +9239,8 @@ snapshots: boolbase@1.0.0: {} + boolean@3.2.0: {} + brace-expansion@1.1.18: dependencies: balanced-match: 1.0.2 @@ -9050,7 +9474,7 @@ snapshots: composerize-ts@0.6.2: dependencies: commander: 10.0.0 - deepmerge-ts: 5.1.0 + deepmerge-ts: 8.0.2 flex-js: 1.0.5 ip-cidr: 3.1.0 set-value: 4.1.0 @@ -9403,7 +9827,7 @@ snapshots: deep-is@0.1.4: {} - deepmerge-ts@5.1.0: {} + deepmerge-ts@8.0.2: {} deepmerge@2.2.1: {} @@ -9443,6 +9867,10 @@ snapshots: destr@2.0.3: {} + detect-libc@2.1.2: {} + + detect-node@2.1.0: {} + diff-sequences@29.4.3: {} diff@5.2.2: {} @@ -9626,6 +10054,8 @@ snapshots: is-date-object: 1.1.0 is-symbol: 1.1.1 + es6-error@4.1.1: {} + esbuild@0.18.20: optionalDependencies: '@esbuild/android-arm': 0.18.20 @@ -9749,7 +10179,7 @@ snapshots: is-glob: 4.0.3 minimatch: 3.1.5 resolve: 1.22.9 - semver: 7.6.3 + semver: 7.8.5 transitivePeerDependencies: - '@typescript-eslint/parser' - eslint-import-resolver-typescript @@ -10033,6 +10463,8 @@ snapshots: flatted: 3.2.7 rimraf: 3.0.2 + flatbuffers@25.9.23: {} + flatted@3.2.7: {} flex-js@1.0.5: {} @@ -10159,6 +10591,15 @@ snapshots: minimatch: 5.1.9 once: 1.4.0 + global-agent@3.0.0: + dependencies: + boolean: 3.2.0 + es6-error: 4.1.1 + matcher: 3.0.0 + roarr: 2.15.4 + semver: 7.8.5 + serialize-error: 7.0.1 + globals@11.12.0: {} globals@13.20.0: @@ -10206,6 +10647,8 @@ snapshots: section-matter: 1.0.0 strip-bom-string: 1.0.0 + guid-typescript@1.0.9: {} + gzip-size@6.0.0: dependencies: duplexer: 0.1.2 @@ -10655,6 +11098,8 @@ snapshots: json-stable-stringify-without-jsonify@1.0.1: {} + json-stringify-safe@5.0.1: {} + json5@2.2.3: {} jsonc-eslint-parser@2.3.0: @@ -10753,6 +11198,8 @@ snapshots: chalk: 4.1.2 is-unicode-supported: 0.1.0 + long@5.3.2: {} + loupe@2.3.6: dependencies: get-func-name: 2.0.0 @@ -10831,6 +11278,10 @@ snapshots: marked@10.0.0: {} + matcher@3.0.0: + dependencies: + escape-string-regexp: 4.0.0 + math-intrinsics@1.0.0: {} mathjs@11.9.1: @@ -11247,6 +11698,25 @@ snapshots: dependencies: mimic-fn: 2.1.0 + onnxruntime-common@1.24.0-dev.20251116-b39e144322: {} + + onnxruntime-common@1.24.3: {} + + onnxruntime-node@1.24.3: + dependencies: + adm-zip: 0.6.0 + global-agent: 3.0.0 + onnxruntime-common: 1.24.3 + + onnxruntime-web@1.26.0-dev.20260416-b7804b056c: + dependencies: + flatbuffers: 25.9.23 + guid-typescript: 1.0.9 + long: 5.3.2 + onnxruntime-common: 1.24.0-dev.20251116-b39e144322 + platform: 1.3.6 + protobufjs: 7.6.5 + open@8.4.2: dependencies: define-lazy-prop: 2.0.0 @@ -11428,6 +11898,8 @@ snapshots: pvutils: 1.2.0 tslib: 2.8.1 + platform@1.3.6: {} + plausible-tracker@0.3.8: {} playwright-core@1.62.1: {} @@ -11582,6 +12054,20 @@ snapshots: proto-list@1.2.4: {} + protobufjs@7.6.5: + dependencies: + '@protobufjs/aspromise': 1.1.2 + '@protobufjs/base64': 1.1.2 + '@protobufjs/codegen': 2.0.5 + '@protobufjs/eventemitter': 1.1.1 + '@protobufjs/fetch': 1.1.1 + '@protobufjs/float': 1.0.2 + '@protobufjs/path': 1.1.2 + '@protobufjs/pool': 1.1.0 + '@protobufjs/utf8': 1.1.2 + '@types/node': 18.15.11 + long: 5.3.2 + prr@1.0.1: optional: true @@ -11751,6 +12237,15 @@ snapshots: dependencies: glob: 7.2.3 + roarr@2.15.4: + dependencies: + boolean: 3.2.0 + detect-node: 2.1.0 + globalthis: 1.0.4 + json-stringify-safe: 5.0.1 + semver-compare: 1.0.0 + sprintf-js: 1.1.3 + robust-predicates@3.0.3: {} rollup@2.79.2: @@ -11812,6 +12307,8 @@ snapshots: seemly@0.3.6: {} + semver-compare@1.0.0: {} + semver@5.7.2: {} semver@6.3.1: {} @@ -11826,6 +12323,8 @@ snapshots: semver@7.6.3: {} + semver@7.8.5: {} + sentence-case@2.1.1: dependencies: no-case: 2.3.2 @@ -11837,6 +12336,10 @@ snapshots: tslib: 2.5.0 upper-case-first: 2.0.2 + serialize-error@7.0.1: + dependencies: + type-fest: 0.13.1 + serialize-javascript@6.0.2: dependencies: randombytes: 2.1.0 @@ -11864,6 +12367,38 @@ snapshots: is-plain-object: 2.0.4 is-primitive: 3.0.1 + sharp@0.35.0: + dependencies: + '@img/colour': 1.1.0 + detect-libc: 2.1.2 + semver: 7.8.5 + optionalDependencies: + '@img/sharp-darwin-arm64': 0.35.0 + '@img/sharp-darwin-x64': 0.35.0 + '@img/sharp-freebsd-wasm32': 0.35.0 + '@img/sharp-libvips-darwin-arm64': 1.3.0 + '@img/sharp-libvips-darwin-x64': 1.3.0 + '@img/sharp-libvips-linux-arm': 1.3.0 + '@img/sharp-libvips-linux-arm64': 1.3.0 + '@img/sharp-libvips-linux-ppc64': 1.3.0 + '@img/sharp-libvips-linux-riscv64': 1.3.0 + '@img/sharp-libvips-linux-s390x': 1.3.0 + '@img/sharp-libvips-linux-x64': 1.3.0 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.0 + '@img/sharp-libvips-linuxmusl-x64': 1.3.0 + '@img/sharp-linux-arm': 0.35.0 + '@img/sharp-linux-arm64': 0.35.0 + '@img/sharp-linux-ppc64': 0.35.0 + '@img/sharp-linux-riscv64': 0.35.0 + '@img/sharp-linux-s390x': 0.35.0 + '@img/sharp-linux-x64': 0.35.0 + '@img/sharp-linuxmusl-arm64': 0.35.0 + '@img/sharp-linuxmusl-x64': 0.35.0 + '@img/sharp-webcontainers-wasm32': 0.35.0 + '@img/sharp-win32-arm64': 0.35.0 + '@img/sharp-win32-ia32': 0.35.0 + '@img/sharp-win32-x64': 0.35.0 + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 @@ -11962,6 +12497,8 @@ snapshots: sprintf-js@1.0.3: {} + sprintf-js@1.1.3: {} + sql-formatter@13.0.0: dependencies: argparse: 2.0.1 @@ -12195,6 +12732,8 @@ snapshots: type-detect@4.0.8: {} + type-fest@0.13.1: {} + type-fest@0.16.0: {} type-fest@0.20.2: {} diff --git a/public/assets/local-llm-models/README.md b/public/assets/local-llm-models/README.md new file mode 100644 index 0000000000..e40c032efc --- /dev/null +++ b/public/assets/local-llm-models/README.md @@ -0,0 +1,10 @@ +# Local LLM model mirror + +Runtime model files in this directory are generated by +`pnpm models:download`. They are pinned, text-only q4 artifacts from the +Apache-2.0 licensed Qwen3.5 ONNX repositories listed in +`src/tools/local-llm-playground/local-llm-model-assets.json`. + +The multi-gigabyte generated revision directories and download manifest are +deliberately not tracked by Git. They must be present when publishing a build +that includes Local LLM Playground. Run `pnpm models:check` before deployment. diff --git a/scripts/build-stats.mjs b/scripts/build-stats.mjs index 01725c1f0d..e65e9fa436 100644 --- a/scripts/build-stats.mjs +++ b/scripts/build-stats.mjs @@ -21,6 +21,7 @@ const DEFAULT_DIST_DIRECTORY = 'dist'; const DEFAULT_LARGEST_ASSET_COUNT = 20; const VITE_MANIFEST_CANDIDATES = ['.vite/manifest.json', 'manifest.json']; const JAVASCRIPT_ARTIFACT_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']); +const EXCLUDED_STATIC_ASSET_PREFIXES = ['assets/local-llm-models/']; const MANDATORY_ASYNC_SHELL_SOURCES = new Set([ 'src/layouts/base.layout.vue', 'src/modules/pwa/OfflineRouteUnavailable.vue', @@ -388,7 +389,9 @@ function toReportRecord(record) { } async function collectFileRecords(distDirectory) { - const paths = await listFiles(distDirectory); + const paths = (await listFiles(distDirectory)).filter(path => ( + !EXCLUDED_STATIC_ASSET_PREFIXES.some(prefix => path.startsWith(prefix)) + )); return Promise.all( paths.map(async (actualPath) => { diff --git a/scripts/build-stats.test.mjs b/scripts/build-stats.test.mjs index 93f13e04a6..9bac8d9c0d 100644 --- a/scripts/build-stats.test.mjs +++ b/scripts/build-stats.test.mjs @@ -30,6 +30,7 @@ async function createFixture(t, { basePath = '/' } = {}) { }); await mkdir(assetsDirectory, { recursive: true }); + await mkdir(join(assetsDirectory, 'local-llm-models'), { recursive: true }); const viteManifest = { '_shared-feedface.js': { file: 'assets/shared-feedface.js', @@ -87,6 +88,7 @@ async function createFixture(t, { basePath = '/' } = {}) { writeFile(join(distDirectory, NESTED_WORKER_PATH), 'self.postMessage("nested worker");\n'), writeFile(join(distDirectory, UNRELATED_WORKER_PATH), 'self.postMessage("unrelated");\n'), writeFile(join(assetsDirectory, 'icon.png'), Buffer.from([0x89, 0x50, 0x4E, 0x47])), + writeFile(join(assetsDirectory, 'local-llm-models', 'weight.onnx_data'), Buffer.alloc(1024, 0x7F)), writeFile(join(distDirectory, 'manifest.json'), `${JSON.stringify(viteManifest, null, 2)}\n`), writeFile( join(distDirectory, 'sw.js'), diff --git a/scripts/download-local-llm-models.mjs b/scripts/download-local-llm-models.mjs new file mode 100644 index 0000000000..311e633dcf --- /dev/null +++ b/scripts/download-local-llm-models.mjs @@ -0,0 +1,158 @@ +#!/usr/bin/env node + +import { createWriteStream } from 'node:fs'; +import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import process from 'node:process'; +import { Readable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { fileURLToPath } from 'node:url'; + +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const catalogPath = resolve(repositoryRoot, 'src/tools/local-llm-playground/local-llm-model-assets.json'); +const outputRoot = resolve(repositoryRoot, 'public/assets/local-llm-models'); +const manifestPath = resolve(outputRoot, '.download-manifest.json'); +const selectedKeys = new Set(process.argv.slice(2).filter(argument => !argument.startsWith('--'))); +const checkOnly = process.argv.includes('--check'); +const concurrency = 2; + +function formatBytes(bytes) { + if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(2)} GiB`; + if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MiB`; + return `${bytes} B`; +} + +async function readJson(path, fallback) { + try { + return JSON.parse(await readFile(path, 'utf8')); + } + catch (error) { + if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return fallback; + throw error; + } +} + +const catalog = await readJson(catalogPath); +if (catalog.schemaVersion !== 1 || !Array.isArray(catalog.models)) { + throw new TypeError('Unsupported local LLM model asset catalog.'); +} + +const models = catalog.models.filter(model => selectedKeys.size === 0 || selectedKeys.has(model.key)); +if (models.length === 0 || [...selectedKeys].some(key => !catalog.models.some(model => model.key === key))) { + throw new TypeError(`Select one or more known model tiers: ${catalog.models.map(model => model.key).join(', ')}`); +} + +const tasks = models.flatMap(model => model.files.map(file => ({ ...model, file }))); +const manifest = await readJson(manifestPath, { schemaVersion: 1, files: {} }); + +function relativeAssetPath(task) { + return `${task.revision}/${task.modelId}/${task.file}`; +} + +async function verifyTask(task) { + const relativePath = relativeAssetPath(task); + const record = manifest.files?.[relativePath]; + const fileStat = await stat(resolve(outputRoot, relativePath)).catch(() => undefined); + if (!record || record.revision !== task.revision || !fileStat?.isFile() || fileStat.size !== record.bytes || fileStat.size < 1) { + throw new Error(`Missing or incomplete local model asset: ${relativePath}`); + } + return fileStat.size; +} + +if (checkOnly) { + let totalBytes = 0; + for (const task of tasks) totalBytes += await verifyTask(task); + process.stdout.write(`local-llm-models: ${tasks.length} files verified (${formatBytes(totalBytes)})\n`); + process.exit(0); +} + +let manifestWrite = Promise.resolve(); +async function persistManifest() { + manifestWrite = manifestWrite.then(async () => { + await mkdir(outputRoot, { recursive: true }); + const temporaryPath = `${manifestPath}.tmp`; + await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`); + await rename(temporaryPath, manifestPath); + }); + await manifestWrite; +} + +async function downloadTask(task) { + const relativePath = relativeAssetPath(task); + try { + const bytes = await verifyTask(task); + process.stdout.write(`cached ${relativePath} (${formatBytes(bytes)})\n`); + return bytes; + } + catch { + // Missing or partial assets are downloaded below. + } + + const destination = resolve(outputRoot, relativePath); + const temporaryPath = `${destination}.part`; + await mkdir(dirname(destination), { recursive: true }); + const existingBytes = (await stat(temporaryPath).catch(() => undefined))?.size ?? 0; + const url = `https://huggingface.co/${task.modelId}/resolve/${task.revision}/${task.file}`; + const headers = existingBytes > 0 ? { Range: `bytes=${existingBytes}-` } : undefined; + let response = await fetch(url, { headers, redirect: 'follow' }); + if (response.status === 416 && existingBytes > 0) { + const remoteBytes = Number(response.headers.get('content-range')?.match(/\*\/(\d+)$/u)?.[1]); + if (Number.isFinite(remoteBytes) && remoteBytes === existingBytes) { + await rename(temporaryPath, destination); + manifest.files ??= {}; + manifest.files[relativePath] = { + bytes: existingBytes, + modelId: task.modelId, + revision: task.revision, + source: url, + }; + await persistManifest(); + process.stdout.write(`ready ${relativePath} (${formatBytes(existingBytes)})\n`); + return existingBytes; + } + response = await fetch(url, { redirect: 'follow' }); + } + if (!response.ok || !response.body) { + throw new Error(`Download failed (${response.status}) for ${url}`); + } + + const append = existingBytes > 0 && response.status === 206; + const offset = append ? existingBytes : 0; + const contentLength = response.headers.get('content-length'); + const responseBytes = contentLength === null ? Number.NaN : Number(contentLength); + const expectedBytes = Number.isFinite(responseBytes) && responseBytes >= 0 ? offset + responseBytes : undefined; + process.stdout.write(`download ${relativePath}${append ? ` (resume at ${formatBytes(offset)})` : ''}\n`); + await pipeline( + Readable.fromWeb(response.body), + createWriteStream(temporaryPath, { flags: append ? 'a' : 'w' }), + ); + + const downloadedBytes = (await stat(temporaryPath)).size; + if (expectedBytes !== undefined && downloadedBytes !== expectedBytes) { + throw new Error(`Incomplete download for ${relativePath}: ${downloadedBytes} of ${expectedBytes} bytes`); + } + await rename(temporaryPath, destination); + manifest.files ??= {}; + manifest.files[relativePath] = { + bytes: downloadedBytes, + modelId: task.modelId, + revision: task.revision, + source: url, + }; + await persistManifest(); + process.stdout.write(`ready ${relativePath} (${formatBytes(downloadedBytes)})\n`); + return downloadedBytes; +} + +let nextTaskIndex = 0; +let totalBytes = 0; +async function worker() { + while (nextTaskIndex < tasks.length) { + const task = tasks[nextTaskIndex++]; + const downloadedBytes = await downloadTask(task); + totalBytes += downloadedBytes; + } +} + +await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, () => worker())); +process.stdout.write(`local-llm-models: ${tasks.length} files ready (${formatBytes(totalBytes)})\n`); diff --git a/scripts/standalone-build-config.mjs b/scripts/standalone-build-config.mjs index 99a99af41a..771df84d02 100644 --- a/scripts/standalone-build-config.mjs +++ b/scripts/standalone-build-config.mjs @@ -7,6 +7,7 @@ export const STANDALONE_EXCLUDED_TOOL_DIRECTORIES = [ 'camera-recorder', 'dns-over-https-query', 'local-encrypted-otp-vault', + 'local-llm-playground', 'mermaid-diagram', 'offline-geoip-inspector', 'pdf-signature-checker', diff --git a/scripts/standalone-build.test.mjs b/scripts/standalone-build.test.mjs index 0eda5791de..740267dd66 100644 --- a/scripts/standalone-build.test.mjs +++ b/scripts/standalone-build.test.mjs @@ -41,6 +41,7 @@ test('generates a standalone-only registry without the reviewed heavyweight rout 'camera-recorder', 'dns-over-https-query', 'local-encrypted-otp-vault', + 'local-llm-playground', 'mermaid-diagram', 'offline-geoip-inspector', 'pdf-signature-checker', diff --git a/src/tools/all-tools-smoke.e2e.spec.ts b/src/tools/all-tools-smoke.e2e.spec.ts index 6ecd04eb7f..84de8cca6a 100644 --- a/src/tools/all-tools-smoke.e2e.spec.ts +++ b/src/tools/all-tools-smoke.e2e.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from '@playwright/test'; -const MINIMUM_TOOL_COUNT = 133; +const MINIMUM_TOOL_COUNT = 134; const FORBIDDEN_CONSOLE_WARNINGS = [ /Could not create web worker/i, /Falling back to loading web worker code in main thread/i, diff --git a/src/tools/index.ts b/src/tools/index.ts index b6e9169af9..97fa0e204b 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -1,12 +1,12 @@ /* eslint-disable import/order -- generated imports mix packages, Vite virtual modules, and local SVGs */ // This file is generated by scripts/generate-tool-registry.mjs. Do not edit manually. -import { ArrowsShuffle as ToolIcon0, Certificate as ToolIcon10, Key as ToolIcon11, FileCertificate as ToolIcon13, Calendar as ToolIcon14, ArrowsLeftRight as ToolIcon15, LetterX as ToolIcon16, FileDigit as ToolIcon17, TextWrap as ToolIcon18, Palette as ToolIcon19, Fingerprint as ToolIcon2, LetterCaseToggle as ToolIcon20, Speakerphone as ToolIcon21, Binary as ToolIcon22, Braces as ToolIcon23, List as ToolIcon24, Markdown as ToolIcon26, Link as ToolIcon27, Code as ToolIcon28, Unlink as ToolIcon29, SortDescendingNumbers as ToolIcon3, DeviceDesktop as ToolIcon30, Tags as ToolIcon32, DeviceMobile as ToolIcon33, World as ToolIcon34, Keyboard as ToolIcon35, Edit as ToolIcon37, Browser as ToolIcon38, EyeOff as ToolIcon4, Mailbox as ToolIcon41, Qrcode as ToolIcon42, Scan as ToolIcon43, Camera as ToolIcon45, BrandGit as ToolIcon46, Terminal2 as ToolIcon47, SettingsAutomation as ToolIcon48, FileText as ToolIcon49, Hash as ToolIcon5, Database as ToolIcon50, FileSearch as ToolIcon52, Server as ToolIcon53, Alarm as ToolIcon54, FileCheck as ToolIcon55, FileInvoice as ToolIcon56, BrandDocker as ToolIcon57, Mail as ToolIcon58, Language as ToolIcon59, LockSquare as ToolIcon6, BrandJavascript as ToolIcon60, Api as ToolIcon61, Devices as ToolIcon64, BuildingFactory as ToolIcon65, MapSearch as ToolIcon66, Math as ToolIcon67, Hourglass as ToolIcon68, Percentage as ToolIcon69, Lock as ToolIcon7, Temperature as ToolIcon71, FileDiff as ToolIcon73, MoodSmile as ToolIcon74, Artboard as ToolIcon76, Phone as ToolIcon79, AlignJustified as ToolIcon8 } from '@vicons/tabler'; -import { PasswordRound as ToolIcon31, AbcRound as ToolIcon36, HttpRound as ToolIcon39, CompareArrowsRound as ToolIcon40, ImageOutlined as ToolIcon44, AccountTreeOutlined as ToolIcon51, RouterOutlined as ToolIcon62, UnfoldMoreOutlined as ToolIcon63, TimerOutlined as ToolIcon70, SpeedFilled as ToolIcon72, TableChartOutlined as ToolIcon77, GridOnOutlined as ToolIcon78, ShortTextRound as ToolIcon9 } from '@vicons/material'; +import { ArrowsShuffle as ToolIcon0, Certificate as ToolIcon10, Key as ToolIcon11, FileCertificate as ToolIcon13, Calendar as ToolIcon14, ArrowsLeftRight as ToolIcon15, LetterX as ToolIcon16, FileDigit as ToolIcon17, TextWrap as ToolIcon18, Palette as ToolIcon19, Fingerprint as ToolIcon2, LetterCaseToggle as ToolIcon20, Speakerphone as ToolIcon21, Binary as ToolIcon22, Braces as ToolIcon23, List as ToolIcon24, Markdown as ToolIcon26, Link as ToolIcon27, Code as ToolIcon28, Unlink as ToolIcon29, SortDescendingNumbers as ToolIcon3, DeviceDesktop as ToolIcon30, Tags as ToolIcon32, DeviceMobile as ToolIcon33, World as ToolIcon34, Keyboard as ToolIcon35, Edit as ToolIcon37, Browser as ToolIcon38, EyeOff as ToolIcon4, Mailbox as ToolIcon41, Qrcode as ToolIcon42, Scan as ToolIcon43, Camera as ToolIcon45, BrandGit as ToolIcon46, Terminal2 as ToolIcon47, SettingsAutomation as ToolIcon48, FileText as ToolIcon49, Hash as ToolIcon5, Database as ToolIcon50, FileSearch as ToolIcon52, Server as ToolIcon53, Alarm as ToolIcon54, FileCheck as ToolIcon55, FileInvoice as ToolIcon56, BrandDocker as ToolIcon57, Mail as ToolIcon58, Language as ToolIcon59, LockSquare as ToolIcon6, BrandJavascript as ToolIcon60, Api as ToolIcon61, Devices as ToolIcon64, BuildingFactory as ToolIcon65, MapSearch as ToolIcon66, Math as ToolIcon67, Hourglass as ToolIcon68, Percentage as ToolIcon69, Lock as ToolIcon7, Temperature as ToolIcon71, FileDiff as ToolIcon73, MoodSmile as ToolIcon74, Artboard as ToolIcon76, Robot as ToolIcon77, AlignJustified as ToolIcon8, Phone as ToolIcon80 } from '@vicons/tabler'; +import { PasswordRound as ToolIcon31, AbcRound as ToolIcon36, HttpRound as ToolIcon39, CompareArrowsRound as ToolIcon40, ImageOutlined as ToolIcon44, AccountTreeOutlined as ToolIcon51, RouterOutlined as ToolIcon62, UnfoldMoreOutlined as ToolIcon63, TimerOutlined as ToolIcon70, SpeedFilled as ToolIcon72, TableChartOutlined as ToolIcon78, GridOnOutlined as ToolIcon79, ShortTextRound as ToolIcon9 } from '@vicons/material'; import ToolIcon1 from '~icons/mdi/form-textbox-password'; import ToolIcon12 from '~icons/mdi/file-certificate-outline'; import ToolIcon25 from '~icons/mdi/code-brackets'; import ToolIcon75 from './numeronym-generator/n7m-icon.svg?component'; -import ToolIcon80 from '~icons/mdi/bank'; +import ToolIcon81 from '~icons/mdi/bank'; import { defineTool } from './tool'; import type { ToolCategory } from './tools.types'; import { codesByCategories } from './http-status-codes/http-status-codes.constants'; @@ -1454,24 +1454,34 @@ const tool128 = defineTool({ }); const tool129 = defineTool({ + name: translate('tools.local-llm-playground.title'), + path: '/local-llm-playground', + description: translate('tools.local-llm-playground.description'), + keywords: ['local llm', 'qwen', 'qwen3.5', 'webgpu', 'ai', 'chat', 'text generation', 'offline model'], + component: () => import('./local-llm-playground/local-llm-playground.vue'), + icon: ToolIcon77, + createdAt: new Date('2026-08-25'), +}); + +const tool130 = defineTool({ name: translate('tools.parquet-reader.title'), path: '/parquet-reader', description: translate('tools.parquet-reader.description'), keywords: ['parquet', 'apache parquet', 'columnar', 'data', 'schema', 'metadata', 'csv', 'json'], component: () => import('./parquet-reader/parquet-reader.vue'), - icon: ToolIcon77, + icon: ToolIcon78, }); -const tool130 = defineTool({ +const tool131 = defineTool({ name: translate('tools.xlsx-reader.title'), path: '/xlsx-reader', description: translate('tools.xlsx-reader.description'), keywords: ['xlsx', 'excel', 'spreadsheet', 'workbook', 'worksheet', 'table', 'csv', 'json'], component: () => import('./xlsx-reader/xlsx-reader.vue'), - icon: ToolIcon78, + icon: ToolIcon79, }); -const tool131 = defineTool({ +const tool132 = defineTool({ name: translate('tools.phone-parser-and-formatter.title'), path: '/phone-parser-and-formatter', description: translate('tools.phone-parser-and-formatter.description'), @@ -1489,17 +1499,17 @@ const tool131 = defineTool({ 'national', ], component: () => import('./phone-parser-and-formatter/phone-parser-and-formatter.vue'), - icon: ToolIcon79, + icon: ToolIcon80, createdAt: new Date('2023-05-01'), }); -const tool132 = defineTool({ +const tool133 = defineTool({ name: translate('tools.iban-validator-and-parser.title'), path: '/iban-validator-and-parser', description: translate('tools.iban-validator-and-parser.description'), keywords: ['iban', 'validator', 'and', 'parser', 'bic', 'bank'], component: () => import('./iban-validator-and-parser/iban-validator-and-parser.vue'), - icon: ToolIcon80, + icon: ToolIcon81, createdAt: new Date('2023-08-26'), }); @@ -1512,8 +1522,8 @@ export const toolsByCategory: ToolCategory[] = [ { name: 'Network', components: [tool97, tool98, tool99, tool100, tool101, tool102, tool103, tool104, tool105, tool106] }, { name: 'Math', components: [tool107, tool108, tool109, tool110] }, { name: 'Measurement', components: [tool111, tool112, tool113, tool114, tool115, tool116, tool117] }, - { name: 'Text', components: [tool118, tool119, tool120, tool121, tool122, tool123, tool124, tool125, tool126, tool127, tool128] }, - { name: 'Data', components: [tool129, tool130, tool131, tool132] }, + { name: 'Text', components: [tool118, tool119, tool120, tool121, tool122, tool123, tool124, tool125, tool126, tool127, tool128, tool129] }, + { name: 'Data', components: [tool130, tool131, tool132, tool133] }, ]; export const tools = toolsByCategory.flatMap(({ components }) => components); diff --git a/src/tools/local-llm-playground/index.ts b/src/tools/local-llm-playground/index.ts new file mode 100644 index 0000000000..04f4fbcc9a --- /dev/null +++ b/src/tools/local-llm-playground/index.ts @@ -0,0 +1,18 @@ +import { Robot } from '@vicons/tabler'; +import { defineTool } from '../tool'; +import { translate } from '@/plugins/i18n.plugin'; + +export const registry = { + category: 'Text', + order: 11, +} as const satisfies import('../tools.types').ToolRegistryMetadata; + +export const tool = defineTool({ + name: translate('tools.local-llm-playground.title'), + path: '/local-llm-playground', + description: translate('tools.local-llm-playground.description'), + keywords: ['local llm', 'qwen', 'qwen3.5', 'webgpu', 'ai', 'chat', 'text generation', 'offline model'], + component: () => import('./local-llm-playground.vue'), + icon: Robot, + createdAt: new Date('2026-08-25'), +}); diff --git a/src/tools/local-llm-playground/local-llm-cache.test.ts b/src/tools/local-llm-playground/local-llm-cache.test.ts new file mode 100644 index 0000000000..51fe005e07 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm-cache.test.ts @@ -0,0 +1,84 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { LOCAL_LLM_CACHE_NAME, LOCAL_LLM_MODELS } from './local-llm.models'; +import { + deleteLocalLlmModelCache, + inspectLocalLlmModelCache, + isLocalLlmModelCached, + markLocalLlmModelCached, +} from './local-llm-cache'; + +class FakeCache { + readonly entries = new Map(); + + async match(request: RequestInfo | URL): Promise { + return this.entries.get(String(request)); + } + + async put(request: RequestInfo | URL, response: Response): Promise { + this.entries.set(String(request), response); + } + + async keys(): Promise { + return [...this.entries.keys()].map(url => new Request(url)); + } + + async delete(request: RequestInfo | URL): Promise { + const key = request instanceof Request ? request.url : String(request); + return this.entries.delete(key); + } +} + +describe('local LLM model cache', () => { + let cache: FakeCache; + let cacheExists: boolean; + + beforeEach(() => { + cache = new FakeCache(); + cacheExists = false; + vi.stubGlobal('caches', { + has: vi.fn(async (name: string) => { + expect(name).toBe(LOCAL_LLM_CACHE_NAME); + return cacheExists; + }), + open: vi.fn(async (name: string) => { + expect(name).toBe(LOCAL_LLM_CACHE_NAME); + cacheExists = true; + return cache; + }), + }); + }); + + it('marks a completed model without persisting prompts or responses', async () => { + const model = LOCAL_LLM_MODELS[0]; + expect(await isLocalLlmModelCached(model.modelId)).toBe(false); + await markLocalLlmModelCached(model.modelId); + expect(await isLocalLlmModelCached(model.modelId)).toBe(true); + const serialized = [...cache.entries.values()].map(response => response.clone().text()); + expect((await Promise.all(serialized)).join('')).not.toContain('prompt'); + }); + + it('deletes only the selected model and its completion marker', async () => { + const [lite, standard] = LOCAL_LLM_MODELS; + cacheExists = true; + cache.entries.set(`https://huggingface.co/${lite.modelId}/resolve/main/config.json`, new Response('{}')); + cache.entries.set(`https://huggingface.co/${lite.modelId}/resolve/main/onnx/model.onnx`, new Response('lite')); + cache.entries.set(`https://huggingface.co/${standard.modelId}/resolve/main/config.json`, new Response('{}')); + await markLocalLlmModelCached(lite.modelId); + await markLocalLlmModelCached(standard.modelId); + + await expect(deleteLocalLlmModelCache(lite.modelId)).resolves.toBe(3); + expect(await isLocalLlmModelCached(lite.modelId)).toBe(false); + expect(await isLocalLlmModelCached(standard.modelId)).toBe(true); + expect([...cache.entries.keys()].some(key => key.includes(standard.modelId))).toBe(true); + }); + + it('reports and removes a partial model download without a completion marker', async () => { + const model = LOCAL_LLM_MODELS[0]; + cacheExists = true; + cache.entries.set(`https://huggingface.co/${model.modelId}/resolve/main/onnx/model.onnx`, new Response('partial')); + + await expect(inspectLocalLlmModelCache(model.modelId)).resolves.toEqual({ complete: false, entryCount: 1 }); + await expect(deleteLocalLlmModelCache(model.modelId)).resolves.toBe(1); + await expect(inspectLocalLlmModelCache(model.modelId)).resolves.toEqual({ complete: false, entryCount: 0 }); + }); +}); diff --git a/src/tools/local-llm-playground/local-llm-cache.ts b/src/tools/local-llm-playground/local-llm-cache.ts new file mode 100644 index 0000000000..c11ff5c881 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm-cache.ts @@ -0,0 +1,122 @@ +import { + LOCAL_LLM_CACHE_NAME, + LOCAL_LLM_STORAGE_HEADROOM_FACTOR, + type LocalLlmModel, +} from './local-llm.models'; + +const CACHE_MARKER_PATH = '/__it_tools_local_llm_cache_v1__/'; + +export interface LocalLlmCapabilities { + cacheAvailable: boolean + deviceMemoryGiB?: number + freeStorageBytes?: number + secureContext: boolean + storageEstimateAvailable: boolean + storageSufficient?: boolean + webGpuAvailable: boolean +} + +export interface LocalLlmCacheState { + complete: boolean + entryCount: number +} + +interface CachedModelMarker { + schemaVersion: 1 + modelId: string + completedAt: string +} + +interface NavigatorWithOptionalCapabilities extends Navigator { + deviceMemory?: number + gpu?: unknown +} + +function markerUrl(modelId: string): string { + return new URL(`${CACHE_MARKER_PATH}${encodeURIComponent(modelId)}`, globalThis.location.origin).href; +} + +function belongsToModel(requestUrl: string, modelId: string): boolean { + try { + return decodeURIComponent(requestUrl).includes(`/${modelId}/`); + } + catch { + return requestUrl.includes(modelId); + } +} + +export async function inspectLocalLlmCapabilities(model: LocalLlmModel): Promise { + const extendedNavigator = globalThis.navigator as NavigatorWithOptionalCapabilities; + const cacheAvailable = typeof globalThis.caches !== 'undefined'; + const storageEstimate = await extendedNavigator.storage?.estimate?.().catch(() => undefined); + const freeStorageBytes = storageEstimate?.quota !== undefined && storageEstimate.usage !== undefined + ? Math.max(0, storageEstimate.quota - storageEstimate.usage) + : undefined; + + return { + cacheAvailable, + deviceMemoryGiB: extendedNavigator.deviceMemory, + freeStorageBytes, + secureContext: globalThis.isSecureContext, + storageEstimateAvailable: freeStorageBytes !== undefined, + storageSufficient: freeStorageBytes === undefined + ? undefined + : freeStorageBytes >= model.estimatedDownloadBytes * LOCAL_LLM_STORAGE_HEADROOM_FACTOR, + webGpuAvailable: extendedNavigator.gpu !== undefined, + }; +} + +export async function isLocalLlmModelCached(modelId: string): Promise { + return (await inspectLocalLlmModelCache(modelId)).complete; +} + +export async function inspectLocalLlmModelCache(modelId: string): Promise { + if (typeof globalThis.caches === 'undefined') { + return { complete: false, entryCount: 0 }; + } + try { + if (!await globalThis.caches.has(LOCAL_LLM_CACHE_NAME)) { + return { complete: false, entryCount: 0 }; + } + const cache = await globalThis.caches.open(LOCAL_LLM_CACHE_NAME); + const requests = await cache.keys(); + const entryCount = requests.filter(request => ( + request.url === markerUrl(modelId) || belongsToModel(request.url, modelId) + )).length; + return { + complete: Boolean(await cache.match(markerUrl(modelId))), + entryCount, + }; + } + catch { + return { complete: false, entryCount: 0 }; + } +} + +export async function markLocalLlmModelCached(modelId: string): Promise { + if (typeof globalThis.caches === 'undefined') { + return; + } + const marker: CachedModelMarker = { + completedAt: new Date().toISOString(), + modelId, + schemaVersion: 1, + }; + const cache = await globalThis.caches.open(LOCAL_LLM_CACHE_NAME); + await cache.put(markerUrl(modelId), new Response(JSON.stringify(marker), { + headers: { 'Content-Type': 'application/json' }, + })); +} + +export async function deleteLocalLlmModelCache(modelId: string): Promise { + if (typeof globalThis.caches === 'undefined') { + return 0; + } + const cache = await globalThis.caches.open(LOCAL_LLM_CACHE_NAME); + const requests = await cache.keys(); + const targets = requests.filter(request => ( + request.url === markerUrl(modelId) || belongsToModel(request.url, modelId) + )); + const results = await Promise.all(targets.map(request => cache.delete(request))); + return results.filter(Boolean).length; +} diff --git a/src/tools/local-llm-playground/local-llm-model-assets.json b/src/tools/local-llm-playground/local-llm-model-assets.json new file mode 100644 index 0000000000..353dbadaa9 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm-model-assets.json @@ -0,0 +1,54 @@ +{ + "schemaVersion": 1, + "models": [ + { + "key": "lite", + "modelId": "onnx-community/Qwen3.5-0.8B-ONNX-OPT", + "revision": "fafab72d87a9e6be3925b38caf48286d2838f2d0", + "files": [ + "chat_template.jinja", + "config.json", + "generation_config.json", + "tokenizer.json", + "tokenizer_config.json", + "onnx/decoder_model_merged_q4.onnx", + "onnx/decoder_model_merged_q4.onnx_data", + "onnx/embed_tokens_q4.onnx", + "onnx/embed_tokens_q4.onnx_data" + ] + }, + { + "key": "standard", + "modelId": "onnx-community/Qwen3.5-2B-ONNX-OPT", + "revision": "2ea7886f48b926aca97de8b0e041ffca7e3ebaa9", + "files": [ + "chat_template.jinja", + "config.json", + "generation_config.json", + "tokenizer.json", + "tokenizer_config.json", + "onnx/decoder_model_merged_q4.onnx", + "onnx/decoder_model_merged_q4.onnx_data", + "onnx/embed_tokens_q4.onnx", + "onnx/embed_tokens_q4.onnx_data" + ] + }, + { + "key": "quality", + "modelId": "onnx-community/Qwen3.5-4B-ONNX-OPT", + "revision": "57b13b4dce7be073be0df3eaf1c842a6bbb2e0a7", + "files": [ + "chat_template.jinja", + "config.json", + "generation_config.json", + "tokenizer.json", + "tokenizer_config.json", + "onnx/decoder_model_merged_q4.onnx", + "onnx/decoder_model_merged_q4.onnx_data", + "onnx/decoder_model_merged_q4.onnx_data_1", + "onnx/embed_tokens_q4.onnx", + "onnx/embed_tokens_q4.onnx_data" + ] + } + ] +} diff --git a/src/tools/local-llm-playground/local-llm-playground.e2e.spec.ts b/src/tools/local-llm-playground/local-llm-playground.e2e.spec.ts new file mode 100644 index 0000000000..4b8d668bf3 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm-playground.e2e.spec.ts @@ -0,0 +1,88 @@ +import { expect, test } from '@playwright/test'; + +const LOCAL_MODEL_PATH_FRAGMENT = '/assets/local-llm-models/'; + +test.use({ serviceWorkers: 'block' }); + +test.describe('Tool - Local LLM playground', () => { + test('loads all three tiers without starting the model runtime or network download', async ({ page }) => { + const modelRequests: string[] = []; + page.on('request', (request) => { + if (/huggingface\.co|local-llm\.worker(?:\.ts|-[^/?]+\.js)(?:\?|$)/iu.test(request.url())) { + modelRequests.push(request.url()); + } + }); + await page.goto('/local-llm-playground'); + + await expect(page).toHaveTitle('Local LLM playground - IT Tools'); + await expect(page.getByRole('radio', { name: 'Lite · 0.8B' })).toBeVisible(); + await expect(page.getByRole('radio', { name: 'Standard · 2B' })).toHaveAttribute('aria-checked', 'true'); + await expect(page.getByRole('radio', { name: 'Quality · 4B' })).toBeVisible(); + await expect(page.getByTestId('local-llm-model-summary')).toContainText('Approx. text-only q4 download'); + await page.waitForTimeout(250); + expect(modelRequests).toEqual([]); + expect(await page.evaluate(async () => typeof caches === 'undefined' ? [] : await caches.keys())) + .not.toContain('it-tools-local-llm-models-v1'); + }); + + test('keeps prompt content ephemeral across reloads', async ({ page }) => { + const secret = 'ephemeral-local-llm-prompt-7bca'; + await page.goto('/local-llm-playground'); + await page.getByTestId('local-llm-prompt').fill(secret); + expect(await page.evaluate(value => Object.values(localStorage).every(item => !item.includes(value)), secret)).toBe(true); + expect(await page.evaluate(value => Object.values(sessionStorage).every(item => !item.includes(value)), secret)).toBe(true); + await page.reload(); + await expect(page.getByTestId('local-llm-prompt')).toHaveValue(''); + expect(page.url()).not.toContain(secret); + }); + + test('loads model files only from the application origin', async ({ page }) => { + await page.addInitScript(() => { + Object.defineProperty(navigator, 'gpu', { configurable: true, value: {} }); + }); + await page.route('**/assets/local-llm-models/**', route => route.abort('blockedbyclient')); + const externalModelRequests: string[] = []; + page.on('request', (request) => { + if (/huggingface\.co|hf\.co/iu.test(request.url())) { + externalModelRequests.push(request.url()); + } + }); + + await page.goto('/local-llm-playground'); + const localRequest = page.waitForRequest(request => request.url().includes('/assets/local-llm-models/')); + await page.getByTestId('local-llm-load').click(); + const request = await localRequest; + + expect(new URL(request.url()).origin).toBe(new URL(page.url()).origin); + expect(request.url()).toContain(LOCAL_MODEL_PATH_FRAGMENT); + await expect(page.getByTestId('local-llm-error')).toBeVisible(); + expect(externalModelRequests).toEqual([]); + }); + + test('keeps cold route work bounded before an explicit model load', async ({ browserName, page }, testInfo) => { + test.skip(browserName !== 'chromium', 'Chromium is the performance baseline.'); + await page.addInitScript(() => { + const durations: number[] = []; + (window as Window & { __localLlmLongTasks?: number[] }).__localLlmLongTasks = durations; + new PerformanceObserver(list => durations.push(...list.getEntries().map(entry => entry.duration))) + .observe({ entryTypes: ['longtask'] }); + }); + await page.goto('/'); + const toolLink = page.getByRole('link', { name: /Local LLM playground/ }).first(); + await expect(toolLink).toBeVisible(); + await page.evaluate(() => { + (window as Window & { __localLlmLongTasks?: number[] }).__localLlmLongTasks?.splice(0); + performance.clearResourceTimings(); + }); + const startedAt = Date.now(); + await toolLink.click(); + await expect(page.getByTestId('local-llm-status')).not.toContainText('Checking'); + const readyMs = Date.now() - startedAt; + const longestTaskMs = await page.evaluate(() => Math.max(0, ...(window as Window & { __localLlmLongTasks?: number[] }).__localLlmLongTasks ?? [])); + expect(longestTaskMs).toBeLessThan(100); + await testInfo.attach('local-llm-cold-route.txt', { + body: `${readyMs} ms cold route-ready; ${longestTaskMs.toFixed(1)} ms longest task; no model worker or weights before explicit Load`, + contentType: 'text/plain', + }); + }); +}); diff --git a/src/tools/local-llm-playground/local-llm-playground.vue b/src/tools/local-llm-playground/local-llm-playground.vue new file mode 100644 index 0000000000..c82dac019d --- /dev/null +++ b/src/tools/local-llm-playground/local-llm-playground.vue @@ -0,0 +1,550 @@ + + + + + diff --git a/src/tools/local-llm-playground/local-llm-progress.test.ts b/src/tools/local-llm-playground/local-llm-progress.test.ts new file mode 100644 index 0000000000..2c35161583 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm-progress.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest'; +import { LocalLlmProgressTracker, localLlmFileProgressPercentage } from './local-llm-progress'; + +describe('local LLM progress tracker', () => { + it('keeps parallel files on independent monotonic progress bars', () => { + const tracker = new LocalLlmProgressTracker(); + expect(tracker.update({ + files: [ + { file: 'decoder.onnx_data', loaded: 20, total: 100 }, + { file: 'embed.onnx_data', loaded: 10, total: 50 }, + ], + loaded: 30, + status: 'model:progress_total', + total: 150, + })).toHaveLength(2); + + const files = tracker.update({ file: 'decoder.onnx_data', loaded: 15, status: 'model:progress', total: 100 }); + expect(files.find(file => file.file === 'decoder.onnx_data')?.loaded).toBe(20); + expect(files.find(file => file.file === 'embed.onnx_data')?.loaded).toBe(10); + }); + + it('starts a fresh set when model weights replace tokenizer files', () => { + const tracker = new LocalLlmProgressTracker(); + tracker.update({ file: 'tokenizer.json', loaded: 100, status: 'tokenizer:progress', total: 100 }); + expect(tracker.update({ file: 'onnx/model.onnx', loaded: 1, status: 'model:progress', total: 10 })) + .toEqual([{ file: 'onnx/model.onnx', loaded: 1, progress: undefined, total: 10 }]); + }); + + it('calculates bounded percentages without combining unrelated files', () => { + expect(localLlmFileProgressPercentage({ file: 'a', loaded: 25, total: 100 })).toBe(25); + expect(localLlmFileProgressPercentage({ file: 'a', progress: 120 })).toBe(100); + expect(localLlmFileProgressPercentage({ file: 'a' })).toBeUndefined(); + }); +}); diff --git a/src/tools/local-llm-playground/local-llm-progress.ts b/src/tools/local-llm-playground/local-llm-progress.ts new file mode 100644 index 0000000000..4427911f5b --- /dev/null +++ b/src/tools/local-llm-playground/local-llm-progress.ts @@ -0,0 +1,61 @@ +import type { LocalLlmProgress, LocalLlmProgressFile } from './local-llm.protocol'; + +const DOWNLOAD_PHASES = new Set(['tokenizer', 'model']); + +function phaseOf(status: string): string { + return status.split(':', 1)[0]; +} + +function mergeProgress(previous: LocalLlmProgressFile | undefined, next: LocalLlmProgressFile): LocalLlmProgressFile { + const total = Math.max(previous?.total ?? 0, next.total ?? 0) || undefined; + const loaded = Math.min(total ?? Number.POSITIVE_INFINITY, Math.max(previous?.loaded ?? 0, next.loaded ?? 0)); + return { + file: next.file, + loaded: loaded || next.loaded === 0 ? loaded : undefined, + progress: Math.max(previous?.progress ?? 0, next.progress ?? 0) || undefined, + total, + }; +} + +export class LocalLlmProgressTracker { + private phase = ''; + private readonly files = new Map(); + + reset(): void { + this.phase = ''; + this.files.clear(); + } + + update(progress: LocalLlmProgress): LocalLlmProgressFile[] { + const nextPhase = phaseOf(progress.status); + if (DOWNLOAD_PHASES.has(nextPhase) && nextPhase !== this.phase) { + this.phase = nextPhase; + this.files.clear(); + } + + for (const fileProgress of progress.files ?? []) { + this.files.set(fileProgress.file, mergeProgress(this.files.get(fileProgress.file), fileProgress)); + } + if (progress.file) { + const fileProgress = { + file: progress.file, + loaded: progress.loaded, + progress: progress.progress, + total: progress.total, + }; + this.files.set(progress.file, mergeProgress(this.files.get(progress.file), fileProgress)); + } + + return [...this.files.values()]; + } +} + +export function localLlmFileProgressPercentage(progress: LocalLlmProgressFile): number | undefined { + if (progress.loaded !== undefined && progress.total) { + return Math.min(100, Math.max(0, progress.loaded / progress.total * 100)); + } + if (progress.progress !== undefined) { + return Math.min(100, Math.max(0, progress.progress)); + } + return undefined; +} diff --git a/src/tools/local-llm-playground/local-llm.models.test.ts b/src/tools/local-llm-playground/local-llm.models.test.ts new file mode 100644 index 0000000000..879bc311b2 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm.models.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; +import modelAssets from './local-llm-model-assets.json'; +import { LOCAL_LLM_MODELS, getLocalLlmModelAssetBasePath } from './local-llm.models'; + +describe('local LLM model assets', () => { + it('keeps runtime models aligned with the pinned same-origin mirror catalog', () => { + expect(modelAssets.models.map(({ key, modelId, revision }) => ({ key, modelId, revision }))) + .toEqual(LOCAL_LLM_MODELS.map(({ key, modelId, revision }) => ({ key, modelId, revision }))); + }); + + it('builds a base-aware same-origin asset path', () => { + expect(getLocalLlmModelAssetBasePath(LOCAL_LLM_MODELS[0], '/it-tools/')) + .toBe(`/it-tools/assets/local-llm-models/${LOCAL_LLM_MODELS[0].revision}/`); + }); + + it('contains only the text q4 sessions and their pinned external data chunks', () => { + for (const model of modelAssets.models) { + expect(model.files).toContain('onnx/decoder_model_merged_q4.onnx'); + expect(model.files).toContain('onnx/embed_tokens_q4.onnx'); + expect(model.files.some(file => /vision_encoder|fp16|quantized/u.test(file))).toBe(false); + } + }); +}); diff --git a/src/tools/local-llm-playground/local-llm.models.ts b/src/tools/local-llm-playground/local-llm.models.ts new file mode 100644 index 0000000000..4aa3c68cf6 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm.models.ts @@ -0,0 +1,88 @@ +export type LocalLlmModelKey = 'lite' | 'standard' | 'quality'; + +export interface LocalLlmModel { + key: LocalLlmModelKey + label: string + parameters: string + modelId: string + revision: string + estimatedDownloadBytes: number + recommendedMemoryGiB: number + summary: string +} + +const GIB = 1024 ** 3; + +export const LOCAL_LLM_MODELS = [ + { + key: 'lite', + label: 'Lite', + parameters: '0.8B', + modelId: 'onnx-community/Qwen3.5-0.8B-ONNX-OPT', + revision: 'fafab72d87a9e6be3925b38caf48286d2838f2d0', + estimatedDownloadBytes: Math.round(0.7 * GIB), + recommendedMemoryGiB: 4, + summary: 'Fastest startup and the broadest device compatibility.', + }, + { + key: 'standard', + label: 'Standard', + parameters: '2B', + modelId: 'onnx-community/Qwen3.5-2B-ONNX-OPT', + revision: '2ea7886f48b926aca97de8b0e041ffca7e3ebaa9', + estimatedDownloadBytes: Math.round(1.6 * GIB), + recommendedMemoryGiB: 8, + summary: 'Balanced quality and speed for modern desktops.', + }, + { + key: 'quality', + label: 'Quality', + parameters: '4B', + modelId: 'onnx-community/Qwen3.5-4B-ONNX-OPT', + revision: '57b13b4dce7be073be0df3eaf1c842a6bbb2e0a7', + estimatedDownloadBytes: Math.round(3.2 * GIB), + recommendedMemoryGiB: 12, + summary: 'Best answers in this tool, with the largest download and memory footprint.', + }, +] as const satisfies readonly LocalLlmModel[]; + +export const LOCAL_LLM_DEFAULT_MODEL_KEY: LocalLlmModelKey = 'standard'; +export const LOCAL_LLM_MAX_PROMPT_CHARACTERS = 16_000; +export const LOCAL_LLM_MAX_SYSTEM_PROMPT_CHARACTERS = 4_000; +export const LOCAL_LLM_MAX_OUTPUT_CHARACTERS = 100_000; +export const LOCAL_LLM_MAX_ERROR_CHARACTERS = 2_048; +export const LOCAL_LLM_MAX_PROGRESS_FILE_CHARACTERS = 2_048; +export const LOCAL_LLM_MAX_PROGRESS_STATUS_CHARACTERS = 256; +export const LOCAL_LLM_MAX_PROGRESS_FILES = 16; +export const LOCAL_LLM_MIN_NEW_TOKENS = 32; +export const LOCAL_LLM_MAX_NEW_TOKENS = 1_024; +export const LOCAL_LLM_DEFAULT_NEW_TOKENS = 512; +export const LOCAL_LLM_CACHE_NAME = 'it-tools-local-llm-models-v1'; +export const LOCAL_LLM_STORAGE_HEADROOM_FACTOR = 1.2; + +export function getLocalLlmModel(key: LocalLlmModelKey): LocalLlmModel { + const model = LOCAL_LLM_MODELS.find(candidate => candidate.key === key); + if (!model) { + throw new TypeError('Unknown local LLM model.'); + } + return model; +} + +export function getLocalLlmModelById(modelId: string): LocalLlmModel | undefined { + return LOCAL_LLM_MODELS.find(model => model.modelId === modelId); +} + +export function getLocalLlmModelAssetBasePath(model: LocalLlmModel, baseUrl: string): string { + const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`; + return `${normalizedBaseUrl}assets/local-llm-models/${model.revision}/`; +} + +export function formatLocalLlmBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) { + return 'Unknown'; + } + if (bytes >= GIB) { + return `${(bytes / GIB).toFixed(1)} GiB`; + } + return `${Math.round(bytes / 1024 ** 2)} MiB`; +} diff --git a/src/tools/local-llm-playground/local-llm.protocol.test.ts b/src/tools/local-llm-playground/local-llm.protocol.test.ts new file mode 100644 index 0000000000..933960ac9e --- /dev/null +++ b/src/tools/local-llm-playground/local-llm.protocol.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from 'vitest'; +import { + LOCAL_LLM_MAX_NEW_TOKENS, + LOCAL_LLM_MAX_OUTPUT_CHARACTERS, + LOCAL_LLM_MAX_PROMPT_CHARACTERS, + LOCAL_LLM_MODELS, +} from './local-llm.models'; +import { + parseLocalLlmWorkerMessage, + parseLocalLlmWorkerRequest, + validateLocalLlmGenerationOptions, +} from './local-llm.protocol'; + +describe('local LLM protocol', () => { + it('accepts only the reviewed Lite, Standard, and Quality model identifiers', () => { + for (const model of LOCAL_LLM_MODELS) { + expect(parseLocalLlmWorkerRequest({ jobId: 1, modelId: model.modelId, type: 'load' })) + .toEqual({ jobId: 1, modelId: model.modelId, type: 'load' }); + } + expect(() => parseLocalLlmWorkerRequest({ jobId: 1, modelId: 'unknown/max-model', type: 'load' })) + .toThrow('not supported'); + }); + + it('trims bounded generation input and rejects oversized prompts and output limits', () => { + expect(validateLocalLlmGenerationOptions({ + maxNewTokens: 512, + prompt: ' Explain this ', + systemPrompt: ' Be concise ', + })).toEqual({ maxNewTokens: 512, prompt: 'Explain this', systemPrompt: 'Be concise' }); + + expect(() => validateLocalLlmGenerationOptions({ + maxNewTokens: 512, + prompt: 'x'.repeat(LOCAL_LLM_MAX_PROMPT_CHARACTERS + 1), + systemPrompt: '', + })).toThrow('limited'); + expect(() => validateLocalLlmGenerationOptions({ + maxNewTokens: LOCAL_LLM_MAX_NEW_TOKENS + 1, + prompt: 'Hello', + systemPrompt: '', + })).toThrow('Maximum output'); + }); + + it('rejects malformed streaming and terminal worker envelopes', () => { + expect(parseLocalLlmWorkerMessage({ + jobId: 2, + progress: { + files: [{ file: 'onnx/model.onnx_data', loaded: 5, total: 10 }], + status: 'model:progress_total', + }, + type: 'progress', + })).toMatchObject({ + progress: { files: [{ file: 'onnx/model.onnx_data', loaded: 5, total: 10 }] }, + }); + expect(parseLocalLlmWorkerMessage({ + jobId: 2, + text: 'hello', + tokenCount: 3, + type: 'token', + })).toMatchObject({ text: 'hello', tokenCount: 3, type: 'token' }); + expect(() => parseLocalLlmWorkerMessage({ jobId: 2, text: 42, tokenCount: 3, type: 'token' })) + .toThrow('invalid text fragment'); + expect(() => parseLocalLlmWorkerMessage({ + cancelled: false, + elapsedMs: 1, + jobId: 2, + output: 'x'.repeat(LOCAL_LLM_MAX_OUTPUT_CHARACTERS + 1), + tokenCount: 3, + type: 'generated', + })).toThrow('invalid result'); + expect(() => parseLocalLlmWorkerMessage({ jobId: 0, type: 'loaded' })) + .toThrow('job identifier'); + }); +}); diff --git a/src/tools/local-llm-playground/local-llm.protocol.ts b/src/tools/local-llm-playground/local-llm.protocol.ts new file mode 100644 index 0000000000..93847b2404 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm.protocol.ts @@ -0,0 +1,230 @@ +import { + LOCAL_LLM_MAX_ERROR_CHARACTERS, + LOCAL_LLM_MAX_NEW_TOKENS, + LOCAL_LLM_MAX_OUTPUT_CHARACTERS, + LOCAL_LLM_MAX_PROGRESS_FILES, + LOCAL_LLM_MAX_PROGRESS_FILE_CHARACTERS, + LOCAL_LLM_MAX_PROGRESS_STATUS_CHARACTERS, + LOCAL_LLM_MAX_PROMPT_CHARACTERS, + LOCAL_LLM_MAX_SYSTEM_PROMPT_CHARACTERS, + LOCAL_LLM_MIN_NEW_TOKENS, + getLocalLlmModelById, +} from './local-llm.models'; + +export type LocalLlmErrorCode = 'cancelled' | 'input-limit' | 'model' | 'unavailable' | 'worker'; + +export interface LocalLlmLoadRequest { + type: 'load' + jobId: number + modelId: string +} + +export interface LocalLlmGenerateRequest { + type: 'generate' + jobId: number + prompt: string + systemPrompt: string + maxNewTokens: number +} + +export interface LocalLlmCancelRequest { + type: 'cancel' + jobId: number +} + +export type LocalLlmWorkerRequest = LocalLlmLoadRequest | LocalLlmGenerateRequest | LocalLlmCancelRequest; + +export interface LocalLlmProgress { + file?: string + files?: LocalLlmProgressFile[] + loaded?: number + total?: number + progress?: number + status: string +} + +export interface LocalLlmProgressFile { + file: string + loaded?: number + total?: number + progress?: number +} + +export type LocalLlmWorkerMessage = + | { type: 'progress'; jobId: number; progress: LocalLlmProgress } + | { type: 'loaded'; jobId: number; modelId: string; elapsedMs: number } + | { type: 'token'; jobId: number; text: string; tokenCount: number } + | { type: 'generated'; jobId: number; output: string; tokenCount: number; elapsedMs: number; cancelled: boolean } + | { type: 'error'; jobId: number; code: LocalLlmErrorCode; message: string }; + +export interface LocalLlmGenerationOptions { + prompt: string + systemPrompt: string + maxNewTokens: number +} + +export class LocalLlmError extends Error { + constructor( + public readonly code: LocalLlmErrorCode, + message: string, + ) { + super(message); + this.name = 'LocalLlmError'; + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function parseJobId(value: unknown): number { + if (!Number.isSafeInteger(value) || Number(value) < 1) { + throw new LocalLlmError('worker', 'The local model worker returned an invalid job identifier.'); + } + return Number(value); +} + +export function validateLocalLlmGenerationOptions(value: LocalLlmGenerationOptions): LocalLlmGenerationOptions { + const prompt = value.prompt.trim(); + const systemPrompt = value.systemPrompt.trim(); + if (!prompt) { + throw new LocalLlmError('input-limit', 'Enter a prompt before generating.'); + } + if (prompt.length > LOCAL_LLM_MAX_PROMPT_CHARACTERS) { + throw new LocalLlmError('input-limit', `Prompt is limited to ${LOCAL_LLM_MAX_PROMPT_CHARACTERS.toLocaleString('en-US')} characters.`); + } + if (systemPrompt.length > LOCAL_LLM_MAX_SYSTEM_PROMPT_CHARACTERS) { + throw new LocalLlmError('input-limit', `System instructions are limited to ${LOCAL_LLM_MAX_SYSTEM_PROMPT_CHARACTERS.toLocaleString('en-US')} characters.`); + } + if (!Number.isSafeInteger(value.maxNewTokens) + || value.maxNewTokens < LOCAL_LLM_MIN_NEW_TOKENS + || value.maxNewTokens > LOCAL_LLM_MAX_NEW_TOKENS) { + throw new LocalLlmError('input-limit', `Maximum output must be between ${LOCAL_LLM_MIN_NEW_TOKENS} and ${LOCAL_LLM_MAX_NEW_TOKENS} tokens.`); + } + return { maxNewTokens: value.maxNewTokens, prompt, systemPrompt }; +} + +export function parseLocalLlmWorkerRequest(value: unknown): LocalLlmWorkerRequest { + if (!isRecord(value) || typeof value.type !== 'string') { + throw new LocalLlmError('worker', 'The local model worker received an invalid request.'); + } + const jobId = parseJobId(value.jobId); + if (value.type === 'cancel') { + return { jobId, type: 'cancel' }; + } + if (value.type === 'load') { + if (typeof value.modelId !== 'string' || !getLocalLlmModelById(value.modelId)) { + throw new LocalLlmError('model', 'The requested local model is not supported.'); + } + return { jobId, modelId: value.modelId, type: 'load' }; + } + if (value.type === 'generate') { + const validated = validateLocalLlmGenerationOptions({ + maxNewTokens: Number(value.maxNewTokens), + prompt: typeof value.prompt === 'string' ? value.prompt : '', + systemPrompt: typeof value.systemPrompt === 'string' ? value.systemPrompt : '', + }); + return { jobId, type: 'generate', ...validated }; + } + throw new LocalLlmError('worker', 'The local model worker received an unsupported request.'); +} + +function parseOptionalFiniteNumber(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined; +} + +function parseProgressFiles(value: unknown): LocalLlmProgressFile[] | undefined { + if (value === undefined) { + return undefined; + } + if (!Array.isArray(value) || value.length > LOCAL_LLM_MAX_PROGRESS_FILES) { + throw new LocalLlmError('worker', 'The local model worker returned invalid file progress.'); + } + return value.map((entry) => { + if (!isRecord(entry) + || typeof entry.file !== 'string' + || !entry.file + || entry.file.length > LOCAL_LLM_MAX_PROGRESS_FILE_CHARACTERS) { + throw new LocalLlmError('worker', 'The local model worker returned invalid file progress.'); + } + return { + file: entry.file, + loaded: parseOptionalFiniteNumber(entry.loaded), + progress: parseOptionalFiniteNumber(entry.progress), + total: parseOptionalFiniteNumber(entry.total), + }; + }); +} + +export function parseLocalLlmWorkerMessage(value: unknown): LocalLlmWorkerMessage { + if (!isRecord(value) || typeof value.type !== 'string') { + throw new LocalLlmError('worker', 'The local model worker returned an unreadable message.'); + } + const jobId = parseJobId(value.jobId); + if (value.type === 'progress') { + if (!isRecord(value.progress) + || typeof value.progress.status !== 'string' + || value.progress.status.length > LOCAL_LLM_MAX_PROGRESS_STATUS_CHARACTERS + || (value.progress.file !== undefined + && (typeof value.progress.file !== 'string' + || value.progress.file.length > LOCAL_LLM_MAX_PROGRESS_FILE_CHARACTERS))) { + throw new LocalLlmError('worker', 'The local model worker returned invalid progress.'); + } + return { + jobId, + type: 'progress', + progress: { + file: typeof value.progress.file === 'string' ? value.progress.file : undefined, + files: parseProgressFiles(value.progress.files), + loaded: parseOptionalFiniteNumber(value.progress.loaded), + progress: parseOptionalFiniteNumber(value.progress.progress), + status: value.progress.status, + total: parseOptionalFiniteNumber(value.progress.total), + }, + }; + } + if (value.type === 'loaded') { + if (typeof value.modelId !== 'string' || !getLocalLlmModelById(value.modelId)) { + throw new LocalLlmError('worker', 'The local model worker returned an unknown model.'); + } + return { jobId, type: 'loaded', modelId: value.modelId, elapsedMs: parseOptionalFiniteNumber(value.elapsedMs) ?? 0 }; + } + if (value.type === 'token') { + if (typeof value.text !== 'string' + || value.text.length > LOCAL_LLM_MAX_OUTPUT_CHARACTERS + || !Number.isSafeInteger(value.tokenCount) + || Number(value.tokenCount) < 0 + || Number(value.tokenCount) > LOCAL_LLM_MAX_NEW_TOKENS) { + throw new LocalLlmError('worker', 'The local model worker returned an invalid text fragment.'); + } + return { jobId, type: 'token', text: value.text, tokenCount: Number(value.tokenCount) }; + } + if (value.type === 'generated') { + if (typeof value.output !== 'string' + || value.output.length > LOCAL_LLM_MAX_OUTPUT_CHARACTERS + || !Number.isSafeInteger(value.tokenCount) + || Number(value.tokenCount) < 0 + || Number(value.tokenCount) > LOCAL_LLM_MAX_NEW_TOKENS + || typeof value.cancelled !== 'boolean') { + throw new LocalLlmError('worker', 'The local model worker returned an invalid result.'); + } + return { + cancelled: value.cancelled, + elapsedMs: parseOptionalFiniteNumber(value.elapsedMs) ?? 0, + jobId, + output: value.output, + tokenCount: Number(value.tokenCount), + type: 'generated', + }; + } + if (value.type === 'error') { + const codes: LocalLlmErrorCode[] = ['cancelled', 'input-limit', 'model', 'unavailable', 'worker']; + if (typeof value.message !== 'string' + || value.message.length > LOCAL_LLM_MAX_ERROR_CHARACTERS + || !codes.includes(value.code as LocalLlmErrorCode)) { + throw new LocalLlmError('worker', 'The local model worker returned an invalid error.'); + } + return { code: value.code as LocalLlmErrorCode, jobId, message: value.message, type: 'error' }; + } + throw new LocalLlmError('worker', 'The local model worker returned an unsupported message.'); +} diff --git a/src/tools/local-llm-playground/local-llm.worker-client.test.ts b/src/tools/local-llm-playground/local-llm.worker-client.test.ts new file mode 100644 index 0000000000..4955c6e1f2 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm.worker-client.test.ts @@ -0,0 +1,123 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { LOCAL_LLM_MAX_OUTPUT_CHARACTERS, LOCAL_LLM_MODELS } from './local-llm.models'; +import { + LocalLlmWorkerClient, + type LocalLlmWorkerHandle, +} from './local-llm.worker-client'; +import type { LocalLlmError, LocalLlmWorkerRequest } from './local-llm.protocol'; + +class FakeWorker implements LocalLlmWorkerHandle { + onmessage: ((event: MessageEvent) => void) | null = null; + onmessageerror: ((event: MessageEvent) => void) | null = null; + onerror: ((event: ErrorEvent) => void) | null = null; + posted: LocalLlmWorkerRequest[] = []; + terminated = false; + + postMessage(message: LocalLlmWorkerRequest): void { + this.posted.push(message); + } + + terminate(): void { + this.terminated = true; + } + + emit(data: unknown): void { + this.onmessage?.({ data } as MessageEvent); + } +} + +function createHarness() { + const workers: FakeWorker[] = []; + const client = new LocalLlmWorkerClient(() => { + const worker = new FakeWorker(); + workers.push(worker); + return worker; + }); + return { client, workers }; +} + +async function expectCode(promise: Promise, code: LocalLlmError['code']): Promise { + await expect(promise).rejects.toMatchObject({ code, name: 'LocalLlmError' }); +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('LocalLlmWorkerClient', () => { + it('loads lazily, reports progress, and streams a bounded generation result', async () => { + const { client, workers } = createHarness(); + expect(workers).toHaveLength(0); + const progress = vi.fn(); + const loading = client.load(LOCAL_LLM_MODELS[1], progress); + expect(workers).toHaveLength(1); + expect(workers[0].posted[0]).toMatchObject({ jobId: 1, modelId: LOCAL_LLM_MODELS[1].modelId, type: 'load' }); + workers[0].emit({ jobId: 1, progress: { loaded: 5, status: 'model:progress', total: 10 }, type: 'progress' }); + workers[0].emit({ elapsedMs: 1_500, jobId: 1, modelId: LOCAL_LLM_MODELS[1].modelId, type: 'loaded' }); + await expect(loading).resolves.toEqual({ elapsedMs: 1_500 }); + expect(progress).toHaveBeenCalledWith({ loaded: 5, progress: undefined, status: 'model:progress', total: 10, file: undefined }); + + const streamed = vi.fn(); + const generation = client.generate({ maxNewTokens: 64, prompt: 'Hello', systemPrompt: '' }, streamed); + workers[0].emit({ jobId: 2, text: 'Hi ', tokenCount: 1, type: 'token' }); + workers[0].emit({ jobId: 2, text: 'there', tokenCount: 2, type: 'token' }); + workers[0].emit({ cancelled: false, elapsedMs: 250, jobId: 2, output: 'Hi there', tokenCount: 2, type: 'generated' }); + await expect(generation).resolves.toEqual({ cancelled: false, elapsedMs: 250, output: 'Hi there', tokenCount: 2 }); + expect(streamed.mock.calls.map(([fragment]) => fragment).join('')).toBe('Hi there'); + expect(workers).toHaveLength(1); + }); + + it('uses graceful generation cancellation and physically terminates a stuck worker', async () => { + vi.useFakeTimers(); + const { client, workers } = createHarness(); + const loading = client.load(LOCAL_LLM_MODELS[0]); + workers[0].emit({ elapsedMs: 10, jobId: 1, modelId: LOCAL_LLM_MODELS[0].modelId, type: 'loaded' }); + await loading; + + const graceful = client.generate({ maxNewTokens: 64, prompt: 'Hello', systemPrompt: '' }); + client.cancelGeneration(); + expect(workers[0].posted.at(-1)).toEqual({ jobId: 2, type: 'cancel' }); + workers[0].emit({ cancelled: true, elapsedMs: 20, jobId: 2, output: 'partial', tokenCount: 1, type: 'generated' }); + await expect(graceful).resolves.toMatchObject({ cancelled: true, output: 'partial' }); + expect(workers[0].terminated).toBe(false); + + const stuck = client.generate({ maxNewTokens: 64, prompt: 'Again', systemPrompt: '' }); + const stuckRejection = expectCode(stuck, 'cancelled'); + client.cancelGeneration(); + await vi.advanceTimersByTimeAsync(2_000); + await stuckRejection; + expect(workers[0].terminated).toBe(true); + expect(client.currentModelId).toBeUndefined(); + }); + + it('physically terminates downloads and route disposal, then rejects stale work', async () => { + const { client, workers } = createHarness(); + const loading = client.load(LOCAL_LLM_MODELS[2]); + client.cancelLoad(); + await expectCode(loading, 'cancelled'); + expect(workers[0].terminated).toBe(true); + + const retry = client.load(LOCAL_LLM_MODELS[0]); + expect(workers).toHaveLength(2); + client.dispose(); + await expectCode(retry, 'cancelled'); + expect(workers[1].terminated).toBe(true); + workers[1].emit({ elapsedMs: 1, jobId: 2, modelId: LOCAL_LLM_MODELS[0].modelId, type: 'loaded' }); + expect(client.currentModelId).toBeUndefined(); + }); + + it('rejects cumulative streaming output beyond the transport bound', async () => { + const { client, workers } = createHarness(); + const loading = client.load(LOCAL_LLM_MODELS[0]); + workers[0].emit({ elapsedMs: 10, jobId: 1, modelId: LOCAL_LLM_MODELS[0].modelId, type: 'loaded' }); + await loading; + + const generation = client.generate({ maxNewTokens: 64, prompt: 'Hello', systemPrompt: '' }); + const rejection = expectCode(generation, 'worker'); + const fragment = 'x'.repeat(Math.floor(LOCAL_LLM_MAX_OUTPUT_CHARACTERS / 2) + 1); + workers[0].emit({ jobId: 2, text: fragment, tokenCount: 1, type: 'token' }); + workers[0].emit({ jobId: 2, text: fragment, tokenCount: 2, type: 'token' }); + await rejection; + expect(workers[0].terminated).toBe(true); + }); +}); diff --git a/src/tools/local-llm-playground/local-llm.worker-client.ts b/src/tools/local-llm-playground/local-llm.worker-client.ts new file mode 100644 index 0000000000..38c25db3de --- /dev/null +++ b/src/tools/local-llm-playground/local-llm.worker-client.ts @@ -0,0 +1,303 @@ +import { + LOCAL_LLM_MAX_OUTPUT_CHARACTERS, + type LocalLlmModel, +} from './local-llm.models'; +import { + LocalLlmError, + type LocalLlmGenerationOptions, + type LocalLlmProgress, + type LocalLlmWorkerRequest, + parseLocalLlmWorkerMessage, + validateLocalLlmGenerationOptions, +} from './local-llm.protocol'; + +const MODEL_LOAD_TIMEOUT_MS = 30 * 60 * 1_000; +const GENERATION_TIMEOUT_MS = 10 * 60 * 1_000; +const CANCEL_GRACE_MS = 2_000; + +export interface LocalLlmWorkerHandle { + onmessage: ((event: MessageEvent) => void) | null + onmessageerror: ((event: MessageEvent) => void) | null + onerror: ((event: ErrorEvent) => void) | null + postMessage: (message: LocalLlmWorkerRequest) => void + terminate: () => void +} + +export type LocalLlmWorkerFactory = () => LocalLlmWorkerHandle; + +export interface LocalLlmGenerationResult { + cancelled: boolean + elapsedMs: number + output: string + tokenCount: number +} + +interface ActiveOperation { + jobId: number + kind: 'load' | 'generate' + timeout: ReturnType + cancelFallback?: ReturnType + expectedModelId?: string + lastTokenCount: number + maxNewTokens?: number + onProgress?: (progress: LocalLlmProgress) => void + onToken?: (text: string, tokenCount: number) => void + streamedCharacters: number + resolve: (value: { elapsedMs: number } | LocalLlmGenerationResult) => void + reject: (error: LocalLlmError) => void +} + +function createWorker(): LocalLlmWorkerHandle { + return new Worker(new URL('./local-llm.worker.ts', import.meta.url), { + name: 'it-tools-local-llm', + type: 'module', + }); +} + +export class LocalLlmWorkerClient { + private worker: LocalLlmWorkerHandle | undefined; + private active: ActiveOperation | undefined; + private nextJobId = 0; + private loadedModelId: string | undefined; + private disposed = false; + + constructor(private readonly workerFactory: LocalLlmWorkerFactory = createWorker) {} + + get currentModelId(): string | undefined { + return this.loadedModelId; + } + + async load(model: LocalLlmModel, onProgress?: (progress: LocalLlmProgress) => void): Promise<{ elapsedMs: number }> { + if (this.loadedModelId === model.modelId) { + return { elapsedMs: 0 }; + } + if (this.loadedModelId) { + throw new LocalLlmError('model', 'Unload the current model before selecting another one.'); + } + return this.startOperation('load', MODEL_LOAD_TIMEOUT_MS, onProgress, undefined, jobId => ({ + jobId, + modelId: model.modelId, + type: 'load', + })) as Promise<{ elapsedMs: number }>; + } + + async generate( + options: LocalLlmGenerationOptions, + onToken?: (text: string, tokenCount: number) => void, + ): Promise { + if (!this.loadedModelId) { + throw new LocalLlmError('model', 'Load a local model before generating.'); + } + const validated = validateLocalLlmGenerationOptions(options); + return this.startOperation('generate', GENERATION_TIMEOUT_MS, undefined, onToken, jobId => ({ + ...validated, + jobId, + type: 'generate', + })) as Promise; + } + + cancelGeneration(): void { + const active = this.active; + if (!active || active.kind !== 'generate' || !this.worker || active.cancelFallback) { + return; + } + this.worker.postMessage({ jobId: active.jobId, type: 'cancel' }); + active.cancelFallback = globalThis.setTimeout(() => { + this.invalidate(new LocalLlmError('cancelled', 'Generation was cancelled and the model was unloaded.')); + }, CANCEL_GRACE_MS); + } + + cancelLoad(): void { + if (this.active?.kind === 'load') { + this.invalidate(new LocalLlmError('cancelled', 'Model loading was cancelled.')); + } + } + + unload(): void { + this.rejectActive(new LocalLlmError('cancelled', 'The local model was unloaded.')); + this.terminateWorker(); + this.loadedModelId = undefined; + } + + dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + this.rejectActive(new LocalLlmError('cancelled', 'The local model tool was closed.')); + this.terminateWorker(); + this.loadedModelId = undefined; + } + + private startOperation( + kind: 'load' | 'generate', + timeoutMs: number, + onProgress: ((progress: LocalLlmProgress) => void) | undefined, + onToken: ((text: string, tokenCount: number) => void) | undefined, + request: (jobId: number) => LocalLlmWorkerRequest, + ): Promise<{ elapsedMs: number } | LocalLlmGenerationResult> { + if (this.disposed) { + return Promise.reject(new LocalLlmError('unavailable', 'The local model tool has already been closed.')); + } + if (this.active) { + return Promise.reject(new LocalLlmError('worker', 'Another local model operation is already running.')); + } + let worker: LocalLlmWorkerHandle; + try { + worker = this.ensureWorker(); + } + catch { + return Promise.reject(new LocalLlmError('unavailable', 'Web Workers are unavailable in this browser.')); + } + this.nextJobId = this.nextJobId === Number.MAX_SAFE_INTEGER ? 1 : this.nextJobId + 1; + const jobId = this.nextJobId; + + return new Promise((resolve, reject) => { + const timeout = globalThis.setTimeout(() => { + this.invalidate(new LocalLlmError('worker', `${kind === 'load' ? 'Model loading' : 'Generation'} timed out.`)); + }, timeoutMs); + const payload = request(jobId); + this.active = { + expectedModelId: payload.type === 'load' ? payload.modelId : undefined, + jobId, + kind, + lastTokenCount: 0, + maxNewTokens: payload.type === 'generate' ? payload.maxNewTokens : undefined, + onProgress, + onToken, + reject, + resolve, + streamedCharacters: 0, + timeout, + }; + try { + worker.postMessage(payload); + } + catch { + this.invalidate(new LocalLlmError('worker', 'The local model worker could not be started.')); + } + }); + } + + private ensureWorker(): LocalLlmWorkerHandle { + if (this.worker) { + return this.worker; + } + const worker = this.workerFactory(); + worker.onmessage = event => this.handleMessage(event.data); + worker.onerror = (event) => { + event.preventDefault(); + this.invalidate(new LocalLlmError('worker', 'The local model worker stopped unexpectedly.')); + }; + worker.onmessageerror = (event) => { + event.preventDefault(); + this.invalidate(new LocalLlmError('worker', 'The local model worker returned an unreadable message.')); + }; + this.worker = worker; + return worker; + } + + private handleMessage(value: unknown): void { + let message; + try { + message = parseLocalLlmWorkerMessage(value); + } + catch (error) { + this.invalidate(error instanceof LocalLlmError ? error : new LocalLlmError('worker', 'The local model worker returned an invalid message.')); + return; + } + const active = this.active; + if (!active || message.jobId !== active.jobId) { + return; + } + if (message.type === 'progress') { + if (active.kind !== 'load') { + this.invalidate(new LocalLlmError('worker', 'The local model worker returned progress for the wrong operation.')); + return; + } + active.onProgress?.(message.progress); + return; + } + if (message.type === 'token') { + const nextCharacters = active.streamedCharacters + message.text.length; + if (active.kind !== 'generate' + || message.tokenCount < active.lastTokenCount + || message.tokenCount > (active.maxNewTokens ?? 0) + || nextCharacters > LOCAL_LLM_MAX_OUTPUT_CHARACTERS) { + this.invalidate(new LocalLlmError('worker', 'The local model worker exceeded its streaming result bounds.')); + return; + } + active.lastTokenCount = message.tokenCount; + active.streamedCharacters = nextCharacters; + active.onToken?.(message.text, message.tokenCount); + return; + } + if (message.type === 'error') { + this.finishActive(); + active.reject(new LocalLlmError(message.code, message.message)); + return; + } + if (message.type === 'loaded') { + if (active.kind !== 'load' || message.modelId !== active.expectedModelId) { + this.invalidate(new LocalLlmError('worker', 'The local model worker returned the wrong loaded model.')); + return; + } + this.loadedModelId = message.modelId; + this.finishActive(); + active.resolve({ elapsedMs: message.elapsedMs }); + return; + } + if (active.kind !== 'generate' || message.tokenCount > (active.maxNewTokens ?? 0)) { + this.invalidate(new LocalLlmError('worker', 'The local model worker returned a result for the wrong operation.')); + return; + } + this.finishActive(); + active.resolve({ + cancelled: message.cancelled, + elapsedMs: message.elapsedMs, + output: message.output, + tokenCount: message.tokenCount, + }); + } + + private finishActive(): void { + if (!this.active) { + return; + } + globalThis.clearTimeout(this.active.timeout); + if (this.active.cancelFallback !== undefined) { + globalThis.clearTimeout(this.active.cancelFallback); + } + this.active = undefined; + } + + private rejectActive(error: LocalLlmError): void { + const active = this.active; + if (!active) { + return; + } + this.finishActive(); + active.reject(error); + } + + private invalidate(error: LocalLlmError): void { + this.rejectActive(error); + this.terminateWorker(); + this.loadedModelId = undefined; + } + + private terminateWorker(): void { + if (!this.worker) { + return; + } + this.worker.onmessage = null; + this.worker.onerror = null; + this.worker.onmessageerror = null; + this.worker.terminate(); + this.worker = undefined; + } +} + +export function createLocalLlmWorkerClient(): LocalLlmWorkerClient { + return new LocalLlmWorkerClient(); +} diff --git a/src/tools/local-llm-playground/local-llm.worker.ts b/src/tools/local-llm-playground/local-llm.worker.ts new file mode 100644 index 0000000000..48172f7216 --- /dev/null +++ b/src/tools/local-llm-playground/local-llm.worker.ts @@ -0,0 +1,286 @@ +/// + +import { + AutoModelForCausalLM, + AutoTokenizer, + InterruptableStoppingCriteria, + TextStreamer, + env, +} from '@huggingface/transformers'; +import { + LOCAL_LLM_CACHE_NAME, + LOCAL_LLM_MAX_ERROR_CHARACTERS, + LOCAL_LLM_MAX_OUTPUT_CHARACTERS, + LOCAL_LLM_MAX_PROGRESS_FILES, + LOCAL_LLM_MAX_PROGRESS_FILE_CHARACTERS, + LOCAL_LLM_MAX_PROGRESS_STATUS_CHARACTERS, + getLocalLlmModelAssetBasePath, + getLocalLlmModelById, +} from './local-llm.models'; +import { + LocalLlmError, + type LocalLlmErrorCode, + type LocalLlmProgress, + type LocalLlmWorkerMessage, + parseLocalLlmWorkerRequest, +} from './local-llm.protocol'; + +type LocalTokenizer = Awaited>; +type LocalModel = Awaited>; +type LocalStoppingCriteria = InstanceType; + +interface LocalLlmWorkerScope { + addEventListener: (type: 'message', listener: (event: MessageEvent) => void) => void + postMessage: (message: LocalLlmWorkerMessage) => void +} + +const workerScope = globalThis as unknown as LocalLlmWorkerScope; +let runtimePromise: Promise | undefined; +let tokenizer: LocalTokenizer | undefined; +let model: LocalModel | undefined; +let loadedModelId: string | undefined; +let activeJobId: number | undefined; +let activeOperation: 'load' | 'generate' | undefined; +let stoppingCriteria: LocalStoppingCriteria | undefined; +let generationCancelled = false; + +function post(message: LocalLlmWorkerMessage): void { + workerScope.postMessage(message); +} + +function toErrorMessage(error: unknown): string { + if (error instanceof Error && error.message.trim()) { + return error.message.slice(0, LOCAL_LLM_MAX_ERROR_CHARACTERS); + } + return 'The local model operation failed.'; +} + +function normalizeProgress(value: unknown, phase: string): LocalLlmProgress { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return { status: phase }; + } + const record = value as Record; + const finite = (candidate: unknown) => typeof candidate === 'number' && Number.isFinite(candidate) && candidate >= 0 + ? candidate + : undefined; + const files = record.files && typeof record.files === 'object' && !Array.isArray(record.files) + ? Object.entries(record.files as Record) + .slice(0, LOCAL_LLM_MAX_PROGRESS_FILES) + .flatMap(([file, fileProgress]) => { + if (!file || typeof fileProgress !== 'object' || fileProgress === null || Array.isArray(fileProgress)) { + return []; + } + const fileRecord = fileProgress as Record; + return [{ + file: file.slice(0, LOCAL_LLM_MAX_PROGRESS_FILE_CHARACTERS), + loaded: finite(fileRecord.loaded), + total: finite(fileRecord.total), + }]; + }) + : undefined; + return { + file: typeof record.file === 'string' ? record.file.slice(0, LOCAL_LLM_MAX_PROGRESS_FILE_CHARACTERS) : undefined, + files, + loaded: finite(record.loaded), + progress: finite(record.progress), + status: (typeof record.status === 'string' ? `${phase}:${record.status}` : phase) + .slice(0, LOCAL_LLM_MAX_PROGRESS_STATUS_CHARACTERS), + total: finite(record.total), + }; +} + +async function initializeRuntime(): Promise { + runtimePromise ??= (async () => { + env.allowLocalModels = true; + env.allowRemoteModels = false; + env.experimental_useCrossOriginStorage = false; + env.useFS = false; + env.useFSCache = false; + env.useBrowserCache = false; + env.useCustomCache = false; + env.customCache = null; + + if (typeof globalThis.caches !== 'undefined') { + try { + env.customCache = await globalThis.caches.open(LOCAL_LLM_CACHE_NAME); + env.useCustomCache = true; + } + catch { + // The model can still run for this tab when Cache Storage is denied. + } + } + })(); + await runtimePromise; +} + +async function loadModel(jobId: number, modelId: string): Promise { + if (activeOperation) { + throw new LocalLlmError('worker', 'Another local model operation is already running.'); + } + if (loadedModelId === modelId && tokenizer && model) { + post({ elapsedMs: 0, jobId, modelId, type: 'loaded' }); + return; + } + if (loadedModelId && loadedModelId !== modelId) { + throw new LocalLlmError('model', 'Unload the current model before selecting another one.'); + } + + activeJobId = jobId; + activeOperation = 'load'; + const startedAt = performance.now(); + try { + await initializeRuntime(); + const selectedModel = getLocalLlmModelById(modelId); + if (!selectedModel) { + throw new LocalLlmError('model', 'The requested local model is not supported.'); + } + env.localModelPath = getLocalLlmModelAssetBasePath(selectedModel, import.meta.env.BASE_URL); + post({ jobId, progress: { status: 'runtime:ready' }, type: 'progress' }); + tokenizer = await AutoTokenizer.from_pretrained(modelId, { + local_files_only: true, + progress_callback: value => post({ jobId, progress: normalizeProgress(value, 'tokenizer'), type: 'progress' }), + }); + model = await AutoModelForCausalLM.from_pretrained(modelId, { + device: 'webgpu', + dtype: { + decoder_model_merged: 'q4', + embed_tokens: 'q4', + }, + local_files_only: true, + progress_callback: value => post({ jobId, progress: normalizeProgress(value, 'model'), type: 'progress' }), + }); + loadedModelId = modelId; + post({ elapsedMs: performance.now() - startedAt, jobId, modelId, type: 'loaded' }); + } + catch (error) { + tokenizer = undefined; + model = undefined; + loadedModelId = undefined; + throw error; + } + finally { + activeJobId = undefined; + activeOperation = undefined; + } +} + +async function generateText( + jobId: number, + prompt: string, + systemPrompt: string, + maxNewTokens: number, +): Promise { + if (activeOperation) { + throw new LocalLlmError('worker', 'Another local model operation is already running.'); + } + if (!tokenizer || !model || !loadedModelId) { + throw new LocalLlmError('model', 'Load a local model before generating.'); + } + + activeJobId = jobId; + activeOperation = 'generate'; + generationCancelled = false; + const startedAt = performance.now(); + let output = ''; + let tokenCount = 0; + try { + await initializeRuntime(); + stoppingCriteria = new InterruptableStoppingCriteria(); + const messages: Array<{ role: 'system' | 'user'; content: string }> = []; + if (systemPrompt) { + messages.push({ content: systemPrompt, role: 'system' }); + } + messages.push({ content: prompt, role: 'user' }); + const chatPrompt = tokenizer.apply_chat_template(messages, { + add_generation_prompt: true, + tokenize: false, + }); + const modelInputs = await tokenizer(`${chatPrompt}\n\n\n\n`); + const streamer = new TextStreamer(tokenizer, { + callback_function: (fragment) => { + if (!fragment || generationCancelled) { + return; + } + const available = LOCAL_LLM_MAX_OUTPUT_CHARACTERS - output.length; + const accepted = fragment.slice(0, Math.max(0, available)); + output += accepted; + if (accepted) { + post({ jobId, text: accepted, tokenCount, type: 'token' }); + } + if (accepted.length !== fragment.length) { + stoppingCriteria?.interrupt(); + } + }, + skip_prompt: true, + skip_special_tokens: true, + token_callback_function: () => { + tokenCount += 1; + }, + }); + + await model.generate({ + ...modelInputs, + do_sample: false, + max_new_tokens: maxNewTokens, + streamer, + stopping_criteria: stoppingCriteria, + }); + + output = output.replace(/<\|im_end\|>/gu, '').trimStart(); + post({ + cancelled: generationCancelled, + elapsedMs: performance.now() - startedAt, + jobId, + output, + tokenCount, + type: 'generated', + }); + } + finally { + stoppingCriteria = undefined; + activeJobId = undefined; + activeOperation = undefined; + generationCancelled = false; + } +} + +function errorCode(error: unknown, operation: 'load' | 'generate' | undefined): LocalLlmErrorCode { + if (error instanceof LocalLlmError) { + return error.code; + } + const message = toErrorMessage(error); + if (/WebGPU|GPU|adapter|device/iu.test(message)) { + return 'unavailable'; + } + return operation === 'load' ? 'model' : 'worker'; +} + +async function handleRequest(value: unknown): Promise { + let jobId = 1; + let operation: 'load' | 'generate' | undefined; + try { + const request = parseLocalLlmWorkerRequest(value); + jobId = request.jobId; + if (request.type === 'cancel') { + if (activeOperation === 'generate' && activeJobId === request.jobId) { + generationCancelled = true; + stoppingCriteria?.interrupt(); + } + return; + } + if (request.type === 'load') { + operation = 'load'; + await loadModel(request.jobId, request.modelId); + return; + } + operation = 'generate'; + await generateText(request.jobId, request.prompt, request.systemPrompt, request.maxNewTokens); + } + catch (error) { + post({ code: errorCode(error, operation), jobId, message: toErrorMessage(error), type: 'error' }); + } +} + +workerScope.addEventListener('message', (event) => { + handleRequest(event.data); +}); diff --git a/src/tools/shell-existing-route-wave.e2e.spec.ts b/src/tools/shell-existing-route-wave.e2e.spec.ts index ece875898e..b1a4f519eb 100644 --- a/src/tools/shell-existing-route-wave.e2e.spec.ts +++ b/src/tools/shell-existing-route-wave.e2e.spec.ts @@ -37,7 +37,7 @@ test.describe('Shell-conscious existing-route interoperability wave', () => { await page.goto('/?q=first&q=second&category=Missing&secret=do-not-keep'); await expect(page).toHaveURL(/\/$/); await expect(page.getByLabel('Search tools')).toHaveValue(''); - await expect(page.getByTestId('home-filter-status')).toContainText('133 tools shown'); + await expect(page.getByTestId('home-filter-status')).toContainText('134 tools shown'); }); test('downloads the complete already-computed converter output with a safe filename', async ({ page }) => { diff --git a/vite.config.ts b/vite.config.ts index e721c7ae76..81662b0fee 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -42,6 +42,7 @@ const figletVersion = readPackageVersion(figletPackageJsonPath); const figletFontAssetDirectory = `assets/figlet-fonts-${figletVersion}`; const lazyAssetCacheName = 'it-tools-lazy-assets-v1'; const figletFontCacheName = `figlet-fonts-${figletVersion}`; +const localLlmModelAssetDirectory = 'assets/local-llm-models'; const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`; const figletFontPublicPath = `${normalizedBaseUrl}${figletFontAssetDirectory}`; const geoIpPublicDirectory = resolve(__dirname, 'public/assets/geoip'); @@ -455,7 +456,10 @@ export default defineConfig({ ], }, workbox: { - globIgnores: [`${figletFontAssetDirectory}/**/*`], + globIgnores: [ + `${figletFontAssetDirectory}/**/*`, + `${localLlmModelAssetDirectory}/**/*`, + ], cleanupOutdatedCaches: true, manifestTransforms: [ async (entries) => {