Help save lives: donate compute to drAIML.dmind (10% default duty cycle), LUV rewards at 1 wei per token valued in BANKON PAI/SATPAY/BTC/GLDB; 'Allow drAIML to solve this for you'
Browse files- README.md +4 -0
- app/draiml/bonsai.py +26 -0
- app/manifest.json +1 -1
- app/views/consult.py +50 -1
- bonsai.js +18 -1
- dmind-host.json +6 -0
- dmind.js +187 -0
README.md
CHANGED
|
@@ -55,6 +55,10 @@ your consultation is stored.
|
|
| 55 |
- **Bonsai in your browser.** Accept drAIML's Agreement once and prism-ml's Bonsai-1.7B (1-bit, Apache-2.0)
|
| 56 |
is downloaded (248 MB, sha256-pinned) and run by the [browseML](https://github.com/browseML/browseML)
|
| 57 |
WebAssembly engine on your own computer: free, private, no account, no key. Every answer carries a bankML receipt.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
- **Open evidence.** 43k passages from openly licensed health datasets
|
| 59 |
([PYTHAI/drAIML-evidence](https://huggingface.co/datasets/PYTHAI/drAIML-evidence)), cited inline.
|
| 60 |
- **Many models.** Every open chat model live on HF Inference Providers (sign in with Hugging Face; your own
|
|
|
|
| 55 |
- **Bonsai in your browser.** Accept drAIML's Agreement once and prism-ml's Bonsai-1.7B (1-bit, Apache-2.0)
|
| 56 |
is downloaded (248 MB, sha256-pinned) and run by the [browseML](https://github.com/browseML/browseML)
|
| 57 |
WebAssembly engine on your own computer: free, private, no account, no key. Every answer carries a bankML receipt.
|
| 58 |
+
- **Help save lives.** A toggle lends a share of your computer (10% by default) to drAIML.dmind, the distributed mind,
|
| 59 |
+
through the same in-browser engine. Rewards: SHAMBA LUV, 1 wei per generated token, measured to 18 decimals
|
| 60 |
+
(SCIEN·TIFIC) and valued in BANKON PAI (1 PAI = 1 USDC), SATPAY, BTC and GLDB. It waits while you ask, in a hidden
|
| 61 |
+
tab and on battery.
|
| 62 |
- **Open evidence.** 43k passages from openly licensed health datasets
|
| 63 |
([PYTHAI/drAIML-evidence](https://huggingface.co/datasets/PYTHAI/drAIML-evidence)), cited inline.
|
| 64 |
- **Many models.** Every open chat model live on HF Inference Providers (sign in with Hugging Face; your own
|
app/draiml/bonsai.py
CHANGED
|
@@ -144,6 +144,32 @@ async def stream(messages: list[dict], *, max_tokens: int = 700,
|
|
| 144 |
_queues.pop(rid, None)
|
| 145 |
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
def request_signin() -> None:
|
| 148 |
"""Ask the page to start Sign in with Hugging Face (the page leaves for the OAuth screen)."""
|
| 149 |
if available():
|
|
|
|
| 144 |
_queues.pop(rid, None)
|
| 145 |
|
| 146 |
|
| 147 |
+
async def donate(on: bool, pct: int = 10, wallet: str = "") -> dict:
|
| 148 |
+
"""Turn lending to drAIML.dmind on or off (on opens the Agreement first if Bonsai is not loaded)."""
|
| 149 |
+
rid, q = _start("donate", on=on, pct=pct, wallet=wallet)
|
| 150 |
+
try:
|
| 151 |
+
while True:
|
| 152 |
+
m = await _next(q, 1800)
|
| 153 |
+
if m.get("type") == "status":
|
| 154 |
+
return m
|
| 155 |
+
if m.get("type") == "error":
|
| 156 |
+
raise BonsaiError(m.get("message", "donation could not change"))
|
| 157 |
+
finally:
|
| 158 |
+
_queues.pop(rid, None)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
async def donate_status() -> dict:
|
| 162 |
+
if not available():
|
| 163 |
+
return {}
|
| 164 |
+
rid, q = _start("donate_status")
|
| 165 |
+
try:
|
| 166 |
+
return await _next(q, 20)
|
| 167 |
+
except BonsaiError:
|
| 168 |
+
return {}
|
| 169 |
+
finally:
|
| 170 |
+
_queues.pop(rid, None)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
def request_signin() -> None:
|
| 174 |
"""Ask the page to start Sign in with Hugging Face (the page leaves for the OAuth screen)."""
|
| 175 |
if available():
|
app/manifest.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
{
|
| 2 |
-
"build": "
|
| 3 |
"requirements": [],
|
| 4 |
"files": [
|
| 5 |
"app.py",
|
|
|
|
| 1 |
{
|
| 2 |
+
"build": "c1cc1254551a",
|
| 3 |
"requirements": [],
|
| 4 |
"files": [
|
| 5 |
"app.py",
|
app/views/consult.py
CHANGED
|
@@ -84,6 +84,55 @@ with st.sidebar:
|
|
| 84 |
if ss.engine == "custom":
|
| 85 |
st.caption(ep.key_help)
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
ss.second_on = st.toggle("Second opinion (compare two models)", ss.second_on and ss.engine != "bonsai",
|
| 88 |
disabled=ss.engine == "bonsai",
|
| 89 |
help="Not with Bonsai: one model runs in this browser at a time." if ss.engine == "bonsai" else None)
|
|
@@ -151,7 +200,7 @@ def _choose_signin() -> None:
|
|
| 151 |
|
| 152 |
def consult_offer(question: str, key: str) -> None:
|
| 153 |
"""Under an evidence-only answer: the two ways to a model, as buttons that act at once."""
|
| 154 |
-
st.markdown("**
|
| 155 |
c1, c2 = st.columns(2)
|
| 156 |
if bonsai.available():
|
| 157 |
c1.button("🌱 Run Bonsai in this browser", key=f"offer_bonsai_{key}", type="primary", use_container_width=True,
|
|
|
|
| 84 |
if ss.engine == "custom":
|
| 85 |
st.caption(ep.key_help)
|
| 86 |
|
| 87 |
+
if bonsai.available():
|
| 88 |
+
st.subheader("❤️ Help save lives")
|
| 89 |
+
ds = await bonsai.donate_status() # noqa: F704
|
| 90 |
+
if ss.pop("don_reset", False): # the Agreement was declined: the toggle goes back off
|
| 91 |
+
ss.don_on = False
|
| 92 |
+
ss.setdefault("don_on", bool(ds.get("on")))
|
| 93 |
+
ss.setdefault("don_pct", int(ds.get("pct") or 10))
|
| 94 |
+
ss.setdefault("don_wallet", ds.get("wallet") or "")
|
| 95 |
+
st.toggle(f"Donate compute to {ds.get('host', 'drAIML.dmind')}", key="don_on",
|
| 96 |
+
help="Lend a share of this computer's CPU, RAM and GPU to drAIML's distributed mind. It runs "
|
| 97 |
+
"only while this tab is open and visible, waits while you ask, and on a laptop waits for the "
|
| 98 |
+
"charger. Needs Bonsai in this browser (the Agreement opens first).")
|
| 99 |
+
st.slider("Share of this computer", 5, 50, step=5, key="don_pct", format="%d%%",
|
| 100 |
+
help="10% means: after each job, rest nine times as long as it took.")
|
| 101 |
+
st.text_input("LUV wallet for rewards (0x…)", key="don_wallet", placeholder="0x… (Ethereum)")
|
| 102 |
+
wallet_ok = not ss.don_wallet or (ss.don_wallet.startswith("0x") and len(ss.don_wallet) == 42)
|
| 103 |
+
if not wallet_ok:
|
| 104 |
+
st.warning("That doesn't look like an Ethereum address (0x + 40 hex characters).")
|
| 105 |
+
want = (ss.don_on, ss.don_pct, ss.don_wallet if wallet_ok else ds.get("wallet", ""))
|
| 106 |
+
have = (bool(ds.get("on")), int(ds.get("pct") or 10), ds.get("wallet") or "")
|
| 107 |
+
if want != have:
|
| 108 |
+
with st.spinner("Updating your donation…"):
|
| 109 |
+
try:
|
| 110 |
+
ds = await bonsai.donate(*want) # noqa: F704
|
| 111 |
+
except bonsai.BonsaiError as e:
|
| 112 |
+
st.error(f"Donation unchanged: {e}")
|
| 113 |
+
if ds.get("declined"):
|
| 114 |
+
ss.don_reset = True
|
| 115 |
+
ss.don_declined = True
|
| 116 |
+
st.rerun()
|
| 117 |
+
if ss.pop("don_declined", False):
|
| 118 |
+
st.info("Donating needs Bonsai in this browser: accept the Agreement to start.")
|
| 119 |
+
if ds.get("on") or int(ds.get("jobs") or 0):
|
| 120 |
+
if ds.get("note"):
|
| 121 |
+
st.caption(f"{'🟢' if ds.get('state') == 'sharing' else '⏸️'} {ds['note']}")
|
| 122 |
+
st.markdown(f"**{ds.get('luv', '0')} LUV** earned · {ds.get('jobs', 0)} jobs · "
|
| 123 |
+
f"{ds.get('tokens', '0')} tokens · {ds.get('engine_s', 0)} s of thinking")
|
| 124 |
+
w = ds.get("worth") or {}
|
| 125 |
+
if "error" in w:
|
| 126 |
+
st.caption(f"Prices unavailable: {w['error']}")
|
| 127 |
+
elif w:
|
| 128 |
+
with st.expander("What it is worth (SCIEN·TIFIC, 18 decimals)"):
|
| 129 |
+
for unit, label in (("PAI", "BANKON PAI (1 = 1 USDC)"), ("SATPAY", "BANKON SATPAY (1 = 1 sat)"),
|
| 130 |
+
("BTC", "BTC"), ("GLDB", "gld.basket GLDB")):
|
| 131 |
+
st.markdown(f"`{w[unit]['exact']}` {label} · ≈ {w[unit]['sci']}")
|
| 132 |
+
st.caption(f"1 LUV = {w['LUV_USD']['sci']} USD from Uniswap reserves at block {ds.get('block')}; "
|
| 133 |
+
"BTC and gold from DeFiLlama. LUV paid: 1 wei per generated token. BANKON PAI, "
|
| 134 |
+
"SATPAY and GLDB are not deployed: units of account only.")
|
| 135 |
+
|
| 136 |
ss.second_on = st.toggle("Second opinion (compare two models)", ss.second_on and ss.engine != "bonsai",
|
| 137 |
disabled=ss.engine == "bonsai",
|
| 138 |
help="Not with Bonsai: one model runs in this browser at a time." if ss.engine == "bonsai" else None)
|
|
|
|
| 200 |
|
| 201 |
def consult_offer(question: str, key: str) -> None:
|
| 202 |
"""Under an evidence-only answer: the two ways to a model, as buttons that act at once."""
|
| 203 |
+
st.markdown("**Allow drAIML to solve this for you:**")
|
| 204 |
c1, c2 = st.columns(2)
|
| 205 |
if bonsai.available():
|
| 206 |
c1.button("🌱 Run Bonsai in this browser", key=f"offer_bonsai_{key}", type="primary", use_container_width=True,
|
bonsai.js
CHANGED
|
@@ -7,7 +7,10 @@ const CHANNEL = "draiml-bonsai";
|
|
| 7 |
const AGREE_KEY = "draiml-bonsai-agreement";
|
| 8 |
const AGREEMENT_VERSION = 1;
|
| 9 |
|
|
|
|
|
|
|
| 10 |
let engine = null; // the browseml.js module, imported on first use
|
|
|
|
| 11 |
const mod = async () => (engine ||= await import("./browseml/browseml.js"));
|
| 12 |
|
| 13 |
const agreed = () => {
|
|
@@ -64,6 +67,8 @@ export function startBridge(pageId, { signin } = {}) {
|
|
| 64 |
const ch = new BroadcastChannel(CHANNEL);
|
| 65 |
const reply = (id, msg) => ch.postMessage({ ...msg, id, to: "py:" + pageId });
|
| 66 |
let ensuring = null;
|
|
|
|
|
|
|
| 67 |
|
| 68 |
async function ensure(id) {
|
| 69 |
const b = await mod();
|
|
@@ -87,6 +92,7 @@ export function startBridge(pageId, { signin } = {}) {
|
|
| 87 |
}, () => {}, { threads });
|
| 88 |
document.getElementById("bonsai-agreement").close();
|
| 89 |
chip("Bonsai · ready in this browser", "ready");
|
|
|
|
| 90 |
return { model: b.MODEL.title, sha256: info.sha256, threads: info.threads };
|
| 91 |
}
|
| 92 |
|
|
@@ -106,13 +112,24 @@ export function startBridge(pageId, { signin } = {}) {
|
|
| 106 |
const b = await mod();
|
| 107 |
if (!b.isReady()) throw new Error("Bonsai is not loaded yet");
|
| 108 |
let text = "";
|
|
|
|
| 109 |
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 },
|
| 110 |
-
(piece) => { text += piece; reply(id, { type: "piece", text: piece }); });
|
| 111 |
const rc = result && result.bankml_receipt;
|
| 112 |
const ok = !!rc && (await sha256hex(text)) === rc.response_sha256;
|
| 113 |
const t = (result && result.timings) || {};
|
| 114 |
const speed = t.predicted_per_second ? ` · ${t.predicted_per_second.toFixed(1)} tok/s` : "";
|
| 115 |
reply(id, { type: "done", verdict: rc ? `${ok ? "✓" : "✗"} bankML receipt · answer sha256 ${ok ? "matches" : "does NOT match"}${speed}` : "no receipt" });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
} else if (type === "signin") {
|
| 117 |
if (signin) signin();
|
| 118 |
} else if (type === "forget") {
|
|
|
|
| 7 |
const AGREE_KEY = "draiml-bonsai-agreement";
|
| 8 |
const AGREEMENT_VERSION = 1;
|
| 9 |
|
| 10 |
+
import { Donor } from "./dmind.js";
|
| 11 |
+
|
| 12 |
let engine = null; // the browseml.js module, imported on first use
|
| 13 |
+
let visitorBusy = false; // the visitor's own question is being answered: lending waits
|
| 14 |
const mod = async () => (engine ||= await import("./browseml/browseml.js"));
|
| 15 |
|
| 16 |
const agreed = () => {
|
|
|
|
| 67 |
const ch = new BroadcastChannel(CHANNEL);
|
| 68 |
const reply = (id, msg) => ch.postMessage({ ...msg, id, to: "py:" + pageId });
|
| 69 |
let ensuring = null;
|
| 70 |
+
// donate compute to drAIML.dmind: lends the engine Bonsai already loaded, so it starts after the Agreement
|
| 71 |
+
const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy);
|
| 72 |
|
| 73 |
async function ensure(id) {
|
| 74 |
const b = await mod();
|
|
|
|
| 92 |
}, () => {}, { threads });
|
| 93 |
document.getElementById("bonsai-agreement").close();
|
| 94 |
chip("Bonsai · ready in this browser", "ready");
|
| 95 |
+
if (donor.ledger.on && !donor.running) donor.start(); // a donation pledged earlier resumes with the engine
|
| 96 |
return { model: b.MODEL.title, sha256: info.sha256, threads: info.threads };
|
| 97 |
}
|
| 98 |
|
|
|
|
| 112 |
const b = await mod();
|
| 113 |
if (!b.isReady()) throw new Error("Bonsai is not loaded yet");
|
| 114 |
let text = "";
|
| 115 |
+
visitorBusy = true;
|
| 116 |
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 },
|
| 117 |
+
(piece) => { text += piece; reply(id, { type: "piece", text: piece }); }).finally(() => { visitorBusy = false; });
|
| 118 |
const rc = result && result.bankml_receipt;
|
| 119 |
const ok = !!rc && (await sha256hex(text)) === rc.response_sha256;
|
| 120 |
const t = (result && result.timings) || {};
|
| 121 |
const speed = t.predicted_per_second ? ` · ${t.predicted_per_second.toFixed(1)} tok/s` : "";
|
| 122 |
reply(id, { type: "done", verdict: rc ? `${ok ? "✓" : "✗"} bankML receipt · answer sha256 ${ok ? "matches" : "does NOT match"}${speed}` : "no receipt" });
|
| 123 |
+
} else if (type === "donate") {
|
| 124 |
+
if (m.on) {
|
| 125 |
+
ensuring ||= ensure(id).finally(() => { ensuring = null; });
|
| 126 |
+
if (!(await ensuring)) { reply(id, { type: "status", ...(await donor.status()), declined: true }); return; }
|
| 127 |
+
}
|
| 128 |
+
donor.settings({ on: m.on, pct: m.pct, wallet: m.wallet });
|
| 129 |
+
await new Promise((r) => setTimeout(r, 300));
|
| 130 |
+
reply(id, { type: "status", ...(await donor.status()) });
|
| 131 |
+
} else if (type === "donate_status") {
|
| 132 |
+
reply(id, { type: "status", ...(await donor.status()) });
|
| 133 |
} else if (type === "signin") {
|
| 134 |
if (signin) signin();
|
| 135 |
} else if (type === "forget") {
|
dmind-host.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"label": "drAIML.dmind",
|
| 3 |
+
"url": "",
|
| 4 |
+
"token_key": "",
|
| 5 |
+
"note": "The dmind host drAIML lends compute to. Empty url: not open yet; donors' pledges are kept in their browsers and sharing starts when a url is set here (it needs /sharedcpu/* routes and CORS for https://pythai-draiml.static.hf.space)."
|
| 6 |
+
}
|
dmind.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// SPDX-License-Identifier: MIT
|
| 2 |
+
// drAIML · donate compute to drAIML.dmind. With the visitor's say-so (a toggle, 10% by default), this tab lends a
|
| 3 |
+
// share of its CPU, RAM and GPU to a distributed.mind host: the host hands it thinking jobs (chat completions), the
|
| 4 |
+
// browseML engine already loaded for Bonsai runs them exactly as sent, and its bankML receipt goes back with the
|
| 5 |
+
// answer. The share is a duty cycle — after a job that held the engine t ms the tab rests t·(100−p)/p ms — and the
|
| 6 |
+
// visitor always comes first: a question of theirs, a hidden tab or a battery not charging pauses the lending.
|
| 7 |
+
//
|
| 8 |
+
// The wire protocol is dmind's, as browseML's share module speaks it (github.com/browseML/browseML, MIT):
|
| 9 |
+
// POST /sharedcpu/join · /update (heartbeat) · /pull (long-poll) · /result · /decline · /leave.
|
| 10 |
+
// Reward: SHAMBA LUV, 1 wei per generated token (dmind's paymint), measured to 18 decimals (SCIEN·TIFIC), and
|
| 11 |
+
// priced in BANKON units: PAI (1 PAI = 1 USDC), SATPAY (1 satoshi), BTC, and GLDB (gld.basket's troy-ounce unit).
|
| 12 |
+
// BANKON tokens are not deployed: here they are units of account only.
|
| 13 |
+
|
| 14 |
+
const STORE = "draiml-dmind";
|
| 15 |
+
const SCALE = 10n ** 18n;
|
| 16 |
+
export const LUV = { token: "0x2711111111683B8708cb9a48cBf36a51315F8254", pair: "0x57D2085Aa859a145cB107845AD03c0eAAFBD8a31", tokenIs0: true };
|
| 17 |
+
const USDC_WETH = "0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc"; // token0 USDC (6), token1 WETH (18)
|
| 18 |
+
const RPC = "https://ethereum-rpc.publicnode.com";
|
| 19 |
+
const LLAMA = "https://coins.llama.fi/prices/current/coingecko:bitcoin,coingecko:pax-gold";
|
| 20 |
+
const GLDB_OZ = "0.000241833"; // troy ounces per GLDB at gld.basket's genesis reading
|
| 21 |
+
const WEI_PER_TOKEN = 1n;
|
| 22 |
+
const MODEL_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"; // browseml/browseML/*.FORK.json // dmind paymint: 1 wei of LUV per generated token
|
| 23 |
+
|
| 24 |
+
// ── 18-decimal arithmetic (SCIEN·TIFIC) ──────────────────────────────────────────────────────────────────────────
|
| 25 |
+
export const format18 = (x) => { const neg = x < 0n; if (neg) x = -x; return `${neg ? "-" : ""}${x / SCALE}.${(x % SCALE).toString().padStart(18, "0")}`; };
|
| 26 |
+
export function parse18(s) {
|
| 27 |
+
const m = /^(\d+)(?:\.(\d{1,18}))?/.exec(String(s).trim());
|
| 28 |
+
return m ? BigInt(m[1]) * SCALE + BigInt(((m[2] || "") + "0".repeat(18)).slice(0, 18)) : 0n;
|
| 29 |
+
}
|
| 30 |
+
/** a small 18-decimal amount in scientific notation as well, since 18 places round it to zero */
|
| 31 |
+
const sci = (x18) => (x18 === 0n ? "0" : (Number(x18) / 1e18).toExponential(3));
|
| 32 |
+
|
| 33 |
+
// ── the ledger, kept in this browser ─────────────────────────────────────────────────────────────────────────────
|
| 34 |
+
function readLedger() {
|
| 35 |
+
try { const l = JSON.parse(localStorage.getItem(STORE) || "{}"); return { tokens: BigInt(l.tokens || 0), jobs: l.jobs || 0, engineMs: l.engineMs || 0, wallet: l.wallet || "", pct: l.pct || 10, on: !!l.on }; }
|
| 36 |
+
catch { return { tokens: 0n, jobs: 0, engineMs: 0, wallet: "", pct: 10, on: false }; }
|
| 37 |
+
}
|
| 38 |
+
function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }
|
| 39 |
+
|
| 40 |
+
// ── prices ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
| 41 |
+
async function rpc(method, params) {
|
| 42 |
+
const r = await fetch(RPC, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) });
|
| 43 |
+
const j = await r.json(); if (!j.result) throw new Error((j.error && j.error.message) || "no result"); return j.result;
|
| 44 |
+
}
|
| 45 |
+
async function reserves(pair, block) {
|
| 46 |
+
const out = await rpc("eth_call", [{ to: pair, data: "0x0902f1ac" }, block]); // getReserves()
|
| 47 |
+
return [BigInt("0x" + out.slice(2, 66)), BigInt("0x" + out.slice(66, 130))];
|
| 48 |
+
}
|
| 49 |
+
let priceCache = null;
|
| 50 |
+
/** USD per LUV (18 decimals) from the Uniswap reserves at one block, as luv.oracle prices it; BTC and gold from
|
| 51 |
+
* DeFiLlama. Cached for 5 minutes. */
|
| 52 |
+
export async function prices() {
|
| 53 |
+
if (priceCache && Date.now() - priceCache.at < 300000) return priceCache;
|
| 54 |
+
const block = await rpc("eth_blockNumber", []);
|
| 55 |
+
const [[l0, l1], [u0, u1]] = await Promise.all([reserves(LUV.pair, block), reserves(USDC_WETH, block)]);
|
| 56 |
+
const [luv, weth] = LUV.tokenIs0 ? [l0, l1] : [l1, l0];
|
| 57 |
+
const usdPerEth18 = u0 * 10n ** 12n * SCALE / u1;
|
| 58 |
+
const luvUsd18 = weth * usdPerEth18 / luv;
|
| 59 |
+
let btcUsd18 = 0n, xauUsd18 = 0n;
|
| 60 |
+
try {
|
| 61 |
+
const c = (await (await fetch(LLAMA)).json()).coins || {};
|
| 62 |
+
btcUsd18 = parse18(String(c["coingecko:bitcoin"]?.price ?? 0));
|
| 63 |
+
xauUsd18 = parse18(String(c["coingecko:pax-gold"]?.price ?? 0));
|
| 64 |
+
} catch {}
|
| 65 |
+
priceCache = { at: Date.now(), block: BigInt(block).toString(), luvUsd18, btcUsd18, xauUsd18 };
|
| 66 |
+
return priceCache;
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
/** What the LUV earned is worth, every amount an 18-decimal integer. */
|
| 70 |
+
export function valuation(luvWei, p) {
|
| 71 |
+
const usd = luvWei * p.luvUsd18 / SCALE; // PAI (= USDC), 18 decimals
|
| 72 |
+
const btc = p.btcUsd18 ? usd * SCALE / p.btcUsd18 : 0n;
|
| 73 |
+
const sat = btc * 100000000n; // SATPAY (1 satoshi), 18 decimals
|
| 74 |
+
const gldbUsd18 = p.xauUsd18 * parse18(GLDB_OZ) / SCALE;
|
| 75 |
+
const gldb = gldbUsd18 ? usd * SCALE / gldbUsd18 : 0n;
|
| 76 |
+
return { PAI: usd, BTC: btc, SATPAY: sat, GLDB: gldb };
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// ── the sharing loop ─────────────────────────────────────────────────────────────────────────────────────────────
|
| 80 |
+
async function sha256hex(t) {
|
| 81 |
+
return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t)))].map((b) => b.toString(16).padStart(2, "0")).join("");
|
| 82 |
+
}
|
| 83 |
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
| 84 |
+
export const restMs = (engineMs, pct) => Math.round(engineMs * (100 - pct) / pct);
|
| 85 |
+
|
| 86 |
+
export class Donor {
|
| 87 |
+
constructor(engine, isVisitorBusy) {
|
| 88 |
+
this.engine = engine; // () => Promise<browseml module>, loaded (the Agreement was accepted)
|
| 89 |
+
this.busy = isVisitorBusy; // () => boolean: the visitor's own question is running
|
| 90 |
+
this.ledger = readLedger();
|
| 91 |
+
this.host = null; this.session = ""; this.running = false; this.state = "off"; this.note = ""; this.wake = null;
|
| 92 |
+
}
|
| 93 |
+
async config() {
|
| 94 |
+
if (this.host) return this.host;
|
| 95 |
+
try { this.host = await (await fetch(new URL("./dmind-host.json", import.meta.url), { cache: "no-cache" })).json(); }
|
| 96 |
+
catch { this.host = { label: "drAIML.dmind", url: "" }; }
|
| 97 |
+
return this.host;
|
| 98 |
+
}
|
| 99 |
+
async call(path, body, keepalive = false) {
|
| 100 |
+
const h = this.host, token = h.token_key ? (localStorage.getItem(h.token_key) || "") : "";
|
| 101 |
+
const r = await fetch(h.url.replace(/\/$/, "") + path, { method: "POST", credentials: "omit", keepalive,
|
| 102 |
+
headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify(body) });
|
| 103 |
+
if (r.status === 401 || r.status === 403) throw Object.assign(new Error("the host asks you to sign in to share"), { final: true });
|
| 104 |
+
return r.json();
|
| 105 |
+
}
|
| 106 |
+
settings({ on, pct, wallet }) {
|
| 107 |
+
if (pct) this.ledger.pct = Math.max(5, Math.min(50, Math.round(pct / 5) * 5));
|
| 108 |
+
if (wallet !== undefined) this.ledger.wallet = /^0x[0-9a-fA-F]{40}$/.test(wallet) ? wallet : "";
|
| 109 |
+
this.ledger.on = !!on; writeLedger(this.ledger);
|
| 110 |
+
if (on && !this.running) this.start(); else if (!on && this.running) this.stop();
|
| 111 |
+
if (this.session) this.call("/sharedcpu/update", { session: this.session, share_pct: this.ledger.pct }).catch(() => {});
|
| 112 |
+
if (this.wake) this.wake();
|
| 113 |
+
}
|
| 114 |
+
pauseReason() {
|
| 115 |
+
if (document.hidden) return "this tab is hidden";
|
| 116 |
+
if (this.busy()) return "your own question comes first";
|
| 117 |
+
if (this.battery && !this.battery.charging) return "on battery — sharing waits for the charger";
|
| 118 |
+
return "";
|
| 119 |
+
}
|
| 120 |
+
async rest(ms) { await Promise.race([sleep(ms), new Promise((r) => { this.wake = r; })]); this.wake = null; }
|
| 121 |
+
async start() {
|
| 122 |
+
this.running = true;
|
| 123 |
+
try { this.battery = navigator.getBattery ? await navigator.getBattery() : null; } catch { this.battery = null; }
|
| 124 |
+
const h = await this.config();
|
| 125 |
+
if (!h.url) { this.state = "waiting"; this.note = `${h.label} is not open yet: your pledge of ${this.ledger.pct}% is saved and sharing starts when it opens.`; this.running = false; return; }
|
| 126 |
+
const b = await this.engine();
|
| 127 |
+
let backoff = 0;
|
| 128 |
+
while (this.running) {
|
| 129 |
+
try {
|
| 130 |
+
const why = this.pauseReason();
|
| 131 |
+
if (why) { this.state = "paused"; this.note = why; if (this.session) await this.call("/sharedcpu/update", { session: this.session, paused: true }).catch(() => {}); await this.rest(5000); continue; }
|
| 132 |
+
if (!this.session) {
|
| 133 |
+
const j = await this.call("/sharedcpu/join", { model: b.MODEL.name, model_sha256: MODEL_SHA256, threads: 1,
|
| 134 |
+
share_pct: this.ledger.pct, max_job_tokens: 256, engine: "browseml/draiml", contributor: "browser",
|
| 135 |
+
...(this.ledger.wallet ? { wallet: this.ledger.wallet } : {}) });
|
| 136 |
+
if (!j.ok) throw Object.assign(new Error(`the host refused: ${j.reason || "no reason given"}`), { final: !!j.barred });
|
| 137 |
+
this.session = String(j.session);
|
| 138 |
+
}
|
| 139 |
+
this.state = "sharing"; this.note = `lending ${this.ledger.pct}% to ${h.label}`;
|
| 140 |
+
const got = await this.call("/sharedcpu/pull", { session: this.session });
|
| 141 |
+
if (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });
|
| 142 |
+
if (!got.ok) { if (/session/.test(String(got.reason))) this.session = ""; await this.rest(got.retry_after_s ? got.retry_after_s * 1000 : 5000); continue; }
|
| 143 |
+
const job = got.job; if (!job) continue;
|
| 144 |
+
if (this.busy()) { await this.call("/sharedcpu/decline", { session: this.session, job: job.job, reason: "the visitor is asking" }).catch(() => {}); continue; }
|
| 145 |
+
let cancelled = false;
|
| 146 |
+
const beat = setInterval(() => { this.call("/sharedcpu/update", { session: this.session }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);
|
| 147 |
+
const t0 = performance.now(); let text = "", res;
|
| 148 |
+
try { res = await b.chat({ messages: job.messages, max_tokens: job.max_tokens, temperature: job.temperature }, (p) => { text += p; }); }
|
| 149 |
+
finally { clearInterval(beat); }
|
| 150 |
+
const ms = performance.now() - t0;
|
| 151 |
+
if (cancelled) continue;
|
| 152 |
+
const rc = res && res.bankml_receipt;
|
| 153 |
+
if (!rc || (await sha256hex(text)) !== rc.response_sha256) { await this.call("/sharedcpu/fail", { session: this.session, job: job.job, reason: "receipt did not match" }).catch(() => {}); continue; }
|
| 154 |
+
const r = await this.call("/sharedcpu/result", { session: this.session, job: job.job, text, receipt: rc, usage: res.usage, timings: res.timings });
|
| 155 |
+
if (r.ok) {
|
| 156 |
+
const n = BigInt((res.usage && res.usage.completion_tokens) || 0);
|
| 157 |
+
this.ledger.tokens += n * WEI_PER_TOKEN; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);
|
| 158 |
+
}
|
| 159 |
+
backoff = 0;
|
| 160 |
+
await this.rest(restMs(ms, this.ledger.pct));
|
| 161 |
+
} catch (e) {
|
| 162 |
+
if (e.final) { this.state = "stopped"; this.note = e.message; break; }
|
| 163 |
+
backoff = Math.min(300000, backoff ? backoff * 2 : 5000);
|
| 164 |
+
this.state = "retrying"; this.note = `${e.message || e} · again in ${backoff / 1000} s`;
|
| 165 |
+
await this.rest(backoff);
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
this.running = false;
|
| 169 |
+
}
|
| 170 |
+
stop() {
|
| 171 |
+
this.running = false; this.state = "off"; this.note = "";
|
| 172 |
+
if (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }
|
| 173 |
+
if (this.wake) this.wake();
|
| 174 |
+
}
|
| 175 |
+
async status() {
|
| 176 |
+
const h = await this.config(), l = this.ledger;
|
| 177 |
+
const luvWei = l.tokens; // 1 wei per token
|
| 178 |
+
let worth = null, block = null;
|
| 179 |
+
try { const p = await prices(); const v = valuation(luvWei, p); block = p.block;
|
| 180 |
+
worth = Object.fromEntries(Object.entries(v).map(([k, x]) => [k, { exact: format18(x), sci: sci(x) }]));
|
| 181 |
+
worth.LUV_USD = { exact: format18(p.luvUsd18), sci: sci(p.luvUsd18) };
|
| 182 |
+
} catch (e) { worth = { error: String(e.message || e) }; }
|
| 183 |
+
return { on: l.on, pct: l.pct, wallet: l.wallet, host: h.label, open: !!h.url, state: this.state, note: this.note,
|
| 184 |
+
jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),
|
| 185 |
+
luv: format18(luvWei), luv_wei: luvWei.toString(), worth, block };
|
| 186 |
+
}
|
| 187 |
+
}
|