File size: 13,820 Bytes
c181f01
 
 
 
 
 
 
 
 
0aee05c
c181f01
 
 
 
c9248c9
 
c181f01
 
 
 
 
 
 
 
 
34f6aa9
c181f01
34f6aa9
 
 
 
 
 
 
 
 
 
 
c181f01
 
 
 
 
 
 
 
 
 
 
5183bcd
 
c181f01
 
 
 
34f6aa9
 
c181f01
34f6aa9
 
c181f01
 
 
 
 
 
 
34f6aa9
 
 
c181f01
 
 
34f6aa9
 
c181f01
34f6aa9
 
 
 
 
c181f01
 
 
 
5183bcd
 
 
 
 
c181f01
 
 
 
 
 
 
 
c2caad6
 
 
 
c181f01
 
 
c2caad6
5183bcd
c181f01
 
c2caad6
c181f01
 
5183bcd
c181f01
34f6aa9
 
 
 
c181f01
34f6aa9
c181f01
5183bcd
 
c2caad6
 
 
c181f01
 
 
34f6aa9
c2caad6
 
 
c181f01
c2caad6
c181f01
 
 
 
 
 
c2caad6
 
c181f01
c2caad6
 
c9248c9
34f6aa9
 
c443a0e
 
5183bcd
c181f01
 
 
 
5183bcd
c181f01
 
 
 
 
c2caad6
c181f01
 
c2caad6
5183bcd
c181f01
 
 
34f6aa9
 
 
 
 
 
 
 
 
 
 
 
c181f01
 
c9248c9
34f6aa9
c181f01
0aee05c
c181f01
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// SPDX-License-Identifier: MIT
// drAIML · donate compute to drAIML.dmind. With the visitor's say-so (a toggle, 10% by default), this tab lends a
// share of its CPU, RAM and GPU to a distributed.mind host: the host hands it thinking jobs (chat completions), the
// browseML engine already loaded for Bonsai runs them exactly as sent, and its bankML receipt goes back with the
// 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
// visitor always comes first: a question of theirs, a hidden tab or a battery not charging pauses the lending.
//
// The wire protocol is dmind's, as browseML's share module speaks it (github.com/browseML/browseML, MIT):
//   POST /sharedcpu/join · /update (heartbeat) · /pull (long-poll) · /result · /decline · /leave.
// Reward: SHAMBA LUV only, 1 LUV per generated token, measured to 18 decimals (SCIEN·TIFIC).

const STORE = "draiml-dmind";
const SCALE = 10n ** 18n;
export const LUV = { token: "0x2711111111683B8708cb9a48cBf36a51315F8254", pair: "0x57D2085Aa859a145cB107845AD03c0eAAFBD8a31", tokenIs0: true };
const WEI_PER_TOKEN = 10n ** 18n;   // 1 SHAMBA LUV per generated token (router's rate)
const MODEL_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3";   // browseml/browseML/*.FORK.json

// ── 18-decimal arithmetic (SCIEN·TIFIC) ──────────────────────────────────────────────────────────────────────────
export const format18 = (x) => { const neg = x < 0n; if (neg) x = -x; return `${neg ? "-" : ""}${x / SCALE}.${(x % SCALE).toString().padStart(18, "0")}`; };
export function parse18(s) {
  const m = /^(\d+)(?:\.(\d{1,18}))?/.exec(String(s).trim());
  return m ? BigInt(m[1]) * SCALE + BigInt(((m[2] || "") + "0".repeat(18)).slice(0, 18)) : 0n;
}

// ── the ledger, kept in this browser ─────────────────────────────────────────────────────────────────────────────
const DEFAULTS = { tokens: 0n, jobs: 0, engineMs: 0, pct: 10, on: false, gpu: false, gpuPct: 25, jobTokens: 256 };
function readLedger() {
  try {
    const l = JSON.parse(localStorage.getItem(STORE) || "{}");
    return { ...DEFAULTS, ...l, tokens: BigInt(l.tokens || 0), on: !!l.on, gpu: !!l.gpu };
  } catch { return { ...DEFAULTS }; }
}

// ── login333 · drAIML: the signed-in wallet (Sign-In with Ethereum, verified by the router) ────────────────────
export const LOGIN_KEY = "draiml-login333";
export function login() {
  try { const s = JSON.parse(localStorage.getItem(LOGIN_KEY) || "null"); return s && s.token && s.exp * 1000 > Date.now() ? s : null; }
  catch { return null; }
}
function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }

// ── the sharing loop ─────────────────────────────────────────────────────────────────────────────────────────────
async function sha256hex(t) {
  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t)))].map((b) => b.toString(16).padStart(2, "0")).join("");
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export const restMs = (engineMs, pct) => Math.round(engineMs * (100 - pct) / pct);

