Gregory-L Professor Codephreak commited on
Commit
0aee05c
·
verified ·
1 Parent(s): 1464612

drAIML agreement opens inside huggingface.co; rewards in LUV only

Browse files

The page now hands Python a MessagePort through Streamlit's worker: huggingface.co's frame partitions BroadcastChannel, so the agreement request never reached the page. BroadcastChannel stays as the fallback.
Rename the dialog to the drAIML agreement. Show rewards in SHAMBA LUV only (no PAI/SATPAY/BTC/GLDB valuation, no price fetches).

Co-Authored-By: Professor Codephreak <codephreak@pythai.net>

README.md CHANGED
@@ -52,13 +52,13 @@ in your browser** ([stlite](https://github.com/whitphx/stlite)). There is no drA
52
  your consultation is stored.
53
 
54
  - **Triage first.** Emergency red flags are checked before any model runs.
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.** The ❤️ Donate panel lets you sign in with login333 · drAIML (one signed message, no gas), choose and
59
  confirm your CPU, RAM and GPU shares, and watch live measurements, earnings and payout requests. It lends a share of your computer (10% by default) to drAIML.dmind, the distributed mind,
60
  through the same in-browser engine. Rewards: SHAMBA LUV, 1 LUV per generated token, measured to 18 decimals
61
- (SCIEN·TIFIC) and valued in BANKON PAI (1 PAI = 1 USDC), SATPAY, BTC and GLDB. It waits while you ask, in a hidden
62
  tab and on battery.
63
  - **WebGPU helper.** For a browser that has WebGPU switched off or finds no card ([webgpu/](webgpu/README.md), live at
64
  `/webgpu/index.html`). It offers three things:
 
52
  your consultation is stored.
53
 
54
  - **Triage first.** Emergency red flags are checked before any model runs.
55
+ - **Bonsai in your browser.** Accept the drAIML 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.** The ❤️ Donate panel lets you sign in with login333 · drAIML (one signed message, no gas), choose and
59
  confirm your CPU, RAM and GPU shares, and watch live measurements, earnings and payout requests. It lends a share of your computer (10% by default) to drAIML.dmind, the distributed mind,
60
  through the same in-browser engine. Rewards: SHAMBA LUV, 1 LUV per generated token, measured to 18 decimals
61
+ (SCIEN·TIFIC), paid in LUV only. It waits while you ask, in a hidden
62
  tab and on battery.
63
  - **WebGPU helper.** For a browser that has WebGPU switched off or finds no card ([webgpu/](webgpu/README.md), live at
64
  `/webgpu/index.html`). It offers three things:
app/draiml/bonsai.py CHANGED
@@ -2,10 +2,11 @@
2
 
3
  The page (index.html + bonsai.js) owns the browseML engine: bankML compiled to WebAssembly, running
4
  prism-ml's Bonsai-1.7B (1-bit, Q1_0, Apache-2.0) on the visitor's own CPU. Before the first download the
5
- page shows drAIML's Agreement; one click downloads the model once (248 MB, checked against its sha256
6
  pin) and keeps it in this browser.
7
 
8
- Streamlit runs in a Web Worker on the same origin, so Python talks to the page over a BroadcastChannel.
 
9
  Every message carries the page's id (DRAIML_PAGE_ID), so two open tabs never answer each other.
10
 
11
  Python -> page: {to, id, type: "status" | "ensure" | "chat" | "stop" | "forget", ...}
@@ -30,7 +31,10 @@ SIZE_MB = 248
30
  _ids = itertools.count(1)
31
  _channel = None
32
  _queues: dict[str, asyncio.Queue] = {}
33
- _proxy = None
 
 
 
34
 
35
 
36
  class BonsaiError(RuntimeError):
@@ -46,41 +50,66 @@ def _page() -> str:
46
  return os.environ.get("DRAIML_PAGE_ID", "")
47
 
48
 
49
- def _open():
50
- global _channel, _proxy
51
- if _channel is not None:
52
- return _channel
53
- from js import BroadcastChannel # type: ignore
54
- from pyodide.ffi import create_proxy # type: ignore
55
-
56
- def on_message(ev):
57
- data = ev.data.to_py() if hasattr(ev.data, "to_py") else ev.data
58
- if not isinstance(data, dict) or data.get("to") != "py:" + _page():
59
- return
60
- q = _queues.get(str(data.get("id")))
61
- if q is not None:
62
- q.put_nowait(data)
63
-
64
- _proxy = create_proxy(on_message)
65
- _channel = BroadcastChannel.new(CHANNEL)
66
- _channel.onmessage = _proxy
67
- return _channel
68
-
69
-
70
- def _post(msg: dict) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  from js import Object # type: ignore
72
  from pyodide.ffi import to_js # type: ignore
73
- _open().postMessage(to_js({**msg, "to": "page:" + _page()}, dict_converter=Object.fromEntries))
 
74
 
75
 
76
- def _start(kind: str, **extra) -> tuple[str, asyncio.Queue]:
77
  if not available():
78
  raise BonsaiError("Bonsai runs only in the browser version of drAIML.")
79
- _open()
80
  rid = f"{kind}-{next(_ids)}"
81
  q: asyncio.Queue = asyncio.Queue()
82
  _queues[rid] = q
83
- _post({"id": rid, "type": kind, **extra})
84
  return rid, q
85
 
86
 
@@ -95,7 +124,7 @@ async def status() -> dict:
95
  """{agreed, cached, loaded, loading} from the page, or {} outside the browser."""
96
  if not available():
97
  return {}
98
- rid, q = _start("status")
99
  try:
100
  return await _next(q, 5)
101
  except BonsaiError:
@@ -105,9 +134,9 @@ async def status() -> dict:
105
 
106
 
107
  async def ensure(on_progress=None) -> dict:
108
- """Load Bonsai, showing the Agreement first when this browser has not agreed or holds no copy.
109
  Returns what bankML verified. Raises BonsaiError if the visitor declines or the load fails."""
110
- rid, q = _start("ensure")
111
  try:
112
  while True:
113
  m = await _next(q, 1800) # a 248 MB download on a slow line
@@ -128,7 +157,7 @@ async def ensure(on_progress=None) -> dict:
128
  async def stream(messages: list[dict], *, max_tokens: int = 700,
129
  temperature: float = 0.3) -> AsyncIterator[tuple[str, str]]:
130
  """Yield ("content", piece) as Bonsai writes, then ("receipt", verdict) once at the end."""
131
- rid, q = _start("chat", messages=messages, max_tokens=max_tokens, temperature=temperature, repeat_penalty=1.1)
132
  try:
133
  while True:
134
  m = await _next(q, 900)
@@ -145,8 +174,8 @@ async def stream(messages: list[dict], *, max_tokens: int = 700,
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)
@@ -161,7 +190,7 @@ async def donate(on: bool, pct: int = 10, wallet: str = "") -> dict:
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:
@@ -173,20 +202,18 @@ async def donate_status() -> dict:
173
  def open_donate() -> None:
174
  """Open the page's donation panel."""
175
  if available():
176
- _open()
177
- _post({"id": f"open-{next(_ids)}", "type": "open_donate"})
178
 
179
 
180
  def request_signin() -> None:
181
  """Ask the page to start Sign in with Hugging Face (the page leaves for the OAuth screen)."""
182
  if available():
183
- _open()
184
- _post({"id": f"signin-{next(_ids)}", "type": "signin"})
185
 
186
 
187
  async def forget() -> None:
188
  """Remove the model from this browser's storage and free the engine."""
189
- rid, q = _start("forget")
190
  try:
191
  await _next(q, 20)
192
  finally:
 
2
 
3
  The page (index.html + bonsai.js) owns the browseML engine: bankML compiled to WebAssembly, running
4
  prism-ml's Bonsai-1.7B (1-bit, Q1_0, Apache-2.0) on the visitor's own CPU. Before the first download the
5
+ page shows the drAIML agreement; one click downloads the model once (248 MB, checked against its sha256
6
  pin) and keeps it in this browser.
7
 
8
+ Streamlit runs in a Web Worker on the same origin. Python asks the page for a MessagePort through that worker
9
+ (huggingface.co's frame partitions BroadcastChannel, so the channel is only the fallback).
10
  Every message carries the page's id (DRAIML_PAGE_ID), so two open tabs never answer each other.
11
 
12
  Python -> page: {to, id, type: "status" | "ensure" | "chat" | "stop" | "forget", ...}
 
31
  _ids = itertools.count(1)
32
  _channel = None
33
  _queues: dict[str, asyncio.Queue] = {}
34
+ _proxies: list = []
35
+ _port = None # the MessagePort the page hands over (see _bridge)
36
+ _bridging: asyncio.Future | None = None
37
+ HELLO_WAIT_S = 3.0
38
 
39
 
40
  class BonsaiError(RuntimeError):
 
50
  return os.environ.get("DRAIML_PAGE_ID", "")
51
 
52
 
53
+ def _on_message(ev) -> None:
54
+ data = ev.data.to_py() if hasattr(ev.data, "to_py") else ev.data
55
+ if not isinstance(data, dict) or data.get("to") != "py:" + _page():
56
+ return
57
+ q = _queues.get(str(data.get("id")))
58
+ if q is not None:
59
+ q.put_nowait(data)
60
+
61
+
62
+ async def _bridge():
63
+ """Reach the page. First choice: a MessagePort the page passes through this worker (works inside huggingface.co's
64
+ frame, where the browser partitions BroadcastChannel). Fallback: the BroadcastChannel, for pages without the port."""
65
+ global _bridging, _channel, _port
66
+ if _bridging is None:
67
+ loop = asyncio.get_running_loop()
68
+ _bridging = loop.create_future()
69
+ import js # type: ignore
70
+ from pyodide.ffi import create_proxy, to_js # type: ignore
71
+
72
+ def on_worker_message(ev):
73
+ d = ev.data.to_py() if hasattr(ev.data, "to_py") else ev.data
74
+ if isinstance(d, dict) and d.get("type") == "draiml:bridge" and d.get("page") == _page() and not _bridging.done():
75
+ port = ev.ports[0]
76
+ p = create_proxy(_on_message)
77
+ _proxies.append(p)
78
+ port.onmessage = p
79
+ _bridging.set_result(port)
80
+
81
+ hp = create_proxy(on_worker_message)
82
+ _proxies.append(hp)
83
+ js.addEventListener("message", hp)
84
+ js.postMessage(to_js({"type": "draiml:hello", "page": _page()}, dict_converter=js.Object.fromEntries))
85
+ try:
86
+ _port = await asyncio.wait_for(asyncio.shield(_bridging), HELLO_WAIT_S)
87
+ except asyncio.TimeoutError:
88
+ _channel = js.BroadcastChannel.new(CHANNEL)
89
+ p = create_proxy(_on_message)
90
+ _proxies.append(p)
91
+ _channel.onmessage = p
92
+ if not _bridging.done():
93
+ _bridging.set_result(None)
94
+ return _port or _channel
95
+ port = await _bridging
96
+ return port or _channel
97
+
98
+
99
+ async def _post(msg: dict) -> None:
100
  from js import Object # type: ignore
101
  from pyodide.ffi import to_js # type: ignore
102
+ target = await _bridge()
103
+ target.postMessage(to_js({**msg, "to": "page:" + _page()}, dict_converter=Object.fromEntries))
104
 
105
 
106
+ async def _start(kind: str, **extra) -> tuple[str, asyncio.Queue]:
107
  if not available():
108
  raise BonsaiError("Bonsai runs only in the browser version of drAIML.")
 
109
  rid = f"{kind}-{next(_ids)}"
110
  q: asyncio.Queue = asyncio.Queue()
111
  _queues[rid] = q
112
+ await _post({"id": rid, "type": kind, **extra})
113
  return rid, q
114
 
115
 
 
124
  """{agreed, cached, loaded, loading} from the page, or {} outside the browser."""
125
  if not available():
126
  return {}
127
+ rid, q = await _start("status")
128
  try:
129
  return await _next(q, 5)
130
  except BonsaiError:
 
134
 
135
 
136
  async def ensure(on_progress=None) -> dict:
137
+ """Load Bonsai, showing the drAIML agreement first when this browser has not agreed or holds no copy.
138
  Returns what bankML verified. Raises BonsaiError if the visitor declines or the load fails."""
139
+ rid, q = await _start("ensure")
140
  try:
141
  while True:
142
  m = await _next(q, 1800) # a 248 MB download on a slow line
 
157
  async def stream(messages: list[dict], *, max_tokens: int = 700,
158
  temperature: float = 0.3) -> AsyncIterator[tuple[str, str]]:
159
  """Yield ("content", piece) as Bonsai writes, then ("receipt", verdict) once at the end."""
160
+ rid, q = await _start("chat", messages=messages, max_tokens=max_tokens, temperature=temperature, repeat_penalty=1.1)
161
  try:
162
  while True:
163
  m = await _next(q, 900)
 
174
 
175
 
176
  async def donate(on: bool, pct: int = 10, wallet: str = "") -> dict:
177
+ """Turn lending to drAIML.dmind on or off (on opens the drAIML agreement first if Bonsai is not loaded)."""
178
+ rid, q = await _start("donate", on=on, pct=pct, wallet=wallet)
179
  try:
180
  while True:
181
  m = await _next(q, 1800)
 
190
  async def donate_status() -> dict:
191
  if not available():
192
  return {}
193
+ rid, q = await _start("donate_status")
194
  try:
195
  return await _next(q, 20)
196
  except BonsaiError:
 
202
  def open_donate() -> None:
203
  """Open the page's donation panel."""
204
  if available():
205
+ asyncio.ensure_future(_post({"id": f"open-{next(_ids)}", "type": "open_donate"}))
 
206
 
207
 
208
  def request_signin() -> None:
209
  """Ask the page to start Sign in with Hugging Face (the page leaves for the OAuth screen)."""
210
  if available():
211
+ asyncio.ensure_future(_post({"id": f"signin-{next(_ids)}", "type": "signin"}))
 
212
 
213
 
214
  async def forget() -> None:
215
  """Remove the model from this browser's storage and free the engine."""
216
+ rid, q = await _start("forget")
217
  try:
218
  await _next(q, 20)
219
  finally:
app/draiml/engines.py CHANGED
@@ -32,7 +32,7 @@ ENDPOINTS: dict[str, Endpoint] = {
32
  "bonsai": Endpoint(
33
  "bonsai", "Bonsai · in this browser (free, private, no key)", "", False, "",
34
  "prism-ml's Bonsai-1.7B (1-bit, Apache-2.0) run by browseML's WebAssembly engine on your own computer. "
35
- "Downloaded once (248 MB) after you accept drAIML's Agreement.",
36
  ("Bonsai-1.7B-Q1_0",)),
37
  "dmind": Endpoint(
38
  "dmind", "drAIML.dmind · donated compute (free, no key)", "https://deltaverse.pythai.net/draiml-dmind/v1",
 
32
  "bonsai": Endpoint(
33
  "bonsai", "Bonsai · in this browser (free, private, no key)", "", False, "",
34
  "prism-ml's Bonsai-1.7B (1-bit, Apache-2.0) run by browseML's WebAssembly engine on your own computer. "
35
+ "Downloaded once (248 MB) after you accept the drAIML agreement.",
36
  ("Bonsai-1.7B-Q1_0",)),
37
  "dmind": Endpoint(
38
  "dmind", "drAIML.dmind · donated compute (free, no key)", "https://deltaverse.pythai.net/draiml-dmind/v1",
app/manifest.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "build": "d9f7947549d9",
3
  "requirements": [],
4
  "files": [
5
  "app.py",
 
1
  {
2
+ "build": "ac88610f1d8a",
3
  "requirements": [],
4
  "files": [
5
  "app.py",
app/views/about.py CHANGED
@@ -20,7 +20,7 @@ on the open Hugging Face ecosystem as a free, open resource for patients and cli
20
  self-care), or **psychotherapy support** (listening, CBT-style self-help, crisis resources first).
21
  4. **Consultation.** Your choice of open model: dozens of hosted engines via HF Inference Providers, or medical
22
  specialists (II-Medical, HuatuoGPT-o1, Baichuan-M2, BioMistral, MediPhi, Meditron-FO…) on your own machine —
23
- or **Bonsai in this browser**: after you accept drAIML's Agreement, prism-ml's Bonsai-1.7B (1-bit, Apache-2.0,
24
  248 MB, sha256-pinned) runs on your own CPU through the [browseML](https://github.com/browseML/browseML)
25
  engine (bankML on WebAssembly). Free, private, no key; each answer carries a bankML receipt.
26
  5. **Hippocratic review.** v1's principle checks — do no harm, beneficence, autonomy, confidentiality — score
 
20
  self-care), or **psychotherapy support** (listening, CBT-style self-help, crisis resources first).
21
  4. **Consultation.** Your choice of open model: dozens of hosted engines via HF Inference Providers, or medical
22
  specialists (II-Medical, HuatuoGPT-o1, Baichuan-M2, BioMistral, MediPhi, Meditron-FO…) on your own machine —
23
+ or **Bonsai in this browser**: after you accept the drAIML agreement, prism-ml's Bonsai-1.7B (1-bit, Apache-2.0,
24
  248 MB, sha256-pinned) runs on your own CPU through the [browseML](https://github.com/browseML/browseML)
25
  engine (bankML on WebAssembly). Free, private, no key; each answer carries a bankML receipt.
26
  5. **Hippocratic review.** v1's principle checks — do no harm, beneficence, autonomy, confidentiality — score
app/views/consult.py CHANGED
@@ -65,11 +65,11 @@ with st.sidebar:
65
  elif bs.get("cached"):
66
  st.info("Kept in this browser: it starts on your first question.", icon="🌱")
67
  else:
68
- st.info(f"Not downloaded yet. drAIML's Agreement opens on your first question ({bonsai.SIZE_MB} MB once).",
69
  icon="🌱")
70
  b1, b2 = st.columns(2)
71
  if not bs.get("loaded") and b1.button("Load now", use_container_width=True,
72
- help="Opens drAIML's Agreement, then loads Bonsai into this browser"):
73
  ss.bonsai_load = True
74
  if (bs.get("cached") or bs.get("loaded")) and b2.button(
75
  "Remove", use_container_width=True, help="Remove Bonsai from this browser"):
@@ -171,7 +171,7 @@ def consult_offer(question: str, key: str) -> None:
171
  if bonsai.available():
172
  c1.button("🌱 Run Bonsai in this browser", key=f"offer_bonsai_{key}", type="primary", use_container_width=True,
173
  on_click=_choose_bonsai, args=(question,),
174
- help="Free, private, no key. Opens drAIML's Agreement; agree and Bonsai starts and answers.")
175
  if state.oauth_available():
176
  c2.button("🤗 Sign in with Hugging Face", key=f"offer_signin_{key}", use_container_width=True,
177
  on_click=_choose_signin, help="Use the hosted models with your own Hugging Face account.")
@@ -272,8 +272,8 @@ async def answer(model: str, prepared, key, base_url) -> dict:
272
 
273
 
274
  async def start_bonsai() -> bool:
275
- """Open drAIML's Agreement in the page (when needed) and load Bonsai into this browser."""
276
- with st.status("Bonsai · waiting for the Agreement (in the page)…", expanded=False) as box:
277
  def progress(text, frac):
278
  box.update(label=f"Bonsai · {text}")
279
  try:
 
65
  elif bs.get("cached"):
66
  st.info("Kept in this browser: it starts on your first question.", icon="🌱")
67
  else:
68
+ st.info(f"Not downloaded yet. the drAIML agreement opens on your first question ({bonsai.SIZE_MB} MB once).",
69
  icon="🌱")
70
  b1, b2 = st.columns(2)
71
  if not bs.get("loaded") and b1.button("Load now", use_container_width=True,
72
+ help="Opens the drAIML agreement, then loads Bonsai into this browser"):
73
  ss.bonsai_load = True
74
  if (bs.get("cached") or bs.get("loaded")) and b2.button(
75
  "Remove", use_container_width=True, help="Remove Bonsai from this browser"):
 
171
  if bonsai.available():
172
  c1.button("🌱 Run Bonsai in this browser", key=f"offer_bonsai_{key}", type="primary", use_container_width=True,
173
  on_click=_choose_bonsai, args=(question,),
174
+ help="Free, private, no key. Opens the drAIML agreement; agree and Bonsai starts and answers.")
175
  if state.oauth_available():
176
  c2.button("🤗 Sign in with Hugging Face", key=f"offer_signin_{key}", use_container_width=True,
177
  on_click=_choose_signin, help="Use the hosted models with your own Hugging Face account.")
 
272
 
273
 
274
  async def start_bonsai() -> bool:
275
+ """Open the drAIML agreement in the page (when needed) and load Bonsai into this browser."""
276
+ with st.status("Bonsai · waiting for the drAIML agreement (in the page)…", expanded=False) as box:
277
  def progress(text, frac):
278
  box.update(label=f"Bonsai · {text}")
279
  try:
bonsai.js CHANGED
@@ -1,6 +1,6 @@
1
  // SPDX-License-Identifier: MIT
2
  // drAIML · Bonsai in this browser. The page side of draiml/bonsai.py: it owns the browseML engine (bankML compiled to
3
- // WebAssembly, browseml/ — MIT OR Apache-2.0) and drAIML's Agreement. Python (Streamlit, in a Web Worker on this
4
  // origin) asks over a BroadcastChannel; nothing here talks to any server except the model's own download.
5
 
6
  const CHANNEL = "draiml-bonsai";
@@ -63,13 +63,13 @@ function chip(text, state = "busy") {
63
  }
64
 
65
  // ── the engine, shared by the bridge (Python) and the donation panel ─────────────────────────────────────────────
66
- /** Donate compute to drAIML.dmind: lends the engine Bonsai already loaded (so it starts after the Agreement). */
67
  export const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy,
68
  (text, state) => { const c = document.getElementById("dmind-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state === "sharing" ? "ready" : "busy"; });
69
  export { mod as engineModule };
70
 
71
  let ensuring = null;
72
- /** Load Bonsai, after the Agreement when this browser has not agreed or holds no copy. Resolves to what bankML
73
  * verified, or null when the visitor declines. One load at a time. */
74
  export function ensureEngine(onProgress = () => {}) {
75
  ensuring ||= ensureOnce(onProgress).finally(() => { ensuring = null; });
@@ -117,15 +117,41 @@ export async function reloadEngine(onProgress = () => {}) {
117
  }
118
 
119
  // ── the bridge ────────────────────────────────────────────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  export function startBridge(pageId, { signin } = {}) {
121
  const ch = new BroadcastChannel(CHANNEL);
122
- const reply = (id, msg) => ch.postMessage({ ...msg, id, to: "py:" + pageId });
123
- const ensure = (id) => ensureEngine((text, frac) => reply(id, { type: "progress", text, frac }));
124
-
125
- ch.onmessage = async (ev) => {
126
  const m = ev.data || {};
127
  if (m.to !== "page:" + pageId) return;
 
 
 
 
128
  const { id, type } = m;
 
 
129
  try {
130
  if (type === "status") {
131
  const b = await mod(); // importing the module is small: the engine and the model load only on ensure
 
1
  // SPDX-License-Identifier: MIT
2
  // drAIML · Bonsai in this browser. The page side of draiml/bonsai.py: it owns the browseML engine (bankML compiled to
3
+ // WebAssembly, browseml/ — MIT OR Apache-2.0) and the drAIML agreement. Python (Streamlit, in a Web Worker on this
4
  // origin) asks over a BroadcastChannel; nothing here talks to any server except the model's own download.
5
 
6
  const CHANNEL = "draiml-bonsai";
 
63
  }
64
 
65
  // ── the engine, shared by the bridge (Python) and the donation panel ─────────────────────────────────────────────
66
+ /** Donate compute to drAIML.dmind: lends the engine Bonsai already loaded (so it starts after the drAIML agreement). */
67
  export const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy,
68
  (text, state) => { const c = document.getElementById("dmind-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state === "sharing" ? "ready" : "busy"; });
69
  export { mod as engineModule };
70
 
71
  let ensuring = null;
72
+ /** Load Bonsai, after the drAIML agreement when this browser has not agreed or holds no copy. Resolves to what bankML
73
  * verified, or null when the visitor declines. One load at a time. */
74
  export function ensureEngine(onProgress = () => {}) {
75
  ensuring ||= ensureOnce(onProgress).finally(() => { ensuring = null; });
 
117
  }
118
 
119
  // ── the bridge ────────────────────────────────────────────────────────────────────────────────────────────────────
120
+ // Python asks over a MessagePort handed to Streamlit's own worker. Inside huggingface.co's frame the browser partitions
121
+ // BroadcastChannel (the worker and this page land in different partitions), so the channel stays only as a fallback.
122
+ let handler = null;
123
+ /** Call before stlite mounts: watches the workers this page starts and answers a "draiml:hello" with a port. */
124
+ export function captureWorkers(pageId) {
125
+ const Native = window.Worker;
126
+ if (!Native || Native.__draiml) return;
127
+ class Watched extends Native {
128
+ constructor(...args) {
129
+ super(...args);
130
+ this.addEventListener("message", (ev) => {
131
+ const d = ev.data;
132
+ if (!d || d.type !== "draiml:hello" || d.page !== pageId) return;
133
+ const mc = new MessageChannel();
134
+ mc.port1.onmessage = (e) => handler && handler(e.data || {}, (msg) => mc.port1.postMessage(msg));
135
+ this.postMessage({ type: "draiml:bridge", page: pageId }, [mc.port2]);
136
+ });
137
+ }
138
+ }
139
+ Watched.__draiml = true;
140
+ window.Worker = Watched;
141
+ }
142
+
143
  export function startBridge(pageId, { signin } = {}) {
144
  const ch = new BroadcastChannel(CHANNEL);
145
+ ch.onmessage = (ev) => {
 
 
 
146
  const m = ev.data || {};
147
  if (m.to !== "page:" + pageId) return;
148
+ handler(m, (msg) => ch.postMessage(msg));
149
+ };
150
+
151
+ handler = async (m, send) => {
152
  const { id, type } = m;
153
+ const reply = (rid, msg) => send({ ...msg, id: rid, to: "py:" + pageId });
154
+ const ensure = (rid) => ensureEngine((text, frac) => reply(rid, { type: "progress", text, frac }));
155
  try {
156
  if (type === "status") {
157
  const b = await mod(); // importing the module is small: the engine and the model load only on ensure
dmind.js CHANGED
@@ -7,17 +7,11 @@
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 LUV per generated token, 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 = 10n ** 18n; // 1 SHAMBA LUV per generated token (router's rate)
22
  const MODEL_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"; // browseml/browseML/*.FORK.json
23
 
@@ -27,8 +21,6 @@ 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
  const DEFAULTS = { tokens: 0n, jobs: 0, engineMs: 0, pct: 10, on: false, gpu: false, gpuPct: 25, jobTokens: 256 };
@@ -47,45 +39,6 @@ export function login() {
47
  }
48
  function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }
49
 
50
- // ── prices ───────────────────────────────────────────────────────────────────────────────────────────────────────
51
- async function rpc(method, params) {
52
- const r = await fetch(RPC, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) });
53
- const j = await r.json(); if (!j.result) throw new Error((j.error && j.error.message) || "no result"); return j.result;
54
- }
55
- async function reserves(pair, block) {
56
- const out = await rpc("eth_call", [{ to: pair, data: "0x0902f1ac" }, block]); // getReserves()
57
- return [BigInt("0x" + out.slice(2, 66)), BigInt("0x" + out.slice(66, 130))];
58
- }
59
- let priceCache = null;
60
- /** USD per LUV (18 decimals) from the Uniswap reserves at one block, as luv.oracle prices it; BTC and gold from
61
- * DeFiLlama. Cached for 5 minutes. */
62
- export async function prices() {
63
- if (priceCache && Date.now() - priceCache.at < 300000) return priceCache;
64
- const block = await rpc("eth_blockNumber", []);
65
- const [[l0, l1], [u0, u1]] = await Promise.all([reserves(LUV.pair, block), reserves(USDC_WETH, block)]);
66
- const [luv, weth] = LUV.tokenIs0 ? [l0, l1] : [l1, l0];
67
- const usdPerEth18 = u0 * 10n ** 12n * SCALE / u1;
68
- const luvUsd18 = weth * usdPerEth18 / luv;
69
- let btcUsd18 = 0n, xauUsd18 = 0n;
70
- try {
71
- const c = (await (await fetch(LLAMA)).json()).coins || {};
72
- btcUsd18 = parse18(String(c["coingecko:bitcoin"]?.price ?? 0));
73
- xauUsd18 = parse18(String(c["coingecko:pax-gold"]?.price ?? 0));
74
- } catch {}
75
- priceCache = { at: Date.now(), block: BigInt(block).toString(), luvUsd18, btcUsd18, xauUsd18 };
76
- return priceCache;
77
- }
78
-
79
- /** What the LUV earned is worth, every amount an 18-decimal integer. */
80
- export function valuation(luvWei, p) {
81
- const usd = luvWei * p.luvUsd18 / SCALE; // PAI (= USDC), 18 decimals
82
- const btc = p.btcUsd18 ? usd * SCALE / p.btcUsd18 : 0n;
83
- const sat = p.btcUsd18 ? usd * SCALE * 100000000n / p.btcUsd18 : 0n; // SATPAY (1 satoshi), 18 decimals, from USD (not the truncated BTC)
84
- const gldbUsd18 = p.xauUsd18 * parse18(GLDB_OZ) / SCALE;
85
- const gldb = gldbUsd18 ? usd * SCALE / gldbUsd18 : 0n;
86
- return { PAI: usd, BTC: btc, SATPAY: sat, GLDB: gldb };
87
- }
88
-
89
  // ── the sharing loop ────────────────────────────────────────────────────────────────────────────────────────────���
90
  async function sha256hex(t) {
91
  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t)))].map((b) => b.toString(16).padStart(2, "0")).join("");
@@ -230,13 +183,8 @@ export class Donor {
230
  async status() {
231
  const h = await this.config(), l = this.ledger;
232
  const luvWei = l.tokens * WEI_PER_TOKEN;
233
- let worth = null, block = null;
234
- try { const p = await prices(); const v = valuation(luvWei, p); block = p.block;
235
- worth = Object.fromEntries(Object.entries(v).map(([k, x]) => [k, { exact: format18(x), sci: sci(x) }]));
236
- worth.LUV_USD = { exact: format18(p.luvUsd18), sci: sci(p.luvUsd18) };
237
- } catch (e) { worth = { error: String(e.message || e) }; }
238
  return { on: l.on, pct: l.pct, gpu: l.gpu, gpuPct: l.gpuPct, jobTokens: l.jobTokens, wallet: (login() || {}).address || "", host: h.label, open: !!h.url, state: this.state, note: this.note,
239
  jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),
240
- luv: format18(luvWei), luv_wei: luvWei.toString(), worth, block };
241
  }
242
  }
 
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 only, 1 LUV per generated token, measured to 18 decimals (SCIEN·TIFIC).
 
 
11
 
12
  const STORE = "draiml-dmind";
13
  const SCALE = 10n ** 18n;
14
  export const LUV = { token: "0x2711111111683B8708cb9a48cBf36a51315F8254", pair: "0x57D2085Aa859a145cB107845AD03c0eAAFBD8a31", tokenIs0: true };
 
 
 
 
15
  const WEI_PER_TOKEN = 10n ** 18n; // 1 SHAMBA LUV per generated token (router's rate)
16
  const MODEL_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"; // browseml/browseML/*.FORK.json
17
 
 
21
  const m = /^(\d+)(?:\.(\d{1,18}))?/.exec(String(s).trim());
22
  return m ? BigInt(m[1]) * SCALE + BigInt(((m[2] || "") + "0".repeat(18)).slice(0, 18)) : 0n;
23
  }
 
 
24
 
25
  // ── the ledger, kept in this browser ─────────────────────────────────────────────────────────────────────────────
26
  const DEFAULTS = { tokens: 0n, jobs: 0, engineMs: 0, pct: 10, on: false, gpu: false, gpuPct: 25, jobTokens: 256 };
 
39
  }
40
  function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  // ── the sharing loop ────────────────────────────────────────────────────────────────────────────────────────────���
43
  async function sha256hex(t) {
44
  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t)))].map((b) => b.toString(16).padStart(2, "0")).join("");
 
183
  async status() {
184
  const h = await this.config(), l = this.ledger;
185
  const luvWei = l.tokens * WEI_PER_TOKEN;
 
 
 
 
 
186
  return { on: l.on, pct: l.pct, gpu: l.gpu, gpuPct: l.gpuPct, jobTokens: l.jobTokens, wallet: (login() || {}).address || "", host: h.label, open: !!h.url, state: this.state, note: this.note,
187
  jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),
188
+ luv: format18(luvWei), luv_wei: luvWei.toString() };
189
  }
190
  }
donate.js CHANGED
@@ -1,11 +1,11 @@
1
  // SPDX-License-Identifier: MIT
2
  // drAIML · the donation panel: sign in with login333 · drAIML, choose the CPU, RAM and GPU shares, confirm them, then
3
- // watch what this computer gives (measured) and what it earns (SHAMBA LUV, 1 LUV per generated token, valued in
4
- // BANKON units), and request a payout to the signed-in wallet. Everything here runs in the page; the router only
5
  // verifies the sign-in, keeps the ledger and records payout claims, which the drAIML operator pays.
6
 
7
  import { donor, ensureEngine, reloadEngine } from "./bonsai.js";
8
- import { LOGIN_KEY, login, format18, prices, valuation } from "./dmind.js";
9
 
10
  const $ = (sel) => document.querySelector(sel);
11
  const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "");
@@ -114,7 +114,7 @@ function review() {
114
  let ok;
115
  if (gpuChanged && mod.isReady()) { say("Restarting Bonsai with the new GPU share…"); ok = await reloadEngine((t) => say(t)); }
116
  else ok = await ensureEngine((t) => say(t));
117
- if (!ok) { say("Donating needs Bonsai in this browser: accept the Agreement to start."); return; }
118
  donor.settings({ on: true });
119
  render();
120
  };
@@ -157,25 +157,15 @@ async function render() {
157
  row("Last job speed", m.genTps ? `reads ${m.promptTps.toFixed(1)} · writes ${m.genTps.toFixed(1)} tokens/s` : "—"),
158
  );
159
 
160
- // earnings: this browser's own count, the router's account, and their worth
161
  const local = BigInt(st.luv_wei || "0");
162
  let acct = null; try { acct = await donor.earnings(); } catch {}
163
- const earned = acct ? BigInt(acct.luv_wei) : local;
164
  const rows = [row("Earned (this browser)", `${format18(local)} LUV`)];
165
  if (acct) {
166
  rows.push(row("Earned (drAIML.dmind ledger)", `${format18(BigInt(acct.luv_wei))} LUV · ${acct.jobs} jobs`),
167
  row("Claimed · paid", `${format18(BigInt(acct.claimed_wei))} · ${format18(BigInt(acct.paid_wei))} LUV`),
168
  row("Available to claim", `${format18(BigInt(acct.available_wei))} LUV`));
169
  }
170
- try {
171
- const p = await prices(), v = valuation(earned, p);
172
- // 18 decimals round tiny amounts to zero: the approximation beside each keeps every significant digit
173
- const usd = Number(earned) / 1e18 * Number(p.luvUsd18) / 1e18, btc = Number(p.btcUsd18) / 1e18, xau = Number(p.xauUsd18) / 1e18;
174
- const ap = (x) => (x ? x.toExponential(3) : "0");
175
- rows.push(row("Worth (18 decimals)", `${format18(v.PAI)} PAI · ${format18(v.SATPAY)} SATPAY · ${format18(v.BTC)} BTC · ${format18(v.GLDB)} GLDB`),
176
- row("Worth (≈)", `${ap(usd)} PAI · ${btc ? ap(usd / btc * 1e8) : "?"} SATPAY · ${btc ? ap(usd / btc) : "?"} BTC · ${xau ? ap(usd / (xau * 0.000241833)) : "?"} GLDB`),
177
- row("Price used", `1 LUV = ${ap(Number(p.luvUsd18) / 1e18)} USD (Uniswap reserves, block ${p.block}) · 1 BTC = ${btc.toFixed(0)} USD`));
178
- } catch { rows.push(row("Worth", "prices unavailable right now")); }
179
  $("#dn-earn").replaceChildren(...rows);
180
  const pay = $("#dn-payout");
181
  pay.disabled = !(acct && BigInt(acct.available_wei) > 0n);
 
1
  // SPDX-License-Identifier: MIT
2
  // drAIML · the donation panel: sign in with login333 · drAIML, choose the CPU, RAM and GPU shares, confirm them, then
3
+ // watch what this computer gives (measured) and what it earns (SHAMBA LUV, 1 LUV per generated token),
4
+ // and request a payout to the signed-in wallet. Everything here runs in the page; the router only
5
  // verifies the sign-in, keeps the ledger and records payout claims, which the drAIML operator pays.
6
 
7
  import { donor, ensureEngine, reloadEngine } from "./bonsai.js";
8
+ import { LOGIN_KEY, login, format18 } from "./dmind.js";
9
 
10
  const $ = (sel) => document.querySelector(sel);
11
  const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "");
 
114
  let ok;
115
  if (gpuChanged && mod.isReady()) { say("Restarting Bonsai with the new GPU share…"); ok = await reloadEngine((t) => say(t)); }
116
  else ok = await ensureEngine((t) => say(t));
117
+ if (!ok) { say("Donating needs Bonsai in this browser: accept the drAIML agreement to start."); return; }
118
  donor.settings({ on: true });
119
  render();
120
  };
 
157
  row("Last job speed", m.genTps ? `reads ${m.promptTps.toFixed(1)} · writes ${m.genTps.toFixed(1)} tokens/s` : "—"),
158
  );
