humuhumu33 Claude Opus 4.8 commited on
Commit
1f751a7
·
1 Parent(s): 0cbced2

Boot inside the κ-addressable holospace runtime from byte zero

Browse files

- index.html is now a byte-zero loader: installs a κ-runtime service worker, then steps into the app THROUGH it
- portal-sw.js = the κ-runtime: serves every same-origin member content-addressed, verify-on-read (blake3),
fail-closed (409 on any byte that does not re-derive to its κ), content-cached by hash → offline + instant on repeat
- app.html = the Bonsai app (former index.html), served & verified by the runtime; larger login ring, warm-visit
ring no longer disappears, em-dash removed from copy
- manifest.holo.json = the closure (17 κ-members); _shared/holo-blake3.mjs + holo-l5.mjs = σ-axis + L5 primitive
- .gitattributes: members are content-addressed → stored byte-exact (-text) so served bytes match their κ
- fail-open: no service worker or any boot error → the app still loads directly

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

Files changed (8) hide show
  1. .gitattributes +8 -0
  2. _shared/holo-blake3.mjs +128 -0
  3. _shared/holo-l5.mjs +39 -0
  4. app.html +593 -0
  5. index.html +22 -582
  6. manifest.holo.json +76 -0
  7. portal-sw.js +56 -0
  8. q/holo-load2bit.mjs +141 -141