export class Donor {
  constructor(engine, isVisitorBusy, onChange = () => {}) {
    this.onChange = onChange;         // (summary) => void: a live line for the page header
    this.engine = engine;             // () => Promise<browseml module>, loaded (the Agreement was accepted)
    this.busy = isVisitorBusy;        // () => boolean: the visitor's own question is running
    this.ledger = readLedger();
    this.host = null; this.session = ""; this.running = false; this.state = "off"; this.note = ""; this.wake = null;
    // measurement of this visit: when lending began, the engine's time on jobs, the last job's speeds
    this.m = { since: 0, engineMs: 0, jobs: 0, tokens: 0, promptTps: 0, genTps: 0, lastJob: 0, lastMs: 0 };
  }
  /** The engine's load options from the visitor's GPU choice. */
  engineOptions() { return this.ledger.gpu ? { gpu: "low-power", gpuTime: this.ledger.gpuPct } : { gpu: "off" }; }   // WebGPU power preference
  async config() {
    if (this.host) return this.host;
    try { this.host = await (await fetch(new URL("./dmind-host.json", import.meta.url), { cache: "no-cache" })).json(); }
    catch { this.host = { label: "drAIML.dmind", url: "" }; }
    return this.host;
  }
  async call(path, body, keepalive = false) {
    const h = this.host, s = login(), token = s ? s.token : "";
    const r = await fetch(h.url.replace(/\/$/, "") + path, { method: body === undefined ? "GET" : "POST", credentials: "omit", keepalive,
      headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
    if (r.status === 401 || r.status === 403) throw Object.assign(new Error("the host asks you to sign in to share"), { final: true });
    return r.json();
  }
  /** The visitor's confirmed share: on, CPU %, GPU on and its % of the card's time, the largest job (RAM). */
  settings({ on, pct, gpu, gpuPct, jobTokens }) {
    if (pct) this.ledger.pct = Math.max(5, Math.min(50, Math.round(pct / 5) * 5));
    if (gpu !== undefined) this.ledger.gpu = !!gpu;
    if (gpuPct) this.ledger.gpuPct = Math.max(25, Math.min(100, Math.round(gpuPct / 5) * 5));
    if (jobTokens) this.ledger.jobTokens = [128, 256, 512].includes(+jobTokens) ? +jobTokens : 256;
    if (on !== undefined) this.ledger.on = !!on;
    on = this.ledger.on; writeLedger(this.ledger);
    if (on && !this.running) this.start(); else if (!on && this.running) this.stop();
    if (this.session) this.call("/sharedcpu/update", { session: this.session, share_pct: this.ledger.pct }).catch(() => {});
    if (this.wake) this.wake();
  }
  emit() {
    const l = this.ledger;
    const what = { sharing: "❤️ lending", paused: "❤️ paused", waiting: "❤️ pledged", retrying: "❤️ reconnecting", stopped: "❤️ stopped" }[this.state];
    this.onChange(what && l.on ? `${what} ${l.pct}% · ${l.jobs} jobs · ${format18(l.tokens * WEI_PER_TOKEN)} LUV` : "", this.state);
  }
  pauseReason() {
    if (document.hidden) return "this tab is hidden";
    if (this.busy()) return "your own question comes first";
    if (this.battery && !this.battery.charging) return "on battery — sharing waits for the charger";
    return "";
  }
  async rest(ms) { await Promise.race([sleep(ms), new Promise((r) => { this.wake = r; })]); this.wake = null; }
  async start() {
    // each run has a generation: a stop() followed by a start() (sign-in, sign-out, GPU change) must not leave the old
    // loop running beside the new one
    const gen = this.gen = (this.gen || 0) + 1;
    const live = () => this.running && gen === this.gen;
    this.running = true;
    try { this.battery = navigator.getBattery ? await navigator.getBattery() : null; } catch { this.battery = null; }
    const h = await this.config();
    if (!live()) return;
    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; this.emit(); return; }
    const b = await this.engine();
    let backoff = 0;
    while (live()) {
      try {
        const why = this.pauseReason();
        if (why) { if (this.state !== "paused") { this.state = "paused"; this.emit(); } this.note = why; if (this.session) await this.call("/sharedcpu/update", { session: this.session, paused: true }).catch(() => {}); await this.rest(5000); continue; }
        if (!this.session) {
          const j = await this.call("/sharedcpu/join", { model: b.MODEL.name, model_sha256: MODEL_SHA256,
            threads: (b.loadStats && b.loadStats.threads) || 1, share_pct: this.ledger.pct, max_job_tokens: this.ledger.jobTokens,
            engine: "browseml/draiml", contributor: "browser",
            ...(b.gpuStatus ? { gpu: { name: String(b.gpuStatus.card || b.gpuStatus.name || "gpu"), share: this.ledger.gpuPct / 100 } } : {}) });
          if (!j.ok) throw Object.assign(new Error(`the host refused: ${j.reason || "no reason given"}`), { final: !!j.barred });
          this.session = String(j.session); this.wallet = j.wallet || ""; if (!this.m.since) this.m.since = Date.now();
        }
        if (this.state !== "sharing") { this.state = "sharing"; this.emit(); }
        this.note = `lending ${this.ledger.pct}% to ${h.label}`;
        const sess = this.session;
        const got = await this.call("/sharedcpu/pull", { session: sess });
        if (!live()) { if (got.job) await this.call("/sharedcpu/decline", { session: sess, job: got.job.job, reason: "stopped" }).catch(() => {}); break; }
        if (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });
        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; }
        const job = got.job; if (!job) continue;
        if (job.max_tokens > this.ledger.jobTokens) job.max_tokens = this.ledger.jobTokens;   // the visitor's RAM limit
        // the long poll can last 25 s: the tab may have been hidden or the charger unplugged meanwhile
        const late = this.pauseReason();
        if (late) { await this.call("/sharedcpu/decline", { session: sess, job: job.job, reason: late }).catch(() => {}); continue; }
        let cancelled = false;
        const beat = setInterval(() => { this.call("/sharedcpu/update", { session: sess }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);
        const t0 = performance.now(); let text = "", res;
        try { res = await b.chat({ messages: job.messages, max_tokens: job.max_tokens, temperature: job.temperature }, (p) => { text += p; }); }
        finally { clearInterval(beat); }
        const ms = performance.now() - t0;
        if (cancelled) continue;
        const rc = res && res.bankml_receipt;
        if (!rc || (await sha256hex(text)) !== rc.response_sha256) { await this.call("/sharedcpu/fail", { session: sess, job: job.job, reason: "receipt did not match" }).catch(() => {}); continue; }
        const r = await this.call("/sharedcpu/result", { session: sess, job: job.job, text, receipt: rc, usage: res.usage, timings: res.timings });
        if (r.ok) {
          // count what the host credited (it bounds the claim, and answering your own question earns nothing)
          const n = BigInt(r.credited_tokens ?? ((res.usage && res.usage.completion_tokens) || 0));
          this.ledger.tokens += n; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);
          const t = res.timings || {};
          Object.assign(this.m, { engineMs: this.m.engineMs + ms, jobs: this.m.jobs + 1, tokens: this.m.tokens + Number(n),
            promptTps: t.prompt_per_second || 0, genTps: t.predicted_per_second || 0, lastJob: Date.now(), lastMs: ms,
            lastUncredited: r.uncredited || "" });
          this.emit();
        }
        backoff = 0;
        await this.rest(restMs(ms, this.ledger.pct));
      } catch (e) {
        if (e.final) { this.state = "stopped"; this.note = e.message; this.emit(); break; }
        backoff = Math.min(300000, backoff ? backoff * 2 : 5000);
        this.state = "retrying"; this.note = `${e.message || e} · again in ${backoff / 1000} s`;
        await this.rest(backoff);
      }
    }
    if (gen === this.gen) this.running = false;
  }
  stop() {
    this.gen = (this.gen || 0) + 1;
    this.running = false; this.state = "off"; this.note = ""; this.emit();
    if (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }
    if (this.wake) this.wake();
  }
  /** What this visit measured: the engine's threads and memory, the GPU, the duty cycle actually given. */
  async measure() {
    let b = null; try { b = await this.engine(); } catch {}
    const wall = this.m.since ? Date.now() - this.m.since : 0;
    return { threads: (b && b.loadStats && b.loadStats.threads) || 0, cores: navigator.hardwareConcurrency || 0,
             memoryMB: b ? Math.round(b.memoryBytes / 1048576) : 0, deviceMemoryGB: navigator.deviceMemory || null,
             gpu: b ? b.gpuStatus : null, gpuWanted: this.ledger.gpu, dutyPct: wall ? (100 * this.m.engineMs / wall) : 0,
             ...this.m, wallMs: wall };
  }
  /** The router's account for the signed-in wallet: earned, claimed, paid, available. */
  async earnings() { await this.config(); if (!login()) return null; return this.call("/sharedcpu/me"); }
  async claim() { await this.config(); return this.call("/sharedcpu/claim", {}); }
  async status() {
    const h = await this.config(), l = this.ledger;
    const luvWei = l.tokens * WEI_PER_TOKEN;
    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,
             jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),
             luv: format18(luvWei), luv_wei: luvWei.toString() };
  }
}