Spaces:
Running
Running
v0.4.0: mobile warning, clean model-load errors, API model option
Browse files- css/app.css +42 -0
- index.html +43 -0
- js/config.js +1 -1
- js/llm.js +5 -0
- js/main.js +191 -20
- js/remote-llm.js +266 -0
- sw.js +2 -2
css/app.css
CHANGED
|
@@ -452,6 +452,47 @@ dialog[open] { animation: pop .14s ease-out; }
|
|
| 452 |
.switch:checked { background: var(--primary); border-color: var(--primary); }
|
| 453 |
.switch:checked::after { transform: translateX(14px); background: var(--primary-ink); }
|
| 454 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
/* ---------- narrow screens ---------- */
|
| 456 |
@media (max-width: 900px) {
|
| 457 |
body { grid-template-rows: auto auto 1fr; }
|
|
@@ -476,3 +517,4 @@ dialog[open] { animation: pop .14s ease-out; }
|
|
| 476 |
|
| 477 |
/* Code should show exactly what is typed: no programming ligatures (=> stays =>). */
|
| 478 |
code, pre, kbd, .mono, .tool-label, .crumbs, .vw-path, .hex, #terminal * { font-variant-ligatures: none !important; font-feature-settings: "liga" 0, "calt" 0 !important; }
|
|
|
|
|
|
| 452 |
.switch:checked { background: var(--primary); border-color: var(--primary); }
|
| 453 |
.switch:checked::after { transform: translateX(14px); background: var(--primary-ink); }
|
| 454 |
|
| 455 |
+
/* ---------- model callouts, mobile banner, API dialog ---------- */
|
| 456 |
+
.callout {
|
| 457 |
+
border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface);
|
| 458 |
+
padding: 12px 14px; font-size: 13px; color: var(--text-2);
|
| 459 |
+
}
|
| 460 |
+
.callout.error { border-color: color-mix(in srgb, var(--bad) 45%, var(--border)); }
|
| 461 |
+
.callout.warn { border-color: color-mix(in srgb, var(--warn) 45%, var(--border)); }
|
| 462 |
+
.callout-title { display: flex; align-items: center; gap: 8px; font-weight: 600; color: var(--text); }
|
| 463 |
+
.callout-title svg { width: 16px; height: 16px; flex: none; fill: none; stroke: currentColor; stroke-width: 2; }
|
| 464 |
+
.callout.error .callout-title svg { color: var(--bad); }
|
| 465 |
+
.callout.warn .callout-title svg { color: var(--warn); }
|
| 466 |
+
.callout p { margin: 6px 0 10px; line-height: 1.5; }
|
| 467 |
+
.callout-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
| 468 |
+
.callout-details { margin-top: 10px; font-size: 12px; }
|
| 469 |
+
.callout-details summary { cursor: pointer; color: var(--text-3); }
|
| 470 |
+
.callout-details pre {
|
| 471 |
+
margin: 6px 0 0; padding: 8px 10px; border-radius: var(--radius-sm); background: var(--code-bg); color: var(--code-text);
|
| 472 |
+
font-family: var(--mono); font-size: 11.5px; white-space: pre-wrap; word-break: break-word; max-height: 180px; overflow: auto;
|
| 473 |
+
}
|
| 474 |
+
.banner {
|
| 475 |
+
display: flex; gap: 10px; align-items: flex-start; padding: 12px 14px; margin: 0 0 24px;
|
| 476 |
+
border-radius: var(--radius); border: 1px solid var(--border); background: var(--surface); font-size: 13px; color: var(--text-2); line-height: 1.5;
|
| 477 |
+
}
|
| 478 |
+
.banner svg { width: 18px; height: 18px; flex: none; margin-top: 1px; fill: none; stroke: currentColor; stroke-width: 2; }
|
| 479 |
+
.banner.warn { border-color: color-mix(in srgb, var(--warn) 50%, var(--border)); }
|
| 480 |
+
.banner.warn svg { color: var(--warn); }
|
| 481 |
+
.banner strong { color: var(--text); display: block; margin-bottom: 2px; }
|
| 482 |
+
.btn.secondary { margin-top: 10px; }
|
| 483 |
+
.dlg-lede { margin: 0 0 14px; font-size: 12.5px; color: var(--text-2); line-height: 1.5; }
|
| 484 |
+
.field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; }
|
| 485 |
+
.field-label { font-size: 12px; font-weight: 500; color: var(--text-2); }
|
| 486 |
+
.field input, .field select {
|
| 487 |
+
height: 36px; padding: 0 10px; border-radius: 10px; border: 1px solid var(--border-strong);
|
| 488 |
+
background: var(--surface-2); color: var(--text); font: inherit; font-size: 13px; width: 100%; min-width: 0;
|
| 489 |
+
}
|
| 490 |
+
.field input:focus, .field select:focus { outline: 2px solid var(--focus); outline-offset: -1px; }
|
| 491 |
+
.field-hint { margin: -4px 0 8px; font-size: 12px; color: var(--text-3); }
|
| 492 |
+
.note.ok { color: var(--ok); }
|
| 493 |
+
.dlg-foot { display: flex; align-items: center; gap: 8px; padding: 12px 22px 18px; border-top: 1px solid var(--border); }
|
| 494 |
+
#api-dlg { max-height: calc(100dvh - 32px); overflow-y: auto; }
|
| 495 |
+
|
| 496 |
/* ---------- narrow screens ---------- */
|
| 497 |
@media (max-width: 900px) {
|
| 498 |
body { grid-template-rows: auto auto 1fr; }
|
|
|
|
| 517 |
|
| 518 |
/* Code should show exactly what is typed: no programming ligatures (=> stays =>). */
|
| 519 |
code, pre, kbd, .mono, .tool-label, .crumbs, .vw-path, .hex, #terminal * { font-variant-ligatures: none !important; font-feature-settings: "liga" 0, "calt" 0 !important; }
|
| 520 |
+
.btn.block.secondary { white-space: normal; height: auto; min-height: 42px; padding: 8px 14px; }
|
index.html
CHANGED
|
@@ -131,6 +131,13 @@
|
|
| 131 |
<div class="setup" id="setup" hidden>
|
| 132 |
<div class="setup-inner">
|
| 133 |
<div class="setup-brand"><img src="icon.svg" alt="" width="22" height="22"><span>LocalWebAgent</span></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
<h2>Install for offline use</h2>
|
| 135 |
<p class="lede">A language model and a Linux machine, both running inside this browser tab. Download once, about 1.6 GB, and it keeps working without an internet connection.</p>
|
| 136 |
|
|
@@ -157,6 +164,7 @@
|
|
| 157 |
</div>
|
| 158 |
|
| 159 |
<button class="btn primary block" id="install" disabled>Install</button>
|
|
|
|
| 160 |
<p class="note" id="setup-note"></p>
|
| 161 |
<p class="fine">
|
| 162 |
The model is <a href="https://huggingface.co/LiquidAI/LFM3-1.7B" target="_blank" rel="noopener">LFM3-1.7B</a> (LFM Open License), loaded from Hugging Face.
|
|
@@ -171,6 +179,13 @@
|
|
| 171 |
<h2 id="settings-title">Settings</h2>
|
| 172 |
<button class="icon-btn" value="close" aria-label="Close"><svg><use href="#i-x"/></svg></button>
|
| 173 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
<div class="dlg-section">
|
| 175 |
<div class="section-label">Agent</div>
|
| 176 |
<label class="row-setting">
|
|
@@ -204,6 +219,34 @@
|
|
| 204 |
</form>
|
| 205 |
</dialog>
|
| 206 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
<script type="module" src="js/main.js"></script>
|
| 208 |
</body>
|
| 209 |
</html>
|
|
|
|
| 131 |
<div class="setup" id="setup" hidden>
|
| 132 |
<div class="setup-inner">
|
| 133 |
<div class="setup-brand"><img src="icon.svg" alt="" width="22" height="22"><span>LocalWebAgent</span></div>
|
| 134 |
+
<div class="banner warn" id="mobile-banner" hidden>
|
| 135 |
+
<svg><use href="#i-alert"/></svg>
|
| 136 |
+
<div>
|
| 137 |
+
<strong>Phones usually can't run the local model.</strong>
|
| 138 |
+
It needs about 1.4 GB of graphics memory, more than most phones give a browser tab. Use an API model instead: the Linux machine still runs on your phone, only the model runs on the provider's servers. You can also install everything and try the local model anyway.
|
| 139 |
+
</div>
|
| 140 |
+
</div>
|
| 141 |
<h2>Install for offline use</h2>
|
| 142 |
<p class="lede">A language model and a Linux machine, both running inside this browser tab. Download once, about 1.6 GB, and it keeps working without an internet connection.</p>
|
| 143 |
|
|
|
|
| 164 |
</div>
|
| 165 |
|
| 166 |
<button class="btn primary block" id="install" disabled>Install</button>
|
| 167 |
+
<button class="btn block secondary" id="setup-api" type="button">Use an API model instead</button>
|
| 168 |
<p class="note" id="setup-note"></p>
|
| 169 |
<p class="fine">
|
| 170 |
The model is <a href="https://huggingface.co/LiquidAI/LFM3-1.7B" target="_blank" rel="noopener">LFM3-1.7B</a> (LFM Open License), loaded from Hugging Face.
|
|
|
|
| 179 |
<h2 id="settings-title">Settings</h2>
|
| 180 |
<button class="icon-btn" value="close" aria-label="Close"><svg><use href="#i-x"/></svg></button>
|
| 181 |
</div>
|
| 182 |
+
<div class="dlg-section">
|
| 183 |
+
<div class="section-label">Model</div>
|
| 184 |
+
<div class="row-setting">
|
| 185 |
+
<span><span class="rs-title">Language model</span><span class="rs-desc" id="set-model-desc"></span></span>
|
| 186 |
+
<button type="button" class="btn" id="set-model">Change</button>
|
| 187 |
+
</div>
|
| 188 |
+
</div>
|
| 189 |
<div class="dlg-section">
|
| 190 |
<div class="section-label">Agent</div>
|
| 191 |
<label class="row-setting">
|
|
|
|
| 219 |
</form>
|
| 220 |
</dialog>
|
| 221 |
|
| 222 |
+
<dialog id="api-dlg" aria-labelledby="api-title">
|
| 223 |
+
<form id="api-form" novalidate>
|
| 224 |
+
<div class="dlg-head">
|
| 225 |
+
<h2 id="api-title">Use an API model</h2>
|
| 226 |
+
<button class="icon-btn" type="button" id="api-close" aria-label="Close"><svg><use href="#i-x"/></svg></button>
|
| 227 |
+
</div>
|
| 228 |
+
<div class="dlg-section">
|
| 229 |
+
<p class="dlg-lede">The Linux machine keeps running in this tab. Only the language model runs on the provider's servers, so the agent needs an internet connection and the provider receives your messages and the command output. Any OpenAI-compatible Chat Completions API works.</p>
|
| 230 |
+
<label class="field"><span class="field-label">Provider</span><select id="api-preset"></select></label>
|
| 231 |
+
<label class="field"><span class="field-label">Base URL</span><input id="api-base" type="url" placeholder="https://api.example.com/v1" spellcheck="false" autocomplete="off"></label>
|
| 232 |
+
<label class="field"><span class="field-label">API key</span><input id="api-key" type="password" placeholder="Leave empty for local servers without a key" spellcheck="false" autocomplete="off"></label>
|
| 233 |
+
<label class="field"><span class="field-label">Model ID</span><input id="api-model" placeholder="As listed by your provider" spellcheck="false" autocomplete="off"></label>
|
| 234 |
+
<p class="field-hint">Pick a model that supports tool calling.</p>
|
| 235 |
+
<label class="row-setting">
|
| 236 |
+
<span><span class="rs-title">Remember key on this device</span><span class="rs-desc">Saved in this browser. When off, the key is forgotten when you close the tab.</span></span>
|
| 237 |
+
<input type="checkbox" class="switch" id="api-remember">
|
| 238 |
+
</label>
|
| 239 |
+
<p class="note" id="api-note" role="status"></p>
|
| 240 |
+
</div>
|
| 241 |
+
<div class="dlg-foot">
|
| 242 |
+
<button type="button" class="btn" id="api-local" hidden>Use the local model</button>
|
| 243 |
+
<span class="spacer"></span>
|
| 244 |
+
<button type="button" class="btn" id="api-test">Test</button>
|
| 245 |
+
<button type="submit" class="btn primary" id="api-save">Save and use</button>
|
| 246 |
+
</div>
|
| 247 |
+
</form>
|
| 248 |
+
</dialog>
|
| 249 |
+
|
| 250 |
<script type="module" src="js/main.js"></script>
|
| 251 |
</body>
|
| 252 |
</html>
|
js/config.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
// Central configuration. Everything that pins a version or a location lives here.
|
| 2 |
-
export const APP_VERSION = "0.
|
| 3 |
|
| 4 |
// --- Language model (loaded from the Hugging Face Hub, cached by transformers.js) ---
|
| 5 |
export const MODEL_ID = "LiquidAI/LFM3-1.7B-ONNX";
|
|
|
|
| 1 |
// Central configuration. Everything that pins a version or a location lives here.
|
| 2 |
+
export const APP_VERSION = "0.4.0";
|
| 3 |
|
| 4 |
// --- Language model (loaded from the Hugging Face Hub, cached by transformers.js) ---
|
| 5 |
export const MODEL_ID = "LiquidAI/LFM3-1.7B-ONNX";
|
js/llm.js
CHANGED
|
@@ -32,6 +32,11 @@ export class LLM {
|
|
| 32 |
}
|
| 33 |
|
| 34 |
stop() { this.worker.postMessage({ type: "stop" }); }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
resetCache() { this.worker.postMessage({ type: "reset" }); }
|
| 36 |
|
| 37 |
#fail(err) {
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
stop() { this.worker.postMessage({ type: "stop" }); }
|
| 35 |
+
/** Ends the worker, releasing the model's GPU memory. */
|
| 36 |
+
dispose() {
|
| 37 |
+
this.worker.terminate();
|
| 38 |
+
this.#fail(new Error("The local model was unloaded."));
|
| 39 |
+
}
|
| 40 |
resetCache() { this.worker.postMessage({ type: "reset" }); }
|
| 41 |
|
| 42 |
#fail(err) {
|
js/main.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import { DEFAULTS, MODEL_DOWNLOAD_BYTES, MODEL_ID, MODEL_DEVICE, APP_VERSION } from "./config.js";
|
| 2 |
import * as setup from "./setup.js";
|
| 3 |
import { LLM } from "./llm.js";
|
|
|
|
| 4 |
import { VM } from "./vm.js";
|
| 5 |
import { Agent } from "./agent.js";
|
| 6 |
import { renderMarkdown } from "./markdown.js";
|
|
@@ -44,7 +45,14 @@ function status(name, state, text) {
|
|
| 44 |
el.title = text;
|
| 45 |
}
|
| 46 |
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
const vm = new VM();
|
| 49 |
let agent = null;
|
| 50 |
let diskManifest = null;
|
|
@@ -54,8 +62,7 @@ let files = null;
|
|
| 54 |
// ---------- boot ----------
|
| 55 |
async function init() {
|
| 56 |
$("#version").textContent = "v" + APP_VERSION;
|
| 57 |
-
|
| 58 |
-
$("#gpu-name").textContent = MODEL_DEVICE === "webgpu" ? "WebGPU" : MODEL_DEVICE;
|
| 59 |
$("#model-size").textContent = fmtBytes(MODEL_DOWNLOAD_BYTES);
|
| 60 |
syncToggles();
|
| 61 |
|
|
@@ -70,11 +77,15 @@ async function init() {
|
|
| 70 |
diskManifest = disk;
|
| 71 |
const installed = { cx: cx.ready, disk: !!disk, model: model.ready };
|
| 72 |
for (const k of Object.keys(installed)) if (installed[k]) setRow(k, 1, "Installed");
|
| 73 |
-
const
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
if (all
|
| 77 |
-
else
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
}
|
| 79 |
|
| 80 |
async function environmentChecks() {
|
|
@@ -83,7 +94,8 @@ async function environmentChecks() {
|
|
| 83 |
? { ok: true, text: "Cross-origin isolation" }
|
| 84 |
: { ok: false, text: window.top !== window ? "The embedded view can't run the VM. Open the app in its own tab." : "Cross-origin isolation is off (COOP/COEP headers missing)" };
|
| 85 |
c.sw = "serviceWorker" in navigator ? { ok: true, text: "Offline storage" } : { ok: false, text: "Offline storage unavailable (private window?)" };
|
| 86 |
-
if (
|
|
|
|
| 87 |
else if (!navigator.gpu) c.gpu = { ok: false, text: "WebGPU unavailable. Use desktop Chrome or Edge." };
|
| 88 |
else {
|
| 89 |
try {
|
|
@@ -120,6 +132,13 @@ function setRow(k, frac, text) {
|
|
| 120 |
|
| 121 |
function showSetup(canInstall) {
|
| 122 |
$("#setup").hidden = false;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
const btn = $("#install");
|
| 124 |
btn.disabled = !canInstall || !navigator.onLine;
|
| 125 |
if (!navigator.onLine) $("#setup-note").textContent = "You're offline. Connect once to install; after that it works without internet.";
|
|
@@ -145,9 +164,13 @@ async function install() {
|
|
| 145 |
diskManifest = await setup.downloadDisk((d, t) => setRow("disk", d / t, `${Math.round((d / t) * 100)}%`));
|
| 146 |
setRow("disk", 1, "Installed");
|
| 147 |
})();
|
| 148 |
-
const modelTask = loadModel((f, text) => setRow("model", f, text)).then(
|
|
|
|
|
|
|
|
|
|
| 149 |
await Promise.all([cxTask, diskTask, modelTask]);
|
| 150 |
-
status("offline", "
|
|
|
|
| 151 |
start();
|
| 152 |
} catch (err) {
|
| 153 |
console.error(err);
|
|
@@ -160,6 +183,9 @@ async function install() {
|
|
| 160 |
|
| 161 |
// Aggregates transformers.js per-file progress into one number.
|
| 162 |
function loadModel(onProgress) {
|
|
|
|
|
|
|
|
|
|
| 163 |
const files = new Map();
|
| 164 |
llm.onProgress = (p) => {
|
| 165 |
if (!p.file) return;
|
|
@@ -224,11 +250,8 @@ async function start() {
|
|
| 224 |
}
|
| 225 |
setComposerEnabled();
|
| 226 |
};
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
addNotice("The model failed to load: " + err.message, "error");
|
| 230 |
-
});
|
| 231 |
-
if (memoryConstrained()) {
|
| 232 |
// Upload the weights to the GPU before Linux takes its share of memory: on phones
|
| 233 |
// the two together at peak are what makes the browser kill the GPU process.
|
| 234 |
status("vm", "busy", "Waiting for the model");
|
|
@@ -242,9 +265,77 @@ async function start() {
|
|
| 242 |
|
| 243 |
// Phones, tablets and machines reporting under 8 GB of RAM (Chrome caps deviceMemory at 8).
|
| 244 |
function memoryConstrained() {
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
}
|
| 249 |
|
| 250 |
// ---------- conversation rendering ----------
|
|
@@ -391,7 +482,9 @@ function setComposerEnabled() {
|
|
| 391 |
$("#send").hidden = running;
|
| 392 |
$("#stop").hidden = !running;
|
| 393 |
$("#send").disabled = !ready;
|
| 394 |
-
$("#prompt").placeholder = ready ? "Describe a task for the agent"
|
|
|
|
|
|
|
| 395 |
}
|
| 396 |
|
| 397 |
async function send(text) {
|
|
@@ -529,6 +622,7 @@ for (const tab of document.querySelectorAll("[data-tab]")) tab.addEventListener(
|
|
| 529 |
|
| 530 |
const dlg = $("#settings");
|
| 531 |
$("#open-settings").addEventListener("click", () => {
|
|
|
|
| 532 |
$("#set-thinking").checked = settings.thinking;
|
| 533 |
$("#set-confirm").checked = settings.confirmCommands;
|
| 534 |
$("#set-steps").value = settings.maxSteps;
|
|
@@ -544,6 +638,83 @@ dlg.addEventListener("close", () => {
|
|
| 544 |
syncToggles();
|
| 545 |
});
|
| 546 |
dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); }); // click on backdrop
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
$("#reset-vm").addEventListener("click", async () => {
|
| 548 |
if (!confirm("Erase all files and changes made inside the Linux machine? The page will reload.")) return;
|
| 549 |
if (vm.overlayName) await setup.resetVmStorage(vm.overlayName);
|
|
|
|
| 1 |
import { DEFAULTS, MODEL_DOWNLOAD_BYTES, MODEL_ID, MODEL_DEVICE, APP_VERSION } from "./config.js";
|
| 2 |
import * as setup from "./setup.js";
|
| 3 |
import { LLM } from "./llm.js";
|
| 4 |
+
import { RemoteLLM, API_PRESETS, loadApiKey, saveApiKey, apiKeyRemembered } from "./remote-llm.js";
|
| 5 |
import { VM } from "./vm.js";
|
| 6 |
import { Agent } from "./agent.js";
|
| 7 |
import { renderMarkdown } from "./markdown.js";
|
|
|
|
| 45 |
el.title = text;
|
| 46 |
}
|
| 47 |
|
| 48 |
+
// ---------- model backend: local (WebGPU) or an OpenAI-compatible API ----------
|
| 49 |
+
const isMobile = () => !!navigator.userAgentData?.mobile || /Android|iPhone|iPad|Mobile/i.test(navigator.userAgent);
|
| 50 |
+
const usingApi = () => settings.backend === "api" && !!settings.api?.baseUrl && !!settings.api?.model;
|
| 51 |
+
const apiConfig = () => ({ baseUrl: settings.api.baseUrl, model: settings.api.model, key: loadApiKey() });
|
| 52 |
+
const apiHost = () => { try { return new URL(settings.api.baseUrl).host; } catch { return settings.api?.baseUrl ?? ""; } };
|
| 53 |
+
|
| 54 |
+
let llm = usingApi() ? new RemoteLLM(apiConfig()) : new LLM();
|
| 55 |
+
let modelError = null; // why the local model failed to load, if it did
|
| 56 |
const vm = new VM();
|
| 57 |
let agent = null;
|
| 58 |
let diskManifest = null;
|
|
|
|
| 62 |
// ---------- boot ----------
|
| 63 |
async function init() {
|
| 64 |
$("#version").textContent = "v" + APP_VERSION;
|
| 65 |
+
setBackendLabels();
|
|
|
|
| 66 |
$("#model-size").textContent = fmtBytes(MODEL_DOWNLOAD_BYTES);
|
| 67 |
syncToggles();
|
| 68 |
|
|
|
|
| 77 |
diskManifest = disk;
|
| 78 |
const installed = { cx: cx.ready, disk: !!disk, model: model.ready };
|
| 79 |
for (const k of Object.keys(installed)) if (installed[k]) setRow(k, 1, "Installed");
|
| 80 |
+
const needModel = !usingApi();
|
| 81 |
+
if (!needModel) setRow("model", 1, "Using API");
|
| 82 |
+
const all = installed.cx && installed.disk && (installed.model || !needModel);
|
| 83 |
+
if (!all) status("offline", "warn", "Not installed");
|
| 84 |
+
else if (needModel) status("offline", "ok", "Available offline");
|
| 85 |
+
else status("offline", "warn", "Model via API");
|
| 86 |
+
|
| 87 |
+
if (all && (checks.gpu.ok || !needModel)) start();
|
| 88 |
+
else showSetup(checks.gpu.ok || !needModel);
|
| 89 |
}
|
| 90 |
|
| 91 |
async function environmentChecks() {
|
|
|
|
| 94 |
? { ok: true, text: "Cross-origin isolation" }
|
| 95 |
: { ok: false, text: window.top !== window ? "The embedded view can't run the VM. Open the app in its own tab." : "Cross-origin isolation is off (COOP/COEP headers missing)" };
|
| 96 |
c.sw = "serviceWorker" in navigator ? { ok: true, text: "Offline storage" } : { ok: false, text: "Offline storage unavailable (private window?)" };
|
| 97 |
+
if (usingApi()) c.gpu = { ok: true, text: `Model runs through an API (${apiHost()})` };
|
| 98 |
+
else if (MODEL_DEVICE !== "webgpu") c.gpu = { ok: true, warn: true, text: `Model runs on ${MODEL_DEVICE} (slow; for testing)` };
|
| 99 |
else if (!navigator.gpu) c.gpu = { ok: false, text: "WebGPU unavailable. Use desktop Chrome or Edge." };
|
| 100 |
else {
|
| 101 |
try {
|
|
|
|
| 132 |
|
| 133 |
function showSetup(canInstall) {
|
| 134 |
$("#setup").hidden = false;
|
| 135 |
+
$("#mobile-banner").hidden = !(isMobile() && !usingApi());
|
| 136 |
+
$("#setup-api").textContent = usingApi() ? `Using ${settings.api.model} via ${apiHost()} · Change` : "Use an API model instead";
|
| 137 |
+
if (usingApi()) {
|
| 138 |
+
$(".c-name", $('[data-row="model"]')).textContent = settings.api.model;
|
| 139 |
+
$(".c-desc", $('[data-row="model"]')).textContent = `Runs through ${apiHost()}, nothing to download`;
|
| 140 |
+
$("#model-size").textContent = "";
|
| 141 |
+
}
|
| 142 |
const btn = $("#install");
|
| 143 |
btn.disabled = !canInstall || !navigator.onLine;
|
| 144 |
if (!navigator.onLine) $("#setup-note").textContent = "You're offline. Connect once to install; after that it works without internet.";
|
|
|
|
| 164 |
diskManifest = await setup.downloadDisk((d, t) => setRow("disk", d / t, `${Math.round((d / t) * 100)}%`));
|
| 165 |
setRow("disk", 1, "Installed");
|
| 166 |
})();
|
| 167 |
+
const modelTask = usingApi() ? Promise.resolve() : loadModel((f, text) => setRow("model", f, text)).then(
|
| 168 |
+
() => setRow("model", 1, "Installed"),
|
| 169 |
+
(err) => { console.error(err); modelError = err; setRow("model", 0, "Failed"); }, // shown once the app opens
|
| 170 |
+
);
|
| 171 |
await Promise.all([cxTask, diskTask, modelTask]);
|
| 172 |
+
if (usingApi()) status("offline", "warn", "Model via API");
|
| 173 |
+
else status("offline", modelError ? "warn" : "ok", modelError ? "Model not installed" : "Available offline");
|
| 174 |
start();
|
| 175 |
} catch (err) {
|
| 176 |
console.error(err);
|
|
|
|
| 183 |
|
| 184 |
// Aggregates transformers.js per-file progress into one number.
|
| 185 |
function loadModel(onProgress) {
|
| 186 |
+
if (llm.remote) {
|
| 187 |
+
return llm.load().then(() => status("model", "ok", "API ready"), (err) => { status("model", "bad", "API not set up"); throw err; });
|
| 188 |
+
}
|
| 189 |
const files = new Map();
|
| 190 |
llm.onProgress = (p) => {
|
| 191 |
if (!p.file) return;
|
|
|
|
| 250 |
}
|
| 251 |
setComposerEnabled();
|
| 252 |
};
|
| 253 |
+
if (isMobile() && !usingApi() && !llm.ready && !modelError) showMobileWarning();
|
| 254 |
+
if (memoryConstrained() && !usingApi()) {
|
|
|
|
|
|
|
|
|
|
| 255 |
// Upload the weights to the GPU before Linux takes its share of memory: on phones
|
| 256 |
// the two together at peak are what makes the browser kill the GPU process.
|
| 257 |
status("vm", "busy", "Waiting for the model");
|
|
|
|
| 265 |
|
| 266 |
// Phones, tablets and machines reporting under 8 GB of RAM (Chrome caps deviceMemory at 8).
|
| 267 |
function memoryConstrained() {
|
| 268 |
+
return isMobile() || (navigator.deviceMemory ?? 8) < 8;
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
// Loads the current backend unless it is ready or already failed. Never rejects: a
|
| 272 |
+
// local-model failure is shown as a callout with the API option.
|
| 273 |
+
function loadModelOnce() {
|
| 274 |
+
if (llm.ready) return Promise.resolve();
|
| 275 |
+
if (modelError) { showModelFailure(modelError); return Promise.resolve(); }
|
| 276 |
+
const mine = llm;
|
| 277 |
+
return loadModel().catch((err) => {
|
| 278 |
+
if (mine !== llm) return; // replaced (e.g. switched to an API model) while loading
|
| 279 |
+
console.error(err);
|
| 280 |
+
if (mine.remote) addNotice("The API model isn't set up: " + err.message, "error");
|
| 281 |
+
else { modelError = err; showModelFailure(err); }
|
| 282 |
+
}).finally(setComposerEnabled);
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
function friendlyModelError(err) {
|
| 286 |
+
const m = String(err?.message ?? err);
|
| 287 |
+
if (/Instance reference|device (was |is )?lost|DeviceLost|out of memory|OOM|allocat|Failed to create a WebGPU|OrtRun|createBuffer|mapAsync|Array buffer/i.test(m)) {
|
| 288 |
+
return "Your device ran out of graphics memory while loading the model. This is common on phones and on computers with little RAM.";
|
| 289 |
+
}
|
| 290 |
+
if (/WebGPU is not available|shader-f16|No WebGPU|WebGPU/i.test(m)) return "This browser can't run the local model because it lacks the WebGPU support the model needs.";
|
| 291 |
+
if (/fetch|network|download|Failed to load|Incomplete/i.test(m)) return "The model files couldn't be downloaded. Check your internet connection.";
|
| 292 |
+
return "The local model hit an error while loading.";
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
function callout(kind, title, text, actions, details) {
|
| 296 |
+
$("#empty")?.remove();
|
| 297 |
+
const el = h("div", { class: `callout ${kind}`, "data-callout": "model" },
|
| 298 |
+
h("div", { class: "callout-title" }, icon("alert"), h("span", {}, title)),
|
| 299 |
+
h("p", {}, text),
|
| 300 |
+
h("div", { class: "callout-actions" }, actions),
|
| 301 |
+
details ? h("details", { class: "callout-details" }, h("summary", {}, "Technical details"), h("pre", {}, details)) : null);
|
| 302 |
+
thread().append(el);
|
| 303 |
+
scrollChat(true);
|
| 304 |
+
return el;
|
| 305 |
+
}
|
| 306 |
+
const clearModelCallouts = () => document.querySelectorAll('[data-callout="model"]').forEach((el) => el.remove());
|
| 307 |
+
|
| 308 |
+
function showModelFailure(err) {
|
| 309 |
+
status("model", "bad", "Model failed");
|
| 310 |
+
clearModelCallouts();
|
| 311 |
+
const el = callout("error", "The model couldn't load",
|
| 312 |
+
`${friendlyModelError(err)} Linux is still running on this device. You can connect an API model instead and the agent will keep using this machine.`,
|
| 313 |
+
[
|
| 314 |
+
h("button", { class: "btn primary small", type: "button", onclick: () => openApiDialog() }, "Use an API model"),
|
| 315 |
+
h("button", { class: "btn small", type: "button", onclick: () => { el.remove(); retryLocalModel(); } }, "Try again"),
|
| 316 |
+
],
|
| 317 |
+
String(err?.message ?? err));
|
| 318 |
+
setComposerEnabled();
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
function showMobileWarning() {
|
| 322 |
+
callout("warn", "You're on a phone or tablet",
|
| 323 |
+
"The local model needs about 1.4 GB of graphics memory, which most phones can't give a browser tab, so it will probably fail to load. Trying anyway. To skip the wait, use an API model: only the model moves to the provider, Linux keeps running here.",
|
| 324 |
+
[h("button", { class: "btn primary small", type: "button", onclick: () => openApiDialog() }, "Use an API model")]);
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
function retryLocalModel() {
|
| 328 |
+
modelError = null;
|
| 329 |
+
llm.dispose?.();
|
| 330 |
+
llm = new LLM();
|
| 331 |
+
if (agent) agent.llm = llm;
|
| 332 |
+
setComposerEnabled();
|
| 333 |
+
loadModelOnce();
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
function setBackendLabels() {
|
| 337 |
+
$("#model-name").textContent = usingApi() ? settings.api.model : MODEL_ID.split("/")[1].replace("-ONNX", "");
|
| 338 |
+
$("#gpu-name").textContent = usingApi() ? "API" : MODEL_DEVICE === "webgpu" ? "WebGPU" : MODEL_DEVICE;
|
| 339 |
}
|
| 340 |
|
| 341 |
// ---------- conversation rendering ----------
|
|
|
|
| 482 |
$("#send").hidden = running;
|
| 483 |
$("#stop").hidden = !running;
|
| 484 |
$("#send").disabled = !ready;
|
| 485 |
+
$("#prompt").placeholder = ready ? "Describe a task for the agent"
|
| 486 |
+
: !llm.ready ? (modelError ? "No model loaded. Use an API model or try again." : "Loading the model…")
|
| 487 |
+
: "Starting Linux…";
|
| 488 |
}
|
| 489 |
|
| 490 |
async function send(text) {
|
|
|
|
| 622 |
|
| 623 |
const dlg = $("#settings");
|
| 624 |
$("#open-settings").addEventListener("click", () => {
|
| 625 |
+
$("#set-model-desc").textContent = usingApi() ? `${settings.api.model} via ${apiHost()}` : "LFM3-1.7B on this device (WebGPU)";
|
| 626 |
$("#set-thinking").checked = settings.thinking;
|
| 627 |
$("#set-confirm").checked = settings.confirmCommands;
|
| 628 |
$("#set-steps").value = settings.maxSteps;
|
|
|
|
| 638 |
syncToggles();
|
| 639 |
});
|
| 640 |
dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); }); // click on backdrop
|
| 641 |
+
$("#set-model").addEventListener("click", () => { dlg.close(); openApiDialog(); });
|
| 642 |
+
|
| 643 |
+
// ---------- API model dialog ----------
|
| 644 |
+
const apiDlg = $("#api-dlg");
|
| 645 |
+
$("#api-preset").replaceChildren(...API_PRESETS.map((p) => h("option", { value: p.id }, p.label)));
|
| 646 |
+
$("#api-preset").addEventListener("change", () => {
|
| 647 |
+
const p = API_PRESETS.find((x) => x.id === $("#api-preset").value);
|
| 648 |
+
if (p?.baseUrl) $("#api-base").value = p.baseUrl;
|
| 649 |
+
else { $("#api-base").value = ""; $("#api-base").focus(); }
|
| 650 |
+
});
|
| 651 |
+
const apiForm = () => ({
|
| 652 |
+
preset: $("#api-preset").value,
|
| 653 |
+
baseUrl: $("#api-base").value.trim(),
|
| 654 |
+
model: $("#api-model").value.trim(),
|
| 655 |
+
key: $("#api-key").value.trim(),
|
| 656 |
+
});
|
| 657 |
+
const apiNote = (text, kind = "") => { const n = $("#api-note"); n.className = "note " + kind; n.textContent = text; };
|
| 658 |
+
|
| 659 |
+
function openApiDialog() {
|
| 660 |
+
const a = settings.api ?? {};
|
| 661 |
+
$("#api-preset").value = a.preset ?? API_PRESETS[0].id;
|
| 662 |
+
$("#api-base").value = a.baseUrl ?? API_PRESETS[0].baseUrl;
|
| 663 |
+
$("#api-model").value = a.model ?? "";
|
| 664 |
+
$("#api-key").value = loadApiKey();
|
| 665 |
+
$("#api-remember").checked = apiKeyRemembered();
|
| 666 |
+
$("#api-local").hidden = !usingApi();
|
| 667 |
+
apiNote("");
|
| 668 |
+
apiDlg.showModal();
|
| 669 |
+
}
|
| 670 |
+
|
| 671 |
+
$("#api-close").addEventListener("click", () => apiDlg.close());
|
| 672 |
+
apiDlg.addEventListener("click", (e) => { if (e.target === apiDlg) apiDlg.close(); });
|
| 673 |
+
|
| 674 |
+
$("#api-test").addEventListener("click", async () => {
|
| 675 |
+
const f = apiForm();
|
| 676 |
+
if (!f.baseUrl || !f.model) return apiNote("Enter a base URL and a model ID first.", "error");
|
| 677 |
+
const btn = $("#api-test");
|
| 678 |
+
btn.disabled = true;
|
| 679 |
+
apiNote("Testing…");
|
| 680 |
+
try {
|
| 681 |
+
const reply = await RemoteLLM.test(f);
|
| 682 |
+
apiNote(`Works. The model replied: "${reply.slice(0, 80)}"`, "ok");
|
| 683 |
+
} catch (err) { apiNote(err.message, "error"); }
|
| 684 |
+
finally { btn.disabled = false; }
|
| 685 |
+
});
|
| 686 |
+
|
| 687 |
+
$("#api-form").addEventListener("submit", async (e) => {
|
| 688 |
+
e.preventDefault();
|
| 689 |
+
const f = apiForm();
|
| 690 |
+
if (!f.baseUrl || !f.model) return apiNote("Enter a base URL and a model ID.", "error");
|
| 691 |
+
if (agent?.running) return apiNote("Stop the agent before switching models.", "error");
|
| 692 |
+
try { new URL(f.baseUrl); } catch { return apiNote("The base URL isn't a valid URL.", "error"); }
|
| 693 |
+
settings.backend = "api";
|
| 694 |
+
settings.api = { preset: f.preset, baseUrl: f.baseUrl, model: f.model };
|
| 695 |
+
saveSettings();
|
| 696 |
+
saveApiKey(f.key, $("#api-remember").checked);
|
| 697 |
+
apiDlg.close();
|
| 698 |
+
if (!$("#setup").hidden) return location.reload(); // re-run setup without the local model
|
| 699 |
+
const old = llm;
|
| 700 |
+
llm = new RemoteLLM(apiConfig());
|
| 701 |
+
old.dispose?.(); // frees the local model's GPU memory
|
| 702 |
+
modelError = null;
|
| 703 |
+
if (agent) agent.llm = llm;
|
| 704 |
+
clearModelCallouts();
|
| 705 |
+
setBackendLabels();
|
| 706 |
+
status("offline", "warn", "Model via API");
|
| 707 |
+
await loadModelOnce();
|
| 708 |
+
addNotice(`Now using ${f.model} through ${apiHost()}. Linux still runs on this device.`);
|
| 709 |
+
});
|
| 710 |
+
|
| 711 |
+
$("#api-local").addEventListener("click", () => {
|
| 712 |
+
if (agent?.running) return apiNote("Stop the agent before switching models.", "error");
|
| 713 |
+
settings.backend = "local";
|
| 714 |
+
saveSettings();
|
| 715 |
+
location.reload();
|
| 716 |
+
});
|
| 717 |
+
$("#setup-api").addEventListener("click", () => openApiDialog());
|
| 718 |
$("#reset-vm").addEventListener("click", async () => {
|
| 719 |
if (!confirm("Erase all files and changes made inside the Linux machine? The page will reload.")) return;
|
| 720 |
if (vm.overlayName) await setup.resetVmStorage(vm.overlayName);
|
js/remote-llm.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Remote model backend: any OpenAI-compatible Chat Completions API (OpenAI, OpenRouter,
|
| 2 |
+
// the Hugging Face router, Groq, a local Ollama/LM Studio server, ...). Used when the
|
| 3 |
+
// local model can't run on this device. The Linux machine still runs in the tab.
|
| 4 |
+
//
|
| 5 |
+
// It has the same interface as LLM (llm.js), so the agent loop is unchanged: the agent's
|
| 6 |
+
// history (LFM3 text format) is translated into API messages with native tool calls, and
|
| 7 |
+
// the streamed reply is rendered back into that text format for the agent to parse.
|
| 8 |
+
import { parseAssistant } from "./toolcalls.js";
|
| 9 |
+
|
| 10 |
+
export const API_PRESETS = [
|
| 11 |
+
{ id: "openrouter", label: "OpenRouter", baseUrl: "https://openrouter.ai/api/v1" },
|
| 12 |
+
{ id: "openai", label: "OpenAI", baseUrl: "https://api.openai.com/v1" },
|
| 13 |
+
{ id: "huggingface", label: "Hugging Face", baseUrl: "https://router.huggingface.co/v1" },
|
| 14 |
+
{ id: "custom", label: "Other (OpenAI-compatible)", baseUrl: "" },
|
| 15 |
+
];
|
| 16 |
+
|
| 17 |
+
const KEY_STORE = "lwa-api-key";
|
| 18 |
+
|
| 19 |
+
export function loadApiKey() {
|
| 20 |
+
try { return localStorage.getItem(KEY_STORE) ?? sessionStorage.getItem(KEY_STORE) ?? ""; } catch { return ""; }
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
/** remember=true keeps the key on this device; otherwise only until the tab is closed. */
|
| 24 |
+
export function saveApiKey(key, remember) {
|
| 25 |
+
try {
|
| 26 |
+
localStorage.removeItem(KEY_STORE);
|
| 27 |
+
sessionStorage.removeItem(KEY_STORE);
|
| 28 |
+
if (key) (remember ? localStorage : sessionStorage).setItem(KEY_STORE, key);
|
| 29 |
+
} catch {}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
export const apiKeyRemembered = () => { try { return localStorage.getItem(KEY_STORE) != null; } catch { return false; } };
|
| 33 |
+
|
| 34 |
+
const endpoint = (baseUrl) => baseUrl.replace(/\/+$/, "").replace(/\/chat\/completions$/, "") + "/chat/completions";
|
| 35 |
+
|
| 36 |
+
function headersFor(key) {
|
| 37 |
+
const h = { "Content-Type": "application/json" };
|
| 38 |
+
if (key) h.Authorization = `Bearer ${key}`;
|
| 39 |
+
return h;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
async function httpError(res) {
|
| 43 |
+
let detail = "";
|
| 44 |
+
try {
|
| 45 |
+
const body = await res.text();
|
| 46 |
+
try { const j = JSON.parse(body); detail = j.error?.message ?? j.message ?? j.error ?? body; } catch { detail = body; }
|
| 47 |
+
} catch {}
|
| 48 |
+
detail = String(detail).slice(0, 300);
|
| 49 |
+
const hint = res.status === 401 || res.status === 403 ? "The provider rejected the API key."
|
| 50 |
+
: res.status === 404 ? "Endpoint or model not found. Check the base URL and model ID."
|
| 51 |
+
: res.status === 429 ? "Rate limited or out of credits."
|
| 52 |
+
: res.status === 400 ? "The provider rejected the request (does this model support tool calling?)."
|
| 53 |
+
: `The provider returned HTTP ${res.status}.`;
|
| 54 |
+
return new Error(detail ? `${hint} ${detail}` : hint);
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
function networkError(baseUrl, err) {
|
| 58 |
+
let host = baseUrl;
|
| 59 |
+
try { host = new URL(baseUrl).host; } catch {}
|
| 60 |
+
return new Error(`Couldn't reach ${host}. Check the URL and your internet connection. The provider must also allow requests from web pages (CORS). (${err.message})`);
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
// ---------- history translation ----------
|
| 64 |
+
|
| 65 |
+
const argValue = (v) => (typeof v === "string" ? v : JSON.stringify(v));
|
| 66 |
+
|
| 67 |
+
/** One API tool call rendered in the LFM3 format that toolcalls.js parses. */
|
| 68 |
+
function renderCall(name, rawArgs, final) {
|
| 69 |
+
let args = null;
|
| 70 |
+
try { args = rawArgs.trim() ? JSON.parse(rawArgs) : {}; } catch {}
|
| 71 |
+
if (args && typeof args === "object" && !Array.isArray(args)) {
|
| 72 |
+
const params = Object.entries(args).map(([k, v]) => `<parameter=${k}>\n${argValue(v)}\n</parameter>\n`).join("");
|
| 73 |
+
return `<tool_call>\n<function=${name}>\n${params}</function>\n</tool_call>`;
|
| 74 |
+
}
|
| 75 |
+
// Arguments still streaming (incomplete JSON): show the call as being prepared.
|
| 76 |
+
if (!final) return `<tool_call>\n<function=${name}>\n`;
|
| 77 |
+
// Invalid JSON at the end: run it with no arguments so the agent reports the problem.
|
| 78 |
+
return `<tool_call>\n<function=${name}>\n</function>\n</tool_call>`;
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
/** Agent history (LFM3 text format) -> Chat Completions messages with native tool calls. */
|
| 82 |
+
export function toApiMessages(messages) {
|
| 83 |
+
const out = [];
|
| 84 |
+
let pending = []; // tool_call ids still waiting for a result
|
| 85 |
+
let n = 0;
|
| 86 |
+
const flush = () => {
|
| 87 |
+
for (const id of pending) out.push({ role: "tool", tool_call_id: id, content: "(not run)" });
|
| 88 |
+
pending = [];
|
| 89 |
+
};
|
| 90 |
+
for (const m of messages) {
|
| 91 |
+
if (m.role === "assistant") {
|
| 92 |
+
flush();
|
| 93 |
+
const p = parseAssistant(m.content, { thinkingOpen: false });
|
| 94 |
+
const calls = p.calls.map((c) => ({
|
| 95 |
+
id: `call_${++n}`,
|
| 96 |
+
type: "function",
|
| 97 |
+
function: { name: c.name, arguments: JSON.stringify(c.arguments) },
|
| 98 |
+
}));
|
| 99 |
+
const msg = { role: "assistant", content: p.content || (calls.length ? null : "(no reply)") };
|
| 100 |
+
if (calls.length) msg.tool_calls = calls;
|
| 101 |
+
out.push(msg);
|
| 102 |
+
pending = calls.map((c) => c.id);
|
| 103 |
+
} else if (m.role === "tool") {
|
| 104 |
+
const id = pending.shift();
|
| 105 |
+
out.push(id ? { role: "tool", tool_call_id: id, content: m.content } : { role: "user", content: `Tool result:\n${m.content}` });
|
| 106 |
+
} else {
|
| 107 |
+
flush();
|
| 108 |
+
out.push({ role: m.role, content: m.content });
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
flush();
|
| 112 |
+
return out;
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// ---------- backend ----------
|
| 116 |
+
|
| 117 |
+
export class RemoteLLM {
|
| 118 |
+
/** config: { baseUrl, model, key } */
|
| 119 |
+
constructor(config) {
|
| 120 |
+
this.config = config;
|
| 121 |
+
this.ready = false;
|
| 122 |
+
this.remote = true;
|
| 123 |
+
this.onProgress = null;
|
| 124 |
+
this.onStatus = null;
|
| 125 |
+
this.onGpu = null;
|
| 126 |
+
this.ctrl = null;
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
get label() { return this.config.model; }
|
| 130 |
+
|
| 131 |
+
async load() {
|
| 132 |
+
if (!this.config.baseUrl || !this.config.model) throw new Error("Set the API base URL and model first.");
|
| 133 |
+
this.ready = true;
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
stop() { this.ctrl?.abort(); }
|
| 137 |
+
resetCache() {}
|
| 138 |
+
dispose() { this.stop(); }
|
| 139 |
+
|
| 140 |
+
/** Sends a tiny request to check the URL, key and model. Resolves with the reply text. */
|
| 141 |
+
static async test(config) {
|
| 142 |
+
let res;
|
| 143 |
+
try {
|
| 144 |
+
res = await fetch(endpoint(config.baseUrl), {
|
| 145 |
+
method: "POST",
|
| 146 |
+
headers: headersFor(config.key),
|
| 147 |
+
body: JSON.stringify({ model: config.model, messages: [{ role: "user", content: "Reply with the word OK." }] }),
|
| 148 |
+
});
|
| 149 |
+
} catch (err) { throw networkError(config.baseUrl, err); }
|
| 150 |
+
if (!res.ok) throw await httpError(res);
|
| 151 |
+
const j = await res.json().catch(() => null);
|
| 152 |
+
const msg = j?.choices?.[0]?.message;
|
| 153 |
+
if (!msg) throw new Error("The reply wasn't in the OpenAI Chat Completions format.");
|
| 154 |
+
return String(msg.content ?? "").trim() || "(empty reply)";
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
async generate(messages, tools, options = {}, onEvent = null) {
|
| 158 |
+
const { baseUrl, model, key } = this.config;
|
| 159 |
+
const ctrl = new AbortController();
|
| 160 |
+
this.ctrl = ctrl;
|
| 161 |
+
const t0 = performance.now();
|
| 162 |
+
let tFirst = 0;
|
| 163 |
+
let reasoning = "";
|
| 164 |
+
let content = "";
|
| 165 |
+
const calls = []; // { name, args } by stream index
|
| 166 |
+
let finish = null;
|
| 167 |
+
let usage = null;
|
| 168 |
+
let stopped = false;
|
| 169 |
+
|
| 170 |
+
const render = (final = false) => {
|
| 171 |
+
let r = reasoning;
|
| 172 |
+
let c = content;
|
| 173 |
+
// Some models put their reasoning inside <think> tags in the content.
|
| 174 |
+
const m = c.match(/^\s*<think>([\s\S]*?)(<\/think>|$)/);
|
| 175 |
+
if (m) { r += m[1]; c = c.slice(m[0].length); }
|
| 176 |
+
let s = r + "</think>" + c;
|
| 177 |
+
for (const call of calls) if (call?.name) s += renderCall(call.name, call.args, final);
|
| 178 |
+
return s;
|
| 179 |
+
};
|
| 180 |
+
|
| 181 |
+
const absorb = (delta) => {
|
| 182 |
+
if (!tFirst) tFirst = performance.now();
|
| 183 |
+
reasoning += delta.reasoning_content ?? delta.reasoning ?? "";
|
| 184 |
+
content += delta.content ?? "";
|
| 185 |
+
for (const tc of delta.tool_calls ?? []) {
|
| 186 |
+
const i = tc.index ?? calls.length;
|
| 187 |
+
calls[i] ??= { name: "", args: "" };
|
| 188 |
+
if (tc.function?.name) calls[i].name += tc.function.name;
|
| 189 |
+
if (tc.function?.arguments) calls[i].args += typeof tc.function.arguments === "string" ? tc.function.arguments : JSON.stringify(tc.function.arguments);
|
| 190 |
+
}
|
| 191 |
+
};
|
| 192 |
+
|
| 193 |
+
try {
|
| 194 |
+
let res;
|
| 195 |
+
try {
|
| 196 |
+
res = await fetch(endpoint(baseUrl), {
|
| 197 |
+
method: "POST",
|
| 198 |
+
headers: headersFor(key),
|
| 199 |
+
body: JSON.stringify({ model, messages: toApiMessages(messages), tools, tool_choice: "auto", stream: true }),
|
| 200 |
+
signal: ctrl.signal,
|
| 201 |
+
});
|
| 202 |
+
} catch (err) {
|
| 203 |
+
if (err.name === "AbortError") throw err;
|
| 204 |
+
throw networkError(baseUrl, err);
|
| 205 |
+
}
|
| 206 |
+
if (!res.ok) throw await httpError(res);
|
| 207 |
+
|
| 208 |
+
if (!(res.headers.get("Content-Type") ?? "").includes("text/event-stream")) {
|
| 209 |
+
// Provider ignored stream:true and sent one JSON reply.
|
| 210 |
+
const j = await res.json();
|
| 211 |
+
if (j.error) throw new Error(j.error.message ?? JSON.stringify(j.error));
|
| 212 |
+
const ch = j.choices?.[0];
|
| 213 |
+
if (ch?.message) absorb(ch.message);
|
| 214 |
+
finish = ch?.finish_reason ?? null;
|
| 215 |
+
usage = j.usage ?? null;
|
| 216 |
+
} else {
|
| 217 |
+
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
| 218 |
+
let buf = "";
|
| 219 |
+
for (;;) {
|
| 220 |
+
const { done, value } = await reader.read();
|
| 221 |
+
if (done) break;
|
| 222 |
+
buf += value;
|
| 223 |
+
let nl;
|
| 224 |
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
| 225 |
+
const line = buf.slice(0, nl).trim();
|
| 226 |
+
buf = buf.slice(nl + 1);
|
| 227 |
+
if (!line.startsWith("data:")) continue;
|
| 228 |
+
const data = line.slice(5).trim();
|
| 229 |
+
if (!data || data === "[DONE]") continue;
|
| 230 |
+
let j;
|
| 231 |
+
try { j = JSON.parse(data); } catch { continue; }
|
| 232 |
+
if (j.error) throw new Error(j.error.message ?? JSON.stringify(j.error));
|
| 233 |
+
if (j.usage) usage = j.usage;
|
| 234 |
+
const ch = j.choices?.[0];
|
| 235 |
+
if (!ch) continue;
|
| 236 |
+
if (ch.delta) absorb(ch.delta);
|
| 237 |
+
if (ch.finish_reason) finish = ch.finish_reason;
|
| 238 |
+
onEvent?.({ type: "replace", text: render() });
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
}
|
| 242 |
+
} catch (err) {
|
| 243 |
+
if (err.name !== "AbortError") throw err;
|
| 244 |
+
stopped = true;
|
| 245 |
+
} finally {
|
| 246 |
+
if (this.ctrl === ctrl) this.ctrl = null;
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
const text = render(true);
|
| 250 |
+
onEvent?.({ type: "replace", text });
|
| 251 |
+
const end = performance.now();
|
| 252 |
+
const promptChars = messages.reduce((n, m) => n + (m.content?.length ?? 0), 0);
|
| 253 |
+
return {
|
| 254 |
+
text,
|
| 255 |
+
stopped,
|
| 256 |
+
hitLimit: finish === "length",
|
| 257 |
+
thinkingCut: null,
|
| 258 |
+
promptTokens: usage?.prompt_tokens ?? Math.ceil(promptChars / 3.5),
|
| 259 |
+
genTokens: usage?.completion_tokens ?? Math.ceil((reasoning.length + content.length) / 3.5),
|
| 260 |
+
reused: 0,
|
| 261 |
+
newPrefill: 0,
|
| 262 |
+
prefillMs: tFirst ? tFirst - t0 : end - t0,
|
| 263 |
+
genMs: tFirst ? end - tFirst : 0,
|
| 264 |
+
};
|
| 265 |
+
}
|
| 266 |
+
}
|
sw.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
| 6 |
// (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
|
| 7 |
// 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
|
| 8 |
// CheerpX and multi-threaded WASM need, even when a host forgets to send them.
|
| 9 |
-
const SHELL_VERSION = "lwa-shell-0.
|
| 10 |
const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
|
| 11 |
const CX_CACHE_PREFIX = "lwa-cheerpx-";
|
| 12 |
const DISK_CACHE = "lwa-disk";
|
|
@@ -18,7 +18,7 @@ const chunkKey = (i) => SCOPE + "__vm__/chunk/" + i;
|
|
| 18 |
const SHELL_FILES = [
|
| 19 |
"./", "index.html", "css/app.css", "icon.svg",
|
| 20 |
"js/config.js", "js/config-defaults.js", "js/main.js", "js/setup.js", "js/vm.js", "js/agent.js", "js/llm.js",
|
| 21 |
-
"js/llm-worker.js", "js/llm-engine.js", "js/lazy-weights.js", "js/prompts.js", "js/toolcalls.js", "js/markdown.js", "js/files.js",
|
| 22 |
"vendor/transformers.min.js", "vendor/highlight.min.js",
|
| 23 |
"vendor/ort/ort-wasm-simd-threaded.asyncify.mjs", "vendor/ort/ort-wasm-simd-threaded.asyncify.wasm",
|
| 24 |
"vendor/xterm/xterm.mjs", "vendor/xterm/xterm.css", "vendor/xterm/addon-fit.mjs",
|
|
|
|
| 6 |
// (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
|
| 7 |
// 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
|
| 8 |
// CheerpX and multi-threaded WASM need, even when a host forgets to send them.
|
| 9 |
+
const SHELL_VERSION = "lwa-shell-0.4.0";
|
| 10 |
const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
|
| 11 |
const CX_CACHE_PREFIX = "lwa-cheerpx-";
|
| 12 |
const DISK_CACHE = "lwa-disk";
|
|
|
|
| 18 |
const SHELL_FILES = [
|
| 19 |
"./", "index.html", "css/app.css", "icon.svg",
|
| 20 |
"js/config.js", "js/config-defaults.js", "js/main.js", "js/setup.js", "js/vm.js", "js/agent.js", "js/llm.js",
|
| 21 |
+
"js/llm-worker.js", "js/llm-engine.js", "js/lazy-weights.js", "js/remote-llm.js", "js/prompts.js", "js/toolcalls.js", "js/markdown.js", "js/files.js",
|
| 22 |
"vendor/transformers.min.js", "vendor/highlight.min.js",
|
| 23 |
"vendor/ort/ort-wasm-simd-threaded.asyncify.mjs", "vendor/ort/ort-wasm-simd-threaded.asyncify.wasm",
|
| 24 |
"vendor/xterm/xterm.mjs", "vendor/xterm/xterm.css", "vendor/xterm/addon-fit.mjs",
|