.gitattributes CHANGED
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+
37
+ # κ-portal members are content-addressed — store byte-exact (no EOL conversion) or verification 409s
38
+ *.html -text
39
+ *.js -text
40
+ *.mjs -text
41
+ *.json -text
42
+ *.svg -text
43
+ *.css -text
_shared/holo-blake3.mjs ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // holo-blake3.mjs — BLAKE3 (the hologram substrate's σ-axis, ADR-052), pure JS, lean +
2
+ // browser-native. This is the convergence seam made real: the substrate addresses content as
3
+ // `blake3:<hex>` = standard BLAKE3 of the canonical bytes (proven: its own differential test
4
+ // asserts the blake3 axis == the reference `blake3` crate). Reproducing standard BLAKE3 here —
5
+ // witnessed byte-identical against the substrate's own `kappa()` wasm across chunk boundaries —
6
+ // makes OS2 κ byte-identical to upstream WITHOUT a 6.5 MB wasm or restating substrate internals
7
+ // (BLAKE3 is the public standard the substrate itself consumes). Implements the official spec:
8
+ // 1024-byte chunks, 64-byte blocks, 7-round compression, binary tree of chaining values.
9
+
10
+ const IV = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
11
+ const MSG = [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8];
12
+ const CHUNK_START = 1, CHUNK_END = 2, PARENT = 4, ROOT = 8, BLOCK = 64, CHUNK = 1024;
13
+ const rotr = (x, n) => ((x >>> n) | (x << (32 - n))) >>> 0;
14
+
15
+ function g(v, a, b, c, d, mx, my) {
16
+ v[a] = (v[a] + v[b] + mx) >>> 0; v[d] = rotr(v[d] ^ v[a], 16);
17
+ v[c] = (v[c] + v[d]) >>> 0; v[b] = rotr(v[b] ^ v[c], 12);
18
+ v[a] = (v[a] + v[b] + my) >>> 0; v[d] = rotr(v[d] ^ v[a], 8);
19
+ v[c] = (v[c] + v[d]) >>> 0; v[b] = rotr(v[b] ^ v[c], 7);
20
+ }
21
+ function roundFn(v, m) {
22
+ g(v, 0, 4, 8, 12, m[0], m[1]); g(v, 1, 5, 9, 13, m[2], m[3]);
23
+ g(v, 2, 6, 10, 14, m[4], m[5]); g(v, 3, 7, 11, 15, m[6], m[7]);
24
+ g(v, 0, 5, 10, 15, m[8], m[9]); g(v, 1, 6, 11, 12, m[10], m[11]);
25
+ g(v, 2, 7, 8, 13, m[12], m[13]); g(v, 3, 4, 9, 14, m[14], m[15]);
26
+ }
27
+ // compress(cv[8], m[16], counter, blockLen, flags) → out[16]
28
+ function compress(cv, m0, counter, blockLen, flags) {
29
+ const cl = counter >>> 0, ch = Math.floor(counter / 4294967296) >>> 0;
30
+ const v = [cv[0], cv[1], cv[2], cv[3], cv[4], cv[5], cv[6], cv[7],
31
+ IV[0], IV[1], IV[2], IV[3], cl, ch, blockLen >>> 0, flags >>> 0];
32
+ let m = m0.slice();
33
+ for (let r = 0; r < 7; r++) { roundFn(v, m); if (r < 6) { const p = new Array(16); for (let i = 0; i < 16; i++) p[i] = m[MSG[i]]; m = p; } }
34
+ const out = new Array(16);
35
+ for (let i = 0; i < 8; i++) { out[i] = (v[i] ^ v[i + 8]) >>> 0; out[i + 8] = (v[i + 8] ^ cv[i]) >>> 0; }
36
+ return out;
37
+ }
38
+ // read a 64-byte block (zero-padded) into 16 LE u32 words
39
+ function words(bytes, off, len) {
40
+ const m = new Array(16).fill(0);
41
+ for (let i = 0; i < len; i++) m[i >> 2] |= bytes[off + i] << ((i & 3) * 8);
42
+ for (let i = 0; i < 16; i++) m[i] >>>= 0;
43
+ return m;
44
+ }
45
+
46
+ // An "output" node: its chaining value, or (with ROOT) its 32-byte hash.
47
+ function nodeChainingValue(o) { return compress(o.cv, o.m, o.counter, o.blockLen, o.flags).slice(0, 8); }
48
+ function nodeRootBytes(o) {
49
+ const out = compress(o.cv, o.m, 0, o.blockLen, o.flags | ROOT); // output block counter 0 → first 32 bytes
50
+ const b = new Uint8Array(32);
51
+ for (let i = 0; i < 8; i++) { const w = out[i]; b[i * 4] = w & 255; b[i * 4 + 1] = (w >>> 8) & 255; b[i * 4 + 2] = (w >>> 16) & 255; b[i * 4 + 3] = (w >>> 24) & 255; }
52
+ return b;
53
+ }
54
+
55
+ // One chunk (≤1024 bytes) → its output node (its last block carries CHUNK_END).
56
+ function chunkNode(bytes, start, len, counter) {
57
+ let cv = IV.slice();
58
+ const nBlocks = Math.max(1, Math.ceil(len / BLOCK));
59
+ let flags = CHUNK_START;
60
+ for (let i = 0; i < nBlocks - 1; i++) { cv = compress(cv, words(bytes, start + i * BLOCK, BLOCK), counter, BLOCK, flags).slice(0, 8); flags = 0; }
61
+ const lastOff = start + (nBlocks - 1) * BLOCK;
62
+ const lastLen = len - (nBlocks - 1) * BLOCK; // 0..64 (0 only when len==0)
63
+ return { cv, m: words(bytes, lastOff, lastLen), counter, blockLen: lastLen, flags: flags | CHUNK_END };
64
+ }
65
+ function parentNode(leftCV, rightCV) {
66
+ const m = leftCV.concat(rightCV);
67
+ return { cv: IV.slice(), m, counter: 0, blockLen: BLOCK, flags: PARENT };
68
+ }
69
+ // Hash a subtree [start, start+len) starting at chunk index `counter` → an output node.
70
+ function subtree(bytes, start, len, counter) {
71
+ if (len <= CHUNK) return chunkNode(bytes, start, len, counter);
72
+ let left = CHUNK; while (left * 2 < len) left *= 2; // largest power-of-two chunk span < len
73
+ const leftCV = nodeChainingValue(subtree(bytes, start, left, counter));
74
+ const rightCV = nodeChainingValue(subtree(bytes, start + left, len - left, counter + left / CHUNK));
75
+ return parentNode(leftCV, rightCV);
76
+ }
77
+
78
+ export function blake3(bytes) {
79
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
80
+ return nodeRootBytes(subtree(b, 0, b.length, 0));
81
+ }
82
+ export function blake3hex(bytes) {
83
+ const d = blake3(bytes); let s = "";
84
+ for (let i = 0; i < 32; i++) s += d[i].toString(16).padStart(2, "0");
85
+ return s;
86
+ }
87
+ // the hologram σ-axis κ-label: "blake3:" + 64 hex (the 71-byte ContentLabel).
88
+ export function kappaBlake3(bytes) { return "blake3:" + blake3hex(bytes); }
89
+
90
+ // ── tree internals (the σ-axis Merkle structure) ─────────────────────────────────────
91
+ // Exposed so holo-bao.mjs can build verified-streaming (Bao) proofs against the SAME ONE
92
+ // implementation (Law L2 — no second hash). These are the standard BLAKE3 tree pieces:
93
+ // a chunk → output node, two CVs → parent node, a node → its chaining value or ROOT bytes.
94
+ export const CHUNK_BYTES = CHUNK;
95
+ export { chunkNode, parentNode, nodeChainingValue, nodeRootBytes, subtree };
96
+
97
+ // ── incremental hasher (stream-mint without a tail pass) ─────────────────────────────
98
+ // BLAKE3's streaming Hasher: feed chunks via update(), get the SAME digest as one-shot blake3() at
99
+ // digest()/hex(). Buffers at most ONE 1024-byte chunk; each completed chunk's CV folds into a stack via the
100
+ // standard add-chunk-cv merge (collapse while the chunk count is even), and digest() merges the final chunk
101
+ // down the stack with the ROOT flag — the canonical left-balanced tree, byte-identical to blake3() across
102
+ // chunk boundaries. Lets the streaming seam mint a κ AS bytes arrive instead of re-hashing the whole buffer.
103
+ export function createBlake3() {
104
+ const stack = []; // CVs of completed left subtrees (bottom = leftmost)
105
+ let counter = 0; // index of the current chunk
106
+ const buf = new Uint8Array(CHUNK);
107
+ let bufLen = 0;
108
+ const add = (cv, totalChunks) => { let t = totalChunks, c = cv; while ((t & 1) === 0) { c = nodeChainingValue(parentNode(stack.pop(), c)); t >>= 1; } stack.push(c); };
109
+ const api = {
110
+ update(bytes) {
111
+ const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
112
+ let off = 0; const n = b.length;
113
+ while (off < n) {
114
+ if (bufLen === CHUNK) { const cv = nodeChainingValue(chunkNode(buf, 0, CHUNK, counter)); counter++; add(cv, counter); bufLen = 0; }
115
+ const take = Math.min(CHUNK - bufLen, n - off);
116
+ buf.set(b.subarray(off, off + take), bufLen); bufLen += take; off += take;
117
+ }
118
+ return api;
119
+ },
120
+ digest() {
121
+ let node = chunkNode(buf, 0, bufLen, counter);
122
+ for (let i = stack.length - 1; i >= 0; i--) node = parentNode(stack[i], nodeChainingValue(node));
123
+ return nodeRootBytes(node);
124
+ },
125
+ hex() { const d = api.digest(); let s = ""; for (let i = 0; i < 32; i++) s += d[i].toString(16).padStart(2, "0"); return s; },
126
+ };
127
+ return api;
128
+ }
_shared/holo-l5.mjs ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // holo-l5.mjs — THE verify-by-re-derivation primitive (Law L5), in one place. "Does this byte blob re-derive to
2
+ // this κ?" is the whole trust model of κ-Portal (source is irrelevant; the math admits). It was copied into the
3
+ // closure completeness check (holo-dotholo.verifyClosure) AND the delivery Service Worker (portal-sw) — now both
4
+ // call HERE. (The single-file portal inlines an equivalent check on purpose: that file must be dependency-free.)
5
+ // Pure + isomorphic; blake3 (the σ-axis) is wired by default, inject others to admit more axes. ────────────────
6
+ import { blake3hex } from "./holo-blake3.mjs";
7
+
8
+ const enc = (s) => new TextEncoder().encode(s);
9
+ const kappaOf = (v) => (typeof v === "string" ? v : v && v.kappa);
10
+ // parse did:holo:<algo>:<hex>, or a bare 64-hex (assumed blake3 — the canonical σ-axis)
11
+ const algoHexOf = (k) => { const s = String(k || ""); const m = /^did:holo:([a-z0-9]+):([0-9a-f]+)$/.exec(s); if (m) return { algo: m[1], hex: m[2] }; return /^[0-9a-f]{64}$/i.test(s) ? { algo: "blake3", hex: s.toLowerCase() } : null; };
12
+
13
+ // reDerives(bytes, kappa, {digests}) → bool. The atomic L5 check: re-hash the bytes on the κ's axis and compare.
14
+ // A κ whose axis has no digest → false (fail-closed; an unverifiable byte is never "trusted").
15
+ export async function reDerives(bytes, kappa, { digests = { blake3: blake3hex } } = {}) {
16
+ const ah = algoHexOf(kappa); if (!ah) return false;
17
+ const d = digests[ah.algo]; if (!d || bytes == null) return false;
18
+ return (await d(typeof bytes === "string" ? enc(bytes) : bytes)) === ah.hex;
19
+ }
20
+
21
+ // verifyMembers(members, resolve, {digests}) → the closure COMPLETENESS gate (fail-closed): re-derive EVERY member
22
+ // or refuse. members: path → κ (or {kappa}). resolve(path) → bytes|null (content-blind). Returns
23
+ // { ok, files, verified, missing, tampered, unverifiable }. (Exposed as holo-dotholo.verifyClosure.)
24
+ export async function verifyMembers(members, resolve, { digests = { blake3: blake3hex } } = {}) {
25
+ const missing = [], tampered = [], unverifiable = []; let verified = 0;
26
+ const paths = Object.keys(members);
27
+ for (const p of paths) {
28
+ const ah = algoHexOf(kappaOf(members[p]));
29
+ if (!ah || !digests[ah.algo]) { unverifiable.push(p); continue; }
30
+ let bytes; try { bytes = await resolve(p); } catch { bytes = null; }
31
+ if (bytes == null) { missing.push(p); continue; }
32
+ const hex = await digests[ah.algo](typeof bytes === "string" ? enc(bytes) : bytes);
33
+ if (hex !== ah.hex) { tampered.push(p); continue; }
34
+ verified++;
35
+ }
36
+ return { ok: missing.length === 0 && tampered.length === 0 && unverifiable.length === 0, files: paths.length, verified, missing, tampered, unverifiable };
37
+ }
38
+
39
+ export default { reDerives, verifyMembers };
app.html ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <meta charset="utf-8">
3
+ <meta name="viewport" content="width=device-width,initial-scale=1">
4
+ <title>Bonsai</title>
5
+ <style>
6
+ /* Claude-desktop look: warm charcoal stage, 11% hairlines, 12-14px radii, serif display.
7
+ NEUTRAL accent (was Claude coral): a premium bone fill on the charcoal — mono, sharp, calm.
8
+ Type floor is 15px everywhere. Everything fits ONE viewport at 1280×800 AND 375×812 (dvh + clamp). */
9
+ :root { --bg:#262624; --ink:#eceae4; --muted:#b8b5ad; --faint:rgba(232,230,224,.45);
10
+ --hair:rgba(255,255,255,.11);
11
+ --accent:#ece9e3; --accent-ink:#20201e; --accent-hi:#f7f5ef; --focus:rgba(255,255,255,.4);
12
+ --coral:var(--accent); --coral-hi:var(--muted); --lav:rgba(255,255,255,.5); --r:13px;
13
+ --serif:"Tiempos Text","Charter","Iowan Old Style",Georgia,serif; }
14
+ * { box-sizing:border-box; margin:0; padding:0; }
15
+ html,body { height:100%; }
16
+ body { background:var(--bg); color:var(--ink); font:15px/1.55 system-ui,-apple-system,"Segoe UI",Inter,sans-serif;
17
+ -webkit-font-smoothing:antialiased; overflow:hidden; }
18
+ .num { font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:15px; }
19
+ .stage { position:fixed; inset:0; height:100dvh; display:flex; flex-direction:column; align-items:center;
20
+ justify-content:center; padding:24px; opacity:0; pointer-events:none; transition:opacity .6s ease; }
21
+ .stage.on { opacity:1; pointer-events:auto; }
22
+
23
+ /* ── arrival: full-bleed hologram canvas behind left-aligned copy ── */
24
+ #arrive { flex-direction:row; align-items:center; justify-content:flex-start; padding:0; }
25
+ #holo { position:absolute; inset:0; width:100%; height:100%; display:block; }
26
+ #arrive .copy { position:relative; z-index:1; max-width:620px; padding:0 clamp(24px,6vw,96px); }
27
+ #arrive h1 { font-family:var(--serif); font-weight:500; font-size:clamp(40px,7vw,84px); line-height:1.06;
28
+ letter-spacing:-.015em; text-wrap:balance; }
29
+ #arrive .sub { margin-top:22px; font-size:clamp(18px,1.6vw,20px); line-height:1.5; color:var(--muted); max-width:46ch; }
30
+ #arrive button { margin-top:34px; background:var(--accent); border:none; color:var(--accent-ink); border-radius:999px;
31
+ padding:16px 34px; font:600 16px/1 system-ui,sans-serif; letter-spacing:-.01em; cursor:pointer;
32
+ transition:transform .2s ease, background .2s ease; }
33
+ #arrive button:hover { background:var(--accent-hi); transform:translateY(-1px); }
34
+ #arrive button:disabled { filter:saturate(.3) brightness(.8); cursor:default; transform:none; }
35
+ #arrive .fine { margin-top:16px; font-size:15px; color:var(--faint); }
36
+ @media (max-width:760px) { /* stacked: hologram floats in the upper half, copy anchors low */
37
+ #arrive { align-items:flex-end; }
38
+ #arrive .copy { padding-bottom:max(44px, env(safe-area-inset-bottom, 0px) + 36px); }
39
+ }
40
+
41
+ /* ── chat: the Claude-desktop room — serif greeting, ONE centered input card, quiet metrics ── */
42
+ #chat { justify-content:center; padding:0; }
43
+ #chat .col { display:flex; flex-direction:column; width:min(100%,760px); height:100%; padding:0 22px; justify-content:center; }
44
+ #chat .col.started { justify-content:flex-start; }
45
+ #hello { text-align:center; margin-bottom:26px; }
46
+ #hello .mark { display:inline-block; width:30px; height:30px; vertical-align:-4px; margin-right:12px; color:var(--coral); }
47
+ #hello h2 { display:inline; font-family:var(--serif); font-weight:500; font-size:clamp(30px,4.4vw,44px); letter-spacing:-.01em; }
48
+ .col.started #hello { display:none; }
49
+ #log { display:none; }
50
+ .col.started #log { display:block; flex:1; overflow-y:auto; padding:30px 4px 16px;
51
+ scrollbar-width:none; -ms-overflow-style:none; } /* the content scrolls; no chrome */
52
+ #log::-webkit-scrollbar { width:0; height:0; }
53
+ .msg { margin:0 0 22px; }
54
+ .msg .who { font-size:15px; color:var(--faint); margin-bottom:4px; }
55
+ .msg.user { display:flex; justify-content:flex-end; } /* Grok/Claude: user turn is a right bubble */
56
+ .msg.user .who { display:none; }
57
+ .msg.user .body { background:rgba(255,255,255,.05); border:1px solid var(--hair); border-radius:16px 16px 4px 16px;
58
+ padding:11px 16px; max-width:78%; }
59
+ .msg .body { white-space:pre-wrap; font-size:16px; line-height:1.65; }
60
+ /* "Thought for Ns" — a quiet collapsible reasoning header (Grok's signature, in Claude's palette) */
61
+ details.think { margin:0 0 10px; }
62
+ details.think summary { list-style:none; cursor:pointer; font-size:15px; color:var(--faint);
63
+ display:inline-flex; align-items:center; gap:7px; user-select:none; }
64
+ details.think summary::-webkit-details-marker { display:none; }
65
+ details.think summary .chev { transition:transform .2s ease; font-size:11px; }
66
+ details.think[open] summary .chev { transform:rotate(90deg); }
67
+ details.think .t { color:var(--faint); font-size:15px; line-height:1.6; white-space:pre-wrap; margin-top:8px;
68
+ border-left:2px solid var(--hair); padding-left:12px; }
69
+ /* assistant action row: copy · regenerate (appears when the answer settles) */
70
+ .acts { display:flex; gap:4px; margin-top:8px; opacity:0; transition:opacity .25s ease; }
71
+ .msg:hover .acts, .acts.shown { opacity:1; }
72
+ .acts button { background:none; border:none; color:var(--faint); cursor:pointer; border-radius:8px;
73
+ width:30px; height:30px; display:grid; place-items:center; transition:background .15s, color .15s; }
74
+ .acts button:hover { background:rgba(255,255,255,.06); color:var(--ink); }
75
+ .acts button svg { width:16px; height:16px; stroke:currentColor; fill:none; stroke-width:1.7; }
76
+ .acts .ok { color:var(--coral-hi); }
77
+ /* follow-up suggestions: Grok's placement — borderless rows stacked in the conversation flow */
78
+ .fu { display:flex; flex-direction:column; margin:14px 0 4px; }
79
+ .fu button { display:flex; align-items:center; gap:12px; background:none; border:none; border-top:1px solid transparent;
80
+ color:var(--muted); font-size:16px; text-align:left; padding:11px 6px; cursor:pointer;
81
+ border-radius:10px; transition:background .15s, color .15s; }
82
+ .fu button:hover { background:rgba(255,255,255,.045); color:var(--ink); }
83
+ .fu .arr { color:var(--faint); font-size:15px; flex:none; }
84
+ .note { text-align:center; font-size:15px; color:var(--faint); margin:6px 0 12px; }
85
+ #card { background:rgba(255,255,255,.03); border:1px solid var(--hair); border-radius:18px; padding:6px 8px 8px; }
86
+ #card:focus-within { border-color:var(--focus); }
87
+ #inp { width:100%; background:none; border:none; color:var(--ink); padding:14px 12px 10px;
88
+ font:16px/1.45 system-ui,sans-serif; outline:none; }
89
+ #cardrow { display:flex; align-items:center; gap:12px; padding:0 8px 4px 12px; }
90
+ #modelname { font-size:15px; color:var(--muted); }
91
+ #cardrow .grow { flex:1; }
92
+ #send { background:var(--accent); border:none; color:var(--accent-ink); border-radius:999px; width:38px; height:38px;
93
+ font:500 17px/1 system-ui,sans-serif; cursor:pointer; transition:background .2s ease; }
94
+ #send:hover { background:var(--accent-hi); }
95
+ #send:disabled { background:rgba(255,255,255,.06); color:var(--faint); cursor:default; }
96
+ #metrics { text-align:center; font-size:15px; color:var(--faint); padding:12px 0 16px; min-height:22px; }
97
+ #metrics b { color:var(--muted); font-weight:500; }
98
+ #err { color:#f87171; font-size:15px; padding:0 0 18px; text-align:center; white-space:pre-wrap; }
99
+ .spn { display:inline-block; width:1.1ch; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
100
+ color:var(--coral-hi); margin-right:7px; }
101
+ /* CSS hologram (fallback when WebGL is unavailable/blocked): layered orb + scanlines + drift */
102
+ #holofb { position:absolute; width:min(46vw,520px); aspect-ratio:1; right:4vw; top:50%;
103
+ transform:translateY(-50%); border-radius:50%; pointer-events:none;
104
+ background:radial-gradient(circle at 38% 34%, rgba(255,255,255,.5), rgba(206,204,198,.22) 42%, rgba(255,255,255,.1) 72%, transparent 76%);
105
+ box-shadow:0 0 90px rgba(255,255,255,.14), inset 0 0 60px rgba(255,255,255,.12);
106
+ animation:holofloat 7s ease-in-out infinite; }
107
+ #holofb::before { content:""; position:absolute; inset:0; border-radius:50%;
108
+ background:repeating-linear-gradient(to bottom, rgba(255,255,255,.09) 0 2px, transparent 2px 7px);
109
+ mix-blend-mode:screen; animation:holoscan 2.6s linear infinite;
110
+ -webkit-mask:radial-gradient(circle, #000 70%, transparent 74%); mask:radial-gradient(circle, #000 70%, transparent 74%); }
111
+ #holofb::after { content:""; position:absolute; inset:-2%; border-radius:50%;
112
+ border:1px solid rgba(255,255,255,.25); filter:blur(.4px); }
113
+ @keyframes holofloat { 50% { transform:translateY(calc(-50% - 14px)); } }
114
+ @keyframes holoscan { to { background-position:0 7px; } }
115
+ @media (max-width:760px){ #holofb { right:50%; top:26%; transform:translate(50%,-50%); width:min(62vw,300px); }
116
+ @keyframes holofloat { 50% { transform:translate(50%,calc(-50% - 10px)); } } }
117
+ @media (prefers-reduced-motion: reduce){ #holofb, #holofb::before { animation:none; } }
118
+ </style>
119
+ <body>
120
+
121
+ <div class="stage on" id="arrive">
122
+ <canvas id="holo"></canvas>
123
+ <div id="holofb" hidden></div>
124
+ <div class="copy">
125
+ <h1>An AI<br>that&rsquo;s yours.</h1>
126
+ <p class="sub">It runs entirely on your device. Private, and works offline.</p>
127
+ <button id="go">Start chatting</button>
128
+ <div class="fine" id="fine">Free. No account, nothing to install.</div>
129
+ </div>
130
+ </div>
131
+
132
+ <div class="stage" id="chat">
133
+ <div class="col" id="col">
134
+ <div id="hello">
135
+ <svg class="mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" aria-hidden="true"><path d="M12 3v18M3 12h18M5.6 5.6l12.8 12.8M18.4 5.6L5.6 18.4"/></svg><h2>Ready when you are.</h2>
136
+ </div>
137
+ <div id="log"></div>
138
+ <div id="card">
139
+ <input id="inp" placeholder="Ask anything" autocomplete="off">
140
+ <div id="cardrow">
141
+ <span id="modelname">Bonsai</span>
142
+ <span class="grow"></span>
143
+ <button id="send" aria-label="Send">&uarr;</button>
144
+ </div>
145
+ </div>
146
+ <div id="metrics">on your device</div>
147
+ <div id="err" hidden></div>
148
+ </div>
149
+ </div>
150
+
151
+ <script type="module">
152
+ // ── the OS boot animation, verbatim look ─────────────────────────────────────────────────────
153
+ // This is the SAME animation the OS greeter shows on its login screen (holo-plymouth.mjs): the
154
+ // abstract_ring Plymouth theme — a dense torus of dark spheres cycling progress-0..40.png at
155
+ // 25 fps — streamed progressively from the same public pack the OS streams from
156
+ // (adi1090x/plymouth-themes, GPL-3.0 artwork), cached in the Cache API so every return visit
157
+ // paints instantly and offline. Each frame's baked-black background is CHROMA-KEYED to
158
+ // transparent on decode (the greeter's keyBlack, verbatim), so the emblem floats over the stage
159
+ // with no black box — identical to the login screen.
160
+ const cv = document.getElementById("holo");
161
+ const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
162
+ window.__holoOff = null;
163
+ try {
164
+ const N = 41, FPS = 25;
165
+ const url = (i) => "https://raw.githubusercontent.com/adi1090x/plymouth-themes/master/pack_1/abstract_ring/progress-" + i + ".png";
166
+ const ctx = cv.getContext("2d");
167
+ const frames = new Array(N).fill(null);
168
+ let have = 0, dead = false, raf = 0;
169
+ // Plymouth sprites bake their black screen into the PNG; over the stage that black must be AIR.
170
+ // keyBlack (holo-plymouth.mjs, verbatim ramp) fades near-black pixels to transparent → the ring
171
+ // floats on the charcoal exactly like the greeter's emblem floats on the login wall.
172
+ const keyBlack = (bmp) => {
173
+ try {
174
+ const w = bmp.width, h = bmp.height; if (!w || !h) return bmp;
175
+ const c = document.createElement("canvas"); c.width = w; c.height = h;
176
+ const x = c.getContext("2d", { willReadFrequently: true });
177
+ x.drawImage(bmp, 0, 0);
178
+ const d = x.getImageData(0, 0, w, h), p = d.data;
179
+ for (let i = 0; i < p.length; i += 4) {
180
+ const v = Math.max(p[i], p[i + 1], p[i + 2]);
181
+ if (v < 48) p[i + 3] = Math.min(p[i + 3], Math.max(0, ((v - 12) / 36) * 255) | 0);
182
+ }
183
+ x.putImageData(d, 0, 0);
184
+ return c;
185
+ } catch { return bmp; }
186
+ };
187
+ const cachePromise = caches.open("holo-plymouth-v1").catch(() => null);
188
+ const loadFrame = async (i) => {
189
+ try {
190
+ const cache = await cachePromise;
191
+ let resp = cache && await cache.match(url(i));
192
+ if (!resp) { resp = await fetch(url(i)); if (cache && resp.ok) { try { await cache.put(url(i), resp.clone()); } catch {} } }
193
+ if (!resp || !resp.ok) return;
194
+ frames[i] = keyBlack(await createImageBitmap(await resp.blob()));
195
+ have++;
196
+ } catch {}
197
+ };
198
+ // frame 0 first (first paint), then the rest with small concurrency — plays as it arrives
199
+ await loadFrame(0);
200
+ (async () => { let i = 1; const w = async () => { while (i < N && !dead) { const k = i++; await loadFrame(k); } };
201
+ await Promise.all([w(), w(), w(), w()]); })();
202
+ const size = () => { cv.width = innerWidth * Math.min(devicePixelRatio || 1, 2); cv.height = innerHeight * Math.min(devicePixelRatio || 1, 2); };
203
+ size(); addEventListener("resize", size);
204
+ let f = 0, last = 0;
205
+ const draw = (t) => {
206
+ if (dead) return;
207
+ raf = requestAnimationFrame(draw);
208
+ if (t - last < 1000 / FPS) return; last = t;
209
+ if (!reduced) { f = (f + 1) % N; }
210
+ let img = frames[f]; if (!img) { for (let k = 0; k < N; k++) if (frames[k]) { img = frames[k]; break; } }
211
+ if (!img) return;
212
+ ctx.clearRect(0, 0, cv.width, cv.height);
213
+ const desktop = cv.width / cv.height > 0.92;
214
+ const s = Math.min(cv.width, cv.height) * (desktop ? 0.84 : 0.72) / Math.max(img.width, img.height);
215
+ const w = img.width * s, h = img.height * s;
216
+ const x = desktop ? cv.width * 0.72 - w / 2 : cv.width / 2 - w / 2;
217
+ const y = desktop ? cv.height / 2 - h / 2 : cv.height * 0.28 - h / 2;
218
+ ctx.drawImage(img, x, y, w, h);
219
+ };
220
+ raf = requestAnimationFrame(draw);
221
+ document.addEventListener("visibilitychange", () => { if (dead) return; if (document.hidden) cancelAnimationFrame(raf); else raf = requestAnimationFrame(draw); });
222
+ window.__holoFrame = () => cv.toDataURL("image/png");
223
+ window.__holoOff = () => { dead = true; cancelAnimationFrame(raf); window.__holoFrame = null; cv.remove(); };
224
+ setTimeout(() => { if (!dead && have === 0) { const fb = document.getElementById("holofb"); if (fb) fb.hidden = false; } }, 4000); // no frames at all → CSS stand-in
225
+ } catch (e) {
226
+ const fb = document.getElementById("holofb"); if (fb) fb.hidden = false;
227
+ }
228
+ </script>
229
+
230
+ <script type="module">
231
+ import init, { qvac_load_gpu, qvac_gpu_free } from "./q/pkg/holospaces_web.js";
232
+ import { loadKappaObject } from "./q/holo-load2bit.mjs";
233
+ import { createQvacGPU } from "./q/qvac-gpu.js?v=68";
234
+ import { createEngine } from "./q/core/engine.js";
235
+
236
+ const $ = (id) => document.getElementById(id);
237
+ // braille pulse: one 80ms ticker animates every [data-spin] slot (loading, waking, thinking) —
238
+ // a single interval, zero layout work, stops mattering the instant the last spinner is removed.
239
+ const SPIN = ["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];
240
+ let _sf = 0;
241
+ setInterval(() => { const els = document.querySelectorAll("[data-spin]"); if (!els.length) return; const f = SPIN[_sf = (_sf + 1) % SPIN.length]; for (const el of els) el.textContent = f; }, 80);
242
+ const spn = () => `<span class="spn" data-spin>${SPIN[0]}</span>`;
243
+ const show = (id) => { for (const s of document.querySelectorAll(".stage")) s.classList.toggle("on", s.id === id); };
244
+ const short = (k) => String(k).replace(/^(did:holo:)?sha256:/, "").slice(0, 12) + "…";
245
+
246
+ // model source: ?src=<κ-object dir> for dev, HF mirror by default; ?m=27b flips to the 27B
247
+ // κ-object (engine support for its hybrid layers lands separately — the guard below is honest).
248
+ // Everything shown to the user (name, size) is READ FROM THE MANIFEST — swapping the κ URL is a
249
+ // zero-code model change. The manifest pin is the Law-L5 anchor.
250
+ const QS = new URLSearchParams(location.search);
251
+ const SRC = QS.get("src");
252
+ const DEFAULT_27B = false; // flips true the moment the hybrid engine passes parity (κ-object already published)
253
+ const M27 = QS.get("m") === "27b" || (DEFAULT_27B && QS.get("m") !== "8b");
254
+ const BASE = SRC || (M27 ? "https://huggingface.co/HOLOGRAMTECH/q-bonsai-27b/resolve/main" : "https://huggingface.co/HOLOGRAMTECH/q-bonsai-8b/resolve/main");
255
+ const PIN = M27 ? "did:holo:sha256:00beea03509a79f6567879f019c04bb15dda8721f6320f8295d9ea1dd9ba54af" : "did:holo:sha256:a0dc81f26ec5ce98b28ee9c1fab620e91c20720f777e1de6bc416317f54d27e2";
256
+ const CTX = 2048; // room for the reasoning trace + the answer on open-ended questions
257
+
258
+ let engine = null, gpu = null, rootK = "", warm = false, mind = [], thinkOpen = -1, thinkClose = -1;
259
+ let modelName = "Bonsai"; // set from the manifest once loaded
260
+ let story = [], memoryNote = ""; // the WHOLE conversation + the folded memory of its older part
261
+ const STORE = "bonsai.story.v1";
262
+ // ── O(1) κ-ANSWER MEMO (the hologram-runtime thesis, applied honestly) ────────────────────────
263
+ // Greedy decode is deterministic: the answer is a PURE FUNCTION of (model root κ, exact input token
264
+ // ids). So the answer is itself content-addressable. Key = sha256(rootκ · ids) → cached reply. A hit
265
+ // streams instantly and is BYTE-IDENTICAL to recomputing — repeated questions, and the model-authored
266
+ // follow-ups other visitors also click, become 0-latency. Persisted; survives reloads and works offline.
267
+ const MEMO = "bonsai.memo.v1";
268
+ let memoMap = null;
269
+ function memoLoad() { if (memoMap) return memoMap; try { memoMap = JSON.parse(localStorage.getItem(MEMO) || "{}"); } catch { memoMap = {}; } return memoMap; }
270
+ async function memoKey(ids) {
271
+ const b = new TextEncoder().encode(rootK + ":" + ids.join(","));
272
+ const h = await crypto.subtle.digest("SHA-256", b);
273
+ return [...new Uint8Array(h)].slice(0, 16).map((x) => x.toString(16).padStart(2, "0")).join("");
274
+ }
275
+ function memoSave(key, val) {
276
+ const m = memoLoad(); m[key] = val;
277
+ const ks = Object.keys(m); if (ks.length > 400) delete m[ks[0]]; // bounded FIFO
278
+ try { localStorage.setItem(MEMO, JSON.stringify(m)); } catch {}
279
+ }
280
+ function persistStory() {
281
+ try { localStorage.setItem(STORE, JSON.stringify({ story: story.slice(-200), memoryNote })); } catch {}
282
+ }
283
+ // fold everything so far into a compact memory the model writes for itself (bounded, abortable-free:
284
+ // runs inside send() before the next turn, with the braille pulse narrating it)
285
+ async function foldMemory() {
286
+ const recent = story.slice(-8).map((t) => `Q: ${t.q}
287
+ A: ${t.a.slice(0, 300)}`).join("\n");
288
+ const prior = memoryNote ? "Earlier memory: " + memoryNote + "\n\n" : "";
289
+ const ask = prior + "Recent conversation:\n" + recent + "\n\nFold ALL of the above into one memory note under 130 words. Keep every name, number, decision and open question. Write only the note.";
290
+ const ids = engine.tokenize(engine.frameTurn(ask, false));
291
+ const res = await engine.generate(ids, { maxNew: 300 });
292
+ const seg = splitThink(res.outIds || []);
293
+ const text = (seg.ans.length ? engine.detokenize(seg.ans) : res.text || "").trim();
294
+ return text.slice(0, 1200);
295
+ }
296
+
297
+ let entered = false, streamStarted = false;
298
+ async function stream() {
299
+ if (entered) { show("chat"); $("inp").focus(); } // welcome (and its living hologram) stays until the visitor enters
300
+ const t0 = performance.now();
301
+ const phase = (s) => { $("metrics").innerHTML = s; };
302
+ try {
303
+ if (!navigator.gpu) throw new Error("This browser has no WebGPU. Chrome or Edge 113+ required.");
304
+ // warm-load detect (honest offline copy): the κ-cache already holds the manifest → this visit is disk-speed.
305
+ try { const c = await caches.open("holo-kappa-v1"); warm = !!(await c.match(BASE + "/manifest.json")); } catch {}
306
+ phase(spn() + (warm ? "Waking up · from your device" : "Loading · verified as it arrives"));
307
+ await init();
308
+ // PARALLEL κ-BLOCKS FIRST (the measured Netflix path on CDN origins): 399 content-addressed
309
+ // blocks race over 12 connections (HF cdn-lfs caps a single stream ~2 MB/s; the parallel parts
310
+ // path measured 6.8 MB/s on the same line). The ONE-file .holo stays as the fallback for
311
+ // origins that only host the wafer (and its OPFS warm store makes revisits 0-network either way).
312
+ let r, pinned = true, holo = false;
313
+ try {
314
+ r = await loadKappaObject(BASE, { expectKappa: PIN, blake3: false });
315
+ } catch (e1) {
316
+ try {
317
+ const hs = await import("./q/core/holo-stream-load.mjs");
318
+ r = await hs.openHoloKappa(BASE + "/q-bonsai-8b.v1.holo", {});
319
+ holo = true; warm = !!r.warm;
320
+ } catch (e) { if (!SRC) throw e; pinned = false; r = await loadKappaObject(BASE, { allowUnpinned: true, blake3: false }); } // dev fallback only under ?src
321
+ }
322
+ rootK = (r.info && r.info.root) || PIN;
323
+ modelName = String((r.info && r.info.model) || "Bonsai").replace(/-/g, " ");
324
+ $("modelname").textContent = modelName;
325
+ // HONESTY GATE: the hybrid (27B) engine ships separately — never pretend to run what we can't.
326
+ if (r.manifest.hybrid) throw new Error(modelName + " uses a hybrid engine this build does not include yet. It is arriving; the 8B runs today.");
327
+ // progress = ONE quiet line under the input (per-tensor counters; no grid, no takeover)
328
+ const total = (r.manifest.tensors || []).length;
329
+ let done = 0, bytes = 0;
330
+ const tick = () => {
331
+ const dt = (performance.now() - t0) / 1000;
332
+ if (warm) phase(`${spn()}Waking up · ${Math.round(done / Math.max(total, 1) * 100)}%`);
333
+ else phase(`${spn()}Loading · <b>${(bytes / 1e6).toFixed(0)} MB</b> · ${(bytes / 1e6 / Math.max(dt, .1)).toFixed(1)} MB/s · verified as it arrives`);
334
+ };
335
+ const iv = setInterval(tick, 400);
336
+ const fetchT = async (name) => { // wrap fetchTensor: the progress driver
337
+ const b = await r.fetchTensor(name);
338
+ bytes += b.byteLength; done++;
339
+ return b;
340
+ };
341
+ // tokenizer header (arch + vocab) — embedded in the .holo (0 extra fetches), else same κ-object dir.
342
+ const hdr = r.tokenizerBytes || new Uint8Array(await (await fetch(BASE + "/tokenizer.gguf")).arrayBuffer());
343
+ const lr = JSON.parse(qvac_load_gpu(hdr));
344
+ if (lr.error) throw new Error("tokenizer: " + lr.error);
345
+ try { qvac_gpu_free(); } catch {}
346
+ r.manifest.kv4 = false; // exact f32 KV (the proven first-light config)
347
+ gpu = await createQvacGPU(r.manifest, fetchT, CTX, lr.eos ?? 2, false);
348
+ clearInterval(iv);
349
+ phase(spn() + "Almost ready");
350
+ const m = { fam: "Bonsai", name: modelName, size: "1.16 GB", fmt: "q1 1-bit κ", cap: 200, ctx: CTX, qwen: true, chat: true, rep: 1.05, gpu: true, gpuOnly: true };
351
+ engine = await createEngine(m, { gpu, info: lr, imageKappa: r.info.root });
352
+ // Qwen3 thinking markers are atomic tokens and clean() strips them from text — split by token id instead.
353
+ const o = engine.tokenize("<think>"), c2 = engine.tokenize("</think>");
354
+ thinkOpen = o.length === 1 ? o[0] : -1; thinkClose = c2.length === 1 ? c2[0] : -1;
355
+ enterChat();
356
+ } catch (e) {
357
+ $("metrics").textContent = ""; $("err").hidden = false;
358
+ $("err").textContent = String(e && e.message || e);
359
+ console.error(e);
360
+ }
361
+ }
362
+
363
+ // the ONLY chat metrics, one quiet line: model · time to first word · tok/s (operator spec)
364
+ let lastTTFT = null, lastTokps = null;
365
+ function metrics(state) {
366
+ const bits = [`<b>${modelName}</b>`];
367
+ if (lastTTFT != null) bits.push(`${lastTTFT.toFixed(1)}s to first word`);
368
+ if (lastTokps != null) bits.push(`<b>${lastTokps.toFixed(0)}</b> tokens a second`);
369
+ if (!lastTTFT && !lastTokps) bits.push(state || (warm ? "on your device · works offline" : "on your device"));
370
+ $("metrics").innerHTML = bits.join(" &nbsp;&middot;&nbsp; ");
371
+ }
372
+ let pendingQ = null, restored = false;
373
+ function restoreStory() {
374
+ if (restored) return; restored = true;
375
+ try {
376
+ const saved = JSON.parse(localStorage.getItem(STORE) || "null");
377
+ if (!saved || !saved.story || !saved.story.length) return;
378
+ story = saved.story; memoryNote = saved.memoryNote || "";
379
+ $("col").classList.add("started");
380
+ for (const t of story.slice(-12)) { // the room re-fills; the model remembers ALL of it via the fold
381
+ msg("You", "user").body.textContent = t.q;
382
+ msg(modelName, "bot").body.textContent = t.a;
383
+ }
384
+ if (!memoryNote && story.length) memoryNote = story.slice(-6).map((t) => `${t.q} → ${t.a.slice(0, 120)}`).join("; ").slice(0, 1200);
385
+ note("picked up where you left off");
386
+ log.scrollTop = log.scrollHeight;
387
+ } catch {}
388
+ }
389
+ function enterChat() {
390
+ ready = true; $("send").disabled = false; restoreStory(); metrics();
391
+ if (pendingQ) { $("inp").value = pendingQ; pendingQ = null; send(); }
392
+ else if (entered) $("inp").focus();
393
+ }
394
+
395
+ const log = $("log");
396
+ function msg(who, cls) {
397
+ const d = document.createElement("div"); d.className = "msg " + cls;
398
+ d.innerHTML = `<div class="who">${who}</div>`;
399
+ const think = document.createElement("details"); think.className = "think"; think.hidden = true;
400
+ think.innerHTML = `<summary><span class="chev">▸</span><span class="sum">thinking…</span></summary><div class="t"></div>`;
401
+ const body = document.createElement("div"); body.className = "body";
402
+ d.appendChild(think); d.appendChild(body);
403
+ let acts = null;
404
+ if (cls === "bot") { acts = document.createElement("div"); acts.className = "acts"; d.appendChild(acts); }
405
+ log.appendChild(d);
406
+ log.scrollTop = log.scrollHeight;
407
+ return { d, body, think, acts, t: think.querySelector(".t") };
408
+ }
409
+ const ICON = {
410
+ copy: '<svg viewBox="0 0 24 24"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>',
411
+ ok: '<svg viewBox="0 0 24 24"><path d="M5 13l4 4L19 7"/></svg>',
412
+ regen:'<svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v5h-5"/></svg>',
413
+ };
414
+ function iconBtn(html, title, fn) { const b = document.createElement("button"); b.type = "button"; b.title = title; b.innerHTML = html; b.onclick = fn; return b; }
415
+ // action row: copy the answer + regenerate the last turn (Grok's row, Claude's restraint)
416
+ function fitActions(ui, text, regen) {
417
+ if (!ui.acts) return; ui.acts.innerHTML = "";
418
+ const copy = iconBtn(ICON.copy, "Copy", async () => {
419
+ try { await navigator.clipboard.writeText(text); copy.classList.add("ok"); copy.innerHTML = ICON.ok;
420
+ setTimeout(() => { copy.classList.remove("ok"); copy.innerHTML = ICON.copy; }, 1200); } catch {}
421
+ });
422
+ ui.acts.appendChild(copy);
423
+ if (regen) ui.acts.appendChild(iconBtn(ICON.regen, "Regenerate", regen));
424
+ ui.acts.classList.add("shown");
425
+ }
426
+ // follow-ups AUTHORED BY THE MODEL about the actual exchange (Grok's behavior, done locally):
427
+ // one bounded extra generation right after the answer; killed instantly if the user starts typing.
428
+ let sugCtl = null;
429
+ async function offerFollowups(lastQ, lastA, host) {
430
+ try { if (sugCtl) sugCtl.abort(); } catch {}
431
+ sugCtl = new AbortController();
432
+ const ask = `Here is a conversation:
433
+ Question: ${lastQ}
434
+ Answer: ${lastA.slice(0, 600)}
435
+
436
+ Write exactly two short, sharp follow-up questions a curious person would ask next. One per line. No numbering, no preamble.`;
437
+ try {
438
+ const ids = engine.tokenize(engine.frameTurn(ask, false));
439
+ const res = await engine.generate(ids, { maxNew: 180, signal: sugCtl.signal });
440
+ const seg = splitThink(res.outIds || []);
441
+ const text = seg.ans.length ? engine.detokenize(seg.ans) : (res.text || "");
442
+ const qs = text.split(/\n+/).map((l) => l.replace(/^[-*\d.\s]+/, "").trim()).filter((l) => l.length > 8 && l.length < 140).slice(0, 2);
443
+ if (!qs.length || busy) return;
444
+ const box = document.createElement("div"); box.className = "fu";
445
+ for (const label of qs) {
446
+ const b = document.createElement("button"); b.type = "button";
447
+ b.innerHTML = `<span class="arr">↳</span>${label.replace(/[<>&]/g, "")}`;
448
+ b.onclick = () => { box.remove(); $("inp").value = label; send(); };
449
+ box.appendChild(b);
450
+ }
451
+ host.appendChild(box);
452
+ log.scrollTop = log.scrollHeight;
453
+ } catch {} // aborted / out of room → no suggestions, no noise
454
+ }
455
+ function note(s) { const d = document.createElement("div"); d.className = "note"; d.textContent = s; log.appendChild(d); }
456
+
457
+ // split streamed outIds into thinking + answer segments by the <think> token ids (robust: no
458
+ // tags at position 0 → everything is answer; unclosed → everything so far is thinking).
459
+ function splitThink(outIds) {
460
+ if (thinkOpen < 0 || outIds[0] !== thinkOpen) return { think: [], ans: outIds };
461
+ const c = outIds.indexOf(thinkClose);
462
+ if (c < 0) return { think: outIds.slice(1), ans: [] };
463
+ return { think: outIds.slice(1, c), ans: outIds.slice(c + 1) };
464
+ }
465
+
466
+ let busy = false, ready = false;
467
+ async function send() {
468
+ const q = $("inp").value.trim();
469
+ if (!q || busy) return;
470
+ if (!ready || !engine) { // the mind is still arriving: hold ONE question, it sends itself
471
+ pendingQ = q; $("inp").value = "";
472
+ $("col").classList.add("started");
473
+ msg("You", "user").body.textContent = q;
474
+ note("This sends as soon as Bonsai is ready.");
475
+ return;
476
+ }
477
+ busy = true; $("inp").value = ""; $("send").disabled = true;
478
+ $("col").classList.add("started"); // the greeting yields to the conversation (Claude-room transition)
479
+ msg("You", "user").body.textContent = q;
480
+ let turn = engine.tokenize(engine.frameTurn(q, mind.length > 0));
481
+ if (mind.length + turn.length + 384 > CTX) { // the window fills: the mind FOLDS its history, never drops it
482
+ $("metrics").innerHTML = spn() + "folding memory · nothing is forgotten";
483
+ try { memoryNote = await foldMemory(); persistStory(); } catch {}
484
+ mind = [];
485
+ }
486
+ let qEff = q;
487
+ if (!mind.length && memoryNote) qEff = `(What you remember of our conversation so far: ${memoryNote})
488
+
489
+ ${q}`;
490
+ if (!mind.length) turn = engine.tokenize(engine.frameTurn(qEff, false));
491
+ const ids = mind.concat(turn);
492
+ try { if (sugCtl) sugCtl.abort(); } catch {}
493
+ document.querySelectorAll(".fu").forEach((n) => n.remove());
494
+ const mindBefore = mind.slice();
495
+ const ui = msg(modelName, "bot"); ui.body.innerHTML = spn();
496
+ ui.think.querySelector("summary").innerHTML = spn() + `<span class="sum">thinking</span>`;
497
+ const tSend = performance.now(); let ttftSet = false, thoughtMs = 0;
498
+ lastTTFT = null; lastTokps = null;
499
+ // κ-MEMO HIT: identical (model, input) seen before → replay the exact answer, instantly. Honest:
500
+ // greedy is deterministic, so this is the same bytes recompute would produce, at O(1).
501
+ const mkey = await memoKey(ids);
502
+ const hit = memoLoad()[mkey];
503
+ if (hit) {
504
+ if (hit.think) { ui.think.hidden = false; ui.t.textContent = hit.think; }
505
+ ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${hit.secs || 1}s</span>`;
506
+ ui.body.textContent = hit.ans;
507
+ mind = ids.concat(hit.ansIds || engine.tokenize(hit.ans));
508
+ story.push({ q, a: hit.ans }); persistStory();
509
+ lastTTFT = (performance.now() - tSend) / 1000; lastTokps = null;
510
+ $("metrics").innerHTML = `<b>${modelName}</b> &nbsp;&middot;&nbsp; from memory &nbsp;&middot;&nbsp; content-addressed &nbsp;&middot;&nbsp; instant`;
511
+ fitActions(ui, hit.ans, () => { if (!busy) { mind = mindBefore; $("inp").value = q; send(); } });
512
+ offerFollowups(q, hit.ans, ui.d);
513
+ busy = false; $("send").disabled = false; $("inp").focus();
514
+ log.scrollTop = log.scrollHeight;
515
+ return;
516
+ }
517
+ $("metrics").innerHTML = spn() + `<b>${modelName}</b> is thinking`;
518
+ try {
519
+ const res = await engine.generate(ids, {
520
+ maxNew: CTX - ids.length - 8, // the whole remaining KV window (eos stops early)
521
+ onToken: (t) => {
522
+ if (!ttftSet) { ttftSet = true; lastTTFT = (performance.now() - tSend) / 1000; } // TTFT = send → first visible token
523
+ if (t.stats && t.stats.tokps) lastTokps = t.stats.tokps;
524
+ metrics();
525
+ const s = splitThink(t.outIds);
526
+ if (s.think.length) { ui.think.hidden = false; ui.t.textContent = engine.detokenize(s.think); }
527
+ if (s.ans.length && !thoughtMs) { thoughtMs = performance.now() - tSend; // answer flowing: freeze "Thought for Ns"
528
+ const secs = Math.max(1, Math.round(thoughtMs / 1000));
529
+ ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${secs}s</span>`; }
530
+ ui.body.textContent = s.ans.length ? engine.detokenize(s.ans) : (s.think.length ? "" : t.text);
531
+ log.scrollTop = log.scrollHeight;
532
+ },
533
+ });
534
+ const s = splitThink(res.outIds || []);
535
+ const secs = Math.max(1, Math.round((thoughtMs || (performance.now() - tSend)) / 1000));
536
+ ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${secs}s</span>`;
537
+ if (s.think.length) { ui.think.hidden = false; ui.t.textContent = engine.detokenize(s.think); }
538
+ if (s.ans.length) {
539
+ const answer = engine.detokenize(s.ans);
540
+ ui.body.textContent = answer;
541
+ mind = ids.concat(s.ans); // history carries the ANSWER only (Qwen3 convention: prior-turn thinking dropped)
542
+ story.push({ q, a: answer }); persistStory();
543
+ memoSave(mkey, { ans: answer, ansIds: s.ans, think: s.think.length ? engine.detokenize(s.think) : "", secs }); // κ-memo: this exact (model,input)→answer is now O(1)
544
+ fitActions(ui, answer, () => { if (!busy) { mind = mindBefore; $("inp").value = q; send(); } }); // regenerate: rewind history, re-ask
545
+ offerFollowups(q, answer, ui.d); // the model writes its own follow-ups, in place
546
+ } else if (s.think.length) {
547
+ ui.body.textContent = "I ran out of room while thinking. Ask again, a bit shorter."; // unclosed <think> at the window edge; turn not kept
548
+ } else {
549
+ ui.body.textContent = res.text;
550
+ mind = ids.concat(res.outIds || []);
551
+ }
552
+ if (res.stats && res.stats.tokps) lastTokps = res.stats.tokps;
553
+ metrics();
554
+ } catch (e) { ui.body.textContent = "Something broke: " + (e && e.message || e); }
555
+ busy = false; $("send").disabled = false; $("inp").focus();
556
+ log.scrollTop = log.scrollHeight;
557
+ }
558
+
559
+ $("go").addEventListener("click", () => {
560
+ entered = true;
561
+ try { if (window.__holoOff) { window.__holoOff(); window.__holoOff = null; } } catch {} // hand the hologram off — ONLY now, as the visitor enters (a warm engine load must never kill the welcome ring)
562
+ show("chat"); $("inp").focus();
563
+ if (!streamStarted) { streamStarted = true; stream(); }
564
+ });
565
+ $("send").disabled = true; // until the mind is resident (early questions queue)
566
+ (async () => {
567
+ try {
568
+ if (navigator.connection && navigator.connection.saveData) return; // respect data saver
569
+ if (SRC) return; // dev override: no background pulls
570
+ const B27 = "https://huggingface.co/HOLOGRAMTECH/q-bonsai-27b/resolve/main";
571
+ const cache = await caches.open("holo-kappa-v1");
572
+ const man = await (await fetch(B27 + "/manifest.json")).json();
573
+ const urls = Object.values(man.tensors || {}).map((r) => B27 + "/b/" + String(r.kappa).replace(":", "_") + ".gz");
574
+ let i = 0;
575
+ const worker = async () => {
576
+ while (i < urls.length) {
577
+ const u = urls[i++];
578
+ if (await cache.match(u)) continue;
579
+ while (streamStarted && !ready) await new Promise((r) => setTimeout(r, 1500)); // the live stream owns the wire
580
+ try { const b = await (await fetch(u, { cache: "no-store" })).arrayBuffer(); await cache.put(u, new Response(b, { headers: { "Content-Type": "application/octet-stream" } })); } catch {}
581
+ }
582
+ };
583
+ Promise.all(Array.from({ length: 3 }, worker)).catch(() => {});
584
+ } catch {}
585
+ })();
586
+ (async () => { // returning visitor: the mind wakes BEHIND the welcome screen
587
+ try { const c = await caches.open("holo-kappa-v1"); if (await c.match(BASE + "/manifest.json")) { streamStarted = true; stream(); } } catch {}
588
+ })();
589
+ $("send").addEventListener("click", send);
590
+ $("inp").addEventListener("keydown", (e) => { if (e.key === "Enter") send(); });
591
+ if (!navigator.gpu) { $("go").disabled = true; $("fine").textContent = "This browser has no WebGPU. Chrome or Edge 113 or newer required."; }
592
+ </script>
593
+ </body>
index.html CHANGED
@@ -2,592 +2,32 @@
2
  <meta charset="utf-8">
3
  <meta name="viewport" content="width=device-width,initial-scale=1">
4
  <title>Bonsai</title>
 
5
  <style>
6
- /* Claude-desktop look: warm charcoal stage, 11% hairlines, 12-14px radii, serif display.
7
- NEUTRAL accent (was Claude coral): a premium bone fill on the charcoal — mono, sharp, calm.
8
- Type floor is 15px everywhere. Everything fits ONE viewport at 1280×800 AND 375×812 (dvh + clamp). */
9
- :root { --bg:#262624; --ink:#eceae4; --muted:#b8b5ad; --faint:rgba(232,230,224,.45);
10
- --hair:rgba(255,255,255,.11);
11
- --accent:#ece9e3; --accent-ink:#20201e; --accent-hi:#f7f5ef; --focus:rgba(255,255,255,.4);
12
- --coral:var(--accent); --coral-hi:var(--muted); --lav:rgba(255,255,255,.5); --r:13px;
13
- --serif:"Tiempos Text","Charter","Iowan Old Style",Georgia,serif; }
14
- * { box-sizing:border-box; margin:0; padding:0; }
15
- html,body { height:100%; }
16
- body { background:var(--bg); color:var(--ink); font:15px/1.55 system-ui,-apple-system,"Segoe UI",Inter,sans-serif;
17
- -webkit-font-smoothing:antialiased; overflow:hidden; }
18
- .num { font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; font-size:15px; }
19
- .stage { position:fixed; inset:0; height:100dvh; display:flex; flex-direction:column; align-items:center;
20
- justify-content:center; padding:24px; opacity:0; pointer-events:none; transition:opacity .6s ease; }
21
- .stage.on { opacity:1; pointer-events:auto; }
22
-
23
- /* ── arrival: full-bleed hologram canvas behind left-aligned copy ── */
24
- #arrive { flex-direction:row; align-items:center; justify-content:flex-start; padding:0; }
25
- #holo { position:absolute; inset:0; width:100%; height:100%; display:block; }
26
- #arrive .copy { position:relative; z-index:1; max-width:620px; padding:0 clamp(24px,6vw,96px); }
27
- #arrive h1 { font-family:var(--serif); font-weight:500; font-size:clamp(40px,7vw,84px); line-height:1.06;
28
- letter-spacing:-.015em; text-wrap:balance; }
29
- #arrive .sub { margin-top:22px; font-size:clamp(18px,1.6vw,20px); line-height:1.5; color:var(--muted); max-width:46ch; }
30
- #arrive button { margin-top:34px; background:var(--accent); border:none; color:var(--accent-ink); border-radius:999px;
31
- padding:16px 34px; font:600 16px/1 system-ui,sans-serif; letter-spacing:-.01em; cursor:pointer;
32
- transition:transform .2s ease, background .2s ease; }
33
- #arrive button:hover { background:var(--accent-hi); transform:translateY(-1px); }
34
- #arrive button:disabled { filter:saturate(.3) brightness(.8); cursor:default; transform:none; }
35
- #arrive .fine { margin-top:16px; font-size:15px; color:var(--faint); }
36
- @media (max-width:760px) { /* stacked: hologram floats in the upper half, copy anchors low */
37
- #arrive { align-items:flex-end; }
38
- #arrive .copy { padding-bottom:max(44px, env(safe-area-inset-bottom, 0px) + 36px); }
39
- }
40
-
41
- /* ── chat: the Claude-desktop room — serif greeting, ONE centered input card, quiet metrics ── */
42
- #chat { justify-content:center; padding:0; }
43
- #chat .col { display:flex; flex-direction:column; width:min(100%,760px); height:100%; padding:0 22px; justify-content:center; }
44
- #chat .col.started { justify-content:flex-start; }
45
- #hello { text-align:center; margin-bottom:26px; }
46
- #hello .mark { display:inline-block; width:30px; height:30px; vertical-align:-4px; margin-right:12px; color:var(--coral); }
47
- #hello h2 { display:inline; font-family:var(--serif); font-weight:500; font-size:clamp(30px,4.4vw,44px); letter-spacing:-.01em; }
48
- .col.started #hello { display:none; }
49
- #log { display:none; }
50
- .col.started #log { display:block; flex:1; overflow-y:auto; padding:30px 4px 16px;
51
- scrollbar-width:none; -ms-overflow-style:none; } /* the content scrolls; no chrome */
52
- #log::-webkit-scrollbar { width:0; height:0; }
53
- .msg { margin:0 0 22px; }
54
- .msg .who { font-size:15px; color:var(--faint); margin-bottom:4px; }
55
- .msg.user { display:flex; justify-content:flex-end; } /* Grok/Claude: user turn is a right bubble */
56
- .msg.user .who { display:none; }
57
- .msg.user .body { background:rgba(255,255,255,.05); border:1px solid var(--hair); border-radius:16px 16px 4px 16px;
58
- padding:11px 16px; max-width:78%; }
59
- .msg .body { white-space:pre-wrap; font-size:16px; line-height:1.65; }
60
- /* "Thought for Ns" — a quiet collapsible reasoning header (Grok's signature, in Claude's palette) */
61
- details.think { margin:0 0 10px; }
62
- details.think summary { list-style:none; cursor:pointer; font-size:15px; color:var(--faint);
63
- display:inline-flex; align-items:center; gap:7px; user-select:none; }
64
- details.think summary::-webkit-details-marker { display:none; }
65
- details.think summary .chev { transition:transform .2s ease; font-size:11px; }
66
- details.think[open] summary .chev { transform:rotate(90deg); }
67
- details.think .t { color:var(--faint); font-size:15px; line-height:1.6; white-space:pre-wrap; margin-top:8px;
68
- border-left:2px solid var(--hair); padding-left:12px; }
69
- /* assistant action row: copy · regenerate (appears when the answer settles) */
70
- .acts { display:flex; gap:4px; margin-top:8px; opacity:0; transition:opacity .25s ease; }
71
- .msg:hover .acts, .acts.shown { opacity:1; }
72
- .acts button { background:none; border:none; color:var(--faint); cursor:pointer; border-radius:8px;
73
- width:30px; height:30px; display:grid; place-items:center; transition:background .15s, color .15s; }
74
- .acts button:hover { background:rgba(255,255,255,.06); color:var(--ink); }
75
- .acts button svg { width:16px; height:16px; stroke:currentColor; fill:none; stroke-width:1.7; }
76
- .acts .ok { color:var(--coral-hi); }
77
- /* follow-up suggestions: Grok's placement — borderless rows stacked in the conversation flow */
78
- .fu { display:flex; flex-direction:column; margin:14px 0 4px; }
79
- .fu button { display:flex; align-items:center; gap:12px; background:none; border:none; border-top:1px solid transparent;
80
- color:var(--muted); font-size:16px; text-align:left; padding:11px 6px; cursor:pointer;
81
- border-radius:10px; transition:background .15s, color .15s; }
82
- .fu button:hover { background:rgba(255,255,255,.045); color:var(--ink); }
83
- .fu .arr { color:var(--faint); font-size:15px; flex:none; }
84
- .note { text-align:center; font-size:15px; color:var(--faint); margin:6px 0 12px; }
85
- #card { background:rgba(255,255,255,.03); border:1px solid var(--hair); border-radius:18px; padding:6px 8px 8px; }
86
- #card:focus-within { border-color:var(--focus); }
87
- #inp { width:100%; background:none; border:none; color:var(--ink); padding:14px 12px 10px;
88
- font:16px/1.45 system-ui,sans-serif; outline:none; }
89
- #cardrow { display:flex; align-items:center; gap:12px; padding:0 8px 4px 12px; }
90
- #modelname { font-size:15px; color:var(--muted); }
91
- #cardrow .grow { flex:1; }
92
- #send { background:var(--accent); border:none; color:var(--accent-ink); border-radius:999px; width:38px; height:38px;
93
- font:500 17px/1 system-ui,sans-serif; cursor:pointer; transition:background .2s ease; }
94
- #send:hover { background:var(--accent-hi); }
95
- #send:disabled { background:rgba(255,255,255,.06); color:var(--faint); cursor:default; }
96
- #metrics { text-align:center; font-size:15px; color:var(--faint); padding:12px 0 16px; min-height:22px; }
97
- #metrics b { color:var(--muted); font-weight:500; }
98
- #err { color:#f87171; font-size:15px; padding:0 0 18px; text-align:center; white-space:pre-wrap; }
99
- .spn { display:inline-block; width:1.1ch; font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
100
- color:var(--coral-hi); margin-right:7px; }
101
- /* CSS hologram (fallback when WebGL is unavailable/blocked): layered orb + scanlines + drift */
102
- #holofb { position:absolute; width:min(46vw,520px); aspect-ratio:1; right:4vw; top:50%;
103
- transform:translateY(-50%); border-radius:50%; pointer-events:none;
104
- background:radial-gradient(circle at 38% 34%, rgba(255,255,255,.5), rgba(206,204,198,.22) 42%, rgba(255,255,255,.1) 72%, transparent 76%);
105
- box-shadow:0 0 90px rgba(255,255,255,.14), inset 0 0 60px rgba(255,255,255,.12);
106
- animation:holofloat 7s ease-in-out infinite; }
107
- #holofb::before { content:""; position:absolute; inset:0; border-radius:50%;
108
- background:repeating-linear-gradient(to bottom, rgba(255,255,255,.09) 0 2px, transparent 2px 7px);
109
- mix-blend-mode:screen; animation:holoscan 2.6s linear infinite;
110
- -webkit-mask:radial-gradient(circle, #000 70%, transparent 74%); mask:radial-gradient(circle, #000 70%, transparent 74%); }
111
- #holofb::after { content:""; position:absolute; inset:-2%; border-radius:50%;
112
- border:1px solid rgba(255,255,255,.25); filter:blur(.4px); }
113
- @keyframes holofloat { 50% { transform:translateY(calc(-50% - 14px)); } }
114
- @keyframes holoscan { to { background-position:0 7px; } }
115
- @media (max-width:760px){ #holofb { right:50%; top:26%; transform:translate(50%,-50%); width:min(62vw,300px); }
116
- @keyframes holofloat { 50% { transform:translate(50%,calc(-50% - 10px)); } } }
117
- @media (prefers-reduced-motion: reduce){ #holofb, #holofb::before { animation:none; } }
118
  </style>
119
- <body>
120
-
121
- <div class="stage on" id="arrive">
122
- <canvas id="holo"></canvas>
123
- <div id="holofb" hidden></div>
124
- <div class="copy">
125
- <h1>An AI<br>that&rsquo;s yours.</h1>
126
- <p class="sub">It runs entirely on your device. Private, and works offline.</p>
127
- <button id="go">Start chatting</button>
128
- <div class="fine" id="fine">Free. No account, nothing to install.</div>
129
- </div>
130
- </div>
131
-
132
- <div class="stage" id="chat">
133
- <div class="col" id="col">
134
- <div id="hello">
135
- <svg class="mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" aria-hidden="true"><path d="M12 3v18M3 12h18M5.6 5.6l12.8 12.8M18.4 5.6L5.6 18.4"/></svg><h2>Ready when you are.</h2>
136
- </div>
137
- <div id="log"></div>
138
- <div id="card">
139
- <input id="inp" placeholder="Ask anything" autocomplete="off">
140
- <div id="cardrow">
141
- <span id="modelname">Bonsai</span>
142
- <span class="grow"></span>
143
- <button id="send" aria-label="Send">&uarr;</button>
144
- </div>
145
- </div>
146
- <div id="metrics">on your device</div>
147
- <div id="err" hidden></div>
148
- </div>
149
- </div>
150
-
151
  <script type="module">
152
- // ── the OS boot animation, verbatim look ─────────────────────────────────────────────────────
153
- // This is the SAME animation the OS greeter shows on its login screen (holo-plymouth.mjs): the
154
- // abstract_ring Plymouth theme — a dense torus of dark spheres cycling progress-0..40.png at
155
- // 25 fps — streamed progressively from the same public pack the OS streams from
156
- // (adi1090x/plymouth-themes, GPL-3.0 artwork), cached in the Cache API so every return visit
157
- // paints instantly and offline. Each frame's baked-black background is CHROMA-KEYED to
158
- // transparent on decode (the greeter's keyBlack, verbatim), so the emblem floats over the stage
159
- // with no black box — identical to the login screen.
160
- const cv = document.getElementById("holo");
161
- const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
162
- window.__holoOff = null;
163
- try {
164
- const N = 41, FPS = 25;
165
- const url = (i) => "https://raw.githubusercontent.com/adi1090x/plymouth-themes/master/pack_1/abstract_ring/progress-" + i + ".png";
166
- const ctx = cv.getContext("2d");
167
- const frames = new Array(N).fill(null);
168
- let have = 0, dead = false, raf = 0;
169
- // Plymouth sprites bake their black screen into the PNG; over the stage that black must be AIR.
170
- // keyBlack (holo-plymouth.mjs, verbatim ramp) fades near-black pixels to transparent → the ring
171
- // floats on the charcoal exactly like the greeter's emblem floats on the login wall.
172
- const keyBlack = (bmp) => {
173
- try {
174
- const w = bmp.width, h = bmp.height; if (!w || !h) return bmp;
175
- const c = document.createElement("canvas"); c.width = w; c.height = h;
176
- const x = c.getContext("2d", { willReadFrequently: true });
177
- x.drawImage(bmp, 0, 0);
178
- const d = x.getImageData(0, 0, w, h), p = d.data;
179
- for (let i = 0; i < p.length; i += 4) {
180
- const v = Math.max(p[i], p[i + 1], p[i + 2]);
181
- if (v < 48) p[i + 3] = Math.min(p[i + 3], Math.max(0, ((v - 12) / 36) * 255) | 0);
182
- }
183
- x.putImageData(d, 0, 0);
184
- return c;
185
- } catch { return bmp; }
186
- };
187
- const cachePromise = caches.open("holo-plymouth-v1").catch(() => null);
188
- const loadFrame = async (i) => {
189
- try {
190
- const cache = await cachePromise;
191
- let resp = cache && await cache.match(url(i));
192
- if (!resp) { resp = await fetch(url(i)); if (cache && resp.ok) { try { await cache.put(url(i), resp.clone()); } catch {} } }
193
- if (!resp || !resp.ok) return;
194
- frames[i] = keyBlack(await createImageBitmap(await resp.blob()));
195
- have++;
196
- } catch {}
197
- };
198
- // frame 0 first (first paint), then the rest with small concurrency — plays as it arrives
199
- await loadFrame(0);
200
- (async () => { let i = 1; const w = async () => { while (i < N && !dead) { const k = i++; await loadFrame(k); } };
201
- await Promise.all([w(), w(), w(), w()]); })();
202
- const size = () => { cv.width = innerWidth * Math.min(devicePixelRatio || 1, 2); cv.height = innerHeight * Math.min(devicePixelRatio || 1, 2); };
203
- size(); addEventListener("resize", size);
204
- let f = 0, last = 0;
205
- const draw = (t) => {
206
- if (dead) return;
207
- raf = requestAnimationFrame(draw);
208
- if (t - last < 1000 / FPS) return; last = t;
209
- if (!reduced) { f = (f + 1) % N; }
210
- let img = frames[f]; if (!img) { for (let k = 0; k < N; k++) if (frames[k]) { img = frames[k]; break; } }
211
- if (!img) return;
212
- ctx.clearRect(0, 0, cv.width, cv.height);
213
- const desktop = cv.width / cv.height > 0.92;
214
- const s = Math.min(cv.width, cv.height) * (desktop ? 0.84 : 0.72) / Math.max(img.width, img.height);
215
- const w = img.width * s, h = img.height * s;
216
- const x = desktop ? cv.width * 0.72 - w / 2 : cv.width / 2 - w / 2;
217
- const y = desktop ? cv.height / 2 - h / 2 : cv.height * 0.28 - h / 2;
218
- ctx.drawImage(img, x, y, w, h);
219
- };
220
- raf = requestAnimationFrame(draw);
221
- document.addEventListener("visibilitychange", () => { if (dead) return; if (document.hidden) cancelAnimationFrame(raf); else raf = requestAnimationFrame(draw); });
222
- window.__holoFrame = () => cv.toDataURL("image/png");
223
- window.__holoOff = () => { dead = true; cancelAnimationFrame(raf); window.__holoFrame = null; cv.remove(); };
224
- setTimeout(() => { if (!dead && have === 0) { const fb = document.getElementById("holofb"); if (fb) fb.hidden = false; } }, 4000); // no frames at all → CSS stand-in
225
- } catch (e) {
226
- const fb = document.getElementById("holofb"); if (fb) fb.hidden = false;
227
- }
228
- </script>
229
-
230
- <script type="module">
231
- import init, { qvac_load_gpu, qvac_gpu_free } from "./q/pkg/holospaces_web.js";
232
- import { loadKappaObject } from "./q/holo-load2bit.mjs";
233
- import { createQvacGPU } from "./q/qvac-gpu.js?v=68";
234
- import { createEngine } from "./q/core/engine.js";
235
-
236
- const $ = (id) => document.getElementById(id);
237
- // braille pulse: one 80ms ticker animates every [data-spin] slot (loading, waking, thinking) —
238
- // a single interval, zero layout work, stops mattering the instant the last spinner is removed.
239
- const SPIN = ["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];
240
- let _sf = 0;
241
- setInterval(() => { const els = document.querySelectorAll("[data-spin]"); if (!els.length) return; const f = SPIN[_sf = (_sf + 1) % SPIN.length]; for (const el of els) el.textContent = f; }, 80);
242
- const spn = () => `<span class="spn" data-spin>${SPIN[0]}</span>`;
243
- const show = (id) => { for (const s of document.querySelectorAll(".stage")) s.classList.toggle("on", s.id === id); };
244
- const short = (k) => String(k).replace(/^(did:holo:)?sha256:/, "").slice(0, 12) + "…";
245
-
246
- // model source: ?src=<κ-object dir> for dev, HF mirror by default; ?m=27b flips to the 27B
247
- // κ-object (engine support for its hybrid layers lands separately — the guard below is honest).
248
- // Everything shown to the user (name, size) is READ FROM THE MANIFEST — swapping the κ URL is a
249
- // zero-code model change. The manifest pin is the Law-L5 anchor.
250
- const QS = new URLSearchParams(location.search);
251
- const SRC = QS.get("src");
252
- const DEFAULT_27B = false; // flips true the moment the hybrid engine passes parity (κ-object already published)
253
- const M27 = QS.get("m") === "27b" || (DEFAULT_27B && QS.get("m") !== "8b");
254
- const BASE = SRC || (M27 ? "https://huggingface.co/HOLOGRAMTECH/q-bonsai-27b/resolve/main" : "https://huggingface.co/HOLOGRAMTECH/q-bonsai-8b/resolve/main");
255
- const PIN = M27 ? "did:holo:sha256:00beea03509a79f6567879f019c04bb15dda8721f6320f8295d9ea1dd9ba54af" : "did:holo:sha256:a0dc81f26ec5ce98b28ee9c1fab620e91c20720f777e1de6bc416317f54d27e2";
256
- const CTX = 2048; // room for the reasoning trace + the answer on open-ended questions
257
-
258
- let engine = null, gpu = null, rootK = "", warm = false, mind = [], thinkOpen = -1, thinkClose = -1;
259
- let modelName = "Bonsai"; // set from the manifest once loaded
260
- let story = [], memoryNote = ""; // the WHOLE conversation + the folded memory of its older part
261
- const STORE = "bonsai.story.v1";
262
- // ── O(1) κ-ANSWER MEMO (the hologram-runtime thesis, applied honestly) ────────────────────────
263
- // Greedy decode is deterministic: the answer is a PURE FUNCTION of (model root κ, exact input token
264
- // ids). So the answer is itself content-addressable. Key = sha256(rootκ · ids) → cached reply. A hit
265
- // streams instantly and is BYTE-IDENTICAL to recomputing — repeated questions, and the model-authored
266
- // follow-ups other visitors also click, become 0-latency. Persisted; survives reloads and works offline.
267
- const MEMO = "bonsai.memo.v1";
268
- let memoMap = null;
269
- function memoLoad() { if (memoMap) return memoMap; try { memoMap = JSON.parse(localStorage.getItem(MEMO) || "{}"); } catch { memoMap = {}; } return memoMap; }
270
- async function memoKey(ids) {
271
- const b = new TextEncoder().encode(rootK + ":" + ids.join(","));
272
- const h = await crypto.subtle.digest("SHA-256", b);
273
- return [...new Uint8Array(h)].slice(0, 16).map((x) => x.toString(16).padStart(2, "0")).join("");
274
- }
275
- function memoSave(key, val) {
276
- const m = memoLoad(); m[key] = val;
277
- const ks = Object.keys(m); if (ks.length > 400) delete m[ks[0]]; // bounded FIFO
278
- try { localStorage.setItem(MEMO, JSON.stringify(m)); } catch {}
279
- }
280
- function persistStory() {
281
- try { localStorage.setItem(STORE, JSON.stringify({ story: story.slice(-200), memoryNote })); } catch {}
282
- }
283
- // fold everything so far into a compact memory the model writes for itself (bounded, abortable-free:
284
- // runs inside send() before the next turn, with the braille pulse narrating it)
285
- async function foldMemory() {
286
- const recent = story.slice(-8).map((t) => `Q: ${t.q}
287
- A: ${t.a.slice(0, 300)}`).join("\n");
288
- const prior = memoryNote ? "Earlier memory: " + memoryNote + "\n\n" : "";
289
- const ask = prior + "Recent conversation:\n" + recent + "\n\nFold ALL of the above into one memory note under 130 words. Keep every name, number, decision and open question. Write only the note.";
290
- const ids = engine.tokenize(engine.frameTurn(ask, false));
291
- const res = await engine.generate(ids, { maxNew: 300 });
292
- const seg = splitThink(res.outIds || []);
293
- const text = (seg.ans.length ? engine.detokenize(seg.ans) : res.text || "").trim();
294
- return text.slice(0, 1200);
295
- }
296
-
297
- let entered = false, streamStarted = false;
298
- async function stream() {
299
- if (entered) { show("chat"); $("inp").focus(); } // welcome (and its living hologram) stays until the visitor enters
300
- const t0 = performance.now();
301
- const phase = (s) => { $("metrics").innerHTML = s; };
302
- try {
303
- if (!navigator.gpu) throw new Error("This browser has no WebGPU. Chrome or Edge 113+ required.");
304
- // warm-load detect (honest offline copy): the κ-cache already holds the manifest → this visit is disk-speed.
305
- try { const c = await caches.open("holo-kappa-v1"); warm = !!(await c.match(BASE + "/manifest.json")); } catch {}
306
- phase(spn() + (warm ? "Waking up · from your device" : "Loading · verified as it arrives"));
307
- await init();
308
- // PARALLEL κ-BLOCKS FIRST (the measured Netflix path on CDN origins): 399 content-addressed
309
- // blocks race over 12 connections (HF cdn-lfs caps a single stream ~2 MB/s; the parallel parts
310
- // path measured 6.8 MB/s on the same line). The ONE-file .holo stays as the fallback for
311
- // origins that only host the wafer (and its OPFS warm store makes revisits 0-network either way).
312
- let r, pinned = true, holo = false;
313
- try {
314
- r = await loadKappaObject(BASE, { expectKappa: PIN, blake3: false });
315
- } catch (e1) {
316
- try {
317
- const hs = await import("./q/core/holo-stream-load.mjs");
318
- r = await hs.openHoloKappa(BASE + "/q-bonsai-8b.v1.holo", {});
319
- holo = true; warm = !!r.warm;
320
- } catch (e) { if (!SRC) throw e; pinned = false; r = await loadKappaObject(BASE, { allowUnpinned: true, blake3: false }); } // dev fallback only under ?src
321
- }
322
- rootK = (r.info && r.info.root) || PIN;
323
- modelName = String((r.info && r.info.model) || "Bonsai").replace(/-/g, " ");
324
- $("modelname").textContent = modelName;
325
- // HONESTY GATE: the hybrid (27B) engine ships separately — never pretend to run what we can't.
326
- if (r.manifest.hybrid) throw new Error(modelName + " uses a hybrid engine this build does not include yet. It is arriving; the 8B runs today.");
327
- // progress = ONE quiet line under the input (per-tensor counters; no grid, no takeover)
328
- const total = (r.manifest.tensors || []).length;
329
- let done = 0, bytes = 0;
330
- const tick = () => {
331
- const dt = (performance.now() - t0) / 1000;
332
- if (warm) phase(`${spn()}Waking up · ${Math.round(done / Math.max(total, 1) * 100)}%`);
333
- else phase(`${spn()}Loading · <b>${(bytes / 1e6).toFixed(0)} MB</b> · ${(bytes / 1e6 / Math.max(dt, .1)).toFixed(1)} MB/s · verified as it arrives`);
334
- };
335
- const iv = setInterval(tick, 400);
336
- const fetchT = async (name) => { // wrap fetchTensor: the progress driver
337
- const b = await r.fetchTensor(name);
338
- bytes += b.byteLength; done++;
339
- return b;
340
- };
341
- // tokenizer header (arch + vocab) — embedded in the .holo (0 extra fetches), else same κ-object dir.
342
- const hdr = r.tokenizerBytes || new Uint8Array(await (await fetch(BASE + "/tokenizer.gguf")).arrayBuffer());
343
- const lr = JSON.parse(qvac_load_gpu(hdr));
344
- if (lr.error) throw new Error("tokenizer: " + lr.error);
345
- try { qvac_gpu_free(); } catch {}
346
- r.manifest.kv4 = false; // exact f32 KV (the proven first-light config)
347
- gpu = await createQvacGPU(r.manifest, fetchT, CTX, lr.eos ?? 2, false);
348
- clearInterval(iv);
349
- phase(spn() + "Almost ready");
350
- const m = { fam: "Bonsai", name: modelName, size: "1.16 GB", fmt: "q1 1-bit κ", cap: 200, ctx: CTX, qwen: true, chat: true, rep: 1.05, gpu: true, gpuOnly: true };
351
- engine = await createEngine(m, { gpu, info: lr, imageKappa: r.info.root });
352
- // Qwen3 thinking markers are atomic tokens and clean() strips them from text — split by token id instead.
353
- const o = engine.tokenize("<think>"), c2 = engine.tokenize("</think>");
354
- thinkOpen = o.length === 1 ? o[0] : -1; thinkClose = c2.length === 1 ? c2[0] : -1;
355
- enterChat();
356
- } catch (e) {
357
- $("metrics").textContent = ""; $("err").hidden = false;
358
- $("err").textContent = String(e && e.message || e);
359
- console.error(e);
360
- }
361
- }
362
-
363
- // the ONLY chat metrics, one quiet line: model · time to first word · tok/s (operator spec)
364
- let lastTTFT = null, lastTokps = null;
365
- function metrics(state) {
366
- const bits = [`<b>${modelName}</b>`];
367
- if (lastTTFT != null) bits.push(`${lastTTFT.toFixed(1)}s to first word`);
368
- if (lastTokps != null) bits.push(`<b>${lastTokps.toFixed(0)}</b> tokens a second`);
369
- if (!lastTTFT && !lastTokps) bits.push(state || (warm ? "on your device · works offline" : "on your device"));
370
- $("metrics").innerHTML = bits.join(" &nbsp;&middot;&nbsp; ");
371
- }
372
- let pendingQ = null, restored = false;
373
- function restoreStory() {
374
- if (restored) return; restored = true;
375
- try {
376
- const saved = JSON.parse(localStorage.getItem(STORE) || "null");
377
- if (!saved || !saved.story || !saved.story.length) return;
378
- story = saved.story; memoryNote = saved.memoryNote || "";
379
- $("col").classList.add("started");
380
- for (const t of story.slice(-12)) { // the room re-fills; the model remembers ALL of it via the fold
381
- msg("You", "user").body.textContent = t.q;
382
- msg(modelName, "bot").body.textContent = t.a;
383
- }
384
- if (!memoryNote && story.length) memoryNote = story.slice(-6).map((t) => `${t.q} → ${t.a.slice(0, 120)}`).join("; ").slice(0, 1200);
385
- note("picked up where you left off");
386
- log.scrollTop = log.scrollHeight;
387
- } catch {}
388
- }
389
- function enterChat() {
390
- ready = true; $("send").disabled = false; restoreStory(); metrics();
391
- if (pendingQ) { $("inp").value = pendingQ; pendingQ = null; send(); }
392
- else if (entered) $("inp").focus();
393
- }
394
-
395
- const log = $("log");
396
- function msg(who, cls) {
397
- const d = document.createElement("div"); d.className = "msg " + cls;
398
- d.innerHTML = `<div class="who">${who}</div>`;
399
- const think = document.createElement("details"); think.className = "think"; think.hidden = true;
400
- think.innerHTML = `<summary><span class="chev">▸</span><span class="sum">thinking…</span></summary><div class="t"></div>`;
401
- const body = document.createElement("div"); body.className = "body";
402
- d.appendChild(think); d.appendChild(body);
403
- let acts = null;
404
- if (cls === "bot") { acts = document.createElement("div"); acts.className = "acts"; d.appendChild(acts); }
405
- log.appendChild(d);
406
- log.scrollTop = log.scrollHeight;
407
- return { d, body, think, acts, t: think.querySelector(".t") };
408
- }
409
- const ICON = {
410
- copy: '<svg viewBox="0 0 24 24"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>',
411
- ok: '<svg viewBox="0 0 24 24"><path d="M5 13l4 4L19 7"/></svg>',
412
- regen:'<svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v5h-5"/></svg>',
413
- };
414
- function iconBtn(html, title, fn) { const b = document.createElement("button"); b.type = "button"; b.title = title; b.innerHTML = html; b.onclick = fn; return b; }
415
- // action row: copy the answer + regenerate the last turn (Grok's row, Claude's restraint)
416
- function fitActions(ui, text, regen) {
417
- if (!ui.acts) return; ui.acts.innerHTML = "";
418
- const copy = iconBtn(ICON.copy, "Copy", async () => {
419
- try { await navigator.clipboard.writeText(text); copy.classList.add("ok"); copy.innerHTML = ICON.ok;
420
- setTimeout(() => { copy.classList.remove("ok"); copy.innerHTML = ICON.copy; }, 1200); } catch {}
421
- });
422
- ui.acts.appendChild(copy);
423
- if (regen) ui.acts.appendChild(iconBtn(ICON.regen, "Regenerate", regen));
424
- ui.acts.classList.add("shown");
425
- }
426
- // follow-ups AUTHORED BY THE MODEL about the actual exchange (Grok's behavior, done locally):
427
- // one bounded extra generation right after the answer; killed instantly if the user starts typing.
428
- let sugCtl = null;
429
- async function offerFollowups(lastQ, lastA, host) {
430
- try { if (sugCtl) sugCtl.abort(); } catch {}
431
- sugCtl = new AbortController();
432
- const ask = `Here is a conversation:
433
- Question: ${lastQ}
434
- Answer: ${lastA.slice(0, 600)}
435
-
436
- Write exactly two short, sharp follow-up questions a curious person would ask next. One per line. No numbering, no preamble.`;
437
- try {
438
- const ids = engine.tokenize(engine.frameTurn(ask, false));
439
- const res = await engine.generate(ids, { maxNew: 180, signal: sugCtl.signal });
440
- const seg = splitThink(res.outIds || []);
441
- const text = seg.ans.length ? engine.detokenize(seg.ans) : (res.text || "");
442
- const qs = text.split(/\n+/).map((l) => l.replace(/^[-*\d.\s]+/, "").trim()).filter((l) => l.length > 8 && l.length < 140).slice(0, 2);
443
- if (!qs.length || busy) return;
444
- const box = document.createElement("div"); box.className = "fu";
445
- for (const label of qs) {
446
- const b = document.createElement("button"); b.type = "button";
447
- b.innerHTML = `<span class="arr">↳</span>${label.replace(/[<>&]/g, "")}`;
448
- b.onclick = () => { box.remove(); $("inp").value = label; send(); };
449
- box.appendChild(b);
450
- }
451
- host.appendChild(box);
452
- log.scrollTop = log.scrollHeight;
453
- } catch {} // aborted / out of room → no suggestions, no noise
454
- }
455
- function note(s) { const d = document.createElement("div"); d.className = "note"; d.textContent = s; log.appendChild(d); }
456
-
457
- // split streamed outIds into thinking + answer segments by the <think> token ids (robust: no
458
- // tags at position 0 → everything is answer; unclosed → everything so far is thinking).
459
- function splitThink(outIds) {
460
- if (thinkOpen < 0 || outIds[0] !== thinkOpen) return { think: [], ans: outIds };
461
- const c = outIds.indexOf(thinkClose);
462
- if (c < 0) return { think: outIds.slice(1), ans: [] };
463
- return { think: outIds.slice(1, c), ans: outIds.slice(c + 1) };
464
- }
465
-
466
- let busy = false, ready = false;
467
- async function send() {
468
- const q = $("inp").value.trim();
469
- if (!q || busy) return;
470
- if (!ready || !engine) { // the mind is still arriving: hold ONE question, it sends itself
471
- pendingQ = q; $("inp").value = "";
472
- $("col").classList.add("started");
473
- msg("You", "user").body.textContent = q;
474
- note("This sends as soon as Bonsai is ready.");
475
- return;
476
- }
477
- busy = true; $("inp").value = ""; $("send").disabled = true;
478
- $("col").classList.add("started"); // the greeting yields to the conversation (Claude-room transition)
479
- msg("You", "user").body.textContent = q;
480
- let turn = engine.tokenize(engine.frameTurn(q, mind.length > 0));
481
- if (mind.length + turn.length + 384 > CTX) { // the window fills: the mind FOLDS its history, never drops it
482
- $("metrics").innerHTML = spn() + "folding memory · nothing is forgotten";
483
- try { memoryNote = await foldMemory(); persistStory(); } catch {}
484
- mind = [];
485
- }
486
- let qEff = q;
487
- if (!mind.length && memoryNote) qEff = `(What you remember of our conversation so far: ${memoryNote})
488
-
489
- ${q}`;
490
- if (!mind.length) turn = engine.tokenize(engine.frameTurn(qEff, false));
491
- const ids = mind.concat(turn);
492
- try { if (sugCtl) sugCtl.abort(); } catch {}
493
- document.querySelectorAll(".fu").forEach((n) => n.remove());
494
- const mindBefore = mind.slice();
495
- const ui = msg(modelName, "bot"); ui.body.innerHTML = spn();
496
- ui.think.querySelector("summary").innerHTML = spn() + `<span class="sum">thinking</span>`;
497
- const tSend = performance.now(); let ttftSet = false, thoughtMs = 0;
498
- lastTTFT = null; lastTokps = null;
499
- // κ-MEMO HIT: identical (model, input) seen before → replay the exact answer, instantly. Honest:
500
- // greedy is deterministic, so this is the same bytes recompute would produce, at O(1).
501
- const mkey = await memoKey(ids);
502
- const hit = memoLoad()[mkey];
503
- if (hit) {
504
- if (hit.think) { ui.think.hidden = false; ui.t.textContent = hit.think; }
505
- ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${hit.secs || 1}s</span>`;
506
- ui.body.textContent = hit.ans;
507
- mind = ids.concat(hit.ansIds || engine.tokenize(hit.ans));
508
- story.push({ q, a: hit.ans }); persistStory();
509
- lastTTFT = (performance.now() - tSend) / 1000; lastTokps = null;
510
- $("metrics").innerHTML = `<b>${modelName}</b> &nbsp;&middot;&nbsp; from memory &nbsp;&middot;&nbsp; content-addressed &nbsp;&middot;&nbsp; instant`;
511
- fitActions(ui, hit.ans, () => { if (!busy) { mind = mindBefore; $("inp").value = q; send(); } });
512
- offerFollowups(q, hit.ans, ui.d);
513
- busy = false; $("send").disabled = false; $("inp").focus();
514
- log.scrollTop = log.scrollHeight;
515
- return;
516
- }
517
- $("metrics").innerHTML = spn() + `<b>${modelName}</b> is thinking`;
518
- try {
519
- const res = await engine.generate(ids, {
520
- maxNew: CTX - ids.length - 8, // the whole remaining KV window (eos stops early)
521
- onToken: (t) => {
522
- if (!ttftSet) { ttftSet = true; lastTTFT = (performance.now() - tSend) / 1000; } // TTFT = send → first visible token
523
- if (t.stats && t.stats.tokps) lastTokps = t.stats.tokps;
524
- metrics();
525
- const s = splitThink(t.outIds);
526
- if (s.think.length) { ui.think.hidden = false; ui.t.textContent = engine.detokenize(s.think); }
527
- if (s.ans.length && !thoughtMs) { thoughtMs = performance.now() - tSend; // answer flowing: freeze "Thought for Ns"
528
- const secs = Math.max(1, Math.round(thoughtMs / 1000));
529
- ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${secs}s</span>`; }
530
- ui.body.textContent = s.ans.length ? engine.detokenize(s.ans) : (s.think.length ? "" : t.text);
531
- log.scrollTop = log.scrollHeight;
532
- },
533
- });
534
- const s = splitThink(res.outIds || []);
535
- const secs = Math.max(1, Math.round((thoughtMs || (performance.now() - tSend)) / 1000));
536
- ui.think.querySelector("summary").innerHTML = `<span class="chev">▸</span><span class="sum">Thought for ${secs}s</span>`;
537
- if (s.think.length) { ui.think.hidden = false; ui.t.textContent = engine.detokenize(s.think); }
538
- if (s.ans.length) {
539
- const answer = engine.detokenize(s.ans);
540
- ui.body.textContent = answer;
541
- mind = ids.concat(s.ans); // history carries the ANSWER only (Qwen3 convention: prior-turn thinking dropped)
542
- story.push({ q, a: answer }); persistStory();
543
- memoSave(mkey, { ans: answer, ansIds: s.ans, think: s.think.length ? engine.detokenize(s.think) : "", secs }); // κ-memo: this exact (model,input)→answer is now O(1)
544
- fitActions(ui, answer, () => { if (!busy) { mind = mindBefore; $("inp").value = q; send(); } }); // regenerate: rewind history, re-ask
545
- offerFollowups(q, answer, ui.d); // the model writes its own follow-ups, in place
546
- } else if (s.think.length) {
547
- ui.body.textContent = "I ran out of room while thinking. Ask again, a bit shorter."; // unclosed <think> at the window edge; turn not kept
548
- } else {
549
- ui.body.textContent = res.text;
550
- mind = ids.concat(res.outIds || []);
551
- }
552
- if (res.stats && res.stats.tokps) lastTokps = res.stats.tokps;
553
- metrics();
554
- } catch (e) { ui.body.textContent = "Something broke: " + (e && e.message || e); }
555
- busy = false; $("send").disabled = false; $("inp").focus();
556
- log.scrollTop = log.scrollHeight;
557
- }
558
-
559
- $("go").addEventListener("click", () => {
560
- entered = true;
561
- try { if (window.__holoOff) { window.__holoOff(); window.__holoOff = null; } } catch {} // hand the hologram off — ONLY now, as the visitor enters (a warm engine load must never kill the welcome ring)
562
- show("chat"); $("inp").focus();
563
- if (!streamStarted) { streamStarted = true; stream(); }
564
- });
565
- $("send").disabled = true; // until the mind is resident (early questions queue)
566
  (async () => {
567
  try {
568
- if (navigator.connection && navigator.connection.saveData) return; // respect data saver
569
- if (SRC) return; // dev override: no background pulls
570
- const B27 = "https://huggingface.co/HOLOGRAMTECH/q-bonsai-27b/resolve/main";
571
- const cache = await caches.open("holo-kappa-v1");
572
- const man = await (await fetch(B27 + "/manifest.json")).json();
573
- const urls = Object.values(man.tensors || {}).map((r) => B27 + "/b/" + String(r.kappa).replace(":", "_") + ".gz");
574
- let i = 0;
575
- const worker = async () => {
576
- while (i < urls.length) {
577
- const u = urls[i++];
578
- if (await cache.match(u)) continue;
579
- while (streamStarted && !ready) await new Promise((r) => setTimeout(r, 1500)); // the live stream owns the wire
580
- try { const b = await (await fetch(u, { cache: "no-store" })).arrayBuffer(); await cache.put(u, new Response(b, { headers: { "Content-Type": "application/octet-stream" } })); } catch {}
581
- }
582
- };
583
- Promise.all(Array.from({ length: 3 }, worker)).catch(() => {});
584
- } catch {}
585
- })();
586
- (async () => { // returning visitor: the mind wakes BEHIND the welcome screen
587
- try { const c = await caches.open("holo-kappa-v1"); if (await c.match(BASE + "/manifest.json")) { streamStarted = true; stream(); } } catch {}
588
  })();
589
- $("send").addEventListener("click", send);
590
- $("inp").addEventListener("keydown", (e) => { if (e.key === "Enter") send(); });
591
- if (!navigator.gpu) { $("go").disabled = true; $("fine").textContent = "This browser has no WebGPU. Chrome or Edge 113 or newer required."; }
592
  </script>
593
- </body>
 
2
  <meta charset="utf-8">
3
  <meta name="viewport" content="width=device-width,initial-scale=1">
4
  <title>Bonsai</title>
5
+ <meta name="description" content="An AI that's yours — runs entirely on your device, private and offline.">
6
  <style>
7
+ :root{color-scheme:dark}
8
+ *{margin:0;box-sizing:border-box}
9
+ html,body{height:100%}
10
+ body{background:#262624;color:#eceae4;font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased;overflow:hidden}
11
+ #s{position:fixed;inset:0;display:grid;place-content:center;justify-items:center;gap:16px;text-align:center;padding:24px}
12
+ .dot{width:11px;height:11px;border-radius:50%;background:#ece9e3;animation:p 1.3s ease-in-out infinite}
13
+ @keyframes p{0%,100%{opacity:.22;transform:scale(.8)}50%{opacity:1;transform:scale(1)}}
14
+ .t{font-size:15px;color:rgba(232,230,224,.5);letter-spacing:.01em}
15
+ @media (prefers-reduced-motion:reduce){.dot{animation:none;opacity:.85}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  </style>
17
+ <div id="s"><div class="dot"></div><div class="t">Verifying</div></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  <script type="module">
19
+ // Byte zero: install the κ-runtime, then step into the app THROUGH it (every byte content-addressed after this).
20
+ // Fail-open at every branch — a browser without service workers, or any boot error, still gets the app.
21
+ const FLAG = "__bonsai_kboot";
22
+ const app = () => location.replace("app.html");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  (async () => {
24
  try {
25
+ if (!("serviceWorker" in navigator)) return app();
26
+ const reg = await navigator.serviceWorker.register("portal-sw.js", { type: "module" });
27
+ await navigator.serviceWorker.ready; // an active worker now governs this scope
28
+ if (sessionStorage.getItem(FLAG)) return app(); // reloaded once and STILL the loader → SW not shadowing → show the app
29
+ sessionStorage.setItem(FLAG, "1");
30
+ location.reload(); // the reload navigates THROUGH the runtime → it serves the verified app
31
+ } catch (e) { app(); }
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  })();
 
 
 
33
  </script>
 
manifest.holo.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "holo": "kappa-portal/1",
3
+ "algo": "blake3",
4
+ "entry": "app.html",
5
+ "root": "did:holo:blake3:2e169f7c6d32d97e5e5d76f04516dfa459da761775697bd0c3705b7c69380c11",
6
+ "members": {
7
+ "app.html": {
8
+ "blake3": "did:holo:blake3:2e169f7c6d32d97e5e5d76f04516dfa459da761775697bd0c3705b7c69380c11",
9
+ "bytes": 37761
10
+ },
11
+ "q/core/engine.js": {
12
+ "blake3": "did:holo:blake3:f1b362f077fe5d59946445952c8c94433234381bfb9115a3915ada40ea75d09e",
13
+ "bytes": 21735
14
+ },
15
+ "q/core/holo-stream-load.mjs": {
16
+ "blake3": "did:holo:blake3:0f0b3c111ca3dba42b6141c4feed97b7fa87e8caf0a93559ea652b642fb59dff",
17
+ "bytes": 13125
18
+ },
19
+ "q/core/kappa.js": {
20
+ "blake3": "did:holo:blake3:ce25065ca66be6834ee7658eb3f52af810cdca38edccf9c4cc994033818469ad",
21
+ "bytes": 5066
22
+ },
23
+ "q/core/kv-commons.mjs": {
24
+ "blake3": "did:holo:blake3:32c9ef2f711e28db8d9e269fe2e456c2e4ac4a2e7c3e42fdeba88b903b576781",
25
+ "bytes": 2664
26
+ },
27
+ "q/forge/gguf-forge-iq-dequant.mjs": {
28
+ "blake3": "did:holo:blake3:213e24bdc3ce4c6da25d4eebc96e103b2190292595c3074dd32b2a408a62b79c",
29
+ "bytes": 11568
30
+ },
31
+ "q/forge/gguf-forge-iq-grids.mjs": {
32
+ "blake3": "did:holo:blake3:87880133b512c20baf3cfc78dec9f37d24233c70d1a6ff88cec8f5c16ba7fc8b",
33
+ "bytes": 46068
34
+ },
35
+ "q/holo-delta.mjs": {
36
+ "blake3": "did:holo:blake3:28b845c09b34d8bca7c2c2889e00a5ec19a4daf7d7f8a1d2f2b2336b54e49b3c",
37
+ "bytes": 10781
38
+ },
39
+ "q/holo-load-delta.mjs": {
40
+ "blake3": "did:holo:blake3:20858f7b5361ed90eeeffbd854595eee3436c019d88bb27775e5da7defc12672",
41
+ "bytes": 3805
42
+ },
43
+ "q/holo-load2bit.mjs": {
44
+ "blake3": "did:holo:blake3:59823819bcb7c0a7eb89a965fc070b3997670f6575e61affa8a944495dce9992",
45
+ "bytes": 11861
46
+ },
47
+ "q/pkg/holospaces_web.js": {
48
+ "blake3": "did:holo:blake3:bd4118a57c12e421fa18aff14c6948e7f70916817a1994ecfad5f30303cca69a",
49
+ "bytes": 127867
50
+ },
51
+ "q/pkg/holospaces_web_bg.wasm": {
52
+ "blake3": "did:holo:blake3:12861f3bd9cf81ce33116b0020f26b4fd11aa6f1ad206173b382c1ac2e1f4c77",
53
+ "bytes": 6469596
54
+ },
55
+ "q/qvac-2bit.mjs": {
56
+ "blake3": "did:holo:blake3:996684e9627d45646b72d468fdb680bef71b9a4325119e51ca4ec04c136dd404",
57
+ "bytes": 19973
58
+ },
59
+ "q/qvac-gpu.js": {
60
+ "blake3": "did:holo:blake3:47832f8bfc037998a7254d71be614e5c6e4632ed6f699c910599eb5f62919cc3",
61
+ "bytes": 176735
62
+ },
63
+ "q/qvac-ingest.mjs": {
64
+ "blake3": "did:holo:blake3:598bd95b2bb16d5bff61aae814c0f39f40339dbe9dc2bfefe2073b351ba8d323",
65
+ "bytes": 28560
66
+ },
67
+ "vendor/three.core.min.js": {
68
+ "blake3": "did:holo:blake3:ea9bce76382aa29701ff54bf518d39eab41df6eee28bfaa35b026073f27bcf42",
69
+ "bytes": 384222
70
+ },
71
+ "vendor/three.module.min.js": {
72
+ "blake3": "did:holo:blake3:fbe28e0101f059d49e8921dc6c76daf4ec129eb40c5f418d1c8f88496f309fd6",
73
+ "bytes": 364998
74
+ }
75
+ }
76
+ }
portal-sw.js ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // portal-sw.js — the κ-addressable holospace RUNTIME (self-contained, in-image). Serves every same-origin
2
+ // member content-addressed: fetch → re-derive to its blake3 κ → serve or REFUSE (Law L5, fail-closed). Cached
3
+ // by content hash, so a return visit paints from cache with zero network (offline), and a new ship (new κ)
4
+ // invalidates itself. Cross-origin (model weights, boot frames) passes straight through — the app verifies
5
+ // those on its own axis. A module SW importing the real substrate blake3. ─────────────────────────────────
6
+ import { reDerives } from "./_shared/holo-l5.mjs";
7
+ const CACHE = "holo-portal-v1";
8
+ const CT = { html:"text/html", css:"text/css", js:"text/javascript", mjs:"text/javascript", json:"application/json",
9
+ svg:"image/svg+xml", png:"image/png", webp:"image/webp", jpg:"image/jpeg", jpeg:"image/jpeg", wasm:"application/wasm",
10
+ gguf:"application/octet-stream", bin:"application/octet-stream", woff2:"font/woff2", map:"application/json", ico:"image/x-icon" };
11
+ const ctOf = (p) => CT[(p.split(".").pop() || "").toLowerCase()] || "application/octet-stream";
12
+ const hexOf = (k) => String(k).split(":").pop();
13
+ let MAN = null;
14
+
15
+ self.addEventListener("install", () => self.skipWaiting());
16
+ self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
17
+
18
+ // the manifest is the source of truth — fetched FRESH each entry (a new ship propagates with no cache-bust),
19
+ // mirrored to the cache so an offline boot still resolves the closure.
20
+ async function manifest() {
21
+ const scope = self.registration.scope;
22
+ try {
23
+ const r = await fetch(scope + "manifest.holo.json", { cache: "no-store" });
24
+ if (r.ok) { MAN = await r.json(); try { const c = await caches.open(CACHE); await c.put(scope + "manifest.holo.json", new Response(JSON.stringify(MAN), { headers: { "content-type": "application/json" } })); } catch {} return MAN; }
25
+ } catch {}
26
+ if (!MAN) { try { const c = await caches.open(CACHE); const h = await c.match(scope + "manifest.holo.json"); if (h) MAN = await h.json(); } catch {} }
27
+ return MAN;
28
+ }
29
+
30
+ // content-addressed serve: cache-by-κ → miss → fetch origin bytes → re-derive to κ → serve or refuse.
31
+ async function serve(fetchRel, kappa) {
32
+ const scope = self.registration.scope, c = await caches.open(CACHE), key = scope + "b/" + hexOf(kappa);
33
+ const hit = await c.match(key); if (hit) return hit;
34
+ let net; try { net = await fetch(scope + fetchRel, { cache: "no-store" }); } catch { return new Response("offline · not in cache", { status: 504 }); }
35
+ if (!net || !net.ok) return net || new Response("not found", { status: 404 });
36
+ const buf = new Uint8Array(await net.arrayBuffer());
37
+ if (!(await reDerives(buf, kappa))) return new Response("L5 refused — " + fetchRel + " does not re-derive to its κ", { status: 409 });
38
+ const resp = new Response(buf, { headers: { "content-type": ctOf(fetchRel), "cache-control": "no-cache", "x-kappa": hexOf(kappa) } });
39
+ try { await c.put(key, resp.clone()); } catch {}
40
+ return resp;
41
+ }
42
+
43
+ async function entry() {
44
+ const m = await manifest();
45
+ if (!m || !m.members || !m.entry || !m.members[m.entry]) return fetch(self.registration.scope + "app.html");
46
+ return serve(m.entry, m.members[m.entry].blake3);
47
+ }
48
+
49
+ self.addEventListener("fetch", (e) => {
50
+ const scope = self.registration.scope, url = e.request.url;
51
+ if (e.request.method !== "GET" || !url.startsWith(scope)) return; // cross-origin / non-GET → network
52
+ const rel = url.slice(scope.length).split("?")[0].split("#")[0];
53
+ if (rel === "" || rel === "index.html" || rel.endsWith("/")) { e.respondWith(entry()); return; } // root → the app
54
+ if (rel === "portal-sw.js" || rel === "manifest.holo.json" || rel.startsWith("_shared/")) return; // runtime files → origin
55
+ e.respondWith((async () => { const m = await manifest(); const mem = m && m.members && m.members[rel]; return mem ? serve(rel, mem.blake3) : fetch(e.request); })());
56
+ });
q/holo-load2bit.mjs CHANGED
@@ -1,141 +1,141 @@
1
- // holo-load2bit.mjs — the LOAD-DIRECT consumer (the "load" half of the 7B infra). Given a pre-compiled
2
- // 2-bit κ-object (manifest.json + content-addressed b/<κ>.gz blocks, produced by compile2bit.mjs), it builds
3
- // the engine manifest + a fetchTensor that streams blocks, verifies each by re-deriving its κ (Law L5),
4
- // gunzips, and hands the engine the weights ALREADY 2-bit — no re-quant at load. The engine reads
5
- // manifest.preQuantized=true (parts() returns the blocks verbatim) and incoherent=false (LDLQ ⇒ no FWHT).
6
- // Hosting = serve the κ-object dir from anywhere; the κ-verify makes any mirror untrusted-safe.
7
- //
8
- // A family FINETUNE is stored as `base-κ + delta` (format "holo-delta/1"); loadKappaObject detects that and
9
- // transparently delegates to holo-load-delta.mjs, which reconstructs the finetune's blocks and returns the
10
- // SAME { manifest, fetchTensor } shape — so the engine, KV-cache, and Q's brain loader need no changes.
11
- import { f16ToF32 } from "./qvac-ingest.mjs";
12
-
13
- async function gunzip(u8) { const ds = new DecompressionStream("gzip"); const w = ds.writable.getWriter(); w.write(u8); w.close(); return new Uint8Array(await new Response(ds.readable).arrayBuffer()); }
14
- const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
15
-
16
- // ── PERSISTENT κ-CACHE (the returning-user path): a κ-object's manifest + blocks are content-addressed and
17
- // IMMUTABLE, so once fetched they can live in the browser's Cache API FOREVER, keyed by their own URL. A
18
- // returning user then loads Q from local disk — ~0 network, no server (serverless by construction). It is
19
- // untrusted-safe: every cached block is still L5 re-derived below, so a poisoned cache entry is rejected
20
- // exactly like a poisoned network body. First visit warms the cache; every visit after is disk-speed. ──
21
- const KCACHE = "holo-kappa-v1";
22
- let _persistAsked = false;
23
- async function _askPersist() {
24
- if (_persistAsked) return; _persistAsked = true; // once per session: ask the browser NOT to evict the model under storage pressure
25
- try { if (navigator.storage && navigator.storage.persist && !(await navigator.storage.persisted())) await navigator.storage.persist(); } catch (e) {}
26
- }
27
- // fetch a URL as bytes, disk-cached by URL. cache HIT → no network. MISS → fetch once (no-store bounds the
28
- // in-flight RAM to one body) then store to disk. All failures fall back to a plain fetch (never block a load).
29
- const _inflight = new Map(); // URL → in-flight fetch promise, so a parallel prefetch + the engine's read of the
30
- // SAME block share ONE network fetch (never double-download).
31
- async function cachedBytes(url) {
32
- let cache = null;
33
- try { cache = await caches.open(KCACHE); const hit = await cache.match(url); if (hit) return new Uint8Array(await hit.arrayBuffer()); } catch (e) { cache = null; }
34
- if (_inflight.has(url)) return _inflight.get(url);
35
- const p = (async () => {
36
- const buf = await (await fetch(url, { cache: "no-store" })).arrayBuffer();
37
- if (cache) { try { await cache.put(url, new Response(buf.slice(0), { headers: { "Content-Type": "application/octet-stream" } })); _askPersist(); } catch (e) {} }
38
- return new Uint8Array(buf);
39
- })();
40
- _inflight.set(url, p);
41
- try { return await p; } finally { _inflight.delete(url); }
42
- }
43
- // FAST FIRST LOAD: warm the whole block cache with bounded concurrency, so the engine's sequential per-tensor
44
- // reads hit the cache instead of paying one HF round-trip at a time (~1.5 blocks/s → tens of blocks/s over HTTP/2).
45
- // Fire-and-forget; the engine's getBlock shares any in-flight fetch (no double-download). Cross-origin-CDN safe.
46
- function prefetchBlocks(baseUrl, kappas, conc = 12) {
47
- try {
48
- const urls = [...new Set(kappas.filter(Boolean))].map((k) => baseUrl + "/b/" + String(k).replace(":", "_") + ".gz");
49
- let i = 0;
50
- const worker = async () => { while (i < urls.length) { const u = urls[i++]; try { await cachedBytes(u); } catch (e) {} } };
51
- Promise.all(Array.from({ length: Math.min(conc, urls.length) }, worker)).catch(() => {});
52
- } catch (e) {}
53
- }
54
-
55
- // reshape a raw (gunzipped) block to what the engine reads. PURE — shared with the delta loader so both
56
- // paths apply identical per-fmt handling. 2bit+fp16 → 2bit+f32 scales; everything else verbatim.
57
- export function reshapeTensor(rec, raw) {
58
- if (rec.fmt === "2bit" && rec.fp16) { // [2-bit packed][fp16 scales] → [2-bit][f32 scales]
59
- const Kp = rec.K, q2 = (rec.N * Kp) / 4, nsc = rec.N * (Kp / 32);
60
- const f16 = new Uint16Array(raw.buffer, raw.byteOffset + q2, nsc);
61
- const out = new Uint8Array(q2 + nsc * 4); out.set(raw.subarray(0, q2), 0);
62
- const f32 = new Float32Array(out.buffer, q2, nsc); for (let i = 0; i < nsc; i++) f32[i] = f16ToF32(f16[i]);
63
- return out;
64
- }
65
- return raw; // 2bit+f32 (incoherence), q8 (embed), f32 (norms) — verbatim
66
- }
67
-
68
- // build the engine manifest from model meta + normalized tensor records {name→{N,K,fmt,s?}}. PURE — shared.
69
- export function buildEngineManifest(man, normRecs, e8lutData) {
70
- const tensors = Object.entries(normRecs).map(([name, rec]) => ({ name, N: rec.N, K: rec.K, blk: rec.fmt !== "f32", fmt: rec.fmt, ...(rec.s !== undefined ? { s: rec.s } : {}) }));
71
- const native = man.mode === "q4" || man.mode === "q3" || man.mode === "e8" || man.mode === "bitnet" || man.mode === "q1"; // native-bits κ-object (q1 = Bonsai binary)
72
- return {
73
- d: man.d, n_heads: man.n_heads, n_kv_heads: man.n_kv_heads, ff: man.ff, vocab: man.vocab, n_layers: man.n_layers, hd: man.hd,
74
- bits: native ? man.bits : 8, layout: man.layout, rope_base: man.rope_base, ...(man.maskId !== undefined ? { maskId: man.maskId, diffusion: true } : {}), attn_bias: man.attn_bias, qk_norm: man.qk_norm, qk_norm_dim: man.qk_norm_dim, tied: man.tied,
75
- ...(man.sub_norm ? { sub_norm: true } : {}), ...(man.hybrid ? { hybrid: man.hybrid } : {}), ...(man.rope_sections ? { rope_sections: man.rope_sections } : {}), ...(man.bitlinear ? { bitlinear: true } : {}), ...(man.ffn_act ? { ffn_act: man.ffn_act } : {}), ...(man.moe ? { moe: man.moe } : {}),
76
- ...(native ? {} : { twoBit: true, incoherent: man.incoherent === true, preQuantized: true }), tensors, ...(e8lutData ? { e8lutData } : {}),
77
- };
78
- }
79
-
80
- export async function loadKappaObject(baseUrl, opts = {}) {
81
- // Law L5: the manifest is the ROOT that names every block's κ. Verify the manifest's OWN bytes
82
- // re-derive to a pinned κ BEFORE trusting man.tensors[*].kappa — otherwise a tampered manifest can
83
- // re-point every block to a forged-but-self-consistent κ and each per-block check passes against the
84
- // forgery. The pin is an EXTERNAL anchor (catalog/lock), never the manifest's own self-asserted root.
85
- const manRaw = await cachedBytes(baseUrl + "/manifest.json"); // disk-cached (pinned + verified below), so a returning user's load is 0-network end to end
86
- const manKappa = "sha256:" + hex(await crypto.subtle.digest("SHA-256", manRaw));
87
- const pin = opts.expectKappa ? String(opts.expectKappa).replace(/^did:holo:/, "") : null;
88
- if (pin) { if (manKappa !== pin) throw new Error("manifest κ MISMATCH (Law L5): " + manKappa.slice(0, 24) + "… ≠ pinned " + pin.slice(0, 24) + "…"); }
89
- else if (!opts.allowUnpinned) throw new Error("manifest unpinned (Law L5): pass opts.expectKappa (catalog pin) or opts.allowUnpinned for dev");
90
- const man = JSON.parse(new TextDecoder().decode(manRaw));
91
- // CANONICAL BLAKE3 (Law L1), best-effort + fully gated: if the object publishes a sha256→blake3 map,
92
- // verify each block's canonical BLAKE3 κ IN ADDITION to its sha256 transport κ (both over the stored
93
- // gzipped block — sha256(gz)=name, blake3(gz)=canonical; proven on real q-bitnet-2b). Absent map or no
94
- // wasm → b3 stays null → sha256-only, i.e. byte-for-byte today's behavior (no-op until the map ships).
95
- let b3map = null, b3 = null;
96
- if (opts.blake3 !== false) try {
97
- const fn = (await import("./pkg/holospaces_web.js")).kappa;
98
- let ok = false; try { ok = fn(new Uint8Array([1])).startsWith("blake3:"); } catch (e) { ok = false; } // wasm already init'd by loader.ready()
99
- if (ok) {
100
- if (opts.blake3Map) b3map = opts.blake3Map; // injected map (test before the HF upload)
101
- else { const mr = await fetch(baseUrl + "/sha256-to-blake3.map.json"); if (mr.ok) b3map = await mr.json(); }
102
- if (b3map) b3 = fn;
103
- }
104
- } catch (e) { b3map = null; b3 = null; }
105
- // FAMILY FINETUNE: a `base-κ + delta` object — reconstruct via the delta loader (same return shape).
106
- if (man.format === "holo-delta/1") return (await import("./holo-load-delta.mjs")).loadDeltaObject(baseUrl, { ...opts, manifest: man });
107
- // FAST FIRST LOAD: prefetch every block into the cache in parallel while the engine builds (turns a
108
- // latency-bound sequential stream into a bandwidth-bound one — critical when serving off a remote CDN like HF).
109
- if (opts.prefetch !== false) { try { prefetchBlocks(baseUrl, Object.values(man.tensors || {}).map((r) => r.kappa)); } catch (e) {} }
110
- // RAM-bounded, DISK-cached: the engine fetches each tensor once, so decoded blocks are handed over and
111
- // released — in-flight RAM stays ~one block (a 7B κ-object decompresses to >2.6 GB). The gzipped block
112
- // bytes are persisted to the Cache API by their content-addressed URL (cachedBytes), so a returning user
113
- // reads them from disk with no network. Every block — cached or fresh — is L5 re-derived (κ must match),
114
- // so the cache is untrusted-safe.
115
- const getBlock = async (kappa) => {
116
- const gz = await cachedBytes(baseUrl + "/b/" + kappa.replace(":", "_") + ".gz");
117
- const got = "sha256:" + hex(await crypto.subtle.digest("SHA-256", gz)); // Law L5: re-derive the transport κ
118
- if (got !== kappa) throw new Error("κ MISMATCH " + kappa.slice(0, 24));
119
- if (b3 && b3map) { const want = b3map[kappa]; if (want) { if (b3(gz) !== want) throw new Error("BLAKE3 κ MISMATCH " + kappa.slice(0, 24)); if (typeof window !== "undefined") window.__b3n = (window.__b3n || 0) + 1; } } // Law L1 canonical axis
120
- return await gunzip(gz);
121
- };
122
- const fetchTensor = async (name) => {
123
- const rec = man.tensors[name]; if (!rec) return new Uint8Array(0);
124
- return reshapeTensor(rec, await getBlock(rec.kappa));
125
- };
126
- // E₈ codebook (mode e8): the 256×8 LUT is its own content-addressed block — fetch + κ-verify (Law L5)
127
- let e8lutData;
128
- if (man.e8lut) { const b = await getBlock(man.e8lut.replace(/^did:holo:/, "")); e8lutData = new Float32Array(b.buffer, b.byteOffset, 2048); }
129
- const manifest = buildEngineManifest(man, man.tensors, e8lutData);
130
- // bundled tokenizer (SERVERLESS load): the header (tokenizer + arch) should load same-origin/on-device, no
131
- // external host. A RELATIVE `source` already resolves against the κ-object's own dir. When the manifest
132
- // declares a REMOTE (http) source but the κ-object ALSO ships a local tokenizer.gguf, PREFER the bundle —
133
- // one cheap HEAD probe, and the manifest bytes (hence its Law-L5 pin) stay untouched. No bundle served →
134
- // fall back to the declared source. This makes a κ-object with a bundled header 100% serverless to load.
135
- const base = baseUrl.replace(/\/+$/, "");
136
- if (man.source && !/^https?:\/\//.test(man.source)) man.source = base + "/" + man.source;
137
- else if (man.source && /^https?:\/\//.test(man.source)) {
138
- try { const h = await fetch(base + "/tokenizer.gguf", { method: "HEAD" }); if (h && h.ok) man.source = base + "/tokenizer.gguf"; } catch (e) {}
139
- }
140
- return { manifest, fetchTensor, info: man };
141
- }
 
1
+ // holo-load2bit.mjs — the LOAD-DIRECT consumer (the "load" half of the 7B infra). Given a pre-compiled
2
+ // 2-bit κ-object (manifest.json + content-addressed b/<κ>.gz blocks, produced by compile2bit.mjs), it builds
3
+ // the engine manifest + a fetchTensor that streams blocks, verifies each by re-deriving its κ (Law L5),
4
+ // gunzips, and hands the engine the weights ALREADY 2-bit — no re-quant at load. The engine reads
5
+ // manifest.preQuantized=true (parts() returns the blocks verbatim) and incoherent=false (LDLQ ⇒ no FWHT).
6
+ // Hosting = serve the κ-object dir from anywhere; the κ-verify makes any mirror untrusted-safe.
7
+ //
8
+ // A family FINETUNE is stored as `base-κ + delta` (format "holo-delta/1"); loadKappaObject detects that and
9
+ // transparently delegates to holo-load-delta.mjs, which reconstructs the finetune's blocks and returns the
10
+ // SAME { manifest, fetchTensor } shape — so the engine, KV-cache, and Q's brain loader need no changes.
11
+ import { f16ToF32 } from "./qvac-ingest.mjs";
12
+
13
+ async function gunzip(u8) { const ds = new DecompressionStream("gzip"); const w = ds.writable.getWriter(); w.write(u8); w.close(); return new Uint8Array(await new Response(ds.readable).arrayBuffer()); }
14
+ const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
15
+
16
+ // ── PERSISTENT κ-CACHE (the returning-user path): a κ-object's manifest + blocks are content-addressed and
17
+ // IMMUTABLE, so once fetched they can live in the browser's Cache API FOREVER, keyed by their own URL. A
18
+ // returning user then loads Q from local disk — ~0 network, no server (serverless by construction). It is
19
+ // untrusted-safe: every cached block is still L5 re-derived below, so a poisoned cache entry is rejected
20
+ // exactly like a poisoned network body. First visit warms the cache; every visit after is disk-speed. ──
21
+ const KCACHE = "holo-kappa-v1";
22
+ let _persistAsked = false;
23
+ async function _askPersist() {
24
+ if (_persistAsked) return; _persistAsked = true; // once per session: ask the browser NOT to evict the model under storage pressure
25
+ try { if (navigator.storage && navigator.storage.persist && !(await navigator.storage.persisted())) await navigator.storage.persist(); } catch (e) {}
26
+ }
27
+ // fetch a URL as bytes, disk-cached by URL. cache HIT → no network. MISS → fetch once (no-store bounds the
28
+ // in-flight RAM to one body) then store to disk. All failures fall back to a plain fetch (never block a load).
29
+ const _inflight = new Map(); // URL → in-flight fetch promise, so a parallel prefetch + the engine's read of the
30
+ // SAME block share ONE network fetch (never double-download).
31
+ async function cachedBytes(url) {
32
+ let cache = null;
33
+ try { cache = await caches.open(KCACHE); const hit = await cache.match(url); if (hit) return new Uint8Array(await hit.arrayBuffer()); } catch (e) { cache = null; }
34
+ if (_inflight.has(url)) return _inflight.get(url);
35
+ const p = (async () => {
36
+ const buf = await (await fetch(url, { cache: "no-store" })).arrayBuffer();
37
+ if (cache) { try { await cache.put(url, new Response(buf.slice(0), { headers: { "Content-Type": "application/octet-stream" } })); _askPersist(); } catch (e) {} }
38
+ return new Uint8Array(buf);
39
+ })();
40
+ _inflight.set(url, p);
41
+ try { return await p; } finally { _inflight.delete(url); }
42
+ }
43
+ // FAST FIRST LOAD: warm the whole block cache with bounded concurrency, so the engine's sequential per-tensor
44
+ // reads hit the cache instead of paying one HF round-trip at a time (~1.5 blocks/s → tens of blocks/s over HTTP/2).
45
+ // Fire-and-forget; the engine's getBlock shares any in-flight fetch (no double-download). Cross-origin-CDN safe.
46
+ function prefetchBlocks(baseUrl, kappas, conc = 12) {
47
+ try {
48
+ const urls = [...new Set(kappas.filter(Boolean))].map((k) => baseUrl + "/b/" + String(k).replace(":", "_") + ".gz");
49
+ let i = 0;
50
+ const worker = async () => { while (i < urls.length) { const u = urls[i++]; try { await cachedBytes(u); } catch (e) {} } };
51
+ Promise.all(Array.from({ length: Math.min(conc, urls.length) }, worker)).catch(() => {});
52
+ } catch (e) {}
53
+ }
54
+
55
+ // reshape a raw (gunzipped) block to what the engine reads. PURE — shared with the delta loader so both
56
+ // paths apply identical per-fmt handling. 2bit+fp16 → 2bit+f32 scales; everything else verbatim.
57
+ export function reshapeTensor(rec, raw) {
58
+ if (rec.fmt === "2bit" && rec.fp16) { // [2-bit packed][fp16 scales] → [2-bit][f32 scales]
59
+ const Kp = rec.K, q2 = (rec.N * Kp) / 4, nsc = rec.N * (Kp / 32);
60
+ const f16 = new Uint16Array(raw.buffer, raw.byteOffset + q2, nsc);
61
+ const out = new Uint8Array(q2 + nsc * 4); out.set(raw.subarray(0, q2), 0);
62
+ const f32 = new Float32Array(out.buffer, q2, nsc); for (let i = 0; i < nsc; i++) f32[i] = f16ToF32(f16[i]);
63
+ return out;
64
+ }
65
+ return raw; // 2bit+f32 (incoherence), q8 (embed), f32 (norms) — verbatim
66
+ }
67
+
68
+ // build the engine manifest from model meta + normalized tensor records {name→{N,K,fmt,s?}}. PURE — shared.
69
+ export function buildEngineManifest(man, normRecs, e8lutData) {
70
+ const tensors = Object.entries(normRecs).map(([name, rec]) => ({ name, N: rec.N, K: rec.K, blk: rec.fmt !== "f32", fmt: rec.fmt, ...(rec.s !== undefined ? { s: rec.s } : {}) }));
71
+ const native = man.mode === "q4" || man.mode === "q3" || man.mode === "e8" || man.mode === "bitnet" || man.mode === "q1"; // native-bits κ-object (q1 = Bonsai binary)
72
+ return {
73
+ d: man.d, n_heads: man.n_heads, n_kv_heads: man.n_kv_heads, ff: man.ff, vocab: man.vocab, n_layers: man.n_layers, hd: man.hd,
74
+ bits: native ? man.bits : 8, layout: man.layout, rope_base: man.rope_base, ...(man.maskId !== undefined ? { maskId: man.maskId, diffusion: true } : {}), attn_bias: man.attn_bias, qk_norm: man.qk_norm, qk_norm_dim: man.qk_norm_dim, tied: man.tied,
75
+ ...(man.sub_norm ? { sub_norm: true } : {}), ...(man.hybrid ? { hybrid: man.hybrid } : {}), ...(man.rope_sections ? { rope_sections: man.rope_sections } : {}), ...(man.bitlinear ? { bitlinear: true } : {}), ...(man.ffn_act ? { ffn_act: man.ffn_act } : {}), ...(man.moe ? { moe: man.moe } : {}),
76
+ ...(native ? {} : { twoBit: true, incoherent: man.incoherent === true, preQuantized: true }), tensors, ...(e8lutData ? { e8lutData } : {}),
77
+ };
78
+ }
79
+
80
+ export async function loadKappaObject(baseUrl, opts = {}) {
81
+ // Law L5: the manifest is the ROOT that names every block's κ. Verify the manifest's OWN bytes
82
+ // re-derive to a pinned κ BEFORE trusting man.tensors[*].kappa — otherwise a tampered manifest can
83
+ // re-point every block to a forged-but-self-consistent κ and each per-block check passes against the
84
+ // forgery. The pin is an EXTERNAL anchor (catalog/lock), never the manifest's own self-asserted root.
85
+ const manRaw = await cachedBytes(baseUrl + "/manifest.json"); // disk-cached (pinned + verified below), so a returning user's load is 0-network end to end
86
+ const manKappa = "sha256:" + hex(await crypto.subtle.digest("SHA-256", manRaw));
87
+ const pin = opts.expectKappa ? String(opts.expectKappa).replace(/^did:holo:/, "") : null;
88
+ if (pin) { if (manKappa !== pin) throw new Error("manifest κ MISMATCH (Law L5): " + manKappa.slice(0, 24) + "… ≠ pinned " + pin.slice(0, 24) + "…"); }
89
+ else if (!opts.allowUnpinned) throw new Error("manifest unpinned (Law L5): pass opts.expectKappa (catalog pin) or opts.allowUnpinned for dev");
90
+ const man = JSON.parse(new TextDecoder().decode(manRaw));
91
+ // CANONICAL BLAKE3 (Law L1), best-effort + fully gated: if the object publishes a sha256→blake3 map,
92
+ // verify each block's canonical BLAKE3 κ IN ADDITION to its sha256 transport κ (both over the stored
93
+ // gzipped block — sha256(gz)=name, blake3(gz)=canonical; proven on real q-bitnet-2b). Absent map or no
94
+ // wasm → b3 stays null → sha256-only, i.e. byte-for-byte today's behavior (no-op until the map ships).
95
+ let b3map = null, b3 = null;
96
+ if (opts.blake3 !== false) try {
97
+ const fn = (await import("./pkg/holospaces_web.js")).kappa;
98
+ let ok = false; try { ok = fn(new Uint8Array([1])).startsWith("blake3:"); } catch (e) { ok = false; } // wasm already init'd by loader.ready()
99
+ if (ok) {
100
+ if (opts.blake3Map) b3map = opts.blake3Map; // injected map (test before the HF upload)
101
+ else { const mr = await fetch(baseUrl + "/sha256-to-blake3.map.json"); if (mr.ok) b3map = await mr.json(); }
102
+ if (b3map) b3 = fn;
103
+ }
104
+ } catch (e) { b3map = null; b3 = null; }
105
+ // FAMILY FINETUNE: a `base-κ + delta` object — reconstruct via the delta loader (same return shape).
106
+ if (man.format === "holo-delta/1") return (await import("./holo-load-delta.mjs")).loadDeltaObject(baseUrl, { ...opts, manifest: man });
107
+ // FAST FIRST LOAD: prefetch every block into the cache in parallel while the engine builds (turns a
108
+ // latency-bound sequential stream into a bandwidth-bound one — critical when serving off a remote CDN like HF).
109
+ if (opts.prefetch !== false) { try { prefetchBlocks(baseUrl, Object.values(man.tensors || {}).map((r) => r.kappa)); } catch (e) {} }
110
+ // RAM-bounded, DISK-cached: the engine fetches each tensor once, so decoded blocks are handed over and
111
+ // released — in-flight RAM stays ~one block (a 7B κ-object decompresses to >2.6 GB). The gzipped block
112
+ // bytes are persisted to the Cache API by their content-addressed URL (cachedBytes), so a returning user
113
+ // reads them from disk with no network. Every block — cached or fresh — is L5 re-derived (κ must match),
114
+ // so the cache is untrusted-safe.
115
+ const getBlock = async (kappa) => {
116
+ const gz = await cachedBytes(baseUrl + "/b/" + kappa.replace(":", "_") + ".gz");
117
+ const got = "sha256:" + hex(await crypto.subtle.digest("SHA-256", gz)); // Law L5: re-derive the transport κ
118
+ if (got !== kappa) throw new Error("κ MISMATCH " + kappa.slice(0, 24));
119
+ if (b3 && b3map) { const want = b3map[kappa]; if (want) { if (b3(gz) !== want) throw new Error("BLAKE3 κ MISMATCH " + kappa.slice(0, 24)); if (typeof window !== "undefined") window.__b3n = (window.__b3n || 0) + 1; } } // Law L1 canonical axis
120
+ return await gunzip(gz);
121
+ };
122
+ const fetchTensor = async (name) => {
123
+ const rec = man.tensors[name]; if (!rec) return new Uint8Array(0);
124
+ return reshapeTensor(rec, await getBlock(rec.kappa));
125
+ };
126
+ // E₈ codebook (mode e8): the 256×8 LUT is its own content-addressed block — fetch + κ-verify (Law L5)
127
+ let e8lutData;
128
+ if (man.e8lut) { const b = await getBlock(man.e8lut.replace(/^did:holo:/, "")); e8lutData = new Float32Array(b.buffer, b.byteOffset, 2048); }
129
+ const manifest = buildEngineManifest(man, man.tensors, e8lutData);
130
+ // bundled tokenizer (SERVERLESS load): the header (tokenizer + arch) should load same-origin/on-device, no
131
+ // external host. A RELATIVE `source` already resolves against the κ-object's own dir. When the manifest
132
+ // declares a REMOTE (http) source but the κ-object ALSO ships a local tokenizer.gguf, PREFER the bundle —
133
+ // one cheap HEAD probe, and the manifest bytes (hence its Law-L5 pin) stay untouched. No bundle served →
134
+ // fall back to the declared source. This makes a κ-object with a bundled header 100% serverless to load.
135
+ const base = baseUrl.replace(/\/+$/, "");
136
+ if (man.source && !/^https?:\/\//.test(man.source)) man.source = base + "/" + man.source;
137
+ else if (man.source && /^https?:\/\//.test(man.source)) {
138
+ try { const h = await fetch(base + "/tokenizer.gguf", { method: "HEAD" }); if (h && h.ok) man.source = base + "/tokenizer.gguf"; } catch (e) {}
139
+ }
140
+ return { manifest, fetchTensor, info: man };
141
+ }