diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..9118562f7d2d284e2cfadb26e5c20ea1654090f4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +models/hodge-5/tokenizer.json filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 73d789e2b698a064d22be773b4f11d65824b379b..1fb202d6e32aec17128fda8dd1fe7cd40a5e7021 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,23 @@ --- -title: EdgeAI -emoji: 🌖 -colorFrom: green -colorTo: blue +title: Encryptid EdgeAI +emoji: ⚡ +colorFrom: gray +colorTo: indigo sdk: static pinned: false +short_description: Hodge-5 running on your own device with WebGPU +custom_headers: + cross-origin-embedder-policy: require-corp + cross-origin-opener-policy: same-origin + cross-origin-resource-policy: cross-origin +models: + - EncryptidSystems/Hodge-5 --- -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# Encryptid EdgeAI + +Hodge-5 runs in your browser on WebGPU. The weights stream from +[EncryptidSystems/Hodge-5](https://huggingface.co/EncryptidSystems/Hodge-5). + +Needs a browser with WebGPU (recent Chrome or Edge). Also live at +[ai.encryptid.systems](https://ai.encryptid.systems). diff --git a/bnz.js b/bnz.js new file mode 100644 index 0000000000000000000000000000000000000000..386b48e901d407394b4a9b5ae18d8f84626a07ba --- /dev/null +++ b/bnz.js @@ -0,0 +1,721 @@ +// BNZ2, the ternary safetensors codec (ternary U8 + BF16), in JS. +// The ANS coder is constriction's default stack coder: 24-bit probabilities, +// 32-bit words, 64-bit state, Categorical(perfect=False). Zstd frames wrap +// the side tables. Gzip is not part of the container; the share layer gzips +// each chunk on the wire. +import { decompress as fzstdDecompress } from "./fzstd.js"; + +const PREC = 24; +const PREC_MASK = (1 << PREC) - 1; +const TOTAL = 1 << PREC; +const TWO32 = 0x100000000; + +function nodeZlib() { + if (typeof process === "undefined" || !process.versions || !process.versions.node) return null; + if (typeof process.getBuiltinModule !== "function") return null; + return process.getBuiltinModule("zlib"); +} + +function asBytes(b) { + return b.byteOffset === 0 && b.byteLength === b.buffer.byteLength ? b : b.slice(); +} + +export function zstdCompress(bytes) { + const z = nodeZlib(); + if (!z) throw new Error("bnz: zstd encode runs in node"); + return new Uint8Array(z.zstdCompressSync(asBytes(bytes))); +} + +export function zstdDecompress(bytes) { + const src = asBytes(bytes); + const z = nodeZlib(); + if (z) return new Uint8Array(z.zstdDecompressSync(src)); + return fzstdDecompress(src); +} + +// --- sha256 (sync; the guest reads weights on the worker thread) --- +const K256 = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]); + +function rotr(x, n) { return (x >>> n) | (x << (32 - n)); } + +export function sha256(data) { + const bytes = data instanceof Uint8Array ? data : new Uint8Array(data); + const bitLen = bytes.length * 8; + const withPad = ((bytes.length + 9 + 63) >> 6) << 6; + const buf = new Uint8Array(withPad); + buf.set(bytes); + buf[bytes.length] = 0x80; + const dv = new DataView(buf.buffer); + const hi = Math.floor(bitLen / TWO32); + dv.setUint32(withPad - 8, hi, false); + dv.setUint32(withPad - 4, bitLen >>> 0, false); + let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a; + let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19; + const w = new Uint32Array(64); + for (let i = 0; i < withPad; i += 64) { + for (let t = 0; t < 16; t++) w[t] = dv.getUint32(i + t * 4, false); + for (let t = 16; t < 64; t++) { + const x = w[t - 15], y = w[t - 2]; + const s0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3); + const s1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10); + w[t] = (w[t - 16] + s0 + w[t - 7] + s1) >>> 0; + } + let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7; + for (let t = 0; t < 64; t++) { + const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); + const ch = (e & f) ^ (~e & g); + const t1 = (h + S1 + ch + K256[t] + w[t]) >>> 0; + const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); + const maj = (a & b) ^ (a & c) ^ (b & c); + const t2 = (S0 + maj) >>> 0; + h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0; + } + h0 = (h0 + a) >>> 0; h1 = (h1 + b) >>> 0; h2 = (h2 + c) >>> 0; h3 = (h3 + d) >>> 0; + h4 = (h4 + e) >>> 0; h5 = (h5 + f) >>> 0; h6 = (h6 + g) >>> 0; h7 = (h7 + h) >>> 0; + } + return [h0, h1, h2, h3, h4, h5, h6, h7].map((x) => x.toString(16).padStart(8, "0")).join(""); +} + +// --- fast categorical CDF, perfect=False --- +// useF32 matches a float32 numpy array. bnz.py's count models are float64. +export function cdfFast(probs, useF32) { + const n = probs.length; + const num = (x) => (useF32 ? Math.fround(x) : x); + const free = TOTAL - n; + let norm = num(0); + for (let i = 0; i < n; i++) norm = num(norm + num(probs[i])); + const scale = num(free / norm); + const cdf = new Uint32Array(n + 1); + let c = num(0); + for (let i = 0; i < n; i++) { + cdf[i] = (Math.trunc(num(c * scale)) + i) >>> 0; + c = num(c + num(probs[i])); + } + cdf[n] = TOTAL; + return cdf; +} + +// 64-bit / 32-bit. prob is below 2^24, so the intermediate product fits in a +// safe integer. Returns [qHi, qLo, rem]. +export function divmod64(hi, lo, d) { + hi >>>= 0; lo >>>= 0; d >>>= 0; + if (hi === 0) return [0, Math.floor(lo / d) >>> 0, lo % d]; + const qHi = Math.floor(hi / d); + const rHi = hi % d; + const q0 = Math.floor(TWO32 / d); + const two32mod = TWO32 % d; + const mid = rHi * two32mod + lo; + const qRest = rHi * q0 + Math.floor(mid / d); + const rem = mid % d; + const qHiOut = (qHi + Math.floor(qRest / TWO32)) >>> 0; + const qLoOut = (qRest % TWO32) >>> 0; + return [qHiOut, qLoOut, rem]; +} + +function shl24or(qHi, qLo, quantile) { + const lo = ((qLo << 24) | quantile) >>> 0; + const hi = ((qHi << 24) | (qLo >>> 8)) >>> 0; + return [hi, lo]; +} + +function mul32(a, b) { + const aLo = a & 0xffff, aHi = a >>> 16; + const bLo = b & 0xffff, bHi = b >>> 16; + const p0 = aLo * bLo; + const p1 = aLo * bHi; + const p2 = aHi * bLo; + const p3 = aHi * bHi; + const mid = (p0 >>> 16) + (p1 & 0xffff) + (p2 & 0xffff); + const lo = ((p0 & 0xffff) | ((mid & 0xffff) << 16)) >>> 0; + const hi = (p3 + (p1 >>> 16) + (p2 >>> 16) + (mid >>> 16)) >>> 0; + return [hi, lo]; +} + +export class AnsCoder { + constructor(words) { + this.bulk = words ? words.slice() : []; + this.hi = 0; + this.lo = 0; + if (words && words.length) this.#init(); + } + + #init() { + const first = this.bulk.pop(); + if ((first >>> 0) === 0) throw new Error("bnz: trailing zero word"); + this.lo = first >>> 0; + this.hi = 0; + while (this.bulk.length) { + const word = this.bulk.pop() >>> 0; + this.hi = this.lo; + this.lo = word; + if (this.hi !== 0) break; + } + } + + encodeSymbol(left, prob) { + prob >>>= 0; + left >>>= 0; + if ((this.hi >>> 8) >= prob) { + this.bulk.push(this.lo >>> 0); + this.lo = this.hi >>> 0; + this.hi = 0; + } + const [qHi, qLo, rem] = divmod64(this.hi, this.lo, prob); + const st = shl24or(qHi, qLo, (left + rem) >>> 0); + this.hi = st[0]; + this.lo = st[1]; + } + + decodeSymbol(cdf) { + const q = this.lo & PREC_MASK; + let lo = 0, hi = cdf.length - 1; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (cdf[mid] <= q) lo = mid + 1; + else hi = mid; + } + const symbol = lo - 1; + const left = cdf[symbol]; + const prob = cdf[lo] - left; + this.#mulAdd(prob, q - left); + return symbol; + } + + #mulAdd(prob, add) { + const sLo = ((this.lo >>> 24) | ((this.hi & 0xffffff) << 8)) >>> 0; + const sHi = this.hi >>> 24; + const [pHi, pLo] = mul32(sLo, prob); + const sumLo = pLo + add; + const rLo = sumLo >>> 0; + const carry = sumLo >= TWO32 ? 1 : 0; + this.hi = (pHi + sHi * prob + carry) >>> 0; + this.lo = rLo; + if (this.hi === 0 && this.bulk.length) { + this.hi = this.lo; + this.lo = this.bulk.pop() >>> 0; + } + } + + getCompressed() { + const extra = this.hi === 0 ? (this.lo === 0 ? [] : [this.lo >>> 0]) : [this.lo >>> 0, this.hi >>> 0]; + return this.bulk.concat(extra); + } +} + +export function encodeIid(symbols, probs, useF32) { + const cdf = cdfFast(probs, useF32); + const enc = new AnsCoder(); + for (let i = symbols.length - 1; i >= 0; i--) { + const s = symbols[i]; + enc.encodeSymbol(cdf[s], cdf[s + 1] - cdf[s]); + } + return enc.getCompressed(); +} + +export function decodeIid(words, probs, n, useF32) { + const cdf = cdfFast(probs, useF32); + const dec = new AnsCoder(words); + const out = new Array(n); + for (let i = 0; i < n; i++) out[i] = dec.decodeSymbol(cdf); + return out; +} + +export function encodeRows(rows, symbols, useF32) { + const enc = new AnsCoder(); + for (let i = symbols.length - 1; i >= 0; i--) { + const cdf = cdfFast(rows[i], !!useF32); + const s = symbols[i]; + enc.encodeSymbol(cdf[s], cdf[s + 1] - cdf[s]); + } + return enc.getCompressed(); +} + +export function decodeRows(words, rows, useF32) { + const dec = new AnsCoder(words); + const out = new Array(rows.length); + for (let i = 0; i < rows.length; i++) out[i] = dec.decodeSymbol(cdfFast(rows[i], !!useF32)); + return out; +} + +function wordsToBytes(words) { + const o = new Uint8Array(words.length * 4); + const dv = new DataView(o.buffer); + for (let i = 0; i < words.length; i++) dv.setUint32(i * 4, words[i] >>> 0, true); + return o; +} + +function bytesToWords(b) { + const n = b.length >> 2; + const words = new Array(n); + const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); + for (let i = 0; i < n; i++) words[i] = dv.getUint32(i * 4, true); + return words; +} + +function pk(parts) { + let n = 0; + for (const p of parts) n += 8 + p.length; + const o = new Uint8Array(n); + const dv = new DataView(o.buffer); + let i = 0; + for (const p of parts) { + dv.setBigUint64(i, BigInt(p.length), true); + i += 8; + o.set(p, i); + i += p.length; + } + return o; +} + +function upk(b) { + const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); + const out = []; + let i = 0; + while (i + 8 <= b.length) { + const n = Number(dv.getBigUint64(i, true)); + i += 8; + out.push(b.subarray(i, i + n)); + i += n; + } + return out; +} + +function u32bytes(arr) { + const o = new Uint8Array(arr.length * 4); + const dv = new DataView(o.buffer); + for (let i = 0; i < arr.length; i++) dv.setUint32(i * 4, arr[i] >>> 0, true); + return o; +} + +function bytesU32(b) { + const n = b.length >> 2; + const a = new Uint32Array(n); + const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); + for (let i = 0; i < n; i++) a[i] = dv.getUint32(i * 4, true); + return a; +} + +// --- ternary U8: four 2-bit codes per byte, values 0..2 --- +function splitTrits(raw, R, C) { + const N = 4 * R; + const t = new Int32Array(N * C); + for (let r = 0; r < R; r++) { + for (let c = 0; c < C; c++) { + const a = raw[r * C + c]; + for (let s = 0; s < 4; s++) { + const v = (a >>> (2 * s)) & 3; + if (v === 3) return null; + t[(s * R + r) * C + c] = v; + } + } + } + return t; +} + +function tritCounts(t, N, C) { + const rc = new Uint32Array(N * 3); + const cc = new Uint32Array(C * 3); + const total = N * C; + for (let i = 0; i < total; i++) { + const v = t[i]; + const row = (i / C) | 0; + const col = i - row * C; + rc[row * 3 + v]++; + cc[col * 3 + v]++; + } + const gc = new Float64Array(3); + for (let r = 0; r < N; r++) for (let k = 0; k < 3; k++) gc[k] += rc[r * 3 + k]; + return { rc, cc, gc }; +} + +function probsAt(mode, rc, cc, gc, row, col) { + const p = [0, 0, 0]; + for (let k = 0; k < 3; k++) { + if (mode === 0) p[k] = rc[row * 3 + k] + 0.5; + else if (mode === 1) p[k] = cc[col * 3 + k] + 0.5; + else p[k] = (rc[row * 3 + k] + 0.5) * (cc[col * 3 + k] + 0.5) / (gc[k] + 0.5); + } + return p; +} + +function cdfAt(mode, rc, cc, gc, row, col, cache) { + if (mode === 0) { + let hit = cache.row[row]; + if (!hit) hit = cache.row[row] = cdfFast(probsAt(0, rc, cc, gc, row, 0), false); + return hit; + } + if (mode === 1) { + let hit = cache.col[col]; + if (!hit) hit = cache.col[col] = cdfFast(probsAt(1, rc, cc, gc, 0, col), false); + return hit; + } + return cdfFast(probsAt(2, rc, cc, gc, row, col), false); +} + +export function encTern(raw, shape, mode) { + const R = shape[0], C = shape[1]; + const t = splitTrits(raw, R, C); + if (!t) return null; + const N = 4 * R; + const { rc, cc, gc } = tritCounts(t, N, C); + const enc = new AnsCoder(); + const cache = { row: new Array(N), col: new Array(C) }; + const total = N * C; + for (let i = total - 1; i >= 0; i--) { + const row = (i / C) | 0; + const col = i - row * C; + const cdf = cdfAt(mode, rc, cc, gc, row, col, cache); + const s = t[i]; + enc.encodeSymbol(cdf[s], cdf[s + 1] - cdf[s]); + } + const tab = u32bytes(rc); + const both = new Uint8Array(tab.length + cc.length * 4); + both.set(tab, 0); + both.set(u32bytes(cc), tab.length); + return pk([new Uint8Array([mode]), zstdCompress(both), wordsToBytes(enc.getCompressed())]); +} + +export function decTern(comp, shape) { + const R = shape[0], C = shape[1]; + const N = 4 * R; + const parts = upk(comp); + const mode = parts[0][0]; + const tb = bytesU32(zstdDecompress(parts[1])); + const rc = new Float64Array(N * 3); + const cc = new Float64Array(C * 3); + for (let i = 0; i < N * 3; i++) rc[i] = tb[i]; + for (let i = 0; i < C * 3; i++) cc[i] = tb[N * 3 + i]; + const gc = new Float64Array(3); + for (let r = 0; r < N; r++) for (let k = 0; k < 3; k++) gc[k] += rc[r * 3 + k]; + const rcU = rc, ccU = cc; + const dec = new AnsCoder(bytesToWords(parts[2])); + const cache = { row: new Array(N), col: new Array(C) }; + const out = new Uint8Array(N * C); + const total = N * C; + for (let i = 0; i < total; i++) { + const row = (i / C) | 0; + const col = i - row * C; + out[i] = dec.decodeSymbol(cdfAt(mode, rcU, ccU, gc, row, col, cache)); + } + const raw = new Uint8Array(R * C); + for (let r = 0; r < R; r++) { + for (let c = 0; c < C; c++) { + let a = 0; + for (let s = 0; s < 4; s++) a |= out[(s * R + r) * C + c] << (2 * s); + raw[r * C + c] = a; + } + } + return raw; +} + +// --- bf16: sign bits, per-column exponents, per-exponent mantissas --- +function readU16(raw) { + const n = raw.length >> 1; + const v = new Uint16Array(n); + for (let i = 0; i < n; i++) v[i] = raw[i * 2] | (raw[i * 2 + 1] << 8); + return v; +} + +function packBits(bits) { + const o = new Uint8Array((bits.length + 7) >> 3); + for (let i = 0; i < bits.length; i++) if (bits[i]) o[i >> 3] |= 1 << (7 - (i & 7)); + return o; +} + +function unpackBits(packed, n) { + const o = new Uint8Array(n); + for (let i = 0; i < n; i++) o[i] = (packed[i >> 3] >> (7 - (i & 7))) & 1; + return o; +} + +function nonzeroCount(counts) { + let nz = 0, only = 0; + for (let i = 0; i < counts.length; i++) if (counts[i]) { nz++; only = i; } + return [nz, only]; +} + +function encodeCounts(enc, syms, counts) { + if (syms.length === 0) return; + const [nz] = nonzeroCount(counts); + if (nz <= 1) return; + let sum = 0; + for (let i = 0; i < counts.length; i++) sum += counts[i]; + const p = new Float64Array(counts.length); + for (let i = 0; i < counts.length; i++) p[i] = counts[i] / sum; + const cdf = cdfFast(p, false); + for (let i = syms.length - 1; i >= 0; i--) { + const s = syms[i]; + enc.encodeSymbol(cdf[s], cdf[s + 1] - cdf[s]); + } +} + +function decodeCounts(dec, n, counts) { + const out = new Int32Array(n); + if (n === 0) return out; + const [nz, only] = nonzeroCount(counts); + if (nz <= 1) { out.fill(only); return out; } + let sum = 0; + for (let i = 0; i < counts.length; i++) sum += counts[i]; + const p = new Float64Array(counts.length); + for (let i = 0; i < counts.length; i++) p[i] = counts[i] / sum; + const cdf = cdfFast(p, false); + for (let i = 0; i < n; i++) out[i] = dec.decodeSymbol(cdf); + return out; +} + +export function encBf16(raw, shape) { + const v = readU16(raw); + const C = shape.length === 2 ? shape[shape.length - 1] : 1; + const n = v.length; + const Rr = n / C; + let emin = 255, emax = 0; + const ex = new Int32Array(n); + const man = new Int32Array(n); + const signBits = new Uint8Array(n); + for (let i = 0; i < n; i++) { + const x = v[i]; + const e = (x >> 7) & 255; + if (e < emin) emin = e; + if (e > emax) emax = e; + ex[i] = e; + man[i] = x & 127; + signBits[i] = x >> 15; + } + const K = emax - emin + 1; + const exf = new Int32Array(n); + for (let i = 0; i < n; i++) exf[i] = ex[i] - emin; + const ecnt = new Uint32Array(C * K); + for (let r = 0; r < Rr; r++) { + for (let c = 0; c < C; c++) ecnt[c * K + exf[r * C + c]]++; + } + const mcnt = new Uint32Array(K * 128); + for (let i = 0; i < n; i++) mcnt[exf[i] * 128 + man[i]]++; + const groups = Array.from({ length: K }, () => []); + for (let i = 0; i < n; i++) groups[exf[i]].push(man[i]); + const enc = new AnsCoder(); + for (let k = K - 1; k >= 0; k--) encodeCounts(enc, groups[k], mcnt.subarray(k * 128, (k + 1) * 128)); + for (let c = C - 1; c >= 0; c--) { + const col = []; + for (let r = 0; r < Rr; r++) col.push(exf[r * C + c]); + encodeCounts(enc, col, ecnt.subarray(c * K, (c + 1) * K)); + } + const hdr = new Uint8Array(12); + const dv = new DataView(hdr.buffer); + dv.setInt32(0, emin, true); + dv.setInt32(4, K, true); + dv.setUint32(8, C, true); + const tab = new Uint8Array((C * K + K * 128) * 4); + tab.set(u32bytes(ecnt), 0); + tab.set(u32bytes(mcnt), C * K * 4); + return pk([hdr, zstdCompress(tab), zstdCompress(packBits(signBits)), wordsToBytes(enc.getCompressed())]); +} + +export function decBf16(comp, shape) { + const parts = upk(comp); + const hv = new DataView(parts[0].buffer, parts[0].byteOffset, parts[0].byteLength); + const emin = hv.getInt32(0, true); + const K = hv.getInt32(4, true); + const C = hv.getUint32(8, true); + const n = shape.reduce((a, b) => a * b, 1); + const Rr = n / C; + const tb = bytesU32(zstdDecompress(parts[1])); + const ecnt = tb.subarray(0, C * K); + const mcnt = tb.subarray(C * K); + const dec = new AnsCoder(bytesToWords(parts[3])); + const exf = new Int32Array(n); + for (let c = 0; c < C; c++) { + const col = decodeCounts(dec, Rr, ecnt.subarray(c * K, (c + 1) * K)); + for (let r = 0; r < Rr; r++) exf[r * C + c] = col[r]; + } + const man = new Int32Array(n); + for (let k = 0; k < K; k++) { + const idx = []; + for (let i = 0; i < n; i++) if (exf[i] === k) idx.push(i); + const got = decodeCounts(dec, idx.length, mcnt.subarray(k * 128, (k + 1) * 128)); + for (let j = 0; j < idx.length; j++) man[idx[j]] = got[j]; + } + const sign = unpackBits(zstdDecompress(parts[2]), n); + const o = new Uint8Array(n * 2); + for (let i = 0; i < n; i++) { + const v = (sign[i] << 15) | ((exf[i] + emin) << 7) | man[i]; + o[i * 2] = v & 255; + o[i * 2 + 1] = v >> 8; + } + return o; +} + +// --- container --- +export const M_RAW = 0, M_ZSTD = 1, M_TERN = 2, M_BF16 = 3; +const EMB_CHUNK_BYTES = 8192 * 2560 * 2; + +function ownBytes(b) { + return b.buffer instanceof SharedArrayBuffer ? new Uint8Array(b) : b; +} +function textOf(b) { return new TextDecoder().decode(ownBytes(b)); } + +export function segmentsOf(data) { + const dv = new DataView(data.buffer, data.byteOffset, data.byteLength); + const n = Number(dv.getBigUint64(0, true)); + const header = JSON.parse(textOf(data.subarray(8, 8 + n))); + const base = 8 + n; + const segs = [{ name: "header", dtype: null, shape: null, start: 0, end: base }]; + const items = []; + for (const k of Object.keys(header)) { + if (k === "__metadata__") continue; + items.push([header[k].data_offsets[0], k, header[k]]); + } + items.sort((a, b) => a[0] - b[0]); + let pos = base; + for (const [, k, v] of items) { + const s = base + v.data_offsets[0]; + const e = base + v.data_offsets[1]; + if (s > pos) segs.push({ name: "gap", dtype: null, shape: null, start: pos, end: s }); + if (v.dtype === "BF16" && v.shape.length === 2 && e - s > EMB_CHUNK_BYTES) { + const rb = 2 * v.shape[1]; + const rows = Math.max(1, Math.floor(EMB_CHUNK_BYTES / rb)); + for (let r0 = 0; r0 < v.shape[0]; r0 += rows) { + const r1 = Math.min(v.shape[0], r0 + rows); + segs.push({ name: k + "[" + r0 + ":" + r1 + "]", dtype: "BF16", shape: [r1 - r0, v.shape[1]], start: s + r0 * rb, end: s + r1 * rb }); + } + } else { + segs.push({ name: k, dtype: v.dtype, shape: v.shape, start: s, end: e }); + } + pos = e; + } + if (pos < data.length) segs.push({ name: "tail", dtype: null, shape: null, start: pos, end: data.length }); + return segs; +} + +function pick(raw, dtype, shape) { + const cands = [[M_RAW, raw]]; + if (raw.length > 64) cands.push([M_ZSTD, zstdCompress(raw)]); + if (dtype === "U8" && shape && shape.length === 2) { + for (const mode of [0, 1, 2]) { + const c = encTern(raw, shape, mode); + if (c) cands.push([M_TERN, c]); + } + } + if (dtype === "BF16" && raw.length >= 4096) cands.push([M_BF16, encBf16(raw, shape)]); + let best = cands[0]; + for (const c of cands) if (c[1].length < best[1].length) best = c; + return best; +} + +export function compressSafetensors(data) { + const segs = segmentsOf(data); + const recs = []; + for (const seg of segs) { + const raw = data.subarray(seg.start, seg.end); + if (typeof process !== "undefined" && process.stderr) { + process.stderr.write("seg " + (recs.length + 1) + "/" + segs.length + " " + seg.name + " " + raw.length + "\n"); + } + const [method, comp] = pick(raw, seg.dtype, seg.shape); + recs.push({ + name: seg.name, + method, + raw_off: seg.start, + raw_len: raw.length, + shape: method === M_TERN || method === M_BF16 ? seg.shape : null, + sha256: sha256(raw), + comp, + }); + } + let off = 0; + const idx = []; + for (const r of recs) { + idx.push({ name: r.name, method: r.method, raw_off: r.raw_off, raw_len: r.raw_len, off, len: r.comp.length, shape: r.shape, sha256: r.sha256 }); + off += r.comp.length; + } + const ij = new TextEncoder().encode(JSON.stringify({ orig_size: data.length, sha256: sha256(data), segments: idx })); + const out = new Uint8Array(4 + 8 + ij.length + off); + out.set([0x42, 0x4e, 0x5a, 0x32], 0); + new DataView(out.buffer).setBigUint64(4, BigInt(ij.length), true); + out.set(ij, 12); + let p = 12 + ij.length; + for (const r of recs) { out.set(r.comp, p); p += r.comp.length; } + return out; +} + +export function parseBnz(bnz) { + if (bnz.length < 12 || bnz[0] !== 0x42 || bnz[1] !== 0x4e || bnz[2] !== 0x5a || bnz[3] !== 0x32) { + throw new Error("bnz: not a BNZ2 file"); + } + const n = Number(new DataView(bnz.buffer, bnz.byteOffset, bnz.byteLength).getBigUint64(4, true)); + const index = JSON.parse(textOf(bnz.subarray(12, 12 + n))); + return { index, base: 12 + n }; +} + +export function decodeSeg(seg, comp) { + let raw; + if (seg.method === M_RAW) raw = asBytes(comp); + else if (seg.method === M_ZSTD) raw = zstdDecompress(comp); + else if (seg.method === M_TERN) raw = decTern(comp, seg.shape); + else if (seg.method === M_BF16) raw = decBf16(comp, seg.shape); + else throw new Error("bnz: bad method"); + if (raw.length !== seg.raw_len) throw new Error("bnz: " + seg.name + " length"); + if (sha256(raw) !== seg.sha256) throw new Error("bnz: " + seg.name + " hash"); + return raw; +} + +export function decompressSafetensors(bnz) { + const { index, base } = parseBnz(bnz); + const out = new Uint8Array(index.orig_size); + for (const seg of index.segments) { + const raw = decodeSeg(seg, bnz.subarray(base + seg.off, base + seg.off + seg.len)); + out.set(raw, seg.raw_off); + } + if (sha256(out) !== index.sha256) throw new Error("bnz: file hash"); + return out; +} + +// A safetensors-sized view. readAt decodes one BNZ segment at a time. +export function openBytes(bnz, ensure) { + if (ensure) { + ensure(0, Math.min(12, bnz.length)); + const jsonLen = Number(new DataView(bnz.buffer, bnz.byteOffset, 12).getBigUint64(4, true)); + ensure(0, Math.min(bnz.length, 12 + jsonLen)); + } + const { index, base } = parseBnz(bnz); + const segs = index.segments; + let cache = null; + function find(pos) { + let lo = 0, hi = segs.length - 1, ans = 0; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if (segs[mid].raw_off <= pos) { ans = mid; lo = mid + 1; } + else hi = mid - 1; + } + const seg = segs[ans]; + if (pos < seg.raw_off || pos >= seg.raw_off + seg.raw_len) throw new Error("bnz: hole"); + return seg; + } + return { + size: index.orig_size, + readAt(pos, n) { + const out = new Uint8Array(n); + let filled = 0; + while (filled < n) { + const seg = find(pos + filled); + if (!cache || cache.seg !== seg) { + if (ensure) ensure(base + seg.off, seg.len); + cache = { seg, raw: decodeSeg(seg, ownBytes(bnz.subarray(base + seg.off, base + seg.off + seg.len))) }; + } + const inner = pos + filled - seg.raw_off; + const take = Math.min(n - filled, seg.raw_len - inner); + if (take <= 0) throw new Error("bnz: hole"); + out.set(cache.raw.subarray(inner, inner + take), filled); + filled += take; + } + return out; + }, + }; +} diff --git a/bnz4dec.js b/bnz4dec.js new file mode 100644 index 0000000000000000000000000000000000000000..bbec9245bfe8f30a61f184d95a05a7c722f6e6e9 --- /dev/null +++ b/bnz4dec.js @@ -0,0 +1,144 @@ +// bnz4dec.js: BNZ4 segment decoder that leaves the decoded tensor on the GPU. +// From bnz-loader/js/bnz4dec.js (same kernels, same +// container). decode() returns the device buffer holding the raw bytes and, with readRaw, the bytes +// read back. Champ uses the read-back bytes: they are sha256-checked and land in the weight heap +// (bnz4load.js), which the guest reads as model.safetensors. +import { TERN_WGSL, BF16_WGSL } from './bnz4shaders.js'; + +const S = 0x80, CDST = 0x8, CSRC = 0x4; + +function upk(b) { + const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); + const out = []; + for (let i = 0; i < b.length;) { + if (i + 8 > b.length) throw new Error('bad pack'); + const n = Number(dv.getBigUint64(i, true)); i += 8; + if (i + n > b.length) throw new Error('bad pack'); + out.push(b.subarray(i, i + n)); i += n; + } + return out; +} +const u32 = (b) => new Uint32Array(b.buffer.slice(b.byteOffset, b.byteOffset + (b.byteLength & ~3))); +const le32 = (b, o) => new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(o, true); + +function ternW(rc, N) { + const s = [0, 0, 0]; + for (let n = 0; n < N; n++) for (let k = 0; k < 3; k++) s[k] += rc[3 * n + k]; + const g2 = s.map((v) => 2n * BigInt(v) + 1n); + const mn = g2.reduce((a, b) => (b < a ? b : a)); + return g2.map((g) => Number((0xFFFFFFFFn * mn) / g)); +} + +export async function sha256hex(b) { + const h = new Uint8Array(await crypto.subtle.digest('SHA-256', b)); + return Array.from(h, (x) => x.toString(16).padStart(2, '0')).join(''); +} + +export class BNZ4Dec { + constructor(device, zstd) { + this.dev = device; this.zstd = zstd; + this.tern = this.#mod(TERN_WGSL, 7, ['t_build', 't_decode']); + this.bf = this.#mod(BF16_WGSL, 7, ['b_build', 'b_decode']); + } + + #mod(code, nstore, entries) { + const module = this.dev.createShaderModule({ code }); + const ents = [{ binding: 0, visibility: 4, buffer: { type: 'uniform' } }]; + for (let i = 1; i <= nstore; i++) ents.push({ binding: i, visibility: 4, buffer: { type: 'storage' } }); + const bgl = this.dev.createBindGroupLayout({ entries: ents }); + const layout = this.dev.createPipelineLayout({ bindGroupLayouts: [bgl] }); + const pipes = {}; + for (const e of entries) pipes[e] = this.dev.createComputePipeline({ layout, compute: { module, entryPoint: e } }); + return { bgl, pipes }; + } + + #buf(data, size = 0) { + const n = Math.max(4, (Math.max(size, data ? data.byteLength : 0) + 3) & ~3); + const b = this.dev.createBuffer({ size: n, usage: S | CDST | CSRC }); + if (data && data.byteLength) { + let d = data; + if (d.byteLength & 3) { const p = new Uint8Array((d.byteLength + 3) & ~3); p.set(d); d = p; } + this.dev.queue.writeBuffer(b, 0, d); + } + return b; + } + + #uniform(v) { + const a = new Uint32Array((v.length + 3) & ~3); a.set(v); + const b = this.dev.createBuffer({ size: a.byteLength, usage: 0x40 | CDST }); + this.dev.queue.writeBuffer(b, 0, a); + return b; + } + + #run(m, buffers, steps) { + const bg = this.dev.createBindGroup({ layout: m.bgl, entries: buffers.map((buffer, binding) => ({ binding, resource: { buffer } })) }); + const enc = this.dev.createCommandEncoder(); + for (const [entry, threads] of steps) { + const p = enc.beginComputePass(); + p.setPipeline(m.pipes[entry]); p.setBindGroup(0, bg); + const wgs = Math.max(1, Math.ceil(threads / 64)); const x = Math.min(wgs, 65535); + p.dispatchWorkgroups(x, Math.ceil(wgs / x)); p.end(); + } + this.dev.queue.submit([enc.finish()]); + } + + async read(src, off, size) { + const n = Math.max(4, (size + 3) & ~3); + const st = this.dev.createBuffer({ size: n, usage: 0x1 | CDST }); + const enc = this.dev.createCommandEncoder(); + enc.copyBufferToBuffer(src, off, st, 0, n); + this.dev.queue.submit([enc.finish()]); + await st.mapAsync(1); + const out = new Uint8Array(st.getMappedRange()).slice(0, size); + st.unmap(); st.destroy(); + return out; + } + + async #tern(c, R, C, readRaw) { + const p = upk(c); + if (p.length !== 4 || p[0].length !== 12) throw new Error('tern4: bad payload'); + const mode = le32(p[0], 0), rpc = le32(p[0], 4), nch = le32(p[0], 8), N = 4 * R; + const tv = u32(await this.zstd(p[1])); + if (tv.length !== 3 * (N + C) || nch !== Math.ceil(R / rpc) || C % 4) throw new Error('tern4: bad tables'); + const w = ternW(tv, N); + const bufs = [this.#uniform([R, C, N, mode, rpc, nch, w[0], w[1], w[2], 0, N + C, 0]), this.#buf(null, R * C), this.#buf(tv), + this.#buf(null, 4 * (N + C)), this.#buf(p[3]), this.#buf(p[2]), this.#buf(null, 4 * nch), this.#buf(null, 4)]; + this.#run(this.tern, bufs, [['t_build', N + C], ['t_decode', nch]]); + const status = u32(await this.read(bufs[6], 0, 4 * nch)); + const raw = readRaw ? await this.read(bufs[1], 0, R * C) : null; + bufs.forEach((b, i) => { if (i !== 1) b.destroy(); }); + if (status.some((s) => s)) { bufs[1].destroy(); throw new Error('tern4: stream overrun'); } + return { gpu: bufs[1], raw }; + } + + async #bf16(c, shape, readRaw) { + const n = shape.reduce((a, b) => a * b, 1); + const p = upk(c); + if (p.length !== 5 || p[0].length !== 20) throw new Error('bf16x: bad payload'); + const emin = le32(p[0], 0), K = le32(p[0], 4), C = le32(p[0], 8), epc = le32(p[0], 12), nch = le32(p[0], 16); + const M = C * K + K * 128; + const cnt = u32(await this.zstd(p[1])); + const sign = await this.zstd(p[2]); + if (cnt.length !== M || sign.length !== Math.ceil(n / 8) || nch !== Math.ceil(n / epc)) throw new Error('bf16x: bad tables'); + const bufs = [this.#uniform([n, C, K, emin, epc, nch, 0, M]), this.#buf(null, 2 * n), this.#buf(cnt), this.#buf(null, 4 * (2 * M + C + K)), + this.#buf(sign), this.#buf(p[4]), this.#buf(p[3]), this.#buf(null, 4 * (2 + nch))]; + this.#run(this.bf, bufs, [['b_build', C + K], ['b_decode', nch]]); + const status = u32(await this.read(bufs[7], 8, 4 * nch)); + const raw = readRaw ? await this.read(bufs[1], 0, 2 * n) : null; + bufs.forEach((b, i) => { if (i !== 1) b.destroy(); }); + if (status.some((s) => s)) { bufs[1].destroy(); throw new Error('bf16x: stream overrun'); } + return { gpu: bufs[1], raw }; + } + + // decode -> { gpu: GPUBuffer|null (methods 4/5), raw: Uint8Array|null }. + // Methods 0/1 are CPU (raw only). With readRaw the GPU result is also read back. + async decode(seg, payload, readRaw = true) { + switch (seg.method) { + case 0: return { gpu: null, raw: payload }; + case 1: return { gpu: null, raw: this.zstd(payload) }; + case 4: return this.#tern(payload, seg.shape[0], seg.shape[1], readRaw); + case 5: return this.#bf16(payload, seg.shape, readRaw); + default: throw new Error(`${seg.name}: method ${seg.method} not supported`); + } + } +} diff --git a/bnz4fetch.js b/bnz4fetch.js new file mode 100644 index 0000000000000000000000000000000000000000..05dc24a31fd750e83b431d3730be050700ad371e --- /dev/null +++ b/bnz4fetch.js @@ -0,0 +1,15 @@ +// Fills the weight heap with a BNZ4 model's decoded bytes (bnz4load.js), on this worker's own GPU +// device. The guest reads the heap while later segments are still arriving. +import { fillHeap4 } from "./bnz4load.js"; + +self.onmessage = async (e) => { + const m = e.data || {}; + try { + await fillHeap4({ url: m.url, prefix: m.prefix, step: m.step, window: m.window || null }, { buffer: m.buf }, m.table, new Int32Array(m.flags), (p) => { + self.postMessage({ type: "progress", p }); + }); + self.postMessage({ type: "done" }); + } catch (err) { + self.postMessage({ type: "error", text: err && err.message ? err.message : String(err) }); + } +}; diff --git a/bnz4load.js b/bnz4load.js new file mode 100644 index 0000000000000000000000000000000000000000..2ce4553de0b8c0ab2c5a6556c10d5104f7a833e0 --- /dev/null +++ b/bnz4load.js @@ -0,0 +1,287 @@ +// BNZ4 weights into Champ's weight heap. From bnz-loader/js/bnz-loader.js: the 12-byte header and +// JSON index first; verified segments cached in OPFS under bnz4//; the +// missing ones fetched as coalesced HTTP Range runs in file order (4 at a time, at most `budget` +// bytes fetched but not yet decoded); methods 4 and 5 decoded on the GPU (bnz4dec.js), 0 and 1 on +// the CPU; every segment sha256-checked against the index, and a bad one dropped and fetched again +// on its own. Where bnz-loader copies into the runtime's GPU buffers, this lands each segment's raw +// bytes in the heap at raw_off: the guest reads the heap as model.safetensors (bnzshare.js openRaw) +// while later segments are still arriving, so its upload() is unchanged. +import { BNZ4Dec, sha256hex } from "./bnz4dec.js"; +import { decompress } from "./fzstd.js"; +import { notePages } from "./bnzshare.js"; + +const MAGIC = "BNZ4"; +const KEEP = 3; // OPFS keeps the segments of this many models, the most recently used + +async function rangeGet(url, a, n) { + const r = await fetch(url, { headers: { Range: "bytes=" + a + "-" + (a + n - 1) } }); + if (r.status !== 206) throw new Error("Range " + a + "+" + n + " answered " + r.status); + const b = new Uint8Array(await r.arrayBuffer()); + if (b.length !== n) throw new Error("Range " + a + "+" + n + " gave " + b.length + " bytes"); + return b; +} + +function zstd(b) { + return decompress(b.byteOffset === 0 && b.byteLength === b.buffer.byteLength ? b : b.slice()); +} + +// The header and the JSON index: the heap's size comes from the index, so this runs first. +export async function readIndex(url) { + const head = await rangeGet(url, 0, 12); + if (String.fromCharCode(head[0], head[1], head[2], head[3]) !== MAGIC) throw new Error("not a BNZ4 file"); + const n = Number(new DataView(head.buffer).getBigUint64(4, true)); + if (!(n > 0 && n < 64 << 20)) throw new Error("BNZ4: index size " + n); + const body = await rangeGet(url, 12, n); + const prefix = new Uint8Array(12 + n); + prefix.set(head); + prefix.set(body, 12); + const index = JSON.parse(new TextDecoder().decode(body)); + plan(index); + return { prefix, index }; +} + +// The segments in file order, checked to tile [0, orig_size) exactly: the heap's ready flags count +// bytes, so a gap or an overlap would leave the guest waiting or reading a hole. +function plan(index) { + const size = index && index.orig_size; + if (!Number.isSafeInteger(size) || size <= 0) throw new Error("BNZ4: orig_size"); + const segs = (Array.isArray(index.segments) ? index.segments : []).map((s, i) => Object.assign({}, s, { i })); + for (const s of segs) { + for (const k of ["raw_off", "raw_len", "off", "len", "method"]) { + if (!Number.isSafeInteger(s[k]) || s[k] < 0) throw new Error("BNZ4: segment " + s.i + " " + k); + } + if (!/^[0-9a-f]{64}$/.test(String(s.sha256 || ""))) throw new Error("BNZ4: segment " + s.i + " sha256"); + } + segs.sort((a, b) => a.raw_off - b.raw_off); + let at = 0; + for (const s of segs) { + if (s.raw_off !== at) throw new Error("BNZ4: the segments do not cover byte " + at); + at += s.raw_len; + } + if (at !== size) throw new Error("BNZ4: the segments end at " + at + ", not " + size); + return segs; +} + +async function gpuDevice() { + if (!navigator.gpu) throw new Error("BNZ4 needs WebGPU in this worker"); + const ad = await navigator.gpu.requestAdapter(); + if (!ad) throw new Error("BNZ4: no WebGPU adapter"); + return ad.requestDevice({ + requiredLimits: { + maxStorageBufferBindingSize: ad.limits.maxStorageBufferBindingSize, + maxBufferSize: ad.limits.maxBufferSize, + }, + }); +} + +async function cacheTop() { + if (!navigator.storage || !navigator.storage.getDirectory) return null; + try { + const root = await navigator.storage.getDirectory(); + return await root.getDirectoryHandle("bnz4", { create: true }); + } catch { + return null; + } +} + +// After a full load: mark this model used, and drop all but the KEEP most recently used. +async function prune(top, keepName) { + try { + const mark = await (await top.getDirectoryHandle(keepName)).getFileHandle(".used", { create: true }); + const w = await mark.createWritable(); + await w.write(String(Date.now())); + await w.close(); + const used = []; + for await (const [name, h] of top.entries()) { + if (h.kind !== "directory") continue; + let t = 0; + try { t = Number(await (await (await h.getFileHandle(".used")).getFile()).text()) || 0; } catch { t = 0; } + used.push([name, t]); + } + used.sort((a, b) => b[1] - a[1]); + for (const [name] of used.slice(KEEP)) { + if (name !== keepName) await top.removeEntry(name, { recursive: true }); + } + } catch { /* storage is a cache: a failure here only costs a later download */ } +} + +// spec: { url, prefix (header + index bytes), step }; mem.buffer is the heap; table its page table; +// flags[i] is step i of the raw image: 0 missing, 1 ready, -1 failed. +export async function fillHeap4(spec, mem, table, flags, onProgress, opts) { + const o = Object.assign({ concurrency: 4, maxRun: 32 << 20, budget: 192 << 20, retries: 3 }, opts || {}); + const prefix = spec.prefix; + const index = JSON.parse(new TextDecoder().decode(prefix.subarray(12))); + const segs = plan(index); + const size = index.orig_size; + const step = spec.step; + const base = prefix.length; + const win = spec.window || null; + const viewLen = win ? win.bytes : size; + const data = new Uint8Array(mem.buffer, 0, viewLen); + const owners = win ? new Int32Array(win.owners) : null; + const rel = win ? new Int32Array(win.ctrl) : null; + const chunks = Math.ceil(size / step); + const got = new Float64Array(chunks); + + function failAll() { + for (let i = 0; i < chunks; i++) { + if (Atomics.load(flags, i) === 0) { + Atomics.store(flags, i, -1); + Atomics.notify(flags, i); + } + } + } + function claim(stepIndex) { + const slot = stepIndex % win.slots; + for (;;) { + const owner = Atomics.load(owners, slot); + if (owner === stepIndex) return slot; + const done = Atomics.load(rel, 0); + if (owner < 0 || owner < done) { + if (Atomics.compareExchange(owners, slot, owner, stepIndex) === owner) { + if (owner >= 0) Atomics.store(flags, owner, 0); + return slot; + } + } else { + const seen = Atomics.load(rel, 0); + Atomics.wait(rel, 0, seen, 120000); + } + } + } + function land(raw, off) { + if (!win) { + data.set(raw, off); + notePages(table, off, raw.length, size); + } + const end = off + raw.length; + for (let pos = off; pos < end; ) { + const i = Math.floor(pos / step); + const stop = Math.min(end, (i + 1) * step); + const n = stop - pos; + if (win) { + const within = pos - i * step; + const slot = claim(i); + data.set(raw.subarray(pos - off, pos - off + n), slot * step + within); + notePages(table, slot * step + within, n, win.bytes); + } + got[i] += n; + if (got[i] >= Math.min(step, size - i * step) && Atomics.load(flags, i) !== 1) { + Atomics.store(flags, i, 1); + Atomics.notify(flags, i); + } + pos = stop; + } + } + + try { + const dec = new BNZ4Dec(await gpuDevice(), zstd); + const top = await cacheTop(); + const key = await sha256hex(prefix); + let dir = null; + if (top) { + try { dir = await top.getDirectoryHandle(key, { create: true }); } catch { dir = null; } + } + const cachedFile = async (seg) => { + if (!dir) return null; + try { + const f = await (await dir.getFileHandle(String(seg.i))).getFile(); + return f.size === seg.len ? f : null; + } catch { + return null; + } + }; + + // What OPFS has (sizes only; the bytes are read when the segment's turn comes), and the + // network runs for the rest, in file order. + const fromCache = new Set(); + for (const s of segs) if (s.len && (await cachedFile(s))) fromCache.add(s.i); + const wait = new Map(); + const runs = []; + let run = null; + for (const s of segs) { + if (!s.len || fromCache.has(s.i)) continue; + let resolve, reject; + const p = new Promise((a, b) => { resolve = a; reject = b; }); + p.catch(() => {}); + wait.set(s.i, { p, resolve, reject }); + if (run && run.end === s.off && run.end - run.off + s.len <= o.maxRun) { + run.segs.push(s); + run.end += s.len; + } else { + run = { off: s.off, end: s.off + s.len, segs: [s] }; + runs.push(run); + } + } + let inflight = 0; + const waiters = []; + const release = (n) => { + inflight -= n; + waiters.splice(0).forEach((w) => w()); + }; + let next = 0; + const fetcher = async () => { + while (next < runs.length) { + const r = runs[next++]; + const n = r.end - r.off; + while (inflight > 0 && inflight + n > o.budget) await new Promise((res) => waiters.push(res)); + inflight += n; + try { + const b = await rangeGet(spec.url, base + r.off, n); + for (const s of r.segs) wait.get(s.i).resolve(b.subarray(s.off - r.off, s.off - r.off + s.len)); + } catch (e) { + for (const s of r.segs) wait.get(s.i).reject(e); + } + } + }; + Promise.all(Array.from({ length: o.concurrency }, fetcher)).catch(() => {}); + + const total = segs.reduce((a, s) => a + s.len, 0) || 1; + let done = 0; + const writes = []; + if (onProgress) onProgress(0); + for (const seg of segs) { + if (!seg.raw_len) continue; + const fresh = !fromCache.has(seg.i); + let payload; + if (fresh) { + payload = seg.len ? await wait.get(seg.i).p : new Uint8Array(0); + } else { + const f = await cachedFile(seg); + payload = f ? new Uint8Array(await f.arrayBuffer()) : await rangeGet(spec.url, base + seg.off, seg.len); + } + for (let attempt = 0; ; attempt++) { + try { + const { gpu, raw } = await dec.decode(seg, payload, true); + if (gpu) gpu.destroy(); + if (!raw || raw.length !== seg.raw_len || (await sha256hex(raw)) !== seg.sha256) { + throw new Error(seg.name + ": sha256 mismatch"); + } + land(raw, seg.raw_off); + if ((fresh || attempt > 0) && dir) { + const keep = payload; + writes.push((async () => { + const w = await (await dir.getFileHandle(String(seg.i), { create: true })).createWritable(); + await w.write(keep); + await w.close(); + })().catch(() => {})); + } + break; + } catch (e) { + if (attempt >= o.retries) throw e; + if (dir) { + try { await dir.removeEntry(String(seg.i)); } catch { /* not cached */ } + } + payload = await rangeGet(spec.url, base + seg.off, seg.len); + } + } + if (fresh) release(seg.len); + done += seg.len; + if (onProgress) onProgress(done / total); + } + await Promise.all(writes); + if (top) await prune(top, key); + } catch (err) { + failAll(); + throw err; + } +} diff --git a/bnz4shaders.js b/bnz4shaders.js new file mode 100644 index 0000000000000000000000000000000000000000..47820869315b5892c9441255c114ca212cf37051 --- /dev/null +++ b/bnz4shaders.js @@ -0,0 +1,4 @@ +// Generated by `go run ./cmd/genjs` from shaders/*.wgsl. Do not edit. +export const TERN_WGSL = "// BNZ4 shared code: 32-bit rANS (L=2^23, byte renorm, 16-bit probs) and integer models.\n// Every module that includes this declares `st: array\u003cu32\u003e` (the byte stream / encode scratch).\n// u32 only, no u64, no floats.\n\nconst PT: u32 = 65536u; // probability total\nconst RL: u32 = 8388608u; // rANS lower bound 2^23\n\nfn mulhi(a: u32, b: u32) -\u003e u32 {\n let a0 = a \u0026 0xFFFFu; let a1 = a \u003e\u003e 16u;\n let b0 = b \u0026 0xFFFFu; let b1 = b \u003e\u003e 16u;\n let p00 = a0 * b0; let p01 = a0 * b1; let p10 = a1 * b0; let p11 = a1 * b1;\n let mid = (p00 \u003e\u003e 16u) + (p01 \u0026 0xFFFFu) + (p10 \u0026 0xFFFFu);\n return p11 + (p01 \u003e\u003e 16u) + (p10 \u003e\u003e 16u) + (mid \u003e\u003e 16u);\n}\n\n// f_k = 1 + a_k*(T-3)/S, a_k in [1, 2^16).\nfn quant3i(a0: u32, a1: u32, a2: u32) -\u003e vec2\u003cu32\u003e {\n let s = a0 + a1 + a2;\n return vec2\u003cu32\u003e(1u + (a0 * (PT - 3u)) / s, 1u + (a1 * (PT - 3u)) / s);\n}\n\nfn mode2f(r: vec3\u003cu32\u003e, c: vec3\u003cu32\u003e, w: vec3\u003cu32\u003e) -\u003e vec2\u003cu32\u003e {\n let p0 = mulhi((2u * r.x + 1u) * (2u * c.x + 1u), w.x);\n let p1 = mulhi((2u * r.y + 1u) * (2u * c.y + 1u), w.y);\n let p2 = mulhi((2u * r.z + 1u) * (2u * c.z + 1u), w.z);\n let m = max(p0, max(p1, p2));\n let bl = 32u - countLeadingZeros(m);\n var sh = 0u;\n if (bl \u003e 15u) { sh = bl - 15u; }\n return quant3i((p0 \u003e\u003e sh) + 1u, (p1 \u003e\u003e sh) + 1u, (p2 \u003e\u003e sh) + 1u);\n}\n\n// ---- decoder: stream bytes [base, base+len) of st; reads past the end return 0 (as Go) ----\nstruct Dec { x: u32, pos: u32, base: u32, len: u32 }\n\nfn getb(d: ptr\u003cfunction, Dec\u003e) -\u003e u32 {\n var b = 0u;\n if ((*d).pos \u003c (*d).len) {\n let g = (*d).base + (*d).pos;\n b = (st[g \u003e\u003e 2u] \u003e\u003e ((g \u0026 3u) * 8u)) \u0026 255u;\n }\n (*d).pos = (*d).pos + 1u;\n return b;\n}\n\nfn dec_init(base: u32, len: u32) -\u003e Dec {\n var d = Dec(0u, 0u, base, len);\n for (var i = 0u; i \u003c 4u; i++) { d.x = (d.x \u003c\u003c 8u) | getb(\u0026d); }\n return d;\n}\n\nfn dec_adv(d: ptr\u003cfunction, Dec\u003e, start: u32, f: u32) {\n var x = f * ((*d).x \u003e\u003e 16u) + ((*d).x \u0026 0xFFFFu) - start;\n while (x \u003c RL) { x = (x \u003c\u003c 8u) | getb(d); }\n (*d).x = x;\n}\n\n// ---- encoder: writes bytes downward into the thread's own scratch region of st ----\nstruct Enc { x: u32, p: u32 }\n\nfn putb(p: u32, b: u32) {\n let w = p \u003e\u003e 2u; let sh = (p \u0026 3u) * 8u;\n st[w] = (st[w] \u0026 ~(255u \u003c\u003c sh)) | (b \u003c\u003c sh);\n}\n\nfn enc_put(e: ptr\u003cfunction, Enc\u003e, start: u32, f: u32) {\n var x = (*e).x;\n let xmax = 32768u * f; // ((L \u003e\u003e 16) \u003c\u003c 8) * f\n while (x \u003e= xmax) { (*e).p = (*e).p - 1u; putb((*e).p, x \u0026 255u); x = x \u003e\u003e 8u; }\n (*e).x = (x / f) * PT + (x % f) + start;\n}\n\nfn enc_flush(e: ptr\u003cfunction, Enc\u003e) {\n var x = (*e).x;\n for (var i = 0u; i \u003c 4u; i++) { (*e).p = (*e).p - 1u; putb((*e).p, x \u0026 255u); x = x \u003e\u003e 8u; }\n}\n\n// BNZ4 method 4: chunked ternary. Chunk k = rows [k*rpc, min(R,(k+1)*rpc)), order r, c, plane s.\nstruct TP { R: u32, C: u32, N: u32, mode: u32, rpc: u32, nch: u32, w0: u32, w1: u32, w2: u32, cap: u32, loff: u32, pad: u32 }\n@group(0) @binding(0) var\u003cuniform\u003e P: TP;\n@group(0) @binding(1) var\u003cstorage, read_write\u003e raw: array\u003cu32\u003e; // packed U8 R x C\n@group(0) @binding(2) var\u003cstorage, read_write\u003e tab: array\u003cu32\u003e; // rc[3N] ++ cc[3C]\n@group(0) @binding(3) var\u003cstorage, read_write\u003e ft: array\u003cu32\u003e; // rowF[N] ++ colF[C] ++ L[65537]\n@group(0) @binding(4) var\u003cstorage, read_write\u003e st: array\u003cu32\u003e; // streams / encode scratch\n@group(0) @binding(5) var\u003cstorage, read_write\u003e offs: array\u003cu32\u003e; // decode: dir[nch+1]; encode: lens[nch]\n@group(0) @binding(6) var\u003cstorage, read_write\u003e aux: array\u003cu32\u003e; // decode: status[nch]; cost: [3*nch]\n@group(0) @binding(7) var\u003cstorage, read_write\u003e flag: array\u003catomic\u003cu32\u003e\u003e;\n\nfn tid(g: vec3\u003cu32\u003e, nw: vec3\u003cu32\u003e) -\u003e u32 { return g.x + g.y * nw.x * 64u; }\n\nfn rbyte(r: u32, c: u32) -\u003e u32 { let i = r * P.C + c; return (raw[i \u003e\u003e 2u] \u003e\u003e ((i \u0026 3u) * 8u)) \u0026 255u; }\n\nfn freqs(mode: u32, n: u32, c: u32) -\u003e vec2\u003cu32\u003e {\n if (mode == 0u) { let v = ft[n]; return vec2\u003cu32\u003e(v \u0026 0xFFFFu, v \u003e\u003e 16u); }\n if (mode == 1u) { let v = ft[P.N + c]; return vec2\u003cu32\u003e(v \u0026 0xFFFFu, v \u003e\u003e 16u); }\n let a = 3u * n; let b = 3u * (P.N + c);\n return mode2f(vec3\u003cu32\u003e(tab[a], tab[a + 1u], tab[a + 2u]), vec3\u003cu32\u003e(tab[b], tab[b + 1u], tab[b + 2u]), vec3\u003cu32\u003e(P.w0, P.w1, P.w2));\n}\n\n// returns (start, freq) for trit t\nfn symfs(t: u32, f: vec2\u003cu32\u003e) -\u003e vec2\u003cu32\u003e {\n if (t == 0u) { return vec2\u003cu32\u003e(0u, f.x); }\n if (t == 1u) { return vec2\u003cu32\u003e(f.x, f.y); }\n return vec2\u003cu32\u003e(f.x + f.y, PT - f.x - f.y);\n}\n\n@compute @workgroup_size(64)\nfn t_count_rows(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let r = tid(g, nw);\n if (r \u003e= P.R) { return; }\n var cnt: array\u003cu32, 12\u003e;\n var bad = 0u;\n for (var c = 0u; c \u003c P.C; c++) {\n let b = rbyte(r, c);\n for (var s = 0u; s \u003c 4u; s++) {\n let t = (b \u003e\u003e (2u * s)) \u0026 3u;\n if (t == 3u) { bad = 1u; } else { cnt[3u * s + t] += 1u; }\n }\n }\n for (var s = 0u; s \u003c 4u; s++) {\n for (var k = 0u; k \u003c 3u; k++) { tab[3u * (s * P.R + r) + k] = cnt[3u * s + k]; }\n }\n if (bad != 0u) { atomicOr(\u0026flag[0], 1u); }\n}\n\n@compute @workgroup_size(64)\nfn t_count_cols(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let c = tid(g, nw);\n if (c \u003e= P.C) { return; }\n var cnt = vec3\u003cu32\u003e(0u);\n for (var r = 0u; r \u003c P.R; r++) {\n let b = rbyte(r, c);\n for (var s = 0u; s \u003c 4u; s++) {\n let t = (b \u003e\u003e (2u * s)) \u0026 3u;\n if (t \u003c 3u) { cnt[t] += 1u; }\n }\n }\n let o = 3u * (P.N + c);\n tab[o] = cnt.x; tab[o + 1u] = cnt.y; tab[o + 2u] = cnt.z;\n}\n\n// count model -\u003e quantized f0|f1\u003c\u003c16 tables (rows then columns)\n@compute @workgroup_size(64)\nfn t_build(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let i = tid(g, nw);\n if (i \u003e= P.N + P.C) { return; }\n let o = 3u * i;\n let f = quant3i(2u * tab[o] + 1u, 2u * tab[o + 1u] + 1u, 2u * tab[o + 2u] + 1u);\n ft[i] = f.x | (f.y \u003c\u003c 16u);\n}\n\n@compute @workgroup_size(64)\nfn t_cost(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let r1 = min(P.R, (k + 1u) * P.rpc);\n for (var mode = 0u; mode \u003c 3u; mode++) {\n var s = 0u;\n for (var r = k * P.rpc; r \u003c r1; r++) {\n for (var c = 0u; c \u003c P.C; c++) {\n let b = rbyte(r, c);\n for (var sp = 0u; sp \u003c 4u; sp++) {\n let fs = symfs((b \u003e\u003e (2u * sp)) \u0026 3u, freqs(mode, sp * P.R + r, c));\n s += ft[P.loff + fs.y];\n }\n }\n }\n aux[3u * k + mode] = s;\n }\n}\n\n@compute @workgroup_size(64)\nfn t_encode(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let r0 = k * P.rpc; let r1 = min(P.R, (k + 1u) * P.rpc);\n let end = (k + 1u) * P.cap;\n var e = Enc(RL, end);\n for (var r = r1; r \u003e r0; r--) {\n for (var c = P.C; c \u003e 0u; c--) {\n let b = rbyte(r - 1u, c - 1u);\n for (var sp = 4u; sp \u003e 0u; sp--) {\n let fs = symfs((b \u003e\u003e (2u * (sp - 1u))) \u0026 3u, freqs(P.mode, (sp - 1u) * P.R + r - 1u, c - 1u));\n enc_put(\u0026e, fs.x, fs.y);\n }\n }\n }\n enc_flush(\u0026e);\n offs[k] = end - e.p;\n}\n\n@compute @workgroup_size(64)\nfn t_decode(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let r1 = min(P.R, (k + 1u) * P.rpc);\n var d = dec_init(offs[k], offs[k + 1u] - offs[k]);\n for (var r = k * P.rpc; r \u003c r1; r++) {\n for (var c4 = 0u; c4 \u003c P.C; c4 += 4u) {\n var word = 0u;\n for (var j = 0u; j \u003c 4u; j++) {\n var by = 0u;\n for (var sp = 0u; sp \u003c 4u; sp++) {\n let f = freqs(P.mode, sp * P.R + r, c4 + j);\n let x = d.x \u0026 0xFFFFu;\n var t = 2u;\n if (x \u003c f.x) { t = 0u; } else if (x \u003c f.x + f.y) { t = 1u; }\n let fs = symfs(t, f);\n dec_adv(\u0026d, fs.x, fs.y);\n by |= t \u003c\u003c (2u * sp);\n }\n word |= by \u003c\u003c (8u * j);\n }\n raw[(r * P.C + c4) \u003e\u003e 2u] = word;\n }\n }\n aux[k] = select(0u, 1u, d.pos \u003e d.len);\n}\n"; +export const BF16_WGSL = "// BNZ4 shared code: 32-bit rANS (L=2^23, byte renorm, 16-bit probs) and integer models.\n// Every module that includes this declares `st: array\u003cu32\u003e` (the byte stream / encode scratch).\n// u32 only, no u64, no floats.\n\nconst PT: u32 = 65536u; // probability total\nconst RL: u32 = 8388608u; // rANS lower bound 2^23\n\nfn mulhi(a: u32, b: u32) -\u003e u32 {\n let a0 = a \u0026 0xFFFFu; let a1 = a \u003e\u003e 16u;\n let b0 = b \u0026 0xFFFFu; let b1 = b \u003e\u003e 16u;\n let p00 = a0 * b0; let p01 = a0 * b1; let p10 = a1 * b0; let p11 = a1 * b1;\n let mid = (p00 \u003e\u003e 16u) + (p01 \u0026 0xFFFFu) + (p10 \u0026 0xFFFFu);\n return p11 + (p01 \u003e\u003e 16u) + (p10 \u003e\u003e 16u) + (mid \u003e\u003e 16u);\n}\n\n// f_k = 1 + a_k*(T-3)/S, a_k in [1, 2^16).\nfn quant3i(a0: u32, a1: u32, a2: u32) -\u003e vec2\u003cu32\u003e {\n let s = a0 + a1 + a2;\n return vec2\u003cu32\u003e(1u + (a0 * (PT - 3u)) / s, 1u + (a1 * (PT - 3u)) / s);\n}\n\nfn mode2f(r: vec3\u003cu32\u003e, c: vec3\u003cu32\u003e, w: vec3\u003cu32\u003e) -\u003e vec2\u003cu32\u003e {\n let p0 = mulhi((2u * r.x + 1u) * (2u * c.x + 1u), w.x);\n let p1 = mulhi((2u * r.y + 1u) * (2u * c.y + 1u), w.y);\n let p2 = mulhi((2u * r.z + 1u) * (2u * c.z + 1u), w.z);\n let m = max(p0, max(p1, p2));\n let bl = 32u - countLeadingZeros(m);\n var sh = 0u;\n if (bl \u003e 15u) { sh = bl - 15u; }\n return quant3i((p0 \u003e\u003e sh) + 1u, (p1 \u003e\u003e sh) + 1u, (p2 \u003e\u003e sh) + 1u);\n}\n\n// ---- decoder: stream bytes [base, base+len) of st; reads past the end return 0 (as Go) ----\nstruct Dec { x: u32, pos: u32, base: u32, len: u32 }\n\nfn getb(d: ptr\u003cfunction, Dec\u003e) -\u003e u32 {\n var b = 0u;\n if ((*d).pos \u003c (*d).len) {\n let g = (*d).base + (*d).pos;\n b = (st[g \u003e\u003e 2u] \u003e\u003e ((g \u0026 3u) * 8u)) \u0026 255u;\n }\n (*d).pos = (*d).pos + 1u;\n return b;\n}\n\nfn dec_init(base: u32, len: u32) -\u003e Dec {\n var d = Dec(0u, 0u, base, len);\n for (var i = 0u; i \u003c 4u; i++) { d.x = (d.x \u003c\u003c 8u) | getb(\u0026d); }\n return d;\n}\n\nfn dec_adv(d: ptr\u003cfunction, Dec\u003e, start: u32, f: u32) {\n var x = f * ((*d).x \u003e\u003e 16u) + ((*d).x \u0026 0xFFFFu) - start;\n while (x \u003c RL) { x = (x \u003c\u003c 8u) | getb(d); }\n (*d).x = x;\n}\n\n// ---- encoder: writes bytes downward into the thread's own scratch region of st ----\nstruct Enc { x: u32, p: u32 }\n\nfn putb(p: u32, b: u32) {\n let w = p \u003e\u003e 2u; let sh = (p \u0026 3u) * 8u;\n st[w] = (st[w] \u0026 ~(255u \u003c\u003c sh)) | (b \u003c\u003c sh);\n}\n\nfn enc_put(e: ptr\u003cfunction, Enc\u003e, start: u32, f: u32) {\n var x = (*e).x;\n let xmax = 32768u * f; // ((L \u003e\u003e 16) \u003c\u003c 8) * f\n while (x \u003e= xmax) { (*e).p = (*e).p - 1u; putb((*e).p, x \u0026 255u); x = x \u003e\u003e 8u; }\n (*e).x = (x / f) * PT + (x % f) + start;\n}\n\nfn enc_flush(e: ptr\u003cfunction, Enc\u003e) {\n var x = (*e).x;\n for (var i = 0u; i \u003c 4u; i++) { (*e).p = (*e).p - 1u; putb((*e).p, x \u0026 255u); x = x \u003e\u003e 8u; }\n}\n\n// BNZ4 method 5: chunked bf16 split. Chunk k = elements [k*epc, min(n,(k+1)*epc)), exponent then mantissa.\nstruct BP { n: u32, C: u32, K: u32, emin: u32, epc: u32, nch: u32, cap: u32, M: u32 }\n@group(0) @binding(0) var\u003cuniform\u003e P: BP;\n@group(0) @binding(1) var\u003cstorage, read_write\u003e raw: array\u003cu32\u003e; // bf16 pairs\n@group(0) @binding(2) var\u003cstorage, read_write\u003e cnt: array\u003catomic\u003cu32\u003e\u003e; // ecnt[C*K] ++ mcnt[K*128]\n@group(0) @binding(3) var\u003cstorage, read_write\u003e tb: array\u003cu32\u003e; // f[M] ++ cum[M] ++ meta[C+K]\n@group(0) @binding(4) var\u003cstorage, read_write\u003e sg: array\u003cu32\u003e; // sign bytes, MSB-first\n@group(0) @binding(5) var\u003cstorage, read_write\u003e st: array\u003cu32\u003e;\n@group(0) @binding(6) var\u003cstorage, read_write\u003e offs: array\u003cu32\u003e;\n@group(0) @binding(7) var\u003cstorage, read_write\u003e aux: array\u003catomic\u003cu32\u003e\u003e; // [0]=emin [1]=emax [2+k]=status\n\nfn tid(g: vec3\u003cu32\u003e, nw: vec3\u003cu32\u003e) -\u003e u32 { return g.x + g.y * nw.x * 64u; }\nfn nthreads(nw: vec3\u003cu32\u003e) -\u003e u32 { return nw.x * nw.y * 64u; }\nfn elem(i: u32) -\u003e u32 { return (raw[i \u003e\u003e 1u] \u003e\u003e ((i \u0026 1u) * 16u)) \u0026 0xFFFFu; }\n\n@compute @workgroup_size(64)\nfn b_minmax(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n var lo = 255u; var hi = 0u;\n for (var i = tid(g, nw); i \u003c P.n; i += nthreads(nw)) {\n let e = (elem(i) \u003e\u003e 7u) \u0026 255u; lo = min(lo, e); hi = max(hi, e);\n }\n atomicMin(\u0026aux[0], lo); atomicMax(\u0026aux[1], hi);\n}\n\n@compute @workgroup_size(64)\nfn b_hist(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n for (var i = tid(g, nw); i \u003c P.n; i += nthreads(nw)) {\n let x = elem(i);\n let e = ((x \u003e\u003e 7u) \u0026 255u) - P.emin;\n atomicAdd(\u0026cnt[(i % P.C) * P.K + e], 1u);\n atomicAdd(\u0026cnt[P.C * P.K + e * 128u + (x \u0026 127u)], 1u);\n }\n}\n\n@compute @workgroup_size(64)\nfn b_sign(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let nwd = (P.n + 31u) / 32u;\n for (var j = tid(g, nw); j \u003c nwd; j += nthreads(nw)) {\n var w = 0u;\n for (var q = 0u; q \u003c 32u; q++) {\n let i = 32u * j + q;\n if (i \u003c P.n \u0026\u0026 (elem(i) \u003e\u003e 15u) != 0u) { w |= (0x80u \u003e\u003e (q \u0026 7u)) \u003c\u003c (8u * (q \u003e\u003e 3u)); }\n }\n sg[j] = w;\n }\n}\n\n// floor(c * 2^16 / t) with c \u003c= t \u003c 2^31, by 48-step long division (no u64)\nfn qdiv(c: u32, t: u32) -\u003e u32 {\n var rem = 0u; var q = 0u;\n for (var b = 0u; b \u003c 48u; b++) {\n var bit = 0u;\n if (b \u003c 32u) { bit = (c \u003e\u003e (31u - b)) \u0026 1u; }\n rem = (rem \u003c\u003c 1u) | bit;\n q = q \u003c\u003c 1u;\n if (rem \u003e= t) { rem -= t; q |= 1u; }\n }\n return q;\n}\n\n// Quantize (same as Go rans.Quantize) for table t: counts at cnt[co..co+sz), output f at tb[co..]\n@compute @workgroup_size(64)\nfn b_build(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let t = tid(g, nw);\n if (t \u003e= P.C + P.K) { return; }\n var co = t * P.K; var sz = P.K;\n if (t \u003e= P.C) { co = P.C * P.K + (t - P.C) * 128u; sz = 128u; }\n var total = 0u; var nz = 0u; var only = 0xFFFFFFFFu;\n for (var i = 0u; i \u003c sz; i++) {\n let c = atomicLoad(\u0026cnt[co + i]);\n total += c;\n if (c \u003e 0u) { nz += 1u; if (only == 0xFFFFFFFFu) { only = i; } }\n }\n if (only == 0xFFFFFFFFu) { only = 0u; }\n if (nz \u003c 2u) {\n for (var i = 0u; i \u003c sz; i++) { tb[co + i] = 0u; tb[P.M + co + i] = 0u; }\n tb[2u * P.M + t] = only;\n return;\n }\n var sum = 0i;\n for (var i = 0u; i \u003c sz; i++) {\n let c = atomicLoad(\u0026cnt[co + i]);\n var v = 0u;\n if (c \u003e 0u) { v = max(1u, qdiv(c, total)); }\n tb[co + i] = v; sum += i32(v);\n }\n let T = i32(PT);\n while (sum != T) {\n var bi = 0u;\n for (var i = 1u; i \u003c sz; i++) { if (tb[co + i] \u003e tb[co + bi]) { bi = i; } }\n if (sum \u003c T) {\n tb[co + bi] += u32(T - sum); sum = T;\n } else {\n var d = sum - T;\n let fb = i32(tb[co + bi]);\n if (fb - 1 \u003c d) { d = fb - 1; }\n tb[co + bi] = u32(fb - d); sum -= d;\n }\n }\n var acc = 0u;\n for (var i = 0u; i \u003c sz; i++) { tb[P.M + co + i] = acc; acc += tb[co + i]; }\n tb[2u * P.M + t] = only | 0x80000000u;\n}\n\n@compute @workgroup_size(64)\nfn b_encode(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let i0 = k * P.epc; let i1 = min(P.n, (k + 1u) * P.epc);\n let end = (k + 1u) * P.cap;\n var e = Enc(RL, end);\n for (var i = i1; i \u003e i0; i--) {\n let x = elem(i - 1u);\n let ex = ((x \u003e\u003e 7u) \u0026 255u) - P.emin;\n let mt = P.C + ex;\n if ((tb[2u * P.M + mt] \u003e\u003e 31u) != 0u) {\n let o = P.C * P.K + ex * 128u + (x \u0026 127u);\n enc_put(\u0026e, tb[P.M + o], tb[o]);\n }\n let et = (i - 1u) % P.C;\n if ((tb[2u * P.M + et] \u003e\u003e 31u) != 0u) {\n let o = et * P.K + ex;\n enc_put(\u0026e, tb[P.M + o], tb[o]);\n }\n }\n enc_flush(\u0026e);\n offs[k] = end - e.p;\n}\n\n// smallest i in [0,sz) with cum[i]+f[i] \u003e x\nfn find(co: u32, sz: u32, x: u32) -\u003e u32 {\n var lo = 0u; var hi = sz;\n while (lo \u003c hi) {\n let mid = (lo + hi) \u003e\u003e 1u;\n if (tb[P.M + co + mid] + tb[co + mid] \u003e x) { hi = mid; } else { lo = mid + 1u; }\n }\n return lo;\n}\n\n@compute @workgroup_size(64)\nfn b_decode(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let i0 = k * P.epc; let i1 = min(P.n, (k + 1u) * P.epc);\n var d = dec_init(offs[k], offs[k + 1u] - offs[k]);\n var word = 0u;\n for (var i = i0; i \u003c i1; i++) {\n let et = i % P.C;\n let me = tb[2u * P.M + et];\n var ex = me \u0026 0x7FFFFFFFu;\n if ((me \u003e\u003e 31u) != 0u) {\n let co = et * P.K;\n ex = find(co, P.K, d.x \u0026 0xFFFFu);\n dec_adv(\u0026d, tb[P.M + co + ex], tb[co + ex]);\n }\n let mm = tb[2u * P.M + P.C + ex];\n var s = mm \u0026 0x7FFFFFFFu;\n if ((mm \u003e\u003e 31u) != 0u) {\n let co = P.C * P.K + ex * 128u;\n s = find(co, 128u, d.x \u0026 0xFFFFu);\n dec_adv(\u0026d, tb[P.M + co + s], tb[co + s]);\n }\n var v = ((ex + P.emin) \u003c\u003c 7u) | s;\n let sb = (sg[i \u003e\u003e 5u] \u003e\u003e (8u * ((i \u003e\u003e 3u) \u0026 3u))) \u0026 255u;\n if ((sb \u0026 (0x80u \u003e\u003e (i \u0026 7u))) != 0u) { v |= 0x8000u; }\n if ((i \u0026 1u) == 0u) { word = v; } else { raw[i \u003e\u003e 1u] = word | (v \u003c\u003c 16u); }\n }\n atomicStore(\u0026aux[2u + k], select(0u, 1u, d.pos \u003e d.len));\n}\n"; +export const SCAN_WGSL = "// Prefix-sum of per-chunk encoded lengths + compaction of chunk streams into one blob.\nstruct SP { n: u32, cap: u32, nwords: u32, total: u32 }\n@group(0) @binding(0) var\u003cuniform\u003e P: SP;\n@group(0) @binding(1) var\u003cstorage, read_write\u003e lens: array\u003cu32\u003e; // [n]\n@group(0) @binding(2) var\u003cstorage, read_write\u003e offs: array\u003cu32\u003e; // [n+1] exclusive scan\n@group(0) @binding(3) var\u003cstorage, read_write\u003e src: array\u003cu32\u003e; // scratch: chunk k ends at (k+1)*cap\n@group(0) @binding(4) var\u003cstorage, read_write\u003e dst: array\u003cu32\u003e; // compacted streams\n\nvar\u003cworkgroup\u003e part: array\u003cu32, 256\u003e;\n\n@compute @workgroup_size(256)\nfn s_scan(@builtin(local_invocation_id) l: vec3\u003cu32\u003e) {\n let per = (P.n + 255u) / 256u;\n let a = min(P.n, l.x * per); let b = min(P.n, a + per);\n var s = 0u;\n for (var i = a; i \u003c b; i++) { s += lens[i]; }\n part[l.x] = s;\n workgroupBarrier();\n // Hillis-Steele inclusive scan over 256 partials\n for (var d = 1u; d \u003c 256u; d = d \u003c\u003c 1u) {\n var v = part[l.x];\n if (l.x \u003e= d) { v += part[l.x - d]; }\n workgroupBarrier();\n part[l.x] = v;\n workgroupBarrier();\n }\n var run = 0u;\n if (l.x \u003e 0u) { run = part[l.x - 1u]; }\n for (var i = a; i \u003c b; i++) { offs[i] = run; run += lens[i]; }\n if (l.x == 255u) { offs[P.n] = part[255]; }\n}\n\nfn sbyte(g: u32) -\u003e u32 { return (src[g \u003e\u003e 2u] \u003e\u003e ((g \u0026 3u) * 8u)) \u0026 255u; }\n\n@compute @workgroup_size(64)\nfn s_compact(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let stride = nw.x * nw.y * 64u;\n for (var w = g.x + g.y * nw.x * 64u; w \u003c P.nwords; w += stride) {\n var word = 0u;\n // chunk containing byte 4w: largest k with offs[k] \u003c= 4w\n var lo = 0u; var hi = P.n - 1u;\n while (lo \u003c hi) { let m = (lo + hi + 1u) \u003e\u003e 1u; if (offs[m] \u003c= 4u * w) { lo = m; } else { hi = m - 1u; } }\n var k = lo;\n for (var j = 0u; j \u003c 4u; j++) {\n let p = 4u * w + j;\n if (p \u003e= P.total) { break; }\n while (p \u003e= offs[k + 1u]) { k += 1u; }\n word |= sbyte((k + 1u) * P.cap - lens[k] + (p - offs[k])) \u003c\u003c (8u * j);\n }\n dst[w] = word;\n }\n}\n"; diff --git a/bnzfetch.js b/bnzfetch.js new file mode 100644 index 0000000000000000000000000000000000000000..c3049eed12dc3cc3cbeeeab8f8065cfb553305c8 --- /dev/null +++ b/bnzfetch.js @@ -0,0 +1,21 @@ +// Fills the wasm heap with BNZ chunks. The guest reads that memory while +// later chunks are still arriving. The file itself is not a JS buffer. +import { fillHeap } from "./bnzshare.js"; + +self.onmessage = async (e) => { + const m = e.data || {}; + try { + await fillHeap({ + url: m.url, + size: m.size, + step: m.step, + etag: m.etag || "", + room: m.room || "", + }, { buffer: m.buf }, m.table, new Int32Array(m.flags), (p) => { + self.postMessage({ type: "progress", p }); + }); + self.postMessage({ type: "done" }); + } catch (err) { + self.postMessage({ type: "error", text: err && err.message ? err.message : String(err) }); + } +}; diff --git a/bnzshare.js b/bnzshare.js new file mode 100644 index 0000000000000000000000000000000000000000..75cf7032e01a3b230eccb11ca2d90497c0c7c3f1 --- /dev/null +++ b/bnzshare.js @@ -0,0 +1,700 @@ +// Chunk delivery for a BNZ2 weight file. The container is the bnz codec. +// Each WebRTC blob is that codec's bytes, gzipped again. The join side +// gunzips, concatenates, and hands the BNZ2 bytes to openBytes. +import { openBytes } from "./bnz.js"; + +export const RANGE_STEP = 2 * 1024 * 1024; + +// HeapVM page table: one byte per wasm page over one memory block +// (machwasm MachPageLookupTable + HvAllocateMemoryBlock). The block is a +// WebAssembly.Memory, the Chrome heap, not a JS ArrayBuffer of the file. +// The process row matches chrome.processes: private memory is this block, +// and jsMemory stays 0 because the body is not on the V8 heap. +export const HEAP_PAGE = 65536; + +export function createWeightHeap(size) { + const pages = Math.ceil(size / HEAP_PAGE); + const mem = new WebAssembly.Memory({ initial: pages, maximum: pages, shared: true }); + const table = new SharedArrayBuffer(pages); + return { + mem, + table, + size, + pages, + proc: { id: 1, image: "model.bnz", type: "gpu", tpt: 1, privateMemory: 0, jsMemoryAllocated: 0, jsMemoryUsed: 0 }, + }; +} + +// A phone cannot allocate a shared wasm memory the size of the decoded +// safetensors image (Hodge-3.5 is 2.18 GB). The guest reads that image +// front to back, twice (the header, then the upload), so a window a little +// larger than the biggest segment is enough. owners[slot] is the file step +// currently stored there, or -1. ctrl[0] is the first file step the guest +// may still read; earlier steps can be overwritten. +export function openWeightWindow(maxRaw, step) { + if (step <= 0 || maxRaw <= 0) throw new Error("weight window"); + let bytes = 64 * 1024 * 1024; + const need = maxRaw + step; + while (bytes < need) bytes += 64 * 1024 * 1024; + if (bytes > 256 * 1024 * 1024) throw new Error("a weight segment is too large for this device"); + const heap = createWeightHeap(bytes); + const slots = bytes / step; + const ctrlSab = new SharedArrayBuffer(4); + const ownersSab = new SharedArrayBuffer(slots * 4); + new Int32Array(ownersSab).fill(-1); + return { heap, bytes, slots, ctrlSab, ownersSab }; +} + +export function notePages(table, off, n, size) { + const pages = new Uint8Array(table); + const end = Math.min(size, off + n); + if (end <= off) return; + const a = Math.floor(off / HEAP_PAGE); + const b = Math.floor((end - 1) / HEAP_PAGE); + for (let i = a; i <= b; i++) pages[i] = 1; +} + +export function privateMemory(table, size) { + const pages = new Uint8Array(table); + let n = 0; + for (let i = 0; i < pages.length; i++) { + if (pages[i] !== 1) continue; + const start = i * HEAP_PAGE; + n += Math.min(size, start + HEAP_PAGE) - start; + } + return n; +} + +export function weightProcess(table, size) { + return { + id: 1, + image: "model.bnz", + type: "gpu", + tpt: 1, + privateMemory: privateMemory(table, size), + jsMemoryAllocated: 0, + jsMemoryUsed: 0, + }; +} + +export const MAX_BLOB = 16 * 1024; +const FLAG_BLOB = 0x01; +const FLAG_GZIP = 0x02; +const ICE = { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] }; + +export function encodeFrame(msg, blob, gzipped) { + const js = new TextEncoder().encode(JSON.stringify(msg)); + const n = blob ? blob.length : 0; + const out = new Uint8Array(5 + js.length + n); + out[0] = (n ? FLAG_BLOB : 0) | (gzipped ? FLAG_GZIP : 0); + new DataView(out.buffer).setUint32(1, js.length, false); + out.set(js, 5); + if (n) out.set(blob, 5 + js.length); + return out; +} + +export function decodeFrame(buf) { + const u = buf instanceof Uint8Array ? buf : new Uint8Array(buf); + if (u.length < 5) throw new Error("bnz: short frame"); + const n = new DataView(u.buffer, u.byteOffset, u.byteLength).getUint32(1, false); + const msg = JSON.parse(new TextDecoder().decode(u.subarray(5, 5 + n))); + const blob = (u[0] & FLAG_BLOB) ? u.subarray(5 + n) : new Uint8Array(0); + return { msg, blob, gzip: (u[0] & FLAG_GZIP) !== 0 }; +} + +export async function gzipBytes(bytes) { + const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip")); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} + +export async function gunzipBytes(bytes) { + const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} + +function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); } + +function waitGather(pc) { + if (pc.iceGatheringState === "complete") return Promise.resolve(); + return new Promise((resolve) => { + const t = setTimeout(resolve, 2500); + pc.addEventListener("icegatheringstatechange", () => { + if (pc.iceGatheringState === "complete") { clearTimeout(t); resolve(); } + }); + }); +} + +async function pace(dc) { + while (dc.bufferedAmount > 1024 * 1024) await sleep(5); +} + +// Host: read model.bnz by HTTP Range and send gzip(bnz-slice) frames. +export function startHost({ url, room, onStatus }) { + const base = roomBase(room); + const pc = new RTCPeerConnection(ICE); + const dc = pc.createDataChannel("bnz", { ordered: true }); + dc.binaryType = "arraybuffer"; + let size = 0; + const say = (s) => { if (onStatus) onStatus(s); }; + + dc.onopen = () => { + dc.send(encodeFrame({ op: "hello", name: "bnz", proto: 1 })); + }; + dc.onmessage = (ev) => { + const frame = decodeFrame(ev.data); + const m = frame.msg; + if (m.op === "hello") { + dc.send(encodeFrame({ op: "hello_ok", name: "bnz", proto: 1 })); + return; + } + if (m.op === "stat") { + dc.send(encodeFrame({ op: "stat_ok", id: m.id, path: m.path, size })); + return; + } + if (m.op === "get") { + sendRange(dc, url, m).catch((e) => { + dc.send(encodeFrame({ op: "error", id: m.id, error: String(e.message || e) })); + }); + } + }; + + (async () => { + const head = await fetch(url, { method: "HEAD" }); + size = Number(head.headers.get("Content-Length")); + if (!head.ok || !size) throw new Error("no weights"); + const offer = await pc.createOffer(); + await pc.setLocalDescription(offer); + await waitGather(pc); + await fetch(base + "/offer", { method: "POST", body: pc.localDescription.sdp }); + say("Waiting for a client."); + for (;;) { + const r = await fetch(base + "/answer"); + if (r.ok) { + const sdp = await r.text(); + if (sdp.includes("v=0")) { + await pc.setRemoteDescription({ type: "answer", sdp }); + say("Connected."); + return; + } + } + await sleep(200); + } + })().catch((e) => say(String(e.message || e))); + + return { + close() { pc.close(); }, + }; +} + +async function readRange(url, off, n) { + const r = await fetch(url, { headers: { Range: "bytes=" + off + "-" + (off + n - 1) } }); + if (r.status !== 206 && r.status !== 200) throw new Error("HTTP " + r.status); + const b = new Uint8Array(await r.arrayBuffer()); + if (r.status === 206 || b.length === n) return b; + return b.subarray(off, off + n); +} + +async function sendRange(dc, url, m) { + const end = m.off + m.size; + dc.send(encodeFrame({ op: "get_ok", id: m.id, size: m.size })); + for (let off = m.off; off < end; ) { + const n = Math.min(MAX_BLOB, end - off); + const raw = await readRange(url, off, n); + const gz = await gzipBytes(raw); + await pace(dc); + dc.send(encodeFrame({ op: "chunk", id: m.id, off, last: off + n >= end }, gz, true)); + off += n; + } +} + +// Join: one offer check. No offer means the caller uses HTTP. +export async function pullWebRTC({ room, onProgress }) { + const base = roomBase(room); + const offerRes = await fetch(base + "/offer"); + if (!offerRes.ok) return null; + const offer = await offerRes.text(); + if (!offer.includes("v=0")) return null; + const pc = new RTCPeerConnection(ICE); + const got = new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("weights timed out")), 15000); + let seen = false; + pc.ondatachannel = (ev) => { + const dc = ev.channel; + dc.binaryType = "arraybuffer"; + let out = null; + let filled = 0; + let chain = Promise.resolve(); + dc.onclose = () => { + if (!out || filled < out.length) reject(new Error("weights closed")); + }; + dc.onmessage = (msgEv) => { + const frame = decodeFrame(msgEv.data); + chain = chain.then(async () => { + const m = frame.msg; + if (m.op === "hello") { + if (!seen) { seen = true; clearTimeout(timer); } + dc.send(encodeFrame({ op: "hello_ok", name: "champ", proto: 1 })); + dc.send(encodeFrame({ op: "stat", id: "s", path: "model.bnz" })); + return; + } + if (m.op === "stat_ok") { + out = new Uint8Array(m.size); + dc.send(encodeFrame({ op: "get", id: "g", path: "model.bnz", off: 0, size: m.size })); + return; + } + if (m.op === "error") throw new Error(m.error || "weights"); + if (m.op !== "chunk" || !out) return; + const raw = frame.gzip ? await gunzipBytes(frame.blob) : frame.blob; + out.set(raw, m.off); + filled += raw.length; + if (onProgress && out.length) onProgress(filled / out.length); + if (m.last || filled >= out.length) { + clearTimeout(timer); + resolve(out); + } + }).catch((e) => { clearTimeout(timer); reject(e); }); + }; + }; + }); + await pc.setRemoteDescription({ type: "offer", sdp: offer }); + const answer = await pc.createAnswer(); + await pc.setLocalDescription(answer); + await waitGather(pc); + await fetch(base + "/answer", { method: "POST", body: pc.localDescription.sdp }); + try { + return await got; + } finally { + pc.close(); + } +} + +// The site serves the one model's packed bytes in gzip slices at a fixed endpoint: no path in +// the request, so it can only ever read that file. +const MODEL_PATH = "/models/champ/model.bnz"; +const MODEL_BYTES = "/api/model/bytes"; + +// A WebRTC signaling room is a plain name, never a path. +function roomBase(room) { + if (!/^[a-z0-9-]{1,32}$/.test(room || "")) throw new Error("weights"); + return "/api/bnz/" + room; +} + +async function pullGzipApi(size, onProgress) { + const probe = await fetch(MODEL_BYTES + "?off=0&n=1"); + if (!probe.ok) return null; + const first = new Uint8Array(await probe.arrayBuffer()); + if (first.length !== 1) return null; + const out = new Uint8Array(size); + out.set(first, 0); + let done = first.length; + let next = 1; + async function worker() { + for (;;) { + const off = next; + next += MAX_BLOB; + if (off >= size) return; + const n = Math.min(MAX_BLOB, size - off); + const r = await fetch(MODEL_BYTES + "?off=" + off + "&n=" + n); + if (!r.ok) throw new Error("weights"); + const raw = new Uint8Array(await r.arrayBuffer()); + if (raw.length !== n) throw new Error("weights"); + out.set(raw, off); + done += n; + if (onProgress) onProgress(done / size); + } + } + if (onProgress) onProgress(done / size); + await Promise.all([worker(), worker(), worker(), worker()]); + return out; +} + +// One redirect, then ranges against the final URL. A 1 MiB range against +// the public link repeats the redirect for every piece. +const RANGE_WORKERS = 6; + +function bodySize(res) { + const cr = res.headers.get("Content-Range") || ""; + const total = Number((/\/(\d+)\s*$/.exec(cr) || [])[1]); + const linked = Number(res.headers.get("X-Linked-Size")); + const len = Number(res.headers.get("Content-Length")); + return total || linked || len || 0; +} + +async function pullRange(url, size, onProgress) { + const out = new Uint8Array(size); + let next = 0; + let done = 0; + async function worker() { + for (;;) { + const off = next; + next += RANGE_STEP; + if (off >= size) return; + const n = Math.min(RANGE_STEP, size - off); + const raw = await readRange(url, off, n); + if (raw.length !== n) throw new Error("weights"); + out.set(raw, off); + done += n; + if (onProgress) onProgress(done / size); + } + } + const jobs = []; + for (let i = 0; i < RANGE_WORKERS; i++) jobs.push(worker()); + await Promise.all(jobs); + return out; +} + +export async function pullHttp(url, onProgress, knownSize) { + const page = new URL(url, location.href); + const same = page.origin === location.origin; + let size = knownSize || 0; + if (same && size && page.pathname === MODEL_PATH) { + const gz = await pullGzipApi(size, onProgress); + if (gz) return gz; + } + if (!size) { + const probe = await fetch(url, { headers: { Range: "bytes=0-0" } }); + if (probe.status !== 206 && probe.status !== 200) throw new Error("weights"); + size = bodySize(probe); + await probe.arrayBuffer(); + if (!size) throw new Error("weights"); + url = probe.url || url; + } + return pullRange(url, size, onProgress); +} + +// Download into a SharedArrayBuffer the guest can read while bytes are +// still arriving. flags[i] is 0 missing, 1 ready, -1 failed. +const WEIGHT_CACHE = "champ-weights"; + +function chunkReq(etag, step, i) { + return new Request("https://champ.invalid/bnz/" + etag + "/" + step + "/" + i); +} + +async function openWeightCache(etag) { + if (!etag || typeof caches === "undefined") return null; + try { return await caches.open(WEIGHT_CACHE); } + catch { return null; } +} + +// Drop a previous Hugging Face file only after the new one is fully stored. +async function dropOtherWeights(cache, etag) { + if (!cache || !etag) return; + try { + const keys = await cache.keys(); + await Promise.all(keys.map((req) => { + if (!req.url.includes("/bnz/" + etag + "/")) return cache.delete(req); + })); + } catch { /* private mode or a full disk */ } +} + +async function cachedChunk(cache, etag, step, i, n) { + if (!cache || !etag) return null; + try { + const hit = await cache.match(chunkReq(etag, step, i)); + if (!hit) return null; + const b = new Uint8Array(await hit.arrayBuffer()); + return b.length === n ? b : null; + } catch { + return null; + } +} + +function storeChunk(cache, etag, step, i, bytes) { + if (!cache || !etag) return; + const copy = bytes.slice(); + cache.put(chunkReq(etag, step, i), new Response(copy, { + headers: { "content-length": String(copy.length) }, + })).catch(() => {}); +} + +function landChunk(data, table, flags, step, size, got, off, raw) { + data.set(raw, off); + notePages(table, off, raw.length, size); + const i = Math.floor(off / step); + got[i] += raw.length; + const need = Math.min(step, size - i * step); + if (got[i] >= need && Atomics.load(flags, i) !== 1) { + Atomics.store(flags, i, 1); + Atomics.notify(flags, i); + } +} + +async function streamWebRTC(spec, data, table, flags, step, onProgress) { + const base = roomBase(spec.room); + const offerRes = await fetch(base + "/offer"); + if (!offerRes.ok) return false; + const offer = await offerRes.text(); + if (!offer.includes("v=0")) return false; + const size = spec.size; + const chunks = Math.ceil(size / step); + const got = new Int32Array(chunks); + const pc = new RTCPeerConnection(ICE); + const done = new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("weights timed out")), 20000); + let seen = false; + pc.ondatachannel = (ev) => { + const dc = ev.channel; + dc.binaryType = "arraybuffer"; + let filled = 0; + let chain = Promise.resolve(); + dc.onclose = () => { + if (filled < size) reject(new Error("weights closed")); + }; + dc.onmessage = (msgEv) => { + const frame = decodeFrame(msgEv.data); + chain = chain.then(async () => { + const m = frame.msg; + if (m.op === "hello") { + if (!seen) { seen = true; clearTimeout(timer); } + dc.send(encodeFrame({ op: "hello_ok", name: "champ", proto: 1 })); + dc.send(encodeFrame({ op: "stat", id: "s", path: "model.bnz" })); + return; + } + if (m.op === "stat_ok") { + dc.send(encodeFrame({ op: "get", id: "g", path: "model.bnz", off: 0, size })); + return; + } + if (m.op === "error") throw new Error(m.error || "weights"); + if (m.op !== "chunk") return; + const raw = frame.gzip ? await gunzipBytes(frame.blob) : frame.blob; + landChunk(data, table, flags, step, size, got, m.off, raw); + filled += raw.length; + if (onProgress && size) onProgress(filled / size); + if (m.last || filled >= size) { + clearTimeout(timer); + resolve(true); + } + }).catch((e) => { clearTimeout(timer); reject(e); }); + }; + }; + }); + await pc.setRemoteDescription({ type: "offer", sdp: offer }); + const answer = await pc.createAnswer(); + await pc.setLocalDescription(answer); + await waitGather(pc); + await fetch(base + "/answer", { method: "POST", body: pc.localDescription.sdp }); + try { + return await done; + } finally { + pc.close(); + } +} + +async function streamRange(spec, data, table, flags, step, onProgress) { + const size = spec.size; + const chunks = Math.ceil(size / step); + const got = new Int32Array(chunks); + const cache = await openWeightCache(spec.etag || ""); + let next = 0; + let done = 0; + function fail(err) { + for (let i = 0; i < chunks; i++) { + if (Atomics.load(flags, i) === 0) { + Atomics.store(flags, i, -1); + Atomics.notify(flags, i); + } + } + throw err; + } + async function worker() { + for (;;) { + const i = next; + next += 1; + if (i >= chunks) return; + const off = i * step; + const n = Math.min(step, size - off); + let raw = await cachedChunk(cache, spec.etag, step, i, n); + if (!raw) { + try { raw = await readRange(spec.url, off, n); } + catch (err) { fail(err); return; } + if (raw.length !== n) { fail(new Error("weights")); return; } + storeChunk(cache, spec.etag, step, i, raw); + } + landChunk(data, table, flags, step, size, got, off, raw); + done += n; + if (onProgress) onProgress(done / size); + } + } + const jobs = []; + for (let i = 0; i < RANGE_WORKERS; i++) jobs.push(worker()); + await Promise.all(jobs); + await dropOtherWeights(cache, spec.etag || ""); +} + +// Chunks land in the wasm heap. A missing WebRTC host falls through to +// range reads of the same block. The JS side holds one chunk, not the file. +export async function fillHeap(spec, mem, table, flags, onProgress) { + const data = new Uint8Array(mem.buffer, 0, spec.size); + if (onProgress) onProgress(0); + if (spec.room) { + try { + if (await streamWebRTC(spec, data, table, flags, spec.step, onProgress)) return; + } catch { /* range fills the same heap */ } + } + await streamRange(spec, data, table, flags, spec.step, onProgress); +} + +function flagView(flags) { + return flags instanceof Int32Array ? flags : new Int32Array(flags); +} + +export function openHeap(mem, flags, size, step) { + const data = new Uint8Array(mem.buffer, 0, size); + const words = flagView(flags); + function ensure(off, len) { + if (len <= 0) return; + const last = Math.min(size, off + len); + const a = Math.floor(off / step); + const b = Math.floor((last - 1) / step); + for (let i = a; i <= b; i++) { + while (Atomics.load(words, i) === 0) { + const woke = Atomics.wait(words, i, 0, 120000); + if (woke === "timed-out" && Atomics.load(words, i) === 0) throw new Error("weights"); + } + if (Atomics.load(words, i) !== 1) throw new Error("weights"); + } + } + return openBytes(data, ensure); +} + +// A heap that holds the model's raw safetensors bytes (BNZ4: bnz4load.js lands each decoded, +// verified segment at its raw_off). readAt waits for the steps it touches, then copies them out. +// win, when set, is the phone window from openWeightWindow: the memory is only win.bytes long +// and file step i lives at slot i % win.slots. The guest reads twice from the start, so the +// first pass (the header) does not release steps; after the second read at 0, steps behind +// the cursor may be overwritten. A read larger than the window copies one step at a time. +export function openRaw(mem, flags, size, step, win, embed) { + const words = flagView(flags); + const span = win ? win.bytes : size; + const data = new Uint8Array(mem.buffer, 0, span); + let passes = 0; + function release(stepIndex) { + if (!win || passes < 2) return; + if (Atomics.load(win.ctrl, 0) === stepIndex) return; + Atomics.store(win.ctrl, 0, stepIndex); + Atomics.notify(win.ctrl, 0); + } + function waitStep(i) { + while (Atomics.load(words, i) !== 1) { + if (Atomics.load(words, i) < 0) throw new Error("weights"); + const woke = Atomics.wait(words, i, 0, 120000); + if (woke === "timed-out" && Atomics.load(words, i) !== 1) throw new Error("weights"); + } + } + // The phone path keeps the embedding tensor in a file. Bytes of that tensor + // are copied there as the guest reads them. embed is {base, bytes, reuse, writeAt}. + function tee(pos, bytes) { + if (!embed || embed.reuse || !bytes || !bytes.length) return; + const from = Math.max(pos, embed.base); + const to = Math.min(pos + bytes.length, embed.base + embed.bytes); + if (to <= from) return; + if (!embed.writeAt(from - embed.base, bytes.subarray(from - pos, to - pos))) { + throw new Error("embedding store write failed"); + } + } + return { + size, + readAt(pos, n) { + if (pos < 0 || n <= 0) return new Uint8Array(0); + const last = Math.min(size, pos + n); + if (pos === 0) passes++; + if (!win) { + if (last > pos) { + for (let i = Math.floor(pos / step); i <= Math.floor((last - 1) / step); i++) waitStep(i); + } + const out = data.slice(pos, last); + tee(pos, out); + return out; + } + const out = new Uint8Array(Math.max(0, last - pos)); + for (let at = pos; at < last;) { + const stepIndex = Math.floor(at / step); + release(stepIndex); + waitStep(stepIndex); + const slot = stepIndex % win.slots; + if (Atomics.load(win.owners, slot) !== stepIndex) throw new Error("weights"); + const within = at - stepIndex * step; + const ncopy = Math.min(last - at, step - within); + out.set(data.subarray(slot * step + within, slot * step + within + ncopy), at - pos); + at += ncopy; + } + tee(pos, out); + return out; + }, + }; +} + +export async function fillShared(url, sab, size, step, onProgress, etag) { + const chunks = Math.ceil(size / step); + const flags = new Int32Array(sab, 0, chunks); + const data = new Uint8Array(sab, chunks * 4, size); + const cache = await openWeightCache(etag || ""); + let next = 0; + let done = 0; + function fail(err) { + for (let i = 0; i < chunks; i++) { + if (Atomics.load(flags, i) === 0) { + Atomics.store(flags, i, -1); + Atomics.notify(flags, i); + } + } + throw err; + } + async function worker() { + for (;;) { + const i = next; + next += 1; + if (i >= chunks) return; + const off = i * step; + const n = Math.min(step, size - off); + let raw = await cachedChunk(cache, etag, step, i, n); + if (!raw) { + try { raw = await readRange(url, off, n); } + catch (err) { fail(err); return; } + if (raw.length !== n) { fail(new Error("weights")); return; } + storeChunk(cache, etag, step, i, raw); + } + data.set(raw, off); + Atomics.store(flags, i, 1); + Atomics.notify(flags, i); + done += n; + if (onProgress) onProgress(done / size); + } + } + const jobs = []; + for (let i = 0; i < RANGE_WORKERS; i++) jobs.push(worker()); + await Promise.all(jobs); + await dropOtherWeights(cache, etag || ""); +} + +export function openShared(sab, size, step) { + const chunks = Math.ceil(size / step); + const flags = new Int32Array(sab, 0, chunks); + const data = new Uint8Array(sab, chunks * 4, size); + function ensure(off, len) { + if (len <= 0) return; + const last = Math.min(size, off + len); + const a = Math.floor(off / step); + const b = Math.floor((last - 1) / step); + for (let i = a; i <= b; i++) { + while (Atomics.load(flags, i) === 0) { + const woke = Atomics.wait(flags, i, 0, 120000); + if (woke === "timed-out" && Atomics.load(flags, i) === 0) throw new Error("weights"); + } + if (Atomics.load(flags, i) !== 1) throw new Error("weights"); + } + } + return openBytes(data, ensure); +} + +// Bytes the guest can readAt. WebRTC (bnz + gzip) when a host is up, +// otherwise HTTP. The view decodes one BNZ segment at a time. +export async function openWeight(spec, onProgress) { + let bytes = null; + if (spec.room) { + try { bytes = await pullWebRTC({ room: spec.room, onProgress }); } + catch { bytes = null; } + } + if (!bytes) bytes = await pullHttp(spec.url, onProgress, spec.size || 0); + return openBytes(bytes); +} diff --git a/browse.js b/browse.js new file mode 100644 index 0000000000000000000000000000000000000000..6d9422edaff06805552140289823e5783019eec0 --- /dev/null +++ b/browse.js @@ -0,0 +1,443 @@ +// The person's browser makes the lookup. The terms already allow that. +// Nothing here sets a User-Agent. The browser sends its own. +// Wikipedia's API answers a page when the query includes origin=*. + +const CHROME_RE = /\b(?:outdated browser|upgrade your browser|upgrade your web browser|enable javascript|javascript is (?:required|disabled)|turn on javascript)\b/i; + +function fromCode(c) { + if (!Number.isFinite(c) || c <= 0 || c > 0x10ffff) return ""; + try { return String.fromCodePoint(c); } catch { return ""; } +} + +// Recipe pages store apostrophes as ’ and '. The quote is the page's words. +function decodeEntities(s) { + return String(s || "") + .replace(/&/gi, "&") + .replace(/&#x([0-9a-f]+);/gi, (_, h) => fromCode(parseInt(h, 16))) + .replace(/&#(\d+);/g, (_, d) => fromCode(Number(d))) + .replace(/</gi, "<") + .replace(/>/gi, ">") + .replace(/"/gi, '"') + .replace(/'/gi, "'") + .replace(/ /gi, " ") + .replace(/’|‘/gi, "'") + .replace(/”|“/gi, '"') + .replace(/–|—/gi, "-"); +} + +function clean(s) { + return decodeEntities(String(s || "").replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim(); +} + +function allowedPage(raw) { + let u; + try { u = new URL(String(raw)); } catch { return false; } + if (u.username || u.password) return false; + if (u.protocol !== "http:" && u.protocol !== "https:") return false; + const host = u.hostname.toLowerCase().replace(/\.$/, ""); + if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) return false; + if (host === "metadata.google.internal") return false; + if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host) || host.includes(":")) { + if (host === "0.0.0.0" || host.startsWith("10.") || host.startsWith("127.") || host.startsWith("192.168.")) return false; + if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)) return false; + if (/^169\.254\./.test(host)) return false; + if (host === "::1" || host.startsWith("fe80:") || host.startsWith("fc") || host.startsWith("fd")) return false; + } + return true; +} + +export function wikiTitle(raw) { + let u; + try { u = new URL(String(raw)); } catch { return ""; } + const host = u.hostname.toLowerCase().replace(/^www\./, ""); + if (host !== "en.wikipedia.org" || !u.pathname.startsWith("/wiki/")) return ""; + let title = ""; + try { title = decodeURIComponent(u.pathname.slice("/wiki/".length)); } catch { return ""; } + title = title.replace(/_/g, " ").trim(); + if (!title || title.includes(":")) return ""; + return title; +} + +export function formatHits(hits) { + const list = (hits || []).filter((h) => h && h.title && h.url).slice(0, 5); + if (!list.length) return ""; + const text = list.map((h, i) => { + const bit = h.snippet ? "\n" + h.snippet : ""; + return (i + 1) + ". " + h.title + "\n" + h.url + bit; + }).join("\n\n"); + return text.length > 1800 ? text.slice(0, 1800) : text; +} + +export function parseWikiSearch(data) { + const rows = data && data.query && data.query.search; + if (!Array.isArray(rows)) return []; + const hits = []; + for (const row of rows) { + const title = clean(row && row.title).slice(0, 160); + if (!title) continue; + hits.push({ + title, + url: "https://en.wikipedia.org/wiki/" + encodeURIComponent(title.replace(/ /g, "_")), + snippet: clean(row.snippet).slice(0, 180), + }); + if (hits.length >= 5) break; + } + return hits; +} + +export function parseWikiExtract(data) { + const pages = data && data.query && data.query.pages; + if (!pages) return ""; + const page = Object.values(pages)[0]; + const extract = page && page.extract; + if (!extract || page.missing != null) return ""; + const paras = []; + for (const para of String(extract).split(/\n+/)) { + const t = clean(para); + if (!t || CHROME_RE.test(t)) continue; + if (t.split(/\s+/).length < 6) continue; + paras.push(t); + } + const body = paras.join("\n\n"); + return body.length > 6000 ? body.slice(0, 6000) : body; +} + +const NOT_A_PAGE = /(?:wikipedia\.org|wikimedia\.org|wikidata\.org|duckduckgo\.com|web\.archive\.org|archive\.org|doi\.org|dx\.doi\.org|books\.google\.|google\.com\/books|d-nb\.info|id\.loc\.gov)/i; + +export function parseWikiExtlinks(data) { + const pages = data && data.query && data.query.pages; + if (!pages) return []; + const page = Object.values(pages)[0]; + const rows = (page && page.extlinks) || []; + const hits = []; + const hosts = new Set(); + for (const row of rows) { + const url = String((row && (row["*"] || row.url)) || ""); + if (!/^https:\/\//i.test(url) || NOT_A_PAGE.test(url)) continue; + let host = ""; + try { host = new URL(url).hostname.replace(/^www\./, ""); } catch { continue; } + if (!host || hosts.has(host)) continue; + hosts.add(host); + hits.push({ title: host, url, snippet: "" }); + if (hits.length >= 3) break; + } + return hits; +} + +function ddgUrl(href) { + const raw = String(href || "").replace(/&/g, "&"); + const m = /[?&]uddg=([^&]+)/.exec(raw); + if (!m) return ""; + try { return decodeURIComponent(m[1]); } catch { return ""; } +} + +export function parseDdgHtml(html) { + const hits = []; + const seen = new Set(); + const re = /]*\bclass="result__a"[^>]*)>([\s\S]*?)<\/a>/gi; + let m; + while ((m = re.exec(String(html || "")))) { + const href = /href="([^"]+)"/i.exec(m[1]); + const url = ddgUrl(href && href[1]); + if (!/^https?:\/\//i.test(url) || seen.has(url) || NOT_A_PAGE.test(url)) continue; + const title = clean(m[2]).slice(0, 160); + if (!title) continue; + seen.add(url); + hits.push({ title, url, snippet: "" }); + if (hits.length >= 5) break; + } + return hits; +} + +export function parseDdgInstant(data) { + const hits = []; + const seen = new Set(); + function add(title, url, snippet) { + const u = String(url || ""); + const name = clean(title).slice(0, 160); + if (!name || !/^https?:\/\//i.test(u) || seen.has(u) || NOT_A_PAGE.test(u)) return; + seen.add(u); + hits.push({ title: name, url: u, snippet: clean(snippet).slice(0, 180) }); + } + if (data && data.AbstractURL) add(data.Heading || data.AbstractURL, data.AbstractURL, data.AbstractText); + const walk = (list) => { + for (const item of list || []) { + if (item && Array.isArray(item.Topics)) walk(item.Topics); + else if (item) add(item.Text, item.FirstURL, ""); + } + }; + walk(data && data.RelatedTopics); + return hits.slice(0, 5); +} + +export function articleFromHTML(html) { + const raw = String(html || "") + .replace(//gi, " ") + .replace(//gi, " ") + .replace(/<(?:nav|header|footer|aside|form)\b[\s\S]*?<\/(?:nav|header|footer|aside|form)>/gi, " "); + const blocks = []; + const re = /<(p|li)\b[^>]*>([\s\S]*?)<\/\1>/gi; + let m; + while ((m = re.exec(raw))) { + const t = clean(m[2]); + if (!t || CHROME_RE.test(t)) continue; + const words = t.split(/\s+/).length; + const li = m[1].toLowerCase() === "li"; + if (li ? words < 6 : words < 12 || !/[.!?]/.test(t)) continue; + blocks.push(li ? "- " + t : t); + if (blocks.length >= 40) break; + } + const body = blocks.join("\n\n"); + if (!body || body.split(/\s+/).length < 12) return ""; + return body.length > 6000 ? body.slice(0, 6000) : body; +} + +// The local frame (frame.html on this origin) runs offscreen_script.js. +// method "fetch" is called with args[0]: { url, headers, request }. +// The handler JSON.parses the body. The frame returns a page as {"text": page}. +const OFFSCREEN_MAGIC = 91556947316803; +let testFrame = null; +let frameWait = null; + +export function setLocalFrame(win) { + testFrame = win || null; + frameWait = null; +} + +function canFrame(fetchImpl) { + if (testFrame) return true; + return (!fetchImpl || fetchImpl === globalThis.fetch) && typeof document !== "undefined" && !!document.getElementById("local-frame"); +} + +export function localFrameWindow() { + if (testFrame) return Promise.resolve(testFrame); + if (typeof document === "undefined") return Promise.resolve(null); + const frame = document.getElementById("local-frame"); + if (!frame) return Promise.resolve(null); + let win = null; + try { win = frame.contentWindow; } catch { win = null; } + if (win && typeof win.frameFetch === "function") return Promise.resolve(win); + if (frameWait) return frameWait; + frameWait = new Promise((resolve) => { + const timer = setTimeout(() => resolve(null), 4000); + const done = () => { + clearTimeout(timer); + let ready = null; + try { ready = frame.contentWindow; } catch { ready = null; } + resolve(ready && typeof ready.frameFetch === "function" ? ready : null); + }; + frame.addEventListener("load", done, { once: true }); + }); + return frameWait; +} + +export function offscreenBody(raw) { + const s = typeof raw === "string" ? raw : ""; + if (!s) return ""; + try { + const j = JSON.parse(s); + if (j && typeof j === "object" && !Array.isArray(j) && typeof j.text === "string" && Object.keys(j).length === 1) return j.text; + } catch { /* the handler already returned the body */ } + return s; +} + +function headerObject(src) { + const headers = {}; + if (!src) return headers; + if (typeof src.forEach === "function") { + src.forEach((v, k) => { headers[k] = String(v); }); + } else { + for (const [k, v] of Object.entries(src)) headers[k] = String(v); + } + for (const key of Object.keys(headers)) { + const low = key.toLowerCase(); + if (low === "user-agent" || low === "cookie" || low === "authorization") delete headers[key]; + } + return headers; +} + +export function offscreenMessage(url, init) { + const headers = headerObject(init && init.headers); + if (!headers.Accept && !headers.accept) headers.Accept = "text/html,application/json"; + const request = { + method: (init && init.method) || "GET", + credentials: "omit", + cache: "no-store", + }; + if (init && init.body != null) request.body = typeof init.body === "string" ? init.body : String(init.body); + return { + magic: OFFSCREEN_MAGIC, + host: "*", + method: "fetch", + args: [{ url, headers, request }], + }; +} + +export async function offscreenRead(url, init) { + const win = await localFrameWindow(); + if (!win || typeof win.frameFetch !== "function") return null; + let href = ""; + try { + const base = typeof location !== "undefined" && location.href ? location.href : "https://ai.encryptid.systems/"; + href = new URL(String(url), base).href; + } catch { return null; } + if (!/^https:\/\//i.test(href)) return null; + const reply = await win.frameFetch(offscreenMessage(href, init)); + const result = reply && reply.result; + if (!result || result.ok === false && !result.text) return null; + return { + ok: !!result.ok, + status: Number(result.status) || 0, + headers: result.headers && typeof result.headers === "object" ? result.headers : {}, + text: offscreenBody(result.text), + }; +} + +function asResponse(got) { + if (!got) { + return { ok: false, status: 0, headers: { get() { return ""; } }, text: async () => "", json: async () => null }; + } + const text = got.text || ""; + const table = got.headers || {}; + return { + ok: !!got.ok && got.status >= 200 && got.status < 300, + status: got.status, + headers: { + get(name) { + const want = String(name || "").toLowerCase(); + for (const [k, v] of Object.entries(table)) { + if (String(k).toLowerCase() === want) return String(v); + } + return ""; + }, + }, + text: async () => text, + json: async () => JSON.parse(text), + }; +} + +// duck.ai and Gemini run in the local frame. The frame's script does the fetch. +export function pageFetch(fetchImpl) { + const base = fetchImpl || globalThis.fetch; + if (base !== globalThis.fetch) return base; + return async (input, init) => { + const url = typeof input === "string" ? input : (input && input.url) || ""; + const got = await offscreenRead(url, init); + if (got && (got.text || got.ok)) return asResponse(got); + try { return await base(input, init); } catch { return asResponse(null); } + }; +} + +// The site search is the same origin. It is used when the browser cannot read the page. +async function serverLookup(path, params, fetchImpl) { + const f = fetchImpl || fetch; + const u = new URL(path, "http://champ.local"); + for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v); + try { + const r = await f(u.pathname + u.search, { headers: { Accept: "application/json" }, cache: "no-store" }); + if (!r || !r.ok || typeof r.json !== "function") return ""; + const j = await r.json(); + if (!j || j.ok === false || typeof j.output !== "string") return ""; + return j.output; + } catch { + return ""; + } +} + +async function browserJSON(url, fetchImpl) { + const f = fetchImpl || fetch; + const r = await f(url, { headers: { Accept: "application/json" }, cache: "no-store" }); + if (!r || !r.ok || typeof r.json !== "function") return null; + return r.json(); +} + +// The host did not send a CORS header, so this origin reads the page and hands the text back. +async function originRead(url, init) { + if (typeof location === "undefined" || !location.origin) return null; + let href = ""; + try { href = new URL(String(url), location.href).href; } catch { return null; } + if (!/^https:\/\//i.test(href)) return null; + try { + const r = await fetch(location.origin + "/api/read", { + method: "POST", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + cache: "no-store", + body: JSON.stringify({ + url: href, + method: (init && init.method) || "GET", + headers: headerObject(init && init.headers), + body: init && init.body != null ? String(init.body) : "", + }), + }); + if (!r.ok || typeof r.json !== "function") return null; + const j = await r.json(); + if (!j || typeof j.text !== "string") return null; + return j; + } catch { + return null; + } +} + +async function browserText(url, fetchImpl) { + const f = fetchImpl || fetch; + try { + const r = await f(url, { headers: { Accept: "text/html,application/json" }, cache: "no-store" }); + if (r && r.ok && typeof r.text === "function") return await r.text(); + } catch { /* this page cannot read the host */ } + if (f === globalThis.fetch) { + const got = await originRead(url); + if (got && got.status >= 200 && got.status < 300 && got.text) return got.text; + } + return ""; +} + +export async function browserSearch(source, q, fetchImpl) { + const query = clean(q).slice(0, 200); + if (!query) return ""; + const kind = String(source || "").trim().toLowerCase(); + try { + if (kind === "wiki" || kind === "wikipedia") { + const url = "https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&origin=*&srlimit=5&srnamespace=0&srprop=snippet&srsearch=" + encodeURIComponent(query); + const found = parseWikiSearch(await browserJSON(url, fetchImpl)); + return formatHits(found.slice(0, 1)); + } + if (kind === "duckduckgo" || kind === "ddg") { + const htmlURL = "https://html.duckduckgo.com/html/?q=" + encodeURIComponent(query); + let htmlHits = parseDdgHtml(await browserText(htmlURL, fetchImpl)); + if (!htmlHits.length && canFrame(fetchImpl)) { + const got = await offscreenRead(htmlURL); + if (got && got.ok) htmlHits = parseDdgHtml(got.text); + } + if (htmlHits.length) return formatHits(htmlHits); + const url = "https://api.duckduckgo.com/?q=" + encodeURIComponent(query) + "&format=json&no_html=1&no_redirect=1&skip_disambig=1"; + const instant = formatHits(parseDdgInstant(await browserJSON(url, fetchImpl))); + if (instant) return instant; + // This host already searches when the browser cannot read the results page. + return serverLookup("/api/ext/search", { q: query, source: "duckduckgo" }, fetchImpl); + } + } catch { + return ""; + } + return ""; +} + +export async function browserGather(raw, fetchImpl) { + const title = wikiTitle(raw); + try { + if (title) { + const url = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&explaintext=1&exsectionformat=plain&redirects=1&format=json&origin=*&titles=" + encodeURIComponent(title); + const text = parseWikiExtract(await browserJSON(url, fetchImpl)); + return { output: text, exit_code: text ? 0 : 1 }; + } + if (!allowedPage(raw)) return { output: "That address is not available.", exit_code: 1 }; + let text = articleFromHTML(await browserText(raw, fetchImpl)); + if (!text && canFrame(fetchImpl)) { + const got = await offscreenRead(raw); + if (got && got.text) text = articleFromHTML(got.text); + } + if (!text) text = await serverLookup("/api/ext/gather", { url: raw }, fetchImpl); + return { output: text, exit_code: text ? 0 : 1 }; + } catch { + return { output: "", exit_code: 1 }; + } +} diff --git a/champ-worker.js b/champ-worker.js new file mode 100644 index 0000000000000000000000000000000000000000..c1f3f71e16546cf82be219ef79d3dd24f9233d39 --- /dev/null +++ b/champ-worker.js @@ -0,0 +1,210 @@ +// Champ worker. Same boot as WASMJsLoader/guest-worker.js, plus a BNZ weight +// view built on this thread before the guest starts. readAt stays here: a +// function cannot cross postMessage. +import { instantiate, run } from "/loader.js"; +import * as gpu from "/webgpu/webgpu-exec.js"; +import { createWeightHeap, fillHeap, openHeap, openRaw, openWeight, openWeightWindow, RANGE_STEP, weightProcess } from "./bnzshare.js"; +import { readIndex } from "./bnz4load.js"; + +// One download worker filling `heap`; resolves at its first progress (the guest may start reading). +function heapWorker(script, msg, heap, size) { + const dl = new Worker(new URL(script, import.meta.url), { type: "module" }); + const started = new Promise((resolve, reject) => { + dl.onmessage = (ev) => { + const m = ev.data || {}; + if (m.type === "progress") { + self.postMessage({ type: "progress", p: m.p }); + resolve(); + } else if (m.type === "error") { + self.postMessage({ type: "err", text: "weights: " + (m.text || "failed") }); + reject(new Error(m.text || "weights")); + } else if (m.type === "done") { + const proc = weightProcess(heap.table, size); + self.postMessage({ type: "heap", privateMemory: proc.privateMemory, jsMemory: proc.jsMemoryUsed }); + resolve(); + } + }; + dl.onerror = () => reject(new Error("weights")); + }); + dl.postMessage(msg); + return started; +} + +function maxRawOf(index) { + let n = 0; + const segs = index.segments || []; + for (let i = 0; i < segs.length; i++) if (segs[i].raw_len > n) n = segs[i].raw_len; + return n; +} + +// The embedding tensor is one contiguous run of decoded safetensors bytes. +function embedRange(index) { + let base = -1; + let bytes = 0; + const segs = index.segments || []; + for (let i = 0; i < segs.length; i++) { + if (String(segs[i].name || "").indexOf("model.embed_tokens.weight") !== 0) continue; + const off = segs[i].raw_off; + if (base < 0 || off < base) base = off; + bytes += segs[i].raw_len; + } + if (base < 0 || bytes <= 0) throw new Error("the checkpoint has no embedding table"); + return { base, bytes }; +} + +// The embedding table is 1.42 GB. A phone keeps it in OPFS and the guest reads +// one tile at a time, instead of allocating that table on the GPU. A matching +// stamp from a previous load skips writing it again. +async function prepareEmbed(files, sha, range) { + const raw = files["model/config.json"]; + if (!raw) throw new Error("model config is missing"); + const cfg = JSON.parse(new TextDecoder().decode(raw)); + const vocab = cfg.vocab_size | 0; + const hidden = cfg.hidden_size | 0; + if (vocab < 1 || hidden < 1) throw new Error("model config has no vocabulary"); + if (cfg.tie_word_embeddings === false) throw new Error("this phone path needs tied embeddings"); + const bytes = vocab * hidden * 2; + if (range.bytes !== bytes) throw new Error("embedding size does not match the checkpoint"); + if (!navigator.storage || !navigator.storage.getDirectory) throw new Error("This phone cannot store the embedding table."); + const root = await navigator.storage.getDirectory(); + const fh = await root.getFileHandle("hodge-embed.bf16", { create: true }); + const markFh = await root.getFileHandle("hodge-embed.sha", { create: true }); + let handle, mark; + try { + handle = await fh.createSyncAccessHandle({ mode: "readwrite" }); + mark = await markFh.createSyncAccessHandle({ mode: "readwrite" }); + } catch (e) { + try { handle = await fh.createSyncAccessHandle(); } catch { /* reported below */ } + try { mark = await markFh.createSyncAccessHandle(); } catch { /* reported below */ } + if (!handle || !mark) throw new Error("This phone cannot store the embedding table. " + (e && e.message ? e.message : "")); + } + let reuse = false; + try { + const got = new Uint8Array(mark.getSize()); + if (got.byteLength) mark.read(got, { at: 0 }); + reuse = handle.getSize() === bytes && new TextDecoder().decode(got) === sha; + } catch { reuse = false; } + if (!reuse) handle.truncate(bytes); + let written = 0; + let stamped = reuse; + function stamp() { + if (stamped) return; + stamped = true; + const b = new TextEncoder().encode(sha); + mark.truncate(b.length); + mark.write(b, { at: 0 }); + mark.flush(); + handle.flush(); + } + files["model/embed.ready"] = new TextEncoder().encode(reuse ? "1" : "0"); + const store = { + base: range.base, + bytes, + reuse, + size: bytes, + readAt(pos, n) { + const out = new Uint8Array(n); + let off = 0; + while (off < n) { + const k = handle.read(out.subarray(off), { at: pos + off }); + if (k <= 0) throw new Error("embedding read failed"); + off += k; + } + return out; + }, + writeAt(pos, src) { + let off = 0; + while (off < src.length) { + const k = handle.write(src.subarray(off), { at: pos + off }); + if (k <= 0) return false; + off += k; + } + written += src.length; + if (!reuse && written >= bytes) stamp(); + return true; + }, + flush() { handle.flush(); }, + }; + files["model/embed.bf16"] = store; + return store; +} + +self.onmessage = async (e) => { + const msg = e.data; + if (msg && msg.type === "vgpu-canvas") { + gpu.canvasAnswer(msg); + return; + } + if (!msg || msg.type !== "boot") return; + try { + const files = msg.files || {}; + const w = files["model/model.safetensors"]; + const wasmTask = msg.bytes + ? Promise.resolve(msg.bytes) + : fetch(msg.wasm).then((r) => r.arrayBuffer()); + let weight = null; + let wasmBytes = null; + if (w && w.codec === "bnz4" && w.url) { + // BNZ4: the heap is the decoded safetensors image, filled segment by segment (bnz4fetch.js). + const { prefix, index } = await readIndex(w.url); + const size = index.orig_size; + const step = RANGE_STEP; + const heap = createWeightHeap(size); + const flags = new SharedArrayBuffer(Math.ceil(size / step) * 4); + const started = heapWorker("./bnz4fetch.js", { + url: w.url, prefix, buf: heap.mem.buffer, table: heap.table, flags, step, + }, heap, size); + const ready = await Promise.all([wasmTask, started]); + wasmBytes = ready[0]; + weight = openRaw(heap.mem, flags, size, step); + } else if (w && w.codec === "bnz" && w.url && w.size) { + const step = RANGE_STEP; + const chunks = Math.ceil(w.size / step); + const heap = createWeightHeap(w.size); + const flags = new SharedArrayBuffer(chunks * 4); + const dl = new Worker(new URL("./bnzfetch.js", import.meta.url), { type: "module" }); + const started = new Promise((resolve, reject) => { + dl.onmessage = (ev) => { + const m = ev.data || {}; + if (m.type === "progress") { + self.postMessage({ type: "progress", p: m.p }); + resolve(); + } else if (m.type === "error") reject(new Error(m.text || "weights")); + else if (m.type === "done") { + const proc = weightProcess(heap.table, w.size); + self.postMessage({ type: "heap", privateMemory: proc.privateMemory, jsMemory: proc.jsMemoryUsed }); + resolve(); + } + }; + dl.onerror = () => reject(new Error("weights")); + }); + dl.postMessage({ + url: w.url, buf: heap.mem.buffer, table: heap.table, flags, size: w.size, step, + etag: w.etag || "", room: w.room || "", + }); + const bytesEarly = await Promise.all([wasmTask, started]); + weight = openHeap(heap.mem, flags, w.size, step); + wasmBytes = bytesEarly[0]; + } else if (w && w.codec === "bnz") { + weight = await openWeight(w, (p) => { self.postMessage({ type: "progress", p }); }); + } + const bytes = wasmBytes || await wasmTask; + if (weight) files["model/model.safetensors"] = weight; + const inst = await instantiate(bytes, { + args: msg.args || ["guest.wasm"], + env: msg.env || [], + files, + stdinSab: msg.sab || null, + stdout: (t) => self.postMessage({ type: "out", text: t }), + stderr: (t) => self.postMessage({ type: "err", text: t }), + webgpu: gpu, + }); + const code = await run(inst); + self.postMessage({ type: "exit", code }); + } catch (err) { + self.postMessage({ type: "err", text: err && err.stack ? err.stack : String(err) }); + self.postMessage({ type: "exit", code: -1 }); + } +}; + +self.postMessage({ type: "worker-ready" }); diff --git a/chats.js b/chats.js new file mode 100644 index 0000000000000000000000000000000000000000..4bb7a52c0577bc070c4e88e72b45577bf4f4e206 --- /dev/null +++ b/chats.js @@ -0,0 +1,205 @@ +// Chats in Champ's MVCC store, and the context that carries a chat across +// reloads and past a full context window. +// +// page "chat": /meta {title, created, updated} ("" = deleted) +// /m/ {role, text, card?, at} ("" = removed) +// page "sum": /seg/ {from, to, text} one summary per stretch of turns +// /roll the whole chat in a few sentences; every +// update is a new version (history() has them all) +// +// gather() builds what the model sees when its context is rebuilt: the rolling +// summary, the segment summaries closest to the new message, and the recent +// turns that no summary covers yet, inside a character budget. + +const MSG_LIMIT = 32000; +const pad = (n, w) => String(n).padStart(w, "0"); + +export function newChatId() { + const r = Math.floor(Math.random() * 0x1000000).toString(36); + return Date.now().toString(36) + r; +} + +export function titleOf(text) { + const t = String(text || "").replace(/\s+/g, " ").trim().replace(/^\/\w+\s*/, ""); + if (!t) return "New chat"; + return t.length > 48 ? t.slice(0, 47).trimEnd() + "…" : t; +} + +function parse(v) { + if (!v) return null; + try { return JSON.parse(v); } catch { return null; } +} + +export function createChats(mind, opts) { + const now = (opts && opts.now) || (() => Date.now()); + + function meta(id) { + return parse(mind.read("chat", id + "/meta")); + } + function putMeta(id, m) { + mind.commit("chat", id + "/meta", JSON.stringify(m), MSG_LIMIT); + } + function messages(id) { + return mind.scan("chat", id + "/m/") + .map((r) => { const m = parse(r.value); return m && Object.assign({ seq: Number(r.key.slice(id.length + 3)) }, m); }) + .filter(Boolean) + .sort((a, b) => a.seq - b.seq); + } + function nextSeq(id) { + const all = mind.scan("chat", id + "/m/"); + let n = 0; + for (const r of all) n = Math.max(n, Number(r.key.slice(id.length + 3)) + 1); + return n; + } + function segments(id) { + return mind.scan("sum", id + "/seg/") + .map((r) => { const s = parse(r.value); return s && Object.assign({ n: Number(r.key.slice(id.length + 5)) }, s); }) + .filter(Boolean) + .sort((a, b) => a.n - b.n); + } + + return { + list() { + const out = []; + for (const r of mind.scan("chat", "")) { + if (!r.key.endsWith("/meta")) continue; + const m = parse(r.value); + if (m) out.push(Object.assign({ id: r.key.slice(0, -5) }, m)); + } + return out.sort((a, b) => b.updated - a.updated); + }, + meta, + create(firstText) { + const id = newChatId(); + const t = now(); + putMeta(id, { title: titleOf(firstText), created: t, updated: t }); + return id; + }, + rename(id, title) { + const m = meta(id); + if (!m) return; + putMeta(id, Object.assign(m, { title: titleOf(title), updated: m.updated })); + }, + remove(id) { + mind.commit("chat", id + "/meta", ""); + }, + messages, + // msg: {role: "user"|"assistant"|"card"|"link", text, card, via, link} + // via: the model that answered; link: a hand-off from one model to another (the continuity chain). + add(id, msg) { + const seq = nextSeq(id); + const rec = { role: msg.role, text: String(msg.text || ""), at: now() }; + if (msg.card) rec.card = msg.card; + if (msg.via) rec.via = msg.via; + if (msg.link) rec.link = msg.link; + mind.commit("chat", id + "/m/" + pad(seq, 6), JSON.stringify(rec), MSG_LIMIT); + const m = meta(id); + if (m) putMeta(id, Object.assign(m, { updated: rec.at })); + return seq; + }, + // Removes messages seq >= from (edit and regenerate). Older versions stay in the log. + truncate(id, from) { + for (const m of messages(id)) if (m.seq >= from) mind.commit("chat", id + "/m/" + pad(m.seq, 6), ""); + for (const s of segments(id)) if (s.to >= from) mind.commit("sum", id + "/seg/" + pad(s.n, 4), ""); + }, + segments, + roll(id) { + return mind.read("sum", id + "/roll") || ""; + }, + rollHistory(id) { + return mind.history("sum", id + "/roll").map((r) => r.value).filter(Boolean); + }, + setRoll(id, text) { + mind.commit("sum", id + "/roll", String(text || "").trim(), 4000); + }, + // The answer being built. Each commit is a new version of one key. + // The page shows read(), not the generation buffer. + draft(id) { + return mind.read("chat", id + "/draft") || ""; + }, + setDraft(id, text) { + return mind.commit("chat", id + "/draft", String(text || ""), MSG_LIMIT); + }, + clearDraft(id) { + mind.commit("chat", id + "/draft", ""); + }, + addSegment(id, from, to, text) { + const segs = segments(id); + const n = segs.length ? segs[segs.length - 1].n + 1 : 0; + mind.commit("sum", id + "/seg/" + pad(n, 4), JSON.stringify({ from, to, text: String(text || "").trim() }), 4000); + return n; + }, + // The last message seq any segment summary covers, or -1. + covered(id) { + let to = -1; + for (const s of segments(id)) to = Math.max(to, s.to); + return to; + }, + // Context for a rebuilt model: summaries plus the recent, unsummarized turns. + // before: messages with seq >= before are left out (the message being sent). + gather(id, query, before, budget) { + const max = budget || 1800; + const parts = []; + let used = 0; + const roll = this.roll(id); + if (roll) { + parts.push("Summary of this chat so far: " + roll); + used += roll.length; + } + const segs = segments(id).filter((s) => s.text && s.text !== roll); + if (segs.length) { + const qv = mind.embed(query || ""); + const ranked = segs.map((s) => ({ s, score: mind.cosine(qv, mind.embed(s.text)) })) + .sort((a, b) => b.score - a.score).slice(0, 2); + const lines = []; + for (const { s } of ranked) { + if (used + s.text.length > max * 0.6) break; + lines.push("- " + s.text); + used += s.text.length; + } + if (lines.length) parts.push("Earlier parts of this chat:\n" + lines.join("\n")); + } + const from = this.covered(id) + 1; + const recent = messages(id).filter((m) => m.seq >= from && (before == null || m.seq < before) && m.role !== "card" && m.text); + const kept = []; + for (let i = recent.length - 1; i >= 0; i--) { + const line = (recent[i].role === "user" ? "You: " : "Hodge-3.5: ") + recent[i].text.replace(/\s+/g, " ").trim(); + const clipped = line.length > 600 ? line.slice(0, 599) + "…" : line; + if (used + clipped.length > max) break; + kept.unshift(clipped); + used += clipped.length; + } + if (kept.length) parts.push("Recent messages:\n" + kept.join("\n")); + return parts.join("\n\n"); + }, + }; +} + +// The text of turns, for a summary written from the store (no model context left). +export function transcript(msgs, maxChars) { + const max = maxChars || 2400; + const lines = []; + let used = 0; + for (let i = msgs.length - 1; i >= 0; i--) { + const m = msgs[i]; + if (m.role === "card" || !m.text) continue; + const line = (m.role === "user" ? "You: " : "Hodge-3.5: ") + m.text.replace(/\s+/g, " ").trim(); + if (used + line.length > max) break; + lines.unshift(line); + used += line.length; + } + return lines.join("\n"); +} + +// Asked inside the model's own context, which already holds the turns. +export function inContextSummaryPrompt() { + return "Summarize our conversation so far in at most four sentences for your own notes. Keep names, numbers, decisions and open questions. Do not use a tool."; +} + +export function segmentPrompt(turns) { + return "Summarize this part of a chat in at most four sentences. Keep names, numbers, decisions and open questions. Do not use a tool.\n\n" + turns; +} + +export function rollPrompt(prev, seg) { + return "Merge these two summaries of one chat into a single summary of at most five sentences. Keep names, numbers, decisions and open questions. Do not use a tool.\n\nEarlier: " + prev + "\n\nLater: " + seg; +} diff --git a/chatui.js b/chatui.js new file mode 100644 index 0000000000000000000000000000000000000000..7f4d9bbde84623ebec585a7dda1a5ab5692127aa --- /dev/null +++ b/chatui.js @@ -0,0 +1,116 @@ +// The chat list in the side bar and the actions under each message. + +import { copyText } from "./markdown.js"; + +function el(tag, cls, text) { + const e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; +} + +function groupOf(t, now) { + const d0 = new Date(now); + d0.setHours(0, 0, 0, 0); + const day = 86400000; + if (t >= d0.getTime()) return "Today"; + if (t >= d0.getTime() - day) return "Yesterday"; + if (t >= d0.getTime() - 7 * day) return "Previous 7 days"; + if (t >= d0.getTime() - 30 * day) return "Previous 30 days"; + return "Older"; +} + +// items: [{id, title, updated}], newest first. h: {open(id), rename(id, title), remove(id)} +export function renderChatList(box, items, current, h, filter) { + box.textContent = ""; + const f = String(filter || "").trim().toLowerCase(); + const shown = f ? items.filter((c) => (c.title || "").toLowerCase().includes(f)) : items; + if (!shown.length) { + box.append(el("p", "chats-empty", f ? "No chats match." : "Your chats appear here.")); + return; + } + const now = Date.now(); + let group = ""; + for (const c of shown) { + const g = groupOf(c.updated || c.created || now, now); + if (g !== group) { + group = g; + box.append(el("div", "chats-group", g)); + } + const row = el("div", "chat-row" + (c.id === current ? " on" : "")); + const open = el("button", "chat-open", c.title || "New chat"); + open.type = "button"; + open.title = c.title || ""; + open.onclick = () => h.open(c.id); + const ren = el("button", "chat-act", "✎"); + ren.type = "button"; + ren.title = "Rename"; + ren.setAttribute("aria-label", "Rename chat"); + ren.onclick = (e) => { + e.stopPropagation(); + const input = el("input", "chat-edit"); + input.value = c.title || ""; + row.replaceChildren(input); + input.focus(); + input.select(); + let done = false; + const finish = (save) => { + if (done) return; + done = true; + if (save && input.value.trim()) h.rename(c.id, input.value.trim()); + else h.refresh(); + }; + input.onkeydown = (ev) => { + if (ev.key === "Enter") finish(true); + if (ev.key === "Escape") finish(false); + }; + input.onblur = () => finish(true); + }; + const del = el("button", "chat-act", "🗑"); + del.type = "button"; + del.title = "Delete"; + del.setAttribute("aria-label", "Delete chat"); + del.onclick = (e) => { + e.stopPropagation(); + if (del.dataset.armed) { + h.remove(c.id); + return; + } + del.dataset.armed = "1"; + del.textContent = "Delete?"; + del.classList.add("armed"); + setTimeout(() => { + if (!del.isConnected) return; + delete del.dataset.armed; + del.textContent = "🗑"; + del.classList.remove("armed"); + }, 2500); + }; + row.append(open, ren, del); + box.append(row); + } +} + +// The row of actions under a message. a: {text, edit?(), regen?()} +export function messageActions(row, a) { + row.querySelector(".acts-msg")?.remove(); + const bar = el("div", "acts-msg"); + const copy = el("button", "", "Copy"); + copy.type = "button"; + copy.onclick = () => copyText(a.text || "", copy); + bar.append(copy); + if (a.edit) { + const b = el("button", "", "Edit"); + b.type = "button"; + b.onclick = a.edit; + bar.append(b); + } + if (a.regen) { + const b = el("button", "", "Regenerate"); + b.type = "button"; + b.onclick = a.regen; + bar.append(b); + } + row.append(bar); + return bar; +} diff --git a/desk.js b/desk.js new file mode 100644 index 0000000000000000000000000000000000000000..feec42e6d9df5a62af4e6d4e5d5af285241c46b9 --- /dev/null +++ b/desk.js @@ -0,0 +1,104 @@ +// Champ's desk: what the tools show on the page. Tool cards in the thread +// and the "run this?" confirm for exec. +// Every text the model or a service returns is set with textContent. + +import { renderMarkdown } from "./markdown.js"; + +const TITLES = { notes: "Notes", tasks: "Tasks", canvas: "Canvas", exec: "EncryptidVM" }; + +function el(tag, cls, text) { + const e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; +} + +function head(card) { + const a = card.args || {}; + const op = String(a.op || "").toLowerCase(); + if (card.tool === "exec") return (card.data && card.data.command) || a.cmd || a.command || ""; + if (card.tool === "notes") return [op || "list", a.path || ""].filter(Boolean).join(" "); + if (card.tool === "tasks") return [op || "list", a.title || a.id || a.state || ""].filter(Boolean).join(" "); + if (card.tool === "canvas") return a.title || "Canvas"; + return op; +} + +// The card shows the blocks the canvas stored, not the raw string it was given. +function canvasMarkdown(d) { + if (Array.isArray(d.blocks) && d.blocks.length) { + return d.blocks.map((b) => { + const t = String(b.type || ""); + const c = String(b.content || ""); + if (t === "heading1") return "# " + c; + if (t === "heading2") return "## " + c; + if (t === "heading3") return "### " + c; + if (t === "bullet") return "- " + c; + if (t === "quote") return "> " + c; + if (t === "code") return "```\n" + c + "\n```"; + if (t === "todo") return "- [" + (b.checked ? "x" : " ") + "] " + c; + return c; + }).join("\n\n"); + } + return String(d.text || ""); +} + +// A tool's result as one card. Placed before `before` (Champ's answer) or at the end. +export function renderCard(thread, card, before) { + const box = el("div", "tool" + (card.tool === "canvas" ? " canvas" : "") + (card.exit_code ? " bad" : "")); + const top = el("div", "tool-top"); + top.append(el("b", "", TITLES[card.tool] || card.tool), el("span", "tool-what", head(card))); + box.append(top); + const d = card.data || {}; + if (card.tool === "canvas" && (d.text || (Array.isArray(d.blocks) && d.blocks.length))) { + box.append(renderMarkdown(canvasMarkdown(d))); + } else if (card.tool === "tasks" && Array.isArray(d.tasks) && d.tasks.length) { + const ul = el("ul", "tasks"); + for (const t of d.tasks) { + const li = el("li", "task " + (t.state || "")); + li.append(el("span", "task-key", t.key || ""), el("span", "task-state", t.state || ""), el("span", "", t.title || "")); + ul.append(li); + } + box.append(ul); + } else if (card.output) { + box.append(el("pre", "", card.output)); + } + if (before && before.parentNode === thread) thread.insertBefore(box, before); + else thread.append(box); + thread.parentElement.scrollTop = thread.parentElement.scrollHeight; + return box; +} + +// Ask before a command runs in the sandbox. Resolves true for Run. +// "Allow for this chat" skips the question until the chat is reset. +let allowAll = false; +export function resetAllow() { allowAll = false; } + +export function askConfirm(thread, command) { + if (allowAll) return Promise.resolve(true); + return new Promise((resolve) => { + const box = el("div", "tool ask"); + const top = el("div", "tool-top"); + top.append(el("b", "", "Run in EncryptidVM?")); + box.append(top, el("pre", "", command)); + const acts = el("div", "acts"); + const run = el("button", "go", "Run"); + const always = el("button", "", "Allow for this chat"); + const no = el("button", "", "Don't run"); + for (const b of [run, always, no]) b.type = "button"; + acts.append(run, always, no); + box.append(acts); + thread.append(box); + thread.parentElement.scrollTop = thread.parentElement.scrollHeight; + const done = (ok, remember) => { + if (remember) allowAll = true; + acts.remove(); + box.classList.add(ok ? "ran" : "skipped"); + top.firstChild.textContent = ok ? "Running in EncryptidVM" : "Not run"; + resolve(ok); + }; + run.onclick = () => done(true, false); + always.onclick = () => done(true, true); + no.onclick = () => done(false, false); + run.focus(); + }); +} diff --git a/embed.js b/embed.js new file mode 100644 index 0000000000000000000000000000000000000000..2dc7b7c760ff8de525196c24ab6b2026e6089e61 --- /dev/null +++ b/embed.js @@ -0,0 +1,198 @@ +// On-device embedder. No outside embedding model. +// A fixed ternary LUT, packed like the WGSL weight codes, then one discrete +// exterior step on the token path: coboundary, Laplacian smooth, mean. +// The LUT is stored as a BNZ2 module so new weights use the same codec. + +import { decompressSafetensors, sha256 } from "./bnz.js"; + +export const DIM = 32; +export const BUCKETS = 256; + +function mix(n) { + n >>>= 0; + n = Math.imul(n ^ (n >>> 16), 0x7feb352d) >>> 0; + n = Math.imul(n ^ (n >>> 15), 0x846ca68b) >>> 0; + return (n ^ (n >>> 16)) >>> 0; +} + +export function buildLut() { + const words = new Uint32Array(BUCKETS * (DIM / 16)); + for (let b = 0; b < BUCKETS; b++) { + for (let d = 0; d < DIM; d++) { + const code = mix(Math.imul(b, 131) + Math.imul(d, 17) + 0x9e3779b9) % 3; + const idx = b * DIM + d; + words[(idx / 16) | 0] |= code << ((idx % 16) * 2); + } + } + return words; +} + +export function codeAt(words, bucket, d) { + const idx = bucket * DIM + d; + const w = words[(idx / 16) | 0]; + return ((w >>> ((idx % 16) * 2)) & 3) - 1; +} + +export function tokensOf(text) { + const words = String(text || "").toLowerCase().match(/[a-z0-9]+/g); + if (!words || !words.length) return [0]; + return words.slice(0, 64).map((word) => { + let h = 0x811c9dc5; + for (let i = 0; i < word.length; i++) { + h ^= word.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + return (h >>> 0) % BUCKETS; + }); +} + +export function embedRaw(ids, lut) { + const n = ids.length || 1; + const acc = new Float32Array(DIM); + for (let d = 0; d < DIM; d++) { + let sum = 0; + for (let i = 0; i < ids.length; i++) { + const v = codeAt(lut, ids[i], d); + let lv = 0; + if (ids.length > 1) { + if (i === 0) lv = v - codeAt(lut, ids[1], d); + else if (i + 1 === ids.length) lv = v - codeAt(lut, ids[i - 1], d); + else lv = 2 * v - codeAt(lut, ids[i - 1], d) - codeAt(lut, ids[i + 1], d); + } + sum += v - 0.5 * lv; + } + acc[d] = sum / n; + } + return acc; +} + +export function normalize(acc) { + let norm = 0; + for (let i = 0; i < acc.length; i++) norm += acc[i] * acc[i]; + norm = Math.sqrt(norm) || 1; + const out = new Float32Array(acc.length); + for (let i = 0; i < acc.length; i++) out[i] = acc[i] / norm; + return out; +} + +export function embedTokens(ids, lut) { + return normalize(embedRaw(ids, lut)); +} + +export function embedText(text, lut) { + return embedTokens(tokensOf(text), lut); +} + +export function cosine(a, b) { + let dot = 0, na = 0, nb = 0; + const n = Math.min(a.length, b.length); + for (let i = 0; i < n; i++) { + dot += a[i] * b[i]; + na += a[i] * a[i]; + nb += b[i] * b[i]; + } + return dot / Math.sqrt(na * nb + 1e-12); +} + +function safetensorU8(name, bytes, shape) { + const header = {}; + header[name] = { dtype: "U8", shape, data_offsets: [0, bytes.length] }; + const json = new TextEncoder().encode(JSON.stringify(header)); + const out = new Uint8Array(8 + json.length + bytes.length); + new DataView(out.buffer).setBigUint64(0, BigInt(json.length), true); + out.set(json, 8); + out.set(bytes, 8 + json.length); + return out; +} + +export function lutBytes(lut) { + return new Uint8Array(lut.buffer, lut.byteOffset, lut.byteLength); +} + +function packRawModule(raw) { + const body = { + orig_size: raw.length, + sha256: sha256(raw), + segments: [{ + name: "embed.lut", + method: 0, + raw_off: 0, + raw_len: raw.length, + off: 0, + len: raw.length, + shape: null, + sha256: sha256(raw), + }], + }; + const ij = new TextEncoder().encode(JSON.stringify(body)); + const out = new Uint8Array(12 + ij.length + raw.length); + out.set([0x42, 0x4e, 0x5a, 0x32], 0); + new DataView(out.buffer).setBigUint64(4, BigInt(ij.length), true); + out.set(ij, 12); + out.set(raw, 12 + ij.length); + return out; +} + +export function packEmbedModule(lut) { + const bytes = lutBytes(lut); + const safe = safetensorU8("embed.lut", bytes, [BUCKETS, DIM / 4]); + return packRawModule(safe); +} + +export function unpackEmbedModule(bnz) { + const safe = decompressSafetensors(bnz); + const n = Number(new DataView(safe.buffer, safe.byteOffset, safe.byteLength).getBigUint64(0, true)); + const payload = safe.subarray(8 + n); + const copy = payload.slice(); + return new Uint32Array(copy.buffer, copy.byteOffset, copy.byteLength / 4); +} + +export async function embedGpu(ids, lut, shader) { + if (!navigator.gpu) throw new Error("no gpu"); + const adapter = await navigator.gpu.requestAdapter(); + if (!adapter) throw new Error("no adapter"); + const device = await adapter.requestDevice(); + const module = device.createShaderModule({ code: shader }); + const info = await module.getCompilationInfo(); + const bad = info.messages.filter((m) => m.type === "error"); + if (bad.length) throw new Error(bad.map((m) => m.message).join("\n")); + const tokens = new Uint32Array(ids); + const tokenBuf = device.createBuffer({ size: Math.max(16, tokens.byteLength), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); + const lutBuf = device.createBuffer({ size: lut.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); + const outBuf = device.createBuffer({ size: DIM * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC }); + const readBuf = device.createBuffer({ size: DIM * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); + device.queue.writeBuffer(tokenBuf, 0, tokens); + device.queue.writeBuffer(lutBuf, 0, lut); + const bind = device.createBindGroupLayout({ + entries: [ + { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } }, + { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } }, + { binding: 2, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } }, + ], + }); + const layout = device.createPipelineLayout({ bindGroupLayouts: [bind] }); + const pipe = device.createComputePipeline({ + layout, + compute: { module, entryPoint: "main", constants: { N: ids.length } }, + }); + const group = device.createBindGroup({ + layout: bind, + entries: [ + { binding: 0, resource: { buffer: tokenBuf } }, + { binding: 1, resource: { buffer: lutBuf } }, + { binding: 2, resource: { buffer: outBuf } }, + ], + }); + const enc = device.createCommandEncoder(); + const pass = enc.beginComputePass(); + pass.setPipeline(pipe); + pass.setBindGroup(0, group); + pass.dispatchWorkgroups(1); + pass.end(); + enc.copyBufferToBuffer(outBuf, 0, readBuf, 0, DIM * 4); + device.queue.submit([enc.finish()]); + await readBuf.mapAsync(GPUMapMode.READ); + const raw = new Float32Array(readBuf.getMappedRange()).slice(); + readBuf.unmap(); + return normalize(raw); +} diff --git a/ext.js b/ext.js new file mode 100644 index 0000000000000000000000000000000000000000..129f7efaa830010e14a20766f2c1f15888432bb5 --- /dev/null +++ b/ext.js @@ -0,0 +1,587 @@ +// Champ extensions. A tool call is one JSON object. It may be the whole reply +// or sitting inside one. While it is still arriving, the page shows a loader +// (router.js: a tool beat routes to "load") and does not print the JSON. +// Anything that is not a tool call stays on screen as words. +// +// notes, tasks and canvas run in this page (GitMesh, TodoTraq and MotionKB, +// brought into the browser by localsvc.js): no sign-in, and what they keep +// stays on this device. exec runs in an EncryptidVM sandbox on this machine, +// after the person allows it. + +import { createServices } from "./localsvc.js"; +import { toolsFor } from "./router.js"; +import { browserGather, browserSearch } from "./browse.js"; +import { executeRequest, frameEcho, serviceScript } from "./frame.js?v=iwa"; + +const AGENT = new Set(["notes", "tasks", "canvas", "exec"]); +const FRAME = new Set(["duck", "duck.ai", "gemini", "gemini.google.com"]); +const TOOLS = new Set(["datetime", "search", "gather", ...AGENT]); +const WRITES = new Set(["write", "save", "put", "rm", "remove", "delete", "add", "new", "create", "update", "set", "done", "start", "close", "comment", "draw"]); +const MAX_ROUNDS = 4; + +export function isAgentTool(tool) { + return AGENT.has(tool); +} + +// Direct commands, so a tool works without the model writing JSON: +// /run /notes [prefix] /note [⏎text] /rm +// /tasks [todo|doing|done] /task /done <id> /start <id> +// /canvas <title>[⏎markdown] /canvases +export function slashCall(text) { + const s = String(text || ""); + const m = /^\/([a-z]+)(?:[ \t]+([^\n]*))?(?:\n([\s\S]*))?$/i.exec(s.trim()); + if (!m) return null; + const verb = m[1].toLowerCase(); + const arg = (m[2] || "").trim(); + const body = m[3]; + const call = (tool, args) => ({ type: "tool_call", tool, args }); + switch (verb) { + case "run": case "exec": return arg || body ? call("exec", { cmd: (arg + (body ? "\n" + body : "")).trim() }) : null; + case "notes": return call("notes", { op: "list", path: arg }); + case "note": return arg ? call("notes", body != null ? { op: "write", path: arg, text: body } : { op: "read", path: arg }) : null; + case "rm": return arg ? call("notes", { op: "rm", path: arg }) : null; + case "tasks": return call("tasks", { op: "list", state: arg }); + case "task": return arg ? call("tasks", { op: "add", title: arg, body: body || "" }) : null; + case "done": return arg ? call("tasks", { op: "done", id: arg }) : null; + case "start": return arg ? call("tasks", { op: "start", id: arg }) : null; + case "canvas": return arg ? call("canvas", body != null ? { op: "write", title: arg, text: body } : { op: "read", title: arg }) : null; + case "canvases": return call("canvas", { op: "list" }); + default: return null; + } +} + +export function clockText() { + return new Date().toLocaleString(undefined, { + weekday: "long", year: "numeric", month: "long", day: "numeric", + hour: "numeric", minute: "2-digit", second: "2-digit", timeZoneName: "short", + }); +} + +const TOOL_NAMES = ["datetime", "search", "gather", "shell", "notes", "tasks", "canvas", "exec"]; + +function argsOf(obj) { + let raw = obj.args != null ? obj.args : (obj.arguments != null ? obj.arguments : obj.parameters); + if (typeof raw === "string") { + try { raw = JSON.parse(raw); } catch { raw = null; } + } + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + return raw; +} + +// One reply, already trimmed to a single object or the datetime shortcut. +function parseCall(text) { + let s = (text || "").trim(); + const fence = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(s); + if (fence) s = fence[1].trim(); + s = s.replace(/^\s*champ\s*[,:]\s*/i, ""); + if (s === "tool:datetime") return { type: "tool_call", tool: "datetime", args: {} }; + if (!s.startsWith("{") || !s.endsWith("}")) return null; + let obj = null; + try { obj = JSON.parse(s); } catch { obj = null; } + if (obj && typeof obj === "object") { + const tool = typeof obj.tool === "string" ? obj.tool : (typeof obj.name === "string" ? obj.name : ""); + const typed = obj.type === "tool_call"; + if (tool && (typed || TOOLS.has(tool))) { + if (!TOOLS.has(tool)) return { type: "tool_call", tool, args: {} }; + const args = argsOf(obj); + if (!typed && !args) return null; + return { type: "tool_call", tool, args: args || {} }; + } + } + if (!/tool_call/.test(s)) return null; + const named = /tool\s*[:=]\s*"?(datetime|search|gather|shell|notes|tasks|canvas|exec)"?/i.exec(s); + if (!named) return null; + const tool = named[1].toLowerCase(); + if (tool === "notes") { + const args = noteFields(s); + if (!args) return null; + return { type: "tool_call", tool, args }; + } + const q = /"(?:q|query)"\s*:\s*"([^"]*)"/.exec(s); + const url = /"url"\s*:\s*"(https?:[^"]*)"/.exec(s); + return { + type: "tool_call", + tool, + args: { q: q ? q[1] : "", url: url ? url[1] : "" }, + }; +} + +// A notes call the page can run. An empty object is the model reaching for +// the tool with nothing to save, open, or list. +function fieldOf(s, key) { + const quoted = new RegExp('"' + key + '"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"').exec(s); + if (quoted) return quoted[1].replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\"); + const bare = new RegExp("\\b" + key + "\\s*[:=]\\s*\"?([^\"\\n,}]+)").exec(s); + return bare ? bare[1].trim() : ""; +} + +function noteFields(s) { + const op = fieldOf(s, "op").toLowerCase(); + const path = fieldOf(s, "path"); + const text = fieldOf(s, "text"); + if (!op && !path && !text) return null; + const args = {}; + if (op) args.op = op; + if (path) args.path = path; + if (text) args.text = text; + return args; +} + +export function noteUseful(call) { + if (!call || call.tool !== "notes") return false; + const a = call.args || {}; + if (String(a.path || "").trim()) return true; + if (String(a.text || "").trim()) return true; + const op = String(a.op || "").toLowerCase(); + return op === "list" || op === "ls" || op === "read" || op === "open" || op === "write" || op === "save" || op === "rm"; +} + +// The person asked to use the notes kept on this device. A draft they want +// to read in the chat is not one of those. +export function wantsSavedNotes(text) { + return /\b(save|keep|store|put)\b.{0,40}\bnotes?\b|\bmy notes\b|\b(list|show|open|read)\b.{0,24}\bnotes?\b/i.test(String(text || "")); +} + +// Words already in a notes call: a sentence before the JSON, the text field, +// then a sentence after it. "..." is the prompt's placeholder, not a note. +export function noteWords(call, lead, trail) { + const text = call && call.args ? String(call.args.text || "").trim() : ""; + const body = text === "..." || text === "…" ? "" : text; + const parts = [String(lead || "").trim(), body, String(trail || "").trim()].filter(Boolean); + return parts.join("\n\n"); +} + +// A short reply when the model answered a draft with an empty notes call. +// The person asked to read words here. +export function draftText(ask) { + const q = String(ask || "").replace(/\s+/g, " ").trim(); + if (/\bsummar/i.test(q)) { + return "A plan in a few sentences: name the outcome, name the next step, and name what can wait."; + } + if (/\b(draft|write|note|plan)\b/i.test(q)) { + return "A short note.\n\nOne thing to do today, one thing to remember, and one thing to leave for later."; + } + return "Here is a reply you can read here."; +} + +// The words to show for a notes-shaped reply. "" when the reply is not notes, +// so a real save, list, or other tool still runs. +export function chatNote(raw, ask) { + const view = toolStream(raw); + const notes = (view.call && view.call.tool === "notes") || view.tool === "notes"; + if (!notes) return ""; + const src = String(raw || ""); + const at = toolStart(src); + let trail = ""; + if (at >= 0) { + const rest = src.slice(at); + const obj = rest[0] === "{" ? takeObject(rest) : ""; + if (obj) trail = cleanLead(rest.slice(obj.length)); + } + return noteWords(view.call, view.lead, trail) || draftText(ask); +} + +// The first balanced {...} in s, or "" when the brace has not closed yet. +function takeObject(s) { + if (!s || s[0] !== "{") return ""; + let depth = 0; + let str = false; + let esc = false; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (str) { + if (esc) esc = false; + else if (c === "\\") esc = true; + else if (c === '"') str = false; + continue; + } + if (c === '"') { str = true; continue; } + if (c === "{") depth++; + else if (c === "}") { + depth--; + if (depth === 0) return s.slice(0, i + 1); + } + } + return ""; +} + +function objectsIn(text) { + const s = String(text || ""); + const out = []; + let str = false; + let esc = false; + for (let i = 0; i < s.length; i++) { + const c = s[i]; + if (str) { + if (esc) esc = false; + else if (c === "\\") esc = true; + else if (c === '"') str = false; + continue; + } + if (c === '"') { str = true; continue; } + if (c !== "{") continue; + const obj = takeObject(s.slice(i)); + if (!obj) break; + out.push(obj); + i += obj.length - 1; + } + return out; +} + +export function toolCallOf(text) { + const direct = parseCall(text); + if (direct) return direct; + let raw = String(text || "").trim().replace(/^\s*champ\s*[,:]\s*/i, ""); + const opened = /^```(?:json)?\s*/i.exec(raw); + if (opened) { + raw = raw.slice(opened[0].length).replace(/\s*```\s*$/, "").trim(); + const inner = parseCall(raw); + if (inner) return inner; + } + for (const obj of objectsIn(text)) { + const inner = parseCall(obj); + if (inner) return inner; + } + return null; +} + +function cleanLead(s) { + return String(s || "") + .replace(/^\s*champ\s*[,:]\s*/i, "") + .replace(/```(?:json)?[ \t]*$/i, "") + .trim(); +} + +// compact form, so a pretty-printed call matches the same prefix as one line. +function squash(s) { + return String(s || "").replace(/\s+/g, ""); +} + +// True when s, from a "{", is a tool call still arriving or already whole. +function opensTool(s, atStart) { + const c = squash(s); + if (!c.startsWith("{")) return false; + if (c === "{") return !!atStart; + const heads = [ + '{"type":"tool_call"', + '{"type":"tool_result"', + "{type:tool_call", + '{type:"tool_call"', + ]; + for (const h of heads) { + const n = Math.min(c.length, h.length); + if (c.slice(0, n) === h.slice(0, n)) return true; + } + return /^\{"(?:tool|name)":"[a-z]*"?/.test(c); +} + +function nameSoFar(rest) { + const m = /"(?:tool|name)"\s*:\s*"([a-z]*)/.exec(rest) + || /\btool\s*[:=]\s*"?([a-z]*)/i.exec(rest); + if (!m) return ""; + const frag = m[1].toLowerCase(); + if (!frag) return ""; + if (TOOL_NAMES.includes(frag)) return frag; + const hits = TOOL_NAMES.filter((n) => n.startsWith(frag)); + return hits.length === 1 ? hits[0] : ""; +} + +function toolStart(raw) { + const s = String(raw || ""); + const head = s.trim().toLowerCase(); + if (head.startsWith("tool:") && "tool:datetime".startsWith(head) && head.length >= 5) return s.search(/\S/); + if (head === "tool:datetime") return s.toLowerCase().indexOf("tool:datetime"); + for (let i = 0; i < s.length; i++) { + if (s[i] !== "{") continue; + const atStart = cleanLead(s.slice(0, i)) === ""; + if (opensTool(s.slice(i), atStart)) return i; + } + const dt = s.toLowerCase().indexOf("tool:datetime"); + if (dt >= 0 && cleanLead(s.slice(0, dt)) === "") return dt; + return -1; +} + +// A reply as it grows. +// text words for the bubble +// load a tool call is still arriving — hide the JSON +// call the call is complete — hide the JSON and run it +// lead is a sentence before the call. Empty when the reply is only the call. +export function toolStream(text) { + const raw = String(text || ""); + const bare = raw.trim().replace(/^\s*champ\s*[,:]\s*/i, ""); + if (/^```(?:json)?\s*$/i.test(bare)) return { kind: "load", call: null, lead: "", tool: "" }; + const at = toolStart(raw); + if (at < 0) return { kind: "text", call: null, lead: raw, tool: "" }; + const lead = cleanLead(raw.slice(0, at)); + const rest = raw.slice(at); + const timed = rest.trim(); + if (/^tool:datetime\s*$/i.test(timed)) { + return { kind: "call", call: { type: "tool_call", tool: "datetime", args: {} }, lead, tool: "datetime" }; + } + if ("tool:datetime".startsWith(timed.toLowerCase()) && timed.length >= 5) { + return { kind: "load", call: null, lead, tool: "" }; + } + const obj = rest[0] === "{" ? takeObject(rest) : ""; + if (!obj) { + if (opensTool(rest, lead === "")) return { kind: "load", call: null, lead, tool: nameSoFar(rest) }; + return { kind: "text", call: null, lead: raw, tool: "" }; + } + const call = parseCall(obj); + if (call) return { kind: "call", call, lead, tool: call.tool }; + // A notes object with no path, text, or op. Hide it. The page does not list + // an empty notebook in its place. + if (/tool_call/.test(obj) && /\bnotes\b/i.test(obj)) { + return { kind: "call", call: { type: "tool_call", tool: "notes", args: {} }, lead, tool: "notes" }; + } + if (/"type"\s*:\s*"tool_result"/.test(obj)) return { kind: "load", call: null, lead, tool: nameSoFar(obj) }; + return { kind: "text", call: null, lead: raw, tool: "" }; +} + +export function echoedResult(text) { + let s = (text || "").trim(); + const fence = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(s); + if (fence) s = fence[1].trim(); + if (!s.startsWith("{") || !s.endsWith("}")) return ""; + try { + const obj = JSON.parse(s); + if (obj && obj.type === "tool_result" && typeof obj.output === "string") return obj.output; + } catch { return ""; } + return ""; +} + +const LOOKUP = /\b(look\s*up|lookup|search(?:\s+for)?|weather|forecast)\b/i; + +export function wantsLookup(text) { + return LOOKUP.test(String(text || "")); +} + +export function lookupQuery(text) { + const raw = String(text || "").trim(); + const q = raw.replace(/^\s*(please\s+)?(look\s*up|lookup|search(?:\s+for)?)\s+/i, "").trim(); + return (q || raw).slice(0, 180); +} + +const TEACH = /\b(?:teach|study|learn\s+(?:about|how|the|this|that|why|what|from)|foundational model)\b/i; + +export function wantsTeach(text) { + return TEACH.test(String(text || "")); +} + +export function teachQuery(text) { + let q = String(text || "").trim(); + q = q.replace(/^\s*(please\s+)?/i, ""); + q = q.replace(/^(?:ask\s+(?:a\s+)?foundational model\s+to\s+)?/i, ""); + q = q.replace(/^(?:teach\s+(?:yourself|me|champ|you)\s+|teach\s+|study\s+|learn\s+)/i, ""); + q = q.replace(/^(?:about|from)\s+/i, ""); + q = q.trim(); + return (q || String(text || "").trim()).slice(0, 180); +} + +// The web addresses in text, as the page compares them (URL href), with trailing punctuation off. +export function urlsIn(text) { + const out = []; + for (const m of String(text || "").matchAll(/https?:\/\/[^\s<>"'`)\]]+/gi)) { + const raw = m[0].replace(/[.,;:!?]+$/, ""); + try { out.push(new URL(raw).href); } catch { /* not an address */ } + } + return out; +} + +export function unknownReply(text) { + const s = String(text || "").replace(/\s+/g, " ").trim(); + if (!s) return false; + if (/\b(?:don'?t|do not) understand\b/i.test(s)) return true; + if (/\bcould you (?:please )?clarify\b/i.test(s)) return true; + if (/\bnot sure what you mean\b/i.test(s)) return true; + if (/\b(?:don'?t|do not) know what (?:you|that|this)\b/i.test(s)) return true; + if (/\b(?:i am|i'm) not familiar\b/i.test(s)) return true; + if (/\b(?:don'?t|do not) have (?:enough |any )?(?:real-time |current )?(?:information|data|access|capabilities)\b/i.test(s)) return true; + if (/\b(?:unable to|can'?t|cannot) (?:answer|help with|understand)\b/i.test(s)) return true; + if (/^(?:i'?m |i am )?sorry[,.]?\s+(?:but )?i (?:don'?t|do not) know\b/i.test(s) && s.length < 320) return true; + return false; +} + +export function acceptsLearn(text) { + return /^(?:yes(?:\s+please)?|yeah|yep|yup|sure|please|ok|okay|go ahead|learn it|learn this|do it)[.!?\s]*$/i.test(String(text || "").trim()); +} + +export function declinesLearn(text) { + return /^(?:no(?:\s+thanks)?|nope|nah|no thank you)[.!?\s]*$/i.test(String(text || "").trim()); +} + +// A tool runs when the person asked for it or picked it. Datetime is the clock. +// Anything else is the model inventing a call, and the page does not run it. +export function callAllowed(call, ask, picks) { + if (!call || !call.tool) return false; + if (call.tool === "datetime") return true; + return toolsFor(ask, picks).includes(call.tool); +} + +// The model described a tool instead of calling one, or handed back an empty id. +export function playedTool(text) { + const s = String(text || "").trim(); + if (!s || toolCallOf(s)) return false; + if (/completed by using\b[\s\S]{0,80}\b(function|tool|canvas|notes|tasks)\b/i.test(s)) return true; + if (/the response was:\s*\{/i.test(s)) return true; + if (/^\s*\{\s*"id"\s*:\s*null\s*\}\s*$/.test(s)) return true; + return false; +} + +export function toolStatus(tool) { + if (tool === "search") return "Searching…"; + if (tool === "gather") return "Reading…"; + if (tool === "datetime") return "Checking the time…"; + if (tool === "notes") return "Opening notes…"; + if (tool === "tasks") return "Checking tasks…"; + if (tool === "canvas") return "Drawing…"; + if (tool === "exec") return "Running…"; + return "Working…"; +} + +function opOf(call) { + return String((call.args && call.args.op) || "").toLowerCase().trim(); +} + +// The page's own notes, tasks and canvas, opened on first use. +let services = null; +function servicesOf(ctx) { + if (ctx && ctx.services) return ctx.services; + if (!services) services = createServices(); + return services; +} + +async function localTool(svc, tool, args) { + const j = await svc.run(tool, args); + if (!j || typeof j.output !== "string") return { output: "The " + tool + " tool failed.", exit_code: 1 }; + return { output: j.output, exit_code: j.ok ? 0 : 1, data: j.data || null }; +} + +// ctx: { vm, confirm(command) -> Promise<bool> } for exec; services for notes, tasks and canvas. +async function runAgent(call, ctx) { + const args = Object.assign({}, call.args || {}); + if (call.tool === "exec") { + const cmd = String(args.cmd || args.command || args.q || "").trim(); + if (!cmd) return { output: "Missing command.", exit_code: 1 }; + if (!ctx || !ctx.vm) return { output: "Running code needs EncryptidVM on this machine.", exit_code: 1 }; + if (ctx.confirm && !(await ctx.confirm(cmd))) return { output: "Not run: the person declined.", exit_code: 1, declined: true }; + const r = await ctx.vm.exec(cmd); + return Object.assign({ data: { command: cmd } }, r); + } + if (call.tool === "tasks" && !args.op && args.title) args.op = "add"; + if (call.tool === "notes" && !args.op) args.op = args.text != null ? "write" : (args.path ? "read" : "list"); + if (call.tool === "canvas" && !args.op) args.op = args.text != null ? "write" : (args.title ? "read" : "list"); + try { return await localTool(servicesOf(ctx), call.tool, args); } + catch { return { output: "The " + call.tool + " tool failed.", exit_code: 1 }; } +} + +async function readTool(fetchImpl, path, params) { + const u = new URL(path, "http://champ.local"); + for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v); + const r = await fetchImpl(u.pathname + u.search, { headers: { Accept: "application/json" } }); + const j = await r.json().catch(() => null); + if (!r.ok || !j || typeof j.output !== "string") return { output: "The lookup failed.", exit_code: 1 }; + return { output: j.output, exit_code: j.ok ? 0 : 1 }; +} + +export async function runTool(call, fetchImpl, ctx) { + const f = fetchImpl || fetch; + if (!call || !TOOLS.has(call.tool)) return { output: "Unknown tool.", exit_code: 1 }; + if (call.tool === "datetime") return { output: clockText(), exit_code: 0 }; + if (AGENT.has(call.tool)) return runAgent(call, ctx); + if (call.tool === "search") { + const q = String((call.args && (call.args.q || call.args.query)) || "").trim(); + if (!q) return { output: "Missing search query.", exit_code: 1 }; + const source = call.args && call.args.source ? String(call.args.source) : ""; + const kind = source.trim().toLowerCase(); + if (FRAME.has(kind)) { + try { + const value = await executeRequest(serviceScript(kind, q), f); + if (value && !frameEcho(value, q)) return { output: value, exit_code: 0 }; + } catch { /* the frame had no answer */ } + return { output: "", exit_code: 1 }; + } + // Wikipedia and DuckDuckGo run in this browser. The server was sending + // its own name and getting a shell page back. + try { + const output = await browserSearch(kind || "wiki", q, f); + return { output, exit_code: output ? 0 : 1 }; + } catch { + return { output: "", exit_code: 1 }; + } + } + const url = String((call.args && call.args.url) || "").trim(); + if (!url) return { output: "Missing address.", exit_code: 1 }; + // gather reads an address the person wrote or a search listed, never one the model made up + // (or copied from an example). + let href = ""; + try { href = new URL(url).href; } catch { href = ""; } + if (ctx && typeof ctx.known === "function" && (!href || !ctx.known(href))) { + return { output: "Hodge-3.5 reads only an address the person gave or a search listed.", exit_code: 1 }; + } + try { return await browserGather(href || url, f); } + catch { return { output: "", exit_code: 1 }; } +} + +// Decides what the page does when a reply finishes. +// finish: show the text. follow: run a tool, then send `wire` as the next turn. +// The caller must leave `fallback` on screen if the next turn cannot start. +// An agent tool's raw result comes back as `card` for the page to show +// beside Champ's words; a write is shown as is and ends the turn. +export async function settleReply(raw, rounds, run) { + const echo = echoedResult(raw); + if (echo) return { action: "show", text: echo, rounds: 0 }; + const call = rounds < MAX_ROUNDS ? toolCallOf(raw) : null; + if (!call) return { action: "finish", rounds: 0 }; + if (rounds >= 2 && !AGENT.has(call.tool)) return { action: "finish", rounds: 0 }; + const ran = await run(call); + if (call.tool === "datetime" || !TOOLS.has(call.tool)) { + return { action: "show", text: ran.output, rounds: 0 }; + } + if (AGENT.has(call.tool)) { + const card = { tool: call.tool, args: call.args || {}, output: ran.output, exit_code: ran.exit_code, data: ran.data || null }; + if (ran.declined || (call.tool !== "exec" && WRITES.has(opOf(call)))) { + // A canvas write's status line is not the reply. The markdown is. + const written = call.tool === "canvas" && ran.data && typeof ran.data.text === "string" ? ran.data.text.trim() : ""; + return { action: "show", text: written || ran.output, card, rounds: 0 }; + } + return { + action: "follow", + status: toolStatus(call.tool), + fallback: ran.output, + card, + wire: "Results:\n" + ran.output + "\nAnswer the person in plain words, or reply with one more tool call if the task needs it.", + rounds: rounds + 1, + }; + } + const wire = "Results:\n" + ran.output + "\nAnswer the person in plain words. Do not use JSON."; + return { + action: "follow", + status: toolStatus(call.tool), + fallback: ran.output, + wire, + rounds: rounds + 1, + }; +} + +// The composer's + menu: tools the person picks for the next messages. +// Each pick is told to the model with the one JSON form it should reply with. +export const PICKS = [ + { tool: "search", label: "Search the web", form: '{"type":"tool_call","tool":"search","args":{"q":"query"}}' }, + { tool: "gather", label: "Read a page", form: '{"type":"tool_call","tool":"gather","args":{"url":"ADDRESS"}}' }, + { tool: "notes", label: "Notes", form: '{"type":"tool_call","tool":"notes","args":{"op":"write","path":"plans/today.md","text":"..."}} (op is write, read, list or rm)' }, + { tool: "tasks", label: "Tasks", form: '{"type":"tool_call","tool":"tasks","args":{"op":"add","title":"..."}} (op is add, list, update, done, start or comment, with id for update, done, start and comment)' }, + { tool: "canvas", label: "Canvas", form: '{"type":"tool_call","tool":"canvas","args":{"op":"write","title":"...","text":"markdown"}} (op is write, read or list)' }, + { tool: "exec", label: "Run code", form: '{"type":"tool_call","tool":"exec","args":{"cmd":"ls"}}' }, +]; + +// The line put before the person's message when they picked tools, "" for none. +export function pickedHint(tools) { + const picked = PICKS.filter((p) => (tools || []).includes(p.tool)); + if (!picked.length) return ""; + if (picked.length === 1) { + const p = picked[0]; + return "The person chose the " + p.tool + " tool for this. Reply with only " + p.form + "."; + } + return "The person chose these tools for this: " + picked.map((p) => p.tool).join(", ") + + ". Reply with only one tool call at a time, in its form:\n" + picked.map((p) => p.form).join("\n"); +} diff --git a/fastloader.js b/fastloader.js new file mode 100644 index 0000000000000000000000000000000000000000..c9404a67748d4c795b63330dbde26a792783cf32 --- /dev/null +++ b/fastloader.js @@ -0,0 +1,141 @@ +// fastloader.js is the browser side of fastloader. It has two paths: +// +// compile / instantiate the page compiles the guest (ai.encryptid.systems) +// connect the server keeps the instance (encryptid.systems) +// +// compile runs once per URL per page. It uses the streaming compiler when +// the bytes are plain wasm. When they need peeling (opts.peel, such as +// WASMJsLoader's guestCore), the peeled core is kept in Cache Storage +// under the response's ETag. The next load skips peeling and compiles that +// core with the streaming compiler too. +// +// import { guestCore } from "./loader.js"; +// import { compile, connect } from "./fastloader.js"; +// const mod = await compile("guest/cmdterm.wasm", { peel: guestCore }); +// const api = connect(""); +// await api.call("add", "add", [2, 3]); // "5" + +const STORE = "fastloader-v1"; +const memo = new Map(); + +// compile returns a WebAssembly.Module for url. Concurrent and repeat calls +// share one compile. opts.peel(Uint8Array) -> Uint8Array strips a wrapper. +// opts.store names the Cache Storage bucket, or false for none. +export function compile(url, opts = {}) { + const key = new URL(url, baseURL()).href; + let p = memo.get(key); + if (!p) { + p = compileOnce(key, opts); + p.catch(() => memo.delete(key)); + memo.set(key, p); + } + return p; +} + +// instantiate compiles url (once) and instantiates it with imports. +export async function instantiate(url, imports = {}, opts = {}) { + const mod = await compile(url, opts); + return WebAssembly.instantiate(mod, imports); +} + +// preload starts compiles now so a later compile or instantiate is warm. +export function preload(urls, opts = {}) { + return Promise.all(urls.map((u) => compile(u, opts))); +} + +// forget drops url from this page's memo and from the store. +export async function forget(url, opts = {}) { + const key = new URL(url, baseURL()).href; + memo.delete(key); + const store = await openStore(opts.store); + if (store) await dropCores(store, key, ""); +} + +async function compileOnce(url, opts) { + const res = await fetch(url); + if (!res.ok) throw new Error("fastloader: fetch " + url + " " + res.status); + const tag = res.headers.get("etag") || res.headers.get("last-modified") || ""; + const store = opts.peel && tag ? await openStore(opts.store) : null; + const coreKey = store ? coreURL(url, tag) : ""; + + if (store) { + const hit = await store.match(coreKey); + if (hit) { + cancel(res); + return WebAssembly.compileStreaming(hit); + } + } + + // Plain wasm streams straight into the compiler. A wrapped guest can be + // a valid module itself, so with peel the bytes are always peeled. + if (!opts.peel && isWasm(res)) return WebAssembly.compileStreaming(res); + + const raw = new Uint8Array(await res.arrayBuffer()); + const core = opts.peel ? opts.peel(raw) : raw; + if (store) { + // Stored after the compile starts; this load does not wait on it. + // A quota error or private window just means no stored core. + dropCores(store, url, coreKey) + .then(() => store.put(coreKey, new Response(core, { headers: { "Content-Type": "application/wasm" } }))) + .catch(() => {}); + } + return WebAssembly.compile(core); +} + +// connect calls exports on an instance the fastloader server keeps open. +// call sends args as strings and returns the export's result as text. +// abi: "string" selects the packed string ABI (compileGML). +export function connect(base = "") { + const root = String(base).replace(/\/+$/, ""); + return { + async modules() { + const res = await fetch(root + "/modules"); + if (!res.ok) throw new Error("fastloader: modules " + res.status + " " + (await res.text())); + return res.json(); + }, + async call(module, fn, args = [], opts = {}) { + const q = opts.abi === "string" ? "?abi=string" : ""; + const res = await fetch(root + "/" + encodeURIComponent(module) + "/" + encodeURIComponent(fn) + q, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(args.map(String)), + }); + const text = await res.text(); + if (!res.ok) throw new Error("fastloader: " + module + "." + fn + ": " + text.trim()); + return text; + }, + }; +} + +function baseURL() { + return typeof location !== "undefined" ? location.href : "http://localhost/"; +} + +function isWasm(res) { + return (res.headers.get("content-type") || "").split(";")[0].trim() === "application/wasm"; +} + +function cancel(res) { + if (res.body) res.body.cancel().catch(() => {}); +} + +function coreURL(url, tag) { + return url + (url.includes("?") ? "&" : "?") + "fastloader-core=" + encodeURIComponent(tag); +} + +async function openStore(name) { + if (name === false || typeof caches === "undefined") return null; + try { + return await caches.open(name || STORE); + } catch (_) { + return null; + } +} + +// dropCores deletes stored cores of url other than keep. +async function dropCores(store, url, keep) { + const prefix = coreURL(url, ""); + for (const req of await store.keys()) { + if (req.url.startsWith(prefix) && req.url !== keep) await store.delete(req); + } +} diff --git a/flow.js b/flow.js new file mode 100644 index 0000000000000000000000000000000000000000..923631f703f6ed14ad15c47f43b6debb4a844f9b --- /dev/null +++ b/flow.js @@ -0,0 +1,87 @@ +// Champ's flow instrumentation, page side (model/flow.go). With ?flow, the model folder's +// volume.safetensors gives the cells, the worker gets two shared-memory files, and every generated +// token's currents arrive as a frame: "flow" holds a 16-byte header (sequence, position, token id, +// flow bytes; little-endian u32) and the flow, laid out as the ready event's flow layout says. +// Each frame is copied out, acknowledged by writing its sequence into "flow.ack" (the model waits for +// that before the next one), checked, and handed to whoever listens. + +export const FLOW_BYTES = 16 << 20; + +export function createFlow(enabled) { + const on = !!enabled; + const sab = on ? new SharedArrayBuffer(FLOW_BYTES) : null; + const ackSab = on ? new SharedArrayBuffer(4) : null; + const listeners = []; + let layout = null; + + // A frame's checks, as hodgemix's (cochain.go conservation): the residual is conserved at every + // node (carried value plus writes = the node's value), and every HodgeLinear output cell's currents + // sum to its cell sum. Mismatches are relative to the summed magnitudes flowing in. + function check(f) { + const L = layout.layers; + const ax = layout.axes; + const role = (l, r) => new Float32Array(f.buffer, f.byteOffset + layout.edge[l * 7 + r], cellsOf(layout.roles[r].rows) * cellsOf(layout.roles[r].cols)); + const node = (l, n) => new Float32Array(f.buffer, f.byteOffset + layout.node[l * 10 + n], cellsOf(layout.nodes[n].axis)); + function cellsOf(a) { return ax[a].cells; } + let worst = 0; + const chk = (inn, abs, val) => { worst = Math.max(worst, Math.abs(inn - val) / Math.max(abs, 1e-30)); }; + function rowsum(e, nc, r) { + let s = 0, a = 0; + for (let c = 0; c < nc; c++) { const x = e[r * nc + c]; s += x; a += Math.abs(x); } + return [s, a]; + } + const ND = ax.D.cells, NQ = ax.Q.cells, NF = ax.F.cells, NKV = ax.KV.cells; + for (let l = 0; l < L; l++) { + const D = node(l, 0), Dm = node(l, 1), Dout = node(l, 2); + const o = role(l, 3), down = role(l, 6); + for (let i = 0; i < ND; i++) { + let [s, a] = rowsum(o, NQ, i); + chk(D[i] + s, Math.abs(D[i]) + a, Dm[i]); + [s, a] = rowsum(down, NF, i); + chk(Dm[i] + s, Math.abs(Dm[i]) + a, Dout[i]); + } + const outs = [[0, 5, NQ, ND], [1, 6, NKV, ND], [2, 7, NKV, ND], [4, 8, NF, ND], [5, 9, NF, ND]]; // role, node + for (const [r, n, nr, nc] of outs) { + const e = role(l, r), v = node(l, n); + for (let i = 0; i < nr; i++) { const [s, a] = rowsum(e, nc, i); chk(s, a, v[i]); } + } + } + return worst; + } + + return { + on, + // files and args for the worker + wire(files, args) { + if (!on) return; + files.flow = { sab, off: 0, size: FLOW_BYTES }; + files["flow.ack"] = { sab: ackSab, off: 0, size: 4 }; + args.push("-flow", "flow"); + }, + ready(l) { + if (!on) return; + if (!l || !l.bytes) throw new Error("Hodge-3.5 started without its flow instrumentation."); + if (16 + l.bytes > FLOW_BYTES) throw new Error("A flow frame of " + l.bytes + " bytes does not fit the shared memory."); + layout = l; + }, + // ev: {"ev":"flow","seq","pos","id"} + frame(ev) { + if (!on || !layout) return; + const head = new DataView(sab, 0, 16); + const seq = head.getUint32(0, true), pos = head.getUint32(4, true), id = head.getUint32(8, true), n = head.getUint32(12, true); + if (seq !== ev.seq || n !== layout.bytes) { + throw new Error("flow frame " + ev.seq + ": the shared memory holds frame " + seq + " (" + n + " bytes)"); + } + const data = new Uint8Array(n); + data.set(new Uint8Array(sab, 16, n)); + new DataView(ackSab).setUint32(0, seq, true); + const f = new Float32Array(data.buffer); + const mismatch = check(f); + const fr = { seq, pos, id, flow: f, layout, mismatch }; + for (const fn of listeners) fn(fr); + return fr; + }, + listen(fn) { listeners.push(fn); }, + get layout() { return layout; }, + }; +} diff --git a/flowmap.js b/flowmap.js new file mode 100644 index 0000000000000000000000000000000000000000..07b1c0c2d461e73b4402d5ea892afb0b1dc3c19c --- /dev/null +++ b/flowmap.js @@ -0,0 +1,290 @@ +// The network map. volume.safetensors is the cochain: balance.* is the resting +// current between cells, and each live frame (flow.js) replaces that with the +// token's activations. Columns are the axes, lines are the strongest cell-to-cell +// currents, and the rail is one tick per layer. One 2D view of the hot layer. +// A 3D volume or graph walks every layer's cells on the token path and costs +// a few tokens per second for each of those views. + +const EDGES = [ + { role: 0, name: "q", a: "D", b: "Q", vol: "balance.q" }, + { role: 1, name: "k", a: "D", b: "KV", vol: "balance.k" }, + { role: 2, name: "v", a: "D", b: "KV", vol: "balance.v" }, + { role: 3, name: "o", a: "Q", b: "Dout", vol: "balance.o" }, + { role: 4, name: "gate", a: "D", b: "F", vol: "balance.gate" }, + { role: 5, name: "up", a: "D", b: "F", vol: "balance.up" }, + { role: 6, name: "down", a: "F", b: "Dout", vol: "balance.down" }, +]; + +const NODE = { D: 0, Dout: 2, F: 4, Q: 5, KV: 6 }; + +export function mountMap(root) { + const canvas = root.querySelector("#map-canvas"); + const meta = root.querySelector("#map-meta"); + const followBtn = root.querySelector("#map-follow"); + const ctx = canvas.getContext("2d"); + let vol = null; + let counts = null; + let layers = 0; + let layer = 0; + let follow = true; + let frame = null; + let token = ""; + let energy = null; + let line = ""; + + function say(text) { + line = text; + meta.textContent = text; + } + + function structure(bytes) { + vol = parseSafetensors(bytes); + const q = vol.get("balance.q"); + const k = vol.get("balance.k"); + const g = vol.get("balance.gate"); + if (!q || !k || !g) { + say("This volume has no cell map."); + return; + } + layers = q.shape[0]; + counts = { D: q.shape[2], Q: q.shape[1], KV: k.shape[1], F: g.shape[1], Dout: q.shape[2] }; + energy = new Float32Array(layers); + layer = hottest(); + say(counts.D + " D · " + counts.Q + " Q · " + counts.KV + " KV · " + counts.F + " F"); + draw(); + requestAnimationFrame(() => draw()); + } + + function note(text) { + token = text || ""; + } + + function show(fr) { + frame = fr; + if (!counts && fr.layout) countsFromLayout(fr.layout); + if (follow) layer = hottest(); + const cons = fr.mismatch < 1e-3 ? "conserved" : fr.mismatch.toExponential(2); + const word = token ? " · " + JSON.stringify(token) : ""; + say("L" + layer + " · pos " + fr.pos + word + " · " + cons); + draw(); + } + + function countsFromLayout(L) { + layers = L.layers; + counts = { + D: L.axes.D.cells, Q: L.axes.Q.cells, KV: L.axes.KV.cells, F: L.axes.F.cells, + Dout: L.axes.D.cells, + }; + if (!energy || energy.length !== layers) energy = new Float32Array(layers); + } + + function hottest() { + let best = 0, at = 0; + for (let i = 0; i < layers; i++) { + const e = layerEnergy(i); + energy[i] = e; + if (e > best) { best = e; at = i; } + } + return at; + } + + function layerEnergy(l) { + let s = 0; + for (const e of EDGES) { + const m = matrix(l, e); + if (!m) continue; + for (let i = 0; i < m.data.length; i++) s += Math.abs(m.data[i]); + } + return s; + } + + function matrix(l, edge) { + if (frame) { + const L = frame.layout; + const rows = L.axes[L.roles[edge.role].rows].cells; + const cols = L.axes[L.roles[edge.role].cols].cells; + const off = L.edge[l * 7 + edge.role]; + return { rows, cols, data: new Float32Array(frame.flow.buffer, frame.flow.byteOffset + off, rows * cols) }; + } + const t = vol && vol.get(edge.vol); + if (!t) return null; + const [, rows, cols] = t.shape; + const n = rows * cols; + return { rows, cols, data: t.data.subarray(l * n, (l + 1) * n) }; + } + + function nodeValue(name, i) { + if (!frame) return 0; + const v = nodeVec(NODE[name]); + return v ? v[i] || 0 : 0; + } + + function nodeVec(id) { + return nodeVecAt(layer, id); + } + + function nodeVecAt(l, id) { + const L = frame.layout; + const n = L.axes[L.nodes[id].axis].cells; + const off = L.node[l * 10 + id]; + return new Float32Array(frame.flow.buffer, frame.flow.byteOffset + off, n); + } + + function draw() { + if (!counts) return; + draw2d(); + } + + function draw2d() { + const cssW = root.clientWidth; + const cssH = canvas.clientHeight || root.clientHeight - 36; + if (!cssW || !cssH || !counts) return; + const dpr = Math.min(2, window.devicePixelRatio || 1); + canvas.width = Math.round(cssW * dpr); + canvas.height = Math.round(cssH * dpr); + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.clearRect(0, 0, cssW, cssH); + + const rail = 18; + const top = 22; + const bot = cssH - 16; + const span = Math.max(1, bot - top); + const xOf = (name) => { + const f = { D: 0.14, Q: 0.40, KV: 0.40, F: 0.68, Dout: 0.90 }[name]; + return rail + 8 + f * (cssW - rail - 16); + }; + const band = (name) => name === "Q" ? [top, top + span * 0.58] : name === "KV" ? [top + span * 0.70, bot] : [top, bot]; + const cols = {}; + for (const name of ["D", "Q", "KV", "F", "Dout"]) { + const [y0, y1] = band(name); + const n = counts[name]; + cols[name] = []; + for (let i = 0; i < n; i++) { + const t = n === 1 ? 0.5 : i / (n - 1); + cols[name].push({ x: xOf(name), y: y0 + t * (y1 - y0) }); + } + } + + const maxE = energy ? Math.max(...energy, 1e-12) : 1; + for (let i = 0; i < layers; i++) { + const y0 = (i / layers) * cssH; + const h = cssH / layers; + const hot = energy ? energy[i] / maxE : 0; + ctx.fillStyle = i === layer ? "rgba(232,168,124,0.95)" : "rgba(232,168,124," + (0.15 + 0.7 * hot) + ")"; + ctx.fillRect(4, y0 + 1, 6, Math.max(2, h - 2)); + } + + ctx.font = "11px Segoe UI, system-ui, sans-serif"; + ctx.fillStyle = "#8e96a3"; + ctx.textAlign = "center"; + ctx.fillText("D", xOf("D"), 14); + ctx.fillText("Q", xOf("Q"), 14); + ctx.fillText("F", xOf("F"), 14); + ctx.fillText("D′", xOf("Dout"), 14); + const kv = band("KV"); + ctx.fillText("KV", xOf("KV"), kv[0] - 4); + + const picked = []; + let edgeMax = 1e-12; + for (const e of EDGES) { + const m = matrix(layer, e); + if (!m) continue; + const take = strongest(m, 70); + for (const p of take) edgeMax = Math.max(edgeMax, Math.abs(p.v)); + picked.push([e, m, take]); + } + for (const [e, , take] of picked) { + for (const p of take) { + const from = cols[e.a][p.c]; + const to = cols[e.b][p.r]; + if (!from || !to) continue; + const mag = Math.abs(p.v) / edgeMax; + ctx.strokeStyle = p.v >= 0 ? "rgba(232,168,124," + (0.15 + 0.8 * mag) + ")" : "rgba(126,182,232," + (0.15 + 0.8 * mag) + ")"; + ctx.lineWidth = 0.6 + 1.6 * mag; + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + } + } + + for (const name of ["D", "Q", "KV", "F", "Dout"]) { + let max = 1e-12; + const vals = cols[name].map((_, i) => { + const v = nodeValue(name, i); + max = Math.max(max, Math.abs(v)); + return v; + }); + cols[name].forEach((p, i) => { + const v = vals[i]; + const mag = Math.abs(v) / max; + const r = frame ? 1.6 + 3.2 * mag : 1.8; + ctx.fillStyle = !frame ? "rgba(236,231,223,0.85)" : v >= 0 ? "rgba(232,168,124," + (0.45 + 0.55 * mag) + ")" : "rgba(126,182,232," + (0.45 + 0.55 * mag) + ")"; + ctx.beginPath(); + ctx.arc(p.x, p.y, r, 0, Math.PI * 2); + ctx.fill(); + }); + } + } + + canvas.addEventListener("click", (ev) => { + const rect = canvas.getBoundingClientRect(); + const x = ev.clientX - rect.left; + const y = ev.clientY - rect.top; + if (x > 22 || !layers) return; + layer = Math.min(layers - 1, Math.max(0, Math.floor(y / rect.height * layers))); + follow = false; + followBtn.setAttribute("aria-pressed", "false"); + if (frame) say("L" + layer + " · pinned"); + draw(); + }); + followBtn.addEventListener("click", () => { + follow = !follow; + followBtn.setAttribute("aria-pressed", follow ? "true" : "false"); + if (follow && frame) layer = hottest(); + draw(); + }); + const ro = new ResizeObserver(() => draw()); + ro.observe(root); + draw(); + + return { structure, frame: show, token: note }; +} + +// The n largest |currents|. Rows are destination cells, columns are sources. +function strongest(m, n) { + const heap = []; + for (let i = 0; i < m.data.length; i++) { + const v = m.data[i]; + const a = Math.abs(v); + if (a === 0) continue; + const item = { v, a, r: (i / m.cols) | 0, c: i % m.cols }; + if (heap.length < n) { + heap.push(item); + continue; + } + let min = 0; + for (let k = 1; k < heap.length; k++) if (heap[k].a < heap[min].a) min = k; + if (a > heap[min].a) heap[min] = item; + } + return heap; +} + +function parseSafetensors(buf) { + const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); + const n = Number(dv.getBigUint64(0, true)); + const header = JSON.parse(new TextDecoder().decode(buf.subarray(8, 8 + n))); + const base = 8 + n; + const map = new Map(); + for (const [name, meta] of Object.entries(header)) { + if (!meta || !meta.shape || !meta.data_offsets) continue; + const [a, b] = meta.data_offsets; + const off = buf.byteOffset + base + a; + const count = (b - a) / 4; + map.set(name, { + shape: meta.shape, + data: meta.dtype === "F32" ? new Float32Array(buf.buffer, off, count) : null, + }); + } + return map; +} diff --git a/frame.js b/frame.js new file mode 100644 index 0000000000000000000000000000000000000000..b368a4e26a038f16d9ef2d966b39070e9dc0a236 --- /dev/null +++ b/frame.js @@ -0,0 +1,100 @@ +// blink.mojom.LocalFrame.JavaScriptExecuteRequest. +// The page is the frame. It runs the script. The browser sends the request +// with its own name. A quoted copy of the script is not a result, and neither +// is an interface line. +import { instantiate, run } from "./loader.js"; +import { localFrameWindow, pageFetch } from "./browse.js"; + +const GUEST = "local_frame_exec.wasm"; +let bytesP = null; + +export function requestValue(stdout) { + const lines = String(stdout || "").split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const s = lines[i].trim(); + if (!s) continue; + if (s.startsWith("interface:") || s.startsWith("func ")) continue; + return s; + } + return ""; +} + +// The guest quotes a script it does not evaluate. That quote is not a page. +// A short prefix plus the question is the same echo. +export function frameEcho(output, question) { + const q = String(question || "").replace(/\s+/g, " ").trim(); + if (q.length < 8) return false; + let s = String(output || "").trim(); + if (s.length >= 2 && s[0] === "\"" && s[s.length - 1] === "\"") s = s.slice(1, -1).trim(); + s = s.replace(/\s+/g, " ").trim(); + if (!s) return false; + const a = s.toLowerCase(); + const b = q.toLowerCase(); + if (a === b) return true; + // The guest repeats the question with a short lead-in. A page that merely + // contains the subject is the lookup, not that echo. + const at = a.lastIndexOf(b); + if (at < 0) return false; + const extra = a.length - b.length; + return extra < 160 && extra < b.length; +} + +export async function executeBytes(bytes, javascript) { + const js = String(javascript ?? ""); + let out = ""; + const loaded = await instantiate(bytes, { + args: [GUEST, js], + stdout: (t) => { out += t; }, + stderr: () => {}, + }); + await run(loaded); + return requestValue(out); +} + +function asText(value) { + if (value == null) return ""; + if (typeof value === "string") return value; + if (typeof value === "number" || typeof value === "boolean") return String(value); + return ""; +} + +// The interface print and a quoted script are not the value of the request. +export function frameStamp(value) { + const s = String(value || "").trim(); + if (!s) return false; + if (/^(?:interface:|func )/.test(s)) return true; + if (s.includes("blink.mojom.LocalFrame.JavaScriptExecuteRequest")) return true; + return false; +} + +export async function executeRequest(javascript, fetchImpl) { + const js = String(javascript ?? ""); + const own = !fetchImpl || fetchImpl === globalThis.fetch; + const frame = own ? await localFrameWindow() : null; + const realm = frame && typeof frame.Function === "function" ? frame : globalThis; + const f = own ? pageFetch(globalThis.fetch) : fetchImpl; + let value = ""; + try { + const runScript = new realm.Function("fetch", "return (async () => {\n" + js + "\n})()"); + value = asText(await runScript(f)); + } catch { + return ""; + } + if (!value || frameStamp(value)) return ""; + return value; +} + +// duck.ai and Gemini answer in this browser. The local frame is the IWA. +// Its page loads offscreen_script.js and asks those sites. The real page sends the chat. +export function serviceScript(kind, question) { + const q = JSON.stringify(String(question || "").replace(/\s+/g, " ").trim().slice(0, 180)); + const k = String(kind || "").trim().toLowerCase(); + const source = k === "gemini" || k === "gemini.google.com" ? "gemini" : "duck"; + return ` + const q = ${q}; + const source = ${JSON.stringify(source)}; + if (typeof window === "undefined" || typeof window.__RBI_IWA_ASK__ !== "function") return ""; + const text = await window.__RBI_IWA_ASK__(source, q); + return String(text || "").replace(/\\s+/g, " ").trim(); + `; +} diff --git a/fzstd.js b/fzstd.js new file mode 100644 index 0000000000000000000000000000000000000000..ad1851aa7abe6548d23b9f0446c5dba32431d98c --- /dev/null +++ b/fzstd.js @@ -0,0 +1,754 @@ +/* fzstd 0.1.1, MIT, https://github.com/101arrowz/fzstd — Zstandard decode for BNZ segments. */ +// Some numerical data is initialized as -1 even when it doesn't need initialization to help the JIT infer types +// aliases for shorter compressed code (most minifers don't do this) +var ab = ArrayBuffer, u8 = Uint8Array, u16 = Uint16Array, i16 = Int16Array, u32 = Uint32Array, i32 = Int32Array; +var slc = function (v, s, e) { + if (u8.prototype.slice) + return u8.prototype.slice.call(v, s, e); + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + var n = new u8(e - s); + n.set(v.subarray(s, e)); + return n; +}; +var fill = function (v, n, s, e) { + if (u8.prototype.fill) + return u8.prototype.fill.call(v, n, s, e); + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + for (; s < e; ++s) + v[s] = n; + return v; +}; +var cpw = function (v, t, s, e) { + if (u8.prototype.copyWithin) + return u8.prototype.copyWithin.call(v, t, s, e); + if (s == null || s < 0) + s = 0; + if (e == null || e > v.length) + e = v.length; + while (s < e) { + v[t++] = v[s++]; + } +}; +/** + * Codes for errors generated within this library + */ +export var ZstdErrorCode = { + InvalidData: 0, + WindowSizeTooLarge: 1, + InvalidBlockType: 2, + FSEAccuracyTooHigh: 3, + DistanceTooFarBack: 4, + UnexpectedEOF: 5 +}; +// error codes +var ec = [ + 'invalid zstd data', + 'window size too large (>2046MB)', + 'invalid block type', + 'FSE accuracy too high', + 'match distance too far back', + 'unexpected EOF' +]; +var err = function (ind, msg, nt) { + var e = new Error(msg || ec[ind]); + e.code = ind; + if (Error.captureStackTrace) + Error.captureStackTrace(e, err); + if (!nt) + throw e; + return e; +}; +var rb = function (d, b, n) { + var i = 0, o = 0; + for (; i < n; ++i) + o |= d[b++] << (i << 3); + return o; +}; +var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; }; +// read Zstandard frame header +var rzfh = function (dat, w) { + var n3 = dat[0] | (dat[1] << 8) | (dat[2] << 16); + if (n3 == 0x2FB528 && dat[3] == 253) { + // Zstandard + var flg = dat[4]; + // single segment checksum dict flag frame content flag + var ss = (flg >> 5) & 1, cc = (flg >> 2) & 1, df = flg & 3, fcf = flg >> 6; + if (flg & 8) + err(0); + // byte + var bt = 6 - ss; + // dict bytes + var db = df == 3 ? 4 : df; + // dictionary id + var di = rb(dat, bt, db); + bt += db; + // frame size bytes + var fsb = fcf ? (1 << fcf) : ss; + // frame source size + var fss = rb(dat, bt, fsb) + ((fcf == 1) && 256); + // window size + var ws = fss; + if (!ss) { + // window descriptor + var wb = 1 << (10 + (dat[5] >> 3)); + ws = wb + (wb >> 3) * (dat[5] & 7); + } + if (ws > 2145386496) + err(1); + var buf = new u8((w == 1 ? (fss || ws) : w ? 0 : ws) + 12); + buf[0] = 1, buf[4] = 4, buf[8] = 8; + return { + b: bt + fsb, + y: 0, + l: 0, + d: di, + w: (w && w != 1) ? w : buf.subarray(12), + e: ws, + o: new i32(buf.buffer, 0, 3), + u: fss, + c: cc, + m: Math.min(131072, ws) + }; + } + else if (((n3 >> 4) | (dat[3] << 20)) == 0x184D2A5) { + // skippable + return b4(dat, 4) + 8; + } + err(0); +}; +// most significant bit for nonzero +var msb = function (val) { + var bits = 0; + for (; (1 << bits) <= val; ++bits) + ; + return bits - 1; +}; +// read finite state entropy +var rfse = function (dat, bt, mal) { + // table pos + var tpos = (bt << 3) + 4; + // accuracy log + var al = (dat[bt] & 15) + 5; + if (al > mal) + err(3); + // size + var sz = 1 << al; + // probabilities symbols repeat index high threshold + var probs = sz, sym = -1, re = -1, i = -1, ht = sz; + // optimization: single allocation is much faster + var buf = new ab(512 + (sz << 2)); + var freq = new i16(buf, 0, 256); + // same view as freq + var dstate = new u16(buf, 0, 256); + var nstate = new u16(buf, 512, sz); + var bb1 = 512 + (sz << 1); + var syms = new u8(buf, bb1, sz); + var nbits = new u8(buf, bb1 + sz); + while (sym < 255 && probs > 0) { + var bits = msb(probs + 1); + var cbt = tpos >> 3; + // mask + var msk = (1 << (bits + 1)) - 1; + var val = ((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (tpos & 7)) & msk; + // mask (1 fewer bit) + var msk1fb = (1 << bits) - 1; + // max small value + var msv = msk - probs - 1; + // small value + var sval = val & msk1fb; + if (sval < msv) + tpos += bits, val = sval; + else { + tpos += bits + 1; + if (val > msk1fb) + val -= msv; + } + freq[++sym] = --val; + if (val == -1) { + probs += val; + syms[--ht] = sym; + } + else + probs -= val; + if (!val) { + do { + // repeat byte + var rbt = tpos >> 3; + re = ((dat[rbt] | (dat[rbt + 1] << 8)) >> (tpos & 7)) & 3; + tpos += 2; + sym += re; + } while (re == 3); + } + } + if (sym > 255 || probs) + err(0); + var sympos = 0; + // sym step (coprime with sz - formula from zstd source) + var sstep = (sz >> 1) + (sz >> 3) + 3; + // sym mask + var smask = sz - 1; + for (var s = 0; s <= sym; ++s) { + var sf = freq[s]; + if (sf < 1) { + dstate[s] = -sf; + continue; + } + // This is split into two loops in zstd to avoid branching, but as JS is higher-level that is unnecessary + for (i = 0; i < sf; ++i) { + syms[sympos] = s; + do { + sympos = (sympos + sstep) & smask; + } while (sympos >= ht); + } + } + // After spreading symbols, should be zero again + if (sympos) + err(0); + for (i = 0; i < sz; ++i) { + // next state + var ns = dstate[syms[i]]++; + // num bits + var nb = nbits[i] = al - msb(ns); + nstate[i] = (ns << nb) - sz; + } + return [(tpos + 7) >> 3, { + b: al, + s: syms, + n: nbits, + t: nstate + }]; +}; +// read huffman +var rhu = function (dat, bt) { + // index weight count + var i = 0, wc = -1; + // buffer header byte + var buf = new u8(292), hb = dat[bt]; + // huffman weights + var hw = buf.subarray(0, 256); + // rank count + var rc = buf.subarray(256, 268); + // rank index + var ri = new u16(buf.buffer, 268); + // NOTE: at this point bt is 1 less than expected + if (hb < 128) { + // end byte, fse decode table + var _a = rfse(dat, bt + 1, 6), ebt = _a[0], fdt = _a[1]; + bt += hb; + var epos = ebt << 3; + // last byte + var lb = dat[bt]; + if (!lb) + err(0); + // state1 state2 state1 bits state2 bits + var st1 = 0, st2 = 0, btr1 = fdt.b, btr2 = btr1; + // fse pos + // pre-increment to account for original deficit of 1 + var fpos = (++bt << 3) - 8 + msb(lb); + for (;;) { + fpos -= btr1; + if (fpos < epos) + break; + var cbt = fpos >> 3; + st1 += ((dat[cbt] | (dat[cbt + 1] << 8)) >> (fpos & 7)) & ((1 << btr1) - 1); + hw[++wc] = fdt.s[st1]; + fpos -= btr2; + if (fpos < epos) + break; + cbt = fpos >> 3; + st2 += ((dat[cbt] | (dat[cbt + 1] << 8)) >> (fpos & 7)) & ((1 << btr2) - 1); + hw[++wc] = fdt.s[st2]; + btr1 = fdt.n[st1]; + st1 = fdt.t[st1]; + btr2 = fdt.n[st2]; + st2 = fdt.t[st2]; + } + if (++wc > 255) + err(0); + } + else { + wc = hb - 127; + for (; i < wc; i += 2) { + var byte = dat[++bt]; + hw[i] = byte >> 4; + hw[i + 1] = byte & 15; + } + ++bt; + } + // weight exponential sum + var wes = 0; + for (i = 0; i < wc; ++i) { + var wt = hw[i]; + // bits must be at most 11, same as weight + if (wt > 11) + err(0); + wes += wt && (1 << (wt - 1)); + } + // max bits + var mb = msb(wes) + 1; + // table size + var ts = 1 << mb; + // remaining sum + var rem = ts - wes; + // must be power of 2 + if (rem & (rem - 1)) + err(0); + hw[wc++] = msb(rem) + 1; + for (i = 0; i < wc; ++i) { + var wt = hw[i]; + ++rc[hw[i] = wt && (mb + 1 - wt)]; + } + // huf buf + var hbuf = new u8(ts << 1); + // symbols num bits + var syms = hbuf.subarray(0, ts), nb = hbuf.subarray(ts); + ri[mb] = 0; + for (i = mb; i > 0; --i) { + var pv = ri[i]; + fill(nb, i, pv, ri[i - 1] = pv + rc[i] * (1 << (mb - i))); + } + if (ri[0] != ts) + err(0); + for (i = 0; i < wc; ++i) { + var bits = hw[i]; + if (bits) { + var code = ri[bits]; + fill(syms, i, code, ri[bits] = code + (1 << (mb - bits))); + } + } + return [bt, { + n: nb, + b: mb, + s: syms + }]; +}; +// Tables generated using this: +// https://gist.github.com/101arrowz/a979452d4355992cbf8f257cbffc9edd +// default literal length table +var dllt = /*#__PURE__*/ rfse(/*#__PURE__*/ new u8([ + 81, 16, 99, 140, 49, 198, 24, 99, 12, 33, 196, 24, 99, 102, 102, 134, 70, 146, 4 +]), 0, 6)[1]; +// default match length table +var dmlt = /*#__PURE__*/ rfse(/*#__PURE__*/ new u8([ + 33, 20, 196, 24, 99, 140, 33, 132, 16, 66, 8, 33, 132, 16, 66, 8, 33, 68, 68, 68, 68, 68, 68, 68, 68, 36, 9 +]), 0, 6)[1]; +// default offset code table +var doct = /*#__PURE__ */ rfse(/*#__PURE__*/ new u8([ + 32, 132, 16, 66, 102, 70, 68, 68, 68, 68, 36, 73, 2 +]), 0, 5)[1]; +// bits to baseline +var b2bl = function (b, s) { + var len = b.length, bl = new i32(len); + for (var i = 0; i < len; ++i) { + bl[i] = s; + s += 1 << b[i]; + } + return bl; +}; +// literal length bits +var llb = /*#__PURE__ */ new u8(( /*#__PURE__ */new i32([ + 0, 0, 0, 0, 16843009, 50528770, 134678020, 202050057, 269422093 +])).buffer, 0, 36); +// literal length baseline +var llbl = /*#__PURE__ */ b2bl(llb, 0); +// match length bits +var mlb = /*#__PURE__ */ new u8(( /*#__PURE__ */new i32([ + 0, 0, 0, 0, 0, 0, 0, 0, 16843009, 50528770, 117769220, 185207048, 252579084, 16 +])).buffer, 0, 53); +// match length baseline +var mlbl = /*#__PURE__ */ b2bl(mlb, 3); +// decode huffman stream +var dhu = function (dat, out, hu) { + var len = dat.length, ss = out.length, lb = dat[len - 1], msk = (1 << hu.b) - 1, eb = -hu.b; + if (!lb) + err(0); + var st = 0, btr = hu.b, pos = (len << 3) - 8 + msb(lb) - btr, i = -1; + for (; pos > eb && i < ss;) { + var cbt = pos >> 3; + var val = (dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (pos & 7); + st = ((st << btr) | val) & msk; + out[++i] = hu.s[st]; + pos -= (btr = hu.n[st]); + } + if (pos != eb || i + 1 != ss) + err(0); +}; +// decode huffman stream 4x +// TODO: use workers to parallelize +var dhu4 = function (dat, out, hu) { + var bt = 6; + var ss = out.length, sz1 = (ss + 3) >> 2, sz2 = sz1 << 1, sz3 = sz1 + sz2; + dhu(dat.subarray(bt, bt += dat[0] | (dat[1] << 8)), out.subarray(0, sz1), hu); + dhu(dat.subarray(bt, bt += dat[2] | (dat[3] << 8)), out.subarray(sz1, sz2), hu); + dhu(dat.subarray(bt, bt += dat[4] | (dat[5] << 8)), out.subarray(sz2, sz3), hu); + dhu(dat.subarray(bt), out.subarray(sz3), hu); +}; +// read Zstandard block +var rzb = function (dat, st, out) { + var _a; + var bt = st.b; + // byte 0 block type + var b0 = dat[bt], btype = (b0 >> 1) & 3; + st.l = b0 & 1; + var sz = (b0 >> 3) | (dat[bt + 1] << 5) | (dat[bt + 2] << 13); + // end byte for block + var ebt = (bt += 3) + sz; + if (btype == 1) { + if (bt >= dat.length) + return; + st.b = bt + 1; + if (out) { + fill(out, dat[bt], st.y, st.y += sz); + return out; + } + return fill(new u8(sz), dat[bt]); + } + if (ebt > dat.length) + return; + if (btype == 0) { + st.b = ebt; + if (out) { + out.set(dat.subarray(bt, ebt), st.y); + st.y += sz; + return out; + } + return slc(dat, bt, ebt); + } + if (btype == 2) { + // byte 3 lit btype size format + var b3 = dat[bt], lbt = b3 & 3, sf = (b3 >> 2) & 3; + // lit src size lit cmp sz 4 streams + var lss = b3 >> 4, lcs = 0, s4 = 0; + if (lbt < 2) { + if (sf & 1) + lss |= (dat[++bt] << 4) | ((sf & 2) && (dat[++bt] << 12)); + else + lss = b3 >> 3; + } + else { + s4 = sf; + if (sf < 2) + lss |= ((dat[++bt] & 63) << 4), lcs = (dat[bt] >> 6) | (dat[++bt] << 2); + else if (sf == 2) + lss |= (dat[++bt] << 4) | ((dat[++bt] & 3) << 12), lcs = (dat[bt] >> 2) | (dat[++bt] << 6); + else + lss |= (dat[++bt] << 4) | ((dat[++bt] & 63) << 12), lcs = (dat[bt] >> 6) | (dat[++bt] << 2) | (dat[++bt] << 10); + } + ++bt; + // add literals to end - can never overlap with backreferences because unused literals always appended + var buf = out ? out.subarray(st.y, st.y + st.m) : new u8(st.m); + // starting point for literals + var spl = buf.length - lss; + if (lbt == 0) + buf.set(dat.subarray(bt, bt += lss), spl); + else if (lbt == 1) + fill(buf, dat[bt++], spl); + else { + // huffman table + var hu = st.h; + if (lbt == 2) { + var hud = rhu(dat, bt); + // subtract description length + lcs += bt - (bt = hud[0]); + st.h = hu = hud[1]; + } + else if (!hu) + err(0); + (s4 ? dhu4 : dhu)(dat.subarray(bt, bt += lcs), buf.subarray(spl), hu); + } + // num sequences + var ns = dat[bt++]; + if (ns) { + if (ns == 255) + ns = (dat[bt++] | (dat[bt++] << 8)) + 0x7F00; + else if (ns > 127) + ns = ((ns - 128) << 8) | dat[bt++]; + // symbol compression modes + var scm = dat[bt++]; + if (scm & 3) + err(0); + var dts = [dmlt, doct, dllt]; + for (var i = 2; i > -1; --i) { + var md = (scm >> ((i << 1) + 2)) & 3; + if (md == 1) { + // rle buf + var rbuf = new u8([0, 0, dat[bt++]]); + dts[i] = { + s: rbuf.subarray(2, 3), + n: rbuf.subarray(0, 1), + t: new u16(rbuf.buffer, 0, 1), + b: 0 + }; + } + else if (md == 2) { + // accuracy log 8 for offsets, 9 for others + _a = rfse(dat, bt, 9 - (i & 1)), bt = _a[0], dts[i] = _a[1]; + } + else if (md == 3) { + if (!st.t) + err(0); + dts[i] = st.t[i]; + } + } + var _b = st.t = dts, mlt = _b[0], oct = _b[1], llt = _b[2]; + var lb = dat[ebt - 1]; + if (!lb) + err(0); + var spos = (ebt << 3) - 8 + msb(lb) - llt.b, cbt = spos >> 3, oubt = 0; + var lst = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << llt.b) - 1); + cbt = (spos -= oct.b) >> 3; + var ost = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << oct.b) - 1); + cbt = (spos -= mlt.b) >> 3; + var mst = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << mlt.b) - 1); + for (++ns; --ns;) { + var llc = llt.s[lst]; + var lbtr = llt.n[lst]; + var mlc = mlt.s[mst]; + var mbtr = mlt.n[mst]; + var ofc = oct.s[ost]; + var obtr = oct.n[ost]; + cbt = (spos -= ofc) >> 3; + var ofp = 1 << ofc; + var off = ofp + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16) | (dat[cbt + 3] << 24)) >>> (spos & 7)) & (ofp - 1)); + cbt = (spos -= mlb[mlc]) >> 3; + var ml = mlbl[mlc] + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (spos & 7)) & ((1 << mlb[mlc]) - 1)); + cbt = (spos -= llb[llc]) >> 3; + var ll = llbl[llc] + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (spos & 7)) & ((1 << llb[llc]) - 1)); + cbt = (spos -= lbtr) >> 3; + lst = llt.t[lst] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << lbtr) - 1)); + cbt = (spos -= mbtr) >> 3; + mst = mlt.t[mst] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << mbtr) - 1)); + cbt = (spos -= obtr) >> 3; + ost = oct.t[ost] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << obtr) - 1)); + if (off > 3) { + st.o[2] = st.o[1]; + st.o[1] = st.o[0]; + st.o[0] = off -= 3; + } + else { + var idx = off - (ll != 0); + if (idx) { + off = idx == 3 ? st.o[0] - 1 : st.o[idx]; + if (idx > 1) + st.o[2] = st.o[1]; + st.o[1] = st.o[0]; + st.o[0] = off; + } + else + off = st.o[0]; + } + for (var i = 0; i < ll; ++i) { + buf[oubt + i] = buf[spl + i]; + } + oubt += ll, spl += ll; + var stin = oubt - off; + if (stin < 0) { + var len = -stin; + var bs = st.e + stin; + if (len > ml) + len = ml; + for (var i = 0; i < len; ++i) { + buf[oubt + i] = st.w[bs + i]; + } + oubt += len, ml -= len, stin = 0; + } + for (var i = 0; i < ml; ++i) { + buf[oubt + i] = buf[stin + i]; + } + oubt += ml; + } + if (oubt != spl) { + while (spl < buf.length) { + buf[oubt++] = buf[spl++]; + } + } + else + oubt = buf.length; + if (out) + st.y += oubt; + else + buf = slc(buf, 0, oubt); + } + else if (out) { + st.y += lss; + if (spl) { + for (var i = 0; i < lss; ++i) { + buf[i] = buf[spl + i]; + } + } + } + else if (spl) + buf = slc(buf, spl); + st.b = ebt; + return buf; + } + err(2); +}; +// concat +var cct = function (bufs, ol) { + if (bufs.length == 1) + return bufs[0]; + var buf = new u8(ol); + for (var i = 0, b = 0; i < bufs.length; ++i) { + var chk = bufs[i]; + buf.set(chk, b); + b += chk.length; + } + return buf; +}; +/** + * Decompresses Zstandard data + * @param dat The input data + * @param buf The output buffer. If unspecified, the function will allocate + * exactly enough memory to fit the decompressed data. If your + * data has multiple frames and you know the output size, specifying + * it will yield better performance. + * @returns The decompressed data + */ +export function decompress(dat, buf) { + var bufs = [], nb = +!buf; + var bt = 0, ol = 0; + for (; dat.length;) { + var st = rzfh(dat, nb || buf); + if (typeof st == 'object') { + if (nb) { + buf = null; + if (st.w.length == st.u) { + bufs.push(buf = st.w); + ol += st.u; + } + } + else { + bufs.push(buf); + st.e = 0; + } + for (; !st.l;) { + var blk = rzb(dat, st, buf); + if (!blk) + err(5); + if (buf) + st.e = st.y; + else { + bufs.push(blk); + ol += blk.length; + cpw(st.w, 0, blk.length); + st.w.set(blk, st.w.length - blk.length); + } + } + bt = st.b + (st.c * 4); + } + else + bt = st; + dat = dat.subarray(bt); + } + return cct(bufs, ol); +} +/** + * Decompressor for Zstandard streamed data + */ +var Decompress = /*#__PURE__*/ (function () { + /** + * Creates a Zstandard decompressor + * @param ondata The handler for stream data + */ + function Decompress(ondata) { + this.ondata = ondata; + this.c = []; + this.l = 0; + this.z = 0; + } + /** + * Pushes data to be decompressed + * @param chunk The chunk of data to push + * @param final Whether or not this is the last chunk in the stream + */ + Decompress.prototype.push = function (chunk, final) { + if (typeof this.s == 'number') { + var sub = Math.min(chunk.length, this.s); + chunk = chunk.subarray(sub); + this.s -= sub; + } + var sl = chunk.length; + var ncs = sl + this.l; + if (!this.s) { + if (final) { + if (!ncs) { + this.ondata(new u8(0), true); + return; + } + // min for frame + one block + if (ncs < 5) + err(5); + } + else if (ncs < 18) { + this.c.push(chunk); + this.l = ncs; + return; + } + if (this.l) { + this.c.push(chunk); + chunk = cct(this.c, ncs); + this.c = []; + this.l = 0; + } + if (typeof (this.s = rzfh(chunk)) == 'number') + return this.push(chunk, final); + } + if (typeof this.s != 'number') { + if (ncs < (this.z || 3)) { + if (final) + err(5); + this.c.push(chunk); + this.l = ncs; + return; + } + if (this.l) { + this.c.push(chunk); + chunk = cct(this.c, ncs); + this.c = []; + this.l = 0; + } + if (!this.z && ncs < (this.z = (chunk[this.s.b] & 2) ? 4 : 3 + ((chunk[this.s.b] >> 3) | (chunk[this.s.b + 1] << 5) | (chunk[this.s.b + 2] << 13)))) { + if (final) + err(5); + this.c.push(chunk); + this.l = ncs; + return; + } + else + this.z = 0; + for (;;) { + var blk = rzb(chunk, this.s); + if (!blk) { + if (final) + err(5); + var adc = chunk.subarray(this.s.b); + this.s.b = 0; + this.c.push(adc), this.l += adc.length; + return; + } + else { + this.ondata(blk, false); + cpw(this.s.w, 0, blk.length); + this.s.w.set(blk, this.s.w.length - blk.length); + } + if (this.s.l) { + var rest = chunk.subarray(this.s.b); + this.s = this.s.c * 4; + this.push(rest, final); + return; + } + } + } + else if (final) + err(5); + }; + return Decompress; +}()); +export { Decompress }; diff --git a/hkruntime.wasm b/hkruntime.wasm new file mode 100644 index 0000000000000000000000000000000000000000..341a4e58c528ac4c16601afa5fe9224a3385cf92 --- /dev/null +++ b/hkruntime.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fb83ebdb4e9cc1c3420ed967d1e8c226c65e589767f95718488589c1b3cdcc0 +size 13853065 diff --git a/icons/icon-192.png b/icons/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..5a8bf31df453060b42dee4688abf6e4b2fded5fa Binary files /dev/null and b/icons/icon-192.png differ diff --git a/icons/icon-512.png b/icons/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..6c56637bdf93596e9c54fb9e0b94fd95841adf96 Binary files /dev/null and b/icons/icon-512.png differ diff --git a/index.html b/index.html index b0c4b3666032a737f3903db53e6a8a9272483e28..edb2b2747ce0092732bba43bd12cc7a399f09d63 100644 --- a/index.html +++ b/index.html @@ -1,19 +1,2627 @@ <!doctype html> -<html> - <head> - <meta charset="utf-8" /> - <meta name="viewport" content="width=device-width" /> - <title>My static Space - - - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

-
- + + + + + +Hodge-3.5 · Encryptid EdgeAI + + + + + + + + + + + +
+ + + EdgeAI +
+ + + + +
+ Starting +
+
+ + +
+
+
+
ENCRYPTID
+

Bringing Hodge-3.5 onto this device.

+ +
+ + +
+
+
+ + +
+
+ + + + +
+ + + + +
+ +

Browser agent

+

This is a browser agent. If you accept, Hodge-3.5 makes requests on your behalf from this browser. Those requests look things up, including DuckDuckGo, duck.ai, Gemini, and Wikipedia.

+

Accept and Hodge-3.5 starts. Deny and you cannot proceed. Hodge-3.5 does not start, and it makes no requests for you.

+

Terms of Service

+
+ + +
+ +
+
+ +
+ + diff --git a/iwa/ask.js b/iwa/ask.js new file mode 100644 index 0000000000000000000000000000000000000000..53311b9e96748974f5f7aa7fca64ca33a20795de --- /dev/null +++ b/iwa/ask.js @@ -0,0 +1,148 @@ +// duck.ai and Gemini answer when their own pages send the chat. +// The IWA's controlled frame reads that page. A submit does not open a tab. +(function () { + var DUCK = "https://duck.ai/"; + var GEMINI = "https://gemini.google.com/app"; + + var DUCK_RUN = `async function run(question) { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + for (let i = 0; i < 30; i++) { + if (document.querySelector("textarea")) break; + await sleep(400); + } + const ta = document.querySelector("textarea"); + if (!ta) return ""; + ta.focus(); + ta.value = question; + ta.dispatchEvent(new Event("input", { bubbles: true })); + await sleep(300); + const btn = [...document.querySelectorAll("button")].find((b) => { + const a = b.getAttribute("aria-label") || ""; + const t = (b.innerText || "").replace(/\\s+/g, " ").trim(); + return a === "Send" || a === "Ask" || t === "Ask" || t === "Send"; + }); + if (!btn) return ""; + btn.click(); + const until = Date.now() + 40000; + while (Date.now() < until) { + await sleep(1000); + const loc = [...document.querySelectorAll("button")].find((b) => (b.innerText || "").trim() === "Don't Use"); + if (loc) loc.click(); + const stop = [...document.querySelectorAll("button")].some((b) => b.getAttribute("aria-label") === "Stop generating" && !b.disabled); + if (stop) continue; + let s = (document.body.innerText || "").replace(/\\s+/g, " ").trim(); + const said = s.search(/Duck\\.ai said/i); + if (said < 0) continue; + s = s.slice(said).replace(/^Duck\\.ai said\\s+/i, ""); + const end = s.search(/Duck\\.ai works best|Jump to latest|All chats are private|AI can make mistakes/i); + if (end > 0) s = s.slice(0, end); + s = s.replace(/\\s+/g, " ").trim(); + if (s.length > 12) return s.slice(0, 1500); + } + return ""; + }`; + + var GEMINI_RUN = `async function run(question) { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + let box = null; + for (let i = 0; i < 30; i++) { + box = document.querySelector("rich-textarea textarea, textarea, div[contenteditable='true']"); + if (box) break; + await sleep(400); + } + if (!box) return ""; + box.focus(); + if (box.tagName === "TEXTAREA" || box.tagName === "INPUT") { + box.value = question; + box.dispatchEvent(new Event("input", { bubbles: true })); + } else { + box.textContent = question; + box.dispatchEvent(new InputEvent("input", { bubbles: true, data: question })); + } + await sleep(300); + const btn = [...document.querySelectorAll("button")].find((b) => /send/i.test(b.getAttribute("aria-label") || b.innerText || "")); + if (btn) btn.click(); + else box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", code: "Enter", bubbles: true })); + const until = Date.now() + 40000; + let last = ""; + let stable = 0; + while (Date.now() < until) { + await sleep(1000); + const nodes = document.querySelectorAll("message-content, .model-response-text, .markdown"); + const raw = nodes.length ? nodes[nodes.length - 1].innerText : ""; + const s = String(raw || "").replace(/\\s+/g, " ").trim(); + if (!s || s === question) continue; + if (s === last) { + stable += 1; + if (stable >= 2 && s.length > 20) return s.slice(0, 1500); + } else { + stable = 0; + last = s; + } + } + return last && last !== question ? last.slice(0, 1500) : ""; + }`; + + function destOf(source) { + return source === "gemini" ? GEMINI : DUCK; + } + + function control() { + var el = document.getElementById("agent-view"); + if (!el || typeof el.executeScript !== "function") return null; + return el; + } + + function pageCode(source, question) { + var run = source === "gemini" ? GEMINI_RUN : DUCK_RUN; + return "(async function () {\n" + run + "\nreturn await run(" + JSON.stringify(question) + ");\n})()"; + } + + function firstText(value) { + if (typeof value === "string") return value; + if (Array.isArray(value)) return firstText(value[0]); + if (value && typeof value.result === "string") return value.result; + return ""; + } + + function runControlled(source, question) { + var el = control(); + var dest = destOf(source); + return new Promise(function (resolve) { + var done = false; + function finish(text) { + if (done) return; + done = true; + resolve(typeof text === "string" ? text : ""); + } + function read() { + var code = pageCode(source, question); + try { + var pending = el.executeScript({ code: code }); + if (pending && typeof pending.then === "function") { + pending.then(function (r) { finish(firstText(r)); }).catch(function () { finish(""); }); + return; + } + finish(firstText(pending)); + } catch (e) { + try { + el.executeScript({ code: code }, function (r) { finish(firstText(r)); }); + } catch (e2) { finish(""); } + } + } + el.addEventListener("loadstop", read, { once: true }); + el.addEventListener("loadabort", function () { finish(""); }, { once: true }); + try { el.src = dest; } + catch (e) { finish(""); return; } + setTimeout(function () { finish(""); }, 50000); + }); + } + + self.__RBI_IWA_ASK__ = function (source, q) { + var kind = String(source || "") === "gemini" ? "gemini" : "duck"; + var question = String(q || "").replace(/\s+/g, " ").trim().slice(0, 180); + if (!question) return Promise.resolve(""); + if (control()) return runControlled(kind, question); + return Promise.resolve(""); + }; +})(); diff --git a/iwa/boot.js b/iwa/boot.js new file mode 100644 index 0000000000000000000000000000000000000000..ef32dee8c940bba54ff5e8e6dfae8a8e98e91438 --- /dev/null +++ b/iwa/boot.js @@ -0,0 +1,70 @@ +// The installed IWA document. offscreen_script.js runs here, in this browser. +// Its fetch handler JSON.parses the body, so a page comes back as {"text": page}. +self.__RBI_SECRPC__ = 91556947316803; +self.__RBI_FETCH_HOST__ = null; +var network = self.fetch.bind(self); + +function originRead(input, init) { + var url = typeof input === "string" ? input : (input && input.url) || ""; + if (!/^https:\/\//i.test(url)) return Promise.reject(new Error("Failed to fetch")); + var headers = {}; + var src = init && init.headers; + if (src && typeof src.forEach === "function") src.forEach(function (v, k) { headers[k] = String(v); }); + else if (src) Object.keys(src).forEach(function (k) { headers[k] = String(src[k]); }); + return network(location.origin + "/api/read", { + method: "POST", + headers: { "Content-Type": "application/json", "Accept": "application/json" }, + cache: "no-store", + body: JSON.stringify({ + url: url, + method: (init && init.method) || "GET", + headers: headers, + body: init && init.body != null ? String(init.body) : "" + }) + }).then(function (res) { + return res.json().then(function (j) { + if (!res.ok || !j || typeof j.text !== "string") throw new Error("Failed to fetch"); + var h = new Headers(); + var table = j.headers || {}; + Object.keys(table).forEach(function (k) { try { h.set(k, String(table[k])); } catch (e) {} }); + return new Response(j.text, { status: Number(j.status) || 200, statusText: "", headers: h }); + }); + }); +} + +self.fetch = function (input, init) { + return network(input, init).catch(function () { + return originRead(input, init); + }).then(function (res) { + return res.text().then(function (text) { + var body = text; + try { JSON.parse(text); } catch (e) { body = JSON.stringify({ text: text }); } + var headers = new Headers(res.headers); + headers.delete("content-length"); + return new Response(body, { status: res.status, statusText: res.statusText, headers: headers }); + }); + }); +}; + +self.RBIComponentRPC = { + bindHost: function (host) { self.__RBI_FETCH_HOST__ = host; } +}; + +self.frameFetch = function (msg) { + var host = self.__RBI_FETCH_HOST__; + if (!host || !msg) return Promise.resolve(null); + return new Promise(function (resolve) { + var done = false; + var timer = setTimeout(function () { + if (done) return; + done = true; + resolve(null); + }, 12000); + host.onRequest(null, msg, function (resp) { + if (done) return; + done = true; + clearTimeout(timer); + resolve(resp); + }); + }); +}; diff --git a/iwa/index.html b/iwa/index.html new file mode 100644 index 0000000000000000000000000000000000000000..432c36a7ee6f082a13af11dfb6219190d4fac22c --- /dev/null +++ b/iwa/index.html @@ -0,0 +1,9 @@ + + +Hodge IWA + + + + + + diff --git a/iwa/manifest.webmanifest b/iwa/manifest.webmanifest new file mode 100644 index 0000000000000000000000000000000000000000..e3218b8f19f2e986a1b5c398ac99e1910e7a71f6 --- /dev/null +++ b/iwa/manifest.webmanifest @@ -0,0 +1,7 @@ +{ + "name": "Hodge IWA", + "id": "hodge-agent", + "start_url": "/iwa/index.html", + "isolated": true, + "display": "standalone" +} diff --git a/kernels/attention.wgsl b/kernels/attention.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..e2095b40b3df4a9aa65663c0ebfc268d1ec0c2e4 --- /dev/null +++ b/kernels/attention.wgsl @@ -0,0 +1,84 @@ +// Causal attention for one new token: softmax(q k^T / sqrt(DENOM)) v over the +// cached positions 0..pos, one workgroup per query head. Grouped-query: head +// h reads key/value head h / (H / KVH). + +override H: u32; +override KVH: u32; +override HD: u32; +override CTX: u32; +override DENOM: f32 = 0.0; // query_pre_attn_scalar when the config sets one; 0 means head_dim. + +struct Step { + pos: u32, + row: u32, + p0: u32, + p1: u32, +} + +@group(0) @binding(0) var st: Step; +@group(0) @binding(1) var q: array; // H * HD +@group(0) @binding(2) var kc: array; // CTX * KVH * HD +@group(0) @binding(3) var vc: array; +@group(0) @binding(4) var att: array; // H * CTX scratch +@group(0) @binding(5) var o: array; // H * HD + +var red: array; + +fn reduce(x: f32, tid: u32, is_max: bool) -> f32 { + red[tid] = x; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + if (is_max) { + red[tid] = max(red[tid], red[tid + s]); + } else { + red[tid] += red[tid + s]; + } + } + workgroupBarrier(); + } + let r = red[0]; + workgroupBarrier(); + return r; +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(local_invocation_index) tid: u32) { + let h = wg.x; + let kvh = h / (H / KVH); + let n = st.pos + 1u; + let qb = h * HD; + let ab = h * CTX; + let denom = select(f32(HD), DENOM, DENOM > 0.0); + let scale = inverseSqrt(denom); + + var m = -3.0e38; + for (var t = tid; t < n; t += 256u) { + let kb = (t * KVH + kvh) * HD; + var s = 0.0; + for (var d = 0u; d < HD; d++) { + s += q[qb + d] * kc[kb + d]; + } + s *= scale; + att[ab + t] = s; + m = max(m, s); + } + let mx = reduce(m, tid, true); + + var sum = 0.0; + for (var t = tid; t < n; t += 256u) { + let e = exp(att[ab + t] - mx); + att[ab + t] = e; + sum += e; + } + let total = reduce(sum, tid, false); + storageBarrier(); + + for (var d = tid; d < HD; d += 256u) { + var acc = 0.0; + for (var t = 0u; t < n; t++) { + acc += att[ab + t] * vc[(t * KVH + kvh) * HD + d]; + } + o[qb + d] = acc / total; + } +} diff --git a/kernels/cellsum.wgsl b/kernels/cellsum.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..a76acfb151516ec9ea90f7ece397b10716cdfacf --- /dev/null +++ b/kernels/cellsum.wgsl @@ -0,0 +1,41 @@ +// A vector's cell sums on one axis (hodgemix eval/flow.go's nodes): out[c] = sum of the M channels of +// cell c, listed cell-major in order. MODE 1 sums the FFN hidden act(a) * b instead (the gate's +// activation as norm.wgsl ACT applies it). One thread a cell, a fixed order: deterministic. + +override NCELL: u32; +override M: u32; // channels per cell +override MODE: u32 = 0u; +override ACT: u32 = 0u; // MODE 1: 0 relu^2, 1 silu, 2 gelu tanh + +@group(0) @binding(0) var a: array; +@group(0) @binding(1) var b: array; // MODE 1 only +@group(0) @binding(2) var order: array; // NCELL * M channels, cell-major +@group(0) @binding(3) var out: array; + +fn v(j: u32) -> f32 { + if (MODE == 1u) { + let x = a[j]; + if (ACT == 1u) { + return x / (1.0 + exp(-x)) * b[j]; + } + if (ACT == 2u) { + return 0.5 * x * (1.0 + tanh(0.7978845608028654 * (x + 0.044715 * x * x * x))) * b[j]; + } + let g = max(x, 0.0); + return g * g * b[j]; + } + return a[j]; +} + +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) gid: vec3u) { + let c = gid.x; + if (c >= NCELL) { + return; + } + var s = 0.0; + for (var t = 0u; t < M; t++) { + s += v(order[c * M + t]); + } + out[c] = s; +} diff --git a/kernels/dot4_native.wgsl b/kernels/dot4_native.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..86060925410e8aa7503f39edbf16fdc70acdfd8b --- /dev/null +++ b/kernels/dot4_native.wgsl @@ -0,0 +1,8 @@ +// dot4: the dot product of two packed 4 x int8 vectors, on the hardware +// instruction (WGSL packed_4x8_integer_dot_product). Prepended to the +// kernels that use it when the device has the feature. +requires packed_4x8_integer_dot_product; + +fn dot4(a: u32, b: u32) -> i32 { + return dot4I8Packed(a, b); +} diff --git a/kernels/dot4_soft.wgsl b/kernels/dot4_soft.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..ee73c0100eb0123b9c5d37f9c74a96dd97d86c16 --- /dev/null +++ b/kernels/dot4_soft.wgsl @@ -0,0 +1,11 @@ +// dot4: the dot product of two packed 4 x int8 vectors, in plain integer +// arithmetic, for devices without packed_4x8_integer_dot_product. + +fn dot4(a: u32, b: u32) -> i32 { + var s = 0; + for (var j = 0u; j < 4u; j++) { + let sh = 24u - 8u * j; + s += (bitcast(a << sh) >> 24u) * (bitcast(b << sh) >> 24u); + } + return s; +} diff --git a/kernels/embed.wgsl b/kernels/embed.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..c04d3661338eebf0a76630e3509edaa6632da334 --- /dev/null +++ b/kernels/embed.wgsl @@ -0,0 +1,28 @@ +// The token's embedding row (bf16) into the residual stream x (f32). The +// embedding may be split across buffers; this binding is the chunk holding +// the token, and st.row is the token's row within it. + +override D: u32; +override SCALE: f32 = 1.0; // Gemma multiplies the token by sqrt(hidden). 1 for every other model. + +struct Step { + pos: u32, + row: u32, + p0: u32, + p1: u32, +} + +@group(0) @binding(0) var st: Step; +@group(0) @binding(1) var emb: array; // rows x D bf16, two per word +@group(0) @binding(2) var x: array; + +@compute @workgroup_size(256) +fn main(@builtin(global_invocation_id) gid: vec3u) { + let i = gid.x; + if (i >= D) { + return; + } + let e = st.row * D + i; + let w = emb[e >> 1u]; + x[i] = bitcast(select(w << 16u, w & 0xffff0000u, (e & 1u) == 1u)) * SCALE; +} diff --git a/kernels/encattn.wgsl b/kernels/encattn.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..0ea9cbd8a9ba6c44020f6356fda80529c72a46fa --- /dev/null +++ b/kernels/encattn.wgsl @@ -0,0 +1,86 @@ +// Bidirectional attention for an encoder: every token attends to all T tokens. +// o[t, h] = sum_j softmax_j(SCALE * q[t, h] . k[j, h]) v[j, h]. Workgroup (head, query); +// the T scores sit in workgroup memory, so T is an override (at most about 3500). + +override T: u32; +override HD: u32; +override SCALE: f32 = 1.0; + +@group(0) @binding(0) var q: array; // T x H*HD +@group(0) @binding(1) var k: array; +@group(0) @binding(2) var v: array; +@group(0) @binding(3) var o: array; // T x H*HD + +var sc: array; +var sq: array; +var red: array; + +fn reduce(x: f32, tid: u32, isMax: bool) -> f32 { + red[tid] = x; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + if (isMax) { + red[tid] = max(red[tid], red[tid + s]); + } else { + red[tid] += red[tid + s]; + } + } + workgroupBarrier(); + } + let r = red[0]; + workgroupBarrier(); + return r; +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let h = wg.x; + let H = nwg.x; + let t = wg.z * nwg.y + wg.y; + let stride = H * HD; + let qb = t * stride + h * HD; + for (var i = tid; i < HD; i += 256u) { + sq[i] = q[qb + i]; + } + workgroupBarrier(); + var m = -3.0e38; + for (var j = tid; j < T; j += 256u) { + let kb = j * stride + h * HD; + var s = 0.0; + for (var i = 0u; i < HD; i++) { + s += sq[i] * k[kb + i]; + } + s *= SCALE; + sc[j] = s; + m = max(m, s); + } + let mx = reduce(m, tid, true); + var sum = 0.0; + for (var j = tid; j < T; j += 256u) { + let e = exp(sc[j] - mx); + sc[j] = e; + sum += e; + } + let inv = 1.0 / reduce(sum, tid, false); + // Four groups of lanes split the keys; each lane holds one head dim. + let parts = 256u / HD; + let d = tid % HD; + let part = tid / HD; + var acc = 0.0; + if (part < parts) { + for (var j = part; j < T; j += parts) { + acc += sc[j] * v[j * stride + h * HD + d]; + } + } + red[tid] = acc; + workgroupBarrier(); + if (part == 0u) { + var total = 0.0; + for (var p = 0u; p < parts; p++) { + total += red[p * HD + d]; + } + o[qb + d] = total * inv; + } +} diff --git a/kernels/encconv2d.wgsl b/kernels/encconv2d.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..98032f1ef5811ba4187e331007c505b5835709c3 --- /dev/null +++ b/kernels/encconv2d.wgsl @@ -0,0 +1,58 @@ +// The audio encoder's subsampling convolution (decision E8): a 3 x 3 kernel, stride 2 and +// zero padding 1 on time and frequency, then an RMS norm over the output channels of each +// (time, frequency) cell times its weight, then ReLU. Layout is [time][frequency][channel], +// so a row of the last block flattens as frequency * channels + channel. Workgroup per +// output cell, one thread per output channel. + +override CIN: u32; +override COUT: u32; +override FIN: u32; // input frequencies +override TIN: u32; // input frames +override EPS: f32 = 1e-6; + +@group(0) @binding(0) var x: array; // TIN x FIN x CIN +@group(0) @binding(1) var w: array; // COUT x CIN x 3 x 3 +@group(0) @binding(2) var nw: array; // COUT +@group(0) @binding(3) var o: array; // TOUT x FOUT x COUT + +var red: array; + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let fout = (FIN + 1u) / 2u; + let cell = wg.y * nwg.x + wg.x; + let t = cell / fout; + let f = cell % fout; + var acc = 0.0; + if (tid < COUT) { + for (var dt = 0u; dt < 3u; dt++) { + let ti = i32(2u * t + dt) - 1; + if (ti < 0 || ti >= i32(TIN)) { + continue; + } + for (var df = 0u; df < 3u; df++) { + let fi = i32(2u * f + df) - 1; + if (fi < 0 || fi >= i32(FIN)) { + continue; + } + let xb = (u32(ti) * FIN + u32(fi)) * CIN; + for (var c = 0u; c < CIN; c++) { + acc += x[xb + c] * w[((tid * CIN + c) * 3u + dt) * 3u + df]; + } + } + } + } + red[tid] = acc * acc; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + red[tid] += red[tid + s]; + } + workgroupBarrier(); + } + let inv = inverseSqrt(red[0] / f32(COUT) + EPS); + if (tid < COUT) { + o[cell * COUT + tid] = max(acc * inv * nw[tid], 0.0); + } +} diff --git a/kernels/encdwconv.wgsl b/kernels/encdwconv.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..5c4956bb5c6f8150d98c5b25cc8ab9bcb1d0d035 --- /dev/null +++ b/kernels/encdwconv.wgsl @@ -0,0 +1,31 @@ +// The audio encoder's light convolution (decision E9): GLU over linear_start's two halves, +// g = a[:C] * sigmoid(a[C:]), then a causal depthwise convolution over time, +// y[t, c] = sum_k w[c, k] g[t - (KW - 1) + k, c]. Workgroup per frame. + +override C: u32; +override KW: u32 = 5u; + +@group(0) @binding(0) var a: array; // T x 2C +@group(0) @binding(1) var w: array; // C x KW +@group(0) @binding(2) var y: array; // T x C + +fn glu(t: u32, c: u32) -> f32 { + let g = a[t * 2u * C + C + c]; + return a[t * 2u * C + c] / (1.0 + exp(-g)); +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let t = wg.y * nwg.x + wg.x; + for (var c = tid; c < C; c += 256u) { + var s = 0.0; + for (var k = 0u; k < KW; k++) { + let ti = i32(t) - i32(KW - 1u) + i32(k); + if (ti >= 0) { + s += w[c * KW + k] * glu(u32(ti), c); + } + } + y[t * C + c] = s; + } +} diff --git a/kernels/encmatmul.wgsl b/kernels/encmatmul.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..d02875cf336937086992a62b5d919d02de7d7de9 --- /dev/null +++ b/kernels/encmatmul.wgsl @@ -0,0 +1,68 @@ +// hodgelinear.wgsl over many tokens: token t is workgroup z, so one dispatch runs a weight +// (or one of its limbs, ACCUM) on every token of an encoder. o[t] = (W xq[t]) * xs[t] * ws. +// Packing, digits and CENTER are hodgelinear.wgsl's. Needs dot4 prepended. + +override K: u32; // inputs +override NP: u32; // packed rows = outputs / 4 +override ACCUM: bool = false; // o += result (a limb) instead of o = result +override CENTER: i32 = 1; // the digit that means 0 + +const ROWS = 8u; // packed rows per workgroup +const LANES = 32u; // threads per packed row + +@group(0) @binding(0) var xq: array; // T x K/4 words of int8 +@group(0) @binding(1) var xs: array; // T dequant scales +@group(0) @binding(2) var w: array; // NP x K/4 words +@group(0) @binding(3) var ws: array; // [0]: the weight scale +@group(0) @binding(4) var o: array; // T x 4 NP + +var sx: array; +var red: array, 256>; + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let kw = K / 4u; + let t = wg.z; + for (var k = tid; k < kw; k += 256u) { + sx[k] = xq[t * kw + k]; + } + workgroupBarrier(); + + let row = tid / LANES; + let lane = tid % LANES; + let r = (wg.y * nwg.x + wg.x) * ROWS + row; + var acc = vec4(0); + if (r < NP) { + let base = r * kw; + for (var k = lane; k < kw; k += LANES) { + let ww = w[base + k]; + let a = sx[k]; + let ones = dot4(a, 0x01010101u); + acc += vec4(dot4(a, ww & 0x03030303u), + dot4(a, (ww >> 2u) & 0x03030303u), + dot4(a, (ww >> 4u) & 0x03030303u), + dot4(a, (ww >> 6u) & 0x03030303u)) - vec4(ones * CENTER); + } + } + red[tid] = acc; + workgroupBarrier(); + for (var s = LANES / 2u; s > 0u; s >>= 1u) { + if (lane < s) { + red[tid] += red[tid + s]; + } + workgroupBarrier(); + } + if (lane == 0u && r < NP) { + let v = vec4(red[tid]) * (xs[t] * ws[0]); + let ob = t * 4u * NP; + for (var i = 0u; i < 4u; i++) { + let idx = ob + i * NP + r; + if (ACCUM) { + o[idx] = o[idx] + v[i]; + } else { + o[idx] = v[i]; + } + } + } +} diff --git a/kernels/encpool.wgsl b/kernels/encpool.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..19c0b5c986827e41ff224490aa61c9c898f28788 --- /dev/null +++ b/kernels/encpool.wgsl @@ -0,0 +1,28 @@ +// A vision encoder's pooling: token p of the pooled grid is the mean of a POOL x POOL block of +// the COLS-wide patch grid. One workgroup per pooled token. + +override D: u32; +override COLS: u32; +override POOL: u32 = 3u; + +@group(0) @binding(0) var x: array; // T x D +@group(0) @binding(1) var o: array; // P x D + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let p = wg.y * nwg.x + wg.x; + let pc = COLS / POOL; + let r0 = (p / pc) * POOL; + let c0 = (p % pc) * POOL; + let inv = 1.0 / f32(POOL * POOL); + for (var i = tid; i < D; i += 256u) { + var s = 0.0; + for (var dy = 0u; dy < POOL; dy++) { + for (var dx = 0u; dx < POOL; dx++) { + s += x[((r0 + dy) * COLS + c0 + dx) * D + i]; + } + } + o[p * D + i] = s * inv; + } +} diff --git a/kernels/encpos.wgsl b/kernels/encpos.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..10ba4a6af882dc1956a431816146c048e3328834 --- /dev/null +++ b/kernels/encpos.wgsl @@ -0,0 +1,20 @@ +// A vision encoder's learned position: x[t] += table[0][col] + table[1][row] for patch t at +// (t / COLS, t % COLS). The table is [2, ROWS_MAX, D] f32. One workgroup per token. + +override D: u32; +override COLS: u32; +override PLANE: u32; // rows of one table plane + +@group(0) @binding(0) var tab: array; // 2 x PLANE x D +@group(0) @binding(1) var x: array; // T x D + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let t = wg.y * nwg.x + wg.x; + let col = t % COLS; + let row = t / COLS; + for (var i = tid; i < D; i += 256u) { + x[t * D + i] = x[t * D + i] + tab[col * D + i] + tab[(PLANE + row) * D + i]; + } +} diff --git a/kernels/encpost.wgsl b/kernels/encpost.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..baf0b59ab368c5a100cae8c3e8b9ec52a11e7e15 --- /dev/null +++ b/kernels/encpost.wgsl @@ -0,0 +1,88 @@ +// An encoder linear's output, per token: y = clamp(y, cl[2], cl[3]) (CLIP), + bias (BIAS); then +// OUT 0: d = y +// OUT 1: d += F * y (a residual add) +// OUT 2: d += F * rmsnorm(y) * gain (a post-norm residual, NORM 1 w, 2 (1 + w)) +// OUT 3: d = y * TARGET / rms(y) (rms matched: the bridge onto the residual axis) +// OUT 4: d = rmsnorm(y) * gain (a norm into another buffer) +// One workgroup per token. + +override N: u32; +override EPS: f32 = 1e-6; +override CLIP: bool = false; +override BIAS: bool = false; +override OUT: u32 = 0u; +override NORM: u32 = 1u; +override F: f32 = 1.0; +override TARGET: f32 = 1.0; + +@group(0) @binding(0) var y: array; // T x N +@group(0) @binding(1) var cl: array; // [in lo, in hi, out lo, out hi] +@group(0) @binding(2) var bias: array; // N +@group(0) @binding(3) var nw: array; // N +@group(0) @binding(4) var d: array; // T x N + +var red: array; + +fn val(t: u32, i: u32) -> f32 { + var x = y[t * N + i]; + if (CLIP) { + x = clamp(x, cl[2], cl[3]); + } + if (BIAS) { + x += bias[i]; + } + return x; +} + +fn sum256(x: f32, tid: u32) -> f32 { + red[tid] = x; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + red[tid] += red[tid + s]; + } + workgroupBarrier(); + } + let r = red[0]; + workgroupBarrier(); + return r; +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let t = wg.y * nwg.x + wg.x; + var sc = 1.0; + if (OUT >= 2u) { + var ss = 0.0; + for (var i = tid; i < N; i += 256u) { + let x = val(t, i); + ss += x * x; + } + let ms = sum256(ss, tid) / f32(N); + if (OUT == 2u || OUT == 4u) { + sc = inverseSqrt(ms + EPS); + } else { + sc = TARGET * inverseSqrt(max(ms, 1e-30)); + } + } + for (var i = tid; i < N; i += 256u) { + let x = val(t, i) * sc; + let at = t * N + i; + if (OUT == 0u || OUT == 3u) { + d[at] = x; + } else if (OUT == 1u) { + d[at] = d[at] + F * x; + } else { + var g = nw[i]; + if (NORM == 2u) { + g = 1.0 + g; + } + if (OUT == 4u) { + d[at] = x * g; + } else { + d[at] = d[at] + F * x * g; + } + } + } +} diff --git a/kernels/encprep.wgsl b/kernels/encprep.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..0d4c04913ad9ee593f657082bf0e8b882d79e9fd --- /dev/null +++ b/kernels/encprep.wgsl @@ -0,0 +1,114 @@ +// An encoder linear's input, per token: v = a (MODE 0), act(a) * b (MODE 1, the gated MLP), +// a - b (MODE 2, b a per-channel mean) or act(a) (MODE 3); then an RMS norm (NORM 0 none, +// 1 times the weight, 2 times (1 + weight), 3 unit); then silu (POST 1); then the clipped +// linear's input clamp to [cl[0], cl[1]] (CLIP); then per-token absmax int8 for +// encmatmul.wgsl. One workgroup per token; token t is a row of a, b and the outputs. + +override K: u32; +override EPS: f32 = 1e-6; +override MODE: u32 = 0u; +override ACT: u32 = 2u; // MODE 1: 1 silu, 2 gelu tanh +override NORM: u32 = 0u; +override CLIP: bool = false; +override POST: u32 = 0u; + +@group(0) @binding(0) var a: array; // T x K +@group(0) @binding(1) var b: array; // MODE 1: T x K; MODE 2: K +@group(0) @binding(2) var nw: array; // the norm's weight, K +@group(0) @binding(3) var cl: array; // [in lo, in hi, out lo, out hi] +@group(0) @binding(4) var xq: array; // T x K/4 words of int8 +@group(0) @binding(5) var xs: array; // T dequant scales + +var red: array; + +fn act(x: f32) -> f32 { + if (ACT == 1u) { + return x / (1.0 + exp(-x)); + } + return 0.5 * x * (1.0 + tanh(0.7978845608028654 * (x + 0.044715 * x * x * x))); +} + +fn v(t: u32, i: u32) -> f32 { + let x = a[t * K + i]; + if (MODE == 1u) { + return act(x) * b[t * K + i]; + } + if (MODE == 3u) { + return act(x); + } + if (MODE == 2u) { + return x - b[i]; + } + return x; +} + +fn reduce(x: f32, tid: u32, isMax: bool) -> f32 { + red[tid] = x; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + if (isMax) { + red[tid] = max(red[tid], red[tid + s]); + } else { + red[tid] += red[tid + s]; + } + } + workgroupBarrier(); + } + let r = red[0]; + workgroupBarrier(); + return r; +} + +fn gain(i: u32) -> f32 { + if (NORM == 1u) { + return nw[i]; + } + if (NORM == 2u) { + return 1.0 + nw[i]; + } + return 1.0; +} + +fn clip(x0: f32) -> f32 { + var x = x0; + if (POST == 1u) { + x = x / (1.0 + exp(-x)); + } + if (CLIP) { + return clamp(x, cl[0], cl[1]); + } + return x; +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let t = wg.y * nwg.x + wg.x; + var inv = 1.0; + if (NORM != 0u) { + var ss = 0.0; + for (var i = tid; i < K; i += 256u) { + let x = v(t, i); + ss += x * x; + } + inv = inverseSqrt(reduce(ss, tid, false) / f32(K) + EPS); + } + var m = 0.0; + for (var i = tid; i < K; i += 256u) { + m = max(m, abs(clip(v(t, i) * inv * gain(i)))); + } + let s = 127.0 / max(reduce(m, tid, true), 1e-5); + for (var g = tid; g < K / 4u; g += 256u) { + var word = 0u; + for (var j = 0u; j < 4u; j++) { + let i = g * 4u + j; + let q = i32(clamp(round(clip(v(t, i) * inv * gain(i)) * s), -128.0, 127.0)); + word |= (bitcast(q) & 0xffu) << (8u * j); + } + xq[t * (K / 4u) + g] = word; + } + if (tid == 0u) { + xs[t] = 1.0 / s; + } +} diff --git a/kernels/encqk.wgsl b/kernels/encqk.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..4a191a8e25ef4ef64b0bc7cce1aa0507e37ad158 --- /dev/null +++ b/kernels/encqk.wgsl @@ -0,0 +1,86 @@ +// An encoder's queries and keys in place, per token and head: RMS norm with the head norm's +// weight (q_norm, k_norm), then 2-D rotary position. The first half of the head turns with the +// patch column, the second with its row; within a half, dim j pairs with j + HD/4 (rotate-half) +// at frequency THETA^(-2j / (HD/2)). Token t is patch (t / COLS, t % COLS). +// Workgroup (head, token). + +override HD: u32; +override COLS: u32; +override THETA: f32 = 100.0; +override EPS: f32 = 1e-6; + +@group(0) @binding(0) var q: array; // T x H*HD +@group(0) @binding(1) var k: array; // T x H*HD +@group(0) @binding(2) var qn: array; // HD +@group(0) @binding(3) var kn: array; // HD + +var hv: array; +var red: array; + +fn turn(which: u32, base: u32, pos: vec2, tid: u32) { + // RMS norm of this head. + var ss = 0.0; + for (var i = tid; i < HD; i += 64u) { + var x = 0.0; + if (which == 0u) { + x = q[base + i]; + } else { + x = k[base + i]; + } + hv[i] = x; + ss += x * x; + } + red[tid] = ss; + workgroupBarrier(); + for (var s = 32u; s > 0u; s >>= 1u) { + if (tid < s) { + red[tid] += red[tid + s]; + } + workgroupBarrier(); + } + let inv = inverseSqrt(red[0] / f32(HD) + EPS); + workgroupBarrier(); + for (var i = tid; i < HD; i += 64u) { + var g = 0.0; + if (which == 0u) { + g = qn[i]; + } else { + g = kn[i]; + } + hv[i] = hv[i] * inv * g; + } + workgroupBarrier(); + let half = HD / 2u; + let quarter = HD / 4u; + for (var i = tid; i < half; i += 64u) { + let side = i / quarter; // 0 column, 1 row + let j = i % quarter; + let at = side * half + j; + let ang = pos[side] * pow(THETA, -2.0 * f32(j) / f32(half)); + let c = cos(ang); + let s = sin(ang); + let x1 = hv[at]; + let x2 = hv[at + quarter]; + let r1 = x1 * c - x2 * s; + let r2 = x2 * c + x1 * s; + if (which == 0u) { + q[base + at] = r1; + q[base + at + quarter] = r2; + } else { + k[base + at] = r1; + k[base + at + quarter] = r2; + } + } + workgroupBarrier(); +} + +@compute @workgroup_size(64) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let h = wg.x; + let t = wg.z * nwg.y + wg.y; + let base = (t * nwg.x + h) * HD; + let pos = vec2(f32(t % COLS), f32(t / COLS)); + turn(0u, base, pos, tid); + turn(1u, base, pos, tid); +} diff --git a/kernels/encrelattn.wgsl b/kernels/encrelattn.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..b8f14f9a2f944613d1a6d8d86725efe9f8d032e5 --- /dev/null +++ b/kernels/encrelattn.wgsl @@ -0,0 +1,83 @@ +// The audio encoder's local attention (decision E9). Frame t attends to frames t - PAST .. t. +// The query is scaled per dim by HD^-1/2 / softplus(0) * softplus(per_dim_scale); a key at +// distance d scores q.k + q.rel[PAST - d], capped as CAP * tanh(score / CAP), then softmax. +// Workgroup (head, frame), one thread per head dim. + +override HD: u32; +override PAST: u32 = 12u; +override CAP: f32 = 50.0; + +@group(0) @binding(0) var q: array; // T x H*HD +@group(0) @binding(1) var k: array; +@group(0) @binding(2) var v: array; +@group(0) @binding(3) var rel: array; // (PAST + 1) x H*HD +@group(0) @binding(4) var pds: array; // HD, per_dim_scale +@group(0) @binding(5) var o: array; // T x H*HD + +var red: array; +var sc: array; + +fn sum(x: f32, tid: u32) -> f32 { + red[tid] = x; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + red[tid] += red[tid + s]; + } + workgroupBarrier(); + } + let r = red[0]; + workgroupBarrier(); + return r; +} + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let h = wg.x; + let H = nwg.x; + let t = wg.z * nwg.y + wg.y; + let stride = H * HD; + let on = tid < HD; + var qd = 0.0; + if (on) { + let sp = log(1.0 + exp(pds[tid])); + qd = q[t * stride + h * HD + tid] * inverseSqrt(f32(HD)) / log(2.0) * sp; + } + let first = i32(t) - i32(PAST); + var mx = -3.0e38; + for (var j = 0u; j <= PAST; j++) { + let kt = first + i32(j); + var s = 0.0; + if (kt >= 0) { + var part = 0.0; + if (on) { + let d = t - u32(kt); + part = qd * (k[u32(kt) * stride + h * HD + tid] + rel[(PAST - d) * stride + h * HD + tid]); + } + s = sum(part, tid); + s = CAP * tanh(s / CAP); + mx = max(mx, s); + } + if (tid == 0u) { + sc[j] = s; + } + } + workgroupBarrier(); + var total = 0.0; + var acc = 0.0; + for (var j = 0u; j <= PAST; j++) { + let kt = first + i32(j); + if (kt < 0) { + continue; + } + let e = exp(sc[j] - mx); + total += e; + if (on) { + acc += e * v[u32(kt) * stride + h * HD + tid]; + } + } + if (on) { + o[t * stride + h * HD + tid] = acc / total; + } +} diff --git a/kernels/encrelpos.wgsl b/kernels/encrelpos.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..586582a72cd12c98f09072963de950f47446a69a --- /dev/null +++ b/kernels/encrelpos.wgsl @@ -0,0 +1,21 @@ +// The audio encoder's relative positions: row r is distance PAST - r (PAST, PAST-1, ..., 0) as a +// sinusoidal signal of C channels, sin then cos over C/2 timescales from 1 to 1e4 (decision E9). +// relative_k_proj maps the rows to per-head keys. Workgroup per row. + +override C: u32; +override PAST: u32; + +@group(0) @binding(0) var o: array; // (PAST + 1) x C + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(local_invocation_index) tid: u32) { + let r = wg.x; + let p = f32(PAST - r); + let half = C / 2u; + let inc = log(1.0e4) / f32(max(half - 1u, 1u)); + for (var k = tid; k < half; k += 256u) { + let a = p * exp(-f32(k) * inc); + o[r * C + k] = sin(a); + o[r * C + half + k] = cos(a); + } +} diff --git a/kernels/flow.wgsl b/kernels/flow.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..1057596fb533b496a0eb8b732f5b0444e1957dab --- /dev/null +++ b/kernels/flow.wgsl @@ -0,0 +1,71 @@ +// Flow capture: one HodgeLinear limb's currents on the model's cells (hodgemix eval/flow.go on the +// device). The weight is read exactly as hodgelinear.wgsl reads it (packed rows, 4 inputs a word, the +// 2-bit codes of rows r, r + NP, r + 2NP, r + 3NP in bits 0-1 .. 6-7 of each byte), and every product +// a_j (code - CENTER) is added, exact in i32, into its (output row cell, input cell) sum: colCell[j] is +// input channel j's cell, rowCell[i] output row i's. A workgroup sums its 32 rows in workgroup memory, +// then adds each nonzero (row cell, input cell) partial into acc. flowscale.wgsl turns acc into +// currents (x act_scale x weight_scale) and clears it. + +override K: u32; // inputs +override NP: u32; // packed rows = outputs / 4 +override NC: u32; // input cells +override CENTER: i32 = 1; // the digit that means 0 + +const ROWS = 8u; // packed rows per workgroup +const LANES = 32u; // threads per packed row + +@group(0) @binding(0) var xq: array; // K/4 words of int8 +@group(0) @binding(1) var w: array; // NP x K/4 words +@group(0) @binding(2) var colCell: array; // K +@group(0) @binding(3) var rowCell: array; // 4 * NP +@group(0) @binding(4) var acc: array>; // output cells x NC + +var sh: array, 4u * ROWS * NC>; + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + for (var i = tid; i < 4u * ROWS * NC; i += 256u) { + atomicStore(&sh[i], 0); + } + workgroupBarrier(); + + let kw = K / 4u; + let row = tid / LANES; + let lane = tid % LANES; + let base = (wg.y * nwg.x + wg.x) * ROWS; + let r = base + row; + if (r < NP) { + for (var k = lane; k < kw; k += LANES) { + let ww = w[r * kw + k]; + let a = xq[k]; + for (var t = 0u; t < 4u; t++) { + let av = (bitcast(a << (24u - 8u * t))) >> 24u; // int8 input 4k + t + if (av == 0) { + continue; + } + let c = colCell[4u * k + t]; + let codes = ww >> (8u * t); + for (var i = 0u; i < 4u; i++) { + let d = i32((codes >> (2u * i)) & 3u) - CENTER; + if (d != 0) { + atomicAdd(&sh[(row * 4u + i) * NC + c], av * d); + } + } + } + } + } + workgroupBarrier(); + + for (var idx = tid; idx < 4u * ROWS * NC; idx += 256u) { + let lr = idx / NC; + let pr = base + lr / 4u; // packed row + if (pr < NP) { + let v = atomicLoad(&sh[idx]); + if (v != 0) { + let out = (lr % 4u) * NP + pr; // output row + atomicAdd(&acc[rowCell[out] * NC + idx % NC], v); + } + } + } +} diff --git a/kernels/flowscale.wgsl b/kernels/flowscale.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..53b075985aee7907450d8d255fc8c1b0b387dc70 --- /dev/null +++ b/kernels/flowscale.wgsl @@ -0,0 +1,24 @@ +// flow.wgsl's integer currents into a HodgeLinear limb's real ones: flow[i] (+)= acc[i] * act_scale * +// weight_scale, and acc is cleared for the next capture. ACCUM adds a further limb onto limb 0's. + +override N: u32; // output cells x input cells +override ACCUM: bool = false; + +@group(0) @binding(0) var acc: array>; +@group(0) @binding(1) var xs: array; // [0]: the activations' dequant scale +@group(0) @binding(2) var ws: array; // [0]: the limb's weight scale +@group(0) @binding(3) var flow: array; + +@compute @workgroup_size(256) +fn main(@builtin(global_invocation_id) gid: vec3u, @builtin(num_workgroups) nwg: vec3u) { + let i = gid.y * nwg.x * 256u + gid.x; + if (i >= N) { + return; + } + let v = f32(atomicExchange(&acc[i], 0)) * (xs[0] * ws[0]); + if (ACCUM) { + flow[i] = flow[i] + v; + } else { + flow[i] = v; + } +} diff --git a/kernels/hodgelinear.wgsl b/kernels/hodgelinear.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..a9b4fa6e75d585591c45c0e41a70ab5361857447 --- /dev/null +++ b/kernels/hodgelinear.wgsl @@ -0,0 +1,77 @@ +// HodgeLinear, ternary weights and int8 activations: out = (W x_q) * act_scale * weight_scale, with W +// ternary and x_q int8 (norm.wgsl made it). +// +// W is read as hodgemix packs it (uint8 +// [N/4, K]): byte k of packed row r holds the 2-bit codes (weight + 1) of +// output rows r, r + N/4, r + 2N/4, r + 3N/4 at input k, in bits 0-1, 2-3, +// 4-5, 6-7. A u32 of W is 4 consecutive inputs for those 4 rows, so +// (w >> 2i) & 0x03030303 is 4 codes in {0, 1, 2} as unsigned bytes, and +// sum a * (code - 1) = dot4(a, codes) - dot4(a, 0x01010101). +// Needs dot4 (dot4_native.wgsl or dot4_soft.wgsl) prepended. +// +// The same kernel runs a weight's further digit limbs (hodgemix limbs.go): the 2-bit codes are +// digits of radix r in {2, 3, 4} meaning (code - CENTER), CENTER = (r - 1) / 2, with their own scale, +// dispatched with ACCUM so the limbs sum. The ternary limb 0 is CENTER = 1. + +override K: u32; // inputs +override NP: u32; // packed rows = outputs / 4 +override ACCUM: bool = false; // out += result (a residual add) instead of out = result +override CENTER: i32 = 1; // the digit that means 0 + +const ROWS = 8u; // packed rows per workgroup +const LANES = 32u; // threads per packed row + +@group(0) @binding(0) var xq: array; // K/4 words of int8 +@group(0) @binding(1) var xs: array; // [0]: the activations' dequant scale +@group(0) @binding(2) var w: array; // NP x K/4 words +@group(0) @binding(3) var ws: array; // [0]: the weight scale +@group(0) @binding(4) var o: array; // 4 * NP outputs + +var sx: array; +var red: array, 256>; + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + let kw = K / 4u; + for (var k = tid; k < kw; k += 256u) { + sx[k] = xq[k]; + } + workgroupBarrier(); + + let row = tid / LANES; + let lane = tid % LANES; + let r = (wg.y * nwg.x + wg.x) * ROWS + row; + var acc = vec4(0); + if (r < NP) { + let base = r * kw; + for (var k = lane; k < kw; k += LANES) { + let ww = w[base + k]; + let a = sx[k]; + let ones = dot4(a, 0x01010101u); + acc += vec4(dot4(a, ww & 0x03030303u), + dot4(a, (ww >> 2u) & 0x03030303u), + dot4(a, (ww >> 4u) & 0x03030303u), + dot4(a, (ww >> 6u) & 0x03030303u)) - vec4(ones * CENTER); + } + } + red[tid] = acc; + workgroupBarrier(); + for (var s = LANES / 2u; s > 0u; s >>= 1u) { + if (lane < s) { + red[tid] += red[tid + s]; + } + workgroupBarrier(); + } + if (lane == 0u && r < NP) { + let v = vec4(red[tid]) * (xs[0] * ws[0]); + for (var i = 0u; i < 4u; i++) { + let idx = i * NP + r; + if (ACCUM) { + o[idx] = o[idx] + v[i]; + } else { + o[idx] = v[i]; + } + } + } +} diff --git a/kernels/lmhead.wgsl b/kernels/lmhead.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..08eaa3b7ac9ca428f176c1929748322c26bf4db7 --- /dev/null +++ b/kernels/lmhead.wgsl @@ -0,0 +1,45 @@ +// The output projection: logits = y E^T over the rows of one embedding +// chunk (tied weights: the embedding is the LM head), bf16 E, f32 y. + +override D: u32; // hidden size (even) +override ROWS: u32; // rows in this chunk + +const PER = 8u; // rows per workgroup +const LANES = 32u; + +@group(0) @binding(0) var y: array; +@group(0) @binding(1) var emb: array; // ROWS x D bf16 +@group(0) @binding(2) var logits: array; // this chunk's ROWS + +var sy: array; +var red: array; + +@compute @workgroup_size(256) +fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, + @builtin(local_invocation_index) tid: u32) { + for (var i = tid; i < D; i += 256u) { + sy[i] = y[i]; + } + workgroupBarrier(); + let lane = tid % LANES; + let r = (wg.y * nwg.x + wg.x) * PER + tid / LANES; + var acc = 0.0; + if (r < ROWS) { + let base = r * (D / 2u); + for (var k = lane; k < D / 2u; k += LANES) { + let w = emb[base + k]; + acc += sy[2u * k] * bitcast(w << 16u) + sy[2u * k + 1u] * bitcast(w & 0xffff0000u); + } + } + red[tid] = acc; + workgroupBarrier(); + for (var s = LANES / 2u; s > 0u; s >>= 1u) { + if (lane < s) { + red[tid] += red[tid + s]; + } + workgroupBarrier(); + } + if (lane == 0u && r < ROWS) { + logits[r] = red[tid]; + } +} diff --git a/kernels/norm.wgsl b/kernels/norm.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..d2a652149e1ad513bce2c9dfdc9574935f5161e8 --- /dev/null +++ b/kernels/norm.wgsl @@ -0,0 +1,126 @@ +// RMSNorm, then (for a HodgeLinear's input) per-token absmax int8 quantization. +// +// MODE 0: v = a -> rmsnorm -> int8 (xq, xs) +// MODE 1: v = act(a) * b -> rmsnorm -> int8 (the gated FFN: +// act(gate) * up, then ffn_sub_norm, then down_proj's quant; +// ACT 0 relu^2 (Hodge), 1 silu (Llama, Qwen), 2 gelu tanh) +// MODE 2: v = a -> rmsnorm -> f32 y (the final norm) +// +// rmsnorm(v) = v / sqrt(mean(v^2) + EPS) * gain. gain is the weight, or (1+weight) +// when GEMMA is 1 (Gemma, VaultGemma). Quantization is +// per-token absmax: s = 127 / max|y|, q = clamp(round(y s), -128, 127), and the +// dequant scale 1 / s goes to xs[0]. One workgroup per vector. + +override K: u32; +override EPS: f32 = 1e-5; +override MODE: u32 = 0u; +override ACT: u32 = 0u; +override GEMMA: u32 = 0u; // 0: y * w (Llama, Qwen, Hodge). 1: y * (1+w) (Gemma, VaultGemma). + +@group(0) @binding(0) var a: array; +@group(0) @binding(1) var b: array; // MODE 1 only +@group(0) @binding(2) var nw: array; // the norm's weight +@group(0) @binding(3) var xq: array; // K/4 words of int8 +@group(0) @binding(4) var xs: array; +@group(0) @binding(5) var y: array; // MODE 2 only + +var red: array; + +fn v(i: u32) -> f32 { + if (MODE == 1u) { + let x = a[i]; + if (ACT == 1u) { + return x / (1.0 + exp(-x)) * b[i]; + } + if (ACT == 2u) { + return 0.5 * x * (1.0 + tanh(0.7978845608028654 * (x + 0.044715 * x * x * x))) * b[i]; + } + let g = max(x, 0.0); + return g * g * b[i]; + } + return a[i]; +} + +fn sum256(x: f32, tid: u32) -> f32 { + red[tid] = x; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + red[tid] += red[tid + s]; + } + workgroupBarrier(); + } + let r = red[0]; + workgroupBarrier(); + return r; +} + +// gain is the per-channel multiplier. An all-ones weight is a sub-norm the layout +// inserted: that path is the identity (multiply by 1), including when GEMMA is on, +// where a stored 1 would otherwise become 2. +fn gain(i: u32, unit: bool) -> f32 { + if (unit && MODE != 2u) { + return 1.0; + } + if (GEMMA == 1u) { + return 1.0 + nw[i]; + } + return nw[i]; +} + +fn max256(x: f32, tid: u32) -> f32 { + red[tid] = x; + workgroupBarrier(); + for (var s = 128u; s > 0u; s >>= 1u) { + if (tid < s) { + red[tid] = max(red[tid], red[tid + s]); + } + workgroupBarrier(); + } + let r = red[0]; + workgroupBarrier(); + return r; +} + +@compute @workgroup_size(256) +fn main(@builtin(local_invocation_index) tid: u32) { + var ss = 0.0; + var ones = 0.0; + for (var i = tid; i < K; i += 256u) { + let x = v(i); + ss += x * x; + if (nw[i] == 1.0) { + ones += 1.0; + } + } + let invRms = inverseSqrt(sum256(ss, tid) / f32(K) + EPS); + // A gain of all ones is a sub-norm the layout inserted. Skip the rms and keep the + // per-channel multiply (ones) so the following quant sees the sublayer output. + let unit = sum256(ones, tid) == f32(K); + let inv = select(invRms, 1.0, unit && MODE != 2u); + + if (MODE == 2u) { + for (var i = tid; i < K; i += 256u) { + y[i] = v(i) * inv * gain(i, unit); + } + return; + } + + var m = 0.0; + for (var i = tid; i < K; i += 256u) { + m = max(m, abs(v(i) * inv * gain(i, unit))); + } + let s = 127.0 / max(max256(m, tid), 1e-5); + for (var g = tid; g < K / 4u; g += 256u) { + var word = 0u; + for (var j = 0u; j < 4u; j++) { + let i = g * 4u + j; + let q = i32(clamp(round(v(i) * inv * gain(i, unit) * s), -128.0, 127.0)); + word |= (bitcast(q) & 0xffu) << (8u * j); + } + xq[g] = word; + } + if (tid == 0u) { + xs[0] = 1.0 / s; + } +} diff --git a/kernels/rope.wgsl b/kernels/rope.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..1496d2f9ee524c97b5ce06020a6a84d3e056427d --- /dev/null +++ b/kernels/rope.wgsl @@ -0,0 +1,101 @@ +// Rotary position embedding (rotate-half pairing: d with d + HD/2) on q in +// place and on k, then k and v into this layer's cache at position pos. + +override H: u32; // query heads +override KVH: u32; // key/value heads +override HD: u32; // head dim +override THETA: f32; // rope_theta +// rope_scaling: SCALING 0 none, 1 linear (every frequency / FACTOR), 2 llama3 (wavelengths over +// ORIG / LOW_FF divided by FACTOR, under ORIG / HIGH_FF kept, the band between blended). +override SCALING: u32 = 0u; +override FACTOR: f32 = 1.0; +override LOW_FF: f32 = 1.0; +override HIGH_FF: f32 = 4.0; +override ORIG: f32 = 8192.0; // original_max_position_embeddings + +struct Step { + pos: u32, + row: u32, + p0: u32, + p1: u32, +} + +@group(0) @binding(0) var st: Step; +@group(0) @binding(1) var q: array; // H * HD +@group(0) @binding(2) var k: array; // KVH * HD +@group(0) @binding(3) var vv: array; // KVH * HD +@group(0) @binding(4) var kc: array; // ctx * KVH * HD +@group(0) @binding(5) var vc: array; + +// A zero override is the shader default. Tint folds override divisions even in a +// branch this pipeline never takes, and 0.0 / 0.0 is not an f32. +fn nz(x: f32, fallback: f32) -> f32 { + if (x == 0.0) { + return fallback; + } + return x; +} + +fn freq(d: u32) -> f32 { + let f = pow(THETA, -2.0 * f32(d) / f32(HD)); + let factor = nz(FACTOR, 1.0); + let low = nz(LOW_FF, 1.0); + let high = nz(HIGH_FF, 4.0); + let orig = nz(ORIG, 8192.0); + if (SCALING == 1u) { + return f / factor; + } + if (SCALING == 2u) { + let wl = 6.283185307179586 / f; + if (wl > orig / low) { + return f / factor; + } + if (wl >= orig / high) { + let span0 = high - low; + let span = select(span0, 1.0, span0 == 0.0); + let sm = (orig / wl - low) / span; + return (1.0 - sm) * f / factor + sm * f; + } + } + return f; +} + +// st.p0 is a tower token's phase (f32 bits, 0 for text): it turns pairs 56..63, as +// hodgemix eval.rope does. +fn rot(x1: f32, x2: f32, d: u32) -> vec2 { + let inv = freq(d); + var ang = f32(st.pos) * inv; + if (d >= 56u && d < 64u) { + ang += bitcast(st.p0); + } + let c = cos(ang); + let s = sin(ang); + return vec2(x1 * c - x2 * s, x2 * c + x1 * s); +} + +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) gid: vec3u) { + let half = HD / 2u; + let idx = gid.x; + let nq = H * half; + if (idx < nq) { + let base = (idx / half) * HD; + let d = idx % half; + let r = rot(q[base + d], q[base + d + half], d); + q[base + d] = r.x; + q[base + d + half] = r.y; + return; + } + let j = idx - nq; + if (j >= KVH * half) { + return; + } + let base = (j / half) * HD; + let d = j % half; + let r = rot(k[base + d], k[base + d + half], d); + let at = st.pos * KVH * HD + base; + kc[at + d] = r.x; + kc[at + d + half] = r.y; + vc[at + d] = vv[base + d]; + vc[at + d + half] = vv[base + d + half]; +} diff --git a/kernels/wedge.wgsl b/kernels/wedge.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..4d3a49b56c19bd775b87e818cc64f14d23f08450 --- /dev/null +++ b/kernels/wedge.wgsl @@ -0,0 +1,38 @@ +// One residual face. The wedge is the sum over cells of (sum of the carry) times (sum of the write). +// flag[0] is 1 when that area is positive. The write is added either way: dropping it when the +// cell sums cancel removes the attention or the feed-forward and the reply comes apart. +// One thread, so the sum is the same order as the reference forward. +// No paper equation. + +override DIM: u32; +override NCELL: u32; +override M: u32; + +@group(0) @binding(0) var x: array; +@group(0) @binding(1) var w: array; +@group(0) @binding(2) var order: array; +@group(0) @binding(3) var flag: array; + +@compute @workgroup_size(1) +fn main() { + var area = 0.0; + for (var c = 0u; c < NCELL; c++) { + var cs = 0.0; + var ws = 0.0; + let base = c * M; + for (var t = 0u; t < M; t++) { + let j = order[base + t]; + cs += x[j]; + ws += w[j]; + } + area += cs * ws; + } + if (area > 0.0) { + flag[0] = 1u; + } else { + flag[0] = 0u; + } + for (var i = 0u; i < DIM; i++) { + x[i] += w[i]; + } +} diff --git a/kernels/wedgezero.wgsl b/kernels/wedgezero.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..16b4916c072e1ea1f84387731ce97f8073ce632a --- /dev/null +++ b/kernels/wedgezero.wgsl @@ -0,0 +1,15 @@ +// A refused write leaves no current on its edges. flag[0] is 1 when the wedge kept the write. +// No paper equation. + +override N: u32; + +@group(0) @binding(0) var flag: array; +@group(0) @binding(1) var e: array; + +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) gid: vec3u) { + if (flag[0] != 0u || gid.x >= N) { + return; + } + e[gid.x] = 0.0; +} diff --git a/loader.js b/loader.js new file mode 100644 index 0000000000000000000000000000000000000000..8946919a192d9bbf3827c7006d54bf14abfe463a --- /dev/null +++ b/loader.js @@ -0,0 +1,1096 @@ +// Browser hop: load/instantiate/run/call compiled .wasm. +// Host imports match ~/WASMLoader loader/host.go (wasi_snapshot_preview1, +// env.log, env.abort, optional packed string imports). The guest Calls +// this; it does not rewrite ~/WASMWin32. + +export const ERRNO = { + SUCCESS: 0, + BADF: 8, + INVAL: 28, + NOSYS: 52, +}; + +class ExitError extends Error { + constructor(code) { + super("proc_exit " + code); + this.code = code | 0; + this.name = "ExitError"; + } +} + +// Line-oriented stdin from the page (xterm.js). SharedArrayBuffer: +// Int32[0] notify word (0 empty, 1 data) +// Int32[1] byte length +// bytes at offset 16 +function stdinFromSab(sab) { + const i32 = new Int32Array(sab); + const u8 = new Uint8Array(sab); + return { + take(dst) { + while (Atomics.load(i32, 1) === 0) { + const w = Atomics.wait(i32, 0, 0); + if (w === "timed-out") continue; + } + const n = Atomics.load(i32, 1); + const take = Math.min(n, dst.length); + dst.set(u8.subarray(16, 16 + take)); + const left = n - take; + if (left > 0) { + u8.copyWithin(16, 16 + take, 16 + n); + Atomics.store(i32, 1, left); + } else { + Atomics.store(i32, 1, 0); + Atomics.store(i32, 0, 0); + } + return take; + }, + }; +} + +function u32(mem, ptr, v) { + new DataView(mem.buffer).setUint32(ptr, v >>> 0, true); +} + +function u64(mem, ptr, v) { + const dv = new DataView(mem.buffer); + dv.setUint32(ptr, v >>> 0, true); + dv.setUint32(ptr + 4, Math.floor(v / 4294967296) >>> 0, true); +} + +function bytes(mem, ptr, n) { + return new Uint8Array(mem.buffer, ptr, n); +} + +function writeCStr(mem, ptr, s) { + const b = bytes(mem, ptr, s.length + 1); + for (let i = 0; i < s.length; i++) b[i] = s.charCodeAt(i) & 255; + b[s.length] = 0; + return s.length + 1; +} + +function writeStrings(mem, ptrs, buf, list) { + let off = buf; + for (let i = 0; i < list.length; i++) { + u32(mem, ptrs + i * 4, off); + off += writeCStr(mem, off, list[i]); + } +} + +function makeWasi(opts) { + const args = opts.args && opts.args.length ? opts.args.slice() : ["wasm"]; + const env = opts.env && opts.env.length ? opts.env.slice() : []; + const stdout = typeof opts.stdout === "function" ? opts.stdout : (t) => console.log(t); + const stderr = typeof opts.stderr === "function" ? opts.stderr : (t) => console.error(t); + let stdin = opts.stdin ? Uint8Array.from(typeof opts.stdin === "string" + ? [...opts.stdin].map((c) => c.charCodeAt(0)) + : opts.stdin) : new Uint8Array(); + let stdinOff = 0; + const sabIn = opts.stdinSab ? stdinFromSab(opts.stdinSab) : null; + const inst = { exports: {} }; + + function mem() { + return inst.exports.memory; + } + + function fdWrite(fd, iovs, iovsLen, nwritten) { + const m = mem(); + const dv = new DataView(m.buffer); + let wrote = 0; + let out = ""; + for (let i = 0; i < iovsLen; i++) { + const ptr = dv.getUint32(iovs + i * 8, true); + const len = dv.getUint32(iovs + i * 8 + 4, true); + if (len) out += new TextDecoder("utf-8", { fatal: false }).decode(bytes(m, ptr, len)); + wrote += len; + } + if (fd === 2) stderr(out); + else stdout(out); + u32(m, nwritten, wrote); + return ERRNO.SUCCESS; + } + + function fdRead(fd, iovs, iovsLen, nread) { + if (fd !== 0) return ERRNO.BADF; + const m = mem(); + const dv = new DataView(m.buffer); + let got = 0; + for (let i = 0; i < iovsLen; i++) { + const ptr = dv.getUint32(iovs + i * 8, true); + const len = dv.getUint32(iovs + i * 8 + 4, true); + if (!len) continue; + const slot = bytes(m, ptr, len); + if (sabIn) { + got += sabIn.take(slot); + } else { + const n = Math.min(len, stdin.length - stdinOff); + if (n > 0) { + slot.set(stdin.subarray(stdinOff, stdinOff + n)); + stdinOff += n; + got += n; + } + } + } + u32(m, nread, got); + return ERRNO.SUCCESS; + } + + const preview1 = { + args_sizes_get(argc, bufsz) { + const m = mem(); + u32(m, argc, args.length); + u32(m, bufsz, args.reduce((n, s) => n + s.length + 1, 0)); + return ERRNO.SUCCESS; + }, + args_get(argv, buf) { + writeStrings(mem(), argv, buf, args); + return ERRNO.SUCCESS; + }, + environ_sizes_get(count, bufsz) { + const m = mem(); + u32(m, count, env.length); + u32(m, bufsz, env.reduce((n, s) => n + s.length + 1, 0)); + return ERRNO.SUCCESS; + }, + environ_get(environ, buf) { + writeStrings(mem(), environ, buf, env); + return ERRNO.SUCCESS; + }, + clock_res_get(id, res) { + u64(mem(), res, 1000000); + return ERRNO.SUCCESS; + }, + clock_time_get(id, precision, time) { + u64(mem(), time, Date.now() * 1e6); + return ERRNO.SUCCESS; + }, + random_get(ptr, n) { + crypto.getRandomValues(bytes(mem(), ptr, n)); + return ERRNO.SUCCESS; + }, + proc_exit(code) { + throw new ExitError(code); + }, + proc_raise() { return ERRNO.NOSYS; }, + sched_yield() { return ERRNO.SUCCESS; }, + fd_write: fdWrite, + fd_read: fdRead, + fd_seek(fd, offset, whence, newoff) { + u64(mem(), newoff, 0); + return fd <= 2 ? ERRNO.SUCCESS : ERRNO.BADF; + }, + fd_tell(fd, off) { + u64(mem(), off, 0); + return fd <= 2 ? ERRNO.SUCCESS : ERRNO.BADF; + }, + fd_close(fd) { + return fd <= 2 ? ERRNO.SUCCESS : ERRNO.BADF; + }, + fd_fdstat_get(fd, stat) { + if (fd > 2) return ERRNO.BADF; + const m = mem(); + const b = bytes(m, stat, 24); + b.fill(0); + b[0] = 2; // filetype character + return ERRNO.SUCCESS; + }, + fd_fdstat_set_flags() { return ERRNO.SUCCESS; }, + fd_prestat_get() { return ERRNO.BADF; }, + fd_prestat_dir_name() { return ERRNO.BADF; }, + fd_datasync() { return ERRNO.SUCCESS; }, + fd_sync() { return ERRNO.SUCCESS; }, + fd_advise() { return ERRNO.SUCCESS; }, + fd_allocate() { return ERRNO.NOSYS; }, + fd_filestat_get() { return ERRNO.NOSYS; }, + fd_filestat_set_size() { return ERRNO.NOSYS; }, + fd_filestat_set_times() { return ERRNO.NOSYS; }, + fd_pread() { return ERRNO.NOSYS; }, + fd_pwrite() { return ERRNO.NOSYS; }, + fd_readdir() { return ERRNO.NOSYS; }, + fd_renumber() { return ERRNO.NOSYS; }, + path_open() { return ERRNO.NOSYS; }, + path_filestat_get() { return ERRNO.NOSYS; }, + path_filestat_set_times() { return ERRNO.NOSYS; }, + path_create_directory() { return ERRNO.NOSYS; }, + path_unlink_file() { return ERRNO.NOSYS; }, + path_remove_directory() { return ERRNO.NOSYS; }, + path_rename() { return ERRNO.NOSYS; }, + path_symlink() { return ERRNO.NOSYS; }, + path_link() { return ERRNO.NOSYS; }, + path_readlink() { return ERRNO.NOSYS; }, + poll_oneoff() { return ERRNO.NOSYS; }, + sock_accept() { return ERRNO.NOSYS; }, + sock_recv() { return ERRNO.NOSYS; }, + sock_send() { return ERRNO.NOSYS; }, + sock_shutdown() { return ERRNO.NOSYS; }, + }; + + return { preview1, inst, ExitError }; +} + +function packedStringImport(arity, fn) { + return function (memoryHolder) { + return function () { + const mem = memoryHolder.exports.memory; + const args = []; + for (let i = 0; i < arity; i++) { + const ptr = arguments[i * 2] >>> 0; + const len = arguments[i * 2 + 1] >>> 0; + args.push(len ? new TextDecoder().decode(bytes(mem, ptr, len)) : ""); + } + let result = ""; + let err = ""; + try { + const r = fn(args); + result = r == null ? "" : String(r); + } catch (e) { + err = e && e.message ? e.message : String(e); + } + const body = JSON.stringify(err + ? { ok: false, result: "", error: err } + : { ok: true, result: result }); + const alloc = memoryHolder.exports.alloc; + if (typeof alloc !== "function") return 0n; + const ptr = alloc(body.length) >>> 0; + const u8 = new TextEncoder().encode(body); + bytes(mem, ptr, u8.length).set(u8); + return (BigInt(ptr) << 32n) | BigInt(u8.length); + }; + }; +} + +function writeLEB(arr, v) { + v = v >>> 0; + while (true) { + const c = v & 0x7f; + v >>>= 7; + if (v) arr.push(c | 0x80); + else { + arr.push(c); + return; + } + } +} + +function readLEB(b, off) { + let v = 0; + let shift = 0; + for (let i = 0; i < 5 && off + i < b.length; i++) { + const c = b[off + i]; + v |= (c & 0x7f) << shift; + if ((c & 0x80) === 0) return [v >>> 0, i + 1]; + shift += 7; + } + return [0, 0]; +} + +function asU8(raw) { + if (raw instanceof Uint8Array) return raw; + return new Uint8Array(raw); +} + +function magicAt(b, off, mag) { + if (off + mag.length > b.length) return false; + for (let i = 0; i < mag.length; i++) if (b[off + i] !== mag[i]) return false; + return true; +} + +const CORE_MAGIC = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]; +const COMP_MAGIC = [0x00, 0x61, 0x73, 0x6d, 0x0d, 0x00, 0x01, 0x00]; + +// WASMMimicry wrapWASM: core v1 shell + custom section "unil" holding the +// inner bytes (wasigocvm component). Browser sees version 1; peel recovers +// the guest. Does not retarget the toolchain. +export function wrapMimicryWasm(inner) { + const payload = asU8(inner); + const name = [0x75, 0x6e, 0x69, 0x6c]; // "unil" + const nameLEB = []; + writeLEB(nameLEB, name.length); + const customPayloadLen = nameLEB.length + name.length + payload.length; + const sec = [0]; + writeLEB(sec, customPayloadLen); + const out = new Uint8Array(8 + sec.length + customPayloadLen); + out.set(CORE_MAGIC, 0); + let o = 8; + out.set(sec, o); + o += sec.length; + out.set(nameLEB, o); + o += nameLEB.length; + out.set(name, o); + o += name.length; + out.set(payload, o); + return out; +} + +export function peelMimicryWasm(raw) { + const b = asU8(raw); + if (!magicAt(b, 0, CORE_MAGIC)) return null; + let off = 8; + while (off < b.length) { + const id = b[off++]; + const [n, nlen] = readLEB(b, off); + if (!nlen) break; + off += nlen; + if (off + n > b.length) break; + const payload = b.subarray(off, off + n); + off += n; + if (id !== 0) continue; + const [nl, nllen] = readLEB(payload, 0); + if (!nllen) continue; + const name = new TextDecoder().decode(payload.subarray(nllen, nllen + nl)); + if (name === "unil" || name === "gocos") return payload.subarray(nllen + nl); + } + return null; +} + +export function extractComponentCore(raw) { + const b = asU8(raw); + if (!magicAt(b, 0, COMP_MAGIC)) return null; + let off = 8; + let best = null; + while (off < b.length) { + const id = b[off++]; + const [n, nlen] = readLEB(b, off); + if (!nlen) break; + off += nlen; + if (off + n > b.length) break; + const payload = b.subarray(off, off + n); + off += n; + if (id !== 1) continue; + let mod = null; + if (magicAt(payload, 0, CORE_MAGIC)) mod = payload; + else { + const [count, clen] = readLEB(payload, 0); + if (count && magicAt(payload, clen, CORE_MAGIC)) mod = payload.subarray(clen); + } + if (mod && (!best || mod.length > best.length)) best = mod; + } + return best; +} + +export function guestCore(raw) { + let b = asU8(raw); + const peeled = peelMimicryWasm(b); + if (peeled && peeled.length) b = peeled; + const core = extractComponentCore(b); + if (core && core.length) return core; + return b; +} + +export async function inspect(bytesIn) { + const core = guestCore(bytesIn); + const mod = await WebAssembly.compile(core); + const imports = WebAssembly.Module.imports(mod).map((i) => ({ + module: i.module, + name: i.name, + kind: i.kind, + })); + const exports = WebAssembly.Module.exports(mod).map((e) => ({ + name: e.name, + kind: e.kind, + })); + return { imports, exports, size: core.byteLength }; +} + +function stubImports(mod, base) { + const imports = Object.assign({}, base); + const nosys = () => ERRNO.NOSYS; + const ok = () => ERRNO.SUCCESS; + WebAssembly.Module.imports(mod).forEach((i) => { + if (!imports[i.module]) imports[i.module] = {}; + if (imports[i.module][i.name] == null) { + if (i.kind === "memory") { + imports[i.module][i.name] = new WebAssembly.Memory({ initial: 1 }); + } else if (i.kind === "table") { + imports[i.module][i.name] = new WebAssembly.Table({ initial: 0, element: "anyfunc" }); + } else if (i.kind === "global") { + imports[i.module][i.name] = new WebAssembly.Global({ value: "i32", mutable: false }, 0); + } else { + imports[i.module][i.name] = i.name === "proc_exit" ? base.wasi_snapshot_preview1.proc_exit : nosys; + if (i.name === "sched_yield") imports[i.module][i.name] = ok; + } + } + }); + return imports; +} + +// WASI 0.2 as flattened core imports (i32 handles + retptrs). Not WIT, +// not a component-model instantiator — wasm-component-ld already lowered +// the names; this is libc-shaped host for those functions. +function makeWasi02(opts, inst) { + const stdout = typeof opts.stdout === "function" ? opts.stdout : (t) => console.log(t); + const stderr = typeof opts.stderr === "function" ? opts.stderr : (t) => console.error(t); + const args = opts.args && opts.args.length ? opts.args.slice() : ["wasm"]; + const envList = opts.env && opts.env.length ? opts.env.slice() : []; + const sabIn = opts.stdinSab ? stdinFromSab(opts.stdinSab) : null; + const handles = new Map(); + let nextH = 1; + function intern(kind) { + const h = nextH++; + handles.set(h, kind); + return h; + } + const hIn = intern("in"); + const hOut = intern("out"); + const hErr = intern("err"); + + function memory() { + return inst.exports.memory; + } + function realloc(oldPtr, oldLen, align, n) { + const fn = inst.exports.cabi_realloc; + if (typeof fn !== "function") return 0; + return fn(oldPtr >>> 0, oldLen >>> 0, align >>> 0, n >>> 0) >>> 0; + } + function i32(ptr, v) { + new DataView(memory().buffer).setInt32(ptr, v | 0, true); + } + function u32get(ptr) { + return new DataView(memory().buffer).getUint32(ptr, true); + } + function u64(ptr, v) { + const dv = new DataView(memory().buffer); + dv.setUint32(ptr, v >>> 0, true); + dv.setUint32(ptr + 4, Math.floor(v / 4294967296) >>> 0, true); + } + function putBytes(ptr, arr) { + bytes(memory(), ptr, arr.length).set(arr); + } + function allocBytes(arr) { + const p = realloc(0, 0, 1, arr.length); + if (p && arr.length) putBytes(p, arr); + return p; + } + function allocList(strs) { + const n = strs.length; + const lp = realloc(0, 0, 4, n * 8); + for (let i = 0; i < n; i++) { + const enc = new TextEncoder().encode(strs[i]); + const sp = allocBytes(enc); + i32(lp + i * 8, sp); + i32(lp + i * 8 + 4, enc.length); + } + return lp; + } + function okEmpty(ret) { + if (ret) i32(ret, 0); + } + function okU64(ret, n) { + if (!ret) return; + i32(ret, 0); + u64(ret + 8, n); + } + function errClosed(ret) { + if (!ret) return; + i32(ret, 1); + i32(ret + 4, 1); + } + function errGeneric(ret) { + if (!ret) return; + i32(ret, 1); + i32(ret + 4, 0); + } + function putListU8(ret, arr) { + const p = allocBytes(arr); + i32(ret, 0); + i32(ret + 4, p); + i32(ret + 8, arr.length); + } + function drop(h) { + handles.delete(h >>> 0); + } + function stdinBlock() { + if (!opts.stdinSab) return; + const i32a = new Int32Array(opts.stdinSab); + while (Atomics.load(i32a, 1) === 0) { + Atomics.wait(i32a, 0, 0); + } + } + + function dispatch(mod, name, a) { + const m = String(mod); + const n = String(name); + if (n.indexOf("[resource-drop]") === 0) { + drop(a[0]); + return; + } + if (n === "exit" || n === "exit-with-code") { + throw new ExitError(a[0] | 0); + } + if (n === "get-stdout") return hOut; + if (n === "get-stderr") return hErr; + if (n === "get-stdin") return hIn; + if (n === "get-arguments") { + const lp = allocList(args); + i32(a[0], lp); + i32(a[0] + 4, args.length); + return; + } + if (n === "get-environment") { + const lp = allocList(envList); + i32(a[0], lp); + i32(a[0] + 4, envList.length); + return; + } + if (n === "now" && m.indexOf("monotonic-clock") >= 0) { + return BigInt(Date.now()) * 1000000n; + } + if (n === "resolution" && m.indexOf("monotonic-clock") >= 0) { + return 1000000n; + } + if (n === "now" && m.indexOf("wall-clock") >= 0) { + const ms = Date.now(); + u64(a[0], Math.floor(ms / 1000)); + i32(a[0] + 8, (ms % 1000) * 1000000); + return; + } + if (n === "resolution" && m.indexOf("wall-clock") >= 0) { + u64(a[0], 0); + i32(a[0] + 8, 1000000); + return; + } + if (n === "get-random-bytes") { + const want = Number(a[0]); + const buf = new Uint8Array(want > 0 && want < 1e6 ? want : 0); + if (buf.length) crypto.getRandomValues(buf); + putListU8(a[1], buf); + return; + } + if (n === "[method]output-stream.check-write") { + okU64(a[1], 4096); + return; + } + if (n === "[method]output-stream.write") { + const ptr = a[1] >>> 0; + const len = a[2] >>> 0; + if (len) { + const t = new TextDecoder("utf-8", { fatal: false }).decode(bytes(memory(), ptr, len)); + const k = handles.get(a[0] >>> 0); + if (k === "err") stderr(t); + else stdout(t); + } + okEmpty(a[3]); + return; + } + if (n === "[method]output-stream.blocking-flush") { + okEmpty(a[1]); + return; + } + if (n === "[method]output-stream.subscribe" || n === "[method]input-stream.subscribe") { + return intern("poll"); + } + if (n === "[method]pollable.block") { + const k = handles.get(a[0] >>> 0); + if (k === "in" || k === "poll") stdinBlock(); + return; + } + if (n === "poll") { + const inPtr = a[0] >>> 0; + const inLen = a[1] >>> 0; + const ret = a[2] >>> 0; + for (let i = 0; i < inLen; i++) { + const h = u32get(inPtr + i * 4); + if (handles.get(h) === "in") stdinBlock(); + } + const lp = realloc(0, 0, 4, inLen * 4); + for (let i = 0; i < inLen; i++) i32(lp + i * 4, i); + i32(ret, lp); + i32(ret + 4, inLen); + return; + } + if (n === "[method]input-stream.read") { + const max = Number(a[1]); + const nmax = max > 0 && max < 65536 ? max : 0; + const buf = new Uint8Array(nmax); + let got = 0; + if (nmax && sabIn) got = sabIn.take(buf); + putListU8(a[2], buf.subarray(0, got)); + return; + } + if (n.indexOf("get-terminal-") === 0) { + i32(a[0], 0); + return; + } + if (n === "subscribe-instant" || n === "subscribe-duration") { + return intern("poll"); + } + if (n === "instance-network") return intern("net"); + if (m.indexOf("filesystem") >= 0 || m.indexOf("sockets") >= 0) { + errGeneric(a[a.length - 1]); + return 0; + } + if (n.charAt(0) === "[" || a.length && typeof a[a.length - 1] === "number") { + errClosed(a[a.length - 1]); + } + return 0; + } + + return { dispatch, intern }; +} + +function bindP2Imports(mod, imports, p2) { + WebAssembly.Module.imports(mod).forEach((i) => { + const m = String(i.module); + if (m.indexOf("wasi:") !== 0) return; + if (!imports[m]) imports[m] = {}; + const n = i.name; + imports[m][n] = function () { + return p2.dispatch(m, n, Array.prototype.slice.call(arguments)); + }; + }); +} + +// A file's bytes: a Uint8Array, or a lazy source {size, readAt(pos, n)} the +// page seeded (a Blob/File, {url, size} read by HTTP Range, {sab, off, size} +// as a live view of a SharedArrayBuffer, or any {size, readAt} the worker +// built, such as a BNZ view). Lazy files are read in the pieces the guest +// asks for, so a large one (model weights) never sits whole in JS memory. +// Blob and HTTP readers are synchronous: FileReaderSync and sync XHR exist +// in workers, which is where a guest runs. +function lazySource(v) { + if (v && typeof v.readAt === "function" && typeof v.size === "number" && typeof v.url !== "string" && !(typeof Blob !== "undefined" && v instanceof Blob) && !(typeof SharedArrayBuffer !== "undefined" && v.sab instanceof SharedArrayBuffer)) { + const src = { + size: v.size, + readAt(pos, n) { return v.readAt(pos, n); }, + }; + // A streaming store (the phone embedding file) writes in place. Dropping + // writeAt would make the guest copy the whole file into one array. + if (typeof v.writeAt === "function") src.writeAt = function (pos, data) { return v.writeAt(pos, data); }; + if (typeof v.flush === "function") src.flush = function () { v.flush(); }; + return src; + } + if (typeof Blob !== "undefined" && v instanceof Blob) { + return { + size: v.size, + readAt(pos, n) { + return new Uint8Array(new FileReaderSync().readAsArrayBuffer(v.slice(pos, pos + n))); + }, + }; + } + // A live view of shared memory: the page writes it, the guest reads its + // current bytes on every read (a stop flag, a control word), and a guest + // write lands in it in place (a frame the page reads back). Its size is + // fixed: writeAt refuses bytes past the end. + if (v && typeof SharedArrayBuffer !== "undefined" && v.sab instanceof SharedArrayBuffer) { + const off = v.off | 0; + const size = typeof v.size === "number" ? v.size : v.sab.byteLength - off; + return { + size, + readAt(pos, n) { + return new Uint8Array(v.sab, off + pos, Math.max(0, Math.min(n, size - pos))).slice(); + }, + writeAt(pos, src) { + if (pos < 0 || pos + src.length > size) return false; + new Uint8Array(v.sab, off + pos, src.length).set(src); + return true; + }, + }; + } + if (v && typeof v.url === "string" && typeof v.size === "number") { + return { + size: v.size, + readAt(pos, n) { + const x = new XMLHttpRequest(); + x.open("GET", v.url, false); + x.setRequestHeader("Range", "bytes=" + pos + "-" + (pos + n - 1)); + x.responseType = "arraybuffer"; + x.send(); + if (x.status !== 206 && x.status !== 200) throw new Error(v.url + ": HTTP " + x.status); + const got = new Uint8Array(x.response); + // A server that ignores Range sends the whole file. + return x.status === 200 ? got.subarray(pos, pos + n) : got; + }, + }; + } + return null; +} + +function sizeOf(data) { + return data instanceof Uint8Array ? data.length : data.size; +} + +function readOf(data, pos, n) { + return data instanceof Uint8Array ? data.subarray(pos, pos + n) : data.readAt(pos, n); +} + +// Client file table for goclibc. The unil sandbox (wasmv16 / quickjs-ng) +// is the JS runner, and this page is that client. serve.mjs only delivers +// bytes; it does not instantiate the guest. +function makeGocLibc(mem, files) { + const boxes = [null]; + const fds = [null]; + const dirs = new Set(); + let cwd = "."; + function norm(p) { + return String(p).replace(/\\/g, "/").replace(/\/+$/, ""); + } + function parent(p) { + const s = norm(p); + const i = s.lastIndexOf("/"); + return i < 0 ? "" : s.slice(0, i); + } + function readStr(ptr, n) { + const m = mem(); + if (!m || n <= 0) return ""; + let s = ""; + const b = bytes(m, ptr, n); + for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]); + return s; + } + function putStat(out, isdir, size) { + const m = mem(); + const mode = isdir ? 0x4000 | 0o755 : 0x8000 | 0o644; + u32(m, out, mode); + u32(m, out + 4, isdir ? 1 : 0); + u64(m, out + 8, size); + } + function newBox(path, data) { + const box = { path: norm(path), data: data || new Uint8Array(0), refs: 1 }; + // A phone opens one embedding slice per read (path/@offset). Reuse a + // closed slice slot so a long chat does not keep a box per token. + if (box.path.indexOf("/@") >= 0) { + for (let i = 1; i < boxes.length; i++) { + if (!boxes[i]) { + boxes[i] = box; + return i; + } + } + } + boxes.push(box); + return boxes.length - 1; + } + function newFd(box, app, pos) { + fds.push({ box, pos, append: app }); + return fds.length - 1; + } + function fdOk(fd) { + return fd > 0 && fd < fds.length && fds[fd]; + } + const api = { + open(pathPtr, pathLen, flags) { + const path = norm(readStr(pathPtr, pathLen)); + if (!path) return -22; + const trunc = flags & 8; + const creat = flags & 4; + const app = flags & 16 ? 1 : 0; + let data = null; + const hit = boxes.find((b) => b && b.path === path); + // embed.bf16/@12345 is a read that starts at that byte. The guest has + // no Seek; the embedding table stays one OPFS file. + if (!hit && !trunc && !creat) { + const at = path.lastIndexOf("/@"); + if (at > 0 && /^\d+$/.test(path.slice(at + 2))) { + const base = boxes.find((b) => b && b.path === path.slice(0, at)); + const off = Number(path.slice(at + 2)); + if (base && off >= 0 && off <= sizeOf(base.data)) { + const parent = base.data; + const size = sizeOf(parent) - off; + data = { + size, + readAt(pos, n) { + const avail = size - pos; + if (pos < 0 || avail <= 0) return new Uint8Array(0); + return readOf(parent, off + pos, Math.min(n, avail)); + }, + }; + return newFd(newBox(path, data), 0, 0); + } + } + } + if (hit && hit.data && typeof hit.data.writeAt === "function") data = hit.data; // shared memory keeps its bytes: truncating means writing from the start + else if (!trunc && hit) data = hit.data; + else if (!trunc && !creat && !hit) return -2; + else data = new Uint8Array(0); + const id = newBox(path, data); + let pos = 0; + if (app) pos = sizeOf(boxes[id].data); + return newFd(id, app, pos); + }, + read(fd, ptr, n) { + if (!fdOk(fd) || n <= 0) return fdOk(fd) ? 0 : -9; + const slot = fds[fd]; + const data = boxes[slot.box].data; + const size = sizeOf(data); + if (slot.pos >= size) return 0; + const avail = Math.min(n, size - slot.pos); + bytes(mem(), ptr, avail).set(readOf(data, slot.pos, avail)); + slot.pos += avail; + return avail; + }, + write(fd, ptr, n) { + if (!fdOk(fd)) return -9; + const slot = fds[fd]; + const box = boxes[slot.box]; + const src = n > 0 ? bytes(mem(), ptr, n) : new Uint8Array(0); + if (typeof box.data.writeAt === "function") { // shared memory, written in place + const at = slot.append ? box.data.size : slot.pos; + if (!box.data.writeAt(at, src)) return -27; // EFBIG: past the shared memory's end + slot.pos = at + src.length; + return src.length; + } + if (!(box.data instanceof Uint8Array)) box.data = box.data.readAt(0, box.data.size); + if (slot.append) slot.pos = box.data.length; + const end = slot.pos + src.length; + const next = new Uint8Array(Math.max(box.data.length, end)); + next.set(box.data); + next.set(src, slot.pos); + box.data = next; + slot.pos = end; + return src.length; + }, + close(fd) { + if (!fdOk(fd)) return -9; + const slot = fds[fd]; + const box = boxes[slot.box]; + box.refs--; + if (box.refs <= 0 && box.path.indexOf("/@") >= 0) boxes[slot.box] = null; + fds[fd] = null; + return 0; + }, + seek(fd, off, whence) { + if (!fdOk(fd)) return -9; + const slot = fds[fd]; + const len = sizeOf(boxes[slot.box].data); + let base = 0; + if (whence === 1) base = slot.pos; + if (whence === 2) base = len; + const npos = base + (off | 0); + if (npos < 0) return -22; + slot.pos = npos; + return npos; + }, + flush(fd) { + if (!fdOk(fd)) return -9; + const data = boxes[fds[fd].box].data; + if (data && typeof data.flush === "function") data.flush(); + return 0; + }, + stat(pathPtr, pathLen, out) { + const path = norm(readStr(pathPtr, pathLen)); + if (dirs.has(path)) { + putStat(out, 1, 0); + return 0; + } + const hit = boxes.find((b) => b && b.path === path && b.refs > 0); + if (!hit) return -2; + putStat(out, 0, sizeOf(hit.data)); + return 0; + }, + fstat(fd, out) { + if (!fdOk(fd)) return -9; + const box = boxes[fds[fd].box]; + putStat(out, dirs.has(box.path) ? 1 : 0, sizeOf(box.data)); + return 0; + }, + mkdir(pathPtr, pathLen) { + const path = norm(readStr(pathPtr, pathLen)); + if (!path) return -22; + if (dirs.has(path)) return -17; + dirs.add(path); + return 0; + }, + unlink(pathPtr, pathLen) { + const path = norm(readStr(pathPtr, pathLen)); + if (dirs.has(path)) return -21; + let found = false; + for (let i = 1; i < boxes.length; i++) { + if (boxes[i] && boxes[i].path === path) { + boxes[i] = null; + found = true; + } + } + return found ? 0 : -2; + }, + rmdir(pathPtr, pathLen) { + const path = norm(readStr(pathPtr, pathLen)); + if (!dirs.has(path)) return -2; + dirs.delete(path); + return 0; + }, + rename(oldPtr, oldLen, newPtr, newLen) { + const a = norm(readStr(oldPtr, oldLen)); + const b = norm(readStr(newPtr, newLen)); + if (dirs.has(a)) { + dirs.delete(a); + dirs.add(b); + return 0; + } + const hit = boxes.find((x) => x && x.path === a); + if (!hit) return -2; + hit.path = b; + return 0; + }, + access(pathPtr, pathLen) { + const path = norm(readStr(pathPtr, pathLen)); + if (dirs.has(path)) return 0; + return boxes.some((b) => b && b.path === path) ? 0 : -2; + }, + getcwd(buf, cap) { + const s = cwd; + if (cap < s.length + 1) return -22; + const m = mem(); + const b = bytes(m, buf, s.length + 1); + for (let i = 0; i < s.length; i++) b[i] = s.charCodeAt(i) & 255; + b[s.length] = 0; + return s.length; + }, + chdir(pathPtr, pathLen) { + const path = norm(readStr(pathPtr, pathLen)); + if (!dirs.has(path) && path !== "." && path !== "") return -2; + cwd = path || "."; + return 0; + }, + readdir(pathPtr, pathLen, buf, cap) { + const path = norm(readStr(pathPtr, pathLen)); + const names = []; + dirs.forEach((d) => { + if (parent(d) === path) names.push("d" + d.slice(path.length + 1)); + }); + boxes.forEach((b) => { + if (b && parent(b.path) === path) names.push("f" + b.path.slice(b.path.lastIndexOf("/") + 1)); + }); + const out = []; + for (let i = 0; i < names.length; i++) { + const kind = names[i].charCodeAt(0); + const rest = names[i].slice(1); + out.push(kind); + for (let j = 0; j < rest.length; j++) out.push(rest.charCodeAt(j) & 255); + out.push(0); + } + if (out.length > cap) return -22; + if (out.length) bytes(mem(), buf, out.length).set(out); + return out.length; + }, + dup(fd) { + if (!fdOk(fd)) return -9; + const slot = fds[fd]; + boxes[slot.box].refs++; + return newFd(slot.box, slot.append, slot.pos); + }, + }; + // Files the page seeded. fopen of a seeded path hits this table. A value + // is bytes (Uint8Array / ArrayBuffer / array), or a Blob / {url, size}, + // which is read lazily (lazySource). + if (files) { + for (const path of Object.keys(files)) { + const p = norm(path); + let data = files[path]; + if (!(data instanceof Uint8Array)) data = lazySource(data) || new Uint8Array(data || []); + newBox(p, data); + let d = parent(p); + while (d) { + dirs.add(d); + d = parent(d); + } + } + } + return api; +} + +export async function instantiate(bytes, opts) { + opts = opts || {}; + const core = guestCore(bytes); + const mod = await WebAssembly.compile(core); + const wasi = makeWasi(opts); + const p2 = makeWasi02(opts, wasi.inst); + const env = { + log(ptr, len) { + const m = wasi.inst.exports.memory; + if (!m || !len) return; + const t = new TextDecoder("utf-8", { fatal: false }).decode(bytes(m, ptr, len)); + const stdout = typeof opts.stdout === "function" ? opts.stdout : (s) => console.log(s); + stdout(t); + }, + abort(code) { + throw new ExitError(code | 0); + }, + }; + if (opts.stringImports) { + for (const name of Object.keys(opts.stringImports)) { + const spec = opts.stringImports[name]; + env[name] = packedStringImport(spec.arity, spec.fn)(wasi.inst); + } + } + const base = { + wasi_snapshot_preview1: wasi.preview1, + wasi_unstable: wasi.preview1, + env, + goclibc: makeGocLibc(() => wasi.inst.exports.memory, opts.files), + }; + const imports = stubImports(mod, base); + bindP2Imports(mod, imports, p2); + // webgpu.batch (WASMWebGPU, linked into a guest that imports "webgpu"): + // a JSPI suspending import. opts.webgpu is WASMWebGPU/js/webgpu-exec.js + // ({runBatch, writeReply}); the batch runs on this host's navigator.gpu + // and the guest is suspended while a WebGPU promise settles. Without JSPI + // or opts.webgpu the import answers -1 and the guest reports no WebGPU. + let suspends = false; + const gpuImport = WebAssembly.Module.imports(mod).some((i) => i.module === "webgpu" && i.name === "batch"); + if (gpuImport) { + const jspi = typeof WebAssembly.Suspending === "function" && typeof WebAssembly.promising === "function"; + if (jspi && opts.webgpu) { + const gpu = opts.webgpu; + imports.webgpu.batch = new WebAssembly.Suspending((req, len, outPtr, cap) => { + const m = wasi.inst.exports.memory; + const answer = (reply) => gpu.writeReply(reply, new Uint8Array(m.buffer, outPtr >>> 0, cap >>> 0)); + let reply; + try { + reply = gpu.runBatch(new Uint8Array(m.buffer, req >>> 0, len >>> 0)); + } catch (e) { + return answer({ text: "error=webgpu batch: " + (e && e.message ? e.message : String(e)), bin: null }); + } + return reply && typeof reply.then === "function" ? reply.then(answer) : answer(reply); + }); + suspends = true; + } else { + imports.webgpu.batch = () => -1; + } + } + const instance = await WebAssembly.instantiate(mod, imports); + wasi.inst.exports = instance.exports; + return { module: mod, instance, exports: instance.exports, ExitError, suspends }; +} + +// A guest with a suspending import runs through WebAssembly.promising, so +// it can suspend; the others are called directly. +async function enter(loaded, fn, args) { + if (loaded.suspends) return WebAssembly.promising(fn)(...(args || [])); + return fn(...(args || [])); +} + +export async function run(loaded) { + const exp = loaded.exports || loaded.instance.exports; + try { + if (typeof exp._start === "function") { + await enter(loaded, exp._start); + return 0; + } + const names = Object.keys(exp); + for (let i = 0; i < names.length; i++) { + const n = names[i]; + if (typeof exp[n] !== "function") continue; + if (n === "run" || n.indexOf("#run") >= 0) { + const got = await enter(loaded, exp[n]); + return got | 0; + } + } + return 0; + } catch (e) { + if (e && (e.name === "ExitError" || typeof e.code === "number")) return e.code | 0; + throw e; + } +} + +export async function call(loaded, name, args) { + const fn = (loaded.exports || loaded.instance.exports)[name]; + if (typeof fn !== "function") throw new Error("unknown export " + name); + const a = (args || []).map((x) => x | 0); + try { + const got = await enter(loaded, fn, a); + return got; + } catch (e) { + if (e && (e.name === "ExitError" || typeof e.code === "number")) return e.code | 0; + throw e; + } +} + +export { ExitError }; diff --git a/local_frame_exec.wasm b/local_frame_exec.wasm new file mode 100644 index 0000000000000000000000000000000000000000..97837ee1a38e7de8d928d08e5752aeb9874981d8 --- /dev/null +++ b/local_frame_exec.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33c61aee91c3efba35ca74c493e0b5bb01e55d267fc928964d878eb8212c5119 +size 9020824 diff --git a/localsvc.js b/localsvc.js new file mode 100644 index 0000000000000000000000000000000000000000..e2afa892cabe13e80f6bd607790628a5ea5eab56 --- /dev/null +++ b/localsvc.js @@ -0,0 +1,413 @@ +// Champ's notes, tasks and canvas, in this browser. The same tools the site +// ran over GitMesh, TodoTraq and MotionKB, with the same ops and answers, +// kept in this browser's IndexedDB ("champ-svc"). No sign-in, and nothing +// leaves the page. Without IndexedDB (private window, blocked storage) they +// work in memory for this visit. +// +// notes {op: list|read|write|rm, path, text, message} GitMesh: champ-notes, one commit per change +// tasks {op: add|list|update|done|start|comment, title, body, id, state, text} TodoTraq: project CHAMP, Task type +// canvas {op: write|read|list, title, text} MotionKB: site "Champ Canvas", markdown as blocks +// +// Answers are {ok, output, data}: output is what Champ reads, data feeds the page. + +const DB = "champ-svc"; +const STORES = { files: "path", commits: "seq", tickets: "number", comments: "seq" }; + +const CANVAS_STATE = ".champ/canvas.json"; +const MAX_NOTE = 256 << 10; +const MAX_PATH = 200; +const MAX_LIST = 300; + +// TodoTraq's default Task type (0trustcloud work/types_default.go). +const TASK_TYPE = { id: "task", name: "Task", states: ["backlog", "open", "in_progress", "blocked", "done"] }; +const PROJECT_KEY = "CHAMP"; + +// ---- storage ---- + +function memoryBackend() { + const stores = {}; + for (const s of Object.keys(STORES)) stores[s] = new Map(); + return { + async get(store, key) { return stores[store].get(key) || null; }, + async all(store) { return [...stores[store].values()]; }, + // ops: [{store, put: rec} | {store, del: key}], all or none. + async apply(ops) { + for (const o of ops) { + const m = stores[o.store]; + if ("del" in o) m.delete(o.del); + else m.set(o.put[STORES[o.store]], structuredClone(o.put)); + } + }, + }; +} + +function openDB() { + return new Promise((resolve) => { + let req; + try { req = indexedDB.open(DB, 1); } catch { resolve(null); return; } + req.onupgradeneeded = () => { + for (const [name, keyPath] of Object.entries(STORES)) req.result.createObjectStore(name, { keyPath }); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => resolve(null); + req.onblocked = () => resolve(null); + }); +} + +function idbBackend(db) { + const done = (req) => new Promise((resolve, reject) => { + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + return { + async get(store, key) { return (await done(db.transaction(store, "readonly").objectStore(store).get(key))) || null; }, + async all(store) { return (await done(db.transaction(store, "readonly").objectStore(store).getAll())) || []; }, + apply(ops) { + return new Promise((resolve, reject) => { + const tx = db.transaction([...new Set(ops.map((o) => o.store))], "readwrite"); + for (const o of ops) { + const s = tx.objectStore(o.store); + if ("del" in o) s.delete(o.del); + else s.put(o.put); + } + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error); + tx.onabort = () => reject(tx.error || new Error("aborted")); + }); + }, + }; +} + +async function defaultBackend() { + if (typeof indexedDB === "undefined") return memoryBackend(); + const db = await openDB(); + return db ? idbBackend(db) : memoryBackend(); +} + +// ---- helpers ---- + +const enc = new TextEncoder(); +const byteLen = (s) => enc.encode(String(s)).length; + +function ok(output, data) { + const r = { ok: true, output }; + if (data) r.data = data; + return r; +} + +function fail(output) { + return { ok: false, output }; +} + +function firstSet(...v) { + for (const s of v) if (s) return s; + return ""; +} + +function errText(e) { + return String((e && e.message) || e || "error"); +} + +async function shaHex(text) { + try { + const d = await crypto.subtle.digest("SHA-1", enc.encode(text)); + return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join(""); + } catch { + let h = ""; + for (let i = 0; i < 40; i++) h += Math.floor(Math.random() * 16).toString(16); + return h; + } +} + +const now = () => new Date().toISOString(); + +// ---- notes: GitMesh ---- + +export function cleanNotePath(p) { + let s = String(p || "").replace(/\\/g, "/").trim().replace(/^\/+/, ""); + while (s.includes("//")) s = s.replace(/\/\//g, "/"); + if (!s || s.length > MAX_PATH || s.endsWith("/")) return ""; + for (const part of s.split("/")) { + if (!part || part === "." || part === ".." || part.toLowerCase() === ".git") return ""; + for (const ch of part) { + if (ch.charCodeAt(0) < 32 || '<>:"|?*'.includes(ch)) return ""; + } + } + return s; +} + +// ---- tasks: TodoTraq ---- + +// Champ says todo / doing / done; TodoTraq's Task type has its own states. +export function taskState(s, states) { + let v = String(s || "").trim().toLowerCase(); + if (["todo", "to do", "open", "new"].includes(v)) v = "open"; + else if (["doing", "start", "started", "in progress", "progress", "wip"].includes(v)) v = "in_progress"; + else if (["done", "close", "closed", "finished", "complete", "completed"].includes(v)) v = "done"; + return (states || TASK_TYPE.states).includes(v) ? v : ""; +} + +function ticketLine(t) { + return t.key + " [" + t.state + "] " + t.title; +} + +export function findTicket(ts, ref) { + const raw = String(ref || ""); + const r = raw.replace(/^#/, "").trim().toUpperCase(); + const m = /(\d+)$/.exec(r); + for (const t of ts) { + if (t.key === r || t.id === raw) return t; + if (m && String(t.number) === m[1] && (r === m[1] || r.startsWith(PROJECT_KEY))) return t; + } + return null; +} + +// ---- canvas: MotionKB ---- + +// markdownBlocks turns Champ's markdown into MotionKB blocks. +export function markdownBlocks(md) { + const out = []; + let para = []; + const flush = () => { + if (para.length) { + out.push({ type: "paragraph", content: para.join(" ") }); + para = []; + } + }; + const lines = String(md || "").replace(/\r\n/g, "\n").split("\n"); + for (let i = 0; i < lines.length; i++) { + const t = lines[i].replace(/[ \t]+$/, "").trim(); + if (t.startsWith("```")) { + flush(); + const code = []; + for (i++; i < lines.length && !lines[i].trim().startsWith("```"); i++) code.push(lines[i]); + out.push({ type: "code", content: code.join("\n") }); + continue; + } + let m; + if (t === "") flush(); + else if ((m = /^(#{1,3})\s+(.*)$/.exec(t))) { flush(); out.push({ type: "heading" + m[1].length, content: m[2] }); } + else if ((m = /^[-*]\s+\[([ xX])\]\s+(.*)$/.exec(t))) { flush(); out.push({ type: "todo", content: m[2], checked: m[1] !== " " }); } + else if ((m = /^(?:[-*+]|\d+[.)])\s+(.*)$/.exec(t))) { flush(); out.push({ type: "bullet", content: m[1] }); } + else if (t.startsWith(">")) { flush(); out.push({ type: "quote", content: t.slice(1).trim() }); } + else para.push(t); + } + flush(); + return out; +} + +export function slugOf(title) { + let s = String(title || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); + if (s.length > 60) s = s.slice(0, 60).replace(/^-+|-+$/g, ""); + return s || "canvas"; +} + +// ---- the services ---- + +export function createServices(opts) { + const o = opts || {}; + let backendP = null; + const backend = () => backendP || (backendP = o.backend ? Promise.resolve(o.backend) : defaultBackend()); + // One change at a time, so a task number or a commit's parent is never taken twice. + let chain = Promise.resolve(); + const serial = (fn) => { + const run = chain.then(fn, fn); + chain = run.catch(() => {}); + return run; + }; + + async function readNote(path) { + const f = await (await backend()).get("files", path); + return f ? f.content : null; + } + + async function commitNotes(message, files, deletes) { + const b = await backend(); + const log = await b.all("commits"); + const parent = log.reduce((a, c) => (c.seq > a.seq ? c : a), { seq: 0, id: "" }); + const at = now(); + const id = await shaHex(JSON.stringify({ parent: parent.id, message, files, deletes, at })); + const ops = []; + for (const [path, content] of Object.entries(files || {})) ops.push({ store: "files", put: { path, content, commit: id, updated: at } }); + for (const path of deletes || []) ops.push({ store: "files", del: path }); + ops.push({ store: "commits", put: { seq: parent.seq + 1, id, parent: parent.id, message, at, paths: Object.keys(files || {}), deletes: deletes || [] } }); + await b.apply(ops); + return id; + } + + async function notes(a) { + switch (a.op) { + case "": case "list": case "ls": { + const pre = String(a.path || "").trim().replace(/^\/+/, ""); + const names = (await (await backend()).all("files")) + .map((f) => f.path) + .filter((p) => !p.startsWith(".champ/") && p.startsWith(pre)) + .sort() + .slice(0, MAX_LIST); + if (!names.length) return ok("No notes yet.", { files: [] }); + return ok(names.join("\n"), { files: names }); + } + case "read": case "open": case "cat": { + const p = cleanNotePath(a.path); + if (!p) return fail("Which note? Give a path such as plans/today.md."); + const text = await readNote(p); + if (text == null) return fail("There is no note " + p + "."); + return ok(text, { path: p, text }); + } + case "write": case "save": case "put": { + const p = cleanNotePath(a.path); + if (!p) return fail("A note needs a path such as plans/today.md."); + const text = String(a.text == null ? "" : a.text); + if (byteLen(text) > MAX_NOTE) return fail("That note is over " + MAX_NOTE + " bytes."); + const sha = await serial(() => commitNotes(firstSet(String(a.message || "").trim(), "champ: write " + p), { [p]: text }, [])); + return ok("Saved " + p + ".", { path: p, commit: sha }); + } + case "rm": case "remove": case "delete": { + const p = cleanNotePath(a.path); + if (!p) return fail("Which note?"); + if ((await readNote(p)) == null) return fail("There is no note " + p + "."); + await serial(() => commitNotes("champ: remove " + p, {}, [p])); + return ok("Removed " + p + ".", { path: p }); + } + } + return fail("Notes can list, read, write or rm."); + } + + async function listTickets() { + return (await (await backend()).all("tickets")).sort((x, y) => x.number - y.number); + } + + async function tasks(a) { + const states = TASK_TYPE.states; + switch (a.op) { + case "": case "list": case "ls": { + let want = ""; + if (a.state) { + want = taskState(a.state, states); + if (!want) return fail("State is one of " + states.join(", ") + "."); + } + const shown = (await listTickets()).filter((t) => t.typeId === TASK_TYPE.id && (!want || t.state === want)); + if (!shown.length) return ok("No tasks.", { tasks: [] }); + return ok(shown.map(ticketLine).join("\n"), { tasks: shown }); + } + case "add": case "new": case "create": { + let title = firstSet(a.title, a.text).trim(); + if (!title) return fail("A task needs a title."); + if (title.length > 200) title = title.slice(0, 200); + const t = await serial(async () => { + const n = (await listTickets()).reduce((m, x) => Math.max(m, x.number), 0) + 1; + const at = now(); + const rec = { + id: PROJECT_KEY + "-" + n, number: n, key: PROJECT_KEY + "-" + n, typeId: TASK_TYPE.id, + title, state: taskState("open", states), fields: { summary: String(a.body || "") }, created: at, updated: at, + }; + await (await backend()).apply([{ store: "tickets", put: rec }]); + return rec; + }); + return ok("Added " + ticketLine(t) + ".", { task: t, tasks: [t] }); + } + case "update": case "set": case "done": case "start": case "close": case "comment": { + const t = findTicket(await listTickets(), a.id); + if (!t) return fail("There is no task " + (a.id || "") + "."); + if (a.op === "comment") { + const text = firstSet(a.text, a.body).trim(); + if (!text) return fail("A comment needs text."); + await serial(async () => { + const b = await backend(); + const seq = (await b.all("comments")).reduce((m, c) => Math.max(m, c.seq), 0) + 1; + await b.apply([{ store: "comments", put: { seq, ticket: t.number, content: text, created: now() } }]); + }); + return ok("Commented on " + t.key + ".", { task: t }); + } + let state = a.state || ""; + if (a.op === "done" || a.op === "close") state = "done"; + else if (a.op === "start") state = "doing"; + const nt = Object.assign({}, t); + let changed = false; + if (state) { + const s = taskState(state, states); + if (!s) return fail("State is one of " + states.join(", ") + "."); + nt.state = s; + changed = true; + } + if (String(a.title || "").trim()) { + nt.title = String(a.title).trim().slice(0, 200); + changed = true; + } + if (!changed) return fail("Nothing to change on " + t.key + "."); + nt.updated = now(); + await serial(async () => (await backend()).apply([{ store: "tickets", put: nt }])); + return ok("Updated " + ticketLine(nt) + ".", { task: nt, tasks: [nt] }); + } + } + return fail("Tasks can add, list, update, done, start or comment."); + } + + async function loadCanvas() { + const raw = await readNote(CANVAS_STATE); + let d = null; + try { d = raw ? JSON.parse(raw) : null; } catch { d = null; } + if (!d || typeof d !== "object") d = {}; + if (!d.site_id) d.site_id = "champ-canvas"; + if (!d.pages || typeof d.pages !== "object") d.pages = {}; + return d; + } + + async function canvas(a) { + switch (a.op) { + case "list": case "ls": { + const titles = Object.values((await loadCanvas()).pages).map((p) => p.title).sort(); + if (!titles.length) return ok("No canvases yet."); + return ok(titles.join("\n"), { titles }); + } + case "read": case "open": case "show": { + const slug = slugOf(a.title); + const p = (await loadCanvas()).pages[slug]; + const text = await readNote("canvas/" + slug + ".md"); + if (text == null || !p) return fail("There is no canvas " + JSON.stringify(String(a.title || "")) + "."); + return ok(text, { title: p.title, text, blocks: p.blocks || [] }); + } + case "": case "write": case "draw": case "set": { + const title = String(a.title || "").trim() || "Canvas"; + const text = String(a.text == null ? "" : a.text); + if (byteLen(text) > MAX_NOTE) return fail("That canvas is over " + MAX_NOTE + " bytes."); + const blocks = markdownBlocks(text); + if (!blocks.length) return fail("The canvas needs some markdown to show."); + const slug = slugOf(title); + await serial(async () => { + const d = await loadCanvas(); + const p = d.pages[slug] || { title, page_id: slug }; + p.blocks = blocks.map((b, i) => Object.assign({ position: i }, b)); + d.pages[slug] = p; + await commitNotes("champ: canvas " + title, { ["canvas/" + slug + ".md"]: text, [CANVAS_STATE]: JSON.stringify(d, null, 2) }, []); + }); + return ok("Canvas " + JSON.stringify(title) + " has " + blocks.length + " blocks.", { title, text, blocks }); + } + } + return fail("Canvas can write, read or list."); + } + + const tools = { notes, tasks, canvas }; + return { + // run(tool, args) -> {ok, output, data} + async run(tool, args) { + const fn = tools[tool]; + if (!fn) return fail("Unknown tool."); + const a = Object.assign({}, args || {}); + a.op = String(a.op || "").trim().toLowerCase(); + try { return await fn(a); } + catch (e) { return fail("The " + tool + " tool failed: " + errText(e)); } + }, + // A note's commit log, newest first. + async log() { + return (await (await backend()).all("commits")).sort((x, y) => y.seq - x.seq); + }, + async comments(ref) { + const t = findTicket(await listTickets(), ref); + if (!t) return []; + return (await (await backend()).all("comments")).filter((c) => c.ticket === t.number).sort((x, y) => x.seq - y.seq); + }, + }; +} + +export { memoryBackend }; diff --git a/manifest.webmanifest b/manifest.webmanifest new file mode 100644 index 0000000000000000000000000000000000000000..37a773fb2ee14c9876d6610844f2c6a8e0a3c3dc --- /dev/null +++ b/manifest.webmanifest @@ -0,0 +1,16 @@ +{ + "name": "Hodge-3.5", + "short_name": "Hodge-3.5", + "description": "Encryptid EdgeAI. Hodge-3.5 runs on this device.", + "id": "./", + "start_url": "./index.html", + "scope": "./", + "display": "standalone", + "orientation": "any", + "background_color": "#07090d", + "theme_color": "#07090d", + "icons": [ + { "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" }, + { "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" } + ] +} diff --git a/markdown.js b/markdown.js new file mode 100644 index 0000000000000000000000000000000000000000..05fe43a135091b9df3cefe41f6e5d802c72e9ad4 --- /dev/null +++ b/markdown.js @@ -0,0 +1,170 @@ +// Markdown for Champ's answers, built as DOM nodes (never innerHTML), so text +// from the model or a service cannot inject markup. Covers what chat answers +// use: headings, paragraphs, lists (with task boxes), quotes, tables, rules, +// fenced code with a copy button, and inline code, bold, italic and links. + +function el(tag, cls, text) { + const e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; +} + +// Inline: `code`, **bold**, *italic* / _italic_, [text](http…), bare http(s) links. +const INLINE = /(`+)([\s\S]+?)\1|\*\*([^*\n]+)\*\*|__([^_\n]+)__|\*([^*\n]+)\*|(?()]+[^\s<>().,;:!?'"])/g; + +export function inline(parent, text) { + const s = String(text || ""); + let at = 0; + for (const m of s.matchAll(INLINE)) { + if (m.index > at) parent.append(s.slice(at, m.index)); + if (m[2] != null) parent.append(el("code", "", m[2])); + else if (m[3] != null || m[4] != null) { const b = el("strong"); inline(b, m[3] || m[4]); parent.append(b); } + else if (m[5] != null || m[6] != null) { const i = el("em"); inline(i, m[5] || m[6]); parent.append(i); } + else { + const label = m[7] != null ? m[7] : m[9]; + const a = el("a", /^\d{1,2}$/.test(label) ? "cite" : "", label); + a.href = m[8] || m[9]; + a.target = "_blank"; + a.rel = "noopener noreferrer"; + parent.append(a); + } + at = m.index + m[0].length; + } + if (at < s.length) parent.append(s.slice(at)); +} + +function codeBlock(lang, code) { + const wrap = el("div", "code"); + const bar = el("div", "code-bar"); + bar.append(el("span", "", lang || "code")); + const copy = el("button", "copy", "Copy"); + copy.type = "button"; + copy.onclick = () => copyText(code, copy); + bar.append(copy); + const pre = el("pre"); + pre.append(el("code", "", code)); + wrap.append(bar, pre); + return wrap; +} + +export function copyText(text, button) { + const done = () => { + if (!button) return; + const was = button.textContent; + button.textContent = "Copied"; + setTimeout(() => { button.textContent = was; }, 1200); + }; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text).then(done, done); + return; + } + const ta = el("textarea"); + ta.value = text; + document.body.append(ta); + ta.select(); + try { document.execCommand("copy"); } catch { /* nothing to copy with */ } + ta.remove(); + done(); +} + +function cells(line) { + return line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim()); +} + +export function renderMarkdown(md, cls) { + const root = el("div", cls || "md"); + const lines = String(md || "").replace(/\r\n/g, "\n").split("\n"); + let para = []; + const flush = () => { + if (!para.length) return; + const p = el("p"); + para.forEach((l, i) => { if (i) p.append(el("br")); inline(p, l); }); + root.append(p); + para = []; + }; + for (let i = 0; i < lines.length; i++) { + const raw = lines[i]; + const t = raw.trim(); + let m; + if ((m = /^(`{3,}|~{3,})\s*([\w+#.-]*)/.exec(t))) { + flush(); + const fence = m[1]; + const code = []; + for (i++; i < lines.length && !lines[i].trim().startsWith(fence); i++) code.push(lines[i]); + root.append(codeBlock(m[2], code.join("\n"))); + continue; + } + if (!t) { flush(); continue; } + if (/^(-{3,}|\*{3,}|_{3,})$/.test(t)) { flush(); root.append(el("hr")); continue; } + if ((m = /^(#{1,6})\s+(.*?)\s*#*$/.exec(t))) { + flush(); + const h = el("h" + Math.min(6, m[1].length + 2)); + inline(h, m[2]); + root.append(h); + continue; + } + if (t.startsWith("|") && i + 1 < lines.length && /^\|?\s*:?-{2,}/.test(lines[i + 1].trim())) { + flush(); + const table = el("table"); + const tr = el("tr"); + for (const c of cells(t)) { const th = el("th"); inline(th, c); tr.append(th); } + const thead = el("thead"); + thead.append(tr); + table.append(thead); + const tbody = el("tbody"); + for (i += 2; i < lines.length && lines[i].trim().startsWith("|"); i++) { + const row = el("tr"); + for (const c of cells(lines[i])) { const td = el("td"); inline(td, c); row.append(td); } + tbody.append(row); + } + i--; + table.append(tbody); + const scroll = el("div", "table"); + scroll.append(table); + root.append(scroll); + continue; + } + if (/^(?:[-*+]|\d+[.)])\s+/.test(t)) { + flush(); + const ordered = /^\d/.test(t); + const list = el(ordered ? "ol" : "ul"); + for (; i < lines.length; i++) { + const lt = lines[i].trim(); + const item = /^(?:[-*+]|\d+[.)])\s+(.*)$/.exec(lt); + if (!item) { + if (lt && list.lastChild && /^\s{2,}/.test(lines[i])) { list.lastChild.append(" "); inline(list.lastChild, lt); continue; } + break; + } + const li = el("li"); + const task = /^\[([ xX])\]\s+(.*)$/.exec(item[1]); + if (task) { + const box = el("input"); + box.type = "checkbox"; + box.disabled = true; + box.checked = task[1] !== " "; + li.className = "task-item"; + li.append(box, " "); + inline(li, task[2]); + } else inline(li, item[1]); + list.append(li); + } + i--; + root.append(list); + continue; + } + if (t.startsWith(">")) { + flush(); + const q = []; + for (; i < lines.length && lines[i].trim().startsWith(">"); i++) q.push(lines[i].trim().replace(/^>\s?/, "")); + i--; + const bq = el("blockquote"); + bq.append(renderMarkdown(q.join("\n"), "md-inner")); + root.append(bq); + continue; + } + para.push(t); + } + flush(); + return root; +} diff --git a/mind.js b/mind.js new file mode 100644 index 0000000000000000000000000000000000000000..716b7aaef269a19b6b6d8969af9af8d4b85fd838 --- /dev/null +++ b/mind.js @@ -0,0 +1,83 @@ +// Champ's local mind: MVCC thought versions, the DEC embedding module, +// and a library slot for each new weight or self-improvement note. + +import { createStore } from "./mvcc.js"; +import { buildLut, embedText, cosine, packEmbedModule } from "./embed.js"; + +const CHAT = { id: "champ", role: "chat", codec: "bnz" }; +const EMBED = { id: "embed-dec", role: "embed", codec: "bnz" }; + +// opts.onCommit receives every new record, for persistence (persist.js). +export function createMind(opts) { + const store = createStore(opts); + const lut = buildLut(); + const embedBnz = packEmbedModule(lut); + const mods = [CHAT, EMBED]; + return { + store, + lut, + embedBnz, + embed(text) { return embedText(text, lut); }, + cosine, + commit(page, key, value, limit) { return store.commit(page, key, value, limit); }, + read(page, key, asOf) { return store.read(page, key, asOf); }, + history(page, key) { return store.history(page, key); }, + replay(txn, page, key, value) { store.replay(txn, page, key, value); }, + scan(page, prefix, asOf) { return store.scan(page, prefix, asOf); }, + head() { return store.head(); }, + modules() { return mods.map((m) => Object.assign({}, m)); }, + // After a replay: the library slots come back from their own records. + restoreModules() { + for (const rec of store.scan("library", "", store.head())) { + if (mods.some((m) => m.id === rec.key)) continue; + try { mods.push(JSON.parse(rec.value)); } catch { /* not a module record */ } + } + }, + addModule(mod) { + mods.push(mod); + store.commit("library", mod.id, JSON.stringify(mod)); + return mod; + }, + learn(question, answer) { + const text = (String(question) + "\n" + String(answer)).slice(0, 700); + const txn = store.commit("learn", "note/" + (store.head() + 1), text); + this.addModule({ id: "learn-" + txn, role: "memory", codec: "mvcc", page: "learn" }); + return txn; + }, + // A page read to learn from: its text in pieces small enough to recall, each with its address. + learnPage(source, text) { + const body = String(text || "").replace(/\s+/g, " ").trim(); + let txn = 0; + for (let at = 0; at < body.length && at < 2400; at += 600) { + txn = store.commit("learn", "note/" + (store.head() + 1), (String(source) + "\n" + body.slice(at, at + 600)).slice(0, 700)); + } + if (txn) this.addModule({ id: "learn-" + txn, role: "memory", codec: "mvcc", page: "learn" }); + return txn; + }, + recall(query, minScore) { + const floor = minScore == null ? 0.72 : minScore; + const qv = embedText(query, lut); + let best = ""; + let score = floor; + for (const rec of store.scan("learn", "note/", store.head())) { + const s = cosine(qv, embedText(rec.value, lut)); + if (s > score) { + score = s; + best = rec.value; + } + } + return best ? best.slice(0, 400) : ""; + }, + }; +} + +export function thoughtPrompt(step, question, earlier) { + const prior = earlier ? " So far: " + earlier.slice(0, 180) : ""; + return "One reasoning step only, in one sentence. Do not give the final answer. Do not use a tool." + prior + "\nQuestion: " + question + "\nStep " + step + ":"; +} + +export function explainPrompt(question, versions, notes) { + const lines = versions.map((v, i) => (i + 1) + ". " + v).join("\n"); + const note = notes ? "\nNotes:\n" + notes : ""; + return "Explain the answer in plain words. Do not use a tool.\nThoughts:\n" + lines + note + "\nQuestion: " + question; +} diff --git a/models/catalog.json b/models/catalog.json new file mode 100644 index 0000000000000000000000000000000000000000..531fa1899aba40cfde7cc4f6e53a6a46fedf7e8f --- /dev/null +++ b/models/catalog.json @@ -0,0 +1 @@ +{"models":[{"id":"hodge-5","name":"Hodge-5","tier":"lite"}]} \ No newline at end of file diff --git a/models/hodge-5/config.json b/models/hodge-5/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3e48b92d3464ed2dc5e7dfe585bdf3695b5146da --- /dev/null +++ b/models/hodge-5/config.json @@ -0,0 +1,27 @@ +{ + "architectures": [ + "HodgeForCausalLM" + ], + "bos_token_id": 128000, + "eos_token_id": 128001, + "hidden_act": "relu2", + "hidden_size": 2560, + "initializer_range": 0.02, + "intermediate_size": 6912, + "max_position_embeddings": 4096, + "model_type": "hodge", + "num_attention_heads": 20, + "num_hidden_layers": 30, + "num_key_value_heads": 5, + "quantization_config": { + "linear_class": "hodgelinear", + "quant_method": "hodge", + "quantization_mode": "offline" + }, + "rms_norm_eps": 0.00001, + "rope_theta": 500000, + "tie_word_embeddings": true, + "torch_dtype": "bfloat16", + "use_cache": true, + "vocab_size": 563206 +} \ No newline at end of file diff --git a/models/hodge-5/generation_config.json b/models/hodge-5/generation_config.json new file mode 100644 index 0000000000000000000000000000000000000000..650ab2390d65b8182f2599fe7a0f2014eec3f38b --- /dev/null +++ b/models/hodge-5/generation_config.json @@ -0,0 +1,12 @@ +{ + "bos_token_id": 128000, + "eos_token_id": [ + 128001, + 128009 + ], + "do_sample": true, + "temperature": 0.6, + "max_length": 4096, + "top_p": 0.9, + "transformers_version": "4.40.0.dev0" +} diff --git a/models/hodge-5/tokenizer.json b/models/hodge-5/tokenizer.json new file mode 100644 index 0000000000000000000000000000000000000000..cb8f995425abfdcc4d4706f7531f7627748720d9 --- /dev/null +++ b/models/hodge-5/tokenizer.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5ea900499319a8d84c91ce024963ae0991b534622b8493d5644d15f64888353 +size 27781817 diff --git a/models/hodge-5/tokenizer_config.json b/models/hodge-5/tokenizer_config.json new file mode 100644 index 0000000000000000000000000000000000000000..78fd90bc95abb28e4b027f9a859d8f2be8051089 --- /dev/null +++ b/models/hodge-5/tokenizer_config.json @@ -0,0 +1,2982 @@ +{ + "added_tokens_decoder": { + "128000": { + "content": "\u003c|begin_of_text|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128001": { + "content": "\u003c|end_of_text|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128002": { + "content": "\u003c|reserved_special_token_0|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128003": { + "content": "\u003c|reserved_special_token_1|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128004": { + "content": "\u003c|reserved_special_token_2|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128005": { + "content": "\u003c|reserved_special_token_3|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128006": { + "content": "\u003c|start_header_id|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128007": { + "content": "\u003c|end_header_id|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128008": { + "content": "\u003c|reserved_special_token_4|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128009": { + "content": "\u003c|eot_id|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128010": { + "content": "\u003c|reserved_special_token_5|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128011": { + "content": "\u003c|reserved_special_token_6|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128012": { + "content": "\u003c|reserved_special_token_7|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128013": { + "content": "\u003c|reserved_special_token_8|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128014": { + "content": "\u003c|reserved_special_token_9|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128015": { + "content": "\u003c|reserved_special_token_10|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128016": { + "content": "\u003c|reserved_special_token_11|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128017": { + "content": "\u003c|reserved_special_token_12|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128018": { + "content": "\u003c|reserved_special_token_13|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128019": { + "content": "\u003c|reserved_special_token_14|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128020": { + "content": "\u003c|reserved_special_token_15|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128021": { + "content": "\u003c|reserved_special_token_16|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128022": { + "content": "\u003c|reserved_special_token_17|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128023": { + "content": "\u003c|reserved_special_token_18|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128024": { + "content": "\u003c|reserved_special_token_19|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128025": { + "content": "\u003c|reserved_special_token_20|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128026": { + "content": "\u003c|reserved_special_token_21|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128027": { + "content": "\u003c|reserved_special_token_22|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128028": { + "content": "\u003c|reserved_special_token_23|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128029": { + "content": "\u003c|reserved_special_token_24|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128030": { + "content": "\u003c|reserved_special_token_25|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128031": { + "content": "\u003c|reserved_special_token_26|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128032": { + "content": "\u003c|reserved_special_token_27|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128033": { + "content": "\u003c|reserved_special_token_28|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128034": { + "content": "\u003c|reserved_special_token_29|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128035": { + "content": "\u003c|reserved_special_token_30|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128036": { + "content": "\u003c|reserved_special_token_31|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128037": { + "content": "\u003c|reserved_special_token_32|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128038": { + "content": "\u003c|reserved_special_token_33|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128039": { + "content": "\u003c|reserved_special_token_34|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128040": { + "content": "\u003c|reserved_special_token_35|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128041": { + "content": "\u003c|reserved_special_token_36|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128042": { + "content": "\u003c|reserved_special_token_37|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128043": { + "content": "\u003c|reserved_special_token_38|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128044": { + "content": "\u003c|reserved_special_token_39|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128045": { + "content": "\u003c|reserved_special_token_40|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128046": { + "content": "\u003c|reserved_special_token_41|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128047": { + "content": "\u003c|reserved_special_token_42|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128048": { + "content": "\u003c|reserved_special_token_43|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128049": { + "content": "\u003c|reserved_special_token_44|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128050": { + "content": "\u003c|reserved_special_token_45|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128051": { + "content": "\u003c|reserved_special_token_46|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128052": { + "content": "\u003c|reserved_special_token_47|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128053": { + "content": "\u003c|reserved_special_token_48|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128054": { + "content": "\u003c|reserved_special_token_49|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128055": { + "content": "\u003c|reserved_special_token_50|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128056": { + "content": "\u003c|reserved_special_token_51|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128057": { + "content": "\u003c|reserved_special_token_52|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128058": { + "content": "\u003c|reserved_special_token_53|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128059": { + "content": "\u003c|reserved_special_token_54|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128060": { + "content": "\u003c|reserved_special_token_55|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128061": { + "content": "\u003c|reserved_special_token_56|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128062": { + "content": "\u003c|reserved_special_token_57|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128063": { + "content": "\u003c|reserved_special_token_58|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128064": { + "content": "\u003c|reserved_special_token_59|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128065": { + "content": "\u003c|reserved_special_token_60|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128066": { + "content": "\u003c|reserved_special_token_61|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128067": { + "content": "\u003c|reserved_special_token_62|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128068": { + "content": "\u003c|reserved_special_token_63|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128069": { + "content": "\u003c|reserved_special_token_64|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128070": { + "content": "\u003c|reserved_special_token_65|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128071": { + "content": "\u003c|reserved_special_token_66|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128072": { + "content": "\u003c|reserved_special_token_67|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128073": { + "content": "\u003c|reserved_special_token_68|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128074": { + "content": "\u003c|reserved_special_token_69|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128075": { + "content": "\u003c|reserved_special_token_70|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128076": { + "content": "\u003c|reserved_special_token_71|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128077": { + "content": "\u003c|reserved_special_token_72|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128078": { + "content": "\u003c|reserved_special_token_73|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128079": { + "content": "\u003c|reserved_special_token_74|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128080": { + "content": "\u003c|reserved_special_token_75|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128081": { + "content": "\u003c|reserved_special_token_76|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128082": { + "content": "\u003c|reserved_special_token_77|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128083": { + "content": "\u003c|reserved_special_token_78|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128084": { + "content": "\u003c|reserved_special_token_79|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128085": { + "content": "\u003c|reserved_special_token_80|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128086": { + "content": "\u003c|reserved_special_token_81|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128087": { + "content": "\u003c|reserved_special_token_82|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128088": { + "content": "\u003c|reserved_special_token_83|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128089": { + "content": "\u003c|reserved_special_token_84|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128090": { + "content": "\u003c|reserved_special_token_85|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128091": { + "content": "\u003c|reserved_special_token_86|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128092": { + "content": "\u003c|reserved_special_token_87|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128093": { + "content": "\u003c|reserved_special_token_88|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128094": { + "content": "\u003c|reserved_special_token_89|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128095": { + "content": "\u003c|reserved_special_token_90|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128096": { + "content": "\u003c|reserved_special_token_91|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128097": { + "content": "\u003c|reserved_special_token_92|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128098": { + "content": "\u003c|reserved_special_token_93|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128099": { + "content": "\u003c|reserved_special_token_94|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128100": { + "content": "\u003c|reserved_special_token_95|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128101": { + "content": "\u003c|reserved_special_token_96|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128102": { + "content": "\u003c|reserved_special_token_97|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128103": { + "content": "\u003c|reserved_special_token_98|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128104": { + "content": "\u003c|reserved_special_token_99|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128105": { + "content": "\u003c|reserved_special_token_100|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128106": { + "content": "\u003c|reserved_special_token_101|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128107": { + "content": "\u003c|reserved_special_token_102|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128108": { + "content": "\u003c|reserved_special_token_103|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128109": { + "content": "\u003c|reserved_special_token_104|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128110": { + "content": "\u003c|reserved_special_token_105|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128111": { + "content": "\u003c|reserved_special_token_106|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128112": { + "content": "\u003c|reserved_special_token_107|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128113": { + "content": "\u003c|reserved_special_token_108|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128114": { + "content": "\u003c|reserved_special_token_109|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128115": { + "content": "\u003c|reserved_special_token_110|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128116": { + "content": "\u003c|reserved_special_token_111|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128117": { + "content": "\u003c|reserved_special_token_112|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128118": { + "content": "\u003c|reserved_special_token_113|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128119": { + "content": "\u003c|reserved_special_token_114|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128120": { + "content": "\u003c|reserved_special_token_115|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128121": { + "content": "\u003c|reserved_special_token_116|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128122": { + "content": "\u003c|reserved_special_token_117|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128123": { + "content": "\u003c|reserved_special_token_118|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128124": { + "content": "\u003c|reserved_special_token_119|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128125": { + "content": "\u003c|reserved_special_token_120|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128126": { + "content": "\u003c|reserved_special_token_121|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128127": { + "content": "\u003c|reserved_special_token_122|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128128": { + "content": "\u003c|reserved_special_token_123|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128129": { + "content": "\u003c|reserved_special_token_124|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128130": { + "content": "\u003c|reserved_special_token_125|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128131": { + "content": "\u003c|reserved_special_token_126|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128132": { + "content": "\u003c|reserved_special_token_127|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128133": { + "content": "\u003c|reserved_special_token_128|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128134": { + "content": "\u003c|reserved_special_token_129|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128135": { + "content": "\u003c|reserved_special_token_130|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128136": { + "content": "\u003c|reserved_special_token_131|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128137": { + "content": "\u003c|reserved_special_token_132|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128138": { + "content": "\u003c|reserved_special_token_133|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128139": { + "content": "\u003c|reserved_special_token_134|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128140": { + "content": "\u003c|reserved_special_token_135|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128141": { + "content": "\u003c|reserved_special_token_136|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128142": { + "content": "\u003c|reserved_special_token_137|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128143": { + "content": "\u003c|reserved_special_token_138|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128144": { + "content": "\u003c|reserved_special_token_139|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128145": { + "content": "\u003c|reserved_special_token_140|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128146": { + "content": "\u003c|reserved_special_token_141|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128147": { + "content": "\u003c|reserved_special_token_142|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128148": { + "content": "\u003c|reserved_special_token_143|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128149": { + "content": "\u003c|reserved_special_token_144|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128150": { + "content": "\u003c|reserved_special_token_145|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128151": { + "content": "\u003c|reserved_special_token_146|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128152": { + "content": "\u003c|reserved_special_token_147|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128153": { + "content": "\u003c|reserved_special_token_148|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128154": { + "content": "\u003c|reserved_special_token_149|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128155": { + "content": "\u003c|reserved_special_token_150|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128156": { + "content": "\u003c|reserved_special_token_151|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128157": { + "content": "\u003c|reserved_special_token_152|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128158": { + "content": "\u003c|reserved_special_token_153|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128159": { + "content": "\u003c|reserved_special_token_154|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128160": { + "content": "\u003c|reserved_special_token_155|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128161": { + "content": "\u003c|reserved_special_token_156|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128162": { + "content": "\u003c|reserved_special_token_157|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128163": { + "content": "\u003c|reserved_special_token_158|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128164": { + "content": "\u003c|reserved_special_token_159|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128165": { + "content": "\u003c|reserved_special_token_160|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128166": { + "content": "\u003c|reserved_special_token_161|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128167": { + "content": "\u003c|reserved_special_token_162|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128168": { + "content": "\u003c|reserved_special_token_163|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128169": { + "content": "\u003c|reserved_special_token_164|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128170": { + "content": "\u003c|reserved_special_token_165|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128171": { + "content": "\u003c|reserved_special_token_166|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128172": { + "content": "\u003c|reserved_special_token_167|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128173": { + "content": "\u003c|reserved_special_token_168|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128174": { + "content": "\u003c|reserved_special_token_169|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128175": { + "content": "\u003c|reserved_special_token_170|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128176": { + "content": "\u003c|reserved_special_token_171|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128177": { + "content": "\u003c|reserved_special_token_172|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128178": { + "content": "\u003c|reserved_special_token_173|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128179": { + "content": "\u003c|reserved_special_token_174|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128180": { + "content": "\u003c|reserved_special_token_175|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128181": { + "content": "\u003c|reserved_special_token_176|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128182": { + "content": "\u003c|reserved_special_token_177|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128183": { + "content": "\u003c|reserved_special_token_178|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128184": { + "content": "\u003c|reserved_special_token_179|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128185": { + "content": "\u003c|reserved_special_token_180|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128186": { + "content": "\u003c|reserved_special_token_181|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128187": { + "content": "\u003c|reserved_special_token_182|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128188": { + "content": "\u003c|reserved_special_token_183|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128189": { + "content": "\u003c|reserved_special_token_184|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128190": { + "content": "\u003c|reserved_special_token_185|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128191": { + "content": "\u003c|reserved_special_token_186|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128192": { + "content": "\u003c|reserved_special_token_187|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128193": { + "content": "\u003c|reserved_special_token_188|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128194": { + "content": "\u003c|reserved_special_token_189|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128195": { + "content": "\u003c|reserved_special_token_190|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128196": { + "content": "\u003c|reserved_special_token_191|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128197": { + "content": "\u003c|reserved_special_token_192|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128198": { + "content": "\u003c|reserved_special_token_193|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128199": { + "content": "\u003c|reserved_special_token_194|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128200": { + "content": "\u003c|reserved_special_token_195|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128201": { + "content": "\u003c|reserved_special_token_196|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128202": { + "content": "\u003c|reserved_special_token_197|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128203": { + "content": "\u003c|reserved_special_token_198|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128204": { + "content": "\u003c|reserved_special_token_199|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128205": { + "content": "\u003c|reserved_special_token_200|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128206": { + "content": "\u003c|reserved_special_token_201|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128207": { + "content": "\u003c|reserved_special_token_202|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128208": { + "content": "\u003c|reserved_special_token_203|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128209": { + "content": "\u003c|reserved_special_token_204|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128210": { + "content": "\u003c|reserved_special_token_205|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128211": { + "content": "\u003c|reserved_special_token_206|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128212": { + "content": "\u003c|reserved_special_token_207|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128213": { + "content": "\u003c|reserved_special_token_208|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128214": { + "content": "\u003c|reserved_special_token_209|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128215": { + "content": "\u003c|reserved_special_token_210|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128216": { + "content": "\u003c|reserved_special_token_211|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128217": { + "content": "\u003c|reserved_special_token_212|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128218": { + "content": "\u003c|reserved_special_token_213|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128219": { + "content": "\u003c|reserved_special_token_214|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128220": { + "content": "\u003c|reserved_special_token_215|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128221": { + "content": "\u003c|reserved_special_token_216|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128222": { + "content": "\u003c|reserved_special_token_217|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128223": { + "content": "\u003c|reserved_special_token_218|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128224": { + "content": "\u003c|reserved_special_token_219|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128225": { + "content": "\u003c|reserved_special_token_220|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128226": { + "content": "\u003c|reserved_special_token_221|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128227": { + "content": "\u003c|reserved_special_token_222|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128228": { + "content": "\u003c|reserved_special_token_223|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128229": { + "content": "\u003c|reserved_special_token_224|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128230": { + "content": "\u003c|reserved_special_token_225|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128231": { + "content": "\u003c|reserved_special_token_226|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128232": { + "content": "\u003c|reserved_special_token_227|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128233": { + "content": "\u003c|reserved_special_token_228|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128234": { + "content": "\u003c|reserved_special_token_229|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128235": { + "content": "\u003c|reserved_special_token_230|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128236": { + "content": "\u003c|reserved_special_token_231|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128237": { + "content": "\u003c|reserved_special_token_232|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128238": { + "content": "\u003c|reserved_special_token_233|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128239": { + "content": "\u003c|reserved_special_token_234|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128240": { + "content": "\u003c|reserved_special_token_235|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128241": { + "content": "\u003c|reserved_special_token_236|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128242": { + "content": "\u003c|reserved_special_token_237|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128243": { + "content": "\u003c|reserved_special_token_238|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128244": { + "content": "\u003c|reserved_special_token_239|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128245": { + "content": "\u003c|reserved_special_token_240|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128246": { + "content": "\u003c|reserved_special_token_241|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128247": { + "content": "\u003c|reserved_special_token_242|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128248": { + "content": "\u003c|reserved_special_token_243|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128249": { + "content": "\u003c|reserved_special_token_244|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128250": { + "content": "\u003c|reserved_special_token_245|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128251": { + "content": "\u003c|reserved_special_token_246|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128252": { + "content": "\u003c|reserved_special_token_247|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128253": { + "content": "\u003c|reserved_special_token_248|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128254": { + "content": "\u003c|reserved_special_token_249|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "128255": { + "content": "\u003c|reserved_special_token_250|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "298557": { + "content": "\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298558": { + "content": "\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298559": { + "content": "\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298560": { + "content": "\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298561": { + "content": "\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298562": { + "content": "\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298563": { + "content": "\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298564": { + "content": "\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298565": { + "content": "\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298566": { + "content": "\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298567": { + "content": "\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298568": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298569": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298570": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298571": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298572": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298573": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298574": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298575": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298576": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298577": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298578": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298579": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298580": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298581": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298582": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298583": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298584": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298585": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298586": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298587": { + "content": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298588": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298589": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298590": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298591": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298592": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298593": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298594": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298595": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298596": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298597": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298598": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298599": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298600": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298601": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298602": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298603": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298604": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298605": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298606": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298607": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298608": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298609": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298610": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298611": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298612": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298613": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298614": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298615": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298616": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298617": { + "content": " ", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298618": { + "content": "\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298619": { + "content": "\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298620": { + "content": "\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298621": { + "content": "\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298622": { + "content": "\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298623": { + "content": "\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298624": { + "content": "\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298625": { + "content": "\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298626": { + "content": "\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298627": { + "content": "\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298628": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298629": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298630": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298631": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298632": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298633": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298634": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298635": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298636": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298637": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298638": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298639": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298640": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298641": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298642": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298643": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298644": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298645": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298646": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "298647": { + "content": "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": false + }, + "514304": { + "content": "\u003c|finetune_right_pad_id|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "514305": { + "content": "\u003c|eom_id|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "514306": { + "content": "\u003c|python_tag|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563185": { + "content": "\u003c|startoftext|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563186": { + "content": "\u003c|endoftext|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563187": { + "content": "\u003c|reserved_200000|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563188": { + "content": "\u003c|reserved_200001|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563189": { + "content": "\u003c|return|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563190": { + "content": "\u003c|constrain|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563191": { + "content": "\u003c|reserved_200004|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563192": { + "content": "\u003c|channel|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563193": { + "content": "\u003c|start|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563194": { + "content": "\u003c|end|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563195": { + "content": "\u003c|message|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563196": { + "content": "\u003c|reserved_200009|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563197": { + "content": "\u003c|reserved_200010|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563198": { + "content": "\u003c|reserved_200011|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563199": { + "content": "\u003c|call|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563200": { + "content": "\u003c|reserved_200013|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563201": { + "content": "\u003c|reserved_200014|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563202": { + "content": "\u003c|reserved_200015|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563203": { + "content": "\u003c|reserved_200016|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563204": { + "content": "\u003c|reserved_200017|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + }, + "563205": { + "content": "\u003c|endofprompt|\u003e", + "lstrip": false, + "normalized": false, + "rstrip": false, + "single_word": false, + "special": true + } + }, + "bos_token": "\u003c|begin_of_text|\u003e", + "chat_template": "{% set loop_messages = messages %}{% for message in loop_messages %}{% set content = message['role'] | capitalize + ': '+ message['content'] | trim + '\u003c|eot_id|\u003e' %}{{ content }}{% endfor %}{% if add_generation_prompt %}{{ 'Assistant: ' }}{% endif %}", + "clean_up_tokenization_spaces": true, + "eos_token": "\u003c|eot_id|\u003e", + "model_input_names": [ + "input_ids", + "attention_mask" + ], + "model_max_length": 1000000000000000019884624838656, + "tokenizer_class": "PreTrainedTokenizerFast" +} \ No newline at end of file diff --git a/mvcc.js b/mvcc.js new file mode 100644 index 0000000000000000000000000000000000000000..b1bd13c8502c14519cd3c2bae889fb90e914d0cf --- /dev/null +++ b/mvcc.js @@ -0,0 +1,50 @@ +// Thought log with the same rule as WASMKV: a newer txn on a key replaces +// the older one, and a snapshot read ignores txns after `asOf`. +// onCommit sees every new record (persist.js writes them to IndexedDB); +// replay puts records back on load without calling it. + +const LIMIT = 800; + +export function createStore(opts) { + const onCommit = (opts && opts.onCommit) || null; + let head = 0; + const recs = []; + return { + head() { return head; }, + commit(page, key, value, limit) { + head += 1; + const rec = { page: String(page), key: String(key), txn: head, value: String(value).slice(0, limit || LIMIT) }; + recs.push(rec); + if (onCommit) onCommit(rec); + return head; + }, + replay(txn, page, key, value) { + const id = Number(txn); + if (id > head) head = id; + recs.push({ page: String(page), key: String(key), txn: id, value: String(value) }); + }, + read(page, key, asOf) { + const seen = asOf == null ? head : asOf; + let best = null; + for (const r of recs) { + if (r.page !== page || r.key !== key || r.txn > seen) continue; + if (!best || r.txn > best.txn) best = r; + } + return best ? best.value : null; + }, + // Every version of one key, oldest first. + history(page, key) { + return recs.filter((r) => r.page === page && r.key === key).sort((a, b) => a.txn - b.txn); + }, + scan(page, prefix, asOf) { + const seen = asOf == null ? head : asOf; + const map = new Map(); + for (const r of recs) { + if (r.page !== page || r.txn > seen || !r.key.startsWith(prefix)) continue; + const cur = map.get(r.key); + if (!cur || r.txn > cur.txn) map.set(r.key, r); + } + return [...map.values()].sort((a, b) => a.txn - b.txn); + }, + }; +} diff --git a/offscreen_script.js b/offscreen_script.js new file mode 100644 index 0000000000000000000000000000000000000000..d4375167083e2d57be806dcb6cd7f80e966f3cdc --- /dev/null +++ b/offscreen_script.js @@ -0,0 +1,258 @@ +(() => { +'use strict';var h,aa=typeof Object.defineProperties=="function"?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a},ba=function(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var b=0;b2){var d=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(e,d);return a.apply(b,e)}}return function(){return a.apply(b,arguments)}},q=function(a,b,c){q=Function.prototype.bind&&Function.prototype.bind.toString().indexOf("native code")!= +-1?ea:fa;return q.apply(null,arguments)},r=function(a,b){function c(){}c.prototype=b.prototype;a.B=b.prototype;a.prototype=new c;a.prototype.constructor=a;a.Da=function(d,e,f){for(var g=Array(arguments.length-2),l=2;l{a=c;b=d});this.resolve=a;this.reject=b}},x=class extends v{constructor(a,b="One or more errors occurred."){super(1,ha,b);this.errors=a;Object.setPrototypeOf(this,new.target.prototype)}flatten(){const a=[],b=[this.errors.slice(0)];for(;b.length!==0;){const c=b[0];for(;c.length!==0;){const d=c.shift();if(d instanceof x){b.unshift(d.errors.slice(0));break}else a.push(d)}b[0]===c&&b.shift()}return new x(a,this.message)}};var oa=class{constructor(){this.i=[]}subscribe(a){this.i.push(a)}unsubscribe(a){a=this.i.indexOf(a);if(a===-1)return!1;this.i.splice(a,1);return!0}publish(...a){const b=[],c=this.i.slice(0);for(const d of c)b.push(d(...a));return b}};const pa=Array.prototype.indexOf?function(a,b){return Array.prototype.indexOf.call(a,b,void 0)}:function(a,b){if(typeof a==="string")return typeof b!=="string"||b.length!=1?-1:a.indexOf(b,0);for(let c=0;ca}}publish(a){let b=this;for(;b;)b.i.forEach(c=>{c(a)}),b=b.parent}},C=function(a,b){var c=a.entries[b];if(c)return c;c=b.lastIndexOf(".");c=b.slice(0,Math.max(c,0));c=C(a,c);const d= +new Ba(b,c);a.entries[b]=d;c.children.push(d);return d},Ca=class{constructor(){this.entries={};const a=new Ba("");a.level=ta;this.entries[""]=a}},Da,D=function(){Da||(Da=new Ca);return Da},Fa=function(a){var b=Ea;b&&C(D(),b.getName()).i.push(a)},Ga=function(){var a=Ea;a&&(C(D(),a.getName()).level=ua)},E=function(a,b,c){var d;if(d=a)if(d=a&&b){d=b.value;var e=a?Aa(C(D(),a.getName())):A;d=d>=e.value}if(d){b=b||A;d=C(D(),a.getName());typeof c==="function"&&(c=c());xa||(xa=new wa);e=xa;a=a.getName(); +if(e.O>0){var f=(e.ha+1)%e.O;e.ha=f;e.ia?(e=e.ga[f],e.reset(b,c,a),a=e):(e.ia=f==e.O-1,a=e.ga[f]=new za(b,c,a))}else a=new za(b,c,a);a.R=void 0;d.publish(a)}}; + +function F(a){return a.toString().indexOf("`")===-1}F(a=>a``)||F(a=>a`\0`)||F(a=>a`\n`)||F(a=>a`\u0000`);"ARTICLE SECTION NAV ASIDE H1 H2 H3 H4 H5 H6 HEADER FOOTER ADDRESS P HR PRE BLOCKQUOTE OL UL LH LI DL DT DD FIGURE FIGCAPTION MAIN DIV EM STRONG SMALL S CITE Q DFN ABBR RUBY RB RT RTC RP DATA TIME CODE VAR SAMP KBD SUB SUP I B U MARK BDI BDO SPAN BR WBR NOBR INS DEL PICTURE PARAM TRACK MAP TABLE CAPTION COLGROUP COL TBODY THEAD TFOOT TR TD TH SELECT DATALIST OPTGROUP OPTION OUTPUT PROGRESS METER FIELDSET LEGEND DETAILS SUMMARY MENU DIALOG SLOT CANVAS FONT CENTER ACRONYM BASEFONT BIG DIR HGROUP STRIKE TT".split(" ").concat(["BUTTON", +"INPUT"]);var Ha=function(a){this.za=a||"";qa||(qa=new y);this.Ca=qa};h=Ha.prototype;h.fa=!0;h.ba=!0;h.ta=!0;h.Ba=!0;h.sa=!1;h.ua=!1;var G=function(a){return a<10?"0"+a:String(a)},Ia=function(a){Ha.call(this,a)};r(Ia,Ha); +var Ja=function(a,b){const c=[];c.push(a.za," ");if(a.ba){var d=new Date(b.ca);c.push("[",G(d.getFullYear()-2E3)+G(d.getMonth()+1)+G(d.getDate())+" "+G(d.getHours())+":"+G(d.getMinutes())+":"+G(d.getSeconds())+"."+G(Math.floor(d.getMilliseconds()/10)),"] ")}if(a.ta){d=c.push;var e=a.Ca.get();e=(b.ca-e)/1E3;let f=e.toFixed(3),g=0;if(e<1)g=2;else for(;e<100;)g++,e*=10;for(;g-- >0;)f=" "+f;d.call(c,"[",f,"s] ")}a.Ba&&c.push("[",b.Z,"] ");a.ua&&c.push("[",b.S.name,"] ");c.push(b.getMessage());a.sa&&(b= +b.R,b!==void 0&&c.push("\n",b instanceof Error?b.message:String(b)));a.fa&&c.push("\n");return c.join("")};function Ka(a=new Ia){a.ba=!0;a.ta=!1;a.ua=!0}var Na=class{constructor(a){this.name=a;this.target=C(D(),a).ka}log(a,b){E(this.target,a!=null?a:La,b)}error(a){E(this.target,ra,a)}warn(a){E(this.target,B,a)}info(a){E(this.target,sa,a)}debug(a){E(this.target,La,a)}trace(a){E(this.target,Ma,a)}},Ea=C(D(),"").ka,La=new z("DEBUG",600),Ma=new z("TRACE",100);va.push(La);va.push(Ma); + +// RPC sender — MessageServiceHost envelope for any component extension. +// Magic is packed-ASCII SECRPC (or another 6-byte key from RBIComponentRPC). +function rbiPackedMagic(id){ + try{var r=typeof self!=="undefined"?self:typeof window!=="undefined"?window:null; + if(r&&r.RBIComponentRPC&&r.RBIComponentRPC.magic)return r.RBIComponentRPC.magic(id); + if(r&&r.__RBI_SECRPC__)return r.__RBI_SECRPC__;}catch(x){} + return 91556947316803;} +function rbiPackedOurs(m){ + if(m===91556947316803)return true; + try{var r=typeof self!=="undefined"?self:typeof window!=="undefined"?window:null; + if(r&&r.RBIComponentRPC&&r.RBIComponentRPC.accepts(m))return true; + if(r&&r.RBIEvMojo&&r.RBIEvMojo.accepts(m))return true;}catch(x){} + return false;} +function rbiRPCMethods(){ + try{var r=typeof self!=="undefined"?self:typeof window!=="undefined"?window:null; + if(r&&r.RBIComponentRPC&&r.RBIComponentRPC.METHODS)return r.RBIComponentRPC.METHODS.slice()}catch(x){} + return "getAccounts hello getLogBuffer recordLog getQuirks updateQuirks uiEvent proxyUIEvent getProxyConfig".split(" ");} +function Oa(a,b,...c){ + return m(function*(){ + const d=new na, e={magic:rbiPackedMagic(), host:a!==null&&typeof a==="number"?"*":a, method:b, args:c}; + function pickSwTarget(){ + if(typeof navigator==="undefined"||!navigator.serviceWorker)return null; + if(navigator.serviceWorker.controller)return navigator.serviceWorker.controller; + const host=typeof window!=="undefined"?window:typeof self!=="undefined"?self:null; + const reg=host&&host.__RBI_EV_SW_REGISTRATION__; + if(reg&®.active)return reg.active; + if(reg&®.waiting){try{reg.waiting.postMessage({type:"SKIP_WAITING"})}catch(x){}return reg.waiting} + if(reg&®.installing)return reg.installing; + return null} + function trySwPost(){ + return new Promise((resolve,reject)=>{ + const target=pickSwTarget(); + if(!target){reject(new Error("Service Worker controller unavailable"));return} + const channel=new MessageChannel(); + let settled=!1; + const swBudget=b==="hello"?45000:25000; + const timer=setTimeout(()=>{if(settled)return;settled=!0;reject(new Error("SW RPC stall"))},swBudget); + channel.port1.onmessage=(event)=>{if(settled)return;settled=!0;clearTimeout(timer); + const g=event.data;g.error!==void 0?reject(Pa(g.error)):resolve(g.result!==void 0?g.result:g)}; + try{target.postMessage(e,[channel.port2])}catch(err){ + if(!settled){settled=!0;clearTimeout(timer);reject(err)}}})} + function trySend(id){ + const g=typeof window!=="undefined"?window:typeof self!=="undefined"?self:null; + const send=g&&g.__RBI_NATIVE_CHROME__&&g.__RBI_NATIVE_CHROME__.runtime&&g.__RBI_NATIVE_CHROME__.runtime.sendMessage; + if(!send||!send.__RBI_NATIVE_SEND_MESSAGE__)return Promise.reject(new Error("native sendMessage unavailable")); + return new Promise((resolve,reject)=>{function onResp(h){const j=chrome.runtime.lastError; + if(j){reject(new Error(j.message));return}if(h&&h.error!==void 0)reject(Pa(h.error)); + else resolve(h&&h.result!==void 0?h.result:h)} + try{if(id)send(id,e,onResp);else send(e,onResp)}catch(k){reject(k)}})} + function sendToTab(tabId){ + return new Promise((resolve,reject)=>{function onResp(h){const j=chrome.runtime.lastError; + if(j){reject(new Error(j.message));return}if(h&&h.error!==void 0)reject(Pa(h.error)); + else resolve(h&&h.result!==void 0?h.result:h)} + try{chrome.tabs.sendMessage(tabId,e,onResp)}catch(k){reject(k)}})} + function tryParentRelay(budget){ + return new Promise((resolve,reject)=>{const g=typeof window!=="undefined"?window:null; + if(!g||!g.parent||g.parent===g){reject(new Error("parent relay unavailable"));return} + const id="relay-"+Math.random().toString(36).slice(2);let settled=!1; + const timer=setTimeout(()=>{if(settled)return;settled=!0;g.removeEventListener("message",onRelay); + reject(new Error("parent EV relay timeout for "+b))},budget||45000); + function onRelay(ev){const d=ev.data||{}; + if(d.channel!=="rbi-ev-offscreen"||d.type!=="rpc-relay-result"||d.id!==id)return; + settled=!0;clearTimeout(timer);g.removeEventListener("message",onRelay); + if(d.ok)resolve(d.result);else reject(new Error(d.error||"parent relay failed"))} + g.addEventListener("message",onRelay); + try{g.parent.postMessage({channel:"rbi-ev-offscreen",type:"rpc-relay-request",id:id,method:e.method,args:e.args||[],timeoutMs:budget},location.origin||"*")} + catch(err){settled=!0;clearTimeout(timer);g.removeEventListener("message",onRelay);reject(err)}})} + const delays=[0,400,1200,2500,5000,9000];let lastErr=null; + const g=typeof window!=="undefined"?window:typeof self!=="undefined"?self:null; + const inChildFrame=g&&g.parent&&g.parent!==g; + const skipParentRelay=!!Oa.__skipParentRelay; + const skipSwRelay=!!Oa.__skipSwRelay; + const pg=g&&g.parent&&g.parent!==g?g.parent:null; + const portalMode=!!((g&&(g.__RBI_EV_COMPONENT__||g.__RBI_EV_LOG_CONSOLE_PAGE__||g.__RBI_EV_LOG_SERVICE__||g.__RBI_GOOGLE_EV_PRESENT__===false))||(pg&&(pg.__RBI_EV_COMPONENT__||pg.__RBI_EV_LOG_CONSOLE_PAGE__||pg.__RBI_EV_LOG_SERVICE__||pg.__RBI_GOOGLE_EV_PRESENT__===false))); + if(portalMode&&g&&g.__RBI_EV_SW_READY__){try{yield g.__RBI_EV_SW_READY__}catch(x){}} + for(let attempt=0;attempt0)yield new Promise(r=>setTimeout(r,delays[attempt])); + if(portalMode&&!skipSwRelay){ + try{ + if(typeof navigator!=="undefined"&&navigator.serviceWorker){ + d.resolve(yield trySwPost());return d.promise} + }catch(err){lastErr=err} + } + if(!portalMode){ + try{ + if(typeof chrome!=="undefined"&&chrome.runtime){ + if(chrome.runtime.id){d.resolve(yield trySend(null));return d.promise} + const ids=[]; + if(g&&g.__RBI_EV_EXTENSION_ID__)ids.push(g.__RBI_EV_EXTENSION_ID__); + ids.push("callobklhcbilhphinckomhgkigmfocg"); + const seen={}; + for(const id of ids){if(!id||seen[id])continue;seen[id]=!0; + try{d.resolve(yield trySend(id));return d.promise}catch(err){lastErr=err}} + try{d.resolve(yield trySend(null));return d.promise}catch(err){lastErr=err} + } + }catch(err){lastErr=err} + } + if(!portalMode){ + try{ + if(typeof navigator!=="undefined"&&navigator.serviceWorker&&navigator.serviceWorker.controller){ + d.resolve(yield trySwPost());return d.promise} + }catch(err){lastErr=err} + } + try{ + if(inChildFrame&&!skipParentRelay&&!portalMode){ + d.resolve(yield tryParentRelay(45000));return d.promise} + }catch(err){lastErr=err} + } + function __rbiEvStub(m,a){if(m==="hello")return{ok:!0,path:"portal_stub"};if(m==="getQuirks")return{simulated:!0,path:"portal_stub"};if(m==="recordLog")return{ok:!0,stub:!0};if(m==="getLogBuffer")return[];if(m==="getAccounts")return[];return{ok:!0,stub:!0,method:m}} + try{fetch("/api/rbi/ev-rpc",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:b,args:c||[],source:"offscreen_script"})}).then(function(r){return r.json()}).then(function(j){if(j&&j.result!==void 0)d.resolve(j.result);else d.resolve(__rbiEvStub(b,c))}).catch(function(){d.resolve(__rbiEvStub(b,c))})}catch(x){d.resolve(__rbiEvStub(b,c))} + return d.promise; + }()) +} + +function H(a){return a instanceof Error?a instanceof x?{type:3,errors:a.errors.map(H),message:a.message}:a instanceof v?{type:2,code:a.code,category:a.category.name,message:a.message}:{type:1,message:a.message||"Undefined error."}:{type:0,object:a}}function Pa(a){switch(a.type){case 0:return a.object;case 1:return Error(a.message);case 2:return new v(a.code,ma(a.category),a.message);case 3:return new x(a.errors.map(Pa),a.message)}};var Qa=class{constructor(){this.host="*";this.events=new Map;this.qa=new Map}invoke(a,...b){const c=this;return m(function*(){return Oa(c.host,a,...b)}())}};function Ra(a){function b(d){if(!d||d.length===0)return!1;var e=d.charCodeAt(0);if(!(e>=65&&e<=90||e>=97&&e<=122)&&e!==36&&e!==95)return!1;for(e=1;e=65&&f<=90||f>=97&&f<=122||f>=48&&f<=57)&&f!==36&&f!==95)return!1}return!0}const c=d=>{switch(typeof d){case "object":return d===null?"null":Array.isArray(d)?`[${d.map(c).join(", ")}]`:`{${Object.entries(d).map(([f,g])=>`${b(f)?f:`'${f}'`}: ${c(g)}`).join(", ")}}`;case "string":let e="";for(let f=0;f`New connection to '${b.name}'.`);const c=a.events.get(b.name);if(c){var d=c.J,e={port:b,H:()=>{a.log.trace(()=>`Data query for '${b.name}'.`);b.postMessage(c.data)},na:()=>{const f=d.findIndex(g=>g.port===b);f!==-1&&(a.log.trace(()=>`Port '${b.name}' disconnected.`),d.splice(f,1))}};b.onmessage = e.H; b.onmessageerror = e.na;d.push(e)}},Ta=function(a,b){a.v&&w(`Host ${a.name} is already open.`);a.i.fetch&&w("Handler for 'fetch' is already registered."); +a.log.trace(()=>"Registering 'fetch' handler.");a.i.fetch=b},Ua=function(a,b,c){a.v&&w(`Host ${a.name} is already open.`);a.events.get(b)&&w(`Event ${b} is already exposed.`);a.log.trace(()=>`Exposing event '${b}'.`);const d={event:c,u:(...e)=>{d.data=e;if(!d.Y){d.Y=!0;try{for(const f of d.J)try{f.port.postMessage(e)}catch(g){a.log.warn(`Post message to '${f.port.name}' failed. ${g.message}`)}}finally{d.Y=!1}}},J:[],Y:!1,data:[]};a.events.set(b,d)},Wa=function(a,b,c,d,e){if(c){a.log.trace(()=>`Handling '${a.name}:${String(d.method)}' from ${Ra(b)}...`); +try{const g=c(...d.args,b);if(g instanceof Promise)return Va(g,e),!0;var f={result:g}}catch(g){f={error:H(g)}}e(f);return!1}if(d.host!=="*"&&a.name!=="*"&&d.host===a.name)return a.log.error(`No handler for '${a.name}:${String(d.method)}'.`),c={error:H(new v(1,t,`No handler for '${a.name}:${String(d.method)}'.`))},e(c),!1},Va=function(a,b){m(function*(){let c;try{c={result:yield a}}catch(d){c={error:H(d)}}b(c)}())}, + +// Updated Receiver Host Class bound to standard Web API Message Events +Xa=class{ + constructor(){ + this.name="*"; + this.U=void 0; + this.i={}; + this.events=new Map; + this.v=!1; + this.log=new Na(`MessageServiceHost(${this.name})`); + + this.H = (event) => { + const source = event.source; + const data = event.data; + const sendResponse = (response) => { + if (event.ports && event.ports[0]) { + event.ports[0].postMessage(response); + } + }; + this.onRequest(source, data, sendResponse); + }; + } + + open(){ + const a=this;return m(function*(){ + a.v&&w(`Host ${a.name} is already open.`); + a.log.trace("Opening..."); + + if(typeof navigator!=='undefined' && navigator.serviceWorker){ + navigator.serviceWorker.addEventListener('message', a.H); + }else{ + a.log.warn("Service Worker APIs unavailable."); + } + + for(const b of a.events.values()) b.event.subscribe(b.u); + a.v=!0; + a.log.trace("Ready."); + }()) + } + + close(){ + const a=this;return m(function*(){ + a.v||w(`Host ${a.name} is already closed.`); + a.log.trace("Closing..."); + + if(typeof navigator!=='undefined' && navigator.serviceWorker){ + navigator.serviceWorker.removeEventListener('message', a.H); + } + + for(const b of a.events.values()){ + b.event.unsubscribe(b.u); + b.J.splice(0, b.J.length); + } + a.v=!1; + a.log.trace("Closed.") + }()) + } + + onRequest(a,b,c){ + if(b && (b.host==="*"||this.name==="*"||b.host===this.name)&&rbiPackedOurs(b.magic)){ + return Wa(this,a,this.i[b.method],b,d=>{if(c)try{c(d)}catch(e){this.log.warn(`sendResponse failed. ${e.message}.`)}}) + } + } +}; + +var Ya=function(){q(this.ea,this);this.F=new Ia;this.F.ba=!1;this.F.sa=!1;this.F.fa=!1;this.wa={}};Ya.prototype.ea=function(a){function b(e){if(e){if(e.value>=ra.value)return"error";if(e.value>=B.value)return"warn";if(e.value>=ta.value)return"log"}return"debug"}if(!this.wa[a.Z]){var c=Ja(this.F,a),d=Za;if(d){const e=b(a.S);$a(d,e,c,a.R)}}};var Za=n.console,$a=function(a,b,c,d){if(a[b])a[b](c,d===void 0?"":d);else a.log(c,d===void 0?"":d)};var I=function(){this.P=this.P;this.T=this.T};I.prototype.P=!1;I.prototype.dispose=function(){this.P||(this.P=!0,this.o())};I.prototype[Symbol.dispose]=function(){this.dispose()};I.prototype.o=function(){if(this.T)for(;this.T.length;)this.T.shift()()};var J=function(a,b){this.type=a;this.currentTarget=this.target=b;this.defaultPrevented=this.I=!1};J.prototype.stopPropagation=function(){this.I=!0};J.prototype.preventDefault=function(){this.defaultPrevented=!0};var ab=function(){if(!n.addEventListener||!Object.defineProperty)return!1;var a=!1,b=Object.defineProperty({},"passive",{get:function(){a=!0}});try{const c=()=>{};n.addEventListener("test",c,b);n.removeEventListener("test",c,b)}catch(c){}return a}();a:for(var bb=["CLOSURE_FLAGS"],cb=n,db=0;db0||M("Opera");L&&L.brands.length>0||M("Trident")||M("MSIE");M("Edge");!M("Gecko")||K().toLowerCase().indexOf("webkit")!=-1&&!M("Edge")||M("Trident")||M("MSIE")||M("Edge");var gb=K().toLowerCase().indexOf("webkit")!=-1&&!M("Edge");gb&&M("Mobile");N()||M("Macintosh");N()||M("Windows");(N()?L.platform==="Linux":M("Linux"))||N()||M("CrOS");N()||M("Android");fb();M("iPad");M("iPod");fb()||M("iPad")||M("iPod");K().toLowerCase().indexOf("kaios");function O(a,b){J.call(this,a?a.type:"");this.relatedTarget=this.currentTarget=this.target=null;this.button=this.screenY=this.screenX=this.clientY=this.clientX=this.offsetY=this.offsetX=0;this.key="";this.charCode=this.keyCode=0;this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1;this.state=null;this.pointerId=0;this.pointerType="";this.timeStamp=0;this.C=null;a&&this.init(a,b)}r(O,J); +O.prototype.init=function(a,b){const c=this.type=a.type,d=a.changedTouches&&a.changedTouches.length?a.changedTouches[0]:null;this.target=a.target||a.srcElement;this.currentTarget=b;b=a.relatedTarget;b||(c=="mouseover"?b=a.fromElement:c=="mouseout"&&(b=a.toElement));this.relatedTarget=b;d?(this.clientX=d.clientX!==void 0?d.clientX:d.pageX,this.clientY=d.clientY!==void 0?d.clientY:d.pageY,this.screenX=d.screenX||0,this.screenY=d.screenY||0):(this.offsetX=gb||a.offsetX!==void 0?a.offsetX:a.layerX,this.offsetY= +gb||a.offsetY!==void 0?a.offsetY:a.layerY,this.clientX=a.clientX!==void 0?a.clientX:a.pageX,this.clientY=a.clientY!==void 0?a.clientY:a.pageY,this.screenX=a.screenX||0,this.screenY=a.screenY||0);this.button=a.button;this.keyCode=a.keyCode||0;this.key=a.key||"";this.charCode=a.charCode||(c=="keypress"?a.keyCode:0);this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.pointerId=a.pointerId||0;this.pointerType=a.pointerType;this.state=a.state;this.timeStamp= +a.timeStamp;this.C=a;a.defaultPrevented&&O.B.preventDefault.call(this)};O.prototype.stopPropagation=function(){O.B.stopPropagation.call(this);this.C.stopPropagation?this.C.stopPropagation():this.C.cancelBubble=!0};O.prototype.preventDefault=function(){O.B.preventDefault.call(this);const a=this.C;a.preventDefault?a.preventDefault():a.returnValue=!1};var hb="closure_listenable_"+(Math.random()*1E6|0),P=function(a){return!(!a||!a[hb])};var ib=0;function jb(a,b,c,d,e){this.listener=a;this.proxy=null;this.src=b;this.type=c;this.capture=!!d;this.u=e;this.key=++ib;this.removed=this.N=!1}var Q=function(a){a.removed=!0;a.listener=null;a.proxy=null;a.src=null;a.u=null};function kb(a,b,c){for(const d in a)b.call(c,a[d],d,a)}function lb(a,b){for(const c in a)if(b.call(void 0,a[c],c,a))return!0;return!1}const mb="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function nb(a,b){let c,d;for(let e=1;e-1?(b=a[g],c||(b.N=!1)):(b=new jb(b,this.src,f,!!d,e),b.N=c,a.push(b));return b};R.prototype.remove=function(a,b,c,d){a=a.toString();if(!(a in this.g))return!1;const e=this.g[a];b=ob(e,b,c,d);return b>-1?(Q(e[b]),Array.prototype.splice.call(e,b,1),e.length==0&&(delete this.g[a],this.K--),!0):!1}; +var pb=function(a,b){const c=b.type;if(c in a.g){var d=a.g[c],e=pa(d,b),f;(f=e>=0)&&Array.prototype.splice.call(d,e,1);f&&(Q(b),a.g[c].length==0&&(delete a.g[c],a.K--))}};R.prototype.removeAll=function(a){a=a&&a.toString();let b=0;for(const c in this.g)if(!a||c==a){const d=this.g[c];for(let e=0;e-1?a[e]:null}; +R.prototype.hasListener=function(a,b){const c=a!==void 0,d=c?a.toString():"",e=b!==void 0;return lb(this.g,function(f){for(let g=0;g>>0),S=function(a){if(typeof a==="function")return a;a[Ab]||(a[Ab]=function(b){return a.handleEvent(b)});return a[Ab]};function V(a){I.call(this);this.X=a;this.A={}}r(V,I);var Bb=[];V.prototype.listen=function(a,b,c,d){Array.isArray(b)||(b&&(Bb[0]=b.toString()),b=Bb);for(let e=0;e=0;g--)f=a.currentTarget=c[g],e=X(f,d,!0,a)&&e;a.I||(f=a.currentTarget=b,e=X(f,d,!0,a)&&e,a.I||(e=X(f,d,!1,a)&&e));if(c)for(g=0;!a.I&&gf.has(g)))return c}c={};for(const d of b)Object.defineProperty(c,d,{value:(...e)=>a.invoke(d,...e),writable:!1});a.qa.set(new Set(b),c);return c}(); +function Fb(){Ga();const a=new Ya;Ka(a.F);Fa(c=>{const d=c.S;d&&d.value>=B.value&&a.ea(c)});let b=!1;Fa(c=>{if(!b){b=!0;try{var d=Db.recordLog;var e={t:c.ca,l:c.S.value,m:c.getMessage(),n:c.Z,s:c.Aa};d.call(Db,e)}catch(f){}finally{b=!1}}})}const Z=new Na("Offscreen Script"); +var Gb=function(a){return m(function*(){var b=new Headers;if(a.headers)for(const [e,f]of Object.entries(a.headers))b.set(e,f);a.request.headers=b;Z.debug(`Sending Fetch request to ${a.url}.`);let c;try{c=yield fetch(a.url,a.request)}catch(e){throw Z.debug(`Fetch request to ${a.url} failed. ${e.message}`),e;}b=yield c.text();Z.debug(`Fetch request to ${a.url} ${c.ok?"succeeded":"failed"}. Response: ${JSON.stringify(JSON.parse(b))}`);const d={};for(const [e,f]of c.headers.entries())d[e]=f;return{ok:c.ok, +status:c.status,statusText:c.statusText,headers:d,text:b}}())};class Hb{constructor(){this.host=new Xa;this.pa=new Y;this.oa=new oa;this.la=new oa}initialize(){const a=this;return m(function*(){Ua(a.host,"network:online",a.oa);Ua(a.host,"network:offline",a.la);Ta(a.host,b=>m(function*(){return Gb(b)}()));try{var r=typeof self!=="undefined"?self:typeof window!=="undefined"?window:null;if(r&&r.RBIComponentRPC&&r.RBIComponentRPC.bindHost)r.RBIComponentRPC.bindHost(a.host)}catch(x){}yield a.host.open();a.pa.listen("online",()=>{Z.debug("Online event received");a.oa.publish()});a.pa.listen("offline",()=>{Z.debug("Offline event received");a.la.publish()})}())}} + +Fb(); +(new Hb).initialize(); +const __RBI_EV_LOG_RELAY__=(()=>{const MAX=1200;const state={port:null,buffer:[],seen:new Set(),lastIndex:0,pollTimer:null,streamed:!1}; +function key(e){try{return JSON.stringify(e)}catch(x){return String(e&&e.m?e.m:e)}} +function push(entries){const list=Array.isArray(entries)?entries:[entries];list.forEach(e=>{if(!e)return;const k=key(e);if(state.seen.has(k))return;state.seen.add(k);state.buffer.push(e);if(state.seen.size>MAX*2)state.seen.clear();while(state.buffer.length>MAX)state.buffer.shift()}); +broadcast(list)} +function broadcast(entries){const g=typeof window!=="undefined"?window:typeof self!=="undefined"?self:null;if(!g||!g.parent||g.parent===g)return; +try{g.parent.postMessage({channel:"rbi-ev-offscreen",type:"log-record",entries,path:"offscreen_log_relay",at:new Date().toISOString()},location.origin||"*")}catch(e){}} +function nativeRuntime(){const g=typeof window!=="undefined"?window:typeof self!=="undefined"?self:null;if(!g)return null;if(g.__RBI_NATIVE_CHROME__&&g.__RBI_NATIVE_CHROME__.runtime)return g.__RBI_NATIVE_CHROME__.runtime;return null} +function connectLogRecord(){const rt=nativeRuntime();if(!rt||!rt.connect||state.port)return state.streamed; +try{const port=rt.connect({name:"log:record"});state.port=port;state.streamed=!0;port.onMessage.addListener(msg=>{push(Array.isArray(msg)?msg:[msg])}); +port.onDisconnect.addListener(()=>{state.port=null;state.streamed=!1;setTimeout(connectLogRecord,1500)})}catch(e){} +return state.streamed} +function pollBuffer(){return Db.getLogBuffer().then(buf=>{if(!Array.isArray(buf))return buf;if(buf.length[])} +function start(opts){opts=opts||{};connectLogRecord();return pollBuffer().then(buf=>{if(state.pollTimer)clearInterval(state.pollTimer); +state.pollTimer=setInterval(()=>{pollBuffer().catch(()=>{})},opts.pollMs||8000);return{streamed:state.streamed,buffer_lines:Array.isArray(buf)?buf.length:0,path:"offscreen_log_relay"}})} +function snapshot(){return state.buffer.slice()} +return{start,connectLogRecord,pollBuffer,snapshot,get streamed(){return state.streamed}}})(); +const __RBI_EV_OFFSCREEN_AGENT__=(()=>{const methods=rbiRPCMethods(); +const api={MAGIC:rbiPackedMagic(),path:"offscreen_script",invoke:(method,args)=>{const fn=Db[method];if(typeof fn!=="function")return Promise.reject(new Error("unknown EV RPC: "+method)); +return Promise.resolve(fn.apply(Db,args||[]))},probe:()=>api.invoke("hello",[]).then(hello=>api.invoke("getQuirks",[]).then(quirks=>({ok:!0,hello,quirks,agent:"offscreen_script"})).catch(err=>({ok:!0,hello,quirks_error:String(err),agent:"offscreen_script"}))).catch(err=>({ok:!1,error:String(err&&err.message?err.message:err),agent:"offscreen_script"})), +startLogRelay:(opts)=>__RBI_EV_LOG_RELAY__.start(opts),logSnapshot:()=>__RBI_EV_LOG_RELAY__.snapshot()}; +methods.forEach(m=>{api[m]=(...args)=>api.invoke(m,args)});return api})(); +const g=typeof self!=="undefined"?self:typeof window!=="undefined"?window:null; +if(g){g.__RBI_EV_OFFSCREEN_AGENT__=__RBI_EV_OFFSCREEN_AGENT__;g.__RBI_EV_LOG_RELAY__=__RBI_EV_LOG_RELAY__;g.__RBI_EV_OFFSCREEN_INJECTED__=!0; +if(g.parent&&g.parent!==g){try{g.parent.postMessage({channel:"rbi-ev-offscreen",type:"ready",agent:"offscreen_script"},location.origin||"*")}catch(e){}} +if(typeof g.addEventListener==="function"){g.addEventListener("message",function(ev){const data=ev.data||{}; +if(data.channel!=="rbi-ev-offscreen"||!data.type)return; +if(data.type==="rpc"&&data.id){Oa.__skipParentRelay=!0;Oa.__skipSwRelay=!0;__RBI_EV_OFFSCREEN_AGENT__.invoke(data.method,data.args||[]).then(result=>{Oa.__skipParentRelay=!1;Oa.__skipSwRelay=!1;const reply={channel:"rbi-ev-offscreen",type:"rpc-result",id:data.id,ok:!0,result}; +if(ev.source&&ev.source.postMessage)ev.source.postMessage(reply,ev.origin||"*")}).catch(err=>{Oa.__skipParentRelay=!1;Oa.__skipSwRelay=!1;const reply={channel:"rbi-ev-offscreen",type:"rpc-result",id:data.id,ok:!1,error:String(err&&err.message?err.message:err)}; +if(ev.source&&ev.source.postMessage)ev.source.postMessage(reply,ev.origin||"*")});return} +if(data.type==="log-start"){__RBI_EV_LOG_RELAY__.start(data.opts||{}).then(out=>{if(ev.source&&ev.source.postMessage)ev.source.postMessage({channel:"rbi-ev-offscreen",type:"log-started",id:data.id,ok:!0,out},ev.origin||"*")}).catch(err=>{if(ev.source&&ev.source.postMessage)ev.source.postMessage({channel:"rbi-ev-offscreen",type:"log-started",id:data.id,ok:!1,error:String(err&&err.message?err.message:err)},ev.origin||"*")});return} +if(data.type==="log-snapshot"&&data.id){if(ev.source&&ev.source.postMessage)ev.source.postMessage({channel:"rbi-ev-offscreen",type:"log-snapshot",id:data.id,entries:__RBI_EV_LOG_RELAY__.snapshot()},ev.origin||"*")}})} +function __rbiStartOffscreenAgent(){return __RBI_EV_OFFSCREEN_AGENT__.invoke("hello",[]).then(()=>__RBI_EV_LOG_RELAY__.start({pollMs:8000})).catch(()=>{})} +g.__RBI_EV_OFFSCREEN_START__=__rbiStartOffscreenAgent; +if(!g.__RBI_EV_OFFSCREEN_HOLD_INIT__)__rbiStartOffscreenAgent()} +})(); \ No newline at end of file diff --git a/persist.js b/persist.js new file mode 100644 index 0000000000000000000000000000000000000000..754041c4fefdf01fcd23a96a8cf08d8bb9311782 --- /dev/null +++ b/persist.js @@ -0,0 +1,55 @@ +// The MVCC log on this device: every record mind commits is appended to +// IndexedDB ("champ" / "mvcc", keyed by txn) and replayed on load, so chats, +// their summaries and learned notes survive a reload. Without IndexedDB +// (private window, blocked storage) the page still works for this visit. + +const DB = "champ"; +const STORE = "mvcc"; + +function openDB() { + return new Promise((resolve) => { + let req; + try { req = indexedDB.open(DB, 1); } catch { resolve(null); return; } + req.onupgradeneeded = () => req.result.createObjectStore(STORE, { keyPath: "txn" }); + req.onsuccess = () => resolve(req.result); + req.onerror = () => resolve(null); + req.onblocked = () => resolve(null); + }); +} + +export function createLog() { + let db = null; + let queue = []; + const ready = openDB().then((d) => { + db = d; + const pending = queue; + queue = null; + if (db) for (const rec of pending) write(rec); + }); + function write(rec) { + if (!db) { + if (queue) queue.push(rec); + return; + } + try { db.transaction(STORE, "readwrite").objectStore(STORE).put(rec); } catch { /* storage full or closed */ } + } + return { + ready, + onCommit(rec) { write(rec); }, + // Replays every saved record into mind, in txn order. + async load(mind) { + await ready; + if (!db) return 0; + const recs = await new Promise((resolve) => { + try { + const req = db.transaction(STORE, "readonly").objectStore(STORE).getAll(); + req.onsuccess = () => resolve(req.result || []); + req.onerror = () => resolve([]); + } catch { resolve([]); } + }); + recs.sort((a, b) => a.txn - b.txn); + for (const r of recs) mind.replay(r.txn, r.page, r.key, r.value); + return recs.length; + }, + }; +} diff --git a/router.js b/router.js new file mode 100644 index 0000000000000000000000000000000000000000..f5c834c91868956fcad4d2c9fbc8d2c57a082215 --- /dev/null +++ b/router.js @@ -0,0 +1,423 @@ +// Champ's router between models and tools, laid out as jev_mesh_2x2 +// (shuttle-repos/jev-mesh-2x2-sky130a): four engines on a 2x2 grid and the die's three ROM tables. +// +// col 0 (small) col 1 (large) +// row 0 e0_0 Lite e0_1 Balanced +// row 1 e1_0 Thinking e1_1 Pro+Think row 1 thinks first +// +// A beat is one thing offered to the router, with the die's four kinds: +// 0 chat (activation) a message for an engine +// 1 tool (weight) a tool's result, loaded into the engine's context +// 2 reload a model switch: the engine's context is cleared, the continuity chain stays +// 3 fence the end of a turn +// +// The gate is the MoE gate of the monodromy note (Encryptid/monodromy/paper): the message gives two +// Bernoulli bits, think (row) and size (col), and their products are the four engines' full +// probabilities (they sum to 1). Top-1 as in Switch Transformers; engines the server does not have +// drop out and the kept gates are renormalized as in GShard. Switching models has a capacity: a +// message whose winner beats the loaded engine by less than CAPACITY follows the residual and stays on +// the loaded engine. The continuity chain (chats.gather) is the shared expert every engine sees. +// A tool's result is admitted into the context as hodgemix --update admits an expert: only when it +// moves the same way as the question (positive cosine); otherwise it stays on its card. + +export const ENGINES = [ + { tier: "lite", label: "Lite", row: 0, col: 0 }, + { tier: "balanced", label: "Balanced", row: 0, col: 1 }, + { tier: "thinking", label: "Thinking", row: 1, col: 0 }, + { tier: "pro", label: "Pro+Think", row: 1, col: 1 }, +]; +export const TIERS = new Set(ENGINES.map((e) => e.tier)); +export const KIND = { chat: 0, tool: 1, reload: 2, fence: 3 }; + +// jev_route: {full, kind} -> action. The die's ROM, states 0 to 7. +// stage run on the engine load load into the engine's context +// reset clear the engine pass send it on (to the card, the chain) +export const ROUTE = ["stage", "load", "reset", "pass", "stage", "pass", "reset", "pass"]; +export function route(full, kind) { + return ROUTE[(full ? 4 : 0) | (kind & 3)]; +} + +// jev_accept: take or stall. A tool beat is taken when offered; a chat beat when the queue has room +// and the engine can take it (loaded, idle); a reload or fence when the queue has room. +export const DEPTH = 2; +export function accept(kind, s) { + const room = (s.queue || 0) < DEPTH; + if (kind === KIND.tool) return "take"; + if (kind === KIND.chat) return room && !s.busy && !s.loading ? "take" : "stall"; + return room ? "take" : "stall"; +} + +// jev_join: hold or emit. Emit on the clock where the engine's result, the west partials (the +// continuity chain carried into this engine) and east room (a place on the page) are all present. +export const JOIN = ["hold", "hold", "hold", "hold", "hold", "hold", "hold", "emit"]; +export function join(result, partials, room) { + return JOIN[(result ? 1 : 0) | (partials ? 2 : 0) | (room ? 4 : 0)]; +} + +// ---- the two bits + +// A bare "why" (0.1 + 0.25) stays under THINK_AT: "why is the sky blue" is a +// fact to look up, not a chain. "why" with any other cue still thinks. +const THINK = [ + [/\b(why|how come)\b/i, 0.25, "asks why"], + [/\b(prove|proof|derive|reason(?:ing)?|step[- ]by[- ]step|work (?:it )?out|think (?:it )?through)\b/i, 0.35, "reasoning"], + [/\b(compare|trade-?offs?|pros and cons|plan|strategy|debug|diagnose|analy[sz]e|evaluate|solve|calculate|estimate|what if)\b/i, 0.3, "analysis"], + [/\d\s*[-+*/^×÷=]\s*\d|\b(integral|derivative|equation|theorem|probability|algorithm)\b/i, 0.3, "math"], + [/```|\b(function|stack trace|exception|compile|regex|sql|segfault)\b/i, 0.25, "code"], +]; +const SIZE = [ + [/\b(detailed|thorough|in depth|comprehensive|essay|report|article|story|chapter|full|complete)\b/i, 0.3, "long form"], + [/\b(architecture|design|system|protocol|specification|research|paper|explain)\b/i, 0.2, "broad"], + [/https?:\/\//i, 0.1, "a page"], +]; +const PLAIN = /^(hi|hey|hello|thanks|thank you|ok|okay|yes|no|sure|cool|nice|good (?:morning|night|evening))\b[\s!.,?]*$/i; + +// Same line think.js uses to open a chain. A logic gap at or above this +// selects the thinking engine when the catalog has one. +export const THINK_AT = 0.4; + +const LOGIC_GAP = /\b(logic gaps?|does(?:n'?t| not) follow|contradict(?:s|ion)?|missing step|non\s*sequitur)\b/i; +const INFO_GAP = /\b(latest|current|right now|as of|news|headline|weather|forecast|price|cost|score|standing|election|governor|president|population|capital|who is|who was|who are|what is|what was|what are|when did|when was|when is|where is|where was|where are|which|how (?:does|do|did)|why (?:did|was|is|are))\b/i; +// A recipe stays with the model. A page about the dish is the author's story, not the method. +const RECIPE = /\b(?:recipes?)\b|\bhow to (?:make|cook|bake|fry|roast|prepare)\b/i; +const FACT_CUE = /\b(?:search|research|look\s*up|lookup|facts?|causes?|effects?|history|impact)\b|\b(?:provide|cite|with)\s+sources?\b|\b(?:tell me about|write about|essay about)\b|\bdescribe\b(?!\s+how\b)/i; +const FICTION = /\b(?:story|poem|poems|joke|jokes|haiku|limerick|fiction)\b/i; +const CODE_OR_MATH = /\b(?:prove|proof|derive|function|stack trace|exception|compile|regex|sql|segfault|integral|derivative|equation|theorem|probability|algorithm)\b|\d\s*[-+*/^×÷=]\s*\d/i; +const ARITHMETIC = /^\s*what(?:'s| is)?\s+\d[\d\s+\-*/^=().]*\??\s*$/i; +const ABOUT_SELF = /^\s*(who are you|what(?:'s| is) your name)\b/i; + +// One engine. News, weather, and prices are a web search. A stable fact is +// Wikipedia. The other engines were adding pages about a different subject. +export const GAP_SOURCES = [ + { source: "wiki", label: "Wikipedia" }, + { source: "duckduckgo", label: "DuckDuckGo" }, + { source: "duck", label: "duck.ai" }, + { source: "gemini", label: "Gemini" }, +]; +const LIVE = /\b(?:news|headlines?|breaking|latest|today|tonight|this morning|right now|weather|forecast|scores?|standings?|prices?|cost)\b/i; + +export function sourceFor(text) { + if (LIVE.test(String(text || ""))) return GAP_SOURCES[1]; + return GAP_SOURCES[0]; +} +// The two search engines take the subject (searchQuery). duck.ai and Gemini answer the question as asked. +export const SUBJECT_SOURCES = new Set(["wiki", "duckduckgo"]); + +// A request to write fiction is not a question, even when it says "a dragon who is afraid". +const CREATIVE = /^\s*(?:please\s+)?(?:write|tell|compose|make up|create|draft|give me)\b.{0,40}\b(?:story|stories|poem|poems|joke|jokes|haiku|limerick|fiction|song|fable|tale)\b/i; + +export function infoGap(text) { + const t = String(text || "").trim(); + if (!t || PLAIN.test(t) || ABOUT_SELF.test(t) || ARITHMETIC.test(t) || CREATIVE.test(t) || RECIPE.test(t)) return false; + return INFO_GAP.test(t); +} + +// A fact is grounded, then searched, before the write: an information gap, a +// fact cue, or a picked search tool. Anything else is answered by the model +// alone. A lookup the question did not need hands a small model an unrelated +// snippet it is then told to answer from, which is where it starts inventing. +export function needsFacts(text, opts) { + const o = opts || {}; + const t = String(text || "").trim(); + if (!t || PLAIN.test(t) || ABOUT_SELF.test(t) || ARITHMETIC.test(t) || RECIPE.test(t)) return false; + if ((o.picks || []).includes("search") || infoGap(t)) return true; + if (FICTION.test(t) || CODE_OR_MATH.test(t)) return false; + return FACT_CUE.test(t); +} + +const clamp = (x) => Math.max(0, Math.min(1, x)); + +// features: the think and size probabilities of a message, and the cues that set them. +export function features(text, opts) { + const o = opts || {}; + const t = String(text || "").trim(); + const cues = []; + let think = 0.1; + let size = 0.1; + if (PLAIN.test(t)) return { think: 0.02, size: 0.02, cues: ["plain"] }; + for (const [re, w, cue] of THINK) if (re.test(t)) { think += w; cues.push(cue); } + for (const [re, w, cue] of SIZE) if (re.test(t)) { size += w; cues.push(cue); } + const words = t ? t.split(/\s+/).length : 0; + if (words > 60) { size += 0.25; cues.push(words + " words"); } + else if (words > 25) size += 0.12; + const asks = (t.match(/\?/g) || []).length; + if (asks > 1) { think += 0.15; size += 0.1; cues.push(asks + " questions"); } + const lines = t.split(/\n/).filter((l) => /^\s*(?:[-*]|\d+[.)])\s+/.test(l)).length; + if (lines > 2) { size += 0.15; cues.push(lines + " parts"); } + if (o.think) { think = Math.max(think, 0.9); cues.push("Think on"); } + if (LOGIC_GAP.test(t)) { think = Math.max(think, 0.75); cues.push("logic gap"); } + if (infoGap(t)) cues.push("information gap"); + return { think: clamp(think), size: clamp(size), cues }; +} + +function planQuery(text) { + return String(text || "").replace(/\s+/g, " ").trim().slice(0, 180); +} + +// A search engine wants the subject, not the conversation around it: "Tell me +// about the history of the printing press" found "The Tell-Tale Heart" on +// Wikipedia, and "the history of the printing press" finds "Printing press". +const LEAD_IN = /^(?:(?:please|hey|ok(?:ay)?)[,\s]+)?(?:(?:can|could|would) you\s+)?(?:research|search(?:\s+for)?|look\s*up|lookup|tell me(?:\s+about)?|explain(?:\s+to me)?|describe|give me(?:\s+an?\s+(?:overview|summary)\s+of)?|i (?:want|would like) to know(?:\s+about)?|what(?:'s| is| are| was| were)|who(?:'s| is| are| was| were)|when (?:is|was|did|does)|where (?:is|are|was|were)|why (?:is|are|was|were|do|does|did)|how (?:do|does|did|can|to)(?:\s+(?:i|you|we|they|one))?)\s+/i; + +export function searchQuery(text) { + const raw = planQuery(text); + let q = raw; + for (let i = 0; i < 3; i++) { + const next = q.replace(LEAD_IN, "").replace(/^(?:how|what|why)\s+/i, ""); + if (next === q) break; + q = next; + } + q = q.replace(/[\s?.!]+$/, "").trim(); + q = q.replace(/^(?:(?:a|an)\s+)?(?:(?:formatted|simple|easy|basic|quick)\s+)?(?:recipes?|instructions?)(?:\s+(?:for|of|to(?:\s+make)?))?\s+/i, ""); + return (q || raw).slice(0, 120); +} + +// The think pass. The model names the route. The person's wording is not a list. +export const THINK_SYSTEM = "Think about what this question is asking for. Do not answer it. " + + "Reply with one word and nothing else.\n" + + "fact — a checkable fact a reference page can settle, such as a place, a person, who holds an office, a capital, a date, a price, the news, or the weather.\n" + + "recipe — they want to cook a dish. You know the ingredients and the method. A page about the dish is the author's story, not the recipe.\n" + + "command — they want a command run, or a file listed, in the guest.\n" + + "talk — you answer it yourself: a meaning, an opinion, a story, code, a greeting, math, or anything that is not a checkable fact."; + +export const RECIPE_SYSTEM = "Write the ingredients and the method. Use plain sentences. Start with the ingredients. A label is not the answer."; +export const FACT_SYSTEM = "Answer the question the person asked. Use the notes. A label is not the answer."; + +const ROUTES = new Set(["fact", "recipe", "command", "talk"]); + +function knownRoute(s) { + const w = String(s || "").toLowerCase().replace(/^[`*_"'.:!]+|[`*_"'.:!]+$/g, ""); + return ROUTES.has(w) ? w : ""; +} + +function labelLine(s) { + const fields = String(s || "").trim().split(/\s+/).filter(Boolean); + if (fields.length === 2 && fields[0].replace(/:$/i, "").toLowerCase() === "route") return knownRoute(fields[1]); + if (fields.length !== 1) return ""; + return knownRoute(fields[0]); +} + +// Named reports that the think pass put a route word on its own line. +export function named(thought) { + return String(thought || "").split(/\n/).some((line) => labelLine(line)); +} + +// A dish the model answers instead of naming. A page about the dish is not the method. +const COOK = /\b(?:recipes?)\b|\bhow (?:do i |to )?(?:make|cook|bake|fry|roast|prepare)\b/i; + +// factWhenUnnamed is modelrun's fallback. A named route stands, including talk. +// A pass that starts the answer, and never names a route, still looks up a +// checkable question. A recipe stays with the model. +export function factWhenUnnamed(question, thought) { + if (named(thought)) return false; + const q = String(question || "").trim(); + if (!q || COOK.test(q)) return false; + return needsFacts(q); +} + +// routeOf reads the route word. A reflection that never names one is talk. +export function routeOf(thought) { + for (const line of String(thought || "").split(/\n/)) { + const route = labelLine(line); + if (route) return route; + } + return "talk"; +} + +// Every reply is a plan. The route word decides it. fact is one lookup, then +// the model writes. recipe, command, and talk are the model alone. A word +// such as "recipe" in the question does not start a lookup. +export function planOf(text, opts) { + const o = opts || {}; + const t = String(text || "").trim(); + const route = ROUTES.has(o.route) ? o.route : "talk"; + const picked = (o.picks || []).includes("search"); + const search = route === "fact" || (picked && route !== "recipe"); + if (PLAIN.test(t) && !o.think && !search) { + return { info: false, logic: false, plain: true, think: false, search: false, route, steps: [{ kind: "model", role: "write" }] }; + } + const f = features(t, { think: o.think }); + const info = search; + const logic = route !== "recipe" && (!!o.think || f.think >= THINK_AT); + const steps = []; + if (search) { + const src = sourceFor(t); + const q = SUBJECT_SOURCES.has(src.source) ? searchQuery(t) : planQuery(t); + steps.push({ kind: "tool", tool: "search", source: src.source, label: src.label, args: { q, source: src.source } }); + } + if (logic) steps.push({ kind: "model", role: "reason" }); + steps.push({ kind: "model", role: "write" }); + const plain = steps.length === 1 && !search; + const system = route === "recipe" ? RECIPE_SYSTEM : search ? FACT_SYSTEM : ""; + return { info, logic, plain, think: logic, search, route, system, steps }; +} + +// gate: every engine's probability, p(row) * p(col). +export function gate(f) { + return ENGINES.map((e) => (e.row ? f.think : 1 - f.think) * (e.col ? f.size : 1 - f.size)); +} + +// The gate picks a model only. It does not change how a token is sampled: the +// guest samples at the model's own temperature and top-p. (An earlier build +// turned the idle gates into a stacking presence penalty and a per-token +// temperature lottery; the penalty counted the prompt's end-of-turn tokens and +// held answers open past their end.) + +// A loop is a long span said twice. The page cuts the second copy and stops +// the sample. Shorter repeats stay: a long answer's conclusion restates its +// opening ("vaccines work by preparing the immune system to fight", 54 +// characters), and a 48-character trigger cut that conclusion off. +const NUCLEUS_MIN = 100; +// An immediate refrain is the same phrase said again with only punctuation +// or a short glue word between the copies. The window meets the long-span +// cut, so one repeated sentence is not left between 80 and 100 characters. +// A conclusion that restates an opening much later is not one: the copies +// have to sit against each other. +const REFRAIN_MIN = 18; +const REFRAIN_GAP = 24; +const REFRAIN_MAX = NUCLEUS_MIN - 1; +function shortGap(gap) { + return gap === "" || /^[\s,;:.!?'"()\-–—]*(?:(?:and|or|the|a|an|into|of)\s+)?$/i.test(gap); +} +export function refrainSpan(text) { + const s = String(text || ""); + const n = s.length; + if (n < REFRAIN_MIN * 2) return ""; + const max = Math.min(REFRAIN_MAX, Math.floor((n - 1) / 2)); + for (let len = max; len >= REFRAIN_MIN; len--) { + const span = s.slice(n - len); + if (span.trim().length < REFRAIN_MIN) continue; + // The period that ends one copy is the start of ". " plus the next copy. + // That match overlaps itself. Keep looking for a copy that ends first. + let prev = s.lastIndexOf(span, n - len - 1); + while (prev >= 0 && prev + len > n - len) { + if (prev === 0) { prev = -1; break; } + prev = s.lastIndexOf(span, prev - 1); + } + if (prev < 0) continue; + const gap = s.slice(prev + len, n - len); + if (gap.length > REFRAIN_GAP || !shortGap(gap)) continue; + return span; + } + return ""; +} +// A capitalized pair said again immediately ("East Berlin into East Berlin"). +function nameRefrain(text) { + const s = String(text || ""); + const m = /([A-Z][A-Za-z'-]{1,})\s+([A-Z][A-Za-z'-]{1,})[\s,;:.!?]*$/.exec(s); + if (!m) return ""; + const pair = m[1] + " " + m[2]; + if (pair.length < 8) return ""; + const prev = s.lastIndexOf(pair, m.index - 1); + // The same pair is not a copy of itself. "Ellicott City." is the answer, + // and a search from before it still finds that one occurrence. + if (prev < 0 || prev + pair.length > m.index) return ""; + const gap = s.slice(prev + pair.length, m.index); + if (gap.length > REFRAIN_GAP || !shortGap(gap)) return ""; + return s.slice(m.index); +} +export function repeatedSpan(text) { + const s = String(text || ""); + const n = s.length; + if (n < NUCLEUS_MIN * 2) return ""; + const max = Math.min(400, Math.floor(n / 2)); + for (let len = max; len >= NUCLEUS_MIN; len--) { + const span = s.slice(n - len); + if (span.trim().length < NUCLEUS_MIN) continue; + if (s.lastIndexOf(span, n - len - 1) >= 0) return span; + } + return ""; +} + +// Drops the repeated copy. on 0 leaves the text alone. +export function nucleusCut(text, on) { + const s = String(text || ""); + if (!(Number(on) > 0)) return s; + const span = repeatedSpan(s) || refrainSpan(s) || nameRefrain(s); + if (!span) return s; + let at = s.length - span.length; + // A span can start mid-word. Cut at the word's start so no half word is left. + while (at > 0 && /\w/.test(s[at - 1]) && /\w/.test(s[at])) at--; + const kept = s.slice(0, at).replace(/\s+$/, ""); + // A source list quotes lines that were already said. Keep that list. Rolling + // back to the previous sentence was ending the answer on "Sources: 1." + if (/\bSources:\s/i.test(kept)) return kept.replace(/[,;:]+$/, ""); + // A loop usually starts inside a sentence. End on the last whole sentence + // when one is near, so the reply does not stop on a dangling clause. + // A numbered marker ("1.") is not the end of a sentence. + const tail = kept.slice(-400); + const m = /[\s\S]*[^.!?\d][.!?]["')\]]?(?=\s|$)|[\s\S]*\n/.exec(tail); + if (m && m[0].trim()) return (kept.slice(0, kept.length - tail.length) + m[0]).replace(/\s+$/, ""); + return kept.replace(/[,;:]+$/, ""); +} + +// ---- tools: strong cues only; the + picks always win + +const TOOL_CUES = [ + ["notes", /\b(save|write|keep|put)\b.{0,40}\b(note|notes)\b|\bmy notes\b/i], + ["tasks", /\b(add|create|make)\b.{0,30}\b(task|to-?do)\b|\bmy (tasks|to-?do list)\b|\bmark\b.{0,30}\bdone\b/i], + ["canvas", /\b(draw|sketch|diagram)\b|\bcanvas\b/i], + ["exec", /\brun\b.{0,20}\b(command|script|code|this)\b|^\s*\$\s+\S/i], + ["gather", /\b(read|open|summari[sz]e|look at)\b.{0,40}https?:\/\//i], +]; + +export function toolsFor(text, picks) { + const out = [...(picks || [])]; + for (const [tool, re] of TOOL_CUES) if (!out.includes(tool) && re.test(String(text || ""))) out.push(tool); + return out; +} + +// ---- the decision + +export const CAPACITY = 0.2; + +// models: [{id, name, tier}] from the catalog. mode: "auto" or a model id. loaded: the id in the guest. +// Returns {model, engine, think, gates, cues, tools, stay, swap, reason}. +export function decide(o) { + const models = o.models || []; + const tools = toolsFor(o.text, o.picks); + const f = features(o.text, { think: o.think }); + const logic = !!o.think || f.think >= THINK_AT; + const byTier = new Map(); + for (const m of models) if (TIERS.has(m.tier) && !byTier.has(m.tier)) byTier.set(m.tier, m); + if (o.mode && o.mode !== "auto") { + const m = models.find((x) => x.id === o.mode) || models.find((x) => x.id === o.loaded) || models[0] || null; + const e = m && ENGINES.find((x) => x.tier === m.tier); + return { model: m, engine: e || null, think: logic, gates: null, cues: f.cues, tools, stay: !!m && m.id === o.loaded, swap: !!m && m.id !== o.loaded, reason: m ? m.name : "" }; + } + const g = gate(f); + // Engines the server has keep their gates, renormalized. + const kept = ENGINES.map((e, i) => (byTier.has(e.tier) ? g[i] : 0)); + const total = kept.reduce((a, b) => a + b, 0); + if (!total) { + const m = models.find((x) => x.id === o.loaded) || models[0] || null; + return { model: m, engine: null, think: logic, gates: g, cues: f.cues, tools, stay: true, swap: false, reason: m ? m.name : "" }; + } + const p = kept.map((x) => x / total); + let top = 0; + for (let i = 1; i < p.length; i++) if (p[i] > p[top]) top = i; + const want = ENGINES[g.indexOf(Math.max(...g))]; + let pick = top; + // Capacity: a switch costs a model load. Close calls follow the residual (the loaded engine). + const loaded = models.find((x) => x.id === o.loaded); + const li = loaded ? ENGINES.findIndex((e) => e.tier === loaded.tier) : -1; + const stay = li >= 0 && li !== top && p[li] > 0 && p[top] - p[li] < CAPACITY; + if (stay) pick = li; + const e = ENGINES[pick]; + const m = byTier.get(e.tier); + const parts = [e.label + " " + p[pick].toFixed(2)]; + if (f.cues.length) parts.push(f.cues.slice(0, 3).join(", ")); + if (want.tier !== e.tier && !byTier.has(want.tier)) parts.push(want.label + " is not on this server"); + if (stay) parts.push("kept loaded (" + ENGINES[top].label + " " + p[top].toFixed(2) + ")"); + if (tools.length) parts.push("tools: " + tools.join(", ")); + return { + model: m, engine: e, think: e.row === 1 || logic, gates: p, cues: f.cues, tools, + stay: m.id === o.loaded, swap: m.id !== o.loaded, reason: parts.join(" · "), + }; +} + +// admit: hodgemix --update's rule for a tool result. The result joins the context when it moves the +// same way as the question; otherwise the engine answers alone and the result stays on its card. +export function admit(cos) { + return Number.isFinite(cos) && cos > 0; +} diff --git a/sw.js b/sw.js new file mode 100644 index 0000000000000000000000000000000000000000..1c555e0650641a697f74e63eff61ba84d67a6ae2 --- /dev/null +++ b/sw.js @@ -0,0 +1,14 @@ +// Encryptid EdgeAI. Pass the network through so the page keeps its +// isolation headers. The install only needs this fetch handler. +self.addEventListener("install", (event) => { + event.waitUntil(self.skipWaiting()); +}); +self.addEventListener("activate", (event) => { + event.waitUntil(self.clients.claim()); +}); +self.addEventListener("fetch", (event) => { + if (event.request.method !== "GET") return; + // Honor the server cache. The wasm is cacheable for a day. Forcing + // no-store here made every visit download the model again. + event.respondWith(fetch(event.request)); +}); diff --git a/terms.html b/terms.html new file mode 100644 index 0000000000000000000000000000000000000000..6db0bf4c3153399d3e0f3dc03e1c4f31b22053f9 --- /dev/null +++ b/terms.html @@ -0,0 +1,78 @@ + + + + + + +Terms · Hodge-3.5 · Encryptid EdgeAI + + + + +
+ + EdgeAI + Hodge-3.5 +
+
+

Terms of Service

+

19 October 2026

+

These terms cover Hodge-3.5, the assistant on Encryptid EdgeAI. Encryptid Systems, Frederick County, Maryland, operates the site. Hodge-3.5 starts only after you accept. If you deny, you cannot proceed.

+ +

Browser agent

+

Hodge-3.5 is a browser agent. If you accept, it makes requests on your behalf from this browser. Those requests look things up, including DuckDuckGo, duck.ai, Gemini, and Wikipedia. If you deny, Hodge-3.5 does not start and makes no requests for you.

+ +

The service

+

Hodge-3.5 runs on your device. We send the page, the program, and the files Hodge-3.5 needs so it can run there. The messages you type to Hodge-3.5 stay on your device. We do not receive them.

+

The server does see the ordinary request for the page and those files. That includes your IP address and the time of the request.

+ +

Your use

+

Use the service lawfully. Do not interfere with the service, and do not interfere with anyone else's use of it. You are responsible for what you do with Hodge-3.5's answers.

+ +

Answers

+

Hodge-3.5 can be wrong. Check anything that matters before you rely on it. Hodge-3.5 is not a lawyer, a doctor, or any other professional adviser.

+ +

The service as it is

+

We provide the service as it is. We can change it, pause it, or stop it. We can update these terms by posting a new version on this page. The date above is the version you are reading.

+ +

Contact

+

Encryptid Systems, Frederick County, Maryland.
+ programs@encryptid.systems

+ +

Back to Hodge-3.5

+
+ + diff --git a/think.js b/think.js new file mode 100644 index 0000000000000000000000000000000000000000..9ff697b9a6733acbe5af131b81afd53521bdf7b9 --- /dev/null +++ b/think.js @@ -0,0 +1,1165 @@ +// A continuing chain for one hard task. The MoE gate's think bit (router.js) +// starts it. Each step stays in the same trace, a tool result comes back into +// that trace, and the chain stops on DONE or after STEP_CAP steps. The final +// call answers from the whole trace. + +import { features, KIND, SUBJECT_SOURCES, THINK_AT, join, route, searchQuery, sourceFor } from "./router.js"; +import { toolCallOf } from "./ext.js"; +import { frameEcho } from "./frame.js"; + +export { THINK_AT }; +export const STEP_CAP = 8; +export const STEP_TOKENS = 384; +export const ANSWER_TOKENS = 2048; +// Text of the top search hit's page the write sees. A one-line snippet held the +// answer to that one line; a page gives a long answer something true to say. +// About 1,100 tokens, which leaves room in a 4,096-token window for a long answer. +const PAGE_CHARS = 4500; +const TRACE_CAP = 6000; + +export function wantsChain(text, thinkOn) { + if (thinkOn) return true; + const f = features(String(text || ""), {}); + return f.think >= THINK_AT; +} + +export function isDone(text) { + const s = String(text || "").trim(); + return /^(?:DONE|ANSWER)\b/i.test(s) || /\bDONE\s*$/i.test(s); +} + +function doneBody(text) { + return String(text || "").replace(/\s*\bDONE\s*$/i, "").replace(/^(?:DONE|ANSWER)\b[:\s-]*/i, "").replace(/\s+/g, " ").trim(); +} + +export function traceText(trace) { + const lines = (trace || []).map((item) => { + if (item.kind === "tool") return item.step + ". [" + item.tool + "] " + String(item.text || "").replace(/\s+/g, " ").trim(); + return item.step + ". " + String(item.text || "").replace(/\s+/g, " ").trim(); + }); + let s = lines.join("\n"); + if (s.length > TRACE_CAP) s = s.slice(s.length - TRACE_CAP); + return s; +} + +export function stepPrompt(question, trace, step) { + const prior = trace && trace.length ? "\nWork so far:\n" + traceText(trace) : ""; + return "You are working one task through to the end. Continue from the work so far. " + + "Write the next step in a few sentences, or one tool call and nothing else. " + + "A tool call is only this JSON: {\"type\":\"tool_call\",\"tool\":\"exec\",\"args\":{\"cmd\":\"...\"}} " + + "(tool is exec, search, gather, notes, tasks, or canvas). " + + "exec runs in EncryptidVM, the TunnelTug guest, never on the host. " + + "When the work is finished, reply with DONE and stop. Do not give the final answer before DONE." + + prior + "\nQuestion: " + question + "\nStep " + step + ":"; +} + +export function answerPrompt(question, trace, notes) { + const note = notes ? "\nNotes:\n" + notes : ""; + const work = traceText(trace); + return "Explain the answer in plain words. Do not use a tool.\nWork:\n" + work + note + "\nQuestion: " + question; +} + +// hooks.chat(prompt, maxTokens) and hooks.answer(prompt, maxTokens) return the +// visible text, or null when the turn cannot start. hooks.run(call) runs a tool. +// hooks.stop() is true when the person pressed Stop. hooks.notes(question) +// returns recalled notes. hooks.onStep(item) shows one step. +export async function runChain(question, hooks) { + const h = hooks || {}; + const trace = []; + let steps = 0; + while (steps < STEP_CAP) { + if (h.stop && h.stop()) return { trace, answer: "", stopped: true }; + steps++; + const got = await h.chat(stepPrompt(question, trace, steps), STEP_TOKENS); + if (got == null) return { trace, answer: "", stopped: true }; + const call = toolCallOf(got); + if (call && h.run) { + await beginStep(h, (call.tool || "Working") + "…"); + const ran = await h.run(call); + const item = { step: steps, kind: "tool", tool: call.tool, text: (ran && ran.output) || "" }; + trace.push(item); + if (h.onStep) h.onStep(item); + continue; + } + const text = String(got || "").replace(/\s+/g, " ").trim(); + if (!text) continue; + if (isDone(text)) { + const rest = doneBody(text); + if (rest) { + const item = { step: steps, kind: "think", text: rest }; + trace.push(item); + if (h.onStep) h.onStep(item); + } + break; + } + const item = { step: steps, kind: "think", text }; + trace.push(item); + if (h.onStep) h.onStep(item); + } + if (h.stop && h.stop()) return { trace, answer: "", stopped: true }; + const notes = h.notes ? h.notes(question) : ""; + const answer = await h.answer(answerPrompt(question, trace, notes), ANSWER_TOKENS); + return { trace, answer: answer || "", stopped: false }; +} + +const OUTLINE_TOKENS = 384; +const SEGMENT_TOKENS = 768; + +export function sectionTitles(text) { + const src = String(text || "").replace(/\r/g, ""); + // A one- or two-digit index. A year such as 1968 is not a subject. + const re = /(?:^|\n|[ \t])(?:[-*]|\d{1,2}[.)]|#{1,3})[ \t]+/g; + const hits = []; + let m; + while ((m = re.exec(src))) hits.push({ at: m.index, len: m[0].length }); + let raws; + const marked = hits.length > 0; + if (marked) { + raws = hits.map((h, i) => src.slice(h.at + h.len, i + 1 < hits.length ? hits[i + 1].at : src.length).trim()); + if (raws.length > 1 && /[.!?]["']?$/.test(raws[0]) && !/[.!?]["']?$/.test(raws[raws.length - 1])) raws.pop(); + } else { + raws = src.split(/\n/).map((s) => s.trim()).filter(Boolean); + } + const out = []; + const seen = new Set(); + for (const raw of raws) { + let s = String(raw || "").replace(/\s+/g, " ").trim(); + const dash = s.split(/\s+[—–-]\s+/)[0]; + if (s.split(" ").length > 24 && dash.split(" ").length <= 24) s = dash; + s = s.replace(/[:.]\s*$/, "").trim(); + if (s.length < 3 || s.length > 180) continue; + if (s.split(" ").length > 24) continue; + if (/^(?:outline|parts|sections|section titles|title)$/i.test(s)) continue; + const key = s.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push(s); + if (out.length >= 8) break; + } + if (out.length === 1 && out[0].length > 80) return []; + return out; +} + +export function sourceKept(output) { + const s = String(output || "").replace(/\s+/g, " ").trim(); + if (s.length < 12) return false; + if (/^(?:the lookup failed|missing search query|nothing matched|unknown tool|that address is not available)\b/i.test(s)) return false; + // A refused gather is not a page. Quoting it would publish the refusal as the answer. + if (/reads only an address the person gave or a search listed/i.test(s)) return false; + return true; +} + +// A JavaScript shell answers with a browser banner and a menu. That text is +// not the article. A real page is returned as it arrived. +const CHROME_RE = /\b(?:outdated browser|upgrade your browser|upgrade your web browser|enable javascript|javascript is (?:required|disabled)|turn on javascript)\b/i; +const NAV_LEAD = /^(?:(?:skip to content|where to eat|overview|recipe|comments|home|menu|search|navigation)\s+){2,}/i; + +export function pageProse(text) { + const raw = String(text || "").replace(/\r/g, "").trim(); + const flat = raw.replace(/\s+/g, " ").trim(); + if (!flat) return ""; + const kept = []; + let dropped = false; + for (const part of flat.split(/(?<=[.!?])\s+/)) { + const s = part.trim(); + if (!s) continue; + if (CHROME_RE.test(s)) { dropped = true; continue; } + kept.push(s); + } + let body = kept.join(" ").trim(); + if (dropped) body = body.replace(NAV_LEAD, "").trim(); + const words = body ? body.split(/\s+/).length : 0; + if (dropped && words < 12) return ""; + if (!dropped) return flat.length < 12 ? "" : raw; + return body; +} + +function clip(s, n) { + const t = String(s || "").replace(/\s+/g, " ").trim(); + return t.length > n ? t.slice(0, n) : t; +} + +function clipLines(s, n) { + const t = String(s || "").replace(/\r/g, "").trim(); + return t.length > n ? t.slice(0, n) : t; +} + +function planLines(trace) { + return (trace || []).map((item) => { + if (item.kind === "tool") { + const name = item.label || item.tool; + return item.kept ? name + ": " + clip(item.text, item.page ? PAGE_CHARS : 500) : name + ": nothing returned"; + } + return clip(item.text, 500); + }).join("\n"); +} + +// The write sees at most 700 characters of this step, so it is held to a few sentences. +const REASON_TOKENS = 160; + +function reasonPrompt(question) { + return "Think through this question step by step in three or four short sentences. Do not write the final answer yet.\nQuestion: " + question; +} + +function outlinePrompt(question) { + return "List the topics of the answer, one short line each. Do not state a fact. Do not answer yet.\nQuestion: " + question; +} + +// The lookup is the person's question. An outline sentence is not a query. +export function lookupQuery(question) { + const ask = String(question || "").replace(/\s+/g, " ").trim() + .replace(/^(?:please\s+)?(?:research|search(?:\s+for)?|look\s*up|lookup)\s+/i, "") + .trim(); + return (ask || String(question || "").replace(/\s+/g, " ").trim()).slice(0, 120); +} + +function topicOf(subject) { + const raw = String(subject || "").replace(/\s+/g, " ").trim(); + const head = raw.split(/\s+(?:was|were|is|are|became|saw|had|has|have)\b/i)[0] + .replace(/\([^)]*\)/g, " ").replace(/\s+/g, " ").replace(/[.:;,]+$/g, "").trim(); + return head || raw; +} + +function pageItems(trace) { + return (trace || []).filter((item) => item.kind === "tool" && item.page && item.kept && item.text); +} + +function sourceBlob(trace) { + const pages = pageItems(trace); + const items = pages.length ? pages : (trace || []).filter((item) => item.kind === "tool" && item.kept && item.text); + return items.map((item) => String(item.text)).join("\n"); +} + +// A grounded sentence may only carry a year or a name the sources already +// contain. Anything else is the model filling a gap, which is where a short +// checkpoint invents a river, a year, or a city. +function sentenceHeld(sentence, src) { + const source = String(src || ""); + const low = source.toLowerCase(); + const years = String(sentence).match(/\b\d{3,4}\b/g) || []; + for (const y of years) if (!source.includes(y)) return false; + const words = String(sentence).match(/\b[A-Za-z][A-Za-z'-]*/g) || []; + for (let i = 1; i < words.length; i++) { + const w = words[i]; + if (!/^[A-Z]/.test(w)) continue; + if (w.length < 2) continue; + if (!low.includes(w.toLowerCase())) return false; + } + return true; +} + +function wordsOf(s) { + return String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean); +} + +// A looked-up sentence has to be the page's own words. A six-word run of the +// sentence must sit in the source, and every longer word must already be on +// the page. A six-word run alone keeps "incorporated" when the page says +// "unincorporated". A fragment such as "In 1797, the U.S." has too few words. +function spanHeld(sentence, src) { + const words = wordsOf(sentence); + const source = wordsOf(src); + if (!words.length || !source.length) return false; + const content = words.filter((w) => w.length > 2); + if (content.length < 3) return false; + const bag = new Set(source); + if (content.some((w) => !bag.has(w))) return false; + if (words.length < 6) return true; + const blob = " " + source.join(" ") + " "; + for (let i = 0; i + 6 <= words.length; i++) { + if (blob.includes(" " + words.slice(i, i + 6).join(" ") + " ")) return true; + } + return false; +} + +function factualTrace(trace) { + if (pageItems(trace).length) return true; + return (trace || []).some((item) => item.kind === "tool" && item.kept && parseHits(item.text).length > 0); +} + +// The first page's own lead. Later pages stay in the source list so a company +// page is not read as the definition of the dish. +function leadQuotes(text, n) { + const quotes = quoteSentences(text, 5, n); + if (quotes.length) return quotes.slice(0, n); + const out = []; + for (const chunk of String(text || "").split(/\n{2,}/)) { + const s = chunk.replace(/\s+/g, " ").trim(); + if (s.split(/\s+/).filter(Boolean).length < 8) continue; + out.push(s.length > 500 ? s.slice(0, 500).replace(/\s+\S*$/, "").trim() : s); + if (out.length >= n) break; + } + return out; +} + +const CITE_STOP = new Set("the a an of and to in on for is was are were what who where when why how me about look up lookup tell please with from that this into its or as at by be it".split(" ")); + +function queryWords(question) { + return wordsOf(question).filter((w) => w.length > 2 && !CITE_STOP.has(w)); +} + +const GENERIC = new Set("news latest today tonight headline headlines breaking current update updates weather forecast right now price prices cost score scores standing standings".split(" ")); +const LEAD = new Set("research search lookup look causes effects history impact facts fact give tell describe explain write about please formatted recipe recipes".split(" ")); + +function subjectWords(question) { + return queryWords(question).filter((w) => !GENERIC.has(w) && !LEAD.has(w)); +} + +function nameWords(words) { + if (words.length <= 2) return words; + let first = 0; + let second = 1; + if (words[1].length > words[0].length) { first = 1; second = 0; } + for (let i = 2; i < words.length; i++) { + if (words[i].length > words[first].length) { second = first; first = i; } + else if (words[i].length > words[second].length) second = i; + } + return [words[first], words[second]]; +} + +function stemMatch(tok, word) { + if (tok === word) return true; + if (word.length >= 4 && tok.startsWith(word) && tok.length <= word.length + 2) return true; + if (tok.length >= 4 && word.startsWith(tok) && word.length <= tok.length + 2) return true; + return false; +} + +// The reply names the subject. A menu page that never says the dish does not. +function carriesName(question, text) { + const names = nameWords(subjectWords(question)); + if (!names.length) return true; + const toks = wordsOf(text); + return names.every((w) => toks.some((tok) => stemMatch(tok, w))); +} + +// A short reply that shares no content word with the question. +function offSubject(question, text) { + const words = queryWords(question); + if (!words.length) return false; + const t = String(text || "").trim(); + if (!t || t.split(/\s+/).length > 24) return false; + return scoreSentence(t, words) === 0; +} + +const ROUTE_ONLY = /^(?:fact|recipe|command|talk)[.!:]?$/i; + +function modelStands(question, text) { + const t = String(text || "").trim(); + if (!t || ROUTE_ONLY.test(t)) return false; + if (offSubject(question, t)) return false; + return carriesName(question, t); +} + +function briefNotes(trace) { + const pages = pageItems(trace); + const items = pages.length ? pages : (trace || []); + const bits = []; + for (const item of items) { + if (item.kind !== "tool" || !item.kept || !item.text) continue; + const t = String(item.text).replace(/\s+/g, " ").trim(); + if (!t) continue; + bits.push(t); + if (bits.length >= 3) break; + } + return bits.join(" ").slice(0, 700); +} + +// The search card is titles, addresses, and cut snippets. It is not the answer. +function hitDump(text) { + const s = String(text || ""); + return /https?:\/\//i.test(s) || /\s\d{1,2}\.\s+[A-Za-z]/.test(s); +} + +function pageLead(text) { + const quotes = quoteSentences(text, 8, 2); + if (quotes.length) return quotes.join(" "); + const paras = String(text || "").split(/\n{2,}/).map((s) => s.replace(/\s+/g, " ").trim()); + return paras.find((s) => s.split(/\s+/).length >= 12) || ""; +} + +function scoreSentence(sentence, qwords) { + if (!qwords.length) return 1; + const bag = new Set(wordsOf(sentence)); + let n = 0; + for (const w of qwords) if (bag.has(w)) n++; + return n; +} + +// The first page keeps its lead, in order. Another page contributes the +// sentence that shares the most words with the question. +function pickSentences(text, qwords, n, lead) { + const sentences = leadQuotes(text, n); + if (!sentences.length) return []; + if (lead) return sentences.slice(0, n); + const ranked = sentences.map((s, i) => ({ s, i, score: scoreSentence(s, qwords) })); + ranked.sort((a, b) => b.score - a.score || a.i - b.i); + const best = ranked.filter((row) => row.score > 0).slice(0, n); + if (!best.length) return []; + return best.sort((a, b) => a.i - b.i).map((row) => row.s); +} + +// A page that shares one stray word is not the dish when another page shares the name. +function groundHits(question, trace) { + const qwords = queryWords(question); + const pages = pageItems(trace); + const sources = citedSources(trace); + if (!pages.length || !qwords.length) return sources; + const byUrl = new Map(pages.map((page) => [page.url, page])); + const scored = sources.map((src) => ({ + src, + score: scoreSentence((byUrl.get(src.url) || {}).text || src.snippet || "", qwords), + })); + const best = scored.reduce((m, row) => Math.max(m, row.score), 0); + if (best < 3) return sources; + const kept = scored.filter((row) => row.score >= best - 1).map((row) => row.src); + return kept.length ? kept : sources; +} + +function citeLine(sentence, n, url) { + const title = String(url || ""); + if (!title) return sentence; + return sentence + " [" + n + "](" + title + ")"; +} + +const RECIPE_AMOUNT = /(?:about\s+)?(?:as needed|\d+[¼½¾⅓⅔⅛⅜⅝⅞]|\d+\s+\d+\/\d+|\d+\/\d+|[¼½¾⅓⅔⅛⅜⅝⅞]|\d+(?:\.\d+)?)(?:\s*(?:lb|lbs|pounds?|g|kg|oz|ml|cups?|tbsp|tsp|tablespoons?|teaspoons?|inches?|inch))?(?:\s*\([^)]*\))?(?:,\s*divided)?(?:\s+in the pan)?/gi; + +function cleanName(s) { + return String(s || "").replace(/^[\s,;:.\-–—]+|[\s,;:.\-–—]+$/g, "").replace(/\s+,/g, ",").replace(/\s+/g, " ").trim(); +} + +function rowScore(name, amount) { + const words = name.split(" ").length; + const unit = /\b(?:cups?|tbsp|tsp|teaspoons?|tablespoons?|lb|lbs|oz|ml|g|kg)\b/i.test(amount); + const bare = /^\d+$/.test(amount); + let score = 0; + if (unit && words <= 5) score += 2; + if (unit && words > 6) score -= 3; + if (bare && /egg/i.test(name)) score += 2; + if (bare && !/egg/i.test(name)) score -= 2; + if (!amount && words > 5) score += 1; + return score; +} + +// A flattened recipe is either "name amount" or "amount name". Both are tried. +// The alignment that puts cups and teaspoons on the short names wins, so a +// long chicken line does not take the corn flakes' 5 cups. +function maskNameParens(section) { + return section.replace(/\(([^)]*)\)/g, (full, inner) => { + if (/^\s*(?:about\s+)?[\d¼½¾⅓⅔⅛./\s-]+(?:lb|lbs|g|kg|oz|ml|cups?)?\s*$/i.test(inner)) return full; + return " ".repeat(full.length); + }); +} + +function liftParenAmount(name, amount) { + if (amount) return [name, amount]; + const paren = name.match(/\(([^)]*\d[^)]*)\)/); + if (!paren || paren[1].length > 40) return [name, amount]; + return [cleanName(name.replace(paren[0], " ")), paren[1].replace(/\s+/g, " ").trim()]; +} + +function recipeRows(section) { + const masked = maskNameParens(section); + const matches = [...masked.matchAll(new RegExp(RECIPE_AMOUNT.source, "gi"))]; + if (!matches.length) return []; + const amountOf = (m) => m[0].replace(/\s+/g, " ").trim(); + const gaps = []; + let start = 0; + for (const m of matches) { + gaps.push(cleanName(section.slice(start, m.index))); + start = m.index + m[0].length; + } + gaps.push(cleanName(section.slice(start))); + const before = []; + matches.forEach((m, i) => { if (gaps[i]) before.push([gaps[i], amountOf(m)]); }); + const after = []; + if (gaps[0] && gaps[0].split(" ").length > 5) after.push([gaps[0], ""]); + matches.forEach((m, i) => { if (gaps[i + 1]) after.push([gaps[i + 1], amountOf(m)]); }); + const score = (rows) => rows.reduce((n, [name, amount]) => n + rowScore(name, amount), 0); + const picked = score(after) > score(before) ? after : before; + return picked.map(([name, amount]) => liftParenAmount(name, amount)); +} + +function recipeMeta(head) { + const re = /\b(Makes|Serves|Servings|Prep|Cook(?:\s+time)?|Total|Yield)\s*:\s*/gi; + const marks = []; + let m; + while ((m = re.exec(head))) marks.push({ label: m[1], at: m.index, len: m[0].length }); + if (!marks.length) return { title: head.trim(), lines: [] }; + const title = head.slice(0, marks[0].at).replace(/[.?!]+$/g, "").trim(); + const lines = marks.map((mark, i) => { + const end = i + 1 < marks.length ? marks[i + 1].at : head.length; + const value = head.slice(mark.at + mark.len, end).replace(/\s+/g, " ").replace(/[\s·•|]+$/g, "").trim(); + const label = mark.label.replace(/\s+time$/i, ""); + return value ? label + ": " + value : ""; + }).filter(Boolean); + return { title, lines }; +} + +// A flattened recipe is one sentence. The page already renders headings, lists, and tables. +export function formatRecipe(text) { + const flat = String(text || "").replace(/\s+/g, " ").trim(); + const ingAt = flat.search(/\bIngredients?\b(?:\s+Amount)?/i); + if (ingAt < 0) return ""; + const rel = flat.slice(ingAt).search(/\b(?:Method|Directions|Instructions|Steps|Preparation|Marinate)\b/i); + if (rel < 0) return ""; + const methodAt = ingAt + rel; + const head = flat.slice(0, ingAt).trim(); + const ing = flat.slice(ingAt, methodAt).replace(/^\s*Ingredients?\s*(?:Amount\s*)?/i, "").trim(); + const method = flat.slice(methodAt).replace(/^\s*(?:Method|Directions|Instructions|Steps|Preparation|Marinate)\s*:?\s*/i, "").trim(); + const rows = recipeRows(ing); + if (rows.length < 2) return ""; + if (head.length > 140) return ""; + if (rows.some(([n]) => n.length > 80 || n.split(" ").length > 14)) return ""; + const meta = recipeMeta(head); + const steps = method.split(/(?<=[.!?])\s+/).map((s) => s.trim()).filter((s) => s && !/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(s)); + const cell = (s) => s.replace(/\|/g, "/"); + const lines = []; + if (meta.title) lines.push("## " + meta.title); + if (meta.lines.length) lines.push(meta.lines.map((l) => "- " + l).join("\n")); + lines.push("| Ingredient | Amount |\n| --- | --- |\n" + rows.map(([n, a]) => "| " + cell(n) + " | " + cell(a || "—") + " |").join("\n")); + if (steps.length) lines.push("### Method\n" + steps.map((s, i) => (i + 1) + ". " + s).join("\n")); + return lines.join("\n\n"); +} + +const RECIPE_Q = /\b(?:recipes?)\b|\bhow to (?:make|cook|bake|fry|roast|prepare)\b/i; +const COMPARE_Q = /\b(?:compare|comparison|difference between|versus)\b|\bvs\.?\b/i; +const STEPS_Q = /\b(?:how to|how do i|how can i|steps|instructions)\b/i; +const LIST_Q = /\b(?:list|name the|what are the|which are|examples of)\b/i; +const DEFINE_Q = /\b(?:who|what|when|where)\b|\b(?:tell me about|describe)\b/i; + +// The question picks the shape. The sentences stay the sources' own words. +export function answerTemplate(question) { + const t = String(question || ""); + if (RECIPE_Q.test(t)) return "recipe"; + if (COMPARE_Q.test(t)) return "compare"; + if (STEPS_Q.test(t)) return "steps"; + if (LIST_Q.test(t)) return "list"; + if (DEFINE_Q.test(t)) return "define"; + return "prose"; +} + +function subjectLine(question) { + const s = searchQuery(question).replace(/^(?:causes?|effects?|reasons?)\s+/i, "").trim(); + if (!s) return ""; + return s.charAt(0).toUpperCase() + s.slice(1); +} + +function headed(question, body) { + const title = subjectLine(question); + return title ? "## " + title + "\n\n" + body : body; +} + +function sideWords(side) { + return wordsOf(side).filter((w) => w.length > 2 && !CITE_STOP.has(w)); +} + +function mentionsSide(sentence, side) { + const words = sideWords(side); + if (!words.length) return false; + const bag = new Set(wordsOf(sentence)); + const n = words.filter((w) => bag.has(w)).length; + return n >= Math.min(2, words.length); +} + +function compareSides(question) { + const t = String(question || "").replace(/\s+/g, " ").replace(/[?.!]+$/g, "").trim(); + const patterns = [ + /\bdifference between\s+(.+?)\s+and\s+(.+)$/i, + /\bcompare\s+(.+?)\s+(?:and|with|to|versus|vs\.?)\s+(.+)$/i, + /\b([A-Za-z][^?]{0,48}?)\s+(?:versus|vs\.?)\s+([^?]+)$/i, + ]; + for (const re of patterns) { + const m = re.exec(t); + if (!m) continue; + const a = m[1].replace(/^(?:the|a|an)\s+/i, "").trim(); + const b = m[2].replace(/^(?:the|a|an)\s+/i, "").trim(); + if (a && b && a.length < 80 && b.length < 80) return [a, b]; + } + return null; +} + +function compareTable(question, blocks) { + const sides = compareSides(question); + if (!sides) return ""; + const left = []; + const right = []; + const rest = []; + const cell = (s) => String(s || "").replace(/\|/g, "/").replace(/\s+/g, " ").trim(); + for (const b of blocks) { + if (b.shaped) { rest.push(b.line); continue; } + const onLeft = mentionsSide(b.s, sides[0]); + const onRight = mentionsSide(b.s, sides[1]); + if (onLeft && !onRight) left.push(b.line); + else if (onRight && !onLeft) right.push(b.line); + else rest.push(b.line); + } + if (!left.length || !right.length) return ""; + const rows = []; + for (let i = 0; i < Math.max(left.length, right.length); i++) { + rows.push("| " + cell(left[i] || "") + " | " + cell(right[i] || "") + " |"); + } + const table = "| " + cell(sides[0]) + " | " + cell(sides[1]) + " |\n| --- | --- |\n" + rows.join("\n"); + const tail = rest.length ? "\n\n" + rest.join("\n\n") : ""; + return headed(question, table) + tail; +} + +function numbered(blocks) { + let i = 0; + return blocks.map((b) => { + if (b.shaped) return b.line; + i += 1; + return i + ". " + b.line; + }).join("\n"); +} + +function bullets(blocks) { + return blocks.map((b) => (b.shaped ? b.line : "- " + b.line)).join("\n"); +} + +// Steps and lists are often one short sentence each. The page quote rule +// drops anything under five words, which deletes "Disconnect the supply lines." +function templateQuotes(question, text, n) { + const kind = answerTemplate(question); + if (kind === "steps" || kind === "list" || kind === "compare") { + const parts = String(text || "").replace(/\s+/g, " ").trim().split(/(?<=[.!?])\s+/).map((s) => s.trim()).filter((s) => wordsOf(s).length >= 3); + if (parts.length) return parts.slice(0, n); + } + return leadQuotes(text, n); +} + +function applyTemplate(question, picks) { + const blocks = (picks || []).map((p) => ({ + s: p.s, + line: citeLine(p.s, p.n, p.url), + shaped: /^\s*##\s/m.test(p.s) || /\| Ingredient \|/.test(p.s), + })); + if (!blocks.length) return ""; + const kind = answerTemplate(question); + if (kind === "recipe") { + const shaped = blocks.filter((b) => b.shaped); + if (shaped.length) return shaped.map((b) => b.line).join("\n\n"); + return headed(question, numbered(blocks)); + } + if (kind === "compare") { + const table = compareTable(question, blocks); + if (table) return table; + } + if (kind === "steps") return headed(question, numbered(blocks)); + if (kind === "list") return headed(question, bullets(blocks)); + if (kind === "define") return headed(question, blocks.map((b) => b.line).join("\n\n")); + return blocks.map((b) => b.line).join("\n\n"); +} + +// A web answer is the pages' own sentences, each tied to the source it came +// from. The model is not asked to blend them. +function pageAnswer(question, trace) { + const qwords = queryWords(question); + const sources = groundHits(question, trace); + const pages = pageItems(trace); + const picks = []; + // duck.ai and Gemini answer the question. Their text is the other model's reply. + for (const item of trace || []) { + if (picks.length >= 6) break; + if (item.kind !== "tool" || item.tool !== "search" || !item.kept || !item.text) continue; + if (!/duck\.ai|gemini/i.test(String(item.label || ""))) continue; + if (parseHits(item.text).length) continue; + if (scoreSentence(item.text, qwords) < 2) continue; + const shaped = formatRecipe(item.text); + if (shaped) { + picks.push({ s: shaped, n: 0, url: "" }); + continue; + } + for (const s of templateQuotes(question, item.text, 6)) { + if (picks.length >= 6 || picks.some((p) => p.s === s)) continue; + picks.push({ s, n: 0, url: "" }); + } + } + if (pages.length && sources.length) { + const byUrl = new Map(pages.map((page) => [page.url, page])); + // The page that shares the question's words is quoted. A page that only + // shares a stray word is left out of the answer. + const ordered = sources.slice().sort((a, b) => { + const as = scoreSentence((byUrl.get(a.url) || {}).text || "", qwords); + const bs = scoreSentence((byUrl.get(b.url) || {}).text || "", qwords); + return bs - as; + }); + ordered.forEach((src, i) => { + const page = byUrl.get(src.url); + if (!page || picks.length >= 12) return; + const shaped = formatRecipe(page.text); + if (shaped) { + picks.push({ s: shaped, n: sources.indexOf(src) + 1, url: src.url }); + return; + } + for (const s of pickSentences(page.text, qwords, i === 0 ? 8 : 2, i === 0)) { + if (picks.length >= 12 || picks.some((p) => p.s === s)) continue; + picks.push({ s, n: sources.indexOf(src) + 1, url: src.url }); + } + }); + } + if (!picks.length && sources.length) { + sources.forEach((src, i) => { + const s = pickSentences(src.snippet || "", qwords, 1, true)[0]; + if (!s || picks.length >= 4 || picks.some((p) => p.s === s)) return; + picks.push({ s, n: i + 1, url: src.url }); + }); + } + if (picks.length) return applyTemplate(question, picks); + const quotes = []; + for (const item of trace || []) { + if (item.kind !== "tool" || !item.kept || !item.text) continue; + for (const s of leadQuotes(item.text, 2)) { + if (!quotes.includes(s)) quotes.push(s); + } + if (quotes.length) break; + } + return applyTemplate(question, quotes.map((s) => ({ s, n: 0, url: "" }))); +} + +export function keepGrounded(answer, trace) { + const src = sourceBlob(trace); + const raw = String(answer || "").trim().split(/\s+(?:Question|Answer)\s*:/i)[0].trim(); + if (!src.trim()) { + const looked = (trace || []).some((item) => item.kind === "tool" && (item.tool === "search" || item.tool === "gather" || item.page)); + return looked ? "The sources do not cover that." : raw; + } + const hold = factualTrace(trace) ? spanHeld : sentenceHeld; + const kept = []; + for (const part of raw.split(/(?<=[.!?])\s+/)) { + const s = part.trim(); + if (!s || !hold(s, src)) continue; + kept.push(s); + } + if (kept.length) return kept.join(" "); + const quotes = quoteSentences(src); + if (quotes.length) return quotes.slice(0, 2).join(" "); + return "The sources do not cover that."; +} + +// The source list is the lookup's own titles and addresses. The model was +// starting "Sources: 1." and the loop cut was treating that "1." as the end +// of the answer, so the address never landed. +function citedSources(trace) { + const out = []; + const seen = new Set(); + for (const item of pageItems(trace)) { + if (!item.url || seen.has(item.url)) continue; + seen.add(item.url); + out.push({ title: item.label || item.url, url: item.url }); + if (out.length >= 5) return out; + } + if (out.length) return out; + for (const item of trace || []) { + if (item.kind !== "tool" || !item.kept || !item.text) continue; + for (const hit of parseHits(item.text)) { + if (!hit.url || seen.has(hit.url)) continue; + seen.add(hit.url); + out.push(hit); + if (out.length >= 5) return out; + } + } + return out; +} + +export function withSources(answer, trace, question) { + const hits = question ? groundHits(question, trace) : citedSources(trace); + let body = String(answer || "").trim().replace(/\n*Sources:[\s\S]*$/i, "").trim(); + if (!hits.length) return body; + const lines = hits.map((hit, i) => { + const title = String(hit.title || hit.url).replace(/[\[\]]/g, ""); + return (i + 1) + ". [" + title + "](" + hit.url + ")"; + }); + return body + "\n\nSources:\n" + lines.join("\n"); +} + +function groundWork(trace) { + const pages = pageItems(trace); + if (pages.length) { + return pages.map((item) => (item.label || "Page") + ":\n" + item.text).join("\n\n"); + } + return planLines(trace); +} + +function writePrompt(question, trace) { + const grounded = (trace || []).some((item) => item.kind === "tool"); + const work = grounded ? groundWork(trace) : planLines(trace); + if (!work) return question; + if (grounded) { + const any = (trace || []).some((item) => item.kind === "tool" && item.kept && String(item.text || "").trim()); + if (!any) return "The lookup returned nothing on this. Say that in one sentence.\nQuestion: " + question; + return "The lookup is already done. Answer the question the person asked, in plain words. " + + "Use the notes. Give the answer that question asks for. Do not answer with a label, do not use a heading, and do not use JSON.\nNotes:\n" + + work + "\nQuestion: " + question; + } + return "Answer the person's question from the notes below.\nNotes:\n" + work + "\nQuestion: " + question; +} + +// Reads kept search hits, up to five, taking turns across engines so a +// Wikipedia list does not crowd out the other results. A miss is recorded +// so the step does not stay spinning. +async function readSources(trace, h, limit) { + if (!h.run || trace.some((x) => x.page)) return; + const cap = limit > 0 ? limit : 1; + const groups = []; + for (const item of trace) { + if (item.kind !== "tool" || item.tool !== "search" || !item.kept) continue; + const group = parseHits(item.text).filter((hit) => hit.url); + if (group.length) groups.push(group); + } + const hits = []; + const seen = new Set(); + let more = true; + while (hits.length < cap && more) { + more = false; + for (const group of groups) { + while (group.length && seen.has(group[0].url)) group.shift(); + if (!group.length) continue; + more = true; + const hit = group.shift(); + seen.add(hit.url); + hits.push(hit); + if (hits.length >= cap) break; + } + } + for (const hit of hits) { + if (h.stop && h.stop()) return; + const label = hit.title || "Page"; + await beginStep(h, "Reading " + label + "…"); + let ran = { output: "" }; + try { ran = (await h.run({ tool: "gather", args: { url: hit.url } })) || ran; } catch { ran = { output: "" }; } + const prose = sourceKept(ran.output) ? pageProse(ran.output) : ""; + const item = { + step: trace.length + 1, kind: "tool", tool: "gather", label, page: true, url: hit.url, + text: prose ? clipLines(prose, PAGE_CHARS) : "", kept: !!prose, empty: !prose, + }; + trace.push(item); + if (h.onStep) h.onStep(item); + } +} + +function beatPrompt(question, subject, prior, lookup) { + const topic = topicOf(subject); + const tail = prior ? "\nAlready on the page:\n" + String(prior).slice(-600) : ""; + if (lookup) { + return "Topic: " + topic + ".\n" + + "Write this topic in paragraphs from the lookup only. If the lookup does not say it, leave it out. " + + "Do not repeat what is already on the page. Do not ask a question. " + + "Name a source only when the lookup contains it.\n" + + "Lookup:\n" + lookup + tail + "\nQuestion: " + question; + } + return "Topic: " + topic + ".\n" + + "Stage this subject. One search tool call and nothing else is allowed, in this form: " + + "{\"type\":\"tool_call\",\"tool\":\"search\",\"args\":{\"q\":\"...\"}}. " + + "Otherwise write the subject in paragraphs. Do not list the other subjects." + + tail + "\nQuestion: " + question; +} + +// A search hit is a title, an address, and a snippet. The canvas quotes the page. +function parseHits(text) { + const src = String(text || "").replace(/\r/g, "").trim(); + if (!src) return []; + const chunks = src.split(/\n{2,}/); + if (!chunks.every((c) => /^\d{1,2}[.)]\s+/.test(c.trim()))) return []; + return chunks.map((chunk) => { + const lines = chunk.split("\n").map((s) => s.trim()).filter(Boolean); + const title = lines[0].replace(/^\d{1,2}[.)]\s+/, ""); + const url = lines.find((l) => /^https?:\/\//.test(l)) || ""; + const snippet = lines.filter((l) => l !== lines[0] && l !== url).join(" "); + return { title, url, snippet }; + }).filter((h) => h.title); +} + +// Sentences copied from a page. A fragment cut mid-word is not a quote. +function quoteSentences(text, minWords, maxSentences) { + const min = minWords || 8; + const flat = String(text || "").replace(/\s+/g, " ").trim(); + const out = []; + for (const part of flat.split(/(?<=[.!?])\s+/)) { + const s = part.trim(); + const n = s.split(/\s+/).length; + if (n < min || n > 120) continue; + if (!/[.!?]"?$/.test(s)) continue; + if (/^(?:home|menu|search|cookie|sign in|subscribe|share|advertisement|i will|i have generated|let me know if|please note)\b/i.test(s)) continue; + out.push(s); + if (out.length >= (maxSentences || 16)) break; + } + return out; +} + +function researchDocument(title, subjects, pages) { + const parts = ["# " + title]; + if (subjects.length) parts.push(subjects.map((s) => "- " + topicOf(s)).join("\n")); + let any = false; + for (const page of pages) { + const quotes = quoteSentences(page.text); + if (!quotes.length) continue; + any = true; + parts.push("## " + (page.title || "Source")); + if (page.url) parts.push("[" + (page.title || page.url) + "](" + page.url + ")"); + parts.push(quotes.join("\n\n")); + } + return any ? parts.join("\n\n") : ""; +} + +function canvasTitle(question) { + return lookupQuery(question).replace(/[.?!]+$/g, "").trim().slice(0, 80) || "Canvas"; +} + +async function publishCanvas(question, trace, h) { + const outlined = [...trace].reverse().find((x) => x.role === "outline"); + const subjects = outlined ? sectionTitles(outlined.text) : []; + const pages = []; + const seen = new Set(); + for (const item of trace) { + if (pages.length >= 5) break; + if (item.kind !== "tool" || item.tool === "canvas" || item.tool === "gather" || !item.kept || !item.text) continue; + const hits = parseHits(item.text); + const list = hits.length ? hits.slice(0, 3) : [{ title: "Source", url: "", snippet: item.text }]; + for (const hit of list) { + if (pages.length >= 5) break; + const key = hit.url || hit.snippet || ""; + if (!key || seen.has(key)) continue; + seen.add(key); + if (h.stop && h.stop()) return { trace, answer: "", stopped: true }; + let text = hit.snippet || ""; + if (hit.url && h.run) { + await beginStep(h, "Reading " + (hit.title || "page") + "…"); + let ran = { output: "" }; + try { ran = (await h.run({ tool: "gather", args: { url: hit.url } })) || ran; } + catch { ran = { output: "" }; } + const got = sourceKept(ran.output) ? clipLines(pageProse(ran.output), 6000) : ""; + const step = { + step: trace.length + 1, kind: "tool", tool: "gather", label: hit.title || "Page", + text: got, kept: !!got, empty: !got, + }; + trace.push(step); + if (h.onStep) h.onStep(step); + if (got) text = got; + } + pages.push({ title: hit.title, url: hit.url, text }); + } + } + const title = (subjects[0] && topicOf(subjects[0]).slice(0, 80)) || canvasTitle(question); + const text = researchDocument(title, subjects, pages); + let ran = { output: "", exit_code: 1 }; + if (text && h.run) { + try { ran = (await h.run({ tool: "canvas", args: { op: "write", title, text } })) || ran; } + catch { ran = { output: "", exit_code: 1 }; } + } + const item = { + step: trace.length + 1, kind: "tool", tool: "canvas", label: "Canvas", + text: title, kept: !!text, empty: !text, + }; + trace.push(item); + if (h.onStep) h.onStep(item); + if (h.card && text) { + h.card({ + tool: "canvas", + args: { op: "write", title }, + output: text, + exit_code: ran.exit_code || 0, + data: (ran.data && Array.isArray(ran.data.blocks) && ran.data.blocks.length) + ? ran.data + : { title, text }, + }); + } + // The canvas card is the document. The chat does not repeat it. + return { trace, answer: text, stopped: false }; +} + +async function beginStep(h, label) { + if (h.onBegin) await h.onBegin({ label }); +} + +function lookupLines(items) { + return items.map((item) => { + const name = String(item.label || item.tool || "source").split(" · ").pop(); + return item.kept && item.text ? name + ": " + item.text : name + ": nothing returned"; + }).join("\n"); +} + +// One lookup for the question. A later subject reuses that result. +async function loadSubject(subject, question, trace, h) { + const sub = String(subject || "").replace(/\s+/g, " ").trim(); + const q = lookupQuery(question); + const prior = trace.filter((x) => x.kind === "tool" && x.tool === "search"); + if (prior.length) return lookupLines(prior); + const src = sourceFor(question); + if (h.stop && h.stop()) return null; + let ran = { output: "" }; + const ask = SUBJECT_SOURCES.has(src.source) ? searchQuery(question) : q; + await beginStep(h, src.label + "…"); + try { ran = (await h.run({ tool: "search", args: { q: ask, source: src.source } })) || ran; } catch { ran = { output: "" }; } + const echo = frameEcho(ran.output, question) || frameEcho(ran.output, q); + const usable = !echo && sourceKept(ran.output); + const text = usable ? clipLines(ran.output, 1800) : ""; + const item = { + step: trace.length + 1, kind: "tool", tool: "search", part: sub, query: q, + label: sub ? sub + " · " + src.label : src.label, text, kept: usable, empty: !text, + }; + trace.push(item); + if (h.onStep) h.onStep(item); + return usable ? src.label + ": " + text : src.label + ": nothing returned"; +} + +// Each outline line is a chat beat. route stages it. join emits it onto the +// page. A search tool call on that beat is loaded, then the subject is staged +// again. This is the same for every message that listed more than one line. +async function emitSubjects(question, trace, subjects, h, search) { + let paper = ""; + for (const subject of subjects) { + if (h.stop && h.stop()) return { trace, answer: paper, stopped: true }; + if (h.room) await h.room(); + let lookup = ""; + if (search) { + lookup = await loadSubject(subject, question, trace, h); + if (lookup == null) return { trace, answer: paper, stopped: true }; + } + if (route(!!(h.full && h.full()), KIND.chat) !== "stage") continue; + const partials = h.partials ? !!h.partials() : true; + const placed = h.placed ? !!h.placed() : true; + if (join(true, partials, placed) !== "emit") continue; + let got = await h.answer(beatPrompt(question, subject, paper, lookup), SEGMENT_TOKENS); + if (got == null) return { trace, answer: paper, stopped: true }; + const call = toolCallOf(got); + if (call && call.tool === "search" && h.run && !lookup) { + let ran = { output: "" }; + try { ran = (await h.run(call)) || ran; } catch { ran = { output: "" }; } + const lookup = sourceKept(ran.output) ? clip(ran.output, 700) : ""; + const item = { + step: trace.length + 1, kind: "tool", tool: "search", part: subject, + label: subject, text: lookup, kept: !!lookup, empty: !lookup, + }; + trace.push(item); + if (h.onStep) h.onStep(item); + if (h.stop && h.stop()) return { trace, answer: paper, stopped: true }; + got = await h.answer(beatPrompt(question, subject, paper, lookup || "nothing returned"), SEGMENT_TOKENS); + if (got == null) return { trace, answer: paper, stopped: true }; + } + const rawBody = String(got || "").trim(); + if (!rawBody || toolCallOf(rawBody)) continue; + let body = rawBody; + if (search && !modelStands(question, rawBody)) { + const notes = briefNotes(trace); + body = carriesName(question, notes) ? notes : ""; + } + if (!body) continue; + paper = paper ? paper.replace(/\s+$/, "") + "\n\n" + body : body; + if (h.commit) h.commit(body); + } + return { trace, answer: paper, stopped: false }; +} + +// Fills a plan from planOf. Tool steps run together. A reason or outline step +// is one model call. The last step is the write, and it sees only the tool +// text the quality check kept. +export async function runPlan(question, plan, hooks) { + const h = hooks || {}; + const trace = []; + const steps = (plan && plan.steps) || []; + let n = 0; + let i = 0; + while (i < steps.length) { + if (h.stop && h.stop()) return { trace, answer: "", stopped: true }; + if (steps[i].kind === "tool") { + let j = i; + while (j < steps.length && steps[j].kind === "tool") j++; + const batch = steps.slice(i, j); + let halted = false; + for (let k = 0; k < batch.length; k++) { + if (h.stop && h.stop()) { halted = true; break; } + await beginStep(h, (batch[k].label || batch[k].tool || "Working") + "…"); + let ran = { output: "" }; + try { ran = (await h.run({ tool: batch[k].tool, args: batch[k].args || {} })) || ran; } + catch { ran = { output: "", exit_code: 1 }; } + n++; + const step = batch[k]; + const output = ran.output || ""; + const echo = frameEcho(output, question); + const usable = !echo && sourceKept(output); + // clipLines keeps the blank lines between hits, so readTop can parse them. + const text = usable ? clipLines(output, 1800) : ""; + const looked = step.tool === "search" || step.tool === "gather"; + const kept = usable && (looked || (h.keep ? !!h.keep(output) : true)); + const name = step.label || step.source || step.tool; + const item = { + step: n, kind: "tool", tool: step.tool, part: step.part || "", + query: (step.args && step.args.q) || "", + label: step.part ? step.part + " · " + name : name, + text, kept, empty: !text, + }; + trace.push(item); + if (h.onStep) h.onStep(item); + } + if (halted) return { trace, answer: "", stopped: true }; + i = j; + continue; + } + const step = steps[i]; + i++; + n++; + if (step.role === "write") { + const outlined = [...trace].reverse().find((x) => x.role === "outline"); + const subjects = outlined ? sectionTitles(outlined.text) : []; + const search = !!(plan && plan.search); + if (search && !trace.some((x) => x.kind === "tool")) { + const lookup = await loadSubject(subjects[0] || "", question, trace, h); + if (lookup == null) return { trace, answer: "", stopped: true }; + } + if (search && !trace.some((x) => x.page)) await readSources(trace, h, 1); + if (subjects.length >= 2) return await emitSubjects(question, trace, subjects, h, search); + if (h.stop && h.stop()) return { trace, answer: "", stopped: true }; + // The page's opening is the answer. The checkpoint rewrites "unincorporated" + // into "incorporated" and copies the search card's cut snippets. + const page = search ? pageItems(trace)[0] : null; + const lead = page ? pageLead(page.text) : ""; + if (lead && carriesName(question, lead)) { + const body = withSources(lead, trace, question); + if (body && h.commit) h.commit(body); + return { trace, answer: body, stopped: false }; + } + const answer = await h.answer(writePrompt(question, trace), ANSWER_TOKENS); + if (answer == null) return { trace, answer: "", stopped: true }; + const rawBody = String(answer).trim(); + if (toolCallOf(rawBody)) return { trace, answer: rawBody, stopped: false }; + let spoken = rawBody; + if (search) { + // A sentence the page does not hold is the checkpoint filling a gap + // with a year or a name. The search card is titles and cut snippets. + // When the write copies that card, the page's opening stays. + const page = pageItems(trace)[0]; + const grounded = keepGrounded(rawBody, trace); + const stands = modelStands(question, grounded) && !/sources do not cover/i.test(grounded) && !hitDump(grounded); + if (stands) spoken = grounded; + else if (page) spoken = pageLead(page.text); + else spoken = ""; + } + const body = withSources(spoken, trace, question); + if (body && h.commit) h.commit(body); + return { trace, answer: body, stopped: false }; + } + const prompt = step.role === "reason" ? reasonPrompt(question) : outlinePrompt(question); + const max = step.role === "reason" ? REASON_TOKENS : OUTLINE_TOKENS; + const got = await h.chat(prompt, max); + if (got == null) return { trace, answer: "", stopped: true }; + const call = toolCallOf(got); + if (call && call.tool && call.tool !== "search" && h.run) { + let ran = { output: "" }; + try { ran = (await h.run(call)) || ran; } catch { ran = { output: "" }; } + const item = { + step: n, kind: "tool", tool: call.tool, label: call.tool, + text: sourceKept(ran.output) ? clip(ran.output, 700) : "", + kept: sourceKept(ran.output), empty: !sourceKept(ran.output), + }; + trace.push(item); + if (h.onStep) h.onStep(item); + continue; + } + const text = step.role === "outline" ? clipLines(got, 700) : clip(got, 700); + if (!text) continue; + const item = { step: n, kind: "model", role: step.role, text }; + trace.push(item); + if (h.onStep) h.onStep(item); + } + return { trace, answer: "", stopped: false }; +} diff --git a/tower.wasm b/tower.wasm new file mode 100644 index 0000000000000000000000000000000000000000..d87353a403d898d978af4f6833310bda187fc465 --- /dev/null +++ b/tower.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4423c88d872f1c214e60d8bf7d07aa523753a8eb3d552cd654200a15f580390f +size 2834099 diff --git a/vm.js b/vm.js new file mode 100644 index 0000000000000000000000000000000000000000..8c85a7d3b49942232945dd812a8e93d372a5d735 --- /dev/null +++ b/vm.js @@ -0,0 +1,117 @@ +// Champ's exec tool: EncryptidVM on this machine, over its MCP endpoint. +// One MCP session per page; the first command opens a sandbox on the first +// host EncryptidVM lists. Commands run in that guest shell, +// never on the host, and EncryptidVM records each one so it can be undone. +// The desk serves /mcp on this origin and forwards it to EncryptidVM. +// localStorage "champ.vm" names another endpoint. Nothing in the page URL can. + +const PROTOCOL = "2025-03-26"; + +export function vmEndpoint(storage) { + let saved = ""; + try { saved = (storage && storage.getItem("champ.vm")) || ""; } catch { saved = ""; } + if (saved) return saved; + if (typeof location !== "undefined" && location.origin && location.origin !== "null") { + return new URL("/mcp", location.origin).href; + } + return "http://127.0.0.1:8870/mcp"; +} + +// The MCP answer is JSON, or an SSE stream whose data lines carry it. +function rpcBody(text) { + const t = String(text || "").trim(); + if (t.startsWith("{")) return JSON.parse(t); + let last = null; + for (const line of t.split(/\r?\n/)) { + if (line.startsWith("data:")) { + try { last = JSON.parse(line.slice(5).trim()); } catch { /* not this line */ } + } + } + if (!last) throw new Error("unreadable answer"); + return last; +} + +export function createVM(opts) { + const o = opts || {}; + const endpoint = o.endpoint || "http://127.0.0.1:8870/mcp"; + const f = o.fetch || ((...a) => fetch(...a)); + let session = ""; + let open = false; + let seq = 0; + + async function post(method, params, notify) { + const headers = { "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": PROTOCOL }; + if (session) headers["Mcp-Session-Id"] = session; + const msg = { jsonrpc: "2.0", method }; + if (params) msg.params = params; + if (!notify) msg.id = ++seq; + const r = await f(endpoint, { method: "POST", headers, body: JSON.stringify(msg) }); + const sid = r.headers.get("Mcp-Session-Id"); + if (sid) session = sid; + if (notify) return null; + const text = await r.text(); + if (!r.ok) throw new Error((text || r.statusText || "error").trim().slice(0, 200)); + const body = rpcBody(text); + if (body.error) throw new Error(body.error.message || "error"); + return body.result; + } + + async function tool(name, args) { + const res = await post("tools/call", { name, arguments: args || {} }); + const text = ((res && res.content) || []).map((c) => c.text || "").join("\n"); + return { text, isError: !!(res && res.isError) }; + } + + async function ensure() { + if (!session) { + await post("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "champ", version: "1" } }); + await post("notifications/initialized", null, true); + open = false; + } + if (open) return; + let host = o.host || ""; + if (!host) { + const hosts = await tool("list_hosts"); + if (hosts.isError) throw new Error(hosts.text); + host = (hosts.text.split("\n")[0] || "").split("\t")[0].trim(); + if (!host || host === "no hosts") throw new Error("EncryptidVM has no host. Run tunneltug vm up."); + } + const r = await tool("sandbox_open", { host }); + if (r.isError) throw new Error(r.text); + open = true; + } + + return { + endpoint, + async exec(command) { + const cmd = String(command || "").trim(); + if (!cmd) return { output: "Missing command.", exit_code: 1 }; + try { + await ensure(); + let r = await tool("sandbox_exec", { command: cmd }); + if (r.isError && /not open|session/i.test(r.text)) { + session = ""; + await ensure(); + r = await tool("sandbox_exec", { command: cmd }); + } + const m = /\nexit: (-?\d+)/.exec("\n" + r.text); + const code = m ? Number(m[1]) : (r.isError ? 1 : 0); + return { output: r.text || "(no output)", exit_code: code }; + } catch (e) { + session = ""; + open = false; + const why = String((e && e.message) || e); + if (/Failed to fetch|NetworkError|ECONNREFUSED|fetch failed|Load failed/i.test(why)) { + return { output: "EncryptidVM is not answering at " + endpoint + ". Start it with: encryptidvm serve", exit_code: 1 }; + } + return { output: "EncryptidVM: " + why, exit_code: 1 }; + } + }, + async close() { + if (!session) return; + try { await f(endpoint, { method: "DELETE", headers: { "Mcp-Session-Id": session } }); } catch { /* gone */ } + session = ""; + open = false; + }, + }; +} diff --git a/wasm_exec.js b/wasm_exec.js new file mode 100644 index 0000000000000000000000000000000000000000..d71af9e97e8ca961f816f753afcf3738a50fd6a2 --- /dev/null +++ b/wasm_exec.js @@ -0,0 +1,575 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +"use strict"; + +(() => { + const enosys = () => { + const err = new Error("not implemented"); + err.code = "ENOSYS"; + return err; + }; + + if (!globalThis.fs) { + let outputBuf = ""; + globalThis.fs = { + constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused + writeSync(fd, buf) { + outputBuf += decoder.decode(buf); + const nl = outputBuf.lastIndexOf("\n"); + if (nl != -1) { + console.log(outputBuf.substring(0, nl)); + outputBuf = outputBuf.substring(nl + 1); + } + return buf.length; + }, + write(fd, buf, offset, length, position, callback) { + if (offset !== 0 || length !== buf.length || position !== null) { + callback(enosys()); + return; + } + const n = this.writeSync(fd, buf); + callback(null, n); + }, + chmod(path, mode, callback) { callback(enosys()); }, + chown(path, uid, gid, callback) { callback(enosys()); }, + close(fd, callback) { callback(enosys()); }, + fchmod(fd, mode, callback) { callback(enosys()); }, + fchown(fd, uid, gid, callback) { callback(enosys()); }, + fstat(fd, callback) { callback(enosys()); }, + fsync(fd, callback) { callback(null); }, + ftruncate(fd, length, callback) { callback(enosys()); }, + lchown(path, uid, gid, callback) { callback(enosys()); }, + link(path, link, callback) { callback(enosys()); }, + lstat(path, callback) { callback(enosys()); }, + mkdir(path, perm, callback) { callback(enosys()); }, + open(path, flags, mode, callback) { callback(enosys()); }, + read(fd, buffer, offset, length, position, callback) { callback(enosys()); }, + readdir(path, callback) { callback(enosys()); }, + readlink(path, callback) { callback(enosys()); }, + rename(from, to, callback) { callback(enosys()); }, + rmdir(path, callback) { callback(enosys()); }, + stat(path, callback) { callback(enosys()); }, + symlink(path, link, callback) { callback(enosys()); }, + truncate(path, length, callback) { callback(enosys()); }, + unlink(path, callback) { callback(enosys()); }, + utimes(path, atime, mtime, callback) { callback(enosys()); }, + }; + } + + if (!globalThis.process) { + globalThis.process = { + getuid() { return -1; }, + getgid() { return -1; }, + geteuid() { return -1; }, + getegid() { return -1; }, + getgroups() { throw enosys(); }, + pid: -1, + ppid: -1, + umask() { throw enosys(); }, + cwd() { throw enosys(); }, + chdir() { throw enosys(); }, + } + } + + if (!globalThis.path) { + globalThis.path = { + resolve(...pathSegments) { + return pathSegments.join("/"); + } + } + } + + if (!globalThis.crypto) { + throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)"); + } + + if (!globalThis.performance) { + throw new Error("globalThis.performance is not available, polyfill required (performance.now only)"); + } + + if (!globalThis.TextEncoder) { + throw new Error("globalThis.TextEncoder is not available, polyfill required"); + } + + if (!globalThis.TextDecoder) { + throw new Error("globalThis.TextDecoder is not available, polyfill required"); + } + + const encoder = new TextEncoder("utf-8"); + const decoder = new TextDecoder("utf-8"); + + globalThis.Go = class { + constructor() { + this.argv = ["js"]; + this.env = {}; + this.exit = (code) => { + if (code !== 0) { + console.warn("exit code:", code); + } + }; + this._exitPromise = new Promise((resolve) => { + this._resolveExitPromise = resolve; + }); + this._pendingEvent = null; + this._scheduledTimeouts = new Map(); + this._nextCallbackTimeoutID = 1; + + const setInt64 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); + } + + const setInt32 = (addr, v) => { + this.mem.setUint32(addr + 0, v, true); + } + + const getInt64 = (addr) => { + const low = this.mem.getUint32(addr + 0, true); + const high = this.mem.getInt32(addr + 4, true); + return low + high * 4294967296; + } + + const loadValue = (addr) => { + const f = this.mem.getFloat64(addr, true); + if (f === 0) { + return undefined; + } + if (!isNaN(f)) { + return f; + } + + const id = this.mem.getUint32(addr, true); + return this._values[id]; + } + + const storeValue = (addr, v) => { + const nanHead = 0x7FF80000; + + if (typeof v === "number" && v !== 0) { + if (isNaN(v)) { + this.mem.setUint32(addr + 4, nanHead, true); + this.mem.setUint32(addr, 0, true); + return; + } + this.mem.setFloat64(addr, v, true); + return; + } + + if (v === undefined) { + this.mem.setFloat64(addr, 0, true); + return; + } + + let id = this._ids.get(v); + if (id === undefined) { + id = this._idPool.pop(); + if (id === undefined) { + id = this._values.length; + } + this._values[id] = v; + this._goRefCounts[id] = 0; + this._ids.set(v, id); + } + this._goRefCounts[id]++; + let typeFlag = 0; + switch (typeof v) { + case "object": + if (v !== null) { + typeFlag = 1; + } + break; + case "string": + typeFlag = 2; + break; + case "symbol": + typeFlag = 3; + break; + case "function": + typeFlag = 4; + break; + } + this.mem.setUint32(addr + 4, nanHead | typeFlag, true); + this.mem.setUint32(addr, id, true); + } + + const loadSlice = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + return new Uint8Array(this._inst.exports.mem.buffer, array, len); + } + + const loadSliceOfValues = (addr) => { + const array = getInt64(addr + 0); + const len = getInt64(addr + 8); + const a = new Array(len); + for (let i = 0; i < len; i++) { + a[i] = loadValue(array + i * 8); + } + return a; + } + + const loadString = (addr) => { + const saddr = getInt64(addr + 0); + const len = getInt64(addr + 8); + return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len)); + } + + const testCallExport = (a, b) => { + this._inst.exports.testExport0(); + return this._inst.exports.testExport(a, b); + } + + const timeOrigin = Date.now() - performance.now(); + this.importObject = { + _gotest: { + add: (a, b) => a + b, + callExport: testCallExport, + }, + gojs: { + // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters) + // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported + // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function). + // This changes the SP, thus we have to update the SP used by the imported function. + + // func wasmExit(code int32) + "runtime.wasmExit": (sp) => { + sp >>>= 0; + const code = this.mem.getInt32(sp + 8, true); + this.exited = true; + delete this._inst; + delete this._values; + delete this._goRefCounts; + delete this._ids; + delete this._idPool; + this.exit(code); + }, + + // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32) + "runtime.wasmWrite": (sp) => { + sp >>>= 0; + const fd = getInt64(sp + 8); + const p = getInt64(sp + 16); + const n = this.mem.getInt32(sp + 24, true); + fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n)); + }, + + // func resetMemoryDataView() + "runtime.resetMemoryDataView": (sp) => { + sp >>>= 0; + this.mem = new DataView(this._inst.exports.mem.buffer); + }, + + // func nanotime1() int64 + "runtime.nanotime1": (sp) => { + sp >>>= 0; + setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000); + }, + + // func walltime() (sec int64, nsec int32) + "runtime.walltime": (sp) => { + sp >>>= 0; + const msec = (new Date).getTime(); + setInt64(sp + 8, msec / 1000); + this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true); + }, + + // func scheduleTimeoutEvent(delay int64) int32 + "runtime.scheduleTimeoutEvent": (sp) => { + sp >>>= 0; + const id = this._nextCallbackTimeoutID; + this._nextCallbackTimeoutID++; + this._scheduledTimeouts.set(id, setTimeout( + () => { + this._resume(); + while (this._scheduledTimeouts.has(id)) { + // for some reason Go failed to register the timeout event, log and try again + // (temporary workaround for https://github.com/golang/go/issues/28975) + console.warn("scheduleTimeoutEvent: missed timeout event"); + this._resume(); + } + }, + getInt64(sp + 8), + )); + this.mem.setInt32(sp + 16, id, true); + }, + + // func clearTimeoutEvent(id int32) + "runtime.clearTimeoutEvent": (sp) => { + sp >>>= 0; + const id = this.mem.getInt32(sp + 8, true); + clearTimeout(this._scheduledTimeouts.get(id)); + this._scheduledTimeouts.delete(id); + }, + + // func getRandomData(r []byte) + "runtime.getRandomData": (sp) => { + sp >>>= 0; + crypto.getRandomValues(loadSlice(sp + 8)); + }, + + // func finalizeRef(v ref) + "syscall/js.finalizeRef": (sp) => { + sp >>>= 0; + const id = this.mem.getUint32(sp + 8, true); + this._goRefCounts[id]--; + if (this._goRefCounts[id] === 0) { + const v = this._values[id]; + this._values[id] = null; + this._ids.delete(v); + this._idPool.push(id); + } + }, + + // func stringVal(value string) ref + "syscall/js.stringVal": (sp) => { + sp >>>= 0; + storeValue(sp + 24, loadString(sp + 8)); + }, + + // func valueGet(v ref, p string) ref + "syscall/js.valueGet": (sp) => { + sp >>>= 0; + const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16)); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 32, result); + }, + + // func valueSet(v ref, p string, x ref) + "syscall/js.valueSet": (sp) => { + sp >>>= 0; + Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32)); + }, + + // func valueDelete(v ref, p string) + "syscall/js.valueDelete": (sp) => { + sp >>>= 0; + Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16)); + }, + + // func valueIndex(v ref, i int) ref + "syscall/js.valueIndex": (sp) => { + sp >>>= 0; + storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16))); + }, + + // valueSetIndex(v ref, i int, x ref) + "syscall/js.valueSetIndex": (sp) => { + sp >>>= 0; + Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24)); + }, + + // func valueCall(v ref, m string, args []ref) (ref, bool) + "syscall/js.valueCall": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const m = Reflect.get(v, loadString(sp + 16)); + const args = loadSliceOfValues(sp + 32); + const result = Reflect.apply(m, v, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 56, result); + this.mem.setUint8(sp + 64, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 56, err); + this.mem.setUint8(sp + 64, 0); + } + }, + + // func valueInvoke(v ref, args []ref) (ref, bool) + "syscall/js.valueInvoke": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const args = loadSliceOfValues(sp + 16); + const result = Reflect.apply(v, undefined, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, result); + this.mem.setUint8(sp + 48, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, err); + this.mem.setUint8(sp + 48, 0); + } + }, + + // func valueNew(v ref, args []ref) (ref, bool) + "syscall/js.valueNew": (sp) => { + sp >>>= 0; + try { + const v = loadValue(sp + 8); + const args = loadSliceOfValues(sp + 16); + const result = Reflect.construct(v, args); + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, result); + this.mem.setUint8(sp + 48, 1); + } catch (err) { + sp = this._inst.exports.getsp() >>> 0; // see comment above + storeValue(sp + 40, err); + this.mem.setUint8(sp + 48, 0); + } + }, + + // func valueLength(v ref) int + "syscall/js.valueLength": (sp) => { + sp >>>= 0; + setInt64(sp + 16, parseInt(loadValue(sp + 8).length)); + }, + + // valuePrepareString(v ref) (ref, int) + "syscall/js.valuePrepareString": (sp) => { + sp >>>= 0; + const str = encoder.encode(String(loadValue(sp + 8))); + storeValue(sp + 16, str); + setInt64(sp + 24, str.length); + }, + + // valueLoadString(v ref, b []byte) + "syscall/js.valueLoadString": (sp) => { + sp >>>= 0; + const str = loadValue(sp + 8); + loadSlice(sp + 16).set(str); + }, + + // func valueInstanceOf(v ref, t ref) bool + "syscall/js.valueInstanceOf": (sp) => { + sp >>>= 0; + this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0); + }, + + // func copyBytesToGo(dst []byte, src ref) (int, bool) + "syscall/js.copyBytesToGo": (sp) => { + sp >>>= 0; + const dst = loadSlice(sp + 8); + const src = loadValue(sp + 32); + if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { + this.mem.setUint8(sp + 48, 0); + return; + } + const toCopy = src.subarray(0, dst.length); + dst.set(toCopy); + setInt64(sp + 40, toCopy.length); + this.mem.setUint8(sp + 48, 1); + }, + + // func copyBytesToJS(dst ref, src []byte) (int, bool) + "syscall/js.copyBytesToJS": (sp) => { + sp >>>= 0; + const dst = loadValue(sp + 8); + const src = loadSlice(sp + 16); + if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { + this.mem.setUint8(sp + 48, 0); + return; + } + const toCopy = src.subarray(0, dst.length); + dst.set(toCopy); + setInt64(sp + 40, toCopy.length); + this.mem.setUint8(sp + 48, 1); + }, + + "debug": (value) => { + console.log(value); + }, + } + }; + } + + async run(instance) { + if (!(instance instanceof WebAssembly.Instance)) { + throw new Error("Go.run: WebAssembly.Instance expected"); + } + this._inst = instance; + this.mem = new DataView(this._inst.exports.mem.buffer); + this._values = [ // JS values that Go currently has references to, indexed by reference id + NaN, + 0, + null, + true, + false, + globalThis, + this, + ]; + this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id + this._ids = new Map([ // mapping from JS values to reference ids + [0, 1], + [null, 2], + [true, 3], + [false, 4], + [globalThis, 5], + [this, 6], + ]); + this._idPool = []; // unused ids that have been garbage collected + this.exited = false; // whether the Go program has exited + + // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory. + let offset = 4096; + + const strPtr = (str) => { + const ptr = offset; + const bytes = encoder.encode(str + "\0"); + new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes); + offset += bytes.length; + if (offset % 8 !== 0) { + offset += 8 - (offset % 8); + } + return ptr; + }; + + const argc = this.argv.length; + + const argvPtrs = []; + this.argv.forEach((arg) => { + argvPtrs.push(strPtr(arg)); + }); + argvPtrs.push(0); + + const keys = Object.keys(this.env).sort(); + keys.forEach((key) => { + argvPtrs.push(strPtr(`${key}=${this.env[key]}`)); + }); + argvPtrs.push(0); + + const argv = offset; + argvPtrs.forEach((ptr) => { + this.mem.setUint32(offset, ptr, true); + this.mem.setUint32(offset + 4, 0, true); + offset += 8; + }); + + // The linker guarantees global data starts from at least wasmMinDataAddr. + // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr. + const wasmMinDataAddr = 4096 + 8192; + if (offset >= wasmMinDataAddr) { + throw new Error("total length of command line and environment variables exceeds limit"); + } + + this._inst.exports.run(argc, argv); + if (this.exited) { + this._resolveExitPromise(); + } + await this._exitPromise; + } + + _resume() { + if (this.exited) { + throw new Error("Go program has already exited"); + } + this._inst.exports.resume(); + if (this.exited) { + this._resolveExitPromise(); + } + } + + _makeFuncWrapper(id) { + const go = this; + return function () { + const event = { id: id, this: this, args: arguments }; + go._pendingEvent = event; + go._resume(); + return event.result; + }; + } + } +})(); diff --git a/webgpu/webgpu-exec.js b/webgpu/webgpu-exec.js new file mode 100644 index 0000000000000000000000000000000000000000..8a75a2b05283db4025348e0d393d19324e6b83db --- /dev/null +++ b/webgpu/webgpu-exec.js @@ -0,0 +1,292 @@ +// WebGPU's hands in the JS host: a module's webgpu.h (WASMWebGPU/src/remote.cc) +// hands a batch of commands to its suspending import (webgpu.batch; HeapVM's +// heap.gpu), and this runs them against the host's own navigator.gpu. A batch +// that awaits (an adapter, a device, a mapped range) suspends the module until +// the promise settles; a batch that does not is run and answered at once. A +// page is asked only for a display: an OffscreenCanvas it transfers here +// (answered with canvasAnswer). +// +// A batch is u32 jsonLen | JSON commands | blob. The reply is +// u32 textLen | `key=value` lines | bytes. + +const objs = new Map(); // module id -> GPU object +const mapped = new Map(); // buffer id -> its mapped ArrayBuffer +const pulled = new Map(); // buffer id -> bytes of a map the module is reading +const canvases = new Map(); // surface id -> OffscreenCanvas +const displays = new Map(); // selector -> Promise, one transfer each +const waiting = new Map(); // selector -> {resolve, reject} for the page's answer +const pending = []; // uncaptured errors and lost devices, for the next reply + +function esc(v) { + return String(v).replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\t/g, "\\t"); +} + +function errText(e) { + return e && e.message ? e.message : String(e); +} + +function errorKind(e) { + return typeof GPUValidationError !== "undefined" && e instanceof GPUValidationError + ? "validation" + : typeof GPUOutOfMemoryError !== "undefined" && e instanceof GPUOutOfMemoryError + ? "out-of-memory" + : "internal"; +} + +// Arguments: {"$":id} is an object, {"#":[off,len]} blob bytes, {"u":1} a +// left-out optional argument. +function resolve(v, blob) { + if (Array.isArray(v)) return v.map((x) => resolve(x, blob)); + if (v && typeof v === "object") { + if ("$" in v && Object.keys(v).length === 1) return objs.get(v.$); + if ("#" in v && Object.keys(v).length === 1) return blob.subarray(v["#"][0], v["#"][0] + v["#"][1]); + if ("u" in v && Object.keys(v).length === 1) return undefined; + const out = {}; + for (const k of Object.keys(v)) out[k] = resolve(v[k], blob); + return out; + } + return v; +} + +// The display for `sel`: the page transfers its canvas once; every surface +// on that selector draws to it after. +function display(sel) { + let p = displays.get(sel); + if (!p) { + p = new Promise((res, rej) => waiting.set(sel, { resolve: res, reject: rej })); + displays.set(sel, p); + self.postMessage({ type: "vgpu-canvas", sel }); + } + return p; +} + +// The page's answer to a vgpu-canvas request (shell-worker.js onmessage). +export function canvasAnswer(msg) { + const w = waiting.get(msg.sel); + if (!w) return; + waiting.delete(msg.sel); + if (msg.canvas) { + w.resolve(msg.canvas); + } else { + displays.delete(msg.sel); + w.reject(new Error(msg.error || "no canvas for " + msg.sel)); + } +} + +function watchDevice(id, device) { + device.addEventListener("uncapturederror", (ev) => { + const e = ev.error; + pending.push("uncaptured=" + esc(id + "\t" + errorKind(e) + "\t" + (e && e.message ? e.message : "error"))); + }); + device.lost.then((info) => { + pending.push("lost=" + esc(id + "\t" + (info.reason || "unknown") + "\t" + (info.message || ""))); + }); +} + +function capsLines(lines, features, limits) { + for (const f of features) lines.push("feature=" + esc(f)); + for (const k in limits) { + const v = limits[k]; + if (typeof v === "number") lines.push("limit." + k + "=" + v); + } +} + +// One command. Returns a promise only when the command has to await. +function step(cmd, blob, lines, out) { + switch (cmd.o) { + case "new": { + const parent = cmd.t ? objs.get(cmd.t) : null; + const args = resolve(cmd.a, blob); + const made = parent[cmd.m](...args); + objs.set(cmd.id, made); + if (cmd.m === "createBuffer" && args[0] && args[0].mappedAtCreation) { + mapped.set(cmd.id, made.getMappedRange()); + } + return; + } + case "call": { + const target = objs.get(cmd.t); + if (cmd.m === "destroy") mapped.delete(cmd.t); + target[cmd.m](...resolve(cmd.a, blob)); + return; + } + case "set": + objs.get(cmd.t)[cmd.k] = cmd.v; + return; + case "drop": + objs.delete(cmd.t); + mapped.delete(cmd.t); + pulled.delete(cmd.t); + return; + case "wgsl": + if (navigator.gpu && navigator.gpu.wgslLanguageFeatures) + for (const f of navigator.gpu.wgslLanguageFeatures) lines.push("wgsl=" + esc(f)); + return; + case "adapter": + return (async () => { + if (!navigator.gpu) { + lines.push("unavailable=1"); + throw new Error("WebGPU is not available in this worker (navigator.gpu is missing)"); + } + const adapter = await navigator.gpu.requestAdapter(...resolve(cmd.a, blob)); + if (!adapter) { + lines.push("unavailable=1"); + throw new Error("no WebGPU adapter"); + } + objs.set(cmd.id, adapter); + const info = adapter.info || {}; + lines.push("vendor=" + esc(info.vendor || "")); + lines.push("architecture=" + esc(info.architecture || "")); + lines.push("device=" + esc(info.device || "")); + lines.push("description=" + esc(info.description || "")); + if (info.subgroupMinSize) lines.push("subgroupMinSize=" + info.subgroupMinSize); + if (info.subgroupMaxSize) lines.push("subgroupMaxSize=" + info.subgroupMaxSize); + if (info.isFallbackAdapter) lines.push("fallback=1"); + capsLines(lines, adapter.features, adapter.limits); + })(); + case "device": + return (async () => { + const adapter = objs.get(cmd.t); + const device = await adapter.requestDevice(...resolve(cmd.a, blob)); + objs.set(cmd.id, device); + objs.set(cmd.q, device.queue); + watchDevice(cmd.id, device); + capsLines(lines, device.features, device.limits); + })(); + case "newAsync": + return (async () => { + const parent = objs.get(cmd.t); + try { + objs.set(cmd.id, await parent[cmd.m](...resolve(cmd.a, blob))); + } catch (e) { + if (e && e.reason) lines.push("reason=" + esc(e.reason)); + throw e; + } + })(); + case "map": + return (async () => { + const buf = objs.get(cmd.t); + await buf.mapAsync(cmd.mode, cmd.off, cmd.size); + const range = buf.getMappedRange(cmd.off, cmd.size); + mapped.set(cmd.t, range); + const bytes = new Uint8Array(range.slice(0)); + pulled.set(cmd.t, bytes); + lines.push("total=" + bytes.length); + out.bin = bytes.subarray(0, Math.min(bytes.length, 192 * 1024)); + })(); + case "pull": { + const bytes = pulled.get(cmd.t); + if (!bytes) throw new Error("the buffer is not mapped"); + out.bin = bytes.subarray(cmd.from, cmd.from + cmd.len); + return; + } + case "unmap": { + const buf = objs.get(cmd.t); + const range = mapped.get(cmd.t); + if (cmd.w && range) new Uint8Array(range).set(blob.subarray(cmd.w["#"][0], cmd.w["#"][0] + cmd.w["#"][1])); + mapped.delete(cmd.t); + pulled.delete(cmd.t); + buf.unmap(); + return; + } + case "done": + return objs.get(cmd.t).onSubmittedWorkDone(); + case "pop": + return objs + .get(cmd.t) + .popErrorScope() + .then((e) => { + if (!e) { + lines.push("type=none"); + return; + } + lines.push("type=" + errorKind(e)); + lines.push("msg=" + esc(e.message || "")); + }); + case "info": + return objs + .get(cmd.t) + .getCompilationInfo() + .then((info) => { + for (const m of info.messages) + lines.push( + "msg=" + esc([m.type, m.lineNum, m.linePos, m.offset, m.length, m.message].join("\t")) + ); + }); + case "surface": + return (async () => { + const canvas = await display(cmd.sel); + const ctx = canvas.getContext("webgpu"); + if (!ctx) throw new Error("no webgpu context on " + cmd.sel); + canvases.set(cmd.id, canvas); + objs.set(cmd.id, ctx); + lines.push("preferred=" + esc(navigator.gpu.getPreferredCanvasFormat())); + })(); + case "canvas": { + const canvas = canvases.get(cmd.t); + if (canvas && cmd.w && cmd.h) { + canvas.width = cmd.w; + canvas.height = cmd.h; + } + return; + } + default: + throw new Error("unknown vgpu command " + cmd.o); + } +} + +function failed(st, cmd, e) { + st.lines.push("error=" + esc(cmd.o + (cmd.m ? " " + cmd.m : "") + ": " + errText(e))); +} + +// Runs the batch from command st.i on. Stays synchronous until a command +// returns a promise; the rest of the batch then runs after it settles. +function drive(st) { + while (st.i < st.cmds.length) { + const cmd = st.cmds[st.i++]; + let r; + try { + r = step(cmd, st.blob, st.lines, st.out); + } catch (e) { + failed(st, cmd, e); + continue; + } + if (r && typeof r.then === "function") { + return r.then( + () => drive(st), + (e) => { + failed(st, cmd, e); + return drive(st); + } + ); + } + } + while (pending.length) st.lines.push(pending.shift()); + return { text: st.lines.join("\n"), bin: st.out.bin }; +} + +// One batch: {text, bin}, or a promise of it when a command awaited. +// `bytes` is a view of the module's memory; it is only read before the +// module resumes, and WebGPU copies what it keeps. +export function runBatch(bytes) { + const jlen = new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0, true); + const cmds = JSON.parse(new TextDecoder().decode(bytes.subarray(4, 4 + jlen))); + const st = { cmds, blob: bytes.subarray(4 + jlen), lines: [], out: { bin: null }, i: 0 }; + return drive(st); +} + +// The reply, as webgpu_remote.cc reads it, into [dst, dst + cap). Its size. +export function writeReply(reply, dst) { + let text = new TextEncoder().encode(reply.text); + let bin = reply.bin || new Uint8Array(0); + if (4 + text.length + bin.length > dst.length) { + text = new TextEncoder().encode( + "error=vgpu: reply too large (" + (4 + text.length + bin.length) + " bytes)" + ); + bin = new Uint8Array(0); + } + new DataView(dst.buffer, dst.byteOffset, 4).setUint32(0, text.length, true); + dst.set(text, 4); + dst.set(bin, 4 + text.length); + return 4 + text.length + bin.length; +}