159
 
160
+ // earnings, in SHAMBA LUV only: this browser's own count and the router's account
161
  const local = BigInt(st.luv_wei || "0");
162
  let acct = null; try { acct = await donor.earnings(); } catch {}
 
163
  const rows = [row("Earned (this browser)", `${format18(local)} LUV`)];
164
  if (acct) {
165
  rows.push(row("Earned (drAIML.dmind ledger)", `${format18(BigInt(acct.luv_wei))} LUV · ${acct.jobs} jobs`),
166
  row("Claimed · paid", `${format18(BigInt(acct.claimed_wei))} · ${format18(BigInt(acct.paid_wei))} LUV`),
167
  row("Available to claim", `${format18(BigInt(acct.available_wei))} LUV`));
168
  }
 
 
 
 
 
 
 
 
 
169
  $("#dn-earn").replaceChildren(...rows);
170
  const pay = $("#dn-payout");
171
  pay.disabled = !(acct && BigInt(acct.available_wei) > 0n);
index.html CHANGED
@@ -167,8 +167,7 @@
167
  <p class="hint" id="dn-pay-status" role="status"></p>
168
  <ul class="claims" id="dn-claims"></ul>
169
  <p class="hint">1 SHAMBA LUV (0x2711…8254, Ethereum) per generated token, counted to 18 decimals (SCIEN·TIFIC).
170
- Payouts are sent by the drAIML operator from the ledger in batches. BANKON PAI (1 = 1 USDC), SATPAY (1 sat) and
171
- GLDB are units of account only.</p>
172
  </div>
173
  </div>
174
  </dialog>
@@ -184,7 +183,7 @@
184
 
185
  <dialog id="bonsai-agreement" aria-labelledby="agree-title">
186
  <div class="agree">
187
- <h2 id="agree-title">drAIML Agreement · Bonsai in this browser</h2>
188
  <p class="lede">Before drAIML puts a medical consultation model inside your browser, please read and agree.</p>
189
  <h3>What happens</h3>
190
  <ul>
@@ -217,11 +216,12 @@
217
  <script type="module">
218
  import { mount } from "https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.1/build/stlite.js";
219
  import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";
220
- import { startBridge } from "./bonsai.js";
221
  import { init as initDonate } from "./donate.js";
222
 
223
  // this tab's id: Python (in its Web Worker) and this page find each other by it over a BroadcastChannel
224
  const PAGE_ID = (crypto.randomUUID && crypto.randomUUID()) || String(Math.random()).slice(2);
 
225
  startBridge(PAGE_ID, { signin: () => document.getElementById("signin").click() });
226
  initDonate();
227
 
 
167
  <p class="hint" id="dn-pay-status" role="status"></p>
168
  <ul class="claims" id="dn-claims"></ul>
169
  <p class="hint">1 SHAMBA LUV (0x2711…8254, Ethereum) per generated token, counted to 18 decimals (SCIEN·TIFIC).
170
+ Rewards are paid in SHAMBA LUV only, sent by the drAIML operator from the ledger in batches.</p>
 
171
  </div>
172
  </div>
173
  </dialog>
 
183
 
184
  <dialog id="bonsai-agreement" aria-labelledby="agree-title">
185
  <div class="agree">
186
+ <h2 id="agree-title">drAIML agreement</h2>
187
  <p class="lede">Before drAIML puts a medical consultation model inside your browser, please read and agree.</p>
188
  <h3>What happens</h3>
189
  <ul>
 
216
  <script type="module">
217
  import { mount } from "https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.1/build/stlite.js";
218
  import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";
219
+ import { startBridge, captureWorkers } from "./bonsai.js";
220
  import { init as initDonate } from "./donate.js";
221
 
222
  // this tab's id: Python (in its Web Worker) and this page find each other by it over a BroadcastChannel
223
  const PAGE_ID = (crypto.randomUUID && crypto.randomUUID()) || String(Math.random()).slice(2);
224
+ captureWorkers(PAGE_ID); // before mount: Python reaches this page through a port on its worker
225
  startBridge(PAGE_ID, { signin: () => document.getElementById("signin").click() });
226
  initDonate();
227