// SPDX-License-Identifier: MIT // drAIML · Bonsai in this browser. The page side of draiml/bonsai.py: it owns the browseML engine (bankML compiled to // WebAssembly, browseml/ — MIT OR Apache-2.0) and drAIML's Agreement. Python (Streamlit, in a Web Worker on this // origin) asks over a BroadcastChannel; nothing here talks to any server except the model's own download. const CHANNEL = "draiml-bonsai"; const AGREE_KEY = "draiml-bonsai-agreement"; const AGREEMENT_VERSION = 1; import { Donor } from "./dmind.js"; let engine = null; // the browseml.js module, imported on first use let visitorBusy = false; // the visitor's own question is being answered: lending waits const mod = async () => (engine ||= await import("./browseml/browseml.js")); const agreed = () => { try { const a = JSON.parse(localStorage.getItem(AGREE_KEY) || "null"); return !!a && a.v === AGREEMENT_VERSION; } catch { return false; } }; const remember = () => { try { localStorage.setItem(AGREE_KEY, JSON.stringify({ v: AGREEMENT_VERSION, at: new Date().toISOString() })); } catch {} }; async function sha256hex(text) { const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join(""); } const mb = (n) => (n / 1048576).toFixed(0); // ── the Agreement ───────────────────────────────────────────────────────────────────────────────────────────────── function agreement(cachedAlready) { return new Promise((resolve) => { const dlg = document.getElementById("bonsai-agreement"); const go = dlg.querySelector("[data-agree]"); const no = dlg.querySelector("[data-decline]"); go.textContent = cachedAlready ? "I agree — start Bonsai" : "I agree — download 248 MB and start"; dlg.querySelector("[data-progress]").hidden = true; go.disabled = false; no.disabled = false; const done = (yes) => { go.onclick = no.onclick = dlg.oncancel = null; resolve(yes); }; go.onclick = () => { remember(); done(true); }; no.onclick = () => { dlg.close(); done(false); }; dlg.oncancel = () => done(false); dlg.showModal(); go.focus(); }); } function showProgress(text, frac) { const dlg = document.getElementById("bonsai-agreement"); const box = dlg.querySelector("[data-progress]"); box.hidden = false; box.querySelector("span").textContent = text; const bar = box.querySelector("i"); bar.style.width = frac == null ? "100%" : `${Math.round(frac * 100)}%`; dlg.querySelector("[data-agree]").disabled = true; chip(text); } function chip(text, state = "busy") { const c = document.getElementById("bonsai-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state; } // ── the bridge ──────────────────────────────────────────────────────────────────────────────────────────────────── export function startBridge(pageId, { signin } = {}) { const ch = new BroadcastChannel(CHANNEL); const reply = (id, msg) => ch.postMessage({ ...msg, id, to: "py:" + pageId }); let ensuring = null; // donate compute to drAIML.dmind: lends the engine Bonsai already loaded, so it starts after the Agreement const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy); async function ensure(id) { const b = await mod(); if (b.isReady()) return { model: b.MODEL.title }; const cachedAlready = await b.isCached(); if (!(agreed() && cachedAlready)) { if (!(await agreement(cachedAlready))) return null; } else { document.getElementById("bonsai-agreement").showModal(); } const say = (text, frac) => { showProgress(text, frac); reply(id, { type: "progress", text, frac }); }; say(cachedAlready ? "Opening Bonsai from this browser…" : "Downloading Bonsai…", 0); // half the cores (at most 4): Streamlit's own Python worker shares this tab, and all cores at once // crashed a 4-core, 6 GB laptop while the engine opened const threads = Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 2) / 2))); const info = await b.load((got, total, phase) => { if (phase === "download") say(`Downloading Bonsai · ${mb(got)} of ${mb(total)} MB`, got / total); else if (phase === "retry") say(`Connection cut at ${mb(got)} MB · resuming…`, got / total); else if (phase === "cache") say("Bonsai found in this browser", 1); else if (phase === "verify") say("Checking the model against its sha256 pin and starting bankML…", null); }, () => {}, { threads }); document.getElementById("bonsai-agreement").close(); chip("Bonsai · ready in this browser", "ready"); if (donor.ledger.on && !donor.running) donor.start(); // a donation pledged earlier resumes with the engine return { model: b.MODEL.title, sha256: info.sha256, threads: info.threads }; } ch.onmessage = async (ev) => { const m = ev.data || {}; if (m.to !== "page:" + pageId) return; const { id, type } = m; try { if (type === "status") { const b = await mod(); // importing the module is small: the engine and the model load only on ensure reply(id, { type: "status", agreed: agreed(), loaded: b.isReady(), loading: b.isLoading(), cached: await b.isCached() }); } else if (type === "ensure") { ensuring ||= ensure(id).finally(() => { ensuring = null; }); const info = await ensuring; reply(id, info ? { type: "ready", info } : { type: "declined" }); } else if (type === "chat") { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded yet"); let text = ""; visitorBusy = true; const result = await b.chat({ messages: m.messages, max_tokens: m.max_tokens || 700, temperature: m.temperature ?? 0.3, repeat_penalty: m.repeat_penalty ?? 1.1 }, (piece) => { text += piece; reply(id, { type: "piece", text: piece }); }).finally(() => { visitorBusy = false; }); const rc = result && result.bankml_receipt; const ok = !!rc && (await sha256hex(text)) === rc.response_sha256; const t = (result && result.timings) || {}; const speed = t.predicted_per_second ? ` · ${t.predicted_per_second.toFixed(1)} tok/s` : ""; reply(id, { type: "done", verdict: rc ? `${ok ? "✓" : "✗"} bankML receipt · answer sha256 ${ok ? "matches" : "does NOT match"}${speed}` : "no receipt" }); } else if (type === "donate") { if (m.on) { ensuring ||= ensure(id).finally(() => { ensuring = null; }); if (!(await ensuring)) { reply(id, { type: "status", ...(await donor.status()), declined: true }); return; } } donor.settings({ on: m.on, pct: m.pct, wallet: m.wallet }); await new Promise((r) => setTimeout(r, 300)); reply(id, { type: "status", ...(await donor.status()) }); } else if (type === "donate_status") { reply(id, { type: "status", ...(await donor.status()) }); } else if (type === "signin") { if (signin) signin(); } else if (type === "forget") { const b = await mod(); try { b.exit(); } catch {} await b.forget(); try { localStorage.removeItem(AGREE_KEY); } catch {} chip(""); reply(id, { type: "done" }); } } catch (e) { const dlg = document.getElementById("bonsai-agreement"); if (dlg.open && type === "ensure") dlg.close(); chip(""); reply(id, { type: "error", message: String((e && e.message) || e) }); } }; }