drAIML / bonsai.js
Gregory-L's picture
Professor Codephreak
drAIML agreement opens inside huggingface.co; rewards in LUV only
0aee05c verified
Raw History Blame Contribute Delete
10.7 kB
// 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 the drAIML 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 engine, shared by the bridge (Python) and the donation panel ─────────────────────────────────────────────
/** Donate compute to drAIML.dmind: lends the engine Bonsai already loaded (so it starts after the drAIML agreement). */
export const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy,
(text, state) => { const c = document.getElementById("dmind-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state === "sharing" ? "ready" : "busy"; });
export { mod as engineModule };
let ensuring = null;
/** Load Bonsai, after the drAIML agreement when this browser has not agreed or holds no copy. Resolves to what bankML
* verified, or null when the visitor declines. One load at a time. */
export function ensureEngine(onProgress = () => {}) {
ensuring ||= ensureOnce(onProgress).finally(() => { ensuring = null; });
return ensuring;
}
async function ensureOnce(onProgress) {
const b = await mod();
if (b.isReady()) return { model: b.MODEL.title, threads: b.loadStats && b.loadStats.threads };
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); onProgress(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 e = donor.engineOptions(); // the visitor's GPU choice (off unless they turned it on)
try {
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, ...e });
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 };
} finally {
document.getElementById("bonsai-agreement").close();
}
}
/** Start the engine again with new options (the GPU share): waits for the answer being written, if any. */
export async function reloadEngine(onProgress = () => {}) {
const b = await mod();
for (let i = 0; i < 600 && (b.isBusy() || visitorBusy); i++) await new Promise((r) => setTimeout(r, 500));
const wasOn = donor.running;
if (wasOn) donor.stop();
if (b.isReady()) b.unload();
const info = await ensureEngine(onProgress);
if (info && wasOn) donor.settings({ on: true });
return info;
}
// ── the bridge ────────────────────────────────────────────────────────────────────────────────────────────────────
// Python asks over a MessagePort handed to Streamlit's own worker. Inside huggingface.co's frame the browser partitions
// BroadcastChannel (the worker and this page land in different partitions), so the channel stays only as a fallback.
let handler = null;
/** Call before stlite mounts: watches the workers this page starts and answers a "draiml:hello" with a port. */
export function captureWorkers(pageId) {
const Native = window.Worker;
if (!Native || Native.__draiml) return;
class Watched extends Native {
constructor(...args) {
super(...args);
this.addEventListener("message", (ev) => {
const d = ev.data;
if (!d || d.type !== "draiml:hello" || d.page !== pageId) return;
const mc = new MessageChannel();
mc.port1.onmessage = (e) => handler && handler(e.data || {}, (msg) => mc.port1.postMessage(msg));
this.postMessage({ type: "draiml:bridge", page: pageId }, [mc.port2]);
});
}
}
Watched.__draiml = true;
window.Worker = Watched;
}
export function startBridge(pageId, { signin } = {}) {
const ch = new BroadcastChannel(CHANNEL);
ch.onmessage = (ev) => {
const m = ev.data || {};
if (m.to !== "page:" + pageId) return;
handler(m, (msg) => ch.postMessage(msg));
};
handler = async (m, send) => {
const { id, type } = m;
const reply = (rid, msg) => send({ ...msg, id: rid, to: "py:" + pageId });
const ensure = (rid) => ensureEngine((text, frac) => reply(rid, { type: "progress", text, frac }));
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") {
const info = await ensure(id);
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 && !(await ensure(id))) { 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 === "open_donate") {
window.dispatchEvent(new CustomEvent("draiml:donate"));
reply(id, { type: "done" });
} 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) });
}
};
}