Gregory-L commited on
Commit
2c514f2
·
verified ·
1 Parent(s): c181f01

drAIML.dmind: host/router for inference delegation and maintenance (no inference on the host); donors lend to it; new source answers from donated compute

Browse files
README.md CHANGED
@@ -59,6 +59,9 @@ your consultation is stored.
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
 
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
+ - **drAIML.dmind.** A host/router for inference delegation and maintenance ([router/](router/README.md)): it runs no
63
+ inference itself, it queues questions, hands them to donors and checks every receipt. Choose
64
+ "drAIML.dmind · donated compute" as the source to be answered by donors, free and with no key.
65
  - **Open evidence.** 43k passages from openly licensed health datasets
66
  ([PYTHAI/drAIML-evidence](https://huggingface.co/datasets/PYTHAI/drAIML-evidence)), cited inline.
67
  - **Many models.** Every open chat model live on HF Inference Providers (sign in with Hugging Face; your own
app/draiml/engines.py CHANGED
@@ -34,6 +34,12 @@ ENDPOINTS: dict[str, Endpoint] = {
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
  "hf": Endpoint(
38
  "hf", "Hugging Face · Inference Providers", HF_ROUTER, True, "HF token",
39
  "Sign in with Hugging Face (top bar), or paste a fine-grained token with "
@@ -82,6 +88,11 @@ async def stream_chat(endpoint: Endpoint, model: str, messages: list[dict], *, k
82
  async for kind, d in bonsai.stream(msgs, max_tokens=min(max_tokens, 600), temperature=temperature):
83
  yield kind, d
84
  return
 
 
 
 
 
85
  url = (base_url or endpoint.base_url).rstrip("/") + "/chat/completions"
86
  payload = {"model": model, "messages": messages, "stream": True,
87
  "max_tokens": max_tokens, "temperature": temperature}
 
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",
39
+ False, "",
40
+ "Questions go to drAIML.dmind, which hands them to visitors who donate compute: Bonsai-1.7B in their "
41
+ "browsers, each answer with a bankML receipt the router checks. Needs at least one donor online.",
42
+ ("Bonsai-1.7B-Q1_0",)),
43
  "hf": Endpoint(
44
  "hf", "Hugging Face · Inference Providers", HF_ROUTER, True, "HF token",
45
  "Sign in with Hugging Face (top bar), or paste a fine-grained token with "
 
88
  async for kind, d in bonsai.stream(msgs, max_tokens=min(max_tokens, 600), temperature=temperature):
89
  yield kind, d
90
  return
91
+ if endpoint.key == "dmind": # donors run Bonsai-1.7B: no thinking, short answers
92
+ messages = [dict(m) for m in messages]
93
+ if messages and messages[-1]["role"] == "user":
94
+ messages[-1]["content"] += " /no_think"
95
+ max_tokens = min(max_tokens, 600)
96
  url = (base_url or endpoint.base_url).rstrip("/") + "/chat/completions"
97
  payload = {"model": model, "messages": messages, "stream": True,
98
  "max_tokens": max_tokens, "temperature": temperature}
app/manifest.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "build": "c1cc1254551a",
3
  "requirements": [],
4
  "files": [
5
  "app.py",
 
1
  {
2
+ "build": "0ef2748dad8d",
3
  "requirements": [],
4
  "files": [
5
  "app.py",
app/views/consult.py CHANGED
@@ -75,6 +75,8 @@ with st.sidebar:
75
  "Remove", use_container_width=True, help="Remove Bonsai from this browser"):
76
  await bonsai.forget() # noqa: F704
77
  st.rerun()
 
 
78
  elif not (ss.engine == "hf" and ss.get("hf_oauth")):
79
  k = st.text_input(ep.key_label, value=ss.api_keys.get(ss.engine, ""), type="password", help=ep.key_help)
80
  if k != ss.api_keys.get(ss.engine, ""):
@@ -281,6 +283,8 @@ async def answer(model: str, prepared, key, base_url) -> dict:
281
  hint = " — check your key or sign in again."
282
  elif e.status == 402:
283
  hint = " — your Inference Providers credits are used up (huggingface.co/settings/billing)."
 
 
284
  elif e.status in (400, 404) and ss.engine == "hf":
285
  hint = " — this model may have just left the provider network; pick another."
286
  st.error(f"{msg}{hint}")
@@ -328,12 +332,13 @@ async def run_turn(prompt: str, *, new: bool = True) -> None:
328
  with st.chat_message("user", avatar="🧑"):
329
  st.markdown(prompt)
330
  use_bonsai = ss.engine == "bonsai" and bonsai.available()
 
331
  if ss.engine == "bonsai" and not use_bonsai:
332
  key = None
333
  history = ss.history if new else ss.history[:-1] # the question itself is not context for itself
334
  index = await state.evidence_index()
335
  prepared = await consult.prepare(prompt, history, index, k=k_evidence, token=state.key_for("hf"),
336
- audience=audience, mode=ss.mode, compact=use_bonsai)
337
  if new:
338
  ss.history.append({"role": "user", "content": prompt})
339
  triage_msg = prepared.triage.banner() if prepared.triage.emergency else ""
 
75
  "Remove", use_container_width=True, help="Remove Bonsai from this browser"):
76
  await bonsai.forget() # noqa: F704
77
  st.rerun()
78
+ elif ss.engine == "dmind":
79
+ st.caption(ep.key_help)
80
  elif not (ss.engine == "hf" and ss.get("hf_oauth")):
81
  k = st.text_input(ep.key_label, value=ss.api_keys.get(ss.engine, ""), type="password", help=ep.key_help)
82
  if k != ss.api_keys.get(ss.engine, ""):
 
283
  hint = " — check your key or sign in again."
284
  elif e.status == 402:
285
  hint = " — your Inference Providers credits are used up (huggingface.co/settings/billing)."
286
+ elif e.status == 503 and ss.engine == "dmind":
287
+ hint = " — no one is donating compute this minute. Try Bonsai in this browser, or turn on ❤️ Donate compute."
288
  elif e.status in (400, 404) and ss.engine == "hf":
289
  hint = " — this model may have just left the provider network; pick another."
290
  st.error(f"{msg}{hint}")
 
332
  with st.chat_message("user", avatar="🧑"):
333
  st.markdown(prompt)
334
  use_bonsai = ss.engine == "bonsai" and bonsai.available()
335
+ small = use_bonsai or ss.engine == "dmind" # Bonsai-1.7B answers either way: the compact prompt
336
  if ss.engine == "bonsai" and not use_bonsai:
337
  key = None
338
  history = ss.history if new else ss.history[:-1] # the question itself is not context for itself
339
  index = await state.evidence_index()
340
  prepared = await consult.prepare(prompt, history, index, k=k_evidence, token=state.key_for("hf"),
341
+ audience=audience, mode=ss.mode, compact=small)
342
  if new:
343
  ss.history.append({"role": "user", "content": prompt})
344
  triage_msg = prepared.triage.banner() if prepared.triage.emergency else ""
dmind-host.json CHANGED
@@ -1,6 +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
  }
 
1
  {
2
  "label": "drAIML.dmind",
3
+ "url": "https://deltaverse.pythai.net/draiml-dmind",
4
  "token_key": "",
5
+ "note": "drAIML.dmind router (router/draiml_router.py): delegation and maintenance only, no inference on the host. Workers: /sharedcpu/*; clients: /v1/chat/completions."
6
  }
router/README.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # drAIML.dmind — host / router for inference maintenance and delegation
2
+
3
+ drAIML.dmind is a **router, not an inference server**. The host machine does no thinking: it keeps a queue and
4
+ a ledger, and hands every question to someone who lends compute.
5
+
6
+ ```
7
+ clients drAIML.dmind (router) workers
8
+ ─────── ───────────────────── ───────
9
+ drAIML "drAIML.dmind" source ─▶ POST /v1/chat/completions browsers running Bonsai-1.7B
10
+ any OpenAI-compatible app │ queue ─ lease ─ re-queue (drAIML's ❤️ Donate compute,
11
+ │ receipt + model-pin check browseML), bankml serve
12
+ │ occasional cross-check ◀── join · pull · result · decline · fail · leave
13
+ └─ ledger: 1 wei LUV per generated token
14
+ ```
15
+
16
+ ## Delegation
17
+ - A client's chat request becomes a **job** (max 600 tokens). Without workers the router answers 503 with
18
+ `Retry-After: 30` at once, so nobody waits for nothing.
19
+ - Workers **long-poll** `/sharedcpu/pull` (25 s) and run the job exactly as sent on their own engine.
20
+ - The answer reaches the client only after the router checks its **bankML receipt**: `response_sha256`
21
+ must be the sha256 of the text, and `model_sha256` must be the pinned model
22
+ (Bonsai-1.7B Q1_0, `3d7c6c90…f7e3`).
23
+ - `stream: true` is accepted: the whole answer comes as one SSE event, then `[DONE]`.
24
+
25
+ ## Maintenance
26
+ - **Worker registry:** a session silent for 90 s is dropped. Heartbeats come via `/sharedcpu/update`, and the
27
+ donor's `share_pct` and pauses are recorded.
28
+ - **Leases:** a job held 300 s without a result goes back to the queue, up to 3 tries.
29
+ - Declined jobs are re-queued without counting a try (the donor's own question came first).
30
+ - A failed job counts a try.
31
+ - If the client gives up, the job is withdrawn (`cancelled` on the next heartbeat).
32
+ - **Trust:** a bad receipt is refused and the job re-queued.
33
+ - 5% of temperature-0 jobs also go to a second worker; members of one engine group must agree token for token.
34
+ - Three strikes bar a worker.
35
+ - **Ledger:** `ledger.jsonl` records wallet, job, tokens, `luv_wei` (1 wei of SHAMBA LUV per generated token,
36
+ dmind's paymint rule, SCIEN·TIFIC 18-decimal measurement) and the answer's sha256.
37
+ - `GET /sharedcpu/me?wallet=0x…` sums it.
38
+ - The router signs and pays nothing: payout is a separate, operator-run step.
39
+ - **Visibility:** `GET /health` and `GET /insight/sharedcpu` (workers, lending, queue, counters); `GET /v1/models`.
40
+ - **Abuse limits:**
41
+ - Open clients get 6 requests per minute per IP (or pass `--keys` for keyed clients).
42
+ - Queue cap 64, request body 64 KB.
43
+ - CORS only for drAIML's origins.
44
+
45
+ ## Footprint
46
+ Python standard library only (asyncio), one process, about 14 MB of memory, idle between requests. It runs on
47
+ the busy one-core VPS as a sandboxed systemd service:
48
+
49
+ - dynamic user
50
+ - `CPUQuota=5%`, `CPUWeight=10`, `Nice=19`
51
+ - idle I/O
52
+ - `MemoryMax=64M`
53
+ - read-only system
54
+
55
+ Live at **https://deltaverse.pythai.net/draiml-dmind/**, proxied by Apache to `127.0.0.1:4041`.
56
+
57
+ ## Run it
58
+ ```bash
59
+ python3 draiml_router.py --bind 127.0.0.1 --port 4041 --ledger ledger.jsonl --trust-proxy
60
+ ```
61
+ Tests: `pytest tests/test_router.py`. The worker wire protocol is dmind's, as browseML's share module speaks it.
router/draiml_router.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: MIT
3
+ """drAIML.dmind — a host/router for inference maintenance and delegation.
4
+
5
+ The router does no inference. It sits between those who need answers and those who lend compute:
6
+
7
+ clients ──POST /v1/chat/completions──▶ router ◀──join · pull · result── workers
8
+ (drAIML, any OpenAI-compatible app) (queue, leases, receipts, (browsers running browseML's
9
+ cross-checks, ledger) Bonsai, or bankml serve)
10
+
11
+ Delegation: each request becomes a job in a queue; a worker long-polls /sharedcpu/pull, runs the job exactly as
12
+ sent on its own engine, and returns the text with its bankML receipt. The router checks the receipt (the answer's
13
+ sha256 and the pinned model sha256) before the client sees anything.
14
+
15
+ Maintenance: a worker registry with heartbeats and TTLs; leases, so a job whose worker vanishes goes back to the
16
+ queue (up to MAX_TRIES); declined and failed jobs re-queued; an occasional cross-check (a temperature-0 job sent to
17
+ two workers in the same engine group must come back token-identical, else both are marked); health and insight
18
+ endpoints; and a ledger: SHAMBA LUV at 1 wei per generated token (dmind's paymint rule, 18-decimal SCIEN·TIFIC
19
+ measurement), appended to a JSONL file per wallet. The router signs nothing and pays nothing: payment is a separate,
20
+ operator-run step over the ledger.
21
+
22
+ The wire protocol for workers is dmind's as browseML's share module speaks it (github.com/browseML/browseML):
23
+ POST /sharedcpu/join · /update · /pull · /result · /decline · /fail · /leave.
24
+
25
+ Python standard library only (asyncio). One process, a few MB of memory, idle between requests: built to live on a
26
+ busy one-core VPS under systemd's CPUQuota.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import asyncio
32
+ import collections
33
+ import hashlib
34
+ import json
35
+ import os
36
+ import random
37
+ import secrets
38
+ import time
39
+ from dataclasses import dataclass, field
40
+ from urllib.parse import parse_qs, urlsplit
41
+
42
+ VERSION = "0.1.0"
43
+ HOST_LABEL = "drAIML.dmind"
44
+ BONSAI_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"
45
+ MODELS = { # what workers may serve: name -> pinned sha256 and engine group (members must agree token for token)
46
+ "Bonsai-1.7B-Q1_0": {"sha256": BONSAI_SHA256, "group": "bankml-q1"},
47
+ }
48
+ ALLOWED_ORIGINS = ("https://pythai-draiml.static.hf.space", "https://huggingface.co")
49
+ SESSION_TTL_S = 90 # a worker silent this long (no pull/update) is dropped
50
+ PULL_WAIT_S = 25 # long-poll
51
+ LEASE_S = 300 # a job held this long without a result goes back to the queue
52
+ MAX_TRIES = 3
53
+ MAX_QUEUE = 64
54
+ MAX_TOKENS = 600
55
+ MAX_BODY = 64 * 1024
56
+ CLIENT_WAIT_S = 600 # how long a client request may wait for a worker's answer
57
+ CROSS_CHECK = 0.05 # share of temperature-0 jobs also sent to a second worker
58
+ RATE = (6, 60) # client requests per IP: 6 per 60 s
59
+ WEI_PER_TOKEN = 1
60
+
61
+
62
+ def now() -> float:
63
+ return time.monotonic()
64
+
65
+
66
+ @dataclass
67
+ class Worker:
68
+ session: str
69
+ model: str
70
+ engine: str
71
+ share_pct: int
72
+ wallet: str
73
+ contributor: str
74
+ ip: str
75
+ seen: float = field(default_factory=now)
76
+ paused: bool = False
77
+ jobs: int = 0
78
+ tokens: int = 0
79
+ strikes: int = 0
80
+ waiter: asyncio.Future | None = None
81
+
82
+
83
+ @dataclass
84
+ class Job:
85
+ id: str
86
+ model: str
87
+ messages: list
88
+ max_tokens: int
89
+ temperature: float
90
+ created: float = field(default_factory=now)
91
+ tries: int = 0
92
+ holder: str = ""
93
+ lease_until: float = 0.0
94
+ done: asyncio.Future | None = None
95
+ check_of: str = "" # a cross-check copy points at its original
96
+ check_text: str | None = None
97
+ check_worker: str = ""
98
+
99
+
100
+ class Router:
101
+ def __init__(self, ledger_path: str, keys_path: str | None = None):
102
+ self.workers: dict[str, Worker] = {}
103
+ self.queue: collections.deque[Job] = collections.deque()
104
+ self.jobs: dict[str, Job] = {}
105
+ self.ledger_path = ledger_path
106
+ self.keys = self._load_keys(keys_path)
107
+ self.rate: dict[str, collections.deque] = {}
108
+ self.stats = collections.Counter()
109
+ self.started = time.time()
110
+
111
+ # ── helpers ──────────────────────────────────────────────────────────────────────────────────────────────────
112
+ @staticmethod
113
+ def _load_keys(path):
114
+ if not path or not os.path.exists(path):
115
+ return None # open: rate-limited per IP
116
+ with open(path) as f:
117
+ return {line.strip() for line in f if line.strip() and not line.startswith("#")}
118
+
119
+ def _ledger(self, entry: dict) -> None:
120
+ with open(self.ledger_path, "a") as f:
121
+ f.write(json.dumps(entry, separators=(",", ":")) + "\n")
122
+
123
+ def _limited(self, ip: str) -> bool:
124
+ q = self.rate.setdefault(ip, collections.deque())
125
+ t = now()
126
+ while q and t - q[0] > RATE[1]:
127
+ q.popleft()
128
+ if len(q) >= RATE[0]:
129
+ return True
130
+ q.append(t)
131
+ return False
132
+
133
+ def _wake_one(self) -> None:
134
+ for w in self.workers.values():
135
+ if w.waiter and not w.waiter.done() and not w.paused:
136
+ w.waiter.set_result(True)
137
+ return
138
+
139
+ def _take(self, w: Worker) -> Job | None:
140
+ for _ in range(len(self.queue)):
141
+ j = self.queue.popleft()
142
+ if j.done is not None and j.done.done() and not j.check_of:
143
+ continue # the client gave up
144
+ if j.model != w.model:
145
+ self.queue.append(j)
146
+ continue
147
+ if j.check_of and j.check_worker == w.session:
148
+ self.queue.append(j) # a cross-check must go to another worker
149
+ continue
150
+ j.holder, j.lease_until, j.tries = w.session, now() + LEASE_S, j.tries + 1
151
+ return j
152
+ return None
153
+
154
+ def _requeue(self, j: Job, why: str) -> None:
155
+ j.holder = ""
156
+ if j.tries >= MAX_TRIES:
157
+ if j.done and not j.done.done():
158
+ j.done.set_exception(RuntimeError(f"no worker could finish it ({why})"))
159
+ self.jobs.pop(j.id, None)
160
+ self.stats["jobs_failed"] += 1
161
+ return
162
+ self.queue.appendleft(j)
163
+ self._wake_one()
164
+
165
+ async def maintain(self) -> None:
166
+ """Every few seconds: drop silent workers, take back expired leases, forget finished jobs."""
167
+ while True:
168
+ await asyncio.sleep(5)
169
+ t = now()
170
+ for s, w in list(self.workers.items()):
171
+ if t - w.seen > SESSION_TTL_S:
172
+ self.workers.pop(s, None)
173
+ self.stats["workers_dropped"] += 1
174
+ for j in list(self.jobs.values()):
175
+ if j.holder and (t > j.lease_until or j.holder not in self.workers):
176
+ self._requeue(j, "lease expired")
177
+ elif not j.holder and j.done is not None and j.done.done() and not j.check_of:
178
+ self.jobs.pop(j.id, None)
179
+
180
+ # ── worker API (dmind) ───────────────────────────────────────────────────────────────────────────────────────
181
+ def join(self, b: dict, ip: str) -> dict:
182
+ sha = str(b.get("model_sha256", "")).lower()
183
+ model = next((m for m, v in MODELS.items() if v["sha256"] == sha), None)
184
+ if not model:
185
+ return {"ok": False, "reason": "this host serves only pinned models", "models": MODELS}
186
+ wallet = str(b.get("wallet") or "")
187
+ if wallet and not (wallet.startswith("0x") and len(wallet) == 42):
188
+ wallet = ""
189
+ s = secrets.token_hex(16)
190
+ self.workers[s] = Worker(s, model, str(b.get("engine", ""))[:40], max(1, min(100, int(b.get("share_pct") or 10))),
191
+ wallet, str(b.get("contributor", ""))[:20], ip)
192
+ self.stats["joins"] += 1
193
+ return {"ok": True, "session": s, "host": HOST_LABEL, "model": model, "engine_group": MODELS[model]["group"],
194
+ "ttl_s": SESSION_TTL_S, "pull_wait_s": PULL_WAIT_S, "lease_s": LEASE_S,
195
+ "trust": {"note": "receipts checked; occasional cross-checks between workers"}}
196
+
197
+ def _worker(self, b: dict) -> Worker | None:
198
+ w = self.workers.get(str(b.get("session", "")))
199
+ if w:
200
+ w.seen = now()
201
+ return w
202
+
203
+ def update(self, b: dict) -> dict:
204
+ w = self._worker(b)
205
+ if not w:
206
+ return {"ok": False, "reason": "unknown session"}
207
+ if "paused" in b:
208
+ w.paused = bool(b["paused"])
209
+ if b.get("share_pct"):
210
+ w.share_pct = max(1, min(100, int(b["share_pct"])))
211
+ held = [j.id for j in self.jobs.values() if j.holder == w.session]
212
+ out = {"ok": True}
213
+ for jid in held: # a job its client abandoned is withdrawn
214
+ j = self.jobs[jid]
215
+ if j.done is not None and j.done.done() and not j.check_of:
216
+ out["cancelled"] = jid
217
+ else:
218
+ j.lease_until = now() + LEASE_S
219
+ return out
220
+
221
+ async def pull(self, b: dict) -> dict:
222
+ w = self._worker(b)
223
+ if not w:
224
+ return {"ok": False, "reason": "unknown session"}
225
+ if w.strikes >= 3:
226
+ return {"ok": False, "barred": True, "reason": "answers did not match other workers"}
227
+ w.paused = False
228
+ j = self._take(w)
229
+ if not j:
230
+ w.waiter = asyncio.get_running_loop().create_future()
231
+ try:
232
+ await asyncio.wait_for(w.waiter, PULL_WAIT_S)
233
+ except asyncio.TimeoutError:
234
+ pass
235
+ w.waiter, w.seen = None, now()
236
+ j = self._take(w)
237
+ if not j:
238
+ return {"ok": True, "job": None}
239
+ return {"ok": True, "job": {"job": j.id, "messages": j.messages, "max_tokens": j.max_tokens,
240
+ "temperature": j.temperature, "model_sha256": MODELS[j.model]["sha256"],
241
+ "lease_s": LEASE_S, "kind": "chat", "kind_label": "consultation",
242
+ "purpose": "an answer for a drAIML visitor"}}
243
+
244
+ def result(self, b: dict) -> dict:
245
+ w = self._worker(b)
246
+ j = self.jobs.get(str(b.get("job", "")))
247
+ if not w or not j or j.holder != w.session:
248
+ return {"ok": False, "reason": "not your job (lease expired?)"}
249
+ text, rc, usage = str(b.get("text", "")), b.get("receipt") or {}, b.get("usage") or {}
250
+ good = (hashlib.sha256(text.encode()).hexdigest() == rc.get("response_sha256")
251
+ and str(rc.get("model_sha256", "")).lower() == MODELS[j.model]["sha256"])
252
+ if not good:
253
+ w.strikes += 1
254
+ self._requeue(j, "receipt did not match")
255
+ self.stats["receipts_bad"] += 1
256
+ return {"ok": False, "reason": "the receipt does not match the text or the pinned model"}
257
+ tokens = max(0, int(usage.get("completion_tokens") or 0))
258
+ w.jobs += 1
259
+ w.tokens += tokens
260
+ self.stats["jobs_done"] += 1
261
+ self.stats["tokens"] += tokens
262
+ self._ledger({"t": int(time.time()), "host": HOST_LABEL, "wallet": w.wallet, "job": j.id, "tokens": tokens,
263
+ "luv_wei": str(tokens * WEI_PER_TOKEN), "response_sha256": rc.get("response_sha256"),
264
+ "engine": w.engine, "check": bool(j.check_of)})
265
+ j.holder = ""
266
+ if j.check_of: # a cross-check copy: compare with the original's answer
267
+ if j.check_text != text:
268
+ for s in (w.session, j.check_worker):
269
+ if s in self.workers:
270
+ self.workers[s].strikes += 1
271
+ self.stats["cross_mismatch"] += 1
272
+ else:
273
+ self.stats["cross_match"] += 1
274
+ self.jobs.pop(j.id, None)
275
+ return {"ok": True, "credited_tokens": tokens, "luv_wei": str(tokens * WEI_PER_TOKEN), "audit": "cross-check"}
276
+ if j.done and not j.done.done():
277
+ j.done.set_result({"text": text, "receipt": rc, "usage": usage, "timings": b.get("timings") or {},
278
+ "worker": {"engine": w.engine, "contributor": w.contributor}})
279
+ if j.temperature == 0 and random.random() < CROSS_CHECK and len(self.workers) > 1:
280
+ c = Job(secrets.token_hex(8), j.model, j.messages, j.max_tokens, 0.0, check_of=j.id,
281
+ check_text=text, check_worker=w.session)
282
+ self.jobs[c.id] = c
283
+ self.queue.append(c)
284
+ self._wake_one()
285
+ return {"ok": True, "credited_tokens": tokens, "luv_wei": str(tokens * WEI_PER_TOKEN), "audit": "receipt"}
286
+
287
+ def decline(self, b: dict, failed: bool = False) -> dict:
288
+ w = self._worker(b)
289
+ j = self.jobs.get(str(b.get("job", "")))
290
+ if w and j and j.holder == w.session:
291
+ if not failed:
292
+ j.tries -= 1 # declining is not a failed try
293
+ self._requeue(j, str(b.get("reason", "declined"))[:80])
294
+ return {"ok": True}
295
+
296
+ def leave(self, b: dict) -> dict:
297
+ w = self.workers.pop(str(b.get("session", "")), None)
298
+ if w:
299
+ for j in list(self.jobs.values()):
300
+ if j.holder == w.session:
301
+ self._requeue(j, "worker left")
302
+ return {"ok": True}
303
+
304
+ # ── client API (delegation) ─────────────────────────────────────────────────────────────────────────────────
305
+ async def complete(self, b: dict, ip: str, key: str) -> tuple[int, dict]:
306
+ if self.keys is not None and key not in self.keys:
307
+ return 401, {"error": {"message": "a client key is required"}}
308
+ if self.keys is None and self._limited(ip):
309
+ return 429, {"error": {"message": f"at most {RATE[0]} requests per {RATE[1]} s"}}
310
+ model = str(b.get("model") or "Bonsai-1.7B-Q1_0")
311
+ if model not in MODELS:
312
+ return 404, {"error": {"message": f"unknown model; this host serves {list(MODELS)}"}}
313
+ msgs = b.get("messages")
314
+ if not isinstance(msgs, list) or not msgs:
315
+ return 400, {"error": {"message": "messages are required"}}
316
+ if not any(w.model == model for w in self.workers.values()):
317
+ return 503, {"error": {"message": "no worker is lending compute right now; try again soon"}}
318
+ if len(self.queue) >= MAX_QUEUE:
319
+ return 503, {"error": {"message": "the queue is full; try again soon"}}
320
+ j = Job(secrets.token_hex(8), model, msgs, max(1, min(MAX_TOKENS, int(b.get("max_tokens") or 400))),
321
+ float(b.get("temperature") if b.get("temperature") is not None else 0.3))
322
+ j.done = asyncio.get_running_loop().create_future()
323
+ self.jobs[j.id] = j
324
+ self.queue.append(j)
325
+ self.stats["requests"] += 1
326
+ self._wake_one()
327
+ try:
328
+ r = await asyncio.wait_for(asyncio.shield(j.done), CLIENT_WAIT_S)
329
+ except asyncio.TimeoutError:
330
+ j.done.cancel()
331
+ return 504, {"error": {"message": "no worker answered in time"}}
332
+ except RuntimeError as e:
333
+ return 502, {"error": {"message": str(e)}}
334
+ u = r["usage"]
335
+ return 200, {"id": "chatcmpl-" + j.id, "object": "chat.completion", "created": int(time.time()), "model": model,
336
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": r["text"]},
337
+ "finish_reason": "stop"}],
338
+ "usage": u, "timings": r["timings"], "bankml_receipt": r["receipt"],
339
+ "draiml_dmind": {"host": HOST_LABEL, "worker": r["worker"]}}
340
+
341
+ def insight(self) -> dict:
342
+ return {"host": HOST_LABEL, "version": VERSION, "up_s": int(time.time() - self.started),
343
+ "workers": len(self.workers), "lending": sum(1 for w in self.workers.values() if not w.paused),
344
+ "queue": len(self.queue), "models": list(MODELS), "stats": dict(self.stats)}
345
+
346
+ def me(self, wallet: str) -> dict:
347
+ tokens = jobs = 0
348
+ if wallet and os.path.exists(self.ledger_path):
349
+ with open(self.ledger_path) as f:
350
+ for line in f:
351
+ try:
352
+ e = json.loads(line)
353
+ except ValueError:
354
+ continue
355
+ if e.get("wallet", "").lower() == wallet.lower():
356
+ tokens += int(e.get("tokens", 0))
357
+ jobs += 1
358
+ wei = tokens * WEI_PER_TOKEN
359
+ return {"wallet": wallet, "jobs": jobs, "tokens": tokens, "luv_wei": str(wei),
360
+ "luv": f"{wei // 10**18}.{wei % 10**18:018d}", "rule": "1 wei of SHAMBA LUV per generated token"}
361
+
362
+
363
+ # ── a minimal HTTP/1.1 server (stdlib asyncio) ───────────────────────────────────────────────────────────────────
364
+ def cors(origin: str) -> dict:
365
+ if origin in ALLOWED_ORIGINS or origin.endswith(".hf.space") or origin.startswith("http://127.0.0.1"):
366
+ return {"Access-Control-Allow-Origin": origin, "Vary": "Origin",
367
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
368
+ "Access-Control-Allow-Headers": "authorization, content-type",
369
+ "Access-Control-Max-Age": "600"}
370
+ return {}
371
+
372
+
373
+ async def handle(router: Router, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, trust_proxy: bool):
374
+ try:
375
+ head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 15)
376
+ except (asyncio.TimeoutError, asyncio.IncompleteReadError, asyncio.LimitOverrunError, ConnectionError):
377
+ writer.close()
378
+ return
379
+ lines = head.decode("latin-1").split("\r\n")
380
+ try:
381
+ method, target, _ = lines[0].split(" ", 2)
382
+ except ValueError:
383
+ writer.close()
384
+ return
385
+ h = {k.strip().lower(): v.strip() for k, v in (ln.split(":", 1) for ln in lines[1:] if ":" in ln)}
386
+ n = int(h.get("content-length") or 0)
387
+ status, out, extra = 200, {}, {}
388
+ ip = (h.get("x-forwarded-for", "").split(",")[0].strip() if trust_proxy else "") or \
389
+ (writer.get_extra_info("peername") or ("?",))[0]
390
+ path = urlsplit(target).path.rstrip("/") or "/"
391
+ for prefix in ("/draiml-dmind",): # served under a path on a shared vhost
392
+ if path.startswith(prefix):
393
+ path = path[len(prefix):] or "/"
394
+ try:
395
+ if n > MAX_BODY:
396
+ status, out = 413, {"error": "request too large"}
397
+ elif method == "OPTIONS":
398
+ status = 204
399
+ else:
400
+ body = json.loads(await reader.readexactly(n)) if n else {}
401
+ stream = bool(body.get("stream")) if isinstance(body, dict) else False
402
+ if method == "GET" and path in ("/", "/health", "/sharedcpu/health"):
403
+ out = {"ok": True, "host": HOST_LABEL, "version": VERSION}
404
+ elif method == "GET" and path == "/insight/sharedcpu":
405
+ out = router.insight()
406
+ elif method == "GET" and path in ("/v1/models", "/models"):
407
+ out = {"object": "list", "data": [{"id": m, "object": "model", "owned_by": HOST_LABEL} for m in MODELS]}
408
+ elif method == "GET" and path == "/sharedcpu/me":
409
+ out = router.me(parse_qs(urlsplit(target).query).get("wallet", [""])[0])
410
+ elif method == "POST" and path == "/sharedcpu/join":
411
+ out = router.join(body, ip)
412
+ elif method == "POST" and path == "/sharedcpu/update":
413
+ out = router.update(body)
414
+ elif method == "POST" and path == "/sharedcpu/pull":
415
+ out = await router.pull(body)
416
+ elif method == "POST" and path == "/sharedcpu/result":
417
+ out = router.result(body)
418
+ elif method == "POST" and path in ("/sharedcpu/decline", "/sharedcpu/fail"):
419
+ out = router.decline(body, failed=path.endswith("fail"))
420
+ elif method == "POST" and path == "/sharedcpu/leave":
421
+ out = router.leave(body)
422
+ elif method == "POST" and path in ("/v1/chat/completions", "/chat/completions"):
423
+ key = h.get("authorization", "").removeprefix("Bearer ").strip()
424
+ status, out = await router.complete(body, ip, key)
425
+ if stream and status == 200: # one SSE event with the whole answer, then [DONE]
426
+ msg = out["choices"][0]["message"]["content"]
427
+ chunk = {**out, "object": "chat.completion.chunk",
428
+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": msg}, "finish_reason": "stop"}]}
429
+ payload = f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n".encode()
430
+ hdr = {"Content-Type": "text/event-stream", "Cache-Control": "no-cache", **cors(h.get("origin", ""))}
431
+ writer.write(("HTTP/1.1 200 OK\r\n" + "".join(f"{k}: {v}\r\n" for k, v in hdr.items())
432
+ + f"Content-Length: {len(payload)}\r\nConnection: close\r\n\r\n").encode() + payload)
433
+ await writer.drain()
434
+ writer.close()
435
+ return
436
+ else:
437
+ status, out = 404, {"error": "not found"}
438
+ except (ValueError, TypeError) as e:
439
+ status, out = 400, {"error": f"bad request: {e}"}
440
+ except Exception as e: # never take the router down
441
+ status, out = 500, {"error": f"{type(e).__name__}"}
442
+ data = b"" if status == 204 else json.dumps(out).encode()
443
+ reason = {200: "OK", 204: "No Content", 400: "Bad Request", 401: "Unauthorized", 404: "Not Found", 413: "Too Large",
444
+ 429: "Too Many Requests", 500: "Error", 502: "Bad Gateway", 503: "Unavailable", 504: "Timeout"}.get(status, "OK")
445
+ hdr = {"Content-Type": "application/json", "Cache-Control": "no-store", **cors(h.get("origin", "")), **extra}
446
+ if status in (429, 503):
447
+ hdr["Retry-After"] = "30"
448
+ try:
449
+ writer.write((f"HTTP/1.1 {status} {reason}\r\n" + "".join(f"{k}: {v}\r\n" for k, v in hdr.items())
450
+ + f"Content-Length: {len(data)}\r\nConnection: close\r\n\r\n").encode() + data)
451
+ await writer.drain()
452
+ except ConnectionError:
453
+ pass
454
+ writer.close()
455
+
456
+
457
+ async def main() -> None:
458
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
459
+ ap.add_argument("--bind", default="127.0.0.1")
460
+ ap.add_argument("--port", type=int, default=4041)
461
+ ap.add_argument("--ledger", default="ledger.jsonl")
462
+ ap.add_argument("--keys", default=None, help="file of client keys (one per line); without it: open, rate-limited")
463
+ ap.add_argument("--trust-proxy", action="store_true", help="take the client IP from X-Forwarded-For")
464
+ a = ap.parse_args()
465
+ router = Router(a.ledger, a.keys)
466
+ server = await asyncio.start_server(lambda r, w: handle(router, r, w, a.trust_proxy), a.bind, a.port,
467
+ limit=MAX_BODY + 8192)
468
+ asyncio.create_task(router.maintain())
469
+ print(f"{HOST_LABEL} router {VERSION} on {a.bind}:{a.port}", flush=True)
470
+ async with server:
471
+ await server.serve_forever()
472
+
473
+
474
+ if __name__ == "__main__":
475
+ asyncio.run(main())
tests/test_router.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """drAIML.dmind router: delegation end to end with a simulated worker and client."""
2
+ import asyncio
3
+ import hashlib
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "router"))
9
+ import draiml_router as R # noqa: E402
10
+
11
+
12
+ async def http(port, method, path, body=None, origin=""):
13
+ r, w = await asyncio.open_connection("127.0.0.1", port)
14
+ data = json.dumps(body).encode() if body is not None else b""
15
+ hdr = f"{method} {path} HTTP/1.1\r\nHost: x\r\nContent-Length: {len(data)}\r\n"
16
+ if origin:
17
+ hdr += f"Origin: {origin}\r\n"
18
+ w.write((hdr + "\r\n").encode() + data)
19
+ await w.drain()
20
+ raw = await r.read()
21
+ w.close()
22
+ head, _, payload = raw.partition(b"\r\n\r\n")
23
+ lines = head.decode().split("\r\n")
24
+ status = int(lines[0].split()[1])
25
+ headers = {k.lower(): v.strip() for k, v in (ln.split(":", 1) for ln in lines[1:])}
26
+ return status, headers, (json.loads(payload) if payload and headers.get("content-type", "").startswith("application/json") else payload)
27
+
28
+
29
+ def receipt(text, sha=R.BONSAI_SHA256):
30
+ return {"response_sha256": hashlib.sha256(text.encode()).hexdigest(), "model_sha256": sha, "bankml": "0.4.2"}
31
+
32
+
33
+ async def scenario(tmp_path):
34
+ router = R.Router(str(tmp_path / "ledger.jsonl"))
35
+ server = await asyncio.start_server(lambda r, w: R.handle(router, r, w, False), "127.0.0.1", 0)
36
+ port = server.sockets[0].getsockname()[1]
37
+ out = {}
38
+
39
+ # no worker: the client is told to come back
40
+ s, h, j = await http(port, "POST", "/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]})
41
+ out["no_worker"] = (s, h.get("retry-after"))
42
+
43
+ # a worker joins with the wrong model, then the pinned one
44
+ s, _, j = await http(port, "POST", "/sharedcpu/join", {"model_sha256": "00" * 32})
45
+ out["wrong_model"] = j["ok"]
46
+ s, h, j = await http(port, "POST", "/draiml-dmind/sharedcpu/join",
47
+ {"model_sha256": R.BONSAI_SHA256, "share_pct": 10, "wallet": "0x" + "ab" * 20,
48
+ "engine": "browseml/draiml", "contributor": "browser"}, origin="https://pythai-draiml.static.hf.space")
49
+ out["cors"] = h.get("access-control-allow-origin")
50
+ session = j["session"]
51
+
52
+ async def worker(bad=False):
53
+ _, _, p = await http(port, "POST", "/sharedcpu/pull", {"session": session})
54
+ job = p["job"]
55
+ text = "Rest, ice and gentle movement."
56
+ rc = receipt("tampered" if bad else text)
57
+ _, _, r = await http(port, "POST", "/sharedcpu/result", {"session": session, "job": job["job"], "text": text,
58
+ "receipt": rc, "usage": {"completion_tokens": 7}})
59
+ return job, r
60
+
61
+ async def client():
62
+ return await http(port, "POST", "/v1/chat/completions",
63
+ {"messages": [{"role": "user", "content": "sprained ankle?"}], "max_tokens": 5000})
64
+
65
+ # a bad receipt is refused and the job is re-queued; the second try succeeds
66
+ c = asyncio.create_task(client())
67
+ await asyncio.sleep(0.1)
68
+ job, r_bad = await worker(bad=True)
69
+ out["bad_receipt"] = r_bad["ok"]
70
+ out["max_tokens_capped"] = job["max_tokens"]
71
+ job2, r_ok = await worker()
72
+ out["same_job_retried"] = job2["job"] == job["job"]
73
+ out["credited"] = r_ok["luv_wei"]
74
+ s, _, comp = await c
75
+ out["client"] = (s, comp["choices"][0]["message"]["content"], comp["bankml_receipt"]["model_sha256"] == R.BONSAI_SHA256)
76
+
77
+ s, _, me = await http(port, "GET", "/sharedcpu/me?wallet=0x" + "ab" * 20)
78
+ out["me"] = (me["tokens"], me["luv"])
79
+ s, _, ins = await http(port, "GET", "/insight/sharedcpu")
80
+ out["insight"] = (ins["workers"], ins["stats"].get("jobs_done"), ins["stats"].get("receipts_bad"))
81
+ await http(port, "POST", "/sharedcpu/leave", {"session": session})
82
+ s, _, ins = await http(port, "GET", "/insight/sharedcpu")
83
+ out["after_leave"] = ins["workers"]
84
+ server.close()
85
+ return out
86
+
87
+
88
+ def test_router_delegates_and_maintains(tmp_path):
89
+ out = asyncio.run(scenario(tmp_path))
90
+ assert out["no_worker"] == (503, "30")
91
+ assert out["wrong_model"] is False
92
+ assert out["cors"] == "https://pythai-draiml.static.hf.space"
93
+ assert out["bad_receipt"] is False and out["same_job_retried"]
94
+ assert out["max_tokens_capped"] == R.MAX_TOKENS
95
+ assert out["credited"] == "7"
96
+ assert out["client"] == (200, "Rest, ice and gentle movement.", True)
97
+ assert out["me"] == (7, "0.000000000000000007")
98
+ assert out["insight"] == (1, 1, 1)
99
+ assert out["after_leave"] == 0