@witbitz/sdk 4.7.0 → 4.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/acctV2UiCore.js +2 -2
- package/codeCache.js +1 -1
- package/deviceKeyCore.js +44 -6
- package/emailFork.js +5 -4
- package/emptySpaces.js +12 -6
- package/idb.js +31 -4
- package/idbSeal.js +7 -0
- package/l1-worker-src.js +1 -1
- package/manifest.json +30 -30
- package/memberChange.js +9 -0
- package/nativePush.js +6 -0
- package/package.json +2 -2
- package/reqEnvelope.js +1 -1
- package/roomName.js +22 -6
- package/roomRoles.js +22 -0
- package/sdkAccount.js +3 -1
- package/sdkBackupV2.js +20 -9
- package/sdkCloudDevice.js +18 -9
- package/sdkExports.js +1 -1
- package/sdkInvitations.js +2 -2
- package/sdkPlan.js +21 -9
- package/sdkRekey.js +17 -7
- package/sdkVault.js +1 -1
- package/spaceClient.js +2 -1
- package/util.js +11 -1
- package/vault-core.js +41 -11
- package/vault-kit.mjs +1 -1
- package/witbitz-admin.mjs +10 -10
- package/witbitz-sdk.js +49 -23
package/l1-worker-src.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// The Witbitz vault's key worker, as one pinned module (vault-core.js runs it from memory). Generated by the SDK release; do not edit.
|
|
2
|
-
export const SRC = "var __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __esm = (fn, res, err) => function __init() {\n if (err) throw err[0];\n try {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n } catch (e) {\n throw err = [e], e;\n }\n};\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// spaces/public/sdk/4.7.0/ohttp.js\nvar ohttp_exports = {};\n__export(ohttp_exports, {\n SUITE: () => SUITE,\n _eq: () => eq,\n cat: () => cat,\n decapsulateRequest: () => decapsulateRequest,\n decapsulateResponse: () => decapsulateResponse,\n decodeRequest: () => decodeRequest,\n decodeResponse: () => decodeResponse,\n encapsulateRequest: () => encapsulateRequest,\n encapsulateResponse: () => encapsulateResponse,\n encodeRequest: () => encodeRequest,\n encodeResponse: () => encodeResponse,\n hex: () => hex2,\n i2osp: () => i2osp,\n kemDecap: () => kemDecap,\n kemEncap: () => kemEncap,\n keySchedule: () => keySchedule,\n unhex: () => unhex\n});\nasync function hmac(key, data) {\n const k = await subtle.importKey(\"raw\", key.length ? key : new Uint8Array(32), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return new Uint8Array(await subtle.sign(\"HMAC\", k, data));\n}\nasync function expand(prk, info, L) {\n const out = [];\n let t = new Uint8Array(0);\n for (let i = 1; out.reduce((n, b) => n + b.length, 0) < L; i++) {\n t = await hmac(prk, cat(t, info, new Uint8Array([i])));\n out.push(t);\n }\n return cat(...out).slice(0, L);\n}\nasync function extractAndExpand(dh, kemContext) {\n const eaePrk = await labeledExtract(new Uint8Array(0), \"eae_prk\", dh, kemSuite);\n return labeledExpand(eaePrk, \"shared_secret\", kemContext, SUITE.Nsecret, kemSuite);\n}\nasync function kemEncap(pkRraw, ephemeral) {\n const pkR = await importPub(pkRraw);\n const kp = ephemeral || await subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\"deriveBits\"]);\n const dh = new Uint8Array(await subtle.deriveBits({ name: \"ECDH\", public: pkR }, kp.privateKey, 256));\n const enc15 = new Uint8Array(await subtle.exportKey(\"raw\", kp.publicKey));\n const shared = await extractAndExpand(dh, cat(enc15, pkRraw));\n return { shared, enc: enc15 };\n}\nasync function kemDecap(enc15, skR, pkRraw) {\n const pkE = await importPub(enc15);\n const dh = new Uint8Array(await subtle.deriveBits({ name: \"ECDH\", public: pkE }, skR, 256));\n return extractAndExpand(dh, cat(enc15, pkRraw));\n}\nasync function keySchedule(shared, info) {\n const pskIdHash = await labeledExtract(new Uint8Array(0), \"psk_id_hash\", new Uint8Array(0), hpkeSuite);\n const infoHash = await labeledExtract(new Uint8Array(0), \"info_hash\", info, hpkeSuite);\n const ctx = cat(new Uint8Array([0]), pskIdHash, infoHash);\n const secret = await labeledExtract(shared, \"secret\", new Uint8Array(0), hpkeSuite);\n const key = await labeledExpand(secret, \"key\", ctx, SUITE.Nk, hpkeSuite);\n const baseNonce = await labeledExpand(secret, \"base_nonce\", ctx, SUITE.Nn, hpkeSuite);\n const exporter = await labeledExpand(secret, \"exp\", ctx, SUITE.Nh, hpkeSuite);\n return { key, baseNonce, exporter };\n}\nasync function encapsulateRequest(keyConfig, bhttp, _ephemeral) {\n const { keyId, publicKey } = keyConfig;\n const { shared, enc: enc15 } = await kemEncap(publicKey, _ephemeral);\n const ks = await keySchedule(shared, reqInfo(keyId));\n const ct = await aeadSeal(ks.key, ks.baseNonce, new Uint8Array(0), bhttp);\n return { encRequest: cat(hdr(keyId), enc15, ct), ks, enc: enc15 };\n}\nasync function decapsulateRequest(encRequest, skR, pkRraw) {\n const keyId = encRequest[0];\n const enc15 = encRequest.slice(7, 7 + SUITE.Nenc);\n const ct = encRequest.slice(7 + SUITE.Nenc);\n const shared = await kemDecap(enc15, skR, pkRraw);\n const ks = await keySchedule(shared, reqInfo(keyId));\n const bhttp = await aeadOpen(ks.key, ks.baseNonce, new Uint8Array(0), ct);\n return { keyId, bhttp, ks, enc: enc15 };\n}\nasync function encapsulateResponse(ks, enc15, bhttpResp, _fixedNonce) {\n const L = Math.max(SUITE.Nn, SUITE.Nk);\n const responseNonce = _fixedNonce || globalThis.crypto.getRandomValues(new Uint8Array(L));\n const secret = await exportSecret(ks, \"message/bhttp response\", L);\n const prk = await extract(cat(enc15, responseNonce), secret);\n const key = await expand(prk, cat(te.encode(\"key\")), SUITE.Nk);\n const nonce = await expand(prk, cat(te.encode(\"nonce\")), SUITE.Nn);\n const ct = await aeadSeal(key, nonce, new Uint8Array(0), bhttpResp);\n return cat(responseNonce, ct);\n}\nasync function decapsulateResponse(ks, enc15, encResponse) {\n const L = Math.max(SUITE.Nn, SUITE.Nk);\n const responseNonce = encResponse.slice(0, L);\n const ct = encResponse.slice(L);\n const secret = await exportSecret(ks, \"message/bhttp response\", L);\n const prk = await extract(cat(enc15, responseNonce), secret);\n const key = await expand(prk, cat(te.encode(\"key\")), SUITE.Nk);\n const nonce = await expand(prk, cat(te.encode(\"nonce\")), SUITE.Nn);\n return aeadOpen(key, nonce, new Uint8Array(0), ct);\n}\nfunction putVarint(n) {\n if (n < 64) return new Uint8Array([n]);\n if (n < 16384) return new Uint8Array([64 | n >> 8, n & 255]);\n if (n < 1073741824) return new Uint8Array([128 | n >> 24, n >> 16 & 255, n >> 8 & 255, n & 255]);\n throw new Error(\"varint too large\");\n}\nfunction getVarint(b, i) {\n const p = b[i] >> 6, len = 1 << p;\n let v = b[i] & 63;\n for (let j = 1; j < len; j++) v = v * 256 + b[i + j];\n return [v, i + len];\n}\nfunction encodeRequest({ method = \"POST\", scheme = \"https\", authority, path = \"/\", headers = {}, body = new Uint8Array(0) }) {\n const control = cat(strField(method), strField(scheme), strField(authority), strField(path));\n let fields = new Uint8Array(0);\n for (const [k, v] of Object.entries(headers)) fields = cat(fields, strField(k.toLowerCase()), strField(String(v)));\n const content = cat(putVarint(body.length), body);\n return cat(new Uint8Array([0]), control, putVarint(fields.length), fields, content, putVarint(0));\n}\nfunction decodeRequest(b) {\n let i = 1;\n let method, scheme, authority, path;\n [method, i] = getStr(b, i);\n [scheme, i] = getStr(b, i);\n [authority, i] = getStr(b, i);\n [path, i] = getStr(b, i);\n let flen;\n [flen, i] = getVarint(b, i);\n const fEnd = i + flen;\n const headers = {};\n while (i < fEnd) {\n let k, v;\n [k, i] = getStr(b, i);\n [v, i] = getStr(b, i);\n headers[k] = v;\n }\n let clen;\n [clen, i] = getVarint(b, i);\n const body = b.slice(i, i + clen);\n return { method, scheme, authority, path, headers, body };\n}\nfunction encodeResponse({ status = 200, headers = {}, body = new Uint8Array(0) }) {\n let fields = new Uint8Array(0);\n for (const [k, v] of Object.entries(headers)) fields = cat(fields, strField(k.toLowerCase()), strField(String(v)));\n const content = cat(putVarint(body.length), body);\n return cat(new Uint8Array([1]), putVarint(status), putVarint(fields.length), fields, content, putVarint(0));\n}\nfunction decodeResponse(b) {\n let i = 1;\n let status;\n [status, i] = getVarint(b, i);\n let flen;\n [flen, i] = getVarint(b, i);\n const fEnd = i + flen;\n const headers = {};\n while (i < fEnd) {\n let k, v;\n [k, i] = getStr(b, i);\n [v, i] = getStr(b, i);\n headers[k] = v;\n }\n let clen;\n [clen, i] = getVarint(b, i);\n return { status, headers, body: b.slice(i, i + clen) };\n}\nvar subtle, SUITE, te, cat, i2osp, hex2, unhex, eq, extract, kemSuite, hpkeSuite, labeledExtract, labeledExpand, importPub, aeadSeal, aeadOpen, exportSecret, reqInfo, hdr, strField, getStr;\nvar init_ohttp = __esm({\n \"spaces/public/sdk/4.7.0/ohttp.js\"() {\n subtle = globalThis.crypto && globalThis.crypto.subtle;\n if (!subtle) throw new Error(\"ohttp: WebCrypto subtle unavailable\");\n SUITE = { kemId: 16, kdfId: 1, aeadId: 1, Nsecret: 32, Nh: 32, Nk: 16, Nn: 12, Nenc: 65, Npk: 65 };\n te = new TextEncoder();\n cat = (...as) => {\n let n = 0;\n for (const a of as) n += a.length;\n const o = new Uint8Array(n);\n let i = 0;\n for (const a of as) {\n o.set(a, i);\n i += a.length;\n }\n return o;\n };\n i2osp = (n, len) => {\n const o = new Uint8Array(len);\n for (let i = len - 1; i >= 0; i--) {\n o[i] = n & 255;\n n = Math.floor(n / 256);\n }\n return o;\n };\n hex2 = (u8) => [...u8].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n unhex = (s) => {\n const o = new Uint8Array(s.length / 2);\n for (let i = 0; i < o.length; i++) o[i] = parseInt(s.substr(i * 2, 2), 16);\n return o;\n };\n eq = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);\n extract = (salt, ikm) => hmac(salt, ikm);\n kemSuite = cat(te.encode(\"KEM\"), i2osp(SUITE.kemId, 2));\n hpkeSuite = cat(te.encode(\"HPKE\"), i2osp(SUITE.kemId, 2), i2osp(SUITE.kdfId, 2), i2osp(SUITE.aeadId, 2));\n labeledExtract = (salt, label, ikm, suite) => extract(salt, cat(te.encode(\"HPKE-v1\"), suite, te.encode(label), ikm));\n labeledExpand = (prk, label, info, L, suite) => expand(prk, cat(i2osp(L, 2), te.encode(\"HPKE-v1\"), suite, te.encode(label), info), L);\n importPub = (raw) => subtle.importKey(\"raw\", raw, { name: \"ECDH\", namedCurve: \"P-256\" }, true, []);\n aeadSeal = async (key, nonce, aad, pt) => new Uint8Array(await subtle.encrypt({ name: \"AES-GCM\", iv: nonce, additionalData: aad, tagLength: 128 }, await subtle.importKey(\"raw\", key, \"AES-GCM\", false, [\"encrypt\"]), pt));\n aeadOpen = async (key, nonce, aad, ct) => new Uint8Array(await subtle.decrypt({ name: \"AES-GCM\", iv: nonce, additionalData: aad, tagLength: 128 }, await subtle.importKey(\"raw\", key, \"AES-GCM\", false, [\"decrypt\"]), ct));\n exportSecret = (ks, ctx, L) => labeledExpand(ks.exporter, \"sec\", te.encode(ctx), L, hpkeSuite);\n reqInfo = (keyId) => cat(te.encode(\"message/bhttp request\"), new Uint8Array([0]), new Uint8Array([keyId]), i2osp(SUITE.kemId, 2), i2osp(SUITE.kdfId, 2), i2osp(SUITE.aeadId, 2));\n hdr = (keyId) => cat(new Uint8Array([keyId]), i2osp(SUITE.kemId, 2), i2osp(SUITE.kdfId, 2), i2osp(SUITE.aeadId, 2));\n strField = (s) => {\n const u = te.encode(s);\n return cat(putVarint(u.length), u);\n };\n getStr = (b, i) => {\n const [n, j] = getVarint(b, i);\n return [new TextDecoder().decode(b.slice(j, j + n)), j + n];\n };\n }\n});\n\n// spaces/public/sdk/4.7.0/cbor.js\nfunction decode(bytes3) {\n const b = toBytes(bytes3);\n const [value, off] = readItem(b, 0);\n if (value === BREAK) throw new Error(\"cbor: stray break byte\");\n if (off !== b.length) throw new Error(`cbor: ${b.length - off} trailing bytes`);\n return value;\n}\nfunction toBytes(x) {\n if (x instanceof Uint8Array) return x;\n if (x instanceof ArrayBuffer) return new Uint8Array(x);\n if (ArrayBuffer.isView(x)) return new Uint8Array(x.buffer, x.byteOffset, x.byteLength);\n throw new Error(\"cbor: expected bytes\");\n}\nfunction need(b, off, n) {\n if (n < 0 || off + n > b.length) throw new Error(\"cbor: truncated\");\n return off + n;\n}\nfunction readHead(b, off) {\n need(b, off, 1);\n const ib = b[off];\n const major = ib >> 5;\n const ai = ib & 31;\n if (ai < 24) return [major, ai, off + 1];\n if (ai === 24) {\n need(b, off + 1, 1);\n return [major, b[off + 1], off + 2];\n }\n if (ai === 25) {\n need(b, off + 1, 2);\n return [major, b[off + 1] << 8 | b[off + 2], off + 3];\n }\n if (ai === 26) {\n need(b, off + 1, 4);\n const v = (b[off + 1] << 24 | b[off + 2] << 16 | b[off + 3] << 8 | b[off + 4]) >>> 0;\n return [major, v, off + 5];\n }\n if (ai === 27) {\n need(b, off + 1, 8);\n let v = 0;\n for (let i = 1; i <= 8; i++) v = v * 256 + b[off + i];\n if (!Number.isSafeInteger(v)) throw new Error(\"cbor: 64-bit value exceeds safe integer range\");\n return [major, v, off + 9];\n }\n if (ai === 31) throw new Error(\"cbor: indefinite length handled by the caller\");\n throw new Error(`cbor: reserved additional information ${ai}`);\n}\nfunction readChunked(b, off, major, depth) {\n const parts = [];\n let total = 0;\n let p = off;\n for (; ; ) {\n need(b, p, 1);\n const head2 = b[p];\n if (head2 === 255) {\n p += 1;\n break;\n }\n if (head2 >> 5 !== major || (head2 & 31) === 31) {\n throw new Error(\"cbor: indefinite-length string contains a chunk of the wrong kind\");\n }\n const [chunk, next] = readItem(b, p, depth + 1);\n p = next;\n const bytes3 = major === 2 ? chunk : new TextEncoder().encode(chunk);\n total += bytes3.length;\n if (total > MAX_LEN) throw new Error(\"cbor: indefinite-length string too large\");\n parts.push(bytes3);\n }\n const out = concat(...parts);\n return [major === 2 ? out : new TextDecoder(\"utf-8\", { fatal: true }).decode(out), p];\n}\nfunction readItem(b, off, depth = 0) {\n if (depth > 16) throw new Error(\"cbor: nesting too deep\");\n need(b, off, 1);\n const ib = b[off];\n const major0 = ib >> 5;\n if ((ib & 31) === 31) {\n if (major0 === 7) return [BREAK, off + 1];\n if (major0 === 2 || major0 === 3) return readChunked(b, off + 1, major0, depth);\n if (major0 === 4 || major0 === 5) {\n const isMap = major0 === 5;\n const arr = [];\n const map = /* @__PURE__ */ new Map();\n let p2 = off + 1;\n let n = 0;\n for (; ; ) {\n const [k, n1] = readItem(b, p2, depth + 1);\n p2 = n1;\n if (k === BREAK) break;\n if (++n > MAX_LEN) throw new Error(\"cbor: indefinite-length collection too large\");\n if (!isMap) {\n arr.push(k);\n continue;\n }\n const [v, n2] = readItem(b, p2, depth + 1);\n p2 = n2;\n if (v === BREAK) throw new Error(\"cbor: indefinite-length map ended between a key and its value\");\n if (map.has(k)) throw new Error(\"cbor: duplicate map key\");\n map.set(k, v);\n }\n return [isMap ? map : arr, p2];\n }\n throw new Error(`cbor: indefinite length is not valid for major type ${major0}`);\n }\n const [major, value, p] = readHead(b, off);\n switch (major) {\n case 0:\n return [value, p];\n case 1:\n return [-1 - value, p];\n case 2: {\n if (value > MAX_LEN) throw new Error(\"cbor: byte string too large\");\n const end = need(b, p, value);\n return [b.slice(p, end), end];\n }\n case 3: {\n if (value > MAX_LEN) throw new Error(\"cbor: text string too large\");\n const end = need(b, p, value);\n return [new TextDecoder(\"utf-8\", { fatal: true }).decode(b.subarray(p, end)), end];\n }\n case 4: {\n if (value > MAX_LEN) throw new Error(\"cbor: array too long\");\n const out = [];\n let q = p;\n for (let i = 0; i < value; i++) {\n const [v, n] = readItem(b, q, depth + 1);\n if (v === BREAK) throw new Error(\"cbor: break inside a definite-length array\");\n out.push(v);\n q = n;\n }\n return [out, q];\n }\n case 5: {\n if (value > MAX_LEN) throw new Error(\"cbor: map too large\");\n const out = /* @__PURE__ */ new Map();\n let q = p;\n for (let i = 0; i < value; i++) {\n const [k, n1] = readItem(b, q, depth + 1);\n const [v, n2] = readItem(b, n1, depth + 1);\n if (k === BREAK || v === BREAK) throw new Error(\"cbor: break inside a definite-length map\");\n if (out.has(k)) throw new Error(\"cbor: duplicate map key\");\n out.set(k, v);\n q = n2;\n }\n return [out, q];\n }\n case 6: {\n const [v, n] = readItem(b, p, depth + 1);\n return [v, n];\n }\n case 7:\n if (value === 20) return [false, p];\n if (value === 21) return [true, p];\n if (value === 22) return [null, p];\n if (value === 23) return [void 0, p];\n throw new Error(`cbor: unsupported simple/float value ${value}`);\n default:\n throw new Error(\"cbor: unreachable\");\n }\n}\nfunction head(major, value) {\n if (value < 24) return Uint8Array.of(major << 5 | value);\n if (value < 256) return Uint8Array.of(major << 5 | 24, value);\n if (value < 65536) return Uint8Array.of(major << 5 | 25, value >> 8, value & 255);\n if (value < 4294967296) {\n return Uint8Array.of(major << 5 | 26, value >>> 24 & 255, value >>> 16 & 255, value >>> 8 & 255, value & 255);\n }\n throw new Error(\"cbor: length too large to encode\");\n}\nfunction encodeBytes(u8) {\n const b = toBytes(u8);\n return concat(head(2, b.length), b);\n}\nfunction encodeText(s) {\n const b = new TextEncoder().encode(String(s));\n return concat(head(3, b.length), b);\n}\nfunction encodeArray(items) {\n return concat(head(4, items.length), ...items);\n}\nfunction concat(...parts) {\n let n = 0;\n for (const p of parts) n += p.length;\n const out = new Uint8Array(n);\n let o = 0;\n for (const p of parts) {\n out.set(p, o);\n o += p.length;\n }\n return out;\n}\nvar MAX_LEN, BREAK;\nvar init_cbor = __esm({\n \"spaces/public/sdk/4.7.0/cbor.js\"() {\n MAX_LEN = 1 << 22;\n BREAK = /* @__PURE__ */ Symbol(\"cbor-break\");\n }\n});\n\n// spaces/public/sdk/4.7.0/x509.js\nfunction readTLV(b, off) {\n if (off + 2 > b.length) throw new Error(\"der: truncated tag\");\n const tag = b[off];\n if ((tag & 31) === 31) throw new Error(\"der: multi-byte tags not supported\");\n let p = off + 1;\n let len = b[p++];\n if (len & 128) {\n const n = len & 127;\n if (n === 0) throw new Error(\"der: indefinite length is not valid DER\");\n if (n > 4) throw new Error(\"der: length too large\");\n if (p + n > b.length) throw new Error(\"der: truncated length\");\n len = 0;\n for (let i = 0; i < n; i++) len = len * 256 + b[p++];\n }\n const contentEnd = p + len;\n if (contentEnd > b.length) throw new Error(\"der: truncated content\");\n return { tag, start: off, contentStart: p, contentEnd };\n}\nfunction expect(b, off, tag, what) {\n const t = readTLV(b, off);\n if (t.tag !== tag) throw new Error(`der: expected ${what} (tag 0x${tag.toString(16)}), got 0x${t.tag.toString(16)}`);\n return t;\n}\nfunction children(b, t) {\n const out = [];\n let p = t.contentStart;\n while (p < t.contentEnd) {\n const c = readTLV(b, p);\n out.push(c);\n p = c.contentEnd;\n }\n return out;\n}\nfunction oidString(b, t) {\n const c = b.subarray(t.contentStart, t.contentEnd);\n if (!c.length) throw new Error(\"der: empty OID\");\n const parts = [Math.floor(c[0] / 40), c[0] % 40];\n let v = 0;\n for (let i = 1; i < c.length; i++) {\n v = v * 128 + (c[i] & 127);\n if (!(c[i] & 128)) {\n parts.push(v);\n v = 0;\n }\n }\n return parts.join(\".\");\n}\nfunction parseTime(b, t) {\n const s = String.fromCharCode(...b.subarray(t.contentStart, t.contentEnd));\n let m;\n if (t.tag === TAG2.UTCTIME) {\n m = /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(s);\n if (!m) throw new Error(\"der: bad UTCTime\");\n const yy = Number(m[1]);\n return Date.UTC(yy >= 50 ? 1900 + yy : 2e3 + yy, Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));\n }\n if (t.tag === TAG2.GENTIME) {\n m = /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(s);\n if (!m) throw new Error(\"der: bad GeneralizedTime\");\n return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));\n }\n throw new Error(\"der: unsupported time tag\");\n}\nfunction derSigToRaw(der, size) {\n const b = der instanceof Uint8Array ? der : new Uint8Array(der);\n const seq = expect(b, 0, TAG2.SEQ, \"signature SEQUENCE\");\n const [rT, sT] = children(b, seq);\n if (!rT || !sT || rT.tag !== TAG2.INT || sT.tag !== TAG2.INT) throw new Error(\"der: bad ECDSA signature\");\n const out = new Uint8Array(size * 2);\n for (const [i, t] of [[0, rT], [1, sT]]) {\n let v = b.subarray(t.contentStart, t.contentEnd);\n while (v.length > 1 && v[0] === 0) v = v.subarray(1);\n if (v.length > size) throw new Error(\"der: ECDSA integer too large for curve\");\n out.set(v, i * size + (size - v.length));\n }\n return out;\n}\nfunction parseCertificate(der) {\n const b = der instanceof Uint8Array ? der : new Uint8Array(der);\n const cert = expect(b, 0, TAG2.SEQ, \"Certificate\");\n const [tbsT, algT, sigT] = children(b, cert);\n if (!tbsT || !algT || !sigT) throw new Error(\"der: Certificate needs 3 fields\");\n if (sigT.tag !== TAG2.BITSTRING) throw new Error(\"der: signatureValue must be a BIT STRING\");\n const sigAlgOid = oidString(b, expect(b, algT.contentStart, TAG2.OID, \"signature algorithm\"));\n const sigAlg = SIG_OIDS.get(sigAlgOid);\n if (!sigAlg) throw new Error(`der: unsupported signature algorithm ${sigAlgOid}`);\n if (b[sigT.contentStart] !== 0) throw new Error(\"der: signature BIT STRING has unused bits\");\n const sigDer = b.subarray(sigT.contentStart + 1, sigT.contentEnd);\n const kids = children(b, tbsT);\n const base = kids[0] && kids[0].tag === 160 ? 1 : 0;\n const [serialT, innerAlgT, issuerT, validityT, subjectT, spkiT] = kids.slice(base, base + 6);\n if (!serialT || !innerAlgT || !issuerT || !validityT || !subjectT || !spkiT) throw new Error(\"der: malformed tbsCertificate\");\n const innerOid = oidString(b, expect(b, innerAlgT.contentStart, TAG2.OID, \"inner signature algorithm\"));\n if (innerOid !== sigAlgOid) throw new Error(\"der: signature algorithm mismatch between tbs and certificate\");\n const [nbT, naT] = children(b, validityT);\n if (!nbT || !naT) throw new Error(\"der: malformed validity\");\n const [spkiAlgT] = children(b, spkiT);\n const spkiAlgKids = children(b, spkiAlgT);\n if (spkiAlgKids.length < 2) throw new Error(\"der: SPKI algorithm needs a curve parameter\");\n const keyOid = oidString(b, spkiAlgKids[0]);\n if (keyOid !== \"1.2.840.10045.2.1\") throw new Error(`der: not an EC public key (${keyOid})`);\n const curveOid = oidString(b, spkiAlgKids[1]);\n const curve = CURVE_OIDS.get(curveOid);\n if (!curve) throw new Error(`der: unsupported curve ${curveOid}`);\n let isCA = false;\n for (const k of kids.slice(base + 6)) {\n if (k.tag !== 163) continue;\n for (const ext of children(b, children(b, k)[0] || k)) {\n const extKids = children(b, ext);\n if (!extKids.length || oidString(b, extKids[0]) !== \"2.5.29.19\") continue;\n const octet = extKids[extKids.length - 1];\n const bcSeq = readTLV(b, octet.contentStart);\n const bcKids = children(b, bcSeq);\n isCA = !!(bcKids[0] && bcKids[0].tag === 1 && b[bcKids[0].contentStart] !== 0);\n }\n }\n return {\n tbs: b.subarray(tbsT.start, tbsT.contentEnd),\n sig: derSigToRaw(sigDer, curve.size),\n sigHash: sigAlg.hash,\n spki: b.slice(spkiT.start, spkiT.contentEnd),\n // copy: this is handed to WebCrypto, which wants its own buffer\n curve: curve.curve,\n size: curve.size,\n issuer: b.subarray(issuerT.start, issuerT.contentEnd),\n subject: b.subarray(subjectT.start, subjectT.contentEnd),\n notBefore: parseTime(b, nbT),\n notAfter: parseTime(b, naT),\n isCA\n };\n}\nfunction bytesEqual(a, b) {\n if (!a || !b || a.length !== b.length) return false;\n let d = 0;\n for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];\n return d === 0;\n}\nasync function importSpki(cert) {\n return crypto.subtle.importKey(\"spki\", cert.spki, { name: \"ECDSA\", namedCurve: cert.curve }, false, [\"verify\"]);\n}\nasync function verifyChain(chainDer, { now = Date.now() } = {}) {\n if (!Array.isArray(chainDer) || chainDer.length < 2) throw new Error(\"chain: need an anchor and at least one certificate\");\n const certs = chainDer.map((d, i) => {\n try {\n return parseCertificate(d);\n } catch (e) {\n throw new Error(`chain: certificate ${i} unparseable: ${e.message}`);\n }\n });\n for (let i = 1; i < certs.length; i++) {\n const child = certs[i];\n const parent = certs[i - 1];\n if (!bytesEqual(child.issuer, parent.subject)) throw new Error(`chain: certificate ${i} was not issued by certificate ${i - 1}`);\n if (i > 1 && !parent.isCA) throw new Error(`chain: certificate ${i - 1} signs but is not a CA`);\n if (now < child.notBefore) throw new Error(`chain: certificate ${i} is not yet valid`);\n if (now > child.notAfter) throw new Error(`chain: certificate ${i} has expired`);\n const ok = await crypto.subtle.verify({ name: \"ECDSA\", hash: child.sigHash }, await importSpki(parent), child.sig, child.tbs);\n if (!ok) throw new Error(`chain: certificate ${i} has a bad signature`);\n }\n return certs[certs.length - 1];\n}\nvar TAG2, SIG_OIDS, CURVE_OIDS;\nvar init_x509 = __esm({\n \"spaces/public/sdk/4.7.0/x509.js\"() {\n TAG2 = { INT: 2, BITSTRING: 3, OID: 6, SEQ: 48, UTCTIME: 23, GENTIME: 24 };\n SIG_OIDS = /* @__PURE__ */ new Map([\n [\"1.2.840.10045.4.3.2\", { hash: \"SHA-256\" }],\n [\"1.2.840.10045.4.3.3\", { hash: \"SHA-384\" }],\n [\"1.2.840.10045.4.3.4\", { hash: \"SHA-512\" }]\n ]);\n CURVE_OIDS = /* @__PURE__ */ new Map([\n [\"1.2.840.10045.3.1.7\", { curve: \"P-256\", size: 32 }],\n [\"1.3.132.0.34\", { curve: \"P-384\", size: 48 }],\n [\"1.3.132.0.35\", { curve: \"P-521\", size: 66 }]\n ]);\n }\n});\n\n// spaces/public/sdk/4.7.0/nitroVerify.js\nfunction b64ToBytes(b6410) {\n const s = String(b6410).replace(/-/g, \"+\").replace(/_/g, \"/\").replace(/\\s+/g, \"\");\n const bin = atob(s);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\nfunction sigStructure(protectedBytes, payloadBytes) {\n return encodeArray([\n encodeText(\"Signature1\"),\n encodeBytes(protectedBytes),\n encodeBytes(new Uint8Array(0)),\n // external_aad — always empty for Nitro\n encodeBytes(payloadBytes)\n ]);\n}\nfunction parseDocument(payloadBytes) {\n const m = decode(payloadBytes);\n if (!(m instanceof Map)) throw new Error(\"attestation: payload is not a map\");\n const moduleId = m.get(\"module_id\");\n if (typeof moduleId !== \"string\" || !moduleId || moduleId.length > MAX_FIELD) throw new Error(\"attestation: bad module_id\");\n const digest = m.get(\"digest\");\n if (digest !== \"SHA384\") throw new Error(`attestation: unexpected digest ${digest}`);\n const timestamp = m.get(\"timestamp\");\n if (typeof timestamp !== \"number\" || !(timestamp > 0)) throw new Error(\"attestation: bad timestamp\");\n const pcrsMap = m.get(\"pcrs\");\n if (!(pcrsMap instanceof Map) || pcrsMap.size < 1 || pcrsMap.size > 32) throw new Error(\"attestation: bad pcrs\");\n const pcrs = {};\n for (const [k, v] of pcrsMap) {\n if (!Number.isInteger(k) || k < 0 || k > 31) throw new Error(\"attestation: bad PCR index\");\n if (!isBytes(v) || v.length !== 32 && v.length !== 48 && v.length !== 64) throw new Error(`attestation: bad PCR${k}`);\n pcrs[k] = toHex(v);\n }\n const certificate = m.get(\"certificate\");\n if (!isBytes(certificate) || !certificate.length) throw new Error(\"attestation: missing certificate\");\n const cabundle = m.get(\"cabundle\");\n if (!Array.isArray(cabundle) || !cabundle.length || cabundle.length > MAX_CABUNDLE) throw new Error(\"attestation: bad cabundle\");\n for (const c of cabundle) if (!isBytes(c) || !c.length) throw new Error(\"attestation: bad cabundle entry\");\n return {\n moduleId,\n timestamp,\n digest,\n pcrs,\n certificate,\n cabundle,\n publicKey: optBytes(m, \"public_key\"),\n userData: optBytes(m, \"user_data\"),\n nonce: optBytes(m, \"nonce\")\n };\n}\nfunction acceptedSet(pin, label = \"pin\") {\n const list = (Array.isArray(pin) ? pin : [pin]).map((h) => String(h).toLowerCase());\n if (!list.length) throw new Error(`attestation: ${label} pins an empty set — that is not a check`);\n if (list.length > MAX_PIN_SET) throw new Error(`attestation: ${label} pins ${list.length} values; at most ${MAX_PIN_SET} (a rollover is {outgoing, incoming})`);\n return list;\n}\nasync function verifyAttestation(cose, { root, now = Date.now(), maxAgeMs = 0, expectedPCRs = null, nonce = null, atDocTime = false, clockBoundMs = 0 } = {}) {\n const raw = cose instanceof Uint8Array ? cose : new Uint8Array(cose);\n if (!raw.length || raw.length > MAX_DOC) throw new Error(\"attestation: implausible document size\");\n const cs = decode(raw);\n if (!Array.isArray(cs) || cs.length !== 4) throw new Error(\"attestation: not a COSE_Sign1 structure\");\n const [protectedBytes, unprotected, payloadBytes, signature] = cs;\n if (!isBytes(protectedBytes) || !isBytes(payloadBytes) || !isBytes(signature)) throw new Error(\"attestation: malformed COSE_Sign1\");\n if (!(unprotected instanceof Map)) throw new Error(\"attestation: malformed COSE header\");\n const ph = protectedBytes.length ? decode(protectedBytes) : /* @__PURE__ */ new Map();\n if (!(ph instanceof Map) || ph.get(1) !== COSE_ALG_ES384) throw new Error(\"attestation: protected header must specify ES384\");\n if (signature.length !== 96) throw new Error(\"attestation: ES384 signature must be 96 bytes\");\n const doc = parseDocument(payloadBytes);\n const anchor = root ? root instanceof Uint8Array ? root : new Uint8Array(root) : b64ToBytes(NITRO_ROOT_G1_B64);\n const leaf = await verifyChain([anchor, ...doc.cabundle.slice(1), doc.certificate], { now: atDocTime && Number.isFinite(doc.timestamp) ? doc.timestamp : now });\n const ok = await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-384\" },\n await importSpki(leaf),\n signature,\n sigStructure(protectedBytes, payloadBytes)\n );\n if (!ok) throw new Error(\"attestation: COSE signature does not verify under the leaf certificate\");\n if (atDocTime && clockBoundMs > 0 && Number.isFinite(doc.timestamp) && Math.abs(now - doc.timestamp) > clockBoundMs) {\n const h = Math.round(Math.abs(now - doc.timestamp) / 36e5);\n const e = new Error(`attestation: this device's clock is about ${h} hour${h === 1 ? \"\" : \"s\"} off the enclave's — check the date and time settings`);\n e.code = \"clock_off\";\n throw e;\n }\n if (maxAgeMs > 0 && now - doc.timestamp > maxAgeMs) {\n throw new Error(`attestation: document is ${Math.round((now - doc.timestamp) / 1e3)}s old`);\n }\n if (nonce) {\n const want = typeof nonce === \"string\" ? new TextEncoder().encode(nonce) : new Uint8Array(nonce);\n if (!doc.nonce || !bytesEqual(doc.nonce, want)) throw new Error(\"attestation: nonce does not match the challenge\");\n }\n if (expectedPCRs) {\n const wanted = Object.entries(expectedPCRs);\n if (!wanted.length) throw new Error(\"attestation: expectedPCRs was empty — that is not a check\");\n for (const [idx, pin] of wanted) {\n const n = Number(idx);\n if (!Number.isInteger(n) || n < 0 || n > 31) {\n throw new Error(`attestation: expectedPCRs key ${JSON.stringify(idx)} is not a PCR index (0-31)`);\n }\n const accepted = acceptedSet(pin, `PCR${idx}`);\n const got = doc.pcrs[n];\n if (!got) throw new Error(`attestation: PCR${idx} is absent from the document`);\n if (!accepted.includes(got)) throw new Error(`attestation: PCR${idx} mismatch\n expected ${accepted.join(\" or \")}\n got ${got}`);\n }\n }\n return { ok: true, ...doc, leaf };\n}\nvar NITRO_ROOT_G1_B64, COSE_ALG_ES384, MAX_DOC, MAX_FIELD, MAX_CABUNDLE, toHex, isBytes, optBytes, MAX_PIN_SET;\nvar init_nitroVerify = __esm({\n \"spaces/public/sdk/4.7.0/nitroVerify.js\"() {\n init_cbor();\n init_x509();\n NITRO_ROOT_G1_B64 = \"MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTELMAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYDVQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4MTQyODA1WjBJMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEGBSuBBAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSksfbb48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ3BABIeTPYwEoCWZEh8l5YoQwTcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkFR+eWw5b6cp3PmanfS5YwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPWrfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6NIwLz3/Y=\";\n COSE_ALG_ES384 = -35;\n MAX_DOC = 1 << 20;\n MAX_FIELD = 1024;\n MAX_CABUNDLE = 8;\n toHex = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n isBytes = (x) => x instanceof Uint8Array;\n optBytes = (m, k) => {\n const v = m.get(k);\n if (v === null || v === void 0) return null;\n if (!isBytes(v) || v.length > MAX_FIELD) throw new Error(`attestation: bad ${k}`);\n return v.length ? v : null;\n };\n MAX_PIN_SET = 2;\n }\n});\n\n// spaces/public/sdk/4.7.0/sealShare.js\nasync function sealTo2(enclaveKey, nonce, bundle) {\n const eph = await crypto.subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-384\" }, true, [\"deriveBits\"]);\n const shared = await crypto.subtle.deriveBits({ name: \"ECDH\", public: enclaveKey }, eph.privateKey, 384);\n const hk = await crypto.subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n const key = await crypto.subtle.deriveKey({ name: \"HKDF\", hash: \"SHA-256\", salt: nonce, info: enc8.encode(\"witbitz-cc share v1\") }, hk, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\"]);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: nonce }, key, enc8.encode(JSON.stringify(bundle))));\n const epk = new Uint8Array(await crypto.subtle.exportKey(\"raw\", eph.publicKey));\n return { epk: b646(epk), iv: b646(iv), ct: b646(ct), nonce: b646(nonce) };\n}\nvar enc8, b646;\nvar init_sealShare = __esm({\n \"spaces/public/sdk/4.7.0/sealShare.js\"() {\n enc8 = new TextEncoder();\n b646 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)));\n }\n});\n\n// spaces/public/sdk/4.7.0/cloudDevicePins.js\nvar CLOUD_DEVICE_PCR0;\nvar init_cloudDevicePins = __esm({\n \"spaces/public/sdk/4.7.0/cloudDevicePins.js\"() {\n CLOUD_DEVICE_PCR0 = Object.freeze([\"d89c0daf2290536038265b116f4e66fd350c342203c6e6624153596d63c96ebcc57e8e9482afd274a6e0c260f2f22829\"]);\n }\n});\n\n// spaces/public/sdk/4.7.0/sentinelRelease.js\nfunction chainFromSite({ fetchFn = typeof fetch === \"function\" ? fetch : null, urls = CHAIN_URLS } = {}) {\n if (!fetchFn) return Promise.resolve([]);\n const own = fetchFn === globalThis.fetch && urls === CHAIN_URLS;\n if (own && typeof process !== \"undefined\" && process.env && process.env.NODE_TEST_CONTEXT) return Promise.resolve([]);\n if (!own) return readChain(fetchFn, urls);\n return _siteChain || (_siteChain = readChain(fetchFn, urls).then((l) => {\n if (!l.length) _siteChain = null;\n return l;\n }));\n}\nfunction readChain(fetchFn, urls) {\n return (async () => {\n for (const u of urls) {\n try {\n const res = await fetchFn(u, { cache: \"no-store\" });\n if (!res || res.status !== 200 || /text\\/html/.test(res.headers && res.headers.get && res.headers.get(\"content-type\") || \"\")) continue;\n const l = linksOfLogText(await res.text());\n if (l.length) return l;\n } catch {\n }\n }\n return [];\n })();\n}\nfunction linksOfLogText(text) {\n const out = [];\n for (const l of String(text || \"\").split(\"\\n\")) {\n try {\n const r = JSON.parse(l);\n if (r && r.subject === \"build-enclave\" && r.verdict === \"pass\") out.push(r);\n } catch {\n }\n }\n return out.reverse();\n}\nasync function trustedBuilders(links = [], { anchors = BUILD_ENCLAVE_PCR0, deny = BUILD_ENCLAVE_DENY, verify = verifyAttestation, max = LINKS_MAX } = {}) {\n const denied = new Set((deny || []).map((x) => String(x).toLowerCase()));\n const trusted = new Set((anchors || []).map((x) => String(x).toLowerCase()).filter((x) => !denied.has(x)));\n const cache = verify === verifyAttestation;\n let pending = Array.isArray(links) ? links.slice(0, max) : [];\n for (let grew = true; grew && pending.length; ) {\n grew = false;\n const left = [];\n for (const l of pending) {\n try {\n const sig = l && l.signature && typeof l.signature.sig === \"string\" ? l.signature.sig : \"\";\n const known = sig && cache ? verified.get(sig) : null;\n let p;\n if (known && trusted.has(known.builder) && String(l.measurement && l.measurement.pcr0 || \"\").toLowerCase() === known.pcr0) p = known.pcr0;\n else {\n const got = await recordPcrBy(l, \"build-enclave\", [...trusted], verify);\n p = got.pcr0;\n if (sig && cache) {\n if (verified.size >= 4096) verified.delete(verified.keys().next().value);\n verified.set(sig, got);\n }\n }\n if (!denied.has(p) && !trusted.has(p)) {\n trusted.add(p);\n grew = true;\n }\n } catch (e) {\n if (/not made by a build enclave this app trusts/.test(String(e && e.message || e))) left.push(l);\n }\n }\n pending = left;\n }\n return [...trusted];\n}\nasync function recordPcrBy(r, subject, builders, verify = verifyAttestation) {\n if (!r || typeof r !== \"object\") throw new Error(\"no release record came with the attestation\");\n if (r.subject !== subject || r.verdict !== \"pass\") throw new Error(`the record is not a passing ${subject} release`);\n const repro = Array.isArray(r.checks) && r.checks.find((c) => c && c.name === \"reproducible-build\");\n if (!repro || repro.ok !== true) throw new Error(\"the record does not say the image was rebuilt from its source\");\n const pcr0 = String(r.measurement && r.measurement.pcr0 || \"\").toLowerCase();\n if (!/^[0-9a-f]{96}$/.test(pcr0) || r.claim && String(r.claim.pcr0 || \"\").toLowerCase() !== pcr0) throw new Error(\"the record names no single PCR0\");\n if (!r.attestation || !r.attestation.doc || !r.signature || !r.signature.key || !r.signature.sig) throw new Error(\"the record carries no proof\");\n const rest = {};\n for (const [k, v] of Object.entries(r)) if (!PROOFS.includes(k)) rest[k] = v;\n const art = enc9.encode(JSON.stringify(rest));\n const doc = await verify(unb642(r.attestation.doc), { atDocTime: true });\n const builder = String(doc.pcrs && doc.pcrs[0] || \"\").toLowerCase();\n if (!builders.includes(builder)) throw new Error(\"the record was not made by a build enclave this app trusts\");\n const want = enc9.encode(JSON.stringify({ role: \"build-enclave\", verdict: hex3(await crypto.subtle.digest(\"SHA-256\", art)) }));\n if (!doc.userData || !same(new Uint8Array(doc.userData), want)) throw new Error(\"the build enclave's attestation is not for this record\");\n const spki = unb642(r.signature.key);\n if (!doc.publicKey || !same(new Uint8Array(doc.publicKey), spki)) throw new Error(\"the record is not signed by the key the build enclave attested\");\n const key = await crypto.subtle.importKey(\"spki\", spki, { name: \"ECDSA\", namedCurve: \"P-256\" }, false, [\"verify\"]);\n const ok = await crypto.subtle.verify({ name: \"ECDSA\", hash: \"SHA-256\" }, key, derSigToRaw(unb642(r.signature.sig), 32), art);\n if (!ok) throw new Error(\"the record's signature does not verify\");\n return { pcr0, builder };\n}\nvar BUILD_ENCLAVE_PCR0, enc9, unb642, hex3, same, PROOFS, _siteChain, CHAIN_URLS, BUILD_ENCLAVE_DENY, LINKS_MAX, verified;\nvar init_sentinelRelease = __esm({\n \"spaces/public/sdk/4.7.0/sentinelRelease.js\"() {\n init_nitroVerify();\n init_x509();\n BUILD_ENCLAVE_PCR0 = Object.freeze([\n \"c6a8cbd0c05d8e003e75b266f1dde2a6426b7cd61f845e4b128e59063e40968b44f30d934bbe1925582fe33bbdd0b1d7\",\n \"f490096d57e4287146e8b8d7bf4c75f423984ca52199efab0ee8684fbee6cfe6ab82c72d54f05a38f24a0d4ad6e2f557\",\n \"41ec7e0e54beac5759fba7efa06c48081dbd96c7299c29c92a9c619036ce057cec357ad4ad71a165d7f881df120b043b\",\n \"9f0801335a952bdbac70b6793150738d7ce30bc3a0d520fec6f573de22a822aa5ef762f78648bc8608ca0b2eeccda556\",\n \"a145e8524bbe8764d4db6b81b4e18d72eae42e8b9e1c834e62e22aba18cce318f9eaa84942671c688c3eeb89ec30b0e8\",\n \"5d29c3691cd38f6c6ce0da2b2f9d1da82712d9da12a89c99d38a03cae6369ebe6ba7a1ab1060cfa9daf6a19228c7a2dc\",\n \"6c962286faed81c395bcf3d319011f91893cfec723c2dc7069ad8805980d77e99f75c94671881cc793794521fe5d2ff0\",\n \"578945d0342d346d72e50b36ffe74a3631e53e111bc010394108457e362d10830ebadcc7ec5ffa4445d5b10b9c522d28\",\n \"7e9f760db923c6f31fd18db06f6b60a53902beb6b0d80b91b5355d33c461e43bcddc31c08e2380ff9dc75c10909e6acb\",\n \"5b6bffe6953eef271a69e453072b6e202ae024cd3983fff3a637b7421a60ad92ab3fd19f8ae809e19182a3feebbe94c2\",\n \"551006e397efd43a619b370ef336a6a594d8a8338cd49860e54845330354c73afd3ba673360d50f78e5f1d702e19946b\",\n \"eecf817c561e633b30632ca434a28ad56ed46395d765172fedcc0742d8d5c9982845d6ce32b6451b943f4b6f0a55ea36\",\n \"3df18dce5385b467208bfa325d2f812bd622ef6def87ef97e63116310a896427db9f2c69d7c2631bccc9c65549b3d512\",\n \"a51fcaeafa6d188b46d11710442f981169304aa4feecc4b40263943966c3dd8ff9b986d30989b4152fa1540c85a76b5e\",\n \"f977e0490f5abfc77c311b426399bddd6909848bb8175db4142885c839e9cc23c3ca0047317b039883dce4b1a2efe096\",\n \"d5f13dff5647f5f4ee351dd9e1ba9348ecd39da88acd6ffd9c324897b0ca7563da974b08c2e84504a76dc98b48700b74\",\n \"2babe4262b2a00949eeef5b04a81327eb606dc347caaf507527d04f8847730a31dd26d6d7be3e0a672c537b51c914133\",\n \"25a0967ec1366bc0ec43e45e2f89c435adb1a3e54d8702d89599acb442337afcb36f8f64d51a6608cefb3bb1e4f6b8ed\",\n \"8665867cbb86ea3178f4179cf040fdec9e6df22bdd4f1e3d8df6b2d9096db5aecd8420b42203969bbe9446b585c78870\",\n \"ef738ca713ddc39dc29505d857c2aac22a0598a714163ae01e2879085e1c262cc5bde3c239b7ce76385d10c5910ed487\",\n \"41de07c0c12f388f9dc7d87cfa835edce2c58be42f6893f227002329d263285bf78bb209cd69c384dd7566097f2a3d47\",\n \"a77141c4ac00099cbdd9053e0190b70234aa2eccdb22cb358e9b8b0fef5bef6b7ad6d9b5eb73137244a3790f98869505\",\n \"70dde35fed128d1cb007f8c6edfa3de70e991955e1748aa500ad4685d1c752b1775565fb9a6d11c483969d5596e3b159\",\n \"f0ea83ee58b3a4a9ebe7c8c74f102eba17118711573b6ce773b6f31ed223564cbf215992b5a7a30462b70281ae624453\",\n \"f7adfbec8cf3a014f9585c7decc21bb03a50484339811ea3b44947d23fc16aff8eedb56346915b816e83fc5faad55e7a\",\n \"917f7d95eabd64eabd1145cc0898c08ff414037775fd416162002c4783b4f95dcb550c3c5493baadaf41eaceb0e7da0d\",\n \"74b1cbd4398f319a636de05d36eaa40953df4dc0bb86769f7ac4e0fe2c576f55b3c4a15a5583048ded80b0b4d303f55e\",\n \"420088665bd62edcba51dfbcc55cbc85611529985fde54b655a3476198a8f9421e02d1898db28180b153550ceeb66798\"\n ]);\n enc9 = new TextEncoder();\n unb642 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0));\n hex3 = (u8) => [...new Uint8Array(u8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);\n PROOFS = [\"attestation\", \"signature\", \"rekor\"];\n _siteChain = null;\n CHAIN_URLS = Object.freeze([\"https://api.witbitz.chat/v1/trust/build-enclave.jsonl\", \"/audit/releases/build-enclave.jsonl\"]);\n BUILD_ENCLAVE_DENY = Object.freeze([]);\n LINKS_MAX = 4;\n verified = /* @__PURE__ */ new Map();\n }\n});\n\n// spaces/public/sdk/4.7.0/followImage.js\nfunction recordsOfLogText(text, subject) {\n const out = [];\n for (const l of String(text || \"\").split(\"\\n\")) {\n try {\n const r = JSON.parse(l);\n if (r && typeof r === \"object\" && r.subject === subject && r.verdict === \"pass\") out.push(r);\n } catch {\n }\n }\n return out.reverse();\n}\nfunction subjectLog(subject, { fetchFn = typeof fetch === \"function\" ? fetch : null } = {}) {\n if (!fetchFn || !FOLLOWED_SUBJECTS.includes(subject)) return Promise.resolve([]);\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_TEST_CONTEXT && fetchFn === globalThis.fetch) return Promise.resolve([]);\n if (!_logs.has(subject)) {\n _logs.set(subject, (async () => {\n for (const u of [TRUST_BASE + subject + \".jsonl\", \"/audit/releases/\" + subject + \".jsonl\"]) {\n try {\n const res = await fetchFn(u, { cache: \"no-store\" });\n if (!res || res.status !== 200 || /text\\/html/.test(res.headers && res.headers.get && res.headers.get(\"content-type\") || \"\")) continue;\n const l = recordsOfLogText(await res.text(), subject);\n if (l.length) return l;\n } catch {\n }\n }\n return [];\n })().then((l) => {\n if (!l.length) _logs.delete(subject);\n return l;\n }));\n }\n return _logs.get(subject);\n}\nasync function followedImageRecords(subject, { window: window2 = FOLLOW_WINDOW, fetchFn, verify = verifyAttestation, builders = null, records = null } = {}) {\n try {\n const recs = records || await subjectLog(subject, fetchFn ? { fetchFn } : {});\n if (!recs.length) return [];\n const trusted = builders || await trustedBuilders(await chainFromSite(fetchFn ? { fetchFn } : {}), { anchors: BUILD_ENCLAVE_PCR0, verify, max: Infinity });\n const deny = IMAGE_DENY[subject] || [];\n const out = [];\n for (const r of recs) {\n if (out.length >= window2) break;\n try {\n const { pcr0 } = await recordPcrBy(r, subject, trusted, verify);\n if (!deny.includes(pcr0) && !out.some((x) => x.pcr0 === pcr0)) out.push({ pcr0, measurement: r.measurement || {} });\n } catch {\n }\n }\n return out;\n } catch {\n return [];\n }\n}\nasync function followedImages(subject, opts = {}) {\n return (await followedImageRecords(subject, opts)).map((x) => x.pcr0);\n}\nvar FOLLOW_WINDOW, FOLLOWED_SUBJECTS, IMAGE_DENY, TRUST_BASE, _logs;\nvar init_followImage = __esm({\n \"spaces/public/sdk/4.7.0/followImage.js\"() {\n init_sentinelRelease();\n init_nitroVerify();\n FOLLOW_WINDOW = 2;\n FOLLOWED_SUBJECTS = Object.freeze([\"cloud-device\", \"tools-enclave\"]);\n IMAGE_DENY = Object.freeze({ \"cloud-device\": Object.freeze([]), \"tools-enclave\": Object.freeze([]) });\n TRUST_BASE = \"https://api.witbitz.chat/v1/trust/\";\n _logs = /* @__PURE__ */ new Map();\n }\n});\n\n// spaces/public/sdk/4.7.0/cloudDeviceSeal.js\nvar cloudDeviceSeal_exports = {};\n__export(cloudDeviceSeal_exports, {\n cloudDeviceCall: () => cloudDeviceCall\n});\nasync function cloudDeviceCall(post, cd, idToken, { pins = CLOUD_DEVICE_PCR0, verify = verifyAttestation, now, follow = followedImages } = {}) {\n if (!pins || !pins.length) return refuse(\"no_pins\", \"This app names no cloud device build, so nothing was sent to it.\");\n const nonce = crypto.getRandomValues(new Uint8Array(32));\n const a = await post({ op: \"clouddevice\", cd: { t: \"attest\", nonce: b647(nonce) }, idToken });\n if (!a || a.status !== 200 || typeof a.doc !== \"string\") return a && a.status && a.status !== 200 ? a : refuse(a && a.error || \"attest_failed\", \"The cloud device could not show what it runs.\");\n let doc;\n const check = (list) => verify(unb643(a.doc), { nonce, expectedPCRs: { 0: [...list] }, maxAgeMs: 5 * 6e4, ...now ? { now } : {} });\n try {\n doc = await check(pins);\n } catch (e) {\n const more = follow ? (await follow(\"cloud-device\")).filter((p) => !pins.includes(p)) : [];\n let last = e;\n for (const p of more) {\n try {\n doc = await check([p]);\n break;\n } catch (ex) {\n last = ex;\n }\n }\n try {\n if (!doc) throw last;\n } catch (e2) {\n return refuse(\"attestation\", \"The cloud device is not running the published Witbitz image, so nothing was sent to it.\", 502, e2 && e2.message || e2);\n }\n }\n let said = null;\n try {\n said = JSON.parse(new TextDecoder().decode(doc.userData || new Uint8Array(0)));\n } catch {\n said = null;\n }\n if (!said || said.role !== \"clouddevice\" || !doc.publicKey) return refuse(\"attestation\", \"The attestation does not name a cloud device, so nothing was sent to it.\", 502, \"role \" + (said && said.role));\n const key = await crypto.subtle.importKey(\"spki\", doc.publicKey, { name: \"ECDH\", namedCurve: \"P-384\" }, false, []);\n const answerRaw = crypto.getRandomValues(new Uint8Array(32));\n const hint = a.hint && typeof a.hint === \"object\" ? a.hint : null;\n const sealed = await sealTo2(key, nonce, { ...cd, idToken, ...hint ? { hint } : {}, answerKey: b647(answerRaw) });\n const r = await post({ op: \"clouddevice\", cd: { t: \"sealed\", sealed }, idToken });\n if (!r || r.status !== 200) return r;\n if (!r.sealed || typeof r.sealed.iv !== \"string\" || typeof r.sealed.ct !== \"string\") return r.ok === false ? { status: 200, ok: false, error: r.error, message: r.message } : refuse(\"unsealed\", \"The cloud device's answer was not sealed to this request.\");\n let ans;\n try {\n const k = await crypto.subtle.importKey(\"raw\", answerRaw, \"AES-GCM\", false, [\"decrypt\"]);\n ans = JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: unb643(r.sealed.iv) }, k, unb643(r.sealed.ct))));\n } catch {\n return refuse(\"unsealed\", \"The cloud device's answer did not open.\");\n }\n const { re: _re, ...rest } = ans || {};\n return { status: 200, ...rest };\n}\nvar b647, unb643, refuse;\nvar init_cloudDeviceSeal = __esm({\n \"spaces/public/sdk/4.7.0/cloudDeviceSeal.js\"() {\n init_nitroVerify();\n init_sealShare();\n init_cloudDevicePins();\n init_followImage();\n b647 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)));\n unb643 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0));\n refuse = (error, message, status = 502, detail = \"\") => ({ status, ok: false, error, message, ...detail ? { detail: String(detail).slice(0, 200) } : {} });\n }\n});\n\n// spaces/public/sdk/4.7.0/opRouting.js\nfunction routingIndex(op) {\n switch (op) {\n case \"turn\":\n return 2;\n case \"decide\":\n return 3;\n case \"carry\":\n case \"toolRules\":\n return 0;\n default:\n return -1;\n }\n}\n\n// spaces/public/sdk/4.7.0/prefetchPoll.js\nvar PREFETCH_MAX_AGE_MS = 15 * 60 * 1e3;\nasync function prefetchHashKey(room) {\n const d = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(\"wb-prefetch\\n\" + String(room || \"\"))));\n return \"prefetch:h:\" + Array.from(d.slice(0, 16), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction prefetchUsable(pf, sinceCount, now = Date.now()) {\n if (!pf || typeof pf !== \"object\" || !pf.r || typeof pf.r !== \"object\") return \"none\";\n if (!Number.isFinite(pf.at) || now - pf.at > PREFETCH_MAX_AGE_MS) return \"stale\";\n if (pf.tail) {\n if (!Number.isInteger(pf.sinceCount) || pf.sinceCount > (sinceCount | 0) || !Number.isInteger(pf.r.count) || (sinceCount | 0) > pf.r.count) return \"position moved\";\n } else if (!Number.isInteger(pf.sinceCount) || pf.sinceCount !== (sinceCount | 0)) return \"position moved\";\n if (!pf.r.changed || typeof pf.r.sealed !== \"string\") return \"nothing new in it\";\n return \"\";\n}\nfunction positionOf(result) {\n if (!result || result.status !== 200 || !Number.isInteger(result.version)) return null;\n return { etag: typeof result.etag === \"string\" ? result.etag : \"\", count: result.version, at: Date.now() };\n}\nfunction prefetchAnswer(pf, sinceCount) {\n let r0 = pf && pf.r && typeof pf.r === \"object\" ? pf.r : null;\n if (!r0) return null;\n if (pf.tail && Number.isInteger(sinceCount) && sinceCount > pf.sinceCount) {\n let sl = null;\n try {\n sl = JSON.parse(r0.sealed);\n } catch {\n return null;\n }\n if (!sl || !Array.isArray(sl.boxes) || sl.from !== pf.sinceCount || sinceCount > sl.from + sl.boxes.length) return null;\n r0 = { ...r0, sealed: JSON.stringify({ ...sl, boxes: sl.boxes.slice(sinceCount - sl.from), from: sinceCount }), from: sinceCount };\n }\n const { partialStatus, partial, partialSeq, ...r } = r0;\n return Number.isInteger(r.status) ? r : { status: 200, ...r };\n}\n\n// spaces/public/sdk/4.7.0/connectionEntry.js\nvar MCP_TOOLS_PER_SERVER = 40;\nvar TOOL_NAME = /^[A-Za-z0-9_.-]{1,64}$/;\nvar isObj = (v) => v && typeof v === \"object\" && !Array.isArray(v);\nfunction roomTool(t) {\n if (!isObj(t) || !TOOL_NAME.test(String(t.name || \"\"))) return null;\n const schema = isObj(t.inputSchema) && JSON.stringify(t.inputSchema).length <= 8192 ? t.inputSchema : { type: \"object\", properties: {} };\n return { name: String(t.name), title: String(t.title || \"\").slice(0, 120), description: String(t.description || \"\").slice(0, 1e3), inputSchema: schema, readOnly: t.readOnly === true };\n}\nvar JOB_FIELD = /^[A-Za-z_][A-Za-z0-9_]{0,23}$/;\nvar JOB_HEADER = /^[a-z0-9][a-z0-9-]{0,39}$/;\nvar JOB_HEADER_DROP = /* @__PURE__ */ new Set([\"authorization\", \"cookie\", \"host\", \"connection\", \"content-length\", \"transfer-encoding\", \"x-api-key\", \"webhook-id\", \"webhook-timestamp\", \"webhook-signature\"]);\nfunction roomJob(j) {\n if (!isObj(j)) return null;\n const headers = {};\n for (const [k, v] of Object.entries(isObj(j.headers) ? j.headers : {}).slice(0, 6)) {\n const lk = String(k).toLowerCase();\n if (JOB_HEADER.test(lk) && !JOB_HEADER_DROP.has(lk) && !lk.startsWith(\"x-witbitz-\") && typeof v === \"string\" && v.length <= 200 && !/[\\r\\n]/.test(v)) headers[lk] = v;\n }\n return { field: JOB_FIELD.test(String(j.field || \"\")) ? String(j.field) : \"text\", headers };\n}\nfunction roomConnection(x) {\n if (!isObj(x) || !x.id || !x.account || !x.callKey) return null;\n const out = { account: String(x.account), id: String(x.id), callKey: String(x.callKey), label: String(x.label || \"\").slice(0, 80), host: String(x.host || \"\") };\n if (typeof x.webhook === \"string\" && /^\\/[^\\s?#]{1,199}$/.test(x.webhook)) out.webhook = x.webhook;\n if (out.webhook && isObj(x.job)) out.job = roomJob(x.job);\n if (isObj(x.mcp) && Array.isArray(x.mcp.tools)) {\n const tools = x.mcp.tools.map(roomTool).filter(Boolean).slice(0, MCP_TOOLS_PER_SERVER);\n const names = new Set(tools.map((t) => t.name));\n if (tools.length) {\n out.mcp = {\n tools,\n auto: (Array.isArray(x.mcp.auto) ? x.mcp.auto.map(String) : []).filter((n) => names.has(n)),\n ...x.mcp.own === true ? { own: true } : {},\n ...Number.isFinite(x.mcp.listedAt) ? { listedAt: x.mcp.listedAt } : {},\n // THE TOOL BOOK (agent/toolBook.mjs): the tools' descriptions and schemas, stored once in the room — the entry keeps names\n ...isObj(x.mcp.book) && /^i_[A-Za-z0-9_-]{8,64}$/.test(String(x.mcp.book.ref || \"\")) && /^[0-9a-f]{64}$/.test(String(x.mcp.book.sha256 || \"\")) ? { book: { ref: x.mcp.book.ref, sha256: x.mcp.book.sha256 } } : {}\n };\n }\n }\n if (x.reads === \"auto\" && !out.mcp) out.reads = \"auto\";\n return out;\n}\nfunction applyConnectionsPatch(cur, c) {\n const list = Array.isArray(cur) ? cur : [];\n const v = c == null ? null : Array.isArray(c) ? c : c.add ? [...list.filter((x) => x && x.id !== c.add.id), c.add] : c.remove ? list.filter((x) => x && x.id !== c.remove) : c.update && c.update.id ? list.map((x) => x && x.id === c.update.id ? { ...x, ...\"mcp\" in c.update ? { mcp: c.update.mcp } : {}, ...\"reads\" in c.update ? { reads: c.update.reads } : {} } : x) : list;\n return v == null ? void 0 : v.map(roomConnection).filter(Boolean).slice(0, 32);\n}\n\n// spaces/public/sdk/4.7.0/e2ee.js\nvar VERSION = 1;\nvar enc = new TextEncoder();\nvar dec = new TextDecoder();\nvar ledgerAad = (room, index) => enc.encode(\"v3\u001f\" + String(room) + \"\u001f\" + String(index));\nfunction b64(bytes3) {\n const b = bytes3 instanceof Uint8Array ? bytes3 : new Uint8Array(bytes3);\n let s = \"\";\n for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\nfunction ub64(str) {\n let s = String(str || \"\").replace(/-/g, \"+\").replace(/_/g, \"/\");\n s += \"=\".repeat((4 - s.length % 4) % 4);\n const bin = atob(s);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\nasync function roomWrapKey(mk) {\n const ikm = await crypto.subtle.importKey(\"raw\", ub64(mk), \"HKDF\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: enc.encode(\"memwrap\") }, ikm, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n}\nfunction newKey() {\n return b64(crypto.getRandomValues(new Uint8Array(32)));\n}\nasync function commit(mk) {\n const h = await crypto.subtle.digest(\"SHA-256\", enc.encode(String(mk || \"\")));\n return b64(new Uint8Array(h));\n}\nfunction splitKey(mk) {\n const k = ub64(mk);\n if (!k.length) throw new Error(\"splitKey needs a key\");\n const a = crypto.getRandomValues(new Uint8Array(k.length));\n const b = new Uint8Array(k.length);\n for (let i = 0; i < k.length; i++) b[i] = k[i] ^ a[i];\n return { shareA: b64(a), shareB: b64(b) };\n}\nfunction combineShares(shareA, shareB) {\n const a = ub64(shareA || \"\");\n const b = ub64(shareB || \"\");\n if (!a.length || a.length !== b.length) return null;\n const mk = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) mk[i] = a[i] ^ b[i];\n return b64(mk);\n}\nasync function wrapSym(key, cek) {\n const wk = await roomWrapKey(key);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const w = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, wk, cek));\n return { iv: b64(iv), w: b64(w) };\n}\nasync function seal(plaintext, recipients = {}) {\n const entries = Object.entries(recipients).filter(([, k]) => typeof k === \"string\" && k);\n if (!entries.length) throw new Error(\"seal needs at least one recipient key, e.g. { room: mk }\");\n const cek = crypto.getRandomValues(new Uint8Array(32));\n const cekKey = await crypto.subtle.importKey(\"raw\", cek, { name: \"AES-GCM\" }, false, [\"encrypt\"]);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, cekKey, enc.encode(String(plaintext))));\n const out = {};\n for (const [slot, key] of entries) out[slot] = await wrapSym(key, cek);\n return { v: VERSION, iv: b64(iv), ct: b64(ct), recipients: out };\n}\nasync function open(envelope, { mk, aad = null } = {}) {\n if (!isEnvelope(envelope) || !mk) return null;\n if (envelope.aad && !aad) return null;\n const wk = await roomWrapKey(mk);\n for (const slot of Object.keys(envelope.recipients)) {\n const r = envelope.recipients[slot];\n if (!r || typeof r.iv !== \"string\" || typeof r.w !== \"string\") continue;\n try {\n const cek = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: ub64(r.iv) }, wk, ub64(r.w)));\n const cekKey = await crypto.subtle.importKey(\"raw\", cek, { name: \"AES-GCM\" }, false, [\"decrypt\"]);\n const p = { name: \"AES-GCM\", iv: ub64(envelope.iv) };\n if (envelope.aad) p.additionalData = aad;\n const pt = new Uint8Array(await crypto.subtle.decrypt(p, cekKey, ub64(envelope.ct)));\n return dec.decode(pt);\n } catch {\n }\n }\n return null;\n}\nfunction isEnvelope(o) {\n return !!(o && typeof o === \"object\" && o.v === VERSION && typeof o.iv === \"string\" && typeof o.ct === \"string\" && o.recipients && typeof o.recipients === \"object\" && Object.values(o.recipients).some((r) => r && typeof r.iv === \"string\" && typeof r.w === \"string\"));\n}\nvar EC = { name: \"ECDH\", namedCurve: \"P-256\" };\nasync function boxKey(priv, pubJwk) {\n const privKey = priv && priv.kty ? await crypto.subtle.importKey(\"jwk\", priv, EC, false, [\"deriveBits\"]) : priv;\n const pub = await crypto.subtle.importKey(\"jwk\", pubJwk, EC, false, []);\n const bits = await crypto.subtle.deriveBits({ name: \"ECDH\", public: pub }, privKey, 256);\n const ikm = await crypto.subtle.importKey(\"raw\", bits, \"HKDF\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: enc.encode(\"sealedbox\") }, ikm, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n}\nasync function sealTo(plaintext, recipientPublicJwk) {\n if (!recipientPublicJwk) throw new Error(\"sealTo needs the recipient public key\");\n const eph = await crypto.subtle.generateKey(EC, true, [\"deriveBits\"]);\n const key = await boxKey(eph.privateKey, recipientPublicJwk);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, enc.encode(String(plaintext))));\n const epk = await crypto.subtle.exportKey(\"jwk\", eph.publicKey);\n return { v: VERSION, alg: \"box\", epk: { x: epk.x, y: epk.y }, iv: b64(iv), ct: b64(ct) };\n}\n\n// spaces/public/sdk/4.7.0/shamir.js\nvar b642 = (bytes3) => btoa(String.fromCharCode.apply(null, Array.from(bytes3))).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\nvar ub642 = (s) => {\n const bin = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const a = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) a[i] = bin.charCodeAt(i);\n return a;\n};\nvar EXP = new Uint8Array(512);\nvar LOG = new Uint8Array(256);\n(function initField() {\n let x = 1;\n for (let i = 0; i < 255; i++) {\n EXP[i] = x;\n LOG[x] = i;\n let x2 = x << 1;\n if (x2 & 256) x2 ^= 283;\n x = (x2 ^ x) & 255;\n }\n for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];\n})();\nvar mul = (a, b) => a === 0 || b === 0 ? 0 : EXP[LOG[a] + LOG[b]];\nvar div = (a, b) => a === 0 ? 0 : EXP[LOG[a] + 255 - LOG[b]];\nvar rand = (n) => crypto.getRandomValues(new Uint8Array(n));\nfunction shamirSplit(mk, k, n) {\n const secret = ub642(mk);\n if (!secret.length) throw new Error(\"shamirSplit needs a key\");\n if (!(k >= 2 && k <= n && n <= 255)) throw new Error(\"need 2 ≤ k ≤ n ≤ 255\");\n const shares = [];\n for (let j = 1; j <= n; j++) shares.push({ x: j, y: new Uint8Array(secret.length) });\n for (let bi = 0; bi < secret.length; bi++) {\n const coeffs = new Uint8Array(k);\n coeffs[0] = secret[bi];\n const rc = rand(k - 1);\n for (let c = 1; c < k; c++) coeffs[c] = rc[c - 1];\n for (const s of shares) {\n let y = 0;\n for (let c = k - 1; c >= 0; c--) y = mul(y, s.x) ^ coeffs[c];\n s.y[bi] = y;\n }\n }\n return shares.map((s) => b642(Uint8Array.of(s.x, ...s.y)));\n}\nfunction shamirCombine(shareStrings) {\n const pts = (shareStrings || []).map((s) => {\n const a = ub642(s);\n return { x: a[0], y: a.slice(1) };\n }).filter((p) => p.x);\n if (pts.length < 2) return null;\n const xs = pts.map((p) => p.x);\n if (new Set(xs).size !== xs.length) return null;\n const len = pts[0].y.length;\n const out = new Uint8Array(len);\n for (let bi = 0; bi < len; bi++) {\n let acc = 0;\n for (let j = 0; j < pts.length; j++) {\n let num = 1;\n let den = 1;\n for (let m = 0; m < pts.length; m++) {\n if (m === j) continue;\n num = mul(num, pts[m].x);\n den = mul(den, pts[j].x ^ pts[m].x);\n }\n acc ^= mul(pts[j].y[bi], div(num, den));\n }\n out[bi] = acc;\n }\n return b642(out);\n}\n\n// spaces/public/sdk/4.7.0/regions.js\nvar DEFAULT_REGION = \"eu\";\nvar REGIONS = Object.freeze({\n eu: Object.freeze({ aws: \"eu-central-1\" }),\n us: Object.freeze({ aws: \"us-east-1\" })\n});\nvar MARKED = /^(?:sp|tmp)-([a-z]{2})-[0-9a-z]+$/;\nfunction roomRegion(room) {\n const m = MARKED.exec(typeof room === \"string\" ? room : \"\");\n return m && Object.prototype.hasOwnProperty.call(REGIONS, m[1]) ? m[1] : DEFAULT_REGION;\n}\nfunction newRoomId(region, { prefix = \"sp\", rand: rand2 = () => crypto.getRandomValues(new Uint8Array(8)) } = {}) {\n const tail = Array.from(rand2()).map((x) => x.toString(36)).join(\"\").slice(0, 12);\n const marked = region && region !== DEFAULT_REGION && Object.prototype.hasOwnProperty.call(REGIONS, region);\n return `${prefix}-${marked ? region + \"-\" : \"\"}${tail}`;\n}\n\n// spaces/public/sdk/4.7.0/spaceConfig.js\nvar enc2 = (s) => encodeURIComponent(String(s));\nfunction normalizeKeyModel(km) {\n if (km == null || km === \"1-of-1\") return { k: 1, n: 1 };\n if (km === \"2-of-2\") return { k: 2, n: 2 };\n if (km && Number.isInteger(km.k) && Number.isInteger(km.n) && km.k >= 1 && km.k <= km.n) return { k: km.k, n: km.n };\n throw new Error(\"bad keyModel\");\n}\nasync function createConfiguredSpace(config = {}, { base = \"\" } = {}) {\n const { k, n } = normalizeKeyModel(config.keyModel);\n const mk = n === 1 && typeof config.mk === \"string\" && config.mk.length >= 40 ? config.mk : newKey();\n const room = config.room || newRoomId(config.region);\n const c = await commit(mk);\n const link = (frag) => `${String(base).replace(/\\/+$/, \"\")}/space?room=${enc2(room)}#${frag}`;\n let links;\n if (n === 1) {\n links = [link(`mk=${enc2(mk)}`)];\n } else if (k === 2 && n === 2) {\n const { shareA, shareB } = splitKey(mk);\n links = [link(`s=${enc2(shareA)}`), link(`s=${enc2(shareB)}`)];\n } else {\n links = shamirSplit(mk, k, n).map((s) => link(`s=${enc2(s)}`));\n }\n return { room, commit: c, keyModel: { k, n }, links };\n}\nasync function assembleConfiguredKey(pieces, config, expectedCommit) {\n const { k, n } = normalizeKeyModel(config && config.keyModel);\n const arr = Array.isArray(pieces) ? pieces.filter(Boolean) : pieces ? [pieces] : [];\n let mk = null;\n if (n === 1) mk = arr[0] || null;\n else if (k === 2 && n === 2) mk = arr.length >= 2 ? combineShares(arr[0], arr[1]) : null;\n else mk = arr.length >= k ? shamirCombine(arr) : null;\n if (mk == null) return null;\n if (n > 1 && !expectedCommit) return null;\n if (expectedCommit && await commit(mk) !== expectedCommit) return null;\n return mk;\n}\nfunction parseConfiguredLink(url) {\n try {\n const u = new URL(url);\n const raw = (u.hash || \"\").replace(/^#/, \"\");\n const q = raw.indexOf(\"?\");\n const frag = new URLSearchParams(q >= 0 ? raw.slice(0, q) : raw);\n return { room: u.searchParams.get(\"room\") || \"\", share: frag.get(\"s\") || \"\", mk: frag.get(\"mk\") || \"\" };\n } catch {\n return { room: \"\", share: \"\", mk: \"\" };\n }\n}\n\n// spaces/public/sdk/4.7.0/invite.js\nvar enc3 = new TextEncoder();\nvar dec2 = new TextDecoder();\nfunction newCode() {\n const A = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\n const r = crypto.getRandomValues(new Uint8Array(12));\n const s = [].slice.call(r).map((x) => A[x % A.length]).join(\"\");\n return s.slice(0, 4) + \"-\" + s.slice(4, 8) + \"-\" + s.slice(8, 12);\n}\nvar normCode = (code) => String(code || \"\").toUpperCase().replace(/[^A-Z0-9]/g, \"\");\nasync function keyFromCode(code, salt) {\n const base = await crypto.subtle.importKey(\"raw\", enc3.encode(normCode(code)), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey(\n { name: \"PBKDF2\", salt, iterations: 21e4, hash: \"SHA-256\" },\n // slow: the code is low-entropy, so make guessing costly\n base,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"]\n );\n}\nvar b643 = (bytes3) => btoa(String.fromCharCode(...bytes3)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\nvar ub643 = (s) => {\n const b = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const a = new Uint8Array(b.length);\n for (let i = 0; i < b.length; i++) a[i] = b.charCodeAt(i);\n return a;\n};\nasync function sealUnderCode(plaintext, code) {\n const salt = crypto.getRandomValues(new Uint8Array(16));\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const key = await keyFromCode(code, salt);\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, enc3.encode(String(plaintext))));\n const out = new Uint8Array(16 + 12 + ct.length);\n out.set(salt);\n out.set(iv, 16);\n out.set(ct, 28);\n return b643(out);\n}\nasync function openUnderCode(blob, code) {\n try {\n const raw = ub643(blob);\n const key = await keyFromCode(code, raw.slice(0, 16));\n const pt = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: raw.slice(16, 28) }, key, raw.slice(28));\n return dec2.decode(pt);\n } catch {\n return null;\n }\n}\n\n// spaces/public/sdk/4.7.0/enclaveAccept.js\nvar HEX48 = /^[0-9a-f]{96}$/;\nvar MODES = /* @__PURE__ */ new Set([\"follow\", \"pin\"]);\nvar STAGES = [[\"kernel\", \"0\"], [\"payload\", \"16\"], [\"policy\", \"17\"]];\nvar hex = (v, what) => {\n const h = String(v).toLowerCase();\n if (!HEX48.test(h)) throw new Error(`enclave acceptance: ${what} is not a SHA-384 hex digest`);\n return h;\n};\nvar version = (v, what) => {\n if (v === void 0 || v === null) return 0;\n if (typeof v !== \"number\" || !Number.isInteger(v) || v < 0) throw new Error(`enclave acceptance: ${what} must be a non-negative integer`);\n return v;\n};\nfunction tripleOf(att) {\n const p = att && att.pcrs || {};\n const t = {};\n for (const [name, idx] of STAGES) if (p[idx]) t[name] = String(p[idx]).toLowerCase();\n return t;\n}\nvar sameTriple = (a, b) => STAGES.every(([name]) => (a[name] || null) === (b[name] || null));\nfunction parseAcceptance(raw) {\n if (raw === void 0 || raw === null) return null;\n if (typeof raw !== \"object\") throw new Error(\"enclave acceptance: block must be an object\");\n if (!MODES.has(raw.mode)) throw new Error(`enclave acceptance: unknown mode ${JSON.stringify(raw.mode)}`);\n const minPolicyVersion = version(raw.minPolicyVersion, \"minPolicyVersion\");\n const accepted = Array.isArray(raw.accepted) ? raw.accepted.map((e, i) => {\n if (!e || typeof e !== \"object\") throw new Error(`enclave acceptance: accepted[${i}] is not an object`);\n const out = { kernel: hex(e.kernel, `accepted[${i}].kernel`) };\n if (e.payload !== void 0 && e.payload !== null) out.payload = hex(e.payload, `accepted[${i}].payload`);\n if (e.policy !== void 0 && e.policy !== null) out.policy = hex(e.policy, `accepted[${i}].policy`);\n out.policyVersion = version(e.policyVersion, `accepted[${i}].policyVersion`);\n out.label = String(e.label || \"\").slice(0, 64);\n out.at = typeof e.at === \"number\" ? e.at : 0;\n return out;\n }) : [];\n if (raw.mode === \"pin\" && !accepted.length) throw new Error(\"enclave acceptance: a pinned Space that accepts nothing can never seal its key\");\n return { mode: raw.mode, minPolicyVersion, accepted };\n}\nfunction acceptsMeasurement(cfg, attested, platform) {\n const c = parseAcceptance(cfg) || { mode: \"follow\", minPolicyVersion: 0, accepted: [] };\n const live = tripleOf(attested);\n if (!live.kernel) return { ok: false, reason: \"no_attestation\", live };\n const pv = attested && typeof attested.policyVersion === \"number\" ? attested.policyVersion : null;\n if (c.minPolicyVersion > 0 && !(pv !== null && pv >= c.minPolicyVersion)) return { ok: false, reason: \"floor\", live, floor: c.minPolicyVersion, policyVersion: pv };\n if (c.mode === \"pin\") {\n const matched = c.accepted.find((e) => sameTriple(e, live));\n return matched ? { ok: true, matched, live } : { ok: false, reason: \"not_accepted\", live };\n }\n const want = pinSetsOf(platform);\n if (!want.kernel.length) return { ok: false, reason: \"no_platform_claim\", live };\n for (const [name] of STAGES) {\n const ok = want[name].length ? want[name].includes(live[name] || \"\") : !live[name];\n if (!ok) return { ok: false, reason: name, live, platform: want };\n }\n return { ok: true, matched: { ...live }, live };\n}\nfunction pinSetsOf(att) {\n const p = att && att.pcrs || {};\n const t = {};\n for (const [name, idx] of STAGES) t[name] = (Array.isArray(p[idx]) ? p[idx] : p[idx] ? [p[idx]] : []).map((v) => String(v).toLowerCase());\n return t;\n}\nfunction parseTrusted(raw) {\n const out = [];\n for (const e of Array.isArray(raw) ? raw : []) {\n try {\n if (!e || typeof e !== \"object\") continue;\n const t = { kernel: hex(e.kernel, \"kernel\") };\n if (e.payload) t.payload = hex(e.payload, \"payload\");\n if (e.policy) t.policy = hex(e.policy, \"policy\");\n t.at = typeof e.at === \"number\" && Number.isFinite(e.at) ? e.at : 0;\n if (!out.some((x) => sameTriple(x, t))) out.push(t);\n } catch {\n }\n }\n return out;\n}\nfunction userVerdict(trusted, attested, platform) {\n const pub = acceptsMeasurement(null, attested, platform);\n if (!pub.ok) return pub;\n if (trusted === void 0) return { ok: false, reason: \"unknown\", live: pub.live };\n return parseTrusted(trusted).some((e) => sameTriple(e, pub.live)) ? { ok: true, matched: pub.live, live: pub.live } : { ok: false, reason: \"not_accepted\", live: pub.live };\n}\nfunction gatedKey({ key, trusted, attested, platform, room } = {}) {\n if (!key) return null;\n const verdict = userVerdict(trusted, attested, platform);\n if (verdict.ok) return key;\n const err = new Error(`enclave_not_accepted: you have not accepted the enclave build this Space runs on (${verdict.reason})`);\n err.code = \"enclave_not_accepted\";\n err.verdict = verdict;\n err.room = room || null;\n throw err;\n}\n\n// spaces/public/sdk/4.7.0/entrySig.js\nvar enc4 = new TextEncoder();\nvar dec3 = new TextDecoder();\nvar toB64 = (u8) => btoa(String.fromCharCode(...u8)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\nvar ECDSA = { name: \"ECDSA\", namedCurve: \"P-256\" };\nvar SIGN = { name: \"ECDSA\", hash: \"SHA-256\" };\nvar importPriv = (jwk) => crypto.subtle.importKey(\"jwk\", jwk, ECDSA, false, [\"sign\"]);\nfunction canon(o) {\n if (o === null || typeof o !== \"object\") return JSON.stringify(o);\n if (Array.isArray(o)) return \"[\" + o.map(canon).join(\",\") + \"]\";\n return \"{\" + Object.keys(o).sort().map((k) => JSON.stringify(k) + \":\" + canon(o[k])).join(\",\") + \"}\";\n}\nvar entryCore = (e) => ({ room: e.room, author: e.author, ts: e.ts, kind: e.kind, id: e.id, text: e.text, ...e.chal !== void 0 ? { chal: e.chal } : {} });\nasync function signEntry(memberPrivJwk, entry) {\n const sig = toB64(new Uint8Array(await crypto.subtle.sign(SIGN, await importPriv(memberPrivJwk), enc4.encode(canon(entryCore(entry))))));\n return { ...entry, sig };\n}\n\n// spaces/public/sdk/4.7.0/mkseal.js\nvar VERSION2 = 1;\nvar enc5 = new TextEncoder();\nvar MAX_CLOCK_OFFSET_MS = 864e5;\nvar CLOCK = globalThis.__wbSealClock = globalThis.__wbSealClock || { offset: 0 };\nvar sealNow = () => Date.now() + CLOCK.offset;\nfunction noteServerClock(serverNow, localNow = Date.now()) {\n const t = Number(serverNow);\n if (!Number.isFinite(t) || t <= 0) return false;\n const d = Math.max(-MAX_CLOCK_OFFSET_MS, Math.min(MAX_CLOCK_OFFSET_MS, Math.round(t - localNow)));\n const moved = Math.abs(d - CLOCK.offset) > 1e3;\n CLOCK.offset = d;\n return moved;\n}\nfunction b644(bytes3) {\n const b = bytes3 instanceof Uint8Array ? bytes3 : new Uint8Array(bytes3);\n let s = \"\";\n for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\nfunction mkAad({ room, op, ts, nonce } = {}) {\n return `mkseal-v1|${room || \"\"}|${op || \"\"}|${ts || 0}|${nonce || \"\"}`;\n}\nfunction newNonce() {\n return b644(crypto.getRandomValues(new Uint8Array(12)));\n}\nasync function sealMk(mk, publicJwk, aad) {\n const pub = await crypto.subtle.importKey(\"jwk\", publicJwk, { name: \"ECDH\", namedCurve: \"P-256\" }, false, []);\n const eph = await crypto.subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, false, [\"deriveBits\"]);\n const epk = new Uint8Array(await crypto.subtle.exportKey(\"raw\", eph.publicKey));\n const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: \"ECDH\", public: pub }, eph.privateKey, 256));\n const key = await deriveKey(shared, epk);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: enc5.encode(String(aad || \"\")) },\n key,\n enc5.encode(String(mk))\n ));\n return { v: VERSION2, epk: b644(epk), iv: b644(iv), ct: b644(ct) };\n}\nasync function deriveKey(shared, epk) {\n const ikm = await crypto.subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n const info = new Uint8Array([...enc5.encode(\"mkseal-v1\"), ...epk]);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info },\n ikm,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"]\n );\n}\n\n// spaces/public/sdk/4.7.0/reqEnvelope.js\nvar PLAIN_OPS = /* @__PURE__ */ new Set([\n \"create\",\n \"pollsealed\",\n \"blob\",\n \"policy\",\n \"touch\",\n \"purge\",\n \"drop\",\n \"pushdrop\",\n \"user\",\n \"enclaveattest\",\n \"wake\",\n \"changes\",\n \"changesub\",\n \"changemark\",\n \"attest-accept\",\n \"deviceverify\",\n \"receipts\",\n \"receiptsack\",\n // the Lambda answers these itself (agent/enclaveRelay.mjs FRONT_OPS): sealed, it could not read them — device enrollment in an\n // attested confidential room failed (sweep 11-06 #5). spaces/test/frontOpsPlain.test.mjs holds FRONT_OPS ⊆ PLAIN_OPS.\n \"attest-enroll\",\n \"device-verify\",\n \"device-verify-result\",\n // report: what a member CHOSE to show Witbitz (agent/reportOp.mjs — stored and mailed to reports@, never the enclave); the\n // Lambda must read it, so sealed to the enclave it never arrived from a confidential room (CI 2026-11-07, frontOpsPlain)\n \"report\"\n]);\nvar opensEnvelopes = (attested) => {\n if (!attested || !attested.policy || typeof attested.policy !== \"object\") return null;\n return !!(attested.policy.env && attested.policy.env.SEALED_REQUESTS === \"1\");\n};\nvar sealsIdentity = (attested) => !!(attested && attested.policy && attested.policy.env && attested.policy.env.SEALED_IDENTITY === \"1\");\nvar IDENTITY_PLAIN_OPS = /* @__PURE__ */ new Set([\"pollsealed\", \"blob\", \"policy\", \"purge\", \"attest-accept\"]);\nvar READ_OUTSIDE = [\"sinceEtag\", \"sinceCount\", \"changeInbox\"];\nvar carriesIdentity = (body) => !!(body && (typeof body.idToken === \"string\" || body.message && typeof body.message === \"object\" && typeof body.message.idToken === \"string\"));\nvar b645 = (u) => {\n let s = \"\";\n for (const x of u) s += String.fromCharCode(x);\n return btoa(s);\n};\nvar unb64 = (s) => Uint8Array.from(atob(String(s || \"\")), (c) => c.charCodeAt(0));\nvar answerAad = ({ room, op, nonce }) => new TextEncoder().encode(`witbitz-answer|v1|${room}|${op}|${nonce}`);\nfunction outsideOf(body, identity) {\n const o = { op: body.op, room: body.room, enclave: true };\n if (!identity && typeof body.idToken === \"string\") o.idToken = body.idToken;\n if (body.op === \"pollsealed\" || body.op === \"blob\") {\n for (const k of READ_OUTSIDE) if (body[k] !== void 0) o[k] = body[k];\n }\n if (typeof body.bridgeRoom === \"string\") o.bridgeRoom = body.bridgeRoom;\n if (body.op === \"decide\" && typeof body.approve === \"boolean\") o.approve = body.approve;\n if (body.op === \"state\" && body.patch !== void 0) o.patch = null;\n const ra = body.readAttestation && typeof body.readAttestation === \"object\" ? body.readAttestation.attestation : null;\n const plat = (x) => typeof x.platform === \"string\" && /^[a-z]{2,16}$/.test(x.platform) ? { platform: x.platform } : {};\n if (ra && typeof ra === \"object\" && typeof ra.keyId === \"string\") o.readAttestation = { attestation: { keyId: ra.keyId, ...plat(ra) } };\n const m = body.message;\n if (m && typeof m === \"object\") {\n const stub = {};\n if (!identity && typeof m.idToken === \"string\") stub.idToken = m.idToken;\n if (m.attestation && typeof m.attestation === \"object\" && typeof m.attestation.keyId === \"string\") stub.attestation = { keyId: m.attestation.keyId, ...plat(m.attestation) };\n if (Object.keys(stub).length || !identity) o.message = stub;\n }\n return o;\n}\nasync function sealRequest(body, publicJwk, { identity = false, extras = null } = {}) {\n const key = crypto.getRandomValues(new Uint8Array(32));\n const ts = sealNow(), nonce = newNonce();\n const inner = { ...body, answerKey: b645(key) };\n if (identity && extras && typeof extras === \"object\") {\n if (Array.isArray(extras.userHints) && extras.userHints.length) inner.userHints = extras.userHints;\n if (extras.issuerCfg && typeof extras.issuerCfg === \"object\") inner.issuerCfg = extras.issuerCfg;\n if (Array.isArray(extras.boundHints) && extras.boundHints.length) inner.boundHints = extras.boundHints.slice(0, 4);\n }\n delete inner.op;\n delete inner.room;\n delete inner.enclave;\n const envSealed = await sealMk(JSON.stringify(inner), publicJwk, mkAad({ room: body.room, op: body.op + \":env\", ts, nonce }));\n return { outer: { ...outsideOf(body, identity), envSealed, envTs: ts, envNonce: nonce }, answer: { key, aad: answerAad({ room: body.room, op: body.op, nonce }) } };\n}\nvar REFUSAL_FIELDS = [\"error\", \"reason\", \"detail\"];\nasync function openAnswer(reply, answer) {\n const status = reply && Number.isInteger(reply.status) ? reply.status : 0;\n const sa = reply && reply.sealedAnswer;\n if (!sa || typeof sa !== \"object\") {\n if (status >= 200 && status < 300) return { status: 502, ok: false, error: \"answer_unsealed\", reason: \"the answer to a sealed request came back unsealed — not from the enclave\" };\n const out = { status, ok: false };\n for (const k of REFUSAL_FIELDS) if (reply && typeof reply[k] === \"string\") out[k] = reply[k].slice(0, 300);\n if (reply && reply.warming === true) out.warming = true;\n if (reply && reply.confidential === true) out.confidential = true;\n if (reply && Number.isFinite(reply.now)) out.serverNow = reply.now;\n if (!out.error && !(status >= 500)) out.error = \"refused\";\n return out;\n }\n try {\n const k = await crypto.subtle.importKey(\"raw\", answer.key, \"AES-GCM\", false, [\"decrypt\"]);\n const pt = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: unb64(sa.iv), additionalData: answer.aad }, k, unb64(sa.ct));\n const inner = JSON.parse(new TextDecoder().decode(pt));\n return { status, ...inner && typeof inner === \"object\" && !Array.isArray(inner) ? inner : {}, ...reply.confidential === true ? { confidential: true } : {} };\n } catch {\n return { status, ok: false, error: \"answer_unopenable\", reason: \"the enclave's answer could not be opened on this device\" };\n }\n}\n\n// spaces/public/sdk/4.7.0/ownerPolicy.js\nvar enc6 = new TextEncoder();\nvar ECDSA2 = { name: \"ECDSA\", namedCurve: \"P-256\" };\nvar SIGN2 = { name: \"ECDSA\", hash: \"SHA-256\" };\nvar bytesToB64u = (bytes3) => {\n let s = \"\";\n for (const b of bytes3) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar b64uToBytes = (str) => {\n const bin = atob(String(str).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const u = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);\n return u;\n};\nfunction canon2(o) {\n if (o === null || typeof o !== \"object\") return JSON.stringify(o);\n if (Array.isArray(o)) return \"[\" + o.map(canon2).join(\",\") + \"]\";\n return \"{\" + Object.keys(o).sort().map((k) => JSON.stringify(k) + \":\" + canon2(o[k])).join(\",\") + \"}\";\n}\nvar sha256b64u = async (s) => bytesToB64u(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", enc6.encode(s))));\nvar sameKey = (a, b) => !!a && !!b && canon2({ kty: a.kty, crv: a.crv, x: a.x, y: a.y }) === canon2({ kty: b.kty, crv: b.crv, x: b.x, y: b.y });\nasync function ownerKeyId(jwk) {\n return (await sha256b64u(canon2({ kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y }))).slice(0, 22);\n}\nasync function policyHash(policy) {\n return sha256b64u(canon2(policy));\n}\nasync function verifyPolicy(signed, { ownerKey = null, now = Date.now() } = {}) {\n const policy = signed && typeof signed === \"object\" ? signed.policy : null;\n if (!policy || typeof policy !== \"object\" || typeof signed.sig !== \"string\") return { ok: false, reason: \"malformed\" };\n const declared = policy.ownerKey;\n if (!declared || typeof declared !== \"object\") return { ok: false, reason: \"no_owner_key\" };\n if (ownerKey && !sameKey(declared, ownerKey)) return { ok: false, reason: \"owner_mismatch\" };\n let valid = false;\n try {\n valid = await crypto.subtle.verify(SIGN2, await crypto.subtle.importKey(\"jwk\", ownerKey || declared, ECDSA2, false, [\"verify\"]), b64uToBytes(signed.sig), enc6.encode(canon2(policy)));\n } catch {\n valid = false;\n }\n if (!valid) return { ok: false, reason: \"bad_sig\" };\n const nowSec = Math.floor(now / 1e3);\n if (typeof policy.notBefore === \"number\" && nowSec < policy.notBefore) return { ok: false, reason: \"not_yet_valid\" };\n if (typeof policy.notAfter === \"number\" && nowSec >= policy.notAfter) return { ok: false, reason: \"expired\" };\n return { ok: true, policy };\n}\nasync function verifyRoomPolicy({ marker = null, sealed = null, ownerKey = null, required = false, now = Date.now() } = {}) {\n if (!marker) return required ? { ok: false, governed: true, reason: \"policy_required\" } : { ok: true, governed: false };\n if (!sealed || !sealed.policy) return { ok: false, governed: true, reason: \"policy_missing\" };\n const v = await verifyPolicy(sealed, { ownerKey, now });\n if (!v.ok) return { ok: false, governed: true, reason: v.reason };\n if (String(v.policy.app || \"\") !== String(marker.app || \"\")) return { ok: false, governed: true, reason: \"app_mismatch\" };\n if (await policyHash(v.policy) !== marker.policyHash) return { ok: false, governed: true, reason: \"hash_mismatch\" };\n if (await ownerKeyId(v.policy.ownerKey) !== marker.ownerKeyId) return { ok: false, governed: true, reason: \"owner_mismatch\" };\n return { ok: true, governed: true, policy: v.policy };\n}\nfunction qualifies(admit, { authenticated = false, issuer = null, claims = {} } = {}) {\n if (admit === \"anonymous\" || admit && admit.anonymous) return true;\n if (!admit || typeof admit !== \"object\" || !admit.issuer) return false;\n if (!authenticated || issuer !== admit.issuer) return false;\n if (admit.any) return true;\n if (admit.claim && typeof admit.claim === \"object\") {\n return Object.entries(admit.claim).every(([k, val]) => {\n const c = claims && claims[k];\n if (Array.isArray(c)) return c.includes(val);\n if (k === \"group\" && Array.isArray(claims && claims.groups)) return claims.groups.includes(val);\n return c === val;\n });\n }\n return false;\n}\nfunction resolveTier(policy, { authenticated = false, issuer = null, claims = {}, roomTier = null } = {}) {\n const tiers = Array.isArray(policy && policy.tiers) ? policy.tiers : [];\n if (!tiers.length) return { tier: null };\n const ceilingName = roomTier || policy.roomTiers && policy.roomTiers.default || tiers[tiers.length - 1].name;\n const ceilingRank = Math.max(0, tiers.findIndex((t) => t.name === ceilingName));\n let best = -1;\n for (let i = 0; i <= ceilingRank && i < tiers.length; i++) if (qualifies(tiers[i].admit, { authenticated, issuer, claims })) best = i;\n return best < 0 ? { tier: null } : { tier: tiers[best].name, caps: tiers[best].caps || {}, limits: tiers[best].limits || null };\n}\nasync function verifyRoomGovernance({ room, mk, ownerKey = null, fetchPolicy, openConfig, member = null, now = Date.now() } = {}) {\n let marker = null, configSealed = null, key = ownerKey;\n try {\n const r = await fetchPolicy(room) || {};\n marker = r.policy;\n configSealed = r.configSealed;\n if (!key) key = r.ownerKey || null;\n } catch {\n return { ok: false, governed: true, reason: \"fetch_failed\" };\n }\n if (!marker) return { ok: true, governed: false };\n if (!key) return { ok: true, governed: false };\n let sealed = null;\n try {\n const cfg = await openConfig(configSealed, mk);\n sealed = cfg && cfg.ownerPolicy;\n } catch {\n }\n const rp = await verifyRoomPolicy({ marker, sealed, ownerKey: key, now });\n if (!rp.ok) return { ok: false, governed: true, reason: rp.reason };\n const tier = member ? resolveTier(rp.policy, { ...member }).tier : void 0;\n return { ok: true, governed: true, policy: rp.policy, ...tier ? { tier } : {} };\n}\n\n// spaces/public/sdk/4.7.0/roomName.js\nvar staysDirect = (allow) => {\n const a = allow || {}, n = (k) => Array.isArray(a[k]) ? a[k].filter(Boolean).length : 0;\n return !n(\"domains\") && n(\"emails\") + n(\"mh\") + n(\"hidden\") + n(\"users\") <= 2;\n};\n\n// spaces/public/sdk/4.7.0/mirrorBatch.js\nvar encoder = new TextEncoder();\nasync function stageMirrorAttachments(entries, send) {\n if (encoder.encode(JSON.stringify(entries)).length < 21e5) return { entries };\n const prepared = [];\n for (const entry of entries) {\n const copy = { ...entry };\n for (const field of [\"images\", \"files\"]) {\n if (!Array.isArray(entry[field])) continue;\n copy[field] = [];\n for (const attachment of entry[field]) {\n if (!attachment?.b64) {\n copy[field].push(attachment);\n continue;\n }\n const { b64: b6410, ref, parts: oldParts, ...metadata } = attachment;\n const data = b6410.replace(/^data:[^,]*;base64,/, \"\");\n const parts = [];\n let size = 0;\n for (let offset = 0; offset < data.length; offset += 12e5) {\n const r = await send([{ kind: \"mirror-part\", id: entry.id, mime: metadata.mime, b64: data.slice(offset, offset + 12e5) }]);\n if (r?.status === 200 && typeof r.ref !== \"string\") return { entries };\n if (r?.status !== 200 || !Number.isInteger(r.size)) return { error: r?.status && r.status !== 200 ? r : { status: 503, error: \"mirror_part_unconfirmed\" } };\n parts.push(r.ref);\n size += r.size;\n }\n copy[field].push({ ...metadata, size, ...parts.length === 1 ? { ref: parts[0] } : { parts } });\n }\n }\n prepared.push(copy);\n }\n return { entries: prepared };\n}\n\n// spaces/public/sdk/4.7.0/rosterHash.js\nvar enc7 = new TextEncoder();\nvar b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\nvar norm = (s) => String(s == null ? \"\" : s).normalize(\"NFKC\").trim().toLowerCase();\nasync function memberHash(identity, roomSalt) {\n const digest = await crypto.subtle.digest(\"SHA-256\", enc7.encode(`${norm(identity)}|${roomSalt}`));\n return b64url(digest);\n}\n\n// spaces/public/sdk/4.7.0/roomRoles.js\nvar lc = (s) => String(s || \"\").trim().toLowerCase();\nvar TAG = /^[A-Za-z0-9_-]{16,128}$/;\nvar roleOf = (emails, tags) => {\n const t = [...new Set((tags || []).filter((x) => typeof x === \"string\" && TAG.test(x)))];\n return { emails: [...new Set((emails || []).map(lc).filter(Boolean))], ...t.length ? { tags: t } : {} };\n};\n\n// spaces/public/sdk/4.7.0/spaceClient.js\nfunction embedAttribution() {\n try {\n if (typeof location === \"undefined\") return {};\n const tid = new URLSearchParams(location.search).get(\"tid\") || \"\";\n const embedOrigin = typeof document !== \"undefined\" && document.referrer ? new URL(document.referrer).origin : \"\";\n return tid && embedOrigin ? { tid: tid.slice(0, 64), embedOrigin } : {};\n } catch {\n return {};\n }\n}\nasync function directRoster(allow, room) {\n if (!Array.isArray(allow?.emails) || !Array.isArray(allow?.mh) || !allow.mh.length) return allow;\n const shown = new Set(await Promise.all(allow.emails.map((email) => memberHash(email, room))));\n return { ...allow, mh: allow.mh.filter((hash) => !shown.has(hash)) };\n}\nvar sealConfig = async (config, mk) => JSON.stringify(await seal(JSON.stringify({\n tools: config.tools,\n immediateTools: config.immediateTools,\n clientTools: config.clientTools,\n persona: config.persona,\n agentName: config.agentName,\n ...config.appId ? { appId: String(config.appId).slice(0, 40) } : {},\n // §APP STORE Stage 1: the Space's chosen app — an ID, never a URL (the store origin resolves it against its catalog)\n // The DECLARED MCP server (name → typed input schema) — sealed like the rest, so the platform can't read the app's\n // skill surface at rest; the turn op reads it in the mk-scoped decrypt to type-check + admit an app→agent mcp call.\n skills: config.skills,\n // BYO model — {provider, key, model, baseUrl}. Sealed like the rest of the config, so the tenant's credential is\n // ciphertext at rest and the platform cannot read it outside a turn.\n model: config.model,\n // Admission policy + allow-list ride INSIDE the sealed config → the platform can't read a Space's gate or who's\n // allowed at rest; the turn op reads them only in the mk-scoped decrypt (spaceHandler create → spaceService turn).\n // JSON.stringify drops undefined keys, so an open Space seals exactly as before (backward compatible).\n admission: config.admission,\n allow: config.allow,\n requireChallenge: config.requireChallenge,\n agentKeys: config.agentKeys,\n usernames: config.usernames,\n // usernames:false = the room opted out of the server-stamped @username on verified entries (docs/spaces-usernames.md §7)\n // Owner rule (docs/the-owner-rule.md): the owner-SIGNED App Policy + this room's tier, sealed like the rest — so the\n // render enforces it and a joining client can open + peer-verify governance against the pinned owner key. Undefined\n // (ungoverned room) ⇒ JSON.stringify drops them ⇒ sealed exactly as before.\n ownerPolicy: config.ownerPolicy,\n roomTier: config.roomTier,\n // Private lane (docs/spaces-private-lane.md): `bridge` = a private lane's link to its shared room; `agentReplies`\n // = false for a Bridge SHARED room (an observer venue — the agent doesn't auto-reply). Sealed like the rest, so\n // both are content-blind at rest; undefined (a normal Space) ⇒ JSON.stringify drops them ⇒ sealed exactly as before.\n bridge: config.bridge,\n agentReplies: config.agentReplies,\n // THE ROOM AS A STORE (agent/dataTools.mjs): the app's declared collections + field rules. Sealed like the rest; a\n // room without one sees no data tools. Undefined ⇒ dropped ⇒ sealed exactly as before.\n dataSchema: config.dataSchema,\n // WHICH PLATFORM TOOLS the assistant gets (agent/spaceService.mjs normPlatformTools): absent = all, false = none, a list =\n // only those. Undefined ⇒ dropped ⇒ sealed exactly as before.\n platformTools: config.platformTools === false || Array.isArray(config.platformTools) ? config.platformTools : void 0,\n // BUILDER MODE (Tomer, 2026-10-10): `framing: 'builder'` = the prompt is the app's persona and tools only — no Spaces\n // framing; `dataWrites: false` = the room store offers data_query only. Undefined ⇒ dropped ⇒ sealed exactly as before.\n framing: config.framing === \"builder\" ? \"builder\" : void 0,\n // A PURGEABLE room (docs/room-messages.md § Retention): its handled rows may be purged (op 'purge'). Create-time only,\n // and only the account's own control rooms — the server refuses it on any room with an assistant or admission.\n retention: config.retention === \"purgeable\" ? \"purgeable\" : void 0,\n dataWrites: config.dataWrites === false ? false : void 0,\n // SAFE MEDIA (docs/safe-media.md): photos and PDFs here are shown from copies the tools enclave made safe. Undefined ⇒ dropped ⇒ sealed exactly as before.\n safeMedia: config.safeMedia === true ? true : void 0,\n // Private lanes for EVERYONE (create checkbox): a create-time room property every joiner learns from the room —\n // this whitelist silently DROPPED it, which is why an invitee whose link lost the one-shot &lanes=1 hint could\n // never self-heal (the sealed config genuinely lacked the field). Undefined ⇒ dropped ⇒ sealed exactly as before.\n lanes: config.lanes === true ? true : void 0,\n lane: config.lane === true ? true : void 0,\n // A PRIVATE LANE SAYS SO (laneConfig.js `lane: true`): this whitelist dropped it, so the server and the cloud device never saw it (sync sweep 11-19 P1)\n // Membership fork (docs/spaces-membership-fork.md): the epoch's admitted ROSTER (name+spk per keeper), stamped by\n // forkRoom. Since membership only changes via a fork (add = fork), this stays authoritative between forks — so the\n // NEXT fork reads it instead of re-deriving from the ledger (whose carried history still holds removed members'\n // spks). Absent on an original room ⇒ dropped by JSON.stringify ⇒ sealed exactly as before (roster derived from the\n // ledger as the bootstrap). Sealed under mk like the rest — the platform can't read who's in.\n roster: config.roster,\n // `forkAuthority` = the spk allowed to publish a membership-fork notice for this room (the creator, then carried\n // across forks). A keeper AUTO-FOLLOWS a fork only if the notice is signed by this key — the hijack defense, since\n // anyone holding mk could otherwise read keeper spks from the ledger and forge a fork to a room they control.\n forkAuthority: config.forkAuthority,\n // `parent` = { room } of the PRIOR epoch, set by a LINK fork (P4, epoch-keyed): history lives in the parent chain\n // rather than being re-sealed here, so a fork is O(1). readEpochChain walks it with the ancestor keys from the\n // pointer. Absent on a normal/full-fork room ⇒ dropped by JSON.stringify ⇒ sealed exactly as before.\n parent: config.parent,\n // Enclave acceptance (docs/enclave-room-acceptance.md): what THIS Space accepts from the confidential tier —\n // `{mode: follow|pin, minPolicyVersion, accepted:[{kernel,payload,policy,…}]}`. Sealed under mk like the rest, so\n // every member (and the enclave, which re-opens the config) reads the same declaration; create-once, so a change\n // is a fork. Validated here so garbage is refused at mint rather than guessed about by every opener. Absent\n // (a normal Space, or a pre-P2 confidential one ⇒ follow) ⇒ dropped by JSON.stringify ⇒ sealed exactly as before.\n enclave: parseAcceptance(config.enclave) || void 0,\n // ROOM GOVERNANCE (2026-10-02). `admins` ({ emails }) and `approve` ('admins'|'members') are enforced by the SERVER\n // (spaceService hasAdmins/isRoomAdmin/cardNeedsAdmin) — and were MISSING from this list, so an SDK room declared them\n // and sealed without them: no admins, approvals by any member (a builder measured it on production). `forkedFrom` is\n // where a fork came from; `connections` are the grants a fork carries. Undefined ⇒ dropped ⇒ sealed exactly as before.\n admins: config.admins && Array.isArray(config.admins.emails) ? roleOf(config.admins.emails, config.admins.tags) : void 0,\n // tags: an admin by @username tag (docs/spaces-usernames.md § 13.1)\n owners: config.owners && Array.isArray(config.owners.emails) ? roleOf(config.owners.emails, config.owners.tags) : void 0,\n // OWNERS (2026-10-03): above admins, enforced by the room\n forkedFrom: typeof config.forkedFrom === \"string\" && config.forkedFrom ? config.forkedFrom.slice(0, 120) : void 0,\n connections: Array.isArray(config.connections) && config.connections.length ? config.connections : void 0,\n direct: config.direct === true ? true : void 0,\n // a DIRECT chat (directChat.js): the server refuses its rename, the other side files it by this\n help: config.help === true ? true : void 0\n // the account's HELP SPACE (helpSpace.js): the server runs its built-in help configuration\n}), { room: mk }));\nvar invitePad = () => {\n const r = crypto.getRandomValues(new Uint8Array(90));\n return btoa(String.fromCharCode(...r)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar DEFAULT_ENDPOINT = \"/space\";\nvar originBase = () => typeof location !== \"undefined\" && location.origin || \"\";\nvar _ohttp = null;\nasync function readSealedArchive(read) {\n const first = await read(0);\n if (!first?.more) return first;\n const boxes = [], revision = (etag) => String(etag || \"\").replace(/#\\d+$/, \"\");\n let page = first;\n for (let i = 0; i < 400; i++) {\n let slice;\n try {\n slice = JSON.parse(page?.sealed);\n } catch {\n }\n if (page?.status !== 200 || revision(page.etag) !== revision(first.etag) || slice?.v !== 3 || !Array.isArray(slice.boxes) || slice.from !== boxes.length || slice.count !== boxes.length + slice.boxes.length) break;\n for (const box of slice.boxes) boxes.push(box);\n if (!page.more) return { ...page, from: 0, count: boxes.length, sealed: JSON.stringify({ ...slice, from: 0, count: boxes.length, boxes }) };\n if (!slice.boxes.length) break;\n page = await read(boxes.length);\n }\n return { status: 409, error: \"archive_incomplete\" };\n}\nvar _ohttpPending = null;\nasync function awaitOhttpReady() {\n const p = _ohttpPending;\n if (p) {\n try {\n await p;\n } catch {\n }\n }\n}\nvar _ohttpMod = null;\nvar ohttpMod = async () => _ohttpMod || (_ohttpMod = await Promise.resolve().then(() => (init_ohttp(), ohttp_exports)));\nasync function ohttpCall(body, fetchImpl) {\n const O = await ohttpMod();\n const inner = O.encodeRequest({\n method: \"POST\",\n scheme: \"https\",\n authority: _ohttp.gatewayAuthority,\n path: _ohttp.gatewayPath || \"/\",\n headers: { \"content-type\": \"application/json\" },\n body: new TextEncoder().encode(JSON.stringify(body))\n });\n const { encRequest, ks, enc: enc15 } = await O.encapsulateRequest(_ohttp.keyConfig, inner);\n const b6410 = (u8) => {\n let s = \"\";\n for (const b of u8) s += String.fromCharCode(b);\n return btoa(s);\n };\n const ub646 = (s) => {\n const bin = atob(s);\n const u = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);\n return u;\n };\n const res = await fetchImpl(_ohttp.relay, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ op: \"ohttp\", enc: b6410(encRequest) }) });\n if (!res.ok) return { status: res.status };\n let env = {};\n try {\n env = await res.json();\n } catch {\n return { status: res.status };\n }\n if (!env.res) return { status: env.status || res.status, ...env.error ? { error: env.error } : {} };\n const respBhttp = await O.decapsulateResponse(ks, enc15, ub646(env.res));\n const resp = O.decodeResponse(respBhttp);\n let data = {};\n try {\n data = JSON.parse(new TextDecoder().decode(resp.body) || \"{}\");\n } catch {\n }\n return { status: resp.status, ...data };\n}\nasync function call(endpoint, body, fetchImpl) {\n await awaitOhttpReady();\n if (_ohttp) {\n try {\n return _ohttp.send ? await _ohttp.send(body) : await ohttpCall(body, fetchImpl);\n } catch (e) {\n return { status: 0, error: \"ohttp: \" + String(e && e.message || e).slice(0, 120) };\n }\n }\n const res = await fetchImpl(endpoint, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) });\n let data = {};\n try {\n data = await res.json();\n } catch {\n }\n return { status: res.status, ...data };\n}\nvar _pushSelf = \"\";\nfunction setPushSelf(endpoint) {\n _pushSelf = String(endpoint || \"\");\n}\nvar pushSelf = () => _pushSelf;\nasync function crossingPush(room) {\n if (!room) return {};\n return { crossingPush: { room, ...pushSelf() ? { pushSelf: pushSelf() } : {}, ...await pushAcctField(room) } };\n}\nasync function viewingTag(room) {\n if (!_pushSelf || !room || !(globalThis.crypto && crypto.subtle)) return \"\";\n try {\n const k = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(_pushSelf), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return b64u(new Uint8Array(await crypto.subtle.sign(\"HMAC\", k, new TextEncoder().encode(\"witbitz-viewing|\" + room))).slice(0, 16));\n } catch {\n return \"\";\n }\n}\nvar _pushAcct = \"\";\nvar _acctTags = /* @__PURE__ */ new Map();\nfunction setPushAcct(secret) {\n const s = String(secret || \"\");\n if (s !== _pushAcct) {\n _pushAcct = s;\n _acctTags.clear();\n }\n}\nvar b64u = (u8) => {\n let s = \"\";\n for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nasync function pushAcctField(room) {\n if (!_pushAcct || !room || !(globalThis.crypto && crypto.subtle)) return {};\n try {\n let t = _acctTags.get(room);\n if (!t) {\n const k = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(_pushAcct), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n t = b64u(new Uint8Array(await crypto.subtle.sign(\"HMAC\", k, new TextEncoder().encode(\"witbitz-push-acct|\" + room))).slice(0, 16));\n _acctTags.set(room, t);\n }\n return { pushAcct: t };\n } catch {\n return {};\n }\n}\nasync function pushAcctSecretOf(indexMk) {\n const k = typeof indexMk === \"string\" ? indexMk : \"\";\n if (!k || !(globalThis.crypto && crypto.subtle)) return \"\";\n return b64u(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(\"witbitz-push-acct-secret|\" + k))));\n}\nvar _attestProvider = null;\nfunction setAttestProvider(fn) {\n _attestProvider = typeof fn === \"function\" ? fn : null;\n}\nvar _readProvider = null;\nvar readAttestProvider = () => _readProvider || _attestProvider;\nvar attestProvider = () => _attestProvider || (typeof window !== \"undefined\" && typeof window.__vcAttestProvider === \"function\" ? window.__vcAttestProvider : null);\nfunction withSignIn(b, fresh) {\n if (!b || !fresh || typeof fresh.idToken !== \"string\" || !fresh.idToken || !fresh.spk) return null;\n const same2 = (a) => {\n try {\n return JSON.stringify(a) === JSON.stringify(fresh.spk);\n } catch {\n return false;\n }\n };\n if (b.message && typeof b.message === \"object\" && b.message.idToken) return same2(b.message.spk) ? { ...b, message: { ...b.message, idToken: fresh.idToken } } : null;\n if (b.idToken) return { ...b, idToken: fresh.idToken, spk: fresh.spk };\n return null;\n}\nvar SPEND_OPS = /* @__PURE__ */ new Set([\"turn\", \"title\", \"decide\", \"import\"]);\nvar VOICE_OPS = /* @__PURE__ */ new Set([\"stt\", \"tts\"]);\nvar TIER_PROBE_WAITS = [500, 1500];\nvar tierFault = (r) => !r || !r.status || r.status === 429 || r.status >= 500;\nfunction makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl, auth: auth2, mkPub, app, enclave = false, envelope = false, identity = false, tenant, userToken, delCommit, roomPass = null, renewSignIn = null, onConfidential = null, tierWaits = TIER_PROBE_WAITS } = {}) {\n const tenantHint = tenant ? { tid: String(tenant).slice(0, 64) } : {};\n const f = fetchImpl || (typeof fetch !== \"undefined\" ? fetch : null);\n if (!f) throw new Error(\"no fetch available — pass { fetch }\");\n const enclaveFor = (room) => {\n try {\n return typeof enclave === \"function\" ? !!enclave(room) : !!enclave;\n } catch {\n return false;\n }\n };\n const mkPubFor = (room) => {\n try {\n return typeof mkPub === \"function\" ? mkPub(room) || null : mkPub || null;\n } catch (e) {\n if (e && e.code === \"enclave_not_accepted\") throw e;\n return null;\n }\n };\n const envelopeFor = (room) => {\n try {\n const v = typeof envelope === \"function\" ? envelope(room) : envelope;\n return v === true ? true : (v === null || v === void 0) && typeof envelope === \"function\" ? null : false;\n } catch {\n return null;\n }\n };\n const identityFor = (room) => {\n try {\n return (typeof identity === \"function\" ? identity(room) : identity) === true;\n } catch {\n return false;\n }\n };\n const extrasCache = /* @__PURE__ */ new Map();\n const EXTRAS_REFRESH_MS = 36e5;\n const tokenClaims = (tok) => {\n try {\n const p = JSON.parse(atob(String(tok).split(\".\")[1].replace(/-/g, \"+\").replace(/_/g, \"/\")));\n return p && typeof p === \"object\" ? p : null;\n } catch {\n return null;\n }\n };\n const fetchExtras = async (key, tok) => {\n let r = await call(endpoint, { op: \"idextras\", idToken: tok }, f).catch(() => null);\n if (!r || r.status !== 200 && r.status !== 401) {\n await new Promise((ok) => setTimeout(ok, 400));\n r = await call(endpoint, { op: \"idextras\", idToken: tok }, f).catch(() => null);\n }\n if (!r || r.status !== 200 || r.ok !== true || !Number.isFinite(r.exp)) {\n extrasCache.delete(key);\n return null;\n }\n const v = { ...Array.isArray(r.userHints) ? { userHints: r.userHints } : {}, ...r.issuerCfg && typeof r.issuerCfg === \"object\" ? { issuerCfg: r.issuerCfg } : {}, ...Array.isArray(r.boundHints) && r.boundHints.length ? { boundHints: r.boundHints.slice(0, 4) } : {} };\n extrasCache.set(key, { v, exp: r.exp, at: Date.now() });\n return v;\n };\n const extrasFor = async (tok, { fresh = false } = {}) => {\n const c = tokenClaims(tok);\n const email = c && typeof c.email === \"string\" ? c.email.trim().toLowerCase() : \"\";\n if (!email) return {};\n const key = String(c.iss || \"\") + \"|\" + email, now = Date.now();\n if (fresh && !(extrasCache.get(key) || {}).p) extrasCache.delete(key);\n const hit = extrasCache.get(key);\n if (hit && hit.v && now < hit.exp - 6e4) {\n if (now > hit.at + EXTRAS_REFRESH_MS && !hit.p) {\n hit.p = fetchExtras(key, tok).finally(() => {\n const h = extrasCache.get(key);\n if (h) delete h.p;\n });\n }\n return hit.v;\n }\n if (hit && hit.p) return hit.p;\n const p = fetchExtras(key, tok);\n extrasCache.set(key, { p });\n return p;\n };\n const tokenOfBody = (b) => typeof b.idToken === \"string\" ? b.idToken : b.message && typeof b.message.idToken === \"string\" ? b.message.idToken : \"\";\n const tokenFor = async (op) => {\n if (!userToken || !(SPEND_OPS.has(op) || VOICE_OPS.has(op))) return \"\";\n try {\n const t = typeof userToken === \"function\" ? await userToken() : userToken;\n return typeof t === \"string\" ? t : \"\";\n } catch {\n return \"\";\n }\n };\n const post = async (body, billingToken) => {\n const tok = typeof billingToken === \"string\" ? billingToken : body && !body.userToken ? await tokenFor(body.op) : \"\";\n let tokFields = {};\n if (tok) {\n if (body.room && enclaveFor(body.room)) {\n try {\n tokFields = await sealField(body.room, body.op + \":ut\", tok, \"userToken\") || {};\n } catch {\n tokFields = {};\n }\n } else tokFields = { userToken: tok };\n }\n let b0 = tok ? { ...body, ...tokFields } : body;\n const attested = !!(b0 && b0.room && !ATTEST_OWN_OPS.has(b0.op) && !b0.readAttestation);\n const send = async () => {\n let b = attested ? { ...b0, ...passFor(b0.room, b0.op, b0) || await readAttestFor(b0.room) } : b0;\n if (roomPass && b && typeof roomPass.fieldsFor === \"function\") {\n let pf = {};\n try {\n pf = await roomPass.fieldsFor(b, { ts: sealNow() }) || {};\n } catch {\n pf = {};\n }\n if (pf.pass && pf.psig) b = { ...b, pass: pf.pass, psig: pf.psig };\n }\n const body2 = b && (b.enclave === true || enclaveFor(b.room) || learnedConfidential(b)) ? { enclave: true, ...b } : b;\n const enc15 = body2 && body2.enclave === true && typeof body2.room === \"string\";\n const idWay = enc15 && identityFor(body2.room) && carriesIdentity(body2);\n const sealedWay = !enc15 ? false : !PLAIN_OPS.has(body2.op) ? envelopeFor(body2.room) : idWay && IDENTITY_PLAIN_OPS.has(body2.op) && envelopeFor(body2.room) === true;\n if (sealedWay === null) return { status: 503, ok: false, error: \"enclave_policy_unknown\", retryable: true, reason: \"this confidential Space's enclave could not be fully checked yet, so nothing was sent — try again\" };\n const idOnly = sealedWay === true && PLAIN_OPS.has(body2.op) && !gatedRooms.has(body2.room);\n const plainNoId = () => {\n const { idToken: _t, spk: _s, pass: _p, psig: _q, ...rest } = body2;\n return call(endpoint, rest, f);\n };\n if (idOnly && (asleepPlain.get(body2.room) || 0) > Date.now()) return plainNoId();\n if (sealedWay === true) {\n const pub = mkPubFor(body2.room);\n if (!pub) throw new Error(\"enclave key unavailable for this room — refusing to send the request to the relay\");\n let extras = idWay ? await extrasFor(tokenOfBody(body2)) : null;\n const sealedSend = async (ex, bd = body2) => {\n const { outer, answer } = await sealRequest(bd, pub, { identity: idWay, extras: ex || {} });\n return openAnswer(await call(endpoint, outer, f), answer);\n };\n let out = await sealedSend(extras);\n if (idWay && !extras && out && (out.status === 403 && out.error === \"not_authorized\" || out.status === 503 && typeof out.error === \"string\" && out.error)) {\n extras = await extrasFor(tokenOfBody(body2));\n if (extras) out = await sealedSend(extras);\n } else if (idWay && extras && out && out.status === 403 && /^pass: bound_unknown/.test(String(out.reason || \"\"))) {\n const ex = await extrasFor(tokenOfBody(body2), { fresh: true });\n if (ex && Array.isArray(ex.boundHints) && ex.boundHints.length) {\n extras = ex;\n out = await sealedSend(extras);\n }\n }\n if (out && out.error === \"envelope_stale\" && noteServerClock(out.serverNow)) {\n const again = await resealBody(body2);\n if (again) out = await sealedSend(extras, again);\n }\n if (idOnly && out && out.error === \"answer_unsealed\") {\n asleepPlain.set(body2.room, Date.now() + ASLEEP_PLAIN_MS);\n return plainNoId();\n }\n return out;\n }\n if (!enc15 && body2 && typeof body2.room === \"string\") {\n const keyFor = async (room) => {\n const t = await tierOf(room);\n return t === \"enclave\" ? tierRefusal(body2) : t === \"unknown\" ? tierUnknown() : null;\n };\n if (typeof body2.mk === \"string\" && body2.mk) {\n const no = await keyFor(body2.room);\n if (no) return no;\n }\n if (typeof body2.bridgeMk === \"string\" && body2.bridgeMk && typeof body2.bridgeRoom === \"string\" && body2.bridgeRoom) {\n const no = await keyFor(body2.bridgeRoom);\n if (no) return no;\n }\n }\n return call(endpoint, body2, f);\n };\n let r = await send();\n if (r && r.error === \"confidential_room\" && b0 && typeof b0.room === \"string\" && !b0.enclave && !enclaveFor(b0.room) && PLAIN_OPS.has(b0.op) && keyless(b0)) {\n noteTier(b0.room, r);\n if (learnedConfidential(b0)) {\n r = await send();\n if (r && typeof r === \"object\" && !r.tier) r = { ...r, tier: \"enclave\" };\n }\n }\n const passRefused = (re) => !!(r && (r.status === 403 || r.status === 401) && re.test(String(r.reason || \"\")));\n if (renewSignIn && passRefused(/^pass: app_unnamed/)) {\n let fresh = null;\n try {\n fresh = await renewSignIn(b0);\n } catch {\n fresh = { retryable: true };\n }\n const nb = withSignIn(b0, fresh);\n if (nb) {\n b0 = nb;\n r = await send();\n } else if (fresh?.retryable) r = { ...r, passRetryable: true };\n }\n if (roomPass && typeof roomPass.renew === \"function\" && passRefused(/^pass: (pass_expired|pass_required)/)) {\n let renewal;\n try {\n renewal = await roomPass.renew(b0);\n } catch {\n renewal = { retryable: true };\n }\n r = await send();\n if (renewal?.retryable && passRefused(/^pass: pass_required/)) r = { ...r, passRetryable: true };\n }\n if (roomPass && passRefused(/^pass: psig_stale/) && noteServerClock(r.serverNow)) r = await send();\n if (attested) notePass(b0.room, r);\n if (attested && r && r.error === \"attest_required\" && typeof r.challenge === \"string\") {\n attestReadRooms.set(b0.room, r.challenge);\n if (r.reason) attestReadWhy.set(b0.room, String(r.reason));\n r = await send();\n }\n if (attested) {\n notePass(b0.room, r);\n noteReadChal(b0.room, r);\n }\n return r;\n };\n const tierKnown = /* @__PURE__ */ new Map();\n const keyless = (x) => !(typeof x.mk === \"string\" && x.mk) && !(typeof x.bridgeMk === \"string\" && x.bridgeMk) && !x.userShare;\n const learnedConfidential = (x) => !!x && typeof x.room === \"string\" && PLAIN_OPS.has(x.op) && keyless(x) && tierKnown.get(x.room) === \"enclave\";\n const tierAsk = /* @__PURE__ */ new Map();\n const TIER_RETRY_MS = 1e4;\n const noteTier = (room, r) => {\n if (!room || !r || tierKnown.get(room) === \"enclave\") return;\n if (r.tier === \"enclave\" || r.error === \"confidential_room\") {\n tierKnown.set(room, \"enclave\");\n if (!enclaveFor(room) && typeof onConfidential === \"function\") {\n try {\n onConfidential(room);\n } catch {\n }\n }\n } else if (saysStandard(r)) tierKnown.set(room, \"standard\");\n else if (tierKnown.get(room) !== \"standard\") tierKnown.set(room, { until: Date.now() + TIER_RETRY_MS });\n };\n const saysStandard = (r) => r.error !== \"tier_unknown\" && (r.status === 200 || r.status === 401 || r.status === 403);\n const saysTier = (r) => !!r && (r.tier === \"enclave\" || r.error === \"confidential_room\" || saysStandard(r));\n const tierOf = async (room) => {\n if (enclaveFor(room)) return \"enclave\";\n const k = tierKnown.get(room);\n if (k === \"standard\" || k === \"enclave\") return k;\n if (k && k.until > Date.now()) return \"unknown\";\n if (!tierAsk.has(room)) {\n tierAsk.set(room, (async () => {\n try {\n let r = null;\n for (let i = 0; ; i++) {\n try {\n r = await call(endpoint, { op: \"policy\", room, ...await authFor(room) }, f);\n } catch {\n r = { status: 0 };\n }\n if (saysTier(r) || i >= tierWaits.length || !tierFault(r)) break;\n await new Promise((res) => setTimeout(res, tierWaits[i] * (0.5 + Math.random())));\n }\n noteTier(room, r);\n } finally {\n tierAsk.delete(room);\n }\n })());\n }\n await tierAsk.get(room);\n const v = tierKnown.get(room);\n return v === \"standard\" || v === \"enclave\" ? v : \"unknown\";\n };\n const TIER_READS = /* @__PURE__ */ new Set([\"poll\", \"pollsealed\"]);\n const tierRefusal = (body) => TIER_READS.has(body.op) ? { status: 200, ok: true, changed: false, tier: \"enclave\", ...body.sinceEtag ? { etag: body.sinceEtag } : {} } : { status: 409, ok: false, error: \"confidential_room\", tier: \"enclave\", reason: \"this Space is confidential: its requests go to the enclave — nothing was sent. Reopen the Space.\" };\n const tierUnknown = () => ({ status: 503, ok: false, error: \"tier_unknown\", retry: true, reason: \"could not tell yet whether this Space is confidential, so its key was not sent — trying again in a moment\" });\n const ATTEST_OWN_OPS = /* @__PURE__ */ new Set([\"turn\", \"policy\", \"attest-accept\"]);\n const asleepPlain = /* @__PURE__ */ new Map();\n const ASLEEP_PLAIN_MS = 2e4;\n const readAttestFor = async (room) => {\n if (!attestReadRooms.has(room)) return {};\n try {\n const p = readAttestProvider();\n const why = takeReadWhy(room);\n const att = p ? await p(room, { read: true, challenge: attestReadRooms.get(room), ...why ? { refused: why } : {} }) : null;\n return att && att.read ? { readAttestation: att.read } : {};\n } catch {\n return {};\n }\n };\n const authFor = async (room) => {\n if (!auth2) return {};\n try {\n const a = await auth2(room);\n return a && a.idToken && a.spk ? { idToken: a.idToken, spk: a.spk } : {};\n } catch {\n return {};\n }\n };\n const otherAuth = async (rooms) => {\n for (const r of rooms) {\n if (!r) continue;\n const a = await authFor(r);\n if (a.idToken) return a;\n }\n return {};\n };\n const withTurnStatus = async (out, r, mk) => {\n if (typeof r.partialStatus !== \"string\") return out;\n try {\n const st2 = JSON.parse(await open(JSON.parse(r.partialStatus), { mk }));\n const ok = st2 && typeof st2 === \"object\" && (st2.phase === \"thinking\" || st2.phase === \"writing\" || st2.phase === \"deciding\" || typeof st2.tool === \"string\" && /^[a-z0-9_]{1,64}$/.test(st2.tool));\n const since = Number.isFinite(st2.since) ? { since: st2.since } : {};\n return ok ? { ...out, partialStatus: { ...st2.tool ? { tool: st2.tool } : { phase: st2.phase }, ...since }, partialSeq: r.partialSeq || out.partialSeq || 0 } : out;\n } catch {\n return out;\n }\n };\n const withStreamGrants = async (out, r, mk) => {\n let g = Array.isArray(r.stream) ? r.stream : null;\n if (typeof r.streamSealed === \"object\" && r.streamSealed && mk) {\n try {\n g = JSON.parse(await open(r.streamSealed, { mk }));\n } catch {\n g = null;\n }\n }\n const ok = Array.isArray(g) && g.length <= 4 && g.every((x) => x && Number.isInteger(x.e) && typeof x.g === \"string\" && x.g.length <= 64);\n return ok ? { ...out, streamGrants: g.map((x) => ({ e: x.e, g: x.g })) } : out;\n };\n const _reseal = /* @__PURE__ */ new Map();\n const resealable = (nonce, again) => {\n _reseal.set(nonce, again);\n const t = setTimeout(() => _reseal.delete(nonce), 12e4);\n if (t && t.unref) t.unref();\n };\n const resealBody = async (body) => {\n if (!body || body.newMkSealed !== void 0 || body.idSealed !== void 0) return null;\n let out = { ...body };\n for (const [k, v] of Object.entries(body)) {\n if (!/Nonce$/.test(k) || typeof v !== \"string\") continue;\n const again = _reseal.get(v);\n if (!again) return null;\n out = { ...out, ...await again() };\n }\n return out;\n };\n const keyFields = async (room, op, mk) => {\n const pub = mkPubFor(room);\n if (enclaveFor(room) && !pub) throw new Error(\"enclave key unavailable for this room — refusing to send the room key to the relay\");\n if (!pub || !mk) return { mk };\n try {\n const ts = sealNow();\n const nonce = newNonce();\n resealable(nonce, () => keyFields(room, op, mk));\n return { mkSealed: await sealMk(mk, pub, mkAad({ room, op, ts, nonce })), mkTs: ts, mkNonce: nonce };\n } catch (e) {\n if (enclaveFor(room)) throw e;\n return { mk };\n }\n };\n const sealField = async (room, aadOp, plaintext, base) => {\n const pub = mkPubFor(room);\n if (enclaveFor(room) && !pub) throw new Error(\"enclave key unavailable for this room — refusing to send bridged data to the relay\");\n if (!pub) return null;\n const ts = sealNow();\n const nonce = newNonce();\n resealable(nonce, () => sealField(room, aadOp, plaintext, base));\n return { [`${base}Sealed`]: await sealMk(plaintext, pub, mkAad({ room, op: aadOp, ts, nonce })), [`${base}Ts`]: ts, [`${base}Nonce`]: nonce };\n };\n const bridgeFields = async (room, op, bridgeMk) => await sealField(room, op + \":bridge\", bridgeMk, \"bridgeMk\") || { bridgeMk };\n const healEnclaveConfig = async (room, mk) => {\n if (!mk || !enclaveFor(room)) return null;\n let s = null;\n try {\n s = await call(endpoint, { op: \"policy\", room }, f);\n } catch {\n return null;\n }\n if (!s || typeof s.configSealed !== \"string\" || !s.configSealed) return null;\n let cfg = null;\n try {\n cfg = JSON.parse(await open(JSON.parse(s.configSealed), { mk }));\n } catch {\n cfg = null;\n }\n if (!cfg || typeof cfg !== \"object\" || Array.isArray(cfg)) return null;\n let r = null;\n try {\n r = await post({ op: \"config\", room, ...await keyFields(room, \"config\", mk), configSealed: s.configSealed, ...await authFor(room) });\n } catch {\n r = null;\n }\n return { cfg, configSealed: s.configSealed, saved: !!(r && r.status === 200) };\n };\n const policyPost = async (room, mk) => post({ op: \"policy\", room, ...mk ? await keyFields(room, \"policy\", mk) : {}, ...await authFor(room) });\n const linksFields = async (room, op, links) => await sealField(room, op + \":links\", JSON.stringify(links), \"links\") || { links };\n const mkFromLinks = async (links, config, commit2) => {\n const pieces = (Array.isArray(links) ? links : [links]).map((l) => {\n const p = parseConfiguredLink(l);\n return p.share || p.mk;\n }).filter(Boolean);\n return assembleConfiguredKey(pieces, config, commit2);\n };\n const gatedRooms = /* @__PURE__ */ new Set();\n const gatedRefusal = (r) => !!(r && r.reason === \"gated_read_requires_key\" && (r.status === 401 || r.error === \"need_identity\"));\n const sealedRead = async (room, mk, op, fields, { proveKey = false, sent = null } = {}) => {\n const keyed = async () => {\n if (enclaveFor(room) && !mkPubFor(room)) return { status: 503, ok: false, error: \"enclave_warming\", retry: true, reason: \"this confidential Space's enclave is asleep — nothing was sent\" };\n if (sent) sent.keyed = true;\n const k = await post({ op, room, ...fields, ...await keyFields(room, op, mk), ...await authFor(room), ...await attestFor(room) });\n if (k && k.status === 200) keyedOk.add(room);\n return k;\n };\n if (mk && (proveKey || gatedRooms.has(room) && (enclaveFor(room) || keyFirstNow(room)))) return keyed();\n const r = await post({ op, room, ...fields, ...await authFor(room), ...await attestFor(room, op, fields) });\n notePass(room, r);\n if (!enclaveFor(room)) noteTier(room, r);\n if (!mk) return r;\n if (gatedRefusal(r)) {\n if (gatedRooms.has(room) && keyedOk.has(room)) keyFirst.set(room, Date.now() + KEY_FIRST_MS);\n gatedRooms.add(room);\n return keyed();\n }\n if (r && (r.status === 403 || r.status === 200) && r.error === \"not_authorized\") {\n gatedRooms.add(room);\n return keyed();\n }\n return r;\n };\n const keyedOk = /* @__PURE__ */ new Set();\n const keyFirst = /* @__PURE__ */ new Map();\n const KEY_FIRST_MS = 10 * 6e4;\n const keyFirstNow = (room) => {\n const t = keyFirst.get(room);\n return t === Infinity || typeof t === \"number\" && Date.now() < t;\n };\n const verifiedRefusal = (r) => !!(r && r.error === \"no_verified_client\" && (r.status === 403 || r.status === 200));\n const verifiedRooms = /* @__PURE__ */ new Set();\n const attestReadRooms = /* @__PURE__ */ new Map();\n const attestReadWhy = /* @__PURE__ */ new Map();\n const takeReadWhy = (room) => {\n const w = attestReadWhy.get(room);\n attestReadWhy.delete(room);\n return w;\n };\n const attPasses = /* @__PURE__ */ new Map();\n const PASS_USE_MS = 1e5;\n const PASS_OPS = /* @__PURE__ */ new Set([\"poll\", \"pollsealed\", \"blob\", \"pending\"]);\n const passFor = (room, op, body) => {\n const p = attPasses.get(room);\n if (!p || !attestReadRooms.has(room) || Date.now() - p.at > PASS_USE_MS) return null;\n return PASS_OPS.has(op) || op === \"state\" && (!body || body.patch === void 0) ? { readAttestation: { pass: p.pass } } : null;\n };\n const notePass = (room, r) => {\n if (!room || !r) return;\n if (typeof r.attPass === \"string\" && r.attPass) attPasses.set(room, { pass: r.attPass, at: Date.now() });\n else if (r.error === \"attest_required\" && /^attestation: (pass |missing)/.test(String(r.reason || \"\"))) attPasses.delete(room);\n };\n const noteReadChal = (room, r) => {\n if (attestReadRooms.has(room) && r && typeof r.challenge === \"string\" && r.challenge) attestReadRooms.set(room, r.challenge);\n };\n const attestFor = async (room, op = \"\", body = null) => {\n if (attestReadRooms.has(room)) {\n const pass = op ? passFor(room, op, body) : null;\n if (pass) return pass;\n try {\n const p = readAttestProvider();\n const why = takeReadWhy(room);\n const att = p ? await p(room, { read: true, challenge: attestReadRooms.get(room), ...why ? { refused: why } : {} }) : null;\n return att && att.read ? { readAttestation: att.read } : {};\n } catch {\n return {};\n }\n }\n if (!verifiedRooms.has(room)) return {};\n try {\n const p = attestProvider();\n const att = p ? await p(room) : null;\n return att ? { clientAttestation: att } : {};\n } catch {\n return {};\n }\n };\n const withVerified = async (room, doPost) => {\n let r = await doPost();\n notePass(room, r);\n if (verifiedRefusal(r) && !verifiedRooms.has(room)) {\n verifiedRooms.add(room);\n r = await doPost();\n notePass(room, r);\n }\n if (r && r.error === \"attest_required\" && typeof r.challenge === \"string\") {\n attestReadRooms.set(room, r.challenge);\n if (r.reason) attestReadWhy.set(room, String(r.reason));\n r = await doPost();\n }\n notePass(room, r);\n noteReadChal(room, r);\n return r;\n };\n const chains = /* @__PURE__ */ new Map();\n const chainFor = async (room, mk, requireKnown = false) => {\n const k = room + \"|\" + await commit(mk);\n if (chains.has(k)) return chains.get(k);\n let keys = [], known = false;\n try {\n const r = await policyPost(room, mk);\n const cfg = r && r.status === 200 && r.configSealed ? JSON.parse(await open(JSON.parse(r.configSealed), { mk }) || \"null\") : null;\n if (cfg && typeof cfg === \"object\") {\n known = true;\n if (Array.isArray(cfg.keyChain)) keys = cfg.keyChain.filter((x) => x && typeof x.key === \"string\" && x.key && x.key !== mk).map((x) => x.key).reverse();\n }\n } catch {\n keys = [];\n }\n if (known) chains.set(k, keys);\n return known || !requireKnown ? keys : null;\n };\n const openAny = async (room, env, mk, aad = null) => {\n const pt = await open(env, { mk, aad });\n if (pt != null || !room || !mk) return pt;\n for (const k of await chainFor(room, mk)) {\n const o = await open(env, { mk: k, aad });\n if (o != null) return o;\n }\n return null;\n };\n const editField = (opts) => opts && typeof opts.sinceEdit === \"string\" && opts.sinceEdit.length <= 64 ? { sinceEdit: opts.sinceEdit } : {};\n const decodeSealed = async (room, mk, sinceCount, r) => {\n const withPartial = async (o) => {\n let out = o || {};\n if (Array.isArray(r.removed)) out = { ...out, removed: r.removed.filter((x) => x && x.id != null && x.ts != null).slice(0, 500).map((x) => ({ id: String(x.id), ts: Number(x.ts) })) };\n if (typeof r.partial === \"string\") {\n try {\n out = { ...out, partialText: await open(JSON.parse(r.partial), { mk }), partialSeq: r.partialSeq || 0 };\n } catch {\n }\n }\n out = await withTurnStatus(out, r, mk);\n out = await withStreamGrants(out, r, mk);\n if (typeof r.deviceCall === \"string\") {\n try {\n out = { ...out, deviceCall: JSON.parse(await open(JSON.parse(r.deviceCall), { mk })), deviceCallSeq: r.deviceCallSeq || 0 };\n } catch {\n }\n }\n return out;\n };\n if (r.status !== 200 || !r.changed) return await withPartial(r);\n let wrap = null;\n try {\n wrap = JSON.parse(r.sealed);\n } catch {\n wrap = null;\n }\n if (wrap && wrap.v === 3 && Array.isArray(wrap.boxes)) {\n const entries = [];\n const base = Number.isInteger(wrap.from) ? wrap.from : sinceCount;\n let unopenable = 0;\n for (let j = 0; j < wrap.boxes.length; j++) {\n try {\n const pt = await openAny(room, JSON.parse(wrap.boxes[j]), mk, ledgerAad(room, base + j));\n if (pt == null) {\n unopenable++;\n continue;\n }\n entries.push(JSON.parse(pt));\n } catch {\n unopenable++;\n }\n }\n if (wrap.boxes.length && !entries.length && unopenable === wrap.boxes.length) return await withPartial({ status: 422, etag: r.etag, changed: true, reason: \"undecodable\", boxes: wrap.boxes.length, challenge: r.challenge });\n const total = Number.isInteger(r.count) ? r.count : sinceCount + entries.length;\n let edits;\n if (r.edits && typeof r.edits === \"object\" && typeof r.edits.tag === \"string\") {\n const got = [], have = /* @__PURE__ */ new Set();\n for (const pair of Array.isArray(r.edits.boxes) ? r.edits.boxes : []) {\n const i = Array.isArray(pair) ? pair[0] : null;\n if (!Number.isInteger(i) || typeof pair[1] !== \"string\") continue;\n try {\n const pt = await openAny(room, JSON.parse(pair[1]), mk, ledgerAad(room, i));\n if (pt != null) {\n got.push(JSON.parse(pt));\n have.add(i);\n }\n } catch {\n }\n }\n const missing = (Array.isArray(r.edits.at) ? r.edits.at : []).filter((i) => Number.isInteger(i) && !have.has(i));\n edits = { since: typeof r.edits.since === \"string\" ? r.edits.since : void 0, tag: r.edits.tag, entries: got, missing, ...r.edits.lost === true ? { lost: true } : {} };\n }\n return await withPartial({ status: 200, etag: r.etag, changed: true, version: total, entries, ...r.more ? { more: true, ...Number.isInteger(r.total) ? { total: r.total } : {} } : {}, challenge: r.challenge, done: r.done, partial: r.partial, partialSeq: r.partialSeq, boxes: wrap.boxes.length, ...unopenable ? { refused: unopenable } : {}, ...edits ? { edits } : {} });\n }\n let all = null;\n try {\n all = JSON.parse(await openAny(room, JSON.parse(r.sealed), mk));\n } catch {\n all = null;\n }\n if (all && !Array.isArray(all) && Array.isArray(all.entries)) all = all.entries;\n if (!Array.isArray(all)) return { status: 422, etag: r.etag, changed: true, reason: \"undecodable\", challenge: r.challenge };\n const from = Number.isInteger(sinceCount) && sinceCount > 0 ? Math.min(sinceCount, all.length) : 0;\n return await withPartial({ status: 200, etag: r.etag, changed: true, version: all.length, entries: all.slice(from), challenge: r.challenge, partial: r.partial, partialSeq: r.partialSeq });\n };\n const archiveAttachments = async (room, mk, ledger, budget) => {\n const blobs = {}, stats = { total: 0, included: 0, tooLarge: 0, failed: 0, bytes: 0 };\n let entries = [];\n if (ledger && ledger.v === 3 && Array.isArray(ledger.boxes)) {\n const base = Number(ledger.from) || 0;\n for (let j = 0; j < ledger.boxes.length; j++) {\n try {\n const box = ledger.boxes[j], pt = await openAny(room, typeof box === \"string\" ? JSON.parse(box) : box, mk, ledgerAad(room, base + j));\n if (pt != null) entries.push(JSON.parse(pt));\n } catch {\n }\n }\n } else {\n try {\n let all = JSON.parse(await openAny(room, ledger, mk));\n if (all && !Array.isArray(all)) all = all.entries;\n if (Array.isArray(all)) entries = all;\n } catch {\n entries = [];\n }\n }\n const seen = /* @__PURE__ */ new Set(), list = [];\n for (const e of entries) {\n for (const k of [\"images\", \"files\"]) {\n for (const a of e && Array.isArray(e[k]) ? e[k] : []) {\n if (!a || typeof a.b64 === \"string\" && a.b64) continue;\n const refs = Array.isArray(a.parts) && a.parts.length ? a.parts : typeof a.ref === \"string\" && a.ref ? [a.ref] : [];\n if (!refs.length || refs.some((x) => typeof x !== \"string\" || !x)) continue;\n const id = refs.join(\" \");\n if (seen.has(id)) continue;\n seen.add(id);\n list.push({ refs, size: Number(a.size) || 0 });\n }\n }\n }\n stats.total = list.length;\n for (const { refs, size } of list) {\n if (size > 0 && stats.bytes + Math.ceil(size * 4 / 3) > budget) {\n stats.tooLarge++;\n continue;\n }\n const got = [];\n let n = 0, failed = false;\n for (const ref of refs) {\n let r = null;\n try {\n r = await withVerified(room, async () => sealedRead(room, mk, \"blob\", { ref }));\n } catch {\n r = null;\n }\n if (!r || r.status !== 200 || r.sealed == null) {\n failed = true;\n break;\n }\n got.push([ref, r.sealed]);\n n += (typeof r.sealed === \"string\" ? r.sealed : JSON.stringify(r.sealed)).length;\n }\n if (failed) {\n stats.failed++;\n continue;\n }\n if (stats.bytes + n > budget) {\n stats.tooLarge++;\n continue;\n }\n for (const [ref, sealed] of got) blobs[ref] = sealed;\n stats.bytes += n;\n stats.included++;\n }\n return { blobs, stats };\n };\n const api = {\n _openAny: openAny,\n // internal: a box opened with the room's key or, after an in-place change, an earlier one (tests)\n /** Mint a Space from a config, register its PUBLIC record (commit + config) with the server, and return\n * { room, mk, commit, links, keyModel }. `mk` is reconstructed locally from the minted pieces — it is NEVER sent\n * to the server (only its commitment is). The `links` are what you hand to members. */\n async create(config = {}, { base = originBase(), gk, enclave: enclaveOpt, split = false, via = null, lapseDays } = {}) {\n const space = await createConfiguredSpace(config, { base });\n const mk = await mkFromLinks(space.links, config, space.commit);\n if (config && config.admission === \"email\" && config.allow) {\n const a = config.allow;\n const dom = Array.isArray(a.domains) ? a.domains.filter(Boolean) : [];\n const handles = (Array.isArray(a.handles) ? a.handles : []).filter((h) => typeof h === \"string\" && h);\n const hashOf = async (list) => {\n const mh2 = [];\n for (const em of list || []) {\n const h = await memberHash(em, space.room);\n if (h && !mh2.includes(h)) mh2.push(h);\n }\n return mh2;\n };\n const shown = Array.isArray(a.hidden) ? (Array.isArray(a.emails) ? a.emails : []).filter(Boolean) : [];\n const toHash = [...Array.isArray(a.hidden) ? a.hidden : Array.isArray(a.emails) ? a.emails : [], ...handles];\n const mh = await hashOf(toHash);\n for (const u of Array.isArray(a.tagUsers) ? a.tagUsers : []) {\n const r2 = await post({ op: \"user\", mode: \"tag\", username: u, room: space.room });\n if (!r2 || r2.status !== 200 || typeof r2.tag !== \"string\" || !r2.tag) throw Object.assign(new Error(\"@\" + u + \" could not be added (\" + (r2 && (r2.error || r2.status) || \"no answer\") + \")\"), { status: r2 && r2.status || 0, code: \"user_tag\" });\n if (!mh.includes(r2.tag)) mh.push(r2.tag);\n }\n if (shown.length || mh.length || dom.length) config = { ...config, allow: { ...shown.length ? { emails: shown } : {}, ...mh.length ? { mh } : {}, ...dom.length ? { domains: dom } : {} } };\n }\n let ownerFields = {};\n if (config && (config.requireApp === \"served\" || config.requireApp === \"emulated\" || typeof config.ownerFor === \"function\")) throw Object.assign(new Error(\"a Space only a web page served as an app may use is retired — attested Spaces are made in the Witbitz app on iPhone, Android or Mac\"), { status: 410, code: \"level_retired\" });\n if (config && (config.requireApp === \"android\" || config.requireApp === \"app\" || config.requireApp === \"windows\")) {\n const g = await post({ op: \"owner-policy\", room: space.room, level: config.requireApp });\n if (!g || g.status !== 200 || !g.ownerPolicy || !g.roomAuth) throw Object.assign(new Error(\"the Witbitz app requirement could not be set (\" + (g && (g.error || g.status) || \"no answer\") + \")\"), { status: g && g.status || 503 });\n const { requireApp: _r, requireAppId: _ra, attestAccept: acc, ...rest } = config;\n config = { ...rest, ownerPolicy: g.ownerPolicy };\n ownerFields = { ownerPolicy: g.ownerPolicy, roomAuth: g.roomAuth, ...acc ? { attestAccept: acc } : {} };\n }\n const configSealed = await sealConfig(config, mk);\n const sp = split ? splitKey(mk) : null;\n const send = typeof via === \"function\" ? via : post;\n const dc = typeof delCommit === \"function\" ? await delCommit(space.room).catch(() => null) : null;\n const r = await send({ op: \"create\", ...app ? { app } : {}, room: space.room, commit: space.commit, configSealed, invite: invitePad(), ...Number.isInteger(lapseDays) && lapseDays >= 1 && lapseDays <= 7 ? { lapseDays } : {}, ...ownerFields, ...dc ? { delCommit: dc } : {}, ...sp ? { appShare: sp.shareB } : {}, ...embedAttribution(), ...tenantHint, ...config.admission === \"email\" ? { gated: true } : {}, ...config.requireVerifiedClient ? { requireVerifiedClient: true } : {}, ...gk ? { gk } : {}, ...enclaveOpt ? { enclave: true } : {}, ...config.help === true && config.install === true ? { installHelp: true } : {} });\n if (r.status !== 200) throw Object.assign(new Error(`create failed: ${r.status} ${r.error || \"\"}${r.reason ? \" — \" + r.reason : \"\"}`), { status: r.status, ...r.error ? { code: String(r.error) } : {}, ...r.reason ? { reason: r.reason } : {} });\n if (config.admission === \"email\") {\n gatedRooms.add(space.room);\n if (config.ownerPolicy) keyFirst.set(space.room, Infinity);\n }\n if (config.requireVerifiedClient) verifiedRooms.add(space.room);\n return { room: space.room, mk, commit: space.commit, links: space.links, keyModel: space.keyModel, configSealed, ...sp ? { userShare: sp.shareA } : {}, ...enclaveOpt && r.created === true ? { enclaveCreated: true } : {} };\n },\n /** The app half of a SPLIT room, for a page on an origin the room's tenant declared (op:'appshare-page'). → { status, appShare, commit } */\n appSharePage: async (room) => post({ op: \"appshare-page\", room }),\n /** Open a Space from the member link(s) this client actually holds → { room, mk }. `mk` is null below the key\n * threshold (e.g. one partner's link alone in a 2-of-2 Space — the other share must be combined first). */\n async open(links, config = {}, commit2) {\n const arr = Array.isArray(links) ? links : [links];\n const room = parseConfiguredLink(arr[0] || \"\").room;\n if (config && config.admission === \"email\" && room) gatedRooms.add(room);\n return { room, mk: await mkFromLinks(arr, config, commit2) };\n },\n // ── 2-of-2 (couple), async code-sealed handshake ──────────────────────────────────────────────────────────────\n /** Create a 2-of-2 Space. Returns { room, mk, partnerLink, code, commit }. The creator holds `mk`; hand the partner\n * `partnerLink` (their share) + `code` (out of band). shareA is SEALED under the code and registered as the room's\n * invite — the server only ever stores ciphertext. */\n async createCouple(config = {}, { base = originBase(), gk } = {}) {\n const cfg = { ...config, keyModel: \"2-of-2\" };\n const space = await createConfiguredSpace(cfg, { base });\n const shareA = parseConfiguredLink(space.links[0]).share;\n const partnerLink = space.links[1];\n const code = newCode();\n const invite = await sealUnderCode(shareA, code);\n const mk = await assembleConfiguredKey([shareA, parseConfiguredLink(partnerLink).share], cfg, space.commit);\n const r = await post({ op: \"create\", ...app ? { app } : {}, ...tenantHint, room: space.room, commit: space.commit, invite, configSealed: await sealConfig(config, mk), ...gk ? { gk } : {} });\n if (r.status !== 200) throw Object.assign(new Error(`create failed: ${r.status} ${r.error || \"\"}${r.reason ? \" — \" + r.reason : \"\"}`), { status: r.status, ...r.error ? { code: String(r.error) } : {}, ...r.reason ? { reason: r.reason } : {} });\n return { room: space.room, mk, partnerLink, code, commit: space.commit };\n },\n /** Join a 2-of-2 Space from a partner's share-link + the code → { room, mk }. Fetches the sealed shareA, unseals it\n * with the code, and combines with this link's share. `mk` is null on a wrong code or a commitment mismatch. */\n async joinWithCode(link, code) {\n const p = parseConfiguredLink(link);\n if (!p.room || !p.share) return { room: p.room || \"\", mk: null, error: \"bad_link\" };\n const r = await post({ op: \"invite\", room: p.room });\n if (r.status !== 200 || !r.invite) return { room: p.room, mk: null, error: \"no_invite\" };\n const shareA = await openUnderCode(r.invite, code);\n if (!shareA) return { room: p.room, mk: null, error: \"bad_code\" };\n const mk = await assembleConfiguredKey([shareA, p.share], { keyModel: \"2-of-2\" }, r.mkCommit);\n return { room: p.room, mk, error: mk ? void 0 : \"mismatch\" };\n },\n /** Post a turn. `identity` SIGNS it (the entry is signed over its core; the server verifies in-render). Two shapes:\n * • EMAIL gate: `{ email, sign:{priv,pub}, googleIdToken }` → sends `{ from:email, ts, id, kind, sig, spk, idToken }`.\n * The Google token proves the email (bound to `spk` via its nonce); the server checks it against the sealed\n * allow-list and DISCARDS it.\n * • INVITE gate: `{ name, sign:{priv}, grant }` → sends `{ from:name, ts, id, kind, sig, grant }` (Kibitz invite).\n * • ATTESTED-ROOM KEY: `{ name, sign:{priv,pub}, attestKey:true }` → sends `{ from:name, ts, id, kind, sig, spk }` — a\n * member who joined an attested room through its box holds no grant; the server checks the signature against `spk`.\n * Omit `identity` → an unsigned turn (open/legacy rooms), unchanged.\n * `bridgeMk` (private-lane turns only, docs/spaces-private-lane.md): the SHARED room's key, so the runtime can\n * fold the shared negotiation into the agent's context (it OBSERVES the shared room). Ignored by normal rooms. */\n // ONE SIGN-IN PER TURN (2026-11-21): a lane's turn whose message carries its own sign-in sends no second one for the Space it\n // reads (otherAuth) — the server checks the shared room with the message's (spaceService otherRoomAdmits: req.idToken ||\n // m.idToken), and the room pass's psig binds ONE sign-in key: with two (one per room) it covered the top-level one while the\n // turn was checked with the message's, and every first message in a private assistant of a verified group was refused\n // `pass: psig_signature` (\"Your sign-in expired\").\n async turn(room, mk, message, identity2, { bridgeMk, bridgeRoom, viewSource, mode, links, context, instructions, clientTools, clientGuidance, call: call2, stopKey, model, receipt, showPrompt, run, schema } = {}, billingToken) {\n let m = message;\n const text = String(message && message.text || \"\");\n if (identity2 && identity2.googleIdToken && identity2.sign && identity2.sign.priv && identity2.sign.pub) {\n const ts = Date.now();\n const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`;\n const author = message && typeof message.from === \"string\" && message.from.trim() ? message.from : identity2.email;\n const { sig } = await signEntry(identity2.sign.priv, { room, author, ts, kind: \"text\", id, text, ...message && message.chal ? { chal: message.chal } : {} });\n m = { ...message, from: author, ts, id, kind: \"text\", sig, spk: identity2.sign.pub, idToken: identity2.googleIdToken };\n } else if (identity2 && identity2.grant && identity2.sign && identity2.sign.priv) {\n const ts = Date.now();\n const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`;\n const { sig } = await signEntry(identity2.sign.priv, { room, author: identity2.name, ts, kind: \"text\", id, text, ...message && message.chal ? { chal: message.chal } : {} });\n m = { ...message, from: identity2.name, ts, id, kind: \"text\", sig, grant: identity2.grant };\n } else if (identity2 && identity2.attestKey === true && identity2.sign && identity2.sign.priv && identity2.sign.pub) {\n const ts = Date.now();\n const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`;\n const { sig } = await signEntry(identity2.sign.priv, { room, author: identity2.name, ts, kind: \"text\", id, text, ...message && message.chal ? { chal: message.chal } : {} });\n m = { ...message, from: identity2.name, ts, id, kind: \"text\", sig, spk: identity2.sign.pub };\n }\n return post({ op: \"turn\", room, ...await keyFields(room, \"turn\", mk), message: m, ...viewSource ? { viewSource } : {}, ...pushSelf() ? { pushSelf: pushSelf() } : {}, ...await pushAcctField(room), ...await crossingPush(bridgeRoom), ...bridgeMk ? await bridgeFields(room, \"turn\", bridgeMk) : {}, ...bridgeRoom ? { bridgeRoom } : {}, ...m && m.idToken ? {} : await otherAuth([bridgeRoom, ...Array.isArray(links) ? links.map((l) => l && l.room) : []]), ...mode ? { mode } : {}, ...Array.isArray(links) && links.length ? await linksFields(room, \"turn\", links) : {}, ...context ? { context } : {}, ...instructions ? { instructions: String(instructions) } : {}, ...Array.isArray(clientTools) && clientTools.length ? { clientTools } : {}, ...clientGuidance ? { clientGuidance } : {}, ...call2 ? { call: 1 } : {}, ...stopKey ? { stopKey } : {}, ...model ? { model } : {}, ...receipt && receipt.drop ? { receipt } : {}, ...showPrompt === true ? { showPrompt: true } : {}, ...run === true ? { run: true } : {}, ...run === true && schema ? { schema } : {} }, billingToken);\n },\n // USAGE RECEIPTS (docs/usage-receipts.md): this account's sealed receipts in a room, at its per-room drop, and the trim\n // once they are folded into the account's sidecar. Keyless: the drop is the capability; every box is sealed to us.\n receipts: async (room, drop, since = 0) => post({ op: \"receipts\", room, drop, sinceCount: since }),\n receiptsAck: async (room, drop, upTo) => post({ op: \"receiptsack\", room, drop, upTo }),\n // STRAY NOTIFICATIONS (strayPush.js, agent/pushDrop.mjs): this device has no key for the room; ask for its own push\n // address to come off the room's list. Keyless — the address is the capability, and only its hash is kept.\n pushDrop: async (room, subscription) => post({ op: \"pushdrop\", room, subscription: { endpoint: subscription && subscription.endpoint } }),\n // MEMBERSHIP MARK (docs/user-erasure.md § Authority): this account opened the room — a creator's delete then sees it was shared\n mark: async (room, mk, drop) => post({ op: \"mark\", room, ...await keyFields(room, \"mark\", mk), drop, ...await authFor(room) }),\n /** LEAVE A VERIFIED ROOM (agent/roomLeave.mjs): hands over this account's marks ({drops}) and delete secrets ({dels}) → { status, left, last, drops?, dels? } — `last`: no one who joined is left, delete it with what came back. */\n leave: async (room, mk, leave) => post({ op: \"leave\", room, ...await keyFields(room, \"leave\", mk), leave: { drops: [...leave && leave.drops || []].slice(0, 16), dels: [...leave && leave.dels || []].slice(0, 8) }, ...await authFor(room) }),\n // Seed the Space from a PUBLIC ChatGPT share link → continue a one-on-one chat together. The Lambda fetches +\n // parses it (SSRF-guarded) and seals the history into the ledger; the URL is public so this carries no secret.\n importChat: async (room, mk, chatgptUrl, billingToken) => post({ op: \"import\", room, ...await keyFields(room, \"import\", mk), chatgptUrl, ...await authFor(room) }, billingToken),\n // `hints` { tz, order }: the client's time zone (getTimezoneOffset) and date order — each message keeps its own WhatsApp time (side\n // sweep: sdk-whatsapp-import-restamps-message-times); an older server ignores them\n importWhatsApp: async (room, mk, whatsappText, billingToken, hints) => post({ op: \"import\", room, ...await keyFields(room, \"import\", mk), whatsappText, ...hints && Number.isInteger(hints.tz) ? { whatsappTz: hints.tz } : {}, ...hints && typeof hints.zone === \"string\" && /^[A-Za-z0-9_+\\-/]{1,64}$/.test(hints.zone) ? { whatsappZone: hints.zone } : {}, ...hints && (hints.order === \"mdy\" || hints.order === \"dmy\") ? { whatsappOrder: hints.order } : {}, ...await authFor(room) }, billingToken),\n // WhatsApp export: client unzipped the _chat.txt → server parses + seals\n // MIRROR — append entries this device copied from a LINKED room (docs/spaces-private-lane.md) into THIS room's ledger,\n // no agent turn. Deduped by entry id server-side. Files/images ride along so the assistant reads them natively.\n mirror: async (room, mk, entries) => {\n const send = async (batch2) => {\n const kf = await keyFields(room, \"mirror\", mk);\n const ef = enclaveFor(room) ? await sealField(room, \"mirror:entries\", JSON.stringify(batch2), \"mirror\") : { entries: batch2 };\n return post({ op: \"mirror\", room, ...kf, ...ef, ...await authFor(room) });\n };\n const batch = entries || [];\n const prepared = await stageMirrorAttachments(batch, send);\n return prepared.error || send(prepared.entries);\n },\n // CARRY — a verified room's MOVE: the SERVER copies the old room's history into this one (minted with forkedFrom = that\n // room), keeping each entry's verified mark as `carried` (agent/spaceService.mjs op 'carry'). One page per call → { carried,\n // next, total }; loop while `next` is a number. The old room's key rides like a lane's bridge key: sealed to the\n // enclave on a confidential room (AAD op 'carry:bridge'), and filled in by the room worker when only bridgeRoom is given.\n carry: async (room, mk, { bridgeRoom, bridgeMk, cursor = 0 } = {}) => post({ op: \"carry\", room, ...await keyFields(room, \"carry\", mk), ...bridgeMk ? await bridgeFields(room, \"carry\", bridgeMk) : {}, bridgeRoom, ...Number.isInteger(cursor) && cursor > 0 ? { sinceCount: cursor } : {}, ...await authFor(room) }),\n // Generate (or fetch) a real one-line conversation title, sealed to the room so both members share it.\n // `set` = { title, by }: a member RENAMES the room — the server appends it to the room's log (spaces/public/roomName.js).\n title: async (room, mk, recheck, set, billingToken) => post({ op: \"title\", room, ...await keyFields(room, \"title\", mk), ...recheck ? { recheck: true } : {}, ...set && set.title ? { set: String(set.title), ...set.by ? { by: String(set.by).slice(0, 80) } : {}, ...pushSelf() ? { pushSelf: pushSelf() } : {}, ...await pushAcctField(room) } : {}, ...await authFor(room) }, billingToken),\n // The DEFAULT loop. Opens the in-progress reply the same way pollSealed does — the server passes it through\n // sealed on both paths, so the two stay drop-in interchangeable mid-session.\n decodeSealed,\n poll: async (room, mk, sinceEtag, sinceCount = 0, opts = {}) => {\n const ci = opts && typeof opts.changeInbox === \"string\" ? { changeInbox: opts.changeInbox } : {};\n const ed = editField(opts);\n if (enclaveFor(room)) return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, ...ed });\n return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, ...ed, proveKey: !!ci.changeInbox });\n },\n /** CONTENT-BLIND poll — the same contract as `poll`, but `mk` NEVER leaves this device. The server returns the\n * sealed ledger and we open it here, so the hot loop (a poll every ~600ms while the Space is on screen) stops\n * carrying the room key; only `turn` still does, because the agent genuinely needs plaintext.\n * Returns the IDENTICAL shape to `poll` — { status, etag, changed, version, entries } — so it is a drop-in swap\n * and the caller's render path is unchanged. A key that doesn't fit surfaces as the same 422/'undecodable' the\n * server used to return, except now the CLIENT proves it rather than being told. */\n async pollSealed(room, mk, sinceEtag, sinceCount = 0, opts = {}) {\n const ci = opts && typeof opts.changeInbox === \"string\" ? { changeInbox: opts.changeInbox } : {};\n const sent = { keyed: false };\n const send = async () => sealedRead(room, mk, \"pollsealed\", { sinceEtag, sinceCount, ...ci, ...editField(opts) }, { proveKey: !!(opts && opts.proveKey && mk && !enclaveFor(room)), sent });\n const r = await withVerified(room, send);\n const out = await decodeSealed(room, mk, sinceCount, r);\n if (out && out.status === 422 && out.reason === \"undecodable\" && mk && !sent.keyed) {\n const r2 = await withVerified(room, async () => sealedRead(room, mk, \"pollsealed\", { sinceEtag, sinceCount, ...ci, ...editField(opts) }, { proveKey: true }));\n return decodeSealed(room, mk, sinceCount, r2);\n }\n return out;\n },\n // Full SEALED ledger (ciphertext) for a durable LOCAL backup — the raw stored blob (v1/v2 whole, or the v3\n // { v:3, boxes:[…] } wrapper), NOT opened here. sinceCount:0 ⇒ everything. Same gated-retry as pollSealed. The\n // downloaded file carries no plaintext — it is only readable with the room key, via the offline decryptor\n // (/decrypt.html). Returns { status, sealed, count, etag }.\n // `opts.attachments = { budget }` (bytes, > 0): the OFFLINE COPY also carries the attachments stored out of line\n // (agent/attachmentBlobs.mjs) — their sealed envelopes exactly as stored, under `blobs` beside the boxes, up to `budget`;\n // the answer's `attachments` says how many went in and how many were left out (archiveAttachments below). Without it the\n // answer is unchanged — sealedProof hashes it (witbitz-sdk.js receipt).\n exportSealed: async (room, mk, opts = {}) => {\n const archive = await readSealedArchive((sinceCount) => withVerified(room, () => sealedRead(room, mk, \"pollsealed\", { sinceCount })));\n if (archive?.status !== 200 || !archive.sealed) return archive;\n const ledger = JSON.parse(archive.sealed);\n if (ledger.v === 3 && Array.isArray(ledger.boxes)) {\n const previous = await chainFor(room, mk, true);\n if (!previous) {\n for (const [index, item] of ledger.boxes.entries()) {\n let box;\n try {\n box = typeof item === \"string\" ? JSON.parse(item) : item;\n } catch {\n }\n if (await open(box, { mk, aad: ledgerAad(room, (ledger.from || 0) + index) }) == null) return { status: 409, error: \"archive_incomplete\" };\n }\n }\n if (previous?.length) ledger.keyHistory = await seal(JSON.stringify({ room, keys: previous }), { room: mk });\n }\n const budget = Number(opts && opts.attachments && opts.attachments.budget);\n if (!(budget > 0)) return { ...archive, sealed: JSON.stringify(ledger) };\n const { blobs, stats } = await archiveAttachments(room, mk, ledger, budget);\n if (Object.keys(blobs).length) ledger.blobs = blobs;\n return { ...archive, sealed: JSON.stringify(ledger), attachments: stats };\n },\n pending: async (room, mk) => post({ op: \"pending\", room, ...await keyFields(room, \"pending\", mk), ...await authFor(room) }),\n /** APPROVAL REMINDERS for Code (agent/approvalRemind.mjs): this device's push address, signed by the server, for the\n * computer to name when an approval waits there → { status, grant }. `endpointUrl` = where the computer sends it. */\n /** OPTION B: fetch this sign-in's hints ahead of need (at sign-in, on launch), so the fetch is not tied to a room request. */\n prefetchIdentity: async (idToken) => {\n try {\n if (typeof idToken === \"string\" && idToken) await extrasFor(idToken);\n } catch {\n }\n },\n remindGrant: async (subscription, others) => post({ op: \"remindgrant\", subscription, ...Array.isArray(others) && others.length ? { subscriptions: others.slice(0, 16) } : {} }),\n // others: the account's other devices (approvalRemind.makeGrant)\n endpointUrl: () => {\n try {\n return new URL(endpoint, typeof location !== \"undefined\" ? location.href : void 0).href;\n } catch {\n return \"\";\n }\n },\n /** Fetch an OUT-OF-LINE image blob by its ledger pointer and open it here → { status, b64, mime }.\n * The request carries no key (the bytes are sealed; serving ciphertext reveals nothing) — `mk` is used locally to\n * open the envelope, exactly like pollSealed. Blobs are content-addressed and immutable, so a caller may cache the\n * result against `ref` forever without revalidating. */\n /** A connection's TOOL BOOK (agent/toolBook.mjs): its full tool list sealed once into the room → { status, ref, sha256, n }. */\n // carries the member's sign-in like setConfig (authFor): a verified Space refuses it without — the app then saved the whole list (2026-11-17)\n /** THE ROOM'S TOOLS for its ⋯ → Tools sheet (agent/spaceService.mjs op toolrules; toolRules.js) → { status, tools: [{ name, about,\n * default, now, rule? }], rules }. The rules themselves are written with state(…, 'toolrules', …). */\n toolRules: async (room, mk, { bridgeRoom, bridgeMk } = {}) => post({\n op: \"toolrules\",\n room,\n ...await keyFields(room, \"toolrules\", mk),\n ...bridgeRoom ? { bridgeRoom, ...bridgeMk ? await bridgeFields(room, \"toolrules\", bridgeMk) : {} } : {},\n ...await otherAuth([bridgeRoom]),\n ...await authFor(room)\n }),\n toolBook: async (room, mk, tools) => post({ op: \"toolbook\", room, ...await keyFields(room, \"toolbook\", mk), toolbook: { tools: Array.isArray(tools) ? tools.slice(0, 400) : [] }, ...await authFor(room) }),\n async blob(room, mk, ref) {\n const r = await withVerified(room, async () => sealedRead(room, mk, \"blob\", { ref }));\n if (r.status !== 200 || !r.sealed) return r;\n try {\n const o = JSON.parse(await openAny(room, r.sealed, mk));\n if (!o || typeof o.b64 !== \"string\") return { status: 422, reason: \"undecodable\" };\n return { status: 200, ref, b64: o.b64, mime: o.mime || \"image/jpeg\" };\n } catch {\n return { status: 422, reason: \"undecodable\" };\n }\n },\n /** Register this device for push. The subscription is sealed into the room's doc server-side (it is room metadata:\n * which devices care about this room), so it needs mk like any other sealed write. */\n // mk goes through keyFields() like every other material op (turn/import/mirror/title/poll) — so on an ENCLAVE room it\n // is SEALED to the enclave key and the parent relay never sees the raw key (fail-closed for an enclave room with no\n // key). Default tier: keyFields is the identity function → raw {mk}, unchanged. (Was: raw mk in the body — the one\n // material op that skipped the seal, leaking the room key to the parent relay on enclave rooms. Security review #2.)\n subscribe: async (room, mk, subscription, by, quiet) => post({ op: \"subscribe\", room, ...await keyFields(room, \"subscribe\", mk), subscription, by, ...await pushAcctField(room), ...quiet ? { quiet: true } : {}, ...await authFor(room) }),\n // quiet: a bulk or automatic registration — store it, no confirmation push\n /** Turn notifications off for this device. Sends the subscription so the server can drop it by endpoint. */\n unsubscribe: async (room, mk, subscription) => post({ op: \"unsubscribe\", room, ...await keyFields(room, \"unsubscribe\", mk), subscription, ...await authFor(room) }),\n // Content-blind transparency read (the \"trust receipt\"): the EXACT ciphertext the server stores for this room +\n // its recipients. No mk sent — reading ciphertext reveals nothing. → { alg, bytes, sha256, recipients, sealed }.\n sealed: async (room) => post({ op: \"sealed\", room }),\n // VERIFIED-CLIENT capability blob (spaces/public/capLink.js). vcput MINTS: store the OPAQUE {mk}-sealed-under-token\n // ciphertext under a one-way capId — mk-commit gated server-side (only an mk-holder may write it), content-blind\n // (the server sees only id + ciphertext, never the token or mk). vcget RESOLVES: fetch it, ATTESTATION-gated (the\n // gateway withholds without a fresh, approved client-release attestation); carries NO mk — the token off the ?vc=\n // link (never sent to the server with the extension) is what opens the blob, unsealed by L1 locally.\n vcput: async (room, mk, capId, capSealed) => post({ op: \"vcput\", room, capId, capSealed, ...await keyFields(room, \"vcput\", mk), ...await authFor(room) }),\n // email-gated like every keyed write\n vcget: async (room, capId, attestation) => post({ op: \"vcget\", room, capId, ...attestation ? { clientAttestation: attestation } : {} }),\n // The attested client's DEVICE enrollment (docs/the-attested-client.md § The wire; deviceAttest.js): a new hardware key's\n // platform attestation, bound to THIS room's fresh challenge and the member's signing key. Account-level — no mk.\n attestEnroll: async ({ room, chal, spk, enroll }) => post({ op: \"attest-enroll\", room, chal, ...spk ? { spk } : {}, enroll }),\n // A WINDOWS DEVICE'S ACTIVATION BY AN ENCLAVE (agent/winActivation.mjs): `to` 'turn' (confidential rooms) | 'sentinel' (the backup's\n // K_att); `start` → { activate, ticket }, `finish` (the TPM's answer + the ticket) → { ok }. The front keeps the sealed record.\n winAct: async ({ to, step, keyId, activation, ticket }) => post({ op: \"winact\", winact: { to, step, keyId, ...activation ? { activation } : {}, ...ticket ? { ticket } : {} } }),\n // \"Verify this device\" (agent/deviceVerify.mjs, docs/device-verify.md): the hardware key's signature over a CHECKER's nonce.\n // The answer is only the key code — the verdict is collected and checked by the checker, never shown here.\n // Witbitz Mail's receive prototype (agent/mailIntake.mjs): a mail address that drops into this Space's intake.\n mailRoute: async (intake, space) => post({ op: \"mail-route\", mail: { intake, space } }),\n mailRevoke: async (intake, space) => post({ op: \"mail-revoke\", mail: { intake, space } }),\n // stop receiving: the enclave ends the address (agent/mailIntake.mjs revokeOp)\n deviceVerify: async ({ platform, keyId, nonce, assertion, sig, integrity }) => post({ op: \"device-verify\", device: { platform, keyId, nonce, ...assertion ? { assertion } : {}, ...sig ? { sig } : {}, ...integrity ? { integrity } : {} } }),\n // the ATTESTED BACKUP (agent/attestedBackup.mjs): op 'attested-chal' | 'attested-get' | 'attested-put', the fields in `attested`\n attestedOp: async (op, attested, chal) => post({ op, attested, ...chal ? { chal } : {} }),\n // the record of the account's EARLIER keys beside it (agent/attestedPrev.mjs): `mode` chal | get (attested) | put (the new master's proof)\n attestedPrevOp: async (mode, prev, chal) => post({ op: \"attested-prev\", prev: { ...prev || {}, mode }, ...chal ? { chal } : {} }),\n // K_att (infra/cloud-computer/sentinel/attkey.mjs): `mode` chal | get — the standing Sentinel's challenge, then the secret sealed to\n // the device's one-time key (attested.epk), after the attestation it verifies itself. The Space Lambda only relays.\n attkeyOp: async (mode, attested, chal) => post({ op: \"attkey\", ...mode === \"chal\" ? { mode: \"chal\" } : {}, attested, ...chal ? { chal } : {} }),\n // DEVICE tool result — return a client-executed tool's answer (e.g. a calendar read the agent asked for) to the\n // blocked turn. The result is SEALED HERE under mk (content-blind at rest, opened only by the turn); mk never leaves.\n // `{ claim }` instead of a result: claim the call for this device before a tool with a side effect (G#3) — no result,\n // nothing sealed; → { ok, claimed } (claimed false: another device runs it).\n toolResult: async (room, mk, callId, result, opts = {}) => {\n if (opts && opts.claim) return post({ op: \"toolresult\", room, callId, toolClaim: String(opts.claim) });\n const resBox = JSON.stringify(await seal(typeof result === \"string\" ? result : JSON.stringify(result), { room: mk }));\n return post({ op: \"toolresult\", room, callId, resBox });\n },\n // KEEP-ALIVE (docs user-data-lifecycle): extend the idle-expiry of rooms THIS device holds. Called once per open\n // with room ids from the device's OWN recents list — no mk, no content — so the server never learns which rooms are\n // whose (the client does the fan-out; the server just pushes each `lapsesAt` out). Bounded here and again server-side;\n // best-effort by contract → a Space's life must never hinge on this succeeding. → { ok, rooms }.\n touch: async (rooms) => post({ op: \"touch\", rooms: (Array.isArray(rooms) ? rooms : [rooms]).filter((r) => typeof r === \"string\" && r).slice(0, 200) }),\n // §APP STORE Stage 2: the PUBLIC registry-backed app catalog (no room/mk/auth) → { status, apps:[…] }.\n apps: async () => post({ op: \"apps\" }),\n // The create-screen capability probe (model catalog + whether temporary Spaces are supported) — same keyless shape\n // as `apps` above, and it belongs here for the same reason: `post` is the transport that actually works everywhere.\n // The picker used to call `fetch(endpoint, …)` directly, which (a) is not the path a VAULT-framed tenant app uses,\n // so the Model row silently never appeared there while the App row — routed through here — did, and (b) bypasses\n // the OHTTP relay, so with \"Hide my IP\" on, merely opening New Space leaked the device IP to the API.\n models: async () => post({ op: \"models\" }),\n // Stop a running turn (docs/spaces-stop-turn.md). Keyless — the per-turn nonce IS the authorization — but it must\n // still go through `post` for the same two reasons as `models`: it has to work in a vault-framed tenant app, and a\n // direct fetch would step outside the OHTTP relay (leaking the IP on the very op that says \"stop reading me\").\n stop: async (room, key) => post({ op: \"stop\", room, key }),\n // Tier-2 server-blind email invites (docs/spaces-email-invite.md) — identity-plane, no room/mk.\n // oprf: evaluate a blinded point → { z, proof, kpub } (the client verifies the DLEQ + unblinds to a handle).\n // dirGet: public lookup of a handle → { entry:{ boxPub, inbox } } or 404. dirPut: publish/rotate this user's own\n // slot, authenticated by the email-login idToken (the server checks OPRF(email)==handle so nobody can squat a slot).\n oprf: async (blinded) => post({ op: \"oprf\", blinded }),\n // dirGet: public lookup of a handle → { entry:{ boxPub, inbox } } or 404. A member who closed the EMAIL door (Settings →\n // \"People can find me by my email address\", off) answers 404 like an unknown address — except to THEMSELF: pass the\n // sign-in `idToken` (+ the tenant `scope`, as dirPut does) and the row answers its owner (sign-in's \"welcome back\",\n // recovery's duplicate guard). dirDiscoverable: that switch — the row is named by the token, not a handle.\n dirGet: async (handle, { idToken, scope, app: app2 } = {}) => post({ op: \"dir\", mode: \"get\", handle, ...idToken ? { idToken } : {}, ...scope ? { dirScope: scope } : {}, ...app2 ? { app: app2 } : {} }),\n // app: another slot of the account (an attested box, attestedBox.js)\n dirDiscoverable: async (discoverable, idToken, scope) => post({ op: \"dir\", mode: \"discoverable\", discoverable: discoverable !== false, idToken, ...scope ? { dirScope: scope } : {} }),\n dirPut: async (handle, entry, idToken, scope, app2) => post({ op: \"dir\", mode: \"put\", handle, entry, idToken, ...scope ? { dirScope: scope } : {}, ...app2 ? { app: app2 } : {} }),\n // dirScope: the per-tenant handle namespace — the server re-derives OPRF(scope·email) to match (else a scoped account's put is handle_mismatch)\n // USERNAMES (docs/spaces-usernames.md §4): a public \"@name\" → the account's directory HANDLE (never its email).\n // resolve is public; whoami/claim/release prove the account with the same sign-in token the directory put uses.\n userResolve: async (username, app2) => post({ op: \"user\", mode: \"resolve\", username, ...app2 ? { app: app2 } : {} }),\n // app: which of the account's slots comes back with the handle\n // A member by @username, as the room-bound TAG no guessed email can be linked to (docs/spaces-usernames.md §12)\n userTag: async (username, room) => call(endpoint, { op: \"user\", mode: \"tag\", username, room }, f),\n // a DIRECTORY op (the room is only its salt): the Lambda answers it for a room of either tier — through post() a confidential room's went to the enclave, which has no directory (sync sweep 10-21 #5)\n userWhoami: async (idToken) => post({ op: \"user\", mode: \"whoami\", idToken }),\n userAsUser: async (asUser, idToken) => extrasCache.clear() || post({ op: \"user\", mode: \"asuser\", asUser: asUser !== false, idToken }),\n // \"Add me to Spaces as @username\" (docs/spaces-usernames.md § 13); the hints carry it, so they are asked again\n userClaim: async (username, idToken, { name, publish } = {}) => extrasCache.clear() || post({ op: \"user\", mode: \"claim\", username, idToken, ...publish ? { publish: true, ...name ? { name } : {} } : {} }),\n userRelease: async (idToken, username) => extrasCache.clear() || post({ op: \"user\", mode: \"release\", idToken, ...username ? { username } : {} }),\n // username (optional): only that name — the server refuses 'changed' when the account holds another now\n dirErase: async (idToken, scope) => post({ op: \"dir\", mode: \"erase\", idToken, ...scope ? { dirScope: scope } : {} }),\n // DELETE MY ACCOUNT (docs/user-erasure.md): the token's own directory row + inboxes\n // The invite inbox: drop a sealed box into a recipient's mailbox; inboxFetch reads YOUR mailbox (openBox with boxPriv).\n drop: async (inbox, box) => post({ op: \"drop\", inbox, box }),\n inboxFetch: async (inbox, since) => post({ op: \"inbox\", inbox, ...since ? { since } : {} }),\n // \"Which of my rooms changed since `since`?\" — the change inbox, standard tier (docs/change-inbox.md). Keyless.\n changes: async (inbox, since = 0) => post({ op: \"changes\", inbox, since }),\n inboxSubscribe: async (inbox, subscription) => post({ op: \"inboxsub\", inbox, subscription }),\n // register this device for a real-time invite tickle\n // a signed-out device's address off the invite inbox's list (the endpoint alone; an older server answers 400 — never an add)\n inboxUnsubscribe: async (inbox, subscription) => post({ op: \"inboxsub\", inbox, remove: true, subscription: { endpoint: subscription && subscription.endpoint } }),\n decide: async (room, mk, id, approve, by, { bridgeMk, bridgeRoom, editText, deviceExec, recordResult } = {}, billingToken) => post({ op: \"decide\", room, ...await keyFields(room, \"decide\", mk), id, approve, by, ...await crossingPush(bridgeRoom), ...await otherAuth([bridgeRoom]), ...await authFor(room), ...bridgeMk ? await bridgeFields(room, \"decide\", bridgeMk) : {}, ...bridgeRoom ? { bridgeRoom } : {}, ...editText ? { editText } : {}, ...deviceExec ? { deviceExec } : {}, ...recordResult === false ? { recordResult: false } : {} }, billingToken),\n // editText: the approver's edit of the pending crossing // bridgeMk: approving a cross_to_shared posts into the linked shared room // deviceExec: a client-executed action (calendar write) — the server must skip its executor\n // Shared WIDGET state (co-edited by members; the agent reads its `summary` on turns). SET with a `patch` (+ a short\n // `summary`); READ with no patch → { v, state, summary }. The blob is mk-sealed server-side — never sent in clear.\n /** THE ROOM AS A STORE — write rows: ONE sealed ledger entry carrying put/delete ops, ordered by the server without\n * reading it. `ops` = [{ op:'put', collection, id?, row } | { op:'del', collection, id }]; `by` names the writer in\n * the system line every member sees. → { status, id, ops:[{op,collection,id}], text, entries } */\n // `file` (optional, ONE beside one put — a mail's attachment): { b64, mime, name } — the server stores it out of line\n // and the row's `file` field names it (agent/spaceService.mjs op data).\n data: async (room, mk, ops, by, file) => post({ op: \"data\", room, ...await keyFields(room, \"data\", mk), ops: Array.isArray(ops) ? ops.slice(0, 50) : [], ...by ? { by: String(by).slice(0, 80) } : {}, ...file && file.b64 ? { file: { b64: String(file.b64), mime: String(file.mime || \"\"), name: String(file.name || \"file\").slice(0, 120) } } : {}, ...await authFor(room) }),\n // `ifV` (optional): the version this write was built on — the server writes only if the doc is still there (409\n // version_conflict otherwise, with the current `v`), so two devices cannot silently overwrite each other.\n state: async (room, mk, name, patch, summary, by, ifV) => post({ op: \"state\", room, ...await keyFields(room, \"state\", mk), name, ...patch !== void 0 ? { patch, summary, by, ...Number.isInteger(ifV) ? { ifV } : {} } : {}, ...await authFor(room) }),\n // An emoji on one message. `react` is {target, emoji, off} — target is the entryKey the server recomputes from the\n // ledger, so a client cannot react to something that is not there. Never a turn: the assistant stays quiet.\n /** PURGE a purgeable room's handled rows (docs/room-messages.md § Retention) — `ids` = row ids no collection still\n * holds. → { status, purged, live } */\n purge: async (room, mk, ids2) => post({ op: \"purge\", room, ...await keyFields(room, \"purge\", mk), ops: Array.isArray(ids2) ? ids2.slice(0, 50).map(String) : [], ...await authFor(room) }),\n /** DELETE FORWARDED MAIL FOR REAL (agent/mailPurge.mjs): the `mail`/`mailfile` rows named — already deleted with `data` —\n * leave the ledger and their files are overwritten. Only in a solo verified Space, by its member. → { status, purged, files, live } */\n mailPurge: async (room, mk, ids2) => post({ op: \"mailpurge\", room, ...await keyFields(room, \"mailpurge\", mk), ops: Array.isArray(ids2) ? ids2.slice(0, 50).map(String) : [], ...await authFor(room) }),\n /** THE MESSAGE INTAKE (docs/message-intake.md, roomIntake.js). `intakeDrop` is a PRODUCER's call — keyless: a drop\n * token and a box sealed to the intake's public key. The rest are the account's devices (keyed). */\n intakeDrop: async (room, drop, box) => post({ op: \"intakedrop\", room, drop, box }),\n intakeReg: async (room, mk, ops) => post({ op: \"intakereg\", room, ...await keyFields(room, \"intakereg\", mk), ops: Array.isArray(ops) ? ops.slice(0, 50) : [] }),\n intakePush: async (room, mk, subscription, remove = false) => post({ op: \"intakepush\", room, ...await keyFields(room, \"intakepush\", mk), subscription, ...remove ? { remove: true } : {} }),\n // this device on the intake's wake list (messageIntake.mjs)\n intakeDeviceWake: async (room, mk, remove = false) => post({ op: \"intakepush\", room, ...await keyFields(room, \"intakepush\", mk), cloudDevice: true, ...remove ? { remove: true } : {} }),\n // the cloud device on the wake list (docs/cloud-device.md § 12)\n // `from` { drop, n }: start the read at that position (a later page past boxes that must stay — roomIntake.js collect)\n intake: async (room, mk, from) => post({ op: \"intake\", room, ...from && typeof from === \"object\" ? { from: { drop: String(from.drop), n: Number(from.n) } } : {}, ...await keyFields(room, \"intake\", mk) }),\n intakeAck: async (room, mk, items) => post({ op: \"intakeack\", room, ...await keyFields(room, \"intakeack\", mk), ops: Array.isArray(items) ? items.slice(0, 50) : [] }),\n // SAFE MEDIA (docs/safe-media.md § 5): the safe copy a device made of a photo or PDF in the room → stored beside it (agent/safeCopy.mjs)\n safeCopy: async (room, mk, safe, by) => post({ op: \"safe\", room, ...await keyFields(room, \"safe\", mk), safe, ...by ? { by: String(by).slice(0, 80) } : {}, ...await authFor(room) }),\n react: async (room, mk, react, by) => post({ op: \"react\", room, ...await keyFields(room, \"react\", mk), react, ...by ? { by: String(by).slice(0, 80) } : {}, ...await authFor(room) }),\n // OWNER RULE (docs/the-owner-rule.md) — the JOIN-flow peer check. `policyOf` fetches the room's cleartext marker +\n // sealed config (op:'policy', public). `verifyGovernance` opens the config with mk and verifies the owner-signed\n // policy against the PINNED owner key (from /space-config) — so the client trusts a governed room only if it's a\n // genuine room of that owner, not the server's word. Called only when a key is pinned (single-owner deployment);\n // the generic multi-tenant PWA passes no key ⇒ { ok:true, governed:false }.\n // op:'policy' carries the room key and the member's sign-in: an EMAIL-GATED room serves its sealed config only to an\n // allowed member (agent/spaceService.mjs, 2026-10-02) and otherwise answers just { gated: true }.\n policyOf: (room, mk) => policyPost(room, mk),\n /** Does this room require an attested app? (a refusal already said so, or op 'policy' does) → boolean. */\n // a read that FAILED throws — never 'not attested' (sync sweep 11-08: the SDK and the vault made an open lane of an attested Space on a failed read)\n // …and neither is the FRONT'S answer for a confidential room this client had not marked (sync sweep 2026-11-12 #4): a keyless ask\n // then reaches the front, which answers from its mirror row — the tier, never the enclave's `attested` mark (agent/tierGuard.mjs).\n // \"No\" from there was remembered and an ordinary lane made of an attested confidential Space. Only \"yes\", or the answer of the\n // tier the room is on, counts; the page marks the room from the tier this answer carries and the next ask goes to its enclave.\n attestedRoom: async (room, mk) => {\n if (attestReadRooms.has(room)) return true;\n const marked = enclaveFor(room);\n const r = await policyPost(room, mk);\n if (!r || r.status !== 200) throw Object.assign(new Error(\"policy read failed\" + (r && r.status ? \" (HTTP \" + r.status + \")\" : \"\")), { code: \"policy_unreadable\" });\n if (r.attested === true) return true;\n if (!marked && r.tier === \"enclave\") throw Object.assign(new Error(\"policy read: a confidential room answered by the front — its enclave was not asked\"), { code: \"policy_unreadable\" });\n return false;\n },\n /** The room's PUBLIC key commitment (op 'invite', keyless) → string | null (none) | undefined (could not ask). Lets a device\n * check a key it was handed before keeping it (emailInvites.js keyOpens). */\n roomCommit: async (room) => {\n const r = await post({ op: \"invite\", room });\n return r && r.status === 200 ? r.mkCommit || null : void 0;\n },\n // Fetch + decrypt this room's sealed agent CONFIG (persona/tools/agentName/admission/allow/agentKeys/model/…) with\n // mk → the plaintext config, or null. The config ciphertext is content-blind (sealed under mk, served by op:'policy'\n // which already returns it for governance). A membership fork uses this to carry the agent's behavior into the new\n // room (spaceFork.js) — the forking client holds the OLD mk, so it can decrypt without exposing the new key.\n // `{ plainMark: true }`: a PLAIN room (a read that worked, nothing sealed, no lanes bit) answers `{ plain: true }`, so null\n // means only that the read failed — a private lane waits on that, never inherits \"nothing\" (sync sweep 2026-11-03)\n getConfig: async (room, mk, o) => {\n const r = await policyPost(room, mk);\n if (!r || r.status !== 200 || r.error || r.ok === false) return null;\n if (!r.configSealed && r.gated === true) {\n gatedRooms.add(room);\n return { admission: \"email\", gated: true };\n }\n if (!r.configSealed) {\n const h = await healEnclaveConfig(room, mk);\n if (h) return h.cfg;\n }\n if (!r.configSealed) return typeof r.lanes === \"boolean\" ? { lanes: r.lanes } : o && o.plainMark === true ? { plain: true } : null;\n let cfg = null;\n try {\n cfg = JSON.parse(await open(JSON.parse(r.configSealed), { mk }));\n } catch {\n return null;\n }\n if (cfg && typeof cfg === \"object\" && cfg.admission === \"email\") {\n gatedRooms.add(room);\n if (cfg.ownerPolicy) keyFirst.set(room, Infinity);\n }\n return cfg;\n },\n /** Change the assistant IN PLACE — its name, instructions (persona) and model — visibly: the server appends a system\n * line to the ledger (\"⚙️ Dana changed the assistant's instructions\") that every member sees. Only those three\n * fields move; the sealed config is re-sealed WHOLE with them applied, so tools, admission, the owner policy and the\n * enclave block travel byte-identical (the server opens both versions and refuses anything else — those stay\n * fork-and-replay). `by` is the display name for the line. → { status, changed:[…], recorded } */\n /** The standing Sentinel's door (docs/standing-sentinel.md §2): attest / credgrant / credlist / credrevoke, as the\n * signed-in account (the token's email — the server never reads an account the page names). A pipe: the grant\n * inside is sealed to the Sentinel's attested key. → the Sentinel's answer, or { error }. */\n sentinel: async (sentinel, idToken) => post({ op: \"sentinel\", sentinel, idToken }),\n /** The cloud device through the API (agent/cloudDeviceRoute.mjs): `cd` = { t, … }, the account = the verified idToken's. */\n cloudDevice: async (cd, idToken, opts) => (await Promise.resolve().then(() => (init_cloudDeviceSeal(), cloudDeviceSeal_exports))).cloudDeviceCall(post, cd, idToken, opts || void 0),\n // sealed to its enclave once pinned; opts: the dev server's root and pins (witbitz-sdk.js _cloudDeviceOpts)\n // press-to-talk's cloud engine (agent/sttKey.mjs): a short-lived, capped Tinfoil key for this signed-in account\n // SAFE MEDIA (docs/safe-media.md): the tools enclave's attestation for a nonce, then a sealed box to make a file safe\n safeMedia: async (idToken, safemedia) => post({ op: \"safemedia\", idToken, safemedia }),\n stt: async (idToken, userToken2) => post({ op: \"stt\", ...idToken ? { idToken } : {}, ...userToken2 ? { userToken: userToken2 } : {} }),\n // userToken: the SDK's tenant-vouched user (wb.dictation)\n // Report (docs/report-and-block.md §3): what the member chose to show Witbitz — the front stores and mails it (agent/reportOp.mjs)\n report: async (idToken, body, memberToken) => post({ op: \"report\", idToken, room: body.room, report: body, ...memberToken ? { memberToken } : {} }),\n // a MEMBER's token for a report (agent/spaceService.mjs op membertoken): issued only to the room's CURRENT key and, in a verified\n // room, to a sign-in its gate admits (it rides with the request) — sealed to the turn enclave for a confidential room, like any\n // keyed op, so the key never reaches the Lambda\n memberToken: async (room, mk) => post({ op: \"membertoken\", room, ...await keyFields(room, \"membertoken\", mk), ...await authFor(room) }),\n // the sign-in: a verified room issues it only past its email gate (sync sweep 11-11 #2)\n tts: async (idToken, userToken2) => post({ op: \"tts\", ...idToken ? { idToken } : {}, ...userToken2 ? { userToken: userToken2 } : {} }),\n // \"Play aloud\": a capped Tinfoil key for speech OUTPUT (agent/sttKey.mjs § SPEECH OUTPUT)\n /** Witbitz's signed rule + room signature for a NEW room that requires an app (op owner-policy, agent/witbitzOwnerPolicy.mjs) — for\n * a create that is not this client's own (the hosted app's split create, space.js createSplitLocal). */\n ownerPolicyFor: async (room, _mk, level) => post({ op: \"owner-policy\", room, level }),\n setConfig: async (room, mk, patch, by) => {\n let r = await policyPost(room, mk);\n if (!r || r.status !== 200) return { status: r && r.status || 502, error: r && r.error || \"policy_unavailable\" };\n if (!r.configSealed && r.gated !== true) {\n const h = await healEnclaveConfig(room, mk);\n if (h && h.saved) r = { ...r, configSealed: h.configSealed };\n }\n let cur = {};\n if (r.configSealed) {\n let pt = null;\n try {\n pt = await open(JSON.parse(r.configSealed), { mk });\n } catch {\n pt = null;\n }\n if (pt == null) return { status: 409, error: \"config_unreadable\" };\n try {\n cur = JSON.parse(pt) || {};\n } catch {\n return { status: 409, error: \"config_unreadable\" };\n }\n }\n const p = patch && typeof patch === \"object\" ? patch : {};\n const next = { ...cur };\n if (\"persona\" in p) next.persona = p.persona == null ? void 0 : String(p.persona).slice(0, 4e3);\n if (\"agentName\" in p) next.agentName = p.agentName == null ? void 0 : String(p.agentName).slice(0, 80);\n if (\"model\" in p) next.model = p.model == null ? void 0 : p.model;\n if (\"funding\" in p) next.funding = p.funding && typeof p.funding.grant === \"string\" ? { grant: p.funding.grant.slice(0, 1200), perMemberUsd: Number(p.funding.perMemberUsd) || void 0 } : void 0;\n if (\"dataSchema\" in p) next.dataSchema = p.dataSchema == null ? void 0 : p.dataSchema;\n if (\"platformTools\" in p) next.platformTools = p.platformTools === false || Array.isArray(p.platformTools) ? p.platformTools : void 0;\n if (\"framing\" in p) next.framing = p.framing === \"builder\" ? \"builder\" : void 0;\n for (const k of [\"admins\", \"owners\"]) if (k in p) {\n const tags = p[k] && Array.isArray(p[k].tags) ? p[k].tags : cur[k] && Array.isArray(cur[k].tags) ? cur[k].tags : [];\n next[k] = roleOf(p[k] && p[k].emails || [], tags);\n }\n if (\"lanes\" in p) next.lanes = p.lanes === true;\n if (\"dataWrites\" in p) next.dataWrites = p.dataWrites === false ? false : void 0;\n if (\"safeMedia\" in p) next.safeMedia = p.safeMedia === true ? true : void 0;\n if (\"connections\" in p) {\n next.connections = applyConnectionsPatch(next.connections, p.connections);\n }\n const configSealed = JSON.stringify(await seal(JSON.stringify(next), { room: mk }));\n return post({ op: \"config\", room, ...await keyFields(room, \"config\", mk), configSealed, ...by ? { by: String(by).slice(0, 80) } : {}, ...await authFor(room) });\n },\n /** A VERIFIED ROOM RE-KEYED IN PLACE (docs/key-rotation-design.md § (b); agent/roomRekey.mjs has the server's rules).\n * `members` = the new { allow, owners, admins } (absent = a pure rotation, \"Rotate keys now\"); `recipients` = one\n * { mh: memberHash(email, room), boxPub } per member who stays (the caller included). Here, in the realm that holds the\n * key: a NEW key is minted; the config is read under the current key, its members replaced, the current key appended\n * to its chain, and it is sealed under the new key; the new key is sealed to each recipient's invite key; one request.\n * → the server's answer, plus `newMk` on success (the caller keeps it — the worker: l1-worker op 'rekey'). */\n // A SPLIT room (mk = userShare ⊕ appShare; the hosted app): `split.userShare` is the share held now. Only the USER half\n // rotates (§ Split-key rooms): appShare = mk ⊕ userShare, a fresh random userShare', mk' = userShare' ⊕ appShare — the\n // builder's half and its seal stay as they are. The grants carry userShare' (never mk'); the answer carries newShare.\n rekey: async (room, mk, { members = null, recipients = [], pending = [], by = \"\", split = null, creatorPriv = null, link = null, expectEpoch: wantEpoch = null } = {}) => {\n const r = await policyPost(room, mk);\n if (!r || r.status !== 200 || !r.configSealed) return { status: r && r.status || 502, error: r && r.error || \"policy_unavailable\" };\n let cur = null;\n try {\n cur = JSON.parse(await open(JSON.parse(r.configSealed), { mk }) || \"null\");\n } catch {\n cur = null;\n }\n if (!cur || typeof cur !== \"object\") return { status: 409, error: \"config_unreadable\" };\n const chain = Array.isArray(cur.keyChain) ? cur.keyChain : [];\n const epoch = chain.length;\n if (Number.isInteger(wantEpoch) && wantEpoch !== epoch) return { status: 409, error: \"stale_epoch\" };\n let newMk = newKey(), newShare = null;\n if (split && split.userShare) {\n const app2 = combineShares(mk, split.userShare);\n if (!app2) return { status: 400, error: \"bad_split\", reason: \"the held share does not pair with this key\" };\n const s2 = splitKey(app2);\n newShare = s2.shareA;\n newMk = s2.shareB;\n }\n const newCommit = await commit(newMk);\n const next = { ...cur, ...members ? { allow: members.allow, owners: members.owners, admins: members.admins } : {}, ...link ? { admission: \"invite\", roster: link.roster, gk: link.gk } : {}, keyChain: [...chain, { epoch, commit: await commit(mk), key: mk }] };\n for (const k of [\"owners\", \"admins\"]) if (next[k] === void 0) delete next[k];\n if (next.direct === true && members && !staysDirect(await directRoster(next.allow, room))) delete next.direct;\n const configSealed = JSON.stringify(await seal(JSON.stringify(next), { room: newMk }));\n const grant = JSON.stringify(newShare ? { v: 1, kind: \"room-split-key\", room, epoch: epoch + 1, userShare: newShare, commit: newCommit } : { v: 1, kind: \"room-key\", room, epoch: epoch + 1, mk: newMk });\n const grants = {};\n for (const x of recipients || []) {\n const id = x && (x.mh || x.id);\n if (id && x.boxPub && !grants[id]) grants[id] = JSON.stringify(await sealTo(x.extra ? JSON.stringify({ ...JSON.parse(grant), ...x.extra }) : grant, x.boxPub));\n }\n for (const mh of pending || []) {\n if (typeof mh === \"string\" && mh && !grants[mh]) grants[mh] = \"pending\";\n }\n const kf = await keyFields(room, \"rekey\", mk);\n let nf = { newMk };\n if (kf.mkSealed) {\n const pub = mkPubFor(room);\n nf = { newMkSealed: await sealMk(newMk, pub, mkAad({ room, op: \"rekey:new\", ts: kf.mkTs, nonce: kf.mkNonce })) };\n }\n const creatorSig = creatorPriv ? (await signEntry(creatorPriv, { room, kind: \"rekey\", id: newCommit, text: String(epoch), ts: 0, author: \"\" })).sig : void 0;\n const out = await post({ op: \"rekey\", room, ...kf, ...nf, newCommit, expectEpoch: epoch, configSealed, grants, ...creatorSig ? { creatorSig } : {}, ...by ? { by: String(by).slice(0, 80) } : {}, ...await authFor(room) });\n return out && out.status === 200 ? { ...out, newMk, newCommit, ...newShare ? { newShare } : {} } : out;\n },\n /** This member's new key after a rotation: the grant sealed to their account's invite key (op 'grant'), asked with the\n * sign-in alone — the old key opens nothing now. → { status:200, grant, epoch, commit } | { status:404, error:'no_grant' } */\n grant: async (room, _mk, keyProof = null) => post({ op: \"grant\", room, ...keyProof && keyProof.spk && keyProof.keySig ? { spk: keyProof.spk, keySig: keyProof.keySig } : await authFor(room) }),\n // keyProof: a LINK Space's member proves its signing key (no account)\n verifyGovernance: (room, mk, ownerKey, member) => verifyRoomGovernance({ room, mk, ownerKey, member, fetchPolicy: (r) => policyPost(r, r === room ? mk : null), openConfig: async (ct, m) => JSON.parse(await open(JSON.parse(ct), { mk: m })) })\n };\n return api;\n}\n\n// spaces/public/sdk/4.7.0/deviceSeal.js\nvar enc10 = new TextEncoder();\nvar dec4 = new TextDecoder();\nvar INFO = enc10.encode(\"witbitz-device-seal-v1\");\nvar SALT = enc10.encode(\"witbitz-device-seal\");\nvar SEAL_V = 1;\nvar subtle2 = () => {\n const s = globalThis.crypto && globalThis.crypto.subtle;\n if (!s) throw new Error(\"no WebCrypto\");\n return s;\n};\nvar b648 = (u8) => {\n let s = \"\";\n for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]);\n return btoa(s);\n};\nvar fromB64 = (s) => {\n const b = atob(String(s));\n const u = new Uint8Array(b.length);\n for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i);\n return u;\n};\nvar bytes = (x) => x instanceof Uint8Array ? x : x instanceof ArrayBuffer ? new Uint8Array(x) : Array.isArray(x) ? Uint8Array.from(x) : null;\nasync function importRaw(raw) {\n const r = bytes(raw);\n if (!r || r.length !== 32) throw new Error(\"seal key must be 32 bytes\");\n return subtle2().importKey(\"raw\", r, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n}\nasync function seal2(key, value) {\n if (!key) throw new Error(\"no seal key\");\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await subtle2().encrypt({ name: \"AES-GCM\", iv }, key, enc10.encode(JSON.stringify(value === void 0 ? null : value))));\n const out = new Uint8Array(iv.length + ct.length);\n out.set(iv, 0);\n out.set(ct, iv.length);\n return { v: SEAL_V, s: b648(out) };\n}\nasync function open2(key, blob) {\n if (!key) throw new Error(\"no seal key\");\n if (!isSealed(blob)) throw new Error(\"not a sealed blob\");\n const all = fromB64(blob.s);\n if (all.length < 12 + 16) throw new Error(\"sealed blob too short\");\n const pt = await subtle2().decrypt({ name: \"AES-GCM\", iv: all.subarray(0, 12) }, key, all.subarray(12));\n return JSON.parse(dec4.decode(pt));\n}\nvar isSealed = (x) => !!(x && typeof x === \"object\" && !Array.isArray(x) && x.v === SEAL_V && typeof x.s === \"string\" && x.s.length > 0);\nvar sealIf = async (key, value) => key ? seal2(key, value) : value;\nvar openIf = async (key, stored) => isSealed(stored) ? open2(key, stored) : stored;\n\n// spaces/public/sdk/4.7.0/sealedNames.js\nvar enc11 = new TextEncoder();\nvar dec5 = new TextDecoder();\nvar SALT2 = enc11.encode(\"witbitz-sealed-names\");\nvar NAME_PREFIX = \"p:\";\nvar isOpaqueName = (k) => typeof k === \"string\" && k.startsWith(NAME_PREFIX);\nvar subtle3 = () => {\n const s = globalThis.crypto && globalThis.crypto.subtle;\n if (!s) throw new Error(\"no WebCrypto\");\n return s;\n};\nvar toB64u = (u8) => {\n let s = \"\";\n for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar fromB64u = (s) => {\n const b = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const u = new Uint8Array(b.length);\n for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i);\n return u;\n};\nvar bytes2 = (x) => x instanceof Uint8Array ? x : x instanceof ArrayBuffer ? new Uint8Array(x) : Array.isArray(x) ? Uint8Array.from(x) : null;\nasync function nameKeys(raw) {\n const r = bytes2(raw);\n if (!r || r.length < 16) throw new Error(\"bad device key\");\n const base = await subtle3().importKey(\"raw\", r, \"HKDF\", false, [\"deriveKey\"]);\n const hk = (info) => ({ name: \"HKDF\", hash: \"SHA-256\", salt: SALT2, info: enc11.encode(info) });\n const mac = await subtle3().deriveKey(hk(\"witbitz-names-v1-mac\"), base, { name: \"HMAC\", hash: \"SHA-256\", length: 256 }, false, [\"sign\"]);\n const aes = await subtle3().deriveKey(hk(\"witbitz-names-v1-enc\"), base, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n return { mac, aes };\n}\nasync function ivFor(keys, name) {\n return new Uint8Array(await subtle3().sign(\"HMAC\", keys.mac, enc11.encode(name))).slice(0, 12);\n}\nasync function opaqueName(keys, name) {\n const iv = await ivFor(keys, String(name));\n const ct = new Uint8Array(await subtle3().encrypt({ name: \"AES-GCM\", iv }, keys.aes, enc11.encode(String(name))));\n const out = new Uint8Array(iv.length + ct.length);\n out.set(iv);\n out.set(ct, iv.length);\n return NAME_PREFIX + toB64u(out);\n}\nasync function realName(keys, stored) {\n if (!isOpaqueName(stored)) return null;\n try {\n const all = fromB64u(stored.slice(NAME_PREFIX.length));\n if (all.length < 29) return null;\n const iv = all.slice(0, 12);\n const name = dec5.decode(await subtle3().decrypt({ name: \"AES-GCM\", iv }, keys.aes, all.slice(12)));\n const want = await ivFor(keys, name);\n for (let i = 0; i < 12; i++) if (want[i] !== iv[i]) return null;\n return name;\n } catch {\n return null;\n }\n}\nasync function makeNamer(raw) {\n const keys = await nameKeys(raw);\n const fwd = /* @__PURE__ */ new Map(), back = /* @__PURE__ */ new Map();\n return {\n async opaque(name) {\n const n = String(name);\n let o = fwd.get(n);\n if (!o) {\n o = await opaqueName(keys, n);\n fwd.set(n, o);\n back.set(o, n);\n }\n return o;\n },\n async real(stored) {\n if (back.has(stored)) return back.get(stored);\n const n = await realName(keys, stored);\n if (n != null) {\n back.set(stored, n);\n fwd.set(n, stored);\n }\n return n;\n },\n known(name) {\n return fwd.get(String(name)) || null;\n }\n // synchronous: the stored name if computed before\n };\n}\n\n// spaces/public/sdk/4.7.0/idbSeal.js\nvar IDB_SHARED_NAMES = Object.freeze([\"notifTap\", \"notifPreview\", \"protectedNames\", \"swTrail\", \"codeRemindKey\", \"devkey:v1\", \"blocks:sw\", \"chatlocked:sw\"]);\nvar naming = { on: false, key: null, namer: null };\nfunction setIdbNaming({ on = false, key = null, namer = null } = {}) {\n naming.on = !!on;\n naming.key = key;\n naming.namer = namer;\n}\nvar idbNamingState = () => naming;\nasync function armIdbNaming(rawKey) {\n setIdbNaming({ on: true, key: await importRaw(rawKey), namer: await makeNamer(rawKey) });\n}\nvar IDB_PROTECTED_PREFIXES = Object.freeze([\"chat:\", \"wstate:\", \"blob:\", \"code:\", \"vchat:\", \"vblob:\", \"vblobidx\", \"hidx:\", \"zoom:\", \"outbox:\", \"mailpend:\"]);\nvar isProtectedIdbKey = (k) => {\n const s = String(k);\n return IDB_PROTECTED_PREFIXES.some((p) => s.startsWith(p));\n};\nvar st = { active: false, key: null };\nfunction setIdbProtection({ active = st.active, key = st.key } = {}) {\n st.active = !!active;\n st.key = key || null;\n if (!st.active) setIdbNaming({ on: false });\n else if (!st.key) setIdbNaming({ on: true });\n}\nasync function wrapForStore(k, v) {\n if (!st.active || !isProtectedIdbKey(k)) return v;\n if (!st.key) return void 0;\n return sealIf(st.key, v);\n}\nasync function unwrapFromStore(k, v) {\n if (!isProtectedIdbKey(k) || !isSealed(v)) return v;\n if (!st.key) return null;\n try {\n return await openIf(st.key, v);\n } catch {\n return null;\n }\n}\nvar protectedKeys = async (idb2) => {\n const out = [];\n for (const pfx of IDB_PROTECTED_PREFIXES) {\n if (typeof idb2.keysRaw === \"function\") out.push(...await idb2.keysRaw(pfx));\n else for (const [k] of await idb2.entriesRaw(pfx)) out.push(k);\n }\n return out;\n};\nasync function armIdbProtection(rawKey) {\n const key = await importRaw(rawKey);\n setIdbProtection({ active: true, key });\n setIdbNaming({ on: true, key, namer: await makeNamer(rawKey) });\n}\nasync function moveToOpaqueNames(idb2) {\n const { key, namer } = naming;\n if (!key || !namer) return 0;\n try {\n await idb2.setRaw(\"protectedNames\", true);\n } catch {\n }\n let n = 0;\n for (const k of await idb2.keysRaw(\"\")) {\n if (isOpaqueName(k) || IDB_SHARED_NAMES.includes(k) || k.startsWith(\"nk:\")) continue;\n let v = await idb2.getRaw(k);\n if (v === void 0 || v === null) continue;\n if (isProtectedIdbKey(k) && isSealed(v)) {\n try {\n v = await openIf(st.key || key, v);\n } catch {\n continue;\n }\n }\n const o = await namer.opaque(k);\n if (await idb2.getRaw(o) == null) await idb2.setRaw(o, await seal2(key, v));\n if (await idb2.getRaw(o) == null) continue;\n await idb2.delRaw(k);\n n++;\n }\n return n;\n}\nasync function migrateIdbProtection(idb2, rawKey) {\n await armIdbProtection(rawKey);\n return moveToOpaqueNames(idb2);\n}\nasync function unprotectIdb(idb2, rawKey) {\n const key = await importRaw(rawKey), namer = await makeNamer(rawKey);\n for (const o of await idb2.keysRaw(\"p:\")) {\n const name = await namer.real(o);\n const v = await idb2.getRaw(o);\n if (name != null && v != null) {\n let back;\n try {\n back = await open2(key, v);\n } catch {\n back = void 0;\n }\n if (back !== void 0) {\n await idb2.setRaw(name, back);\n if (await idb2.getRaw(name) == null) continue;\n }\n }\n await idb2.delRaw(o);\n }\n for (const k of await protectedKeys(idb2)) {\n const v = await idb2.getRaw(k);\n if (isSealed(v)) {\n try {\n await idb2.setRaw(k, await openIf(key, v));\n } catch {\n await idb2.delRaw(k);\n }\n }\n }\n try {\n await idb2.delRaw(\"protectedNames\");\n } catch {\n }\n setIdbProtection({ active: false, key: null });\n}\ntry {\n if (typeof window !== \"undefined\" && typeof localStorage !== \"undefined\") {\n const rawGet0 = (k) => {\n try {\n return typeof Storage !== \"undefined\" ? Storage.prototype.getItem.call(localStorage, k) : localStorage.getItem(k);\n } catch {\n return null;\n }\n };\n const cfgOn = (k) => {\n try {\n const c = JSON.parse(rawGet0(k) || \"null\");\n return !!(c && c.on && c.protect && c.protect.on);\n } catch {\n return false;\n }\n };\n let sameOriginFramed = false;\n try {\n sameOriginFramed = window.top !== window && window.parent.location.origin === location.origin;\n } catch {\n sameOriginFramed = false;\n }\n const on = window.top === window || sameOriginFramed ? cfgOn(\"space:lock\") || cfgOn(\"vault:lock\") || rawGet0(\"space:protected\") === \"1\" || window.top === window && rawGet0(\"vault:atrest\") === \"1\" || rawGet0(\"space:atrest\") === \"1\" : rawGet0(\"space:protected\") === \"1\";\n if (on) setIdbProtection({ active: true, key: null });\n }\n} catch {\n}\n\n// spaces/public/sdk/4.7.0/idb.js\nvar isNamed = (k) => {\n const n = idbNamingState();\n return n.on && !IDB_SHARED_NAMES.includes(String(k)) && !isOpaqueName(String(k)) && !String(k).startsWith(\"nk:\");\n};\nvar idbMemory = { on: false };\nvar idb = /* @__PURE__ */ (() => {\n let dbp, mem = null;\n const memory = () => {\n if (!mem) {\n mem = /* @__PURE__ */ new Map();\n idbMemory.on = true;\n }\n return mem;\n };\n const copy = (v) => v == null ? v : typeof structuredClone === \"function\" ? structuredClone(v) : v;\n const open3 = () => dbp || (dbp = new Promise((res, rej) => {\n if (typeof indexedDB === \"undefined\" || !indexedDB) {\n rej(Object.assign(new Error(\"no IndexedDB\"), { noIdb: true }));\n return;\n }\n let r;\n try {\n r = indexedDB.open(\"spaces\", 1);\n } catch (e) {\n rej(Object.assign(e instanceof Error ? e : new Error(String(e)), { noIdb: true }));\n return;\n }\n r.onupgradeneeded = () => r.result.createObjectStore(\"kv\");\n r.onsuccess = () => {\n const db = r.result;\n db.onversionchange = () => {\n db.close();\n dbp = null;\n };\n res(db);\n };\n r.onerror = () => rej(Object.assign(r.error || new Error(\"open failed\"), { noIdb: true }));\n }));\n const tx = (mode, fn, onMem) => open3().then(\n (db) => new Promise((res, rej) => {\n const t = db.transaction(\"kv\", mode), rq = fn(t.objectStore(\"kv\"));\n t.oncomplete = () => res(rq && rq.result);\n t.onerror = t.onabort = () => rej(t.error || new Error(\"IndexedDB transaction aborted\"));\n }),\n (e) => {\n if (e && e.noIdb && onMem) return onMem(memory());\n throw e;\n }\n );\n const inRange = (k, pfx) => !pfx || String(k).startsWith(pfx);\n const vault = () => typeof globalThis !== \"undefined\" && typeof globalThis.__wbAppIdb === \"function\" ? globalThis.__wbAppIdb : null;\n const getRaw = (k) => (vault() ? vault()(\"get\", k).then((v) => v === void 0 ? null : v) : tx(\"readonly\", (s) => s.get(k), (m) => copy(m.get(k)))).catch(() => null);\n const setRaw = (k, v) => (vault() ? vault()(\"set\", k, v) : tx(\"readwrite\", (s) => s.put(v, k), (m) => {\n m.set(k, copy(v));\n })).catch(() => {\n });\n const range = (pfx) => pfx ? IDBKeyRange.bound(pfx, pfx + \"\", false, true) : void 0;\n const entriesRaw = (pfx) => vault() ? vault()(\"entries\", pfx || \"\").then((es) => (es || []).map(([k, v]) => [String(k), v])).catch(() => []) : open3().then((db) => new Promise((res, rej) => {\n const t = db.transaction(\"kv\", \"readonly\"), s = t.objectStore(\"kv\"), ks = s.getAllKeys(range(pfx)), vs = s.getAll(range(pfx));\n t.oncomplete = () => {\n const keys = ks.result || [], vals = vs.result || [], out = [];\n for (let i = 0; i < keys.length; i++) if (String(keys[i]).startsWith(pfx)) out.push([String(keys[i]), vals[i]]);\n res(out);\n };\n t.onerror = () => rej(t.error);\n }), (e) => {\n if (e && e.noIdb) return [...memory()].filter(([k]) => inRange(k, pfx)).map(([k, v]) => [String(k), copy(v)]);\n throw e;\n }).catch(() => []);\n const keysRaw = (pfx) => (vault() ? vault()(\"keys\", pfx || \"\") : tx(\"readonly\", (s) => s.getAllKeys(range(pfx)), (m) => [...m.keys()])).then((ks) => (ks || []).map(String).filter((k) => k.startsWith(pfx))).catch(() => []);\n const delRawStrict = (k) => vault() ? vault()(\"del\", k) : tx(\"readwrite\", (s) => s.delete(k), (m) => {\n m.delete(k);\n });\n const delRaw = (k) => delRawStrict(k).catch(() => {\n });\n const delStrict = async (k) => {\n if (isNamed(k)) {\n const namer = idbNamingState().namer;\n if (!namer) throw new Error(\"cannot delete a protected key before unlocking\");\n await delRawStrict(await namer.opaque(k));\n }\n await delRawStrict(k);\n };\n const delPrefixRaw = (pfx) => (vault() ? vault()(\"delPrefix\", pfx || \"\") : tx(\n \"readwrite\",\n (s) => {\n const rq = s.getAllKeys(range(pfx));\n rq.onsuccess = () => {\n for (const k of rq.result || []) if (String(k).startsWith(pfx)) s.delete(k);\n };\n },\n (m) => {\n for (const k of [...m.keys()]) if (String(k).startsWith(pfx)) m.delete(k);\n }\n )).catch(() => {\n });\n const nameIndex = async () => {\n const nm = idbNamingState().namer;\n if (!nm) return [];\n const out = [];\n for (const o of await keysRaw(\"p:\")) {\n const n = await nm.real(o);\n if (n != null) out.push([o, n]);\n }\n return out;\n };\n const legacyGet = (k) => getRaw(k).then((v) => v == null ? v : unwrapFromStore(k, v));\n const getRawStrict = (k) => vault() ? vault()(\"get\", k).then((v) => v === void 0 ? null : v) : tx(\"readonly\", (s) => s.get(k), (m) => copy(m.get(k)));\n const self2 = {\n get: (k) => (!isNamed(k) ? legacyGet(k) : !idbNamingState().namer ? Promise.resolve(null) : (async () => {\n const v = await getRaw(await idbNamingState().namer.opaque(k));\n return v != null ? open2(idbNamingState().key, v) : legacyGet(k);\n })()).catch(() => null),\n set: (k, v) => (!isNamed(k) ? wrapForStore(k, v).then((stored) => stored === void 0 ? void 0 : setRaw(k, stored)) : !idbNamingState().namer ? Promise.resolve(void 0) : (async () => {\n const nm = idbNamingState().namer, key = idbNamingState().key;\n const o = await nm.opaque(k);\n const stored = await seal2(key, v);\n await setRaw(o, stored);\n await delRaw(k);\n })()).catch(() => {\n }),\n async clearStrict() {\n if (vault()) return vault()(\"delPrefix\", \"\");\n if (typeof indexedDB === \"undefined\" || !indexedDB) {\n memory().clear();\n return;\n }\n await tx(\"readwrite\", (store) => store.clear());\n if (mem) mem.clear();\n },\n delStrict,\n del: (k) => (!isNamed(k) || !idbNamingState().namer ? delRaw(k) : idbNamingState().namer.opaque(k).then((o) => Promise.all([delRaw(o), delRaw(k)]))).catch(() => {\n }),\n delPrefix: (pfx) => (!idbNamingState().on || !idbNamingState().namer ? delPrefixRaw(pfx) : nameIndex().then((ix) => Promise.all([...ix.filter(([, n]) => n.startsWith(pfx)).map(([o]) => delRaw(o)), delPrefixRaw(pfx)]))).catch(() => {\n }),\n // All [key, value] pairs whose key starts with pfx. Used by the L1 worker to load its room→mk map.\n entries: (pfx) => (async () => {\n const legacy = await entriesRaw(pfx).then((es) => Promise.all(es.map(async ([k, v]) => [k, await unwrapFromStore(k, v)])));\n if (!idbNamingState().on || pfx.startsWith(\"nk:\") || IDB_SHARED_NAMES.some((n) => n.startsWith(pfx) || pfx.startsWith(n))) return legacy;\n if (!idbNamingState().namer) return [];\n const key = idbNamingState().key, seen = /* @__PURE__ */ new Set(), out = [];\n for (const [o, n] of await nameIndex()) {\n if (!n.startsWith(pfx)) continue;\n const v = await getRaw(o);\n if (v == null) continue;\n try {\n out.push([n, await open2(key, v)]);\n seen.add(n);\n } catch {\n }\n }\n for (const [k, v] of legacy) if (!seen.has(k)) out.push([k, v]);\n return out;\n })().catch(() => []),\n // §NAMES: the real names under a prefix, values never read (the protection migration and listings).\n names: (pfx) => (idbNamingState().on && idbNamingState().namer ? nameIndex().then(async (ix) => [...ix.map(([, n]) => n).filter((n) => n.startsWith(pfx)), ...await keysRaw(pfx)]) : keysRaw(pfx)).catch(() => []),\n getRaw,\n setRaw,\n delRaw,\n entriesRaw,\n keysRaw,\n nameIndex,\n /** A read that THROWS when it failed (never null for an error) — for a value that must not be replaced on a failed read. */\n getStrict: (k) => !isNamed(k) ? getRawStrict(k).then((v) => v == null ? v : unwrapFromStore(k, v)) : self2.get(k),\n // §PROTECT: switch on / unlock (seal the clear content in place) and switch off (write it back) — the lock hooks call these.\n protect: (rawKey) => migrateIdbProtection(self2, rawKey),\n unprotect: (rawKey) => unprotectIdb(self2, rawKey)\n };\n return self2;\n})();\n\n// spaces/public/sdk/4.7.0/compress.js\nvar _jsonBytes = (v) => {\n try {\n return new TextEncoder().encode(JSON.stringify(v ?? null)).length;\n } catch {\n return Infinity;\n }\n};\nasync function _streamToU8(stream) {\n const reader = stream.getReader();\n const chunks = [];\n let n = 0;\n for (; ; ) {\n const { value, done } = await reader.read();\n if (done) break;\n chunks.push(value);\n n += value.length;\n }\n const out = new Uint8Array(n);\n let o = 0;\n for (const c of chunks) {\n out.set(c, o);\n o += c.length;\n }\n ;\n return out;\n}\nfunction _b64ToU8(b6410) {\n const s = atob(b6410);\n const u8 = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) u8[i] = s.charCodeAt(i);\n return u8;\n}\nasync function gunzipB64(b6410) {\n const stream = new Response(_b64ToU8(b6410)).body.pipeThrough(new DecompressionStream(\"gzip\"));\n return JSON.parse(new TextDecoder().decode(await _streamToU8(stream)));\n}\n\n// spaces/public/sdk/4.7.0/notifKey.js\nvar enc12 = new TextEncoder();\nvar b649 = (u8) => {\n const b = u8 instanceof Uint8Array ? u8 : new Uint8Array(u8);\n let s = \"\";\n for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar ub644 = (str) => {\n let s = String(str || \"\").replace(/-/g, \"+\").replace(/_/g, \"/\");\n s += \"=\".repeat((4 - s.length % 4) % 4);\n const bin = atob(s);\n const o = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) o[i] = bin.charCodeAt(i);\n return o;\n};\nasync function deriveNotifKey(mk) {\n if (!mk || typeof mk !== \"string\") throw new Error(\"deriveNotifKey needs the room mk\");\n const ikm = await crypto.subtle.importKey(\"raw\", ub644(mk), \"HKDF\", false, [\"deriveBits\"]);\n const bits = await crypto.subtle.deriveBits({ name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: enc12.encode(\"notif\") }, ikm, 256);\n return b649(new Uint8Array(bits));\n}\n\n// spaces/public/sdk/4.7.0/accountSeal.js\nvar enc13 = new TextEncoder();\nvar dec6 = new TextDecoder();\nvar ub645 = (s) => {\n const b = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const u = new Uint8Array(b.length);\n for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i);\n return u;\n};\nvar b64url2 = (u8) => {\n let s = \"\";\n for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar canZip = typeof CompressionStream === \"function\" && typeof DecompressionStream === \"function\";\nasync function pipeThrough(bytes3, stream) {\n return new Uint8Array(await new Response(new Blob([bytes3]).stream().pipeThrough(stream)).arrayBuffer());\n}\nasync function sealDoc(key, obj) {\n let bytes3 = enc13.encode(JSON.stringify(obj)), z = false;\n if (canZip) {\n bytes3 = await pipeThrough(bytes3, new CompressionStream(\"gzip\"));\n z = true;\n }\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, bytes3));\n const buf = new Uint8Array(12 + ct.length);\n buf.set(iv);\n buf.set(ct, 12);\n return { v: 1, z, s: b64url2(buf) };\n}\nasync function openDoc(key, doc) {\n const buf = ub645(doc.s);\n let bytes3 = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: buf.slice(0, 12) }, key, buf.slice(12)));\n if (doc.z) bytes3 = await pipeThrough(bytes3, new DecompressionStream(\"gzip\"));\n return JSON.parse(dec6.decode(bytes3));\n}\nvar isSealedDoc = (d) => !!(d && typeof d === \"object\" && typeof d.s === \"string\" && d.v === 1);\nvar _rawKeys = /* @__PURE__ */ new Map();\nfunction rawSealKey(b6410) {\n if (!_rawKeys.has(b6410)) _rawKeys.set(b6410, crypto.subtle.importKey(\"raw\", ub645(b6410), { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]));\n return _rawKeys.get(b6410);\n}\n\n// spaces/public/sdk/4.7.0/tempList.js\nvar TEMP_LIST_MAX = 100;\nvar isTempRoomId = (r) => typeof r === \"string\" && r.startsWith(\"tmp-\") && r.length <= 64;\nasync function editTempList(store, room, mk, change, by = \"\") {\n for (let i = 0; i < 3; i++) {\n const r = await store.get(room, mk, \"rooms\");\n if (!(r && r.status === 200)) return null;\n const cur = r.state && Array.isArray(r.state.rooms) ? r.state.rooms : [];\n const next = change(cur);\n if (!next) return cur;\n const w = await store.put(room, mk, \"rooms\", { rooms: next }, \"temp rooms\", by || \"\", Number.isInteger(r.v) ? { ifV: r.v } : {});\n if (w && w.status === 409) continue;\n return w && w.status === 200 ? next : null;\n }\n return null;\n}\nfunction addToTempList(all, { room, title, fresh }) {\n const was = all.find((r) => r && r.room === room);\n const reopen = fresh && fresh.mk ? { mk: fresh.mk } : fresh && fresh.userShare ? { userShare: fresh.userShare, commit: fresh.commit || \"\" } : was && was.mk ? { mk: was.mk } : was && was.userShare ? { userShare: was.userShare, commit: was.commit } : null;\n if (!reopen) return null;\n const prev = all.filter((r) => r && r.room !== room);\n const entry = { room, title: title || was && was.title || \"Space\", at: was && was.at || Date.now(), ...reopen };\n return [entry, ...prev].slice(0, TEMP_LIST_MAX);\n}\nvar removeFromTempList = (all, rooms) => {\n const gone = new Set(rooms);\n return all.filter((r) => r && !gone.has(r.room));\n};\nvar keylessTempList = (list) => (Array.isArray(list) ? list : []).filter((e) => e && isTempRoomId(e.room)).map(({ mk: _mk, userShare: _us, commit: _c, ...rest }) => ({ ...rest, held: 1 }));\n\n// spaces/public/sdk/4.7.0/roomDefaultPrefs.js\nvar ROOM_DEFAULTS_DOC = \"room-defaults\";\nvar BOOLS = [\"quick\", \"enclave\", \"verified\", \"lanes\", \"temporary\"];\nvar STRINGS = [\"assistant\", \"model\"];\nvar FIELDS = [...BOOLS, ...STRINGS];\nfunction cleanRoomDefaults(value) {\n if (!value || typeof value !== \"object\" || value.v !== 1) return null;\n const out = { v: 1, mods: {} };\n for (const key of FIELDS) {\n if (BOOLS.includes(key) ? typeof value[key] !== \"boolean\" : typeof value[key] !== \"string\" || value[key].length > 200) continue;\n out[key] = value[key];\n const at = value.mods?.[key];\n out.mods[key] = Number.isSafeInteger(at) && at >= 0 ? at : 0;\n }\n return FIELDS.some((key) => key in out) ? out : null;\n}\nfunction mergeRoomDefaults(a, b) {\n a = cleanRoomDefaults(a);\n b = cleanRoomDefaults(b);\n if (!a) return b;\n if (!b) return a;\n const out = { v: 1, mods: {} };\n for (const key of FIELDS) {\n const winner = !(key in a) ? b : !(key in b) ? a : a.mods[key] > b.mods[key] ? a : a.mods[key] < b.mods[key] ? b : JSON.stringify(a[key]) >= JSON.stringify(b[key]) ? a : b;\n if (key in winner) {\n out[key] = winner[key];\n out.mods[key] = winner.mods[key];\n }\n }\n if (out.temporary && out.lanes) {\n if (out.mods.temporary >= out.mods.lanes) out.lanes = false;\n else out.temporary = false;\n }\n return out;\n}\n\n// spaces/public/sdk/4.7.0/accountStores.js\nvar SEALED = (name) => \"x\" + name;\nvar MOVED = \"sealed\";\nvar MAPS = [\"rooms\", \"pipes\"];\nvar REGISTRIES = { computers: \"computers\" };\nfunction mergeRegistryMap(a, b) {\n const out = /* @__PURE__ */ Object.create(null);\n const mod = (e) => e && typeof e === \"object\" && typeof e.mod === \"number\" && Number.isFinite(e.mod) && e.mod > 0 ? e.mod : 0;\n for (const src of [a, b]) {\n if (!src || typeof src !== \"object\" || Array.isArray(src)) continue;\n for (const id of Object.keys(src)) {\n const e = src[id], cur = out[id];\n if (!mod(e)) continue;\n if (!cur || mod(e) > mod(cur) || mod(e) === mod(cur) && e.removed && !cur.removed) out[id] = e;\n }\n }\n return out;\n}\nfunction carryMissing(mine, cur, name = \"\") {\n if (!cur || typeof cur !== \"object\" || !mine || typeof mine !== \"object\") return mine;\n const out = { ...mine };\n if (name === \"kept-agent-links\") {\n const links = { ...cur.links || {} };\n for (const [id, link] of Object.entries(mine.links || {})) if (!links[id] || link.at > links[id].at || link.at === links[id].at && link.gone) links[id] = link;\n return { ...out, links };\n }\n if (name === ROOM_DEFAULTS_DOC) return mergeRoomDefaults(mine, cur) || mine;\n if (/^usage-\\d{4}-(0[1-9]|1[0-2])$/.test(name)) {\n const rows = (r) => r && typeof r === \"object\" && !Array.isArray(r) ? r : {};\n return { ...out, r: { ...rows(cur.r), ...rows(mine.r) } };\n }\n const reg = REGISTRIES[name];\n if (reg) {\n out[reg] = mergeRegistryMap(cur[reg], mine[reg]);\n return out;\n }\n for (const m of MAPS) {\n const c = cur[m];\n if (!c || typeof c !== \"object\" || Array.isArray(c) || Array.isArray(mine[m])) continue;\n const have = mine[m] && typeof mine[m] === \"object\" ? mine[m] : {};\n const add = {};\n for (const id of Object.keys(c)) if (!(id in have) && !(m === \"rooms\" && id.startsWith(\"tmp-\"))) add[id] = c[id];\n if (Object.keys(add).length) out[m] = { ...add, ...have };\n }\n return out;\n}\nfunction makeAccountStore({ call: call2, key, oldKeys = async () => [] }) {\n const openAny = async (k, sealed) => {\n try {\n return { st: await openDoc(k, sealed), old: false };\n } catch {\n }\n let olds = [];\n try {\n olds = await oldKeys() || [];\n } catch {\n olds = [];\n }\n for (const ok of olds) {\n try {\n return { st: await openDoc(ok, sealed), old: true };\n } catch {\n }\n }\n return null;\n };\n const cleared = /* @__PURE__ */ new Set();\n const plainSeen = /* @__PURE__ */ new Map();\n const read = async (room, mk, name) => {\n try {\n return await call2(room, mk, name);\n } catch {\n return { status: 0 };\n }\n };\n const removalsToPlain = async (room, mk, name, reg, body) => {\n try {\n const pr = await read(room, mk, name);\n const cur = pr && pr.status === 200 && pr.state && typeof pr.state === \"object\" && !pr.state.z ? pr.state : null;\n const map = cur && cur[reg] && typeof cur[reg] === \"object\" ? cur[reg] : null;\n if (!map) return;\n const gone = {};\n for (const [id, e] of Object.entries(body && body[reg] || {})) if (e && e.removed && map[id] && !map[id].removed && mergeRegistryMap({ [id]: map[id] }, { [id]: e })[id] === e) gone[id] = e;\n if (Object.keys(gone).length) await call2(room, mk, name, { ...cur, [reg]: { ...map, ...gone } }, \"computer removed\", \"\", Number.isInteger(pr.v) ? pr.v : 0);\n } catch {\n }\n };\n return {\n /** → { status, state, sealed: bool, v? } — status 200 only for a DEFINITIVE read. `v`: the sealed doc's version, for a\n * write that must not land over a change it never merged (put's `ifV`). */\n async get(room, mk, name, { plainOpen = (s) => s } = {}) {\n const k = await key();\n const plainR = await read(room, mk, name);\n const pk = room + \"|\" + name;\n if (plainR && plainR.status === 200 && !plainSeen.has(pk)) plainSeen.set(pk, Number.isInteger(plainR.v) ? plainR.v : null);\n const plain = plainR && plainR.status === 200 && plainR.state && typeof plainR.state === \"object\" ? await plainOpen(plainR.state) : null;\n if (plain && plain.moved === MOVED) cleared.add(room + \"|\" + name);\n if (!k) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false };\n const sr = await read(room, mk, SEALED(name));\n if (!(sr && sr.status === 200)) return { status: sr && sr.status || 0, state: null, sealed: false };\n if (!isSealedDoc(sr.state)) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false, ...Number.isInteger(sr.v) ? { v: sr.v } : {} };\n const opened = await openAny(k, sr.state);\n if (!opened) return { status: 0, state: null, sealed: true, unopenable: true };\n let st2 = opened.st;\n let v = Number.isInteger(sr.v) ? { v: sr.v } : {};\n if (opened.old) {\n try {\n const w = await call2(room, mk, SEALED(name), await sealDoc(k, st2), \"sealed under the new account key\", \"\", Number.isInteger(sr.v) ? sr.v : 0);\n if (w && w.status === 200 && Number.isInteger(w.v)) v = { v: w.v };\n } catch {\n }\n }\n const reg = REGISTRIES[name];\n if (reg) return { status: 200, state: plain && plain.moved !== MOVED ? { ...st2, [reg]: mergeRegistryMap(st2[reg], plain[reg]) } : st2, sealed: true, ...v };\n if (plain && plain.moved !== MOVED) {\n st2 = { ...st2 };\n for (const m of MAPS) {\n if (Array.isArray(plain[m])) {\n const have = new Set((Array.isArray(st2[m]) ? st2[m] : []).map((e) => e && e.room));\n st2[m] = [...Array.isArray(st2[m]) ? st2[m] : [], ...plain[m].filter((e) => e && e.room && !have.has(e.room))];\n } else if (plain[m] && typeof plain[m] === \"object\") st2[m] = { ...plain[m], ...st2[m] || {} };\n }\n cleared.delete(room + \"|\" + name);\n }\n return { status: 200, state: st2, sealed: true, ...v };\n },\n /** Write sealed; then empty the plain doc (once). → { status } — 0 + error 'no_account_key' without the key.\n * ⛔ TWO DEVICES MUST NOT OVERWRITE EACH OTHER (a reviewer's finding, 2026-10-05): re-read the CURRENT sealed doc,\n * carry over the map entries this write lacks (carryMissing — rooms/pipes are tombstoned, never dropped by\n * omission), and write only if the doc has not moved since that read (ifV → 409 → again). A current doc that cannot\n * be read or opened is NOT written over. spaces/test/accountStoresConcurrent.test.mjs.\n * ⛔ `ifV` — THE VERSION THE CALLER MERGED (2026-11-07, the implicit-state-machine review): the re-read above carries over\n * only the room/pipe maps; a list (contacts, events, to-dos), the device registry or the read positions written by\n * another device between the CALLER's read and this one was replaced. With `ifV` the write lands only over that version:\n * anything else answers 409 { error: 'moved' } and the caller reads and merges again. Without it: as before. */\n async put(room, mk, name, obj, summary, by, { ifV } = {}) {\n const pinned = Number.isInteger(ifV);\n const k = await key();\n if (!k) return { status: 0, error: \"no_account_key\" };\n for (let i = 0; i < 5; i++) {\n const sr = await read(room, mk, SEALED(name));\n if (!(sr && sr.status === 200)) return { status: sr && sr.status || 0, error: \"unread\" };\n if (pinned && (isSealedDoc(sr.state) || Number.isInteger(sr.v)) && sr.v !== ifV) return { status: 409, error: \"moved\" };\n let body = obj;\n if (isSealedDoc(sr.state)) {\n const opened = await openAny(k, sr.state);\n if (!opened) return { status: 0, error: \"unopenable\" };\n body = carryMissing(obj, opened.st, name);\n }\n const r = await call2(room, mk, SEALED(name), await sealDoc(k, body), summary, by, Number.isInteger(sr.v) ? sr.v : 0);\n const status = r && r.status || 0;\n if (status === 409 && pinned) return { status: 409, error: \"moved\" };\n if (status === 409) {\n await new Promise((res) => setTimeout(res, 20 + Math.floor(Math.random() * 80) * (i + 1)));\n continue;\n }\n if (status === 200 && REGISTRIES[name]) await removalsToPlain(room, mk, name, REGISTRIES[name], body);\n if (status === 200 && !REGISTRIES[name] && !cleared.has(room + \"|\" + name)) {\n const pk = room + \"|\" + name, read0 = plainSeen.has(pk), pv = plainSeen.get(pk);\n plainSeen.delete(pk);\n let w = null;\n if (read0) {\n try {\n w = await call2(room, mk, name, { v: 2, moved: MOVED }, summary, by, ...Number.isInteger(pv) ? [pv] : []);\n } catch {\n }\n }\n if (w && w.status === 200) cleared.add(pk);\n }\n return { status };\n }\n return { status: 409, error: \"busy\" };\n }\n };\n}\n\n// spaces/public/sdk/4.7.0/changePush.js\nvar RELAY_URL = \"wss://code-relay.witbitz.chat\";\nvar RELAY_PING = '{\"t\":\"relay-ping\"}';\nvar RELAY_PONG = '{\"t\":\"relay-pong\"}';\nvar HEARTBEAT_MS = 25e3;\nvar PONG_WAIT_MS = 1e4;\nvar te2 = new TextEncoder();\n\n// spaces/public/sdk/4.7.0/roomStreamClient.js\nvar STREAM_EPOCH_MS = 10 * 60 * 1e3;\nvar te3 = new TextEncoder();\nvar b64u2 = (u) => {\n let s = \"\";\n for (const b of u) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar sha = async (s) => new Uint8Array(await crypto.subtle.digest(\"SHA-256\", te3.encode(s)));\nvar streamChannel = async (mk, grant = \"\") => b64u2(await sha(\"witbitz-room-stream|\" + mk + (grant ? \"|\" + grant : \"\")));\nvar streamKey = async (mk, grant = \"\") => grant ? b64u2(await sha(\"witbitz-room-stream-key|\" + mk + \"|\" + grant)) : mk;\nfunction currentGrant(grants, now = Date.now()) {\n const e = Math.floor(now / STREAM_EPOCH_MS);\n const g = (Array.isArray(grants) ? grants : []).find((x) => x && x.e === e && typeof x.g === \"string\");\n return g ? g.g : null;\n}\nfunction frameReader() {\n let text = \"\", valid = true, lastSeq = 0, owedPoll = false, turn = null;\n const poll = (why) => {\n if (owedPoll) return null;\n owedPoll = true;\n return { k: \"poll\", why };\n };\n return {\n // A poll's text REPAIRS a reader that lost its place; it never overrides one that has not. The writer stores each\n // step and THEN posts its frame, so a poll can be ahead of the frames or behind them — the frames are the authority\n // while they are whole (the page's renderPartial orders the two by sequence number).\n sync(t) {\n if (valid) return;\n text = String(t || \"\");\n valid = true;\n owedPoll = false;\n },\n apply(f) {\n if (!f || typeof f !== \"object\") return null;\n const tail = Number.isInteger(f.count) && f.count > 0 && typeof f.box === \"string\" ? { tail: { count: f.count, box: f.box } } : {};\n if (f.oob) return f.k === \"entries\" ? { k: \"poll\", why: \"changed\", ...tail, ...typeof f.doc === \"string\" && /^[A-Za-z0-9]{1,24}$/.test(f.doc) ? { doc: f.doc } : {} } : f.k === \"views\" ? { k: \"views\" } : null;\n if (f.seq === 1) {\n lastSeq = 0;\n text = \"\";\n valid = true;\n owedPoll = false;\n turn = typeof f.tid === \"string\" ? f.tid : null;\n } else if (turn && typeof f.tid === \"string\" && f.tid !== turn) {\n valid = false;\n return poll(\"other turn\");\n }\n const gap = lastSeq && f.seq !== lastSeq + 1;\n lastSeq = Number(f.seq) || lastSeq;\n if (gap) {\n valid = false;\n return poll(\"gap\");\n }\n if (f.k === \"entries\") {\n if (tail.tail) {\n owedPoll = true;\n return { k: \"poll\", why: \"entries\", ...tail };\n }\n return poll(\"entries\");\n }\n if (f.k === \"resync\") {\n valid = false;\n return poll(\"resync\");\n }\n if (f.k === \"end\") {\n owedPoll = false;\n return { k: \"end\" };\n }\n if (f.k !== \"partial\") return null;\n const add = typeof f.add === \"string\" ? f.add : \"\";\n if (f.from === 0) {\n text = add;\n valid = true;\n owedPoll = false;\n } else if (valid && f.from <= text.length) text = text.slice(0, f.from) + add;\n else {\n valid = false;\n return poll(\"gap\");\n }\n return { k: \"partial\", text, pseq: f.pseq, step: f.step || null };\n }\n };\n}\nfunction openRoomStream({ mk, grants = null, tag = \"\", onEvent = () => {\n}, onState = () => {\n}, relay = RELAY_URL, path = \"c\", WebSocketImpl = globalThis.WebSocket, now = () => Date.now(), heartbeatMs = HEARTBEAT_MS, pongWaitMs = PONG_WAIT_MS } = {}) {\n if (!mk || typeof WebSocketImpl !== \"function\") return { up: () => false, sync() {\n }, setGrants() {\n }, stop() {\n } };\n const reader = frameReader();\n let ws = null, up = false, stopped = false, backoff = 1e3, retry = null, beat = null, pongTimer = null, epochTimer = null, key = null, gs = grants;\n const setUp = (v) => {\n if (v !== up) {\n up = v;\n try {\n onState(v);\n } catch {\n }\n }\n };\n const drop = () => {\n clearInterval(beat);\n clearTimeout(pongTimer);\n clearTimeout(epochTimer);\n beat = pongTimer = epochTimer = null;\n setUp(false);\n if (ws) {\n try {\n ws.onclose = ws.onerror = ws.onmessage = null;\n ws.close();\n } catch {\n }\n }\n ws = null;\n };\n const schedule = () => {\n if (stopped || retry) return;\n retry = setTimeout(() => {\n retry = null;\n connect();\n }, backoff);\n backoff = Math.min(backoff * 2, 3e4);\n };\n async function connect() {\n if (stopped || ws) return;\n const grant = gs ? currentGrant(gs, now()) : \"\";\n if (gs && !grant) return;\n key = await streamKey(mk, grant);\n let s;\n try {\n s = new WebSocketImpl(String(relay).replace(/\\/+$/, \"\") + \"/\" + path + \"/\" + await streamChannel(mk, grant) + (tag ? \"?v=\" + encodeURIComponent(tag) : \"\"));\n } catch {\n schedule();\n return;\n }\n if (stopped) {\n try {\n s.close();\n } catch {\n }\n return;\n }\n ws = s;\n s.onopen = () => {\n backoff = 1e3;\n setUp(true);\n beat = setInterval(() => {\n if (!ws || pongTimer) return;\n try {\n ws.send(RELAY_PING);\n } catch {\n drop();\n schedule();\n return;\n }\n pongTimer = setTimeout(() => {\n pongTimer = null;\n drop();\n schedule();\n }, pongWaitMs);\n }, heartbeatMs);\n if (gs) {\n const t = now();\n epochTimer = setTimeout(() => {\n drop();\n connect();\n }, (Math.floor(t / STREAM_EPOCH_MS) + 1) * STREAM_EPOCH_MS - t + 50);\n }\n };\n s.onmessage = async (ev) => {\n const text = typeof ev.data === \"string\" ? ev.data : \"\";\n if (text === RELAY_PONG) {\n clearTimeout(pongTimer);\n pongTimer = null;\n return;\n }\n if (!text || text.startsWith('{\"t\":')) return;\n let f = null;\n try {\n f = JSON.parse(await open(JSON.parse(text), { mk: key }) || \"null\");\n } catch {\n f = null;\n }\n const e = f && reader.apply(f);\n if (e) {\n try {\n onEvent(e);\n } catch {\n }\n }\n };\n s.onclose = s.onerror = () => {\n if (ws === s) {\n drop();\n schedule();\n }\n };\n }\n connect();\n return {\n up: () => up,\n sync: (t) => reader.sync(t),\n /** Fresh grants from a poll (a gated room): reconnect only if the current epoch's grant changed (a rotation). */\n setGrants(next) {\n if (!Array.isArray(next)) return;\n const changed = currentGrant(next, now()) !== currentGrant(gs, now());\n gs = next;\n if (changed || !ws) {\n drop();\n clearTimeout(retry);\n retry = null;\n connect();\n }\n },\n stop() {\n stopped = true;\n clearTimeout(retry);\n drop();\n }\n };\n}\n\n// spaces/public/sdk/4.7.0/roomPass.js\nvar enc14 = new TextEncoder();\nvar unb64uText = (s) => {\n const b = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return new TextDecoder().decode(Uint8Array.from(b, (c) => c.charCodeAt(0)));\n};\nfunction signInOf(body) {\n const m = body && body.message && typeof body.message === \"object\" ? body.message : null;\n const tok = body && typeof body.idToken === \"string\" && body.idToken || m && typeof m.idToken === \"string\" && m.idToken || \"\";\n const spk = body && body.idToken && body.spk || m && m.idToken && m.spk || null;\n if (!tok || !spk) return null;\n try {\n const p = JSON.parse(unb64uText(tok.split(\".\")[1]));\n const email = typeof p.email === \"string\" ? p.email.trim().toLowerCase() : \"\";\n return email.includes(\"@\") ? { email, spk } : null;\n } catch {\n return null;\n }\n}\nvar REVOKED_RETRY_MS = 5 * 6e4;\nvar SIGNIN_RENEW_AUTH = \"#signin-renew\";\n\n// spaces/public/sdk/4.7.0/l1-worker.js\nvar frameTails = /* @__PURE__ */ new Map();\nvar FRAME_TAIL_MS = 3e4;\nfunction openStreamHere(room, mk, grants, tag) {\n return openRoomStream({ mk, grants: Array.isArray(grants) ? grants : null, tag, onEvent: (ev) => {\n if (ev && ev.tail) {\n frameTails.set(room, { ...ev.tail, at: Date.now() });\n const { tail, ...rest } = ev;\n ev = rest;\n }\n self.postMessage({ t: \"stream\", room, ev });\n }, onState: (up) => self.postMessage({ t: \"stream\", room, up }) });\n}\nvar client = null;\nvar clientRealm = \"\";\nvar acctKey = null;\nvar oldAcctKeys = [];\nvar unzipDoc = async (st2) => st2 && typeof st2 === \"object\" && typeof st2.z === \"string\" ? await gunzipB64(st2.z).catch(() => null) : st2;\nvar acct = makeAccountStore({ call: (...a) => client.state(...a), key: async () => acctKey, oldKeys: async () => oldAcctKeys });\nvar tempPtr = null;\nvar tempStore = makeAccountStore({ call: (...a) => client.state(...a), key: async () => tempPtr && tempPtr.sk ? rawSealKey(tempPtr.sk) : null });\nvar TEMP_SK = /^[A-Za-z0-9_-]{43}$/;\nvar grantsByRoom = /* @__PURE__ */ new Map();\nvar streams = /* @__PURE__ */ new Map();\nfunction rekeyStream(room, mk) {\n const held = streams.get(room);\n if (!held?.s || held.mk === mk) return;\n held.s.stop();\n grantsByRoom.delete(room);\n held.mk = mk;\n held.grants = null;\n held.s = openStreamHere(room, mk, null, held.tag);\n}\nvar streamFeed = (room, result) => {\n const h = streams.get(room);\n if (!result || result.status !== 200) return;\n if (Array.isArray(result.streamGrants)) grantsByRoom.set(room, result.streamGrants);\n if (!h) return;\n if (Array.isArray(result.streamGrants)) {\n h.s?.setGrants(result.streamGrants);\n h.grants = result.streamGrants;\n }\n h.s?.sync(typeof result.partialText === \"string\" ? result.partialText : \"\");\n};\nvar mks = /* @__PURE__ */ new Map();\nvar splits = /* @__PURE__ */ new Map();\nvar sealKey = null;\nvar pushAcctRoom = \"\";\nvar derivePendingAcct = async () => {\n const mk = pushAcctRoom && mks.get(pushAcctRoom);\n if (!mk) return;\n pushAcctRoom = \"\";\n try {\n setPushAcct(await pushAcctSecretOf(mk));\n } catch {\n }\n};\nvar storageEpoch = 0;\nvar storageWiped = false;\nvar nkClear = false;\nvar protectedAtRest = false;\nvar parked = /* @__PURE__ */ new Map();\nvar volatile = /* @__PURE__ */ new Set();\nvar postAttNk = (room, nk) => {\n if (!room || !nk || String(room).startsWith(\"tmp-\")) return;\n try {\n self.postMessage({ t: \"attNk\", room, nk });\n } catch {\n }\n};\nvar roomOfKey = (k) => String(k).slice(String(k).indexOf(\":\") + 1);\nvar memOnlyRoom = (room) => volatile.has(room) || String(room).startsWith(\"tmp-\");\nvar persist = (k, v) => {\n const epoch = storageEpoch;\n return storageWiped || memOnlyRoom(roomOfKey(k)) ? Promise.resolve() : keysReady.then(() => !sealKey && protectedAtRest ? void 0 : sealIf(sealKey, v).then((stored) => epoch === storageEpoch && !storageWiped ? idb.set(k, stored) : void 0)).catch(() => {\n });\n};\nvar persistNk = (room, nk) => storageWiped ? Promise.resolve() : volatile.has(room) ? (postAttNk(room, nk), Promise.resolve()) : memOnlyRoom(room) ? Promise.resolve() : nkClear ? keysReady.then(() => storageWiped ? void 0 : idb.set(\"nk:\" + room, nk)).catch(() => {\n}) : protectedAtRest ? keysReady.then(() => idb.delRaw(\"nk:\" + room)).catch(() => {\n}) : persist(\"nk:\" + room, nk);\nvar eps = /* @__PURE__ */ new Map();\nvar noteEp = (room, ep) => {\n const n = Number(ep) || 0;\n if (room && n > (eps.get(room) || 0)) {\n eps.set(room, n);\n if (!memOnlyRoom(room)) idb.set(\"ep:\" + room, n).catch(() => {\n });\n }\n};\nvar backwards = (room, held, incoming, ep) => held !== incoming && (Number(ep) || 0) < (eps.get(room) || 0);\nvar tellEpoch = (room, ep, key) => {\n if (volatile.has(room) || String(room).startsWith(\"tmp-\")) return;\n try {\n self.postMessage({ t: \"keyEpoch\", room, ep, ...key });\n } catch {\n }\n};\nvar keep = (room, mk, ep) => {\n if (backwards(room, mks.get(room), mk, ep)) return false;\n if ((Number(ep) || 0) > 0 && (mks.get(room) !== mk || Number(ep) > (eps.get(room) || 0))) tellEpoch(room, Number(ep), { mk });\n if (ep) noteEp(room, ep);\n mks.set(room, mk);\n rekeyStream(room, mk);\n persist(\"mk:\" + room, mk);\n deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {\n });\n};\nvar APPSHARE_URL = (() => {\n try {\n const o = self.location && self.location.origin;\n return o && o !== \"null\" ? o + \"/api/appshare\" : \"/api/appshare\";\n } catch (e) {\n return \"/api/appshare\";\n }\n})();\nvar noKeyWhy = /* @__PURE__ */ new Map();\nvar noKeyReason = (room) => \"no key on this device\" + (noKeyWhy.has(room) ? \" — \" + noKeyWhy.get(room) : \"\");\nvar splitAlts = /* @__PURE__ */ new Map();\nvar heldOk = /* @__PURE__ */ new Map();\nasync function heldMatchesShare(room, have) {\n const sp = splits.get(room);\n if (!sp || !sp.commit || !((eps.get(room) || 0) > 0) || heldOk.get(room) === have) return true;\n let ok = false;\n try {\n ok = await commit(have) === sp.commit;\n } catch {\n ok = false;\n }\n if (ok) {\n heldOk.set(room, have);\n return true;\n }\n dropOldKey(room);\n return false;\n}\nvar dropOldKey = (room) => {\n if (!mks.has(room)) return;\n const h = streams.get(room);\n if (h) {\n h.s?.stop();\n h.mk = null;\n h.grants = null;\n }\n ;\n grantsByRoom.delete(room);\n mks.delete(room);\n keysReady.then(() => idb.del(\"mk:\" + room)).catch(() => {\n });\n};\nvar keepSplit = (room, sp, ep) => {\n if (backwards(room, splits.get(room) && splits.get(room).userShare, sp.userShare, ep)) return false;\n if ((Number(ep) || 0) > 0 && ((splits.get(room) || {}).userShare !== sp.userShare || Number(ep) > (eps.get(room) || 0))) {\n tellEpoch(room, Number(ep), { split: { userShare: sp.userShare, commit: sp.commit || \"\" } });\n if (Number(ep) > (eps.get(room) || 0) || (splits.get(room) || {}).userShare !== sp.userShare) dropOldKey(room);\n }\n if (ep) noteEp(room, ep);\n const held = splits.get(room);\n if (held && held.userShare !== sp.userShare) {\n const alts = splitAlts.get(room) || [];\n if (!alts.some((a) => a.userShare === held.userShare)) splitAlts.set(room, [held, ...alts].slice(0, 4));\n }\n splits.set(room, sp);\n persist(\"us:\" + room, sp);\n};\nvar forget = (room) => {\n grantsByRoom.delete(room);\n streams.get(room)?.s?.stop();\n streams.delete(room);\n mks.delete(room);\n splits.delete(room);\n eps.delete(room);\n for (const prefix of [\"mk:\", \"us:\", \"nk:\"]) parked.delete(prefix + room);\n lastPos.delete(room);\n heldOk.delete(room);\n splitAlts.delete(room);\n return Promise.all([\"mk:\", \"nk:\", \"us:\", \"ep:\", \"cnt:\"].map((prefix) => idb.delStrict(prefix + room)));\n};\nasync function resolveMk(room) {\n try {\n await keysReady;\n } catch {\n }\n const have = mks.get(room);\n if (have && await heldMatchesShare(room, have)) return have;\n const sp = splits.get(room);\n if (!sp) {\n noKeyWhy.set(room, \"no split share held\");\n return void 0;\n }\n let r = null;\n try {\n const x = await fetch(APPSHARE_URL, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ op: \"get\", room }) });\n if (!x.ok) {\n noKeyWhy.set(room, \"app half: HTTP \" + x.status);\n return void 0;\n }\n r = await x.json();\n } catch (e) {\n noKeyWhy.set(room, \"app half: \" + String(e && e.message || e).slice(0, 60));\n return void 0;\n }\n if (!r || !r.appShare) {\n noKeyWhy.set(room, \"app half: no share in the answer\");\n return void 0;\n }\n const cands = [sp, ...splitAlts.get(room) || []];\n for (const c of cands) {\n const mk = combineShares(c.userShare, r.appShare);\n if (mk && (!c.commit || await commit(mk) === c.commit)) {\n if (c !== sp) keepSplit(room, c);\n keep(room, mk, c === sp ? eps.get(room) : 0);\n noKeyWhy.delete(room);\n return mk;\n }\n }\n noKeyWhy.set(room, \"commitment mismatch: \" + cands.length + \" share(s) tried against the server half\" + (r.commit ? \" (server commit \" + String(r.commit).slice(0, 8) + \"…)\" : \"\"));\n return void 0;\n}\nvar ids = /* @__PURE__ */ new Map();\nvar encKey = null;\nvar encKeys = {};\nvar encAttested = null;\nvar encTrusted;\nvar encRooms = /* @__PURE__ */ new Set();\nvar authWaiters = /* @__PURE__ */ new Map();\nvar aseq = 0;\nvar attestWaiters = /* @__PURE__ */ new Map();\nvar delWaiters = /* @__PURE__ */ new Map();\nvar dseq = 0;\nvar delAsking = 0;\nvar askDel = (room) => new Promise((resolve) => {\n const a = ++dseq;\n delWaiters.set(a, resolve);\n self.postMessage({ delReq: a, room });\n setTimeout(() => {\n if (delWaiters.delete(a)) resolve(null);\n }, 5e3);\n});\nvar atseq = 0;\nvar publishPresence = () => self.postMessage({ t: \"presence\", rooms: [.../* @__PURE__ */ new Set([...mks.keys(), ...splits.keys()])], rk: 2, tl: 1 });\nvar dropTempCopy = (k) => {\n const room = k.slice(3);\n for (const pfx of [\"mk:\", \"us:\", \"nk:\", \"ep:\"]) idb.del(pfx + room).catch(() => {\n });\n};\nvar namesReady = Promise.all([idb.getRaw(\"protectedNames\"), idb.keysRaw(\"p:\")]).then(([f, ks]) => {\n if (f || ks && ks.length) {\n setIdbNaming({ on: true });\n protectedAtRest = true;\n }\n}).catch(() => {\n});\nvar keysReady = namesReady.then(() => Promise.all([\n idb.entries(\"mk:\").then((es) => {\n let n = 0;\n for (const [k, v] of es) if (k.startsWith(\"mk:tmp-\")) dropTempCopy(k);\n else if (isSealed(v)) {\n parked.set(k, v);\n protectedAtRest = true;\n } else if (v) {\n mks.set(k.slice(3), v);\n n++;\n }\n if (n) publishPresence();\n }).catch(() => {\n }),\n // a sealed entry waits for the device key (§PROTECT)\n idb.entries(\"ep:\").then((es) => {\n for (const [k, v] of es) {\n const n = Number(v);\n if (n > 0) eps.set(k.slice(3), n);\n }\n }).catch(() => {\n }),\n // key epochs (noteEp)\n idb.entries(\"us:\").then((es) => {\n let n = 0;\n for (const [k, v] of es) if (k.startsWith(\"us:tmp-\")) dropTempCopy(k);\n else if (isSealed(v)) {\n parked.set(k, v);\n protectedAtRest = true;\n } else if (v && v.userShare) {\n splits.set(k.slice(3), v);\n n++;\n }\n if (n) publishPresence();\n }).catch(() => {\n })\n // reload the split shares too — the reclaim-window fix\n]));\nvar AUTH_WAIT_MS = 2e4;\nvar auth = (room) => {\n const id = ids.get(room);\n if (id && id.googleIdToken && id.sign && id.sign.pub) return Promise.resolve({ idToken: id.googleIdToken, spk: id.sign.pub });\n return new Promise((resolve) => {\n const a = ++aseq;\n authWaiters.set(a, resolve);\n self.postMessage({ authReq: a, room });\n setTimeout(() => {\n const w = authWaiters.get(a);\n if (w) {\n authWaiters.delete(a);\n w({});\n }\n }, AUTH_WAIT_MS);\n });\n};\nvar attestShim = (room, o) => new Promise((resolve) => {\n const a = ++atseq;\n attestWaiters.set(a, resolve);\n self.postMessage({ attestReq: a, room, ...o && typeof o === \"object\" ? { o: { read: o.read === true, challenge: typeof o.challenge === \"string\" ? o.challenge : void 0 } } : {} });\n});\nsetAttestProvider(attestShim);\nvar IDB_WAIT = 2500;\nvar idbOpen = () => new Promise((res) => {\n const t = setTimeout(() => res(null), IDB_WAIT);\n try {\n const r = indexedDB.open(\"spaces\", 1);\n r.onupgradeneeded = () => {\n try {\n r.result.createObjectStore(\"kv\");\n } catch {\n }\n };\n r.onsuccess = () => {\n clearTimeout(t);\n const db = r.result;\n db.onversionchange = () => db.close();\n res(db);\n };\n r.onerror = () => {\n clearTimeout(t);\n res(null);\n };\n } catch {\n clearTimeout(t);\n res(null);\n }\n});\nvar idbGet = async (k) => {\n try {\n const db = await idbOpen();\n if (!db) return null;\n return await new Promise((res) => {\n const t = setTimeout(() => res(null), IDB_WAIT);\n const q = db.transaction(\"kv\", \"readonly\").objectStore(\"kv\").get(k);\n q.onsuccess = () => {\n clearTimeout(t);\n res(q.result || null);\n };\n q.onerror = () => {\n clearTimeout(t);\n res(null);\n };\n });\n } catch {\n return null;\n }\n};\nvar idbSet = async (k, v) => {\n try {\n const db = await idbOpen();\n if (!db) return false;\n return await new Promise((res) => {\n const t = setTimeout(() => res(false), IDB_WAIT);\n const q = db.transaction(\"kv\", \"readwrite\").objectStore(\"kv\").put(v, k);\n q.onsuccess = () => {\n clearTimeout(t);\n res(true);\n };\n q.onerror = () => {\n clearTimeout(t);\n res(false);\n };\n });\n } catch {\n return false;\n }\n};\nvar idbDel = async (k) => {\n try {\n const db = await idbOpen();\n if (!db) return false;\n return await new Promise((res) => {\n const t = setTimeout(() => res(false), IDB_WAIT);\n const q = db.transaction(\"kv\", \"readwrite\").objectStore(\"kv\").delete(k);\n q.onsuccess = () => {\n clearTimeout(t);\n res(true);\n };\n q.onerror = () => {\n clearTimeout(t);\n res(false);\n };\n });\n } catch {\n return false;\n }\n};\nvar lastPos = /* @__PURE__ */ new Map();\nvar prefetchChecked = /* @__PURE__ */ new Set();\nvar prefetchFlag = /* @__PURE__ */ new Set();\nvar prefetchLookUntil = 0;\ntry {\n const pfc = new BroadcastChannel(\"wb-prefetch\");\n pfc.onmessage = (e) => {\n const r = e && e.data && e.data.room;\n if (typeof r === \"string\") prefetchFlag.add(r);\n };\n} catch {\n}\nself.onmessage = async (e) => {\n const m = e.data || {};\n switch (m.t) {\n case \"delRes\": {\n const w = delWaiters.get(m.a);\n if (w) {\n delWaiters.delete(m.a);\n w(typeof m.v === \"string\" ? m.v : null);\n }\n return;\n }\n case \"authRes\": {\n const w = authWaiters.get(m.a);\n if (w) {\n authWaiters.delete(m.a);\n w(m.v || {});\n }\n return;\n }\n case \"attestRes\": {\n const w = attestWaiters.get(m.a);\n if (w) {\n attestWaiters.delete(m.a);\n w(m.v || null);\n }\n return;\n }\n case \"enclave\": {\n encKey = m.key || null;\n encAttested = m.attested || null;\n encKeys = m.keys && typeof m.keys === \"object\" ? m.keys : {};\n const snap = m.acceptance && typeof m.acceptance === \"object\" ? m.acceptance : {};\n encTrusted = Array.isArray(snap.trusted) ? snap.trusted : void 0;\n encRooms.clear();\n for (const r of m.rooms || []) encRooms.add(r);\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n // ── §PROTECT (docs/device-storage-protection.md): the device key arrives as 32 raw bytes, is imported non-extractable, and lives only here.\n case \"seal\": {\n try {\n sealKey = await importRaw(m.key);\n protectedAtRest = true;\n nkClear = !!m.previews;\n await keysReady;\n for (const k of parked.keys()) {\n try {\n await idb.delRaw(k);\n } catch {\n }\n }\n parked.clear();\n for (const [k, v] of await idb.entries(\"nk:\")) if (isSealed(v)) {\n try {\n await idb.delRaw(k);\n } catch {\n }\n }\n await armIdbNaming(m.key);\n let n = 0;\n for (const [room, mk] of mks) {\n await persist(\"mk:\" + room, mk);\n n++;\n try {\n await persistNk(room, await deriveNotifKey(mk));\n } catch {\n }\n }\n for (const [room, sp] of splits) {\n await persist(\"us:\" + room, sp);\n n++;\n }\n self.postMessage({ id: m.id, result: { sealed: n } });\n } catch (err) {\n sealKey = null;\n self.postMessage({ id: m.id, error: \"seal: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"unseal\": {\n try {\n const t0 = performance.now(), ms = {};\n const key = await importRaw(m.key);\n nkClear = !!m.previews;\n await keysReady;\n ms.ready = performance.now() - t0;\n await armIdbNaming(m.key);\n ms.names = performance.now() - t0;\n if ((await idb.keysRaw(\"p:\")).length && !(await idb.nameIndex()).length) {\n setIdbNaming({ on: true });\n throw new Error(\"this key opens nothing here\");\n }\n ms.check = performance.now() - t0;\n if (!parked.size) {\n for (const pfx of [\"mk:\", \"us:\", \"nk:\"]) for (const [k, v] of await idb.entries(pfx)) if (isSealed(v)) parked.set(k, v);\n }\n for (const k of [...parked.keys()]) if (/^(?:mk|us|nk):tmp-/.test(k)) {\n parked.delete(k);\n dropTempCopy(k);\n }\n ms.read = performance.now() - t0;\n ms.n = parked.size;\n let n = 0;\n const all = [...parked], vals = await Promise.all(all.map(([, blob]) => open2(key, blob)));\n all.forEach(([k], i) => {\n const v = vals[i];\n if (k.startsWith(\"mk:\")) {\n mks.set(k.slice(3), v);\n n++;\n } else if (k.startsWith(\"us:\")) {\n if (v && v.userShare) {\n splits.set(k.slice(3), v);\n n++;\n }\n }\n });\n parked.clear();\n sealKey = key;\n protectedAtRest = true;\n derivePendingAcct();\n for (const [room, mk] of mks) {\n persist(\"mk:\" + room, mk);\n deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {\n });\n }\n for (const [room, sp] of splits) persist(\"us:\" + room, sp);\n ms.open = performance.now() - t0;\n if (n) publishPresence();\n self.postMessage({ id: m.id, result: { opened: n, ms } });\n } catch (err) {\n self.postMessage({ id: m.id, error: \"unseal: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"previews\": {\n nkClear = !!m.on;\n try {\n if (sealKey) for (const [room, mk] of mks) {\n try {\n await persistNk(room, await deriveNotifKey(mk));\n } catch {\n }\n }\n } catch {\n }\n if (m.id != null) self.postMessage({ id: m.id, result: { previews: nkClear } });\n return;\n }\n case \"memoryOnly\": {\n protectedAtRest = true;\n sealKey = null;\n setIdbNaming({ on: true });\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"relock\": {\n if (sealKey) {\n mks.clear();\n splits.clear();\n parked.clear();\n sealKey = null;\n setIdbNaming({ on: true });\n publishPresence();\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"unprotect\": {\n try {\n const key = await importRaw(m.key);\n await keysReady;\n await armIdbNaming(m.key);\n const held = [];\n for (const pfx of [\"mk:\", \"us:\"]) for (const [k, v] of await idb.entries(pfx)) {\n held.push([k, v]);\n await idb.del(k);\n }\n setIdbNaming({ on: false });\n for (const [k, v] of await idb.entries(\"nk:\")) if (isSealed(v)) held.push([k, v]);\n for (const [k, v] of held) {\n const clear = isSealed(v) ? await open2(key, v) : v;\n await idb.set(k, clear);\n if (k.startsWith(\"mk:\")) mks.set(k.slice(3), clear);\n else if (k.startsWith(\"us:\") && clear && clear.userShare) splits.set(k.slice(3), clear);\n }\n parked.clear();\n sealKey = null;\n protectedAtRest = false;\n nkClear = false;\n publishPresence();\n for (const [room, mk] of mks) deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {\n });\n self.postMessage({ id: m.id, result: true });\n } catch (err) {\n self.postMessage({ id: m.id, error: \"unprotect: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"presenceQuery\": {\n await keysReady;\n publishPresence();\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"wipeKeys\": {\n storageWiped = true;\n storageEpoch++;\n await keysReady;\n for (const h of streams.values()) h.s?.stop();\n streams.clear();\n grantsByRoom.clear();\n mks.clear();\n splits.clear();\n parked.clear();\n splitAlts.clear();\n eps.clear();\n heldOk.clear();\n lastPos.clear();\n ids.clear();\n try {\n await idb.clearStrict();\n self.postMessage({ id: m.id, result: true });\n } catch (error) {\n self.postMessage({ id: m.id, error: String(error?.message || error) });\n } finally {\n publishPresence();\n }\n return;\n }\n case \"volatile\": {\n for (const r of Array.isArray(m.rooms) ? m.rooms : []) if (typeof r === \"string\" && r && !volatile.has(r)) {\n volatile.add(r);\n keysReady.then(() => Promise.all([idb.del(\"mk:\" + r), idb.del(\"us:\" + r)])).catch(() => {\n });\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"remember\": {\n keysReady.then(() => {\n if (m.room && m.mk) {\n keep(m.room, m.mk, m.ep);\n publishPresence();\n if (m.room === pushAcctRoom) derivePendingAcct();\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n });\n return;\n }\n case \"create\": {\n try {\n if (!client) throw new Error(\"l1-worker: create before open\");\n const via = m.split ? async (body) => {\n const x = await fetch(APPSHARE_URL, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) });\n const j = await x.json().catch(() => ({}));\n return { ...j && typeof j === \"object\" ? j : {}, status: x.status };\n } : null;\n if (m.delAsk) delAsking++;\n let r;\n try {\n r = await client.create(m.cfg || {}, { base: m.base || void 0, ...m.enclave ? { enclave: true } : {}, ...via ? { split: true, via } : {} });\n } finally {\n if (m.delAsk) delAsking--;\n }\n if (!r || !r.room || !r.mk) throw new Error(\"create: \" + String(r && (r.error || r.status) || \"no room\"));\n if (m.split) {\n if (!r.userShare) throw new Error(\"create: the app-half function gave no share\");\n keepSplit(r.room, { userShare: r.userShare, commit: r.commit || \"\" });\n }\n keep(r.room, r.mk);\n publishPresence();\n const link0 = r.links && r.links[0] || null;\n const link = m.split && link0 ? String(link0).split(\"#\")[0] + \"#us=\" + encodeURIComponent(r.userShare) + (r.commit ? \"&spc=\" + encodeURIComponent(r.commit) : \"\") : link0;\n self.postMessage({ id: m.id, result: { room: r.room, link, ...r.enclaveCreated === true ? { enclaveCreated: true } : {}, commit: r.commit || null, ...r.configSealed ? { configSealed: r.configSealed } : {}, ...m.returnMk ? { mk: r.mk } : {} } });\n } catch (err) {\n self.postMessage({ id: m.id, error: String(err && err.message || err) });\n }\n return;\n }\n case \"forget\": {\n try {\n await keysReady;\n if (m.room) await forget(m.room);\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n } catch (error) {\n if (m.id != null) self.postMessage({ id: m.id, error: String(error?.message || error) });\n } finally {\n publishPresence();\n }\n return;\n }\n case \"setPushAcct\": {\n try {\n if (typeof m.secret === \"string\") {\n pushAcctRoom = \"\";\n if (m.secret === \"\" || /^[A-Za-z0-9_-]{43}$/.test(m.secret)) setPushAcct(m.secret);\n } else {\n const mk = m.room ? mks.get(m.room) || await resolveMk(m.room) : \"\";\n pushAcctRoom = m.room && !mk ? String(m.room) : \"\";\n setPushAcct(await pushAcctSecretOf(mk || \"\"));\n }\n } catch {\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"prefetchIdentity\": {\n try {\n if (client && typeof client.prefetchIdentity === \"function\") await client.prefetchIdentity(String(m.token || \"\"));\n } catch {\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"setPushSelf\": {\n try {\n setPushSelf(m.endpoint || \"\");\n } catch {\n }\n for (const [room, h] of streams) {\n try {\n const tag = await viewingTag(room);\n if (streams.get(room) !== h) continue;\n if (tag && tag !== h.tag && h.mk) {\n h.s?.stop();\n h.s = openStreamHere(room, h.mk, h.grants || null, tag);\n h.tag = tag;\n }\n } catch {\n }\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"serveKeyPort\": {\n const sp = e.ports && e.ports[0];\n if (sp && m.room) {\n try {\n const mk = mks.get(m.room) || await resolveMk(m.room);\n sp.postMessage({ room: m.room, mk: mk || null });\n } catch {\n try {\n sp.postMessage({ room: m.room, mk: null });\n } catch {\n }\n }\n }\n return;\n }\n case \"adoptKeyPort\": {\n const { id: aid, room: aroom } = m;\n const ap = e.ports && e.ports[0];\n if (!ap || !aroom) {\n if (aid != null) self.postMessage({ id: aid, result: { ok: false } });\n return;\n }\n let settled = false;\n const settle = (ok) => {\n if (settled) return;\n settled = true;\n try {\n ap.close();\n } catch {\n }\n if (aid != null) self.postMessage({ id: aid, result: { ok } });\n };\n ap.onmessage = (ev) => {\n const d = ev && ev.data || {};\n if (d.mk && d.room === aroom) {\n keep(aroom, d.mk);\n publishPresence();\n settle(true);\n } else settle(false);\n };\n setTimeout(() => settle(false), m.timeoutMs > 0 ? m.timeoutMs : 8e3);\n return;\n }\n case \"wakeup\": {\n prefetchLookUntil = Date.now() + 8e3;\n return;\n }\n // the page came to the foreground (vault-loader.js / space.js onVisibility): look for a push-time prefetch on the polls that follow\n case \"ping\": {\n self.postMessage({ t: \"pong\", n: m.n | 0 });\n return;\n }\n // liveness heartbeat — the vault detects a RECLAIMED worker (iOS memory pressure) and recreates it; without this a dead handle ate every message silently and rooms stopped opening\n case \"rememberSplit\": {\n keysReady.then(() => {\n if (m.room && m.userShare) {\n keepSplit(m.room, { userShare: m.userShare, commit: m.commit || \"\" }, m.ep);\n publishPresence();\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n });\n return;\n }\n case \"rememberId\": {\n if (m.room && m.identity && m.identity.sign && m.identity.sign.priv) ids.set(m.room, m.identity);\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"ensureMk\": {\n const { id, room } = m;\n try {\n const mk = await resolveMk(room);\n self.postMessage({ id, result: { ok: !!mk } });\n } catch (err) {\n self.postMessage({ id, error: \"ensureMk: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"inviteLink\": {\n const { id, room, base, suffix } = m;\n try {\n const sp = splits.get(room), held = !(sp && sp.userShare) && m.plain === true && typeof mks.get(room) === \"string\" ? mks.get(room) : \"\";\n const link = sp && sp.userShare ? base + \"#us=\" + encodeURIComponent(sp.userShare) + (sp.commit ? \"&spc=\" + encodeURIComponent(sp.commit) : \"\") + (suffix || \"\") : held ? base + \"#mk=\" + held + (suffix || \"\") : null;\n self.postMessage({ id, result: { link } });\n } catch (err) {\n self.postMessage({ id, error: \"inviteLink: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"open\": {\n try {\n if (m.room && m.mk) keep(m.room, m.mk);\n const realm = JSON.stringify([m.endpoint || \"/space\", m.app || \"\", m.tenant || \"\"]);\n if (client && clientRealm === realm) {\n publishPresence();\n self.postMessage({ id: m.id, result: true });\n return;\n }\n clientRealm = \"\";\n client = makeSpaceClient({\n endpoint: m.endpoint || \"/space\",\n app: m.app,\n ...m.tenant ? { tenant: m.tenant } : {},\n // a builder's vault (vault-core.js): the Spaces it creates are its tenant's\n auth,\n mkPub: (r) => encRooms.has(r) ? (() => {\n const e2 = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { key: encKey, attested: encAttested } : {});\n return gatedKey({ key: e2.key || null, trusted: encTrusted, attested: e2.attested || null, platform: e2.attested && e2.attested.platform, room: r });\n })() : null,\n // r's OWN region's key; another region's is never borrowed // trusted undefined until the account's list is known → the gate refuses\n enclave: (r) => encRooms.has(r),\n envelope: (r) => {\n if (!encRooms.has(r)) return false;\n const e2 = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { attested: encAttested } : {});\n return opensEnvelopes(e2.attested);\n },\n // the sealed request envelope (reqEnvelope.js): this room's live enclave opens it\n identity: (r) => {\n if (!encRooms.has(r)) return false;\n const e2 = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { attested: encAttested } : {});\n return sealsIdentity(e2.attested);\n },\n // option B: it takes the sign-in from inside\n // A Spaces ACCOUNT's turn token (accountBilling.js) — asked of the page through the auth channel under a reserved\n // name, only when an op can spend. No answer / no session ⇒ '' ⇒ the turn bills as before.\n userToken: async () => {\n const v = await auth(\"#account-billing\");\n return v && typeof v.userToken === \"string\" ? v.userToken : \"\";\n },\n // A builder's VAULT (vault-core.js) with an account backup: a create carries the deletion commitment, which only the\n // vault can make (it holds the erase key — sdkErase.js). Asked only while a create that said `delAsk` runs.\n delCommit: (r) => delAsking > 0 ? askDel(r) : Promise.resolve(null),\n // a promise either way: spaceClient .catch()es it\n // THE ROOM PASS (docs/device-gate-design.md): the page holds it (roomPassWiring.js) — asked under the reserved name\n // '#room-pass' with this request's op, room and sign-in (its email and key, never the token); {} = none (off)\n roomPass: {\n fieldsFor: async (body, o) => {\n const si = signInOf(body);\n if (!si) return {};\n const v = await auth(\"#room-pass:\" + JSON.stringify({ op: body.op, room: body.room, email: si.email, spk: si.spk, ...o && Number.isFinite(o.ts) ? { ts: o.ts } : {} }));\n return v && v.pass && v.psig ? { pass: v.pass, psig: v.psig } : {};\n },\n // ts: this realm's sealNow — the server's clock as learned here\n renew: async (body) => {\n const si = signInOf(body);\n if (si) return auth(\"#room-pass:\" + JSON.stringify({ renew: true, email: si.email }));\n }\n },\n // A SIGN-IN THAT NAMES NO APP (docs/device-gate-design.md § 12.1, `pass: app_unnamed`): renewed by whoever holds it — the\n // page, or the vault for an identity it seeded here — and, when it is one held here, kept here renewed too\n renewSignIn: async (body) => {\n const room = body && body.room;\n if (!room || !signInOf(body)) return null;\n const v = await auth(SIGNIN_RENEW_AUTH + \":\" + room);\n if (v?.retryable) return { retryable: true };\n if (!v || typeof v.idToken !== \"string\" || !v.spk) return null;\n const id = ids.get(room);\n if (id && id.sign && JSON.stringify(id.sign.pub) === JSON.stringify(v.spk)) ids.set(room, { ...id, googleIdToken: v.idToken });\n return { idToken: v.idToken, spk: v.spk };\n }\n });\n clientRealm = realm;\n publishPresence();\n self.postMessage({ id: m.id, result: true });\n } catch (err) {\n self.postMessage({ id: m.id, error: \"open: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"acctSeal\":\n // {obj} → a doc sealed under the ACCOUNT key (the server never holds it) · null without the key\n case \"acctOpen\": {\n ;\n (async () => {\n try {\n if (!acctKey) return self.postMessage({ id: m.id, result: null });\n const result = m.t === \"acctSeal\" ? await sealDoc(acctKey, m.obj) : isSealedDoc(m.doc) ? await openDoc(acctKey, m.doc) : null;\n self.postMessage({ id: m.id, result });\n } catch {\n self.postMessage({ id: m.id, result: null });\n }\n })();\n return;\n }\n case \"acctKey\": {\n acctKey = m.key || null;\n oldAcctKeys = Array.isArray(m.old) ? m.old.filter(Boolean) : [];\n if (m.id != null) self.postMessage({ id: m.id, result: { ok: !!acctKey } });\n return;\n }\n case \"indexRead\": {\n const { id, indexRoom, indexMk, name } = m;\n const keylessAsk = !!m.keyless;\n try {\n if (!client) throw new Error(\"l1-worker: indexRead before open\");\n await keysReady;\n if (indexMk && !mks.get(indexRoom)) {\n keep(indexRoom, indexMk);\n publishPresence();\n }\n const r = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc });\n if (!(r && r.status === 200 && r.state)) {\n self.postMessage({ id, result: { status: r && r.status || 0, state: null, ...r && Number.isInteger(r.v) ? { v: r.v } : {} } });\n return;\n }\n let st2 = r.state;\n const mirror = {};\n const splitRooms = {};\n if (st2 && typeof st2 === \"object\" && st2.rooms && typeof st2.rooms === \"object\") {\n const keyless = {};\n let replaced = 0;\n for (const rm of Object.keys(st2.rooms)) {\n const e2 = st2.rooms[rm] || {};\n if (e2.deleted) {\n const { mk: _dmk, ep: _dep, split: _ds, userShare: _du, commit: _dc, ...rest } = e2;\n keyless[rm] = rest;\n continue;\n }\n if (e2.split && e2.userShare) {\n const held = splits.get(rm);\n if (keepSplit(rm, { userShare: e2.userShare, commit: e2.commit || \"\" }, e2.ep) !== false) {\n if (held && held.userShare !== e2.userShare) replaced++;\n mirror[rm] = { split: true, userShare: e2.userShare, commit: e2.commit || \"\" };\n }\n splitRooms[rm] = String((splits.get(rm) || {}).commit || e2.commit || \"\");\n const { split: _s, userShare: _u, commit: _c, ep: _sep, ...rest } = e2;\n keyless[rm] = rest;\n } else {\n if (e2.mk && (mks.get(rm) === e2.mk || (Number(e2.ep) || 0) >= (eps.get(rm) || 0))) {\n keep(rm, e2.mk, e2.ep);\n mirror[rm] = { mk: e2.mk };\n }\n const { mk, ep: _ep, ...rest } = e2;\n keyless[rm] = rest;\n }\n }\n publishPresence();\n {\n const all = Object.keys(st2.rooms);\n const bare = all.filter((rm) => {\n const e2 = st2.rooms[rm] || {};\n return !e2.deleted && !(e2.split && e2.userShare) && !e2.mk && !mks.has(rm) && !splits.has(rm);\n });\n self.postMessage({ t: \"note\", line: \"index read: \" + all.length + \" rooms · \" + (all.length - bare.length) + \" with a key here · \" + (bare.length ? \"NO KEY for \" + bare.map((rm) => rm.slice(0, 10)).join(\" \") : \"none keyless\") + (replaced ? \" · \" + replaced + \" held share(s) differ from the index copy\" : \"\") });\n }\n st2 = { ...st2, rooms: keyless };\n }\n if (name === \"index\" && st2 && typeof st2 === \"object\") {\n for (const field of [\"pipesRoom\", \"msgsRoom\"]) {\n const ptr = st2[field];\n if (!ptr?.room) continue;\n if (ptr.mk) keep(ptr.room, ptr.mk);\n if (keylessAsk) st2 = { ...st2, [field]: { room: ptr.room } };\n }\n publishPresence();\n }\n self.postMessage({ id, result: { status: 200, state: st2, splits: splitRooms, ...keylessAsk ? {} : { mkeys: mirror }, ...Number.isInteger(r.v) ? { v: r.v } : {} } });\n } catch (err) {\n self.postMessage({ id, error: \"indexRead: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"indexWrite\": {\n const { id, indexRoom, indexMk, name, patch, summary, by, ifV } = m;\n try {\n if (!client) throw new Error(\"l1-worker: indexWrite before open\");\n await keysReady;\n if (indexMk && !mks.get(indexRoom)) {\n keep(indexRoom, indexMk);\n publishPresence();\n }\n let p = { ...patch || {} };\n let previousIndex;\n if (p.rooms && typeof p.rooms === \"object\") {\n let cur = {};\n try {\n let s = null;\n const rr = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc, notePlain: false });\n if (rr && rr.status === 200 && rr.state) s = rr.state;\n previousIndex = s;\n if (s && s.rooms && typeof s.rooms === \"object\") cur = s.rooms;\n } catch {\n }\n const rooms = {};\n for (const rm of Object.keys(p.rooms)) {\n const e2 = p.rooms[rm] || {};\n if (e2.deleted) {\n const { mk: _dmk, ep: _dep, split: _ds, userShare: _du, commit: _dc, ...rest } = e2;\n rooms[rm] = rest;\n continue;\n }\n if (splits.has(rm)) {\n const sp = splits.get(rm);\n rooms[rm] = { ...e2, split: true, userShare: sp.userShare, ...sp.commit ? { commit: sp.commit } : {}, ...eps.get(rm) ? { ep: eps.get(rm) } : {} };\n continue;\n }\n const mk = mks.get(rm);\n if (mk) {\n rooms[rm] = { ...e2, mk, ...eps.get(rm) ? { ep: eps.get(rm) } : {} };\n continue;\n }\n const prev = cur[rm];\n if (prev && prev.split && prev.userShare) {\n keepSplit(rm, { userShare: prev.userShare, commit: prev.commit || \"\" }, prev.ep);\n rooms[rm] = { ...e2, split: true, userShare: prev.userShare, ...prev.commit ? { commit: prev.commit } : {}, ...prev.ep ? { ep: prev.ep } : {} };\n continue;\n }\n if (prev && prev.mk) {\n keep(rm, prev.mk, prev.ep);\n rooms[rm] = { ...e2, mk: prev.mk, ...prev.ep ? { ep: prev.ep } : {} };\n continue;\n }\n }\n p.rooms = rooms;\n publishPresence();\n }\n if (name === \"index\") for (const field of [\"pipesRoom\", \"msgsRoom\"]) {\n const ptr = p[field];\n if (!ptr?.room || ptr.mk) continue;\n const saved = previousIndex?.[field];\n const mk = saved?.room === ptr.room && saved.mk || mks.get(ptr.room);\n if (!mk) throw new Error(\"The account room key is unavailable. Retry sync.\");\n p[field] = { room: ptr.room, mk };\n }\n const r = await acct.put(indexRoom, mks.get(indexRoom) || indexMk, name, p, summary, by, { ifV });\n self.postMessage({ id, result: { status: r && r.status || 0, bytes: _jsonBytes(p), z: true, ...r && r.error ? { error: r.error } : {} } });\n } catch (err) {\n self.postMessage({ id, error: \"indexWrite: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"pipesRead\": {\n const { id, pipesRoom, pipesMk, name } = m;\n try {\n if (!client) throw new Error(\"l1-worker: pipesRead before open\");\n if (pipesMk && !mks.get(pipesRoom)) {\n keep(pipesRoom, pipesMk);\n publishPresence();\n }\n const r = await acct.get(pipesRoom, mks.get(pipesRoom) || pipesMk, name);\n if (!(r && r.status === 200 && r.state)) {\n self.postMessage({ id, result: { status: r && r.status || 0, state: null, ...r && Number.isInteger(r.v) ? { v: r.v } : {} } });\n return;\n }\n let st2 = r.state;\n if (st2 && typeof st2 === \"object\" && st2.pipes && typeof st2.pipes === \"object\") {\n const keyless = {};\n for (const s of Object.keys(st2.pipes)) {\n const pp = st2.pipes[s] || {};\n const out = { ...pp };\n if (pp.shared && pp.shared.room) {\n if (pp.shared.mk) keep(pp.shared.room, pp.shared.mk);\n const { mk, ...rest } = pp.shared;\n out.shared = rest;\n }\n if (pp.lane && pp.lane.room) {\n if (pp.lane.mk) keep(pp.lane.room, pp.lane.mk);\n const { mk, ...rest } = pp.lane;\n out.lane = rest;\n }\n for (const k of [\"laneA\", \"laneB\"]) {\n const ep = pp[k];\n if (ep && ep.room) {\n if (ep.mk) keep(ep.room, ep.mk);\n const { mk, ...rest } = ep;\n out[k] = rest;\n }\n }\n keyless[s] = out;\n }\n publishPresence();\n st2 = { ...st2, pipes: keyless };\n }\n self.postMessage({ id, result: { status: 200, state: st2, ...Number.isInteger(r.v) ? { v: r.v } : {} } });\n } catch (err) {\n self.postMessage({ id, error: \"pipesRead: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"pipesWrite\": {\n const { id, pipesRoom, pipesMk, name, patch, summary, by, ifV } = m;\n try {\n if (!client) throw new Error(\"l1-worker: pipesWrite before open\");\n if (pipesMk && !mks.get(pipesRoom)) {\n keep(pipesRoom, pipesMk);\n publishPresence();\n }\n let pp = { ...patch || {} };\n if (pp.pipes && typeof pp.pipes === \"object\") {\n const pipes = {};\n for (const s of Object.keys(pp.pipes)) {\n const e2 = pp.pipes[s] || {};\n const out = { ...e2 };\n if (e2.shared && e2.shared.room) {\n const mk = mks.get(e2.shared.room);\n out.shared = mk ? { ...e2.shared, mk } : e2.shared;\n }\n if (e2.lane && e2.lane.room) {\n const mk = mks.get(e2.lane.room);\n out.lane = mk ? { ...e2.lane, mk } : e2.lane;\n }\n for (const k of [\"laneA\", \"laneB\"]) {\n const ep = e2[k];\n if (ep && ep.room) {\n const mk = mks.get(ep.room);\n out[k] = mk ? { ...ep, mk } : ep;\n }\n }\n pipes[s] = out;\n }\n pp.pipes = pipes;\n }\n const r = await acct.put(pipesRoom, mks.get(pipesRoom) || pipesMk, name, pp, summary, by, { ifV });\n self.postMessage({ id, result: { status: r && r.status || 0, ...r && r.error ? { error: r.error } : {} } });\n } catch (err) {\n self.postMessage({ id, error: \"pipesWrite: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"tempHold\": {\n const p = m.ptr || {};\n const ok = isTempRoomId(p.room) && typeof p.mk === \"string\" && !!p.mk && typeof p.sk === \"string\" && TEMP_SK.test(p.sk);\n keysReady.then(() => {\n if (ok) {\n keep(p.room, p.mk);\n tempPtr = { room: p.room, sk: p.sk };\n publishPresence();\n }\n if (m.id != null) self.postMessage({ id: m.id, result: { ok, room: ok ? p.room : null } });\n });\n return;\n }\n case \"tempList\": {\n const { id } = m;\n const answer = (result) => self.postMessage({ id, result });\n (async () => {\n try {\n if (!client) throw new Error(\"l1-worker: tempList before open\");\n await keysReady;\n if (!tempPtr) return answer({ status: 0, error: \"no_pointer\" });\n const p = tempPtr, pmk = mks.get(p.room) || await resolveMk(p.room).catch(() => null);\n if (!pmk) return answer({ status: 0, error: \"no_key\", room: p.room });\n const absorb = (list2) => {\n for (const e2 of list2) {\n if (!e2 || !isTempRoomId(e2.room)) continue;\n if (e2.mk) keep(e2.room, e2.mk);\n else if (e2.userShare) keepSplit(e2.room, { userShare: e2.userShare, commit: e2.commit || \"\" });\n }\n publishPresence();\n };\n let list = null;\n if (m.do === \"read\") {\n const r = await tempStore.get(p.room, pmk, \"rooms\");\n if (!(r && r.status === 200)) return answer({ status: r && r.status || 0, room: p.room });\n list = r.state && Array.isArray(r.state.rooms) ? r.state.rooms : null;\n } else if (m.do === \"add\") {\n const a = m.add || {}, room = a.room;\n if (!isTempRoomId(room)) return answer({ status: 0, error: \"not_temp\", room: p.room });\n const sp = splits.get(room);\n const fresh = a.mk ? { mk: a.mk } : a.userShare ? { userShare: a.userShare, commit: a.commit || \"\" } : sp && sp.userShare ? { userShare: sp.userShare, commit: sp.commit || \"\" } : mks.get(room) ? { mk: mks.get(room) } : null;\n list = await editTempList(tempStore, p.room, pmk, (all) => addToTempList(all, { room, title: typeof a.title === \"string\" ? a.title.slice(0, 120) : \"\", fresh }), m.by);\n if (!list) return answer({ status: 0, room: p.room });\n } else if (m.do === \"remove\") {\n const rooms = (Array.isArray(m.rooms) ? m.rooms : []).filter(isTempRoomId);\n list = await editTempList(tempStore, p.room, pmk, (all) => removeFromTempList(all, rooms), m.by);\n if (!list) return answer({ status: 0, room: p.room });\n } else throw new Error(\"tempList: unknown \" + String(m.do));\n if (list) absorb(list);\n answer({ status: 200, room: p.room, rooms: list ? keylessTempList(list) : null });\n } catch (err) {\n self.postMessage({ id, error: \"tempList: \" + String(err && err.message || err) });\n }\n })();\n return;\n }\n case \"streamOpen\": {\n const { room } = m;\n const grants = m.grants || grantsByRoom.get(room);\n let held = streams.get(room);\n if (held) {\n held.holders++;\n if (Array.isArray(grants)) {\n held.grants = grants;\n held.s?.setGrants(grants);\n }\n return;\n }\n held = { holders: 1, mk: null, s: null, tag: \"\", grants: Array.isArray(grants) ? grants : null };\n streams.set(room, held);\n try {\n await keysReady;\n const mk = typeof m.mk === \"string\" && m.mk || mks.get(room) || await resolveMk(room);\n if (streams.get(room) !== held) return;\n if (!mk) {\n streams.delete(room);\n return;\n }\n const tag = await viewingTag(room).catch(() => \"\");\n if (streams.get(room) !== held) return;\n held.tag = tag;\n held.mk = mks.get(room) || mk;\n held.s = openStreamHere(room, held.mk, held.grants, tag);\n } catch (error) {\n if (streams.get(room) === held) streams.delete(room);\n }\n return;\n }\n case \"streamClose\": {\n const held = streams.get(m.room);\n if (held && --held.holders <= 0) {\n held.s?.stop();\n streams.delete(m.room);\n }\n return;\n }\n case \"op\": {\n const { id, op, room, args } = m;\n try {\n if (!client) throw new Error(\"l1-worker: op before open\");\n try {\n await keysReady;\n } catch {\n }\n if (typeof client[op] !== \"function\") throw new Error(\"l1-worker: unknown op \" + op);\n const aa = args || [];\n if (op === \"turn\" && aa[1] == null && ids.has(room)) aa[1] = ids.get(room);\n const index = routingIndex(op);\n if (index >= 0 && aa[index] && typeof aa[index] === \"object\") {\n const route = { ...aa[index] };\n aa[index] = route;\n if (route.bridgeRoom && !route.bridgeMk) {\n const key = mks.get(route.bridgeRoom) || await resolveMk(route.bridgeRoom);\n if (key) route.bridgeMk = key;\n }\n if (op === \"turn\" && Array.isArray(route.links)) {\n route.links = await Promise.all(route.links.map(async (link) => {\n if (!link?.room || link.mk) return link;\n const key = mks.get(link.room) || await resolveMk(link.room).catch(() => null);\n return key ? { ...link, mk: key } : link;\n }));\n }\n }\n const mkHere = await resolveMk(room);\n let result = null;\n let pfNote = \"\";\n const afterTap = !!(aa[2] && typeof aa[2] === \"object\" && aa[2].afterTap);\n if ((op === \"poll\" || op === \"pollSealed\") && mkHere && typeof client.decodeSealed === \"function\" && (afterTap || Date.now() < prefetchLookUntil || prefetchFlag.has(room) || !prefetchChecked.has(room))) {\n prefetchChecked.add(room);\n prefetchFlag.delete(room);\n let pfKey = \"prefetch:\" + room, pf = await idbGet(pfKey);\n if (!pf) {\n pfKey = await prefetchHashKey(room);\n pf = await idbGet(pfKey);\n }\n if (!pf) pfNote = \"none stored\";\n else {\n idbDel(pfKey);\n const why = prefetchUsable(pf, aa[1] | 0);\n if (why) pfNote = why + (why === \"position moved\" ? \" (stored since \" + pf.sinceCount + \", asked since \" + (aa[1] | 0) + \")\" : \"\");\n else {\n const pfAns = prefetchAnswer(pf, aa[1] | 0);\n if (!pfAns) pfNote = \"the tail does not reach this position\";\n else try {\n const out = await client.decodeSealed(room, mkHere, aa[1] | 0, pfAns);\n if (out && out.status === 200) {\n result = { ...out, prefetched: true };\n pfNote = pf.tail ? \"used (a tail from \" + pf.sinceCount + \")\" : \"used\";\n client[op](room, mkHere, ...aa).catch(() => {\n });\n } else pfNote = \"decoded to status \" + (out && out.status);\n } catch (e2) {\n result = null;\n pfNote = \"decode failed: \" + String(e2 && e2.message || e2).slice(0, 60);\n }\n }\n }\n }\n if (!result && (op === \"poll\" || op === \"pollSealed\") && mkHere && typeof client.decodeSealed === \"function\" && frameTails.has(room)) {\n const ft = frameTails.get(room);\n frameTails.delete(room);\n if (ft && Date.now() - ft.at < FRAME_TAIL_MS && (aa[1] | 0) === ft.count - 1) {\n try {\n const out = await client.decodeSealed(room, mkHere, ft.count - 1, { status: 200, changed: true, count: ft.count, from: ft.count - 1, sealed: JSON.stringify({ v: 3, from: ft.count - 1, count: ft.count, boxes: [ft.box] }) });\n if (out && out.status === 200) {\n result = { ...out, fromFrame: true };\n client[op](room, mkHere, ...aa).catch(() => {\n });\n }\n } catch {\n }\n }\n }\n if (!result && op === \"poll\" && !mkHere) result = { status: 401, error: \"no_key\", reason: noKeyReason(room) };\n if (op === \"rekey\" && splits.has(room)) aa[0] = { ...aa[0] || {}, split: { userShare: splits.get(room).userShare } };\n if (!result) result = await client[op](room, mkHere, ...aa);\n if (op === \"rekey\" && result && result.status === 200 && result.newShare) {\n keepSplit(room, { userShare: result.newShare, commit: result.newCommit }, result.epoch);\n keep(room, result.newMk, result.epoch);\n publishPresence();\n const { newMk: _nm, ...up } = result;\n result = { ...up, split: true };\n } else if (op === \"rekey\" && result && result.status === 200 && result.newMk) {\n keep(room, result.newMk, result.epoch);\n publishPresence();\n }\n if (op === \"pollSealed\" && !mkHere && result && result.status === 422) result = { ...result, error: \"no_key\", reason: noKeyReason(room) };\n if ((op === \"poll\" || op === \"pollSealed\") && result && result.status === 422 && result.reason === \"undecodable\" && splits.has(room) && mks.has(room)) {\n const stale = mks.get(room);\n mks.delete(room);\n idb.del(\"mk:\" + room).catch(() => {\n });\n const fresh = await resolveMk(room).catch(() => void 0);\n if (fresh && fresh !== stale) {\n const again = await client[op](room, fresh, ...aa);\n if (again && typeof again === \"object\") result = { ...again, rekeyed: true };\n } else if (stale) keep(room, stale);\n }\n if (pfNote && result && typeof result === \"object\") result = { ...result, prefetchNote: pfNote };\n if (op === \"poll\" || op === \"pollSealed\") {\n const pos = positionOf(result);\n const last = lastPos.get(room);\n if (pos && (!last || last.etag !== pos.etag || last.count !== pos.count)) {\n lastPos.set(room, pos);\n if (!protectedAtRest) idbSet(\"cnt:\" + room, pos);\n }\n }\n if (op === \"poll\" || op === \"pollSealed\") streamFeed(room, result);\n try {\n self.postMessage({ id, result });\n } catch (ce) {\n self.postMessage({ id, error: \"result-clone(\" + op + \"): \" + String(ce && ce.message || ce) });\n }\n } catch (err) {\n self.postMessage({ id, error: op + \": \" + String(err && err.message || err), ...err && err.code ? { code: err.code, verdict: err.verdict || null, room: err.room || null } : {} });\n }\n return;\n }\n }\n};\n"
|
|
2
|
+
export const SRC = "var __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __esm = (fn, res, err) => function __init() {\n if (err) throw err[0];\n try {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n } catch (e) {\n throw err = [e], e;\n }\n};\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// spaces/public/sdk/4.7.1/ohttp.js\nvar ohttp_exports = {};\n__export(ohttp_exports, {\n SUITE: () => SUITE,\n _eq: () => eq,\n cat: () => cat,\n decapsulateRequest: () => decapsulateRequest,\n decapsulateResponse: () => decapsulateResponse,\n decodeRequest: () => decodeRequest,\n decodeResponse: () => decodeResponse,\n encapsulateRequest: () => encapsulateRequest,\n encapsulateResponse: () => encapsulateResponse,\n encodeRequest: () => encodeRequest,\n encodeResponse: () => encodeResponse,\n hex: () => hex2,\n i2osp: () => i2osp,\n kemDecap: () => kemDecap,\n kemEncap: () => kemEncap,\n keySchedule: () => keySchedule,\n unhex: () => unhex\n});\nasync function hmac(key, data) {\n const k = await subtle.importKey(\"raw\", key.length ? key : new Uint8Array(32), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return new Uint8Array(await subtle.sign(\"HMAC\", k, data));\n}\nasync function expand(prk, info, L) {\n const out = [];\n let t = new Uint8Array(0);\n for (let i = 1; out.reduce((n, b) => n + b.length, 0) < L; i++) {\n t = await hmac(prk, cat(t, info, new Uint8Array([i])));\n out.push(t);\n }\n return cat(...out).slice(0, L);\n}\nasync function extractAndExpand(dh, kemContext) {\n const eaePrk = await labeledExtract(new Uint8Array(0), \"eae_prk\", dh, kemSuite);\n return labeledExpand(eaePrk, \"shared_secret\", kemContext, SUITE.Nsecret, kemSuite);\n}\nasync function kemEncap(pkRraw, ephemeral) {\n const pkR = await importPub(pkRraw);\n const kp = ephemeral || await subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\"deriveBits\"]);\n const dh = new Uint8Array(await subtle.deriveBits({ name: \"ECDH\", public: pkR }, kp.privateKey, 256));\n const enc15 = new Uint8Array(await subtle.exportKey(\"raw\", kp.publicKey));\n const shared = await extractAndExpand(dh, cat(enc15, pkRraw));\n return { shared, enc: enc15 };\n}\nasync function kemDecap(enc15, skR, pkRraw) {\n const pkE = await importPub(enc15);\n const dh = new Uint8Array(await subtle.deriveBits({ name: \"ECDH\", public: pkE }, skR, 256));\n return extractAndExpand(dh, cat(enc15, pkRraw));\n}\nasync function keySchedule(shared, info) {\n const pskIdHash = await labeledExtract(new Uint8Array(0), \"psk_id_hash\", new Uint8Array(0), hpkeSuite);\n const infoHash = await labeledExtract(new Uint8Array(0), \"info_hash\", info, hpkeSuite);\n const ctx = cat(new Uint8Array([0]), pskIdHash, infoHash);\n const secret = await labeledExtract(shared, \"secret\", new Uint8Array(0), hpkeSuite);\n const key = await labeledExpand(secret, \"key\", ctx, SUITE.Nk, hpkeSuite);\n const baseNonce = await labeledExpand(secret, \"base_nonce\", ctx, SUITE.Nn, hpkeSuite);\n const exporter = await labeledExpand(secret, \"exp\", ctx, SUITE.Nh, hpkeSuite);\n return { key, baseNonce, exporter };\n}\nasync function encapsulateRequest(keyConfig, bhttp, _ephemeral) {\n const { keyId, publicKey } = keyConfig;\n const { shared, enc: enc15 } = await kemEncap(publicKey, _ephemeral);\n const ks = await keySchedule(shared, reqInfo(keyId));\n const ct = await aeadSeal(ks.key, ks.baseNonce, new Uint8Array(0), bhttp);\n return { encRequest: cat(hdr(keyId), enc15, ct), ks, enc: enc15 };\n}\nasync function decapsulateRequest(encRequest, skR, pkRraw) {\n const keyId = encRequest[0];\n const enc15 = encRequest.slice(7, 7 + SUITE.Nenc);\n const ct = encRequest.slice(7 + SUITE.Nenc);\n const shared = await kemDecap(enc15, skR, pkRraw);\n const ks = await keySchedule(shared, reqInfo(keyId));\n const bhttp = await aeadOpen(ks.key, ks.baseNonce, new Uint8Array(0), ct);\n return { keyId, bhttp, ks, enc: enc15 };\n}\nasync function encapsulateResponse(ks, enc15, bhttpResp, _fixedNonce) {\n const L = Math.max(SUITE.Nn, SUITE.Nk);\n const responseNonce = _fixedNonce || globalThis.crypto.getRandomValues(new Uint8Array(L));\n const secret = await exportSecret(ks, \"message/bhttp response\", L);\n const prk = await extract(cat(enc15, responseNonce), secret);\n const key = await expand(prk, cat(te.encode(\"key\")), SUITE.Nk);\n const nonce = await expand(prk, cat(te.encode(\"nonce\")), SUITE.Nn);\n const ct = await aeadSeal(key, nonce, new Uint8Array(0), bhttpResp);\n return cat(responseNonce, ct);\n}\nasync function decapsulateResponse(ks, enc15, encResponse) {\n const L = Math.max(SUITE.Nn, SUITE.Nk);\n const responseNonce = encResponse.slice(0, L);\n const ct = encResponse.slice(L);\n const secret = await exportSecret(ks, \"message/bhttp response\", L);\n const prk = await extract(cat(enc15, responseNonce), secret);\n const key = await expand(prk, cat(te.encode(\"key\")), SUITE.Nk);\n const nonce = await expand(prk, cat(te.encode(\"nonce\")), SUITE.Nn);\n return aeadOpen(key, nonce, new Uint8Array(0), ct);\n}\nfunction putVarint(n) {\n if (n < 64) return new Uint8Array([n]);\n if (n < 16384) return new Uint8Array([64 | n >> 8, n & 255]);\n if (n < 1073741824) return new Uint8Array([128 | n >> 24, n >> 16 & 255, n >> 8 & 255, n & 255]);\n throw new Error(\"varint too large\");\n}\nfunction getVarint(b, i) {\n const p = b[i] >> 6, len = 1 << p;\n let v = b[i] & 63;\n for (let j = 1; j < len; j++) v = v * 256 + b[i + j];\n return [v, i + len];\n}\nfunction encodeRequest({ method = \"POST\", scheme = \"https\", authority, path = \"/\", headers = {}, body = new Uint8Array(0) }) {\n const control = cat(strField(method), strField(scheme), strField(authority), strField(path));\n let fields = new Uint8Array(0);\n for (const [k, v] of Object.entries(headers)) fields = cat(fields, strField(k.toLowerCase()), strField(String(v)));\n const content = cat(putVarint(body.length), body);\n return cat(new Uint8Array([0]), control, putVarint(fields.length), fields, content, putVarint(0));\n}\nfunction decodeRequest(b) {\n let i = 1;\n let method, scheme, authority, path;\n [method, i] = getStr(b, i);\n [scheme, i] = getStr(b, i);\n [authority, i] = getStr(b, i);\n [path, i] = getStr(b, i);\n let flen;\n [flen, i] = getVarint(b, i);\n const fEnd = i + flen;\n const headers = {};\n while (i < fEnd) {\n let k, v;\n [k, i] = getStr(b, i);\n [v, i] = getStr(b, i);\n headers[k] = v;\n }\n let clen;\n [clen, i] = getVarint(b, i);\n const body = b.slice(i, i + clen);\n return { method, scheme, authority, path, headers, body };\n}\nfunction encodeResponse({ status = 200, headers = {}, body = new Uint8Array(0) }) {\n let fields = new Uint8Array(0);\n for (const [k, v] of Object.entries(headers)) fields = cat(fields, strField(k.toLowerCase()), strField(String(v)));\n const content = cat(putVarint(body.length), body);\n return cat(new Uint8Array([1]), putVarint(status), putVarint(fields.length), fields, content, putVarint(0));\n}\nfunction decodeResponse(b) {\n let i = 1;\n let status;\n [status, i] = getVarint(b, i);\n let flen;\n [flen, i] = getVarint(b, i);\n const fEnd = i + flen;\n const headers = {};\n while (i < fEnd) {\n let k, v;\n [k, i] = getStr(b, i);\n [v, i] = getStr(b, i);\n headers[k] = v;\n }\n let clen;\n [clen, i] = getVarint(b, i);\n return { status, headers, body: b.slice(i, i + clen) };\n}\nvar subtle, SUITE, te, cat, i2osp, hex2, unhex, eq, extract, kemSuite, hpkeSuite, labeledExtract, labeledExpand, importPub, aeadSeal, aeadOpen, exportSecret, reqInfo, hdr, strField, getStr;\nvar init_ohttp = __esm({\n \"spaces/public/sdk/4.7.1/ohttp.js\"() {\n subtle = globalThis.crypto && globalThis.crypto.subtle;\n if (!subtle) throw new Error(\"ohttp: WebCrypto subtle unavailable\");\n SUITE = { kemId: 16, kdfId: 1, aeadId: 1, Nsecret: 32, Nh: 32, Nk: 16, Nn: 12, Nenc: 65, Npk: 65 };\n te = new TextEncoder();\n cat = (...as) => {\n let n = 0;\n for (const a of as) n += a.length;\n const o = new Uint8Array(n);\n let i = 0;\n for (const a of as) {\n o.set(a, i);\n i += a.length;\n }\n return o;\n };\n i2osp = (n, len) => {\n const o = new Uint8Array(len);\n for (let i = len - 1; i >= 0; i--) {\n o[i] = n & 255;\n n = Math.floor(n / 256);\n }\n return o;\n };\n hex2 = (u8) => [...u8].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n unhex = (s) => {\n const o = new Uint8Array(s.length / 2);\n for (let i = 0; i < o.length; i++) o[i] = parseInt(s.substr(i * 2, 2), 16);\n return o;\n };\n eq = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);\n extract = (salt, ikm) => hmac(salt, ikm);\n kemSuite = cat(te.encode(\"KEM\"), i2osp(SUITE.kemId, 2));\n hpkeSuite = cat(te.encode(\"HPKE\"), i2osp(SUITE.kemId, 2), i2osp(SUITE.kdfId, 2), i2osp(SUITE.aeadId, 2));\n labeledExtract = (salt, label, ikm, suite) => extract(salt, cat(te.encode(\"HPKE-v1\"), suite, te.encode(label), ikm));\n labeledExpand = (prk, label, info, L, suite) => expand(prk, cat(i2osp(L, 2), te.encode(\"HPKE-v1\"), suite, te.encode(label), info), L);\n importPub = (raw) => subtle.importKey(\"raw\", raw, { name: \"ECDH\", namedCurve: \"P-256\" }, true, []);\n aeadSeal = async (key, nonce, aad, pt) => new Uint8Array(await subtle.encrypt({ name: \"AES-GCM\", iv: nonce, additionalData: aad, tagLength: 128 }, await subtle.importKey(\"raw\", key, \"AES-GCM\", false, [\"encrypt\"]), pt));\n aeadOpen = async (key, nonce, aad, ct) => new Uint8Array(await subtle.decrypt({ name: \"AES-GCM\", iv: nonce, additionalData: aad, tagLength: 128 }, await subtle.importKey(\"raw\", key, \"AES-GCM\", false, [\"decrypt\"]), ct));\n exportSecret = (ks, ctx, L) => labeledExpand(ks.exporter, \"sec\", te.encode(ctx), L, hpkeSuite);\n reqInfo = (keyId) => cat(te.encode(\"message/bhttp request\"), new Uint8Array([0]), new Uint8Array([keyId]), i2osp(SUITE.kemId, 2), i2osp(SUITE.kdfId, 2), i2osp(SUITE.aeadId, 2));\n hdr = (keyId) => cat(new Uint8Array([keyId]), i2osp(SUITE.kemId, 2), i2osp(SUITE.kdfId, 2), i2osp(SUITE.aeadId, 2));\n strField = (s) => {\n const u = te.encode(s);\n return cat(putVarint(u.length), u);\n };\n getStr = (b, i) => {\n const [n, j] = getVarint(b, i);\n return [new TextDecoder().decode(b.slice(j, j + n)), j + n];\n };\n }\n});\n\n// spaces/public/sdk/4.7.1/cbor.js\nfunction decode(bytes3) {\n const b = toBytes(bytes3);\n const [value, off] = readItem(b, 0);\n if (value === BREAK) throw new Error(\"cbor: stray break byte\");\n if (off !== b.length) throw new Error(`cbor: ${b.length - off} trailing bytes`);\n return value;\n}\nfunction toBytes(x) {\n if (x instanceof Uint8Array) return x;\n if (x instanceof ArrayBuffer) return new Uint8Array(x);\n if (ArrayBuffer.isView(x)) return new Uint8Array(x.buffer, x.byteOffset, x.byteLength);\n throw new Error(\"cbor: expected bytes\");\n}\nfunction need(b, off, n) {\n if (n < 0 || off + n > b.length) throw new Error(\"cbor: truncated\");\n return off + n;\n}\nfunction readHead(b, off) {\n need(b, off, 1);\n const ib = b[off];\n const major = ib >> 5;\n const ai = ib & 31;\n if (ai < 24) return [major, ai, off + 1];\n if (ai === 24) {\n need(b, off + 1, 1);\n return [major, b[off + 1], off + 2];\n }\n if (ai === 25) {\n need(b, off + 1, 2);\n return [major, b[off + 1] << 8 | b[off + 2], off + 3];\n }\n if (ai === 26) {\n need(b, off + 1, 4);\n const v = (b[off + 1] << 24 | b[off + 2] << 16 | b[off + 3] << 8 | b[off + 4]) >>> 0;\n return [major, v, off + 5];\n }\n if (ai === 27) {\n need(b, off + 1, 8);\n let v = 0;\n for (let i = 1; i <= 8; i++) v = v * 256 + b[off + i];\n if (!Number.isSafeInteger(v)) throw new Error(\"cbor: 64-bit value exceeds safe integer range\");\n return [major, v, off + 9];\n }\n if (ai === 31) throw new Error(\"cbor: indefinite length handled by the caller\");\n throw new Error(`cbor: reserved additional information ${ai}`);\n}\nfunction readChunked(b, off, major, depth) {\n const parts = [];\n let total = 0;\n let p = off;\n for (; ; ) {\n need(b, p, 1);\n const head2 = b[p];\n if (head2 === 255) {\n p += 1;\n break;\n }\n if (head2 >> 5 !== major || (head2 & 31) === 31) {\n throw new Error(\"cbor: indefinite-length string contains a chunk of the wrong kind\");\n }\n const [chunk, next] = readItem(b, p, depth + 1);\n p = next;\n const bytes3 = major === 2 ? chunk : new TextEncoder().encode(chunk);\n total += bytes3.length;\n if (total > MAX_LEN) throw new Error(\"cbor: indefinite-length string too large\");\n parts.push(bytes3);\n }\n const out = concat(...parts);\n return [major === 2 ? out : new TextDecoder(\"utf-8\", { fatal: true }).decode(out), p];\n}\nfunction readItem(b, off, depth = 0) {\n if (depth > 16) throw new Error(\"cbor: nesting too deep\");\n need(b, off, 1);\n const ib = b[off];\n const major0 = ib >> 5;\n if ((ib & 31) === 31) {\n if (major0 === 7) return [BREAK, off + 1];\n if (major0 === 2 || major0 === 3) return readChunked(b, off + 1, major0, depth);\n if (major0 === 4 || major0 === 5) {\n const isMap = major0 === 5;\n const arr = [];\n const map = /* @__PURE__ */ new Map();\n let p2 = off + 1;\n let n = 0;\n for (; ; ) {\n const [k, n1] = readItem(b, p2, depth + 1);\n p2 = n1;\n if (k === BREAK) break;\n if (++n > MAX_LEN) throw new Error(\"cbor: indefinite-length collection too large\");\n if (!isMap) {\n arr.push(k);\n continue;\n }\n const [v, n2] = readItem(b, p2, depth + 1);\n p2 = n2;\n if (v === BREAK) throw new Error(\"cbor: indefinite-length map ended between a key and its value\");\n if (map.has(k)) throw new Error(\"cbor: duplicate map key\");\n map.set(k, v);\n }\n return [isMap ? map : arr, p2];\n }\n throw new Error(`cbor: indefinite length is not valid for major type ${major0}`);\n }\n const [major, value, p] = readHead(b, off);\n switch (major) {\n case 0:\n return [value, p];\n case 1:\n return [-1 - value, p];\n case 2: {\n if (value > MAX_LEN) throw new Error(\"cbor: byte string too large\");\n const end = need(b, p, value);\n return [b.slice(p, end), end];\n }\n case 3: {\n if (value > MAX_LEN) throw new Error(\"cbor: text string too large\");\n const end = need(b, p, value);\n return [new TextDecoder(\"utf-8\", { fatal: true }).decode(b.subarray(p, end)), end];\n }\n case 4: {\n if (value > MAX_LEN) throw new Error(\"cbor: array too long\");\n const out = [];\n let q = p;\n for (let i = 0; i < value; i++) {\n const [v, n] = readItem(b, q, depth + 1);\n if (v === BREAK) throw new Error(\"cbor: break inside a definite-length array\");\n out.push(v);\n q = n;\n }\n return [out, q];\n }\n case 5: {\n if (value > MAX_LEN) throw new Error(\"cbor: map too large\");\n const out = /* @__PURE__ */ new Map();\n let q = p;\n for (let i = 0; i < value; i++) {\n const [k, n1] = readItem(b, q, depth + 1);\n const [v, n2] = readItem(b, n1, depth + 1);\n if (k === BREAK || v === BREAK) throw new Error(\"cbor: break inside a definite-length map\");\n if (out.has(k)) throw new Error(\"cbor: duplicate map key\");\n out.set(k, v);\n q = n2;\n }\n return [out, q];\n }\n case 6: {\n const [v, n] = readItem(b, p, depth + 1);\n return [v, n];\n }\n case 7:\n if (value === 20) return [false, p];\n if (value === 21) return [true, p];\n if (value === 22) return [null, p];\n if (value === 23) return [void 0, p];\n throw new Error(`cbor: unsupported simple/float value ${value}`);\n default:\n throw new Error(\"cbor: unreachable\");\n }\n}\nfunction head(major, value) {\n if (value < 24) return Uint8Array.of(major << 5 | value);\n if (value < 256) return Uint8Array.of(major << 5 | 24, value);\n if (value < 65536) return Uint8Array.of(major << 5 | 25, value >> 8, value & 255);\n if (value < 4294967296) {\n return Uint8Array.of(major << 5 | 26, value >>> 24 & 255, value >>> 16 & 255, value >>> 8 & 255, value & 255);\n }\n throw new Error(\"cbor: length too large to encode\");\n}\nfunction encodeBytes(u8) {\n const b = toBytes(u8);\n return concat(head(2, b.length), b);\n}\nfunction encodeText(s) {\n const b = new TextEncoder().encode(String(s));\n return concat(head(3, b.length), b);\n}\nfunction encodeArray(items) {\n return concat(head(4, items.length), ...items);\n}\nfunction concat(...parts) {\n let n = 0;\n for (const p of parts) n += p.length;\n const out = new Uint8Array(n);\n let o = 0;\n for (const p of parts) {\n out.set(p, o);\n o += p.length;\n }\n return out;\n}\nvar MAX_LEN, BREAK;\nvar init_cbor = __esm({\n \"spaces/public/sdk/4.7.1/cbor.js\"() {\n MAX_LEN = 1 << 22;\n BREAK = /* @__PURE__ */ Symbol(\"cbor-break\");\n }\n});\n\n// spaces/public/sdk/4.7.1/x509.js\nfunction readTLV(b, off) {\n if (off + 2 > b.length) throw new Error(\"der: truncated tag\");\n const tag = b[off];\n if ((tag & 31) === 31) throw new Error(\"der: multi-byte tags not supported\");\n let p = off + 1;\n let len = b[p++];\n if (len & 128) {\n const n = len & 127;\n if (n === 0) throw new Error(\"der: indefinite length is not valid DER\");\n if (n > 4) throw new Error(\"der: length too large\");\n if (p + n > b.length) throw new Error(\"der: truncated length\");\n len = 0;\n for (let i = 0; i < n; i++) len = len * 256 + b[p++];\n }\n const contentEnd = p + len;\n if (contentEnd > b.length) throw new Error(\"der: truncated content\");\n return { tag, start: off, contentStart: p, contentEnd };\n}\nfunction expect(b, off, tag, what) {\n const t = readTLV(b, off);\n if (t.tag !== tag) throw new Error(`der: expected ${what} (tag 0x${tag.toString(16)}), got 0x${t.tag.toString(16)}`);\n return t;\n}\nfunction children(b, t) {\n const out = [];\n let p = t.contentStart;\n while (p < t.contentEnd) {\n const c = readTLV(b, p);\n out.push(c);\n p = c.contentEnd;\n }\n return out;\n}\nfunction oidString(b, t) {\n const c = b.subarray(t.contentStart, t.contentEnd);\n if (!c.length) throw new Error(\"der: empty OID\");\n const parts = [Math.floor(c[0] / 40), c[0] % 40];\n let v = 0;\n for (let i = 1; i < c.length; i++) {\n v = v * 128 + (c[i] & 127);\n if (!(c[i] & 128)) {\n parts.push(v);\n v = 0;\n }\n }\n return parts.join(\".\");\n}\nfunction parseTime(b, t) {\n const s = String.fromCharCode(...b.subarray(t.contentStart, t.contentEnd));\n let m;\n if (t.tag === TAG2.UTCTIME) {\n m = /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(s);\n if (!m) throw new Error(\"der: bad UTCTime\");\n const yy = Number(m[1]);\n return Date.UTC(yy >= 50 ? 1900 + yy : 2e3 + yy, Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));\n }\n if (t.tag === TAG2.GENTIME) {\n m = /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(s);\n if (!m) throw new Error(\"der: bad GeneralizedTime\");\n return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6]));\n }\n throw new Error(\"der: unsupported time tag\");\n}\nfunction derSigToRaw(der, size) {\n const b = der instanceof Uint8Array ? der : new Uint8Array(der);\n const seq = expect(b, 0, TAG2.SEQ, \"signature SEQUENCE\");\n const [rT, sT] = children(b, seq);\n if (!rT || !sT || rT.tag !== TAG2.INT || sT.tag !== TAG2.INT) throw new Error(\"der: bad ECDSA signature\");\n const out = new Uint8Array(size * 2);\n for (const [i, t] of [[0, rT], [1, sT]]) {\n let v = b.subarray(t.contentStart, t.contentEnd);\n while (v.length > 1 && v[0] === 0) v = v.subarray(1);\n if (v.length > size) throw new Error(\"der: ECDSA integer too large for curve\");\n out.set(v, i * size + (size - v.length));\n }\n return out;\n}\nfunction parseCertificate(der) {\n const b = der instanceof Uint8Array ? der : new Uint8Array(der);\n const cert = expect(b, 0, TAG2.SEQ, \"Certificate\");\n const [tbsT, algT, sigT] = children(b, cert);\n if (!tbsT || !algT || !sigT) throw new Error(\"der: Certificate needs 3 fields\");\n if (sigT.tag !== TAG2.BITSTRING) throw new Error(\"der: signatureValue must be a BIT STRING\");\n const sigAlgOid = oidString(b, expect(b, algT.contentStart, TAG2.OID, \"signature algorithm\"));\n const sigAlg = SIG_OIDS.get(sigAlgOid);\n if (!sigAlg) throw new Error(`der: unsupported signature algorithm ${sigAlgOid}`);\n if (b[sigT.contentStart] !== 0) throw new Error(\"der: signature BIT STRING has unused bits\");\n const sigDer = b.subarray(sigT.contentStart + 1, sigT.contentEnd);\n const kids = children(b, tbsT);\n const base = kids[0] && kids[0].tag === 160 ? 1 : 0;\n const [serialT, innerAlgT, issuerT, validityT, subjectT, spkiT] = kids.slice(base, base + 6);\n if (!serialT || !innerAlgT || !issuerT || !validityT || !subjectT || !spkiT) throw new Error(\"der: malformed tbsCertificate\");\n const innerOid = oidString(b, expect(b, innerAlgT.contentStart, TAG2.OID, \"inner signature algorithm\"));\n if (innerOid !== sigAlgOid) throw new Error(\"der: signature algorithm mismatch between tbs and certificate\");\n const [nbT, naT] = children(b, validityT);\n if (!nbT || !naT) throw new Error(\"der: malformed validity\");\n const [spkiAlgT] = children(b, spkiT);\n const spkiAlgKids = children(b, spkiAlgT);\n if (spkiAlgKids.length < 2) throw new Error(\"der: SPKI algorithm needs a curve parameter\");\n const keyOid = oidString(b, spkiAlgKids[0]);\n if (keyOid !== \"1.2.840.10045.2.1\") throw new Error(`der: not an EC public key (${keyOid})`);\n const curveOid = oidString(b, spkiAlgKids[1]);\n const curve = CURVE_OIDS.get(curveOid);\n if (!curve) throw new Error(`der: unsupported curve ${curveOid}`);\n let isCA = false;\n for (const k of kids.slice(base + 6)) {\n if (k.tag !== 163) continue;\n for (const ext of children(b, children(b, k)[0] || k)) {\n const extKids = children(b, ext);\n if (!extKids.length || oidString(b, extKids[0]) !== \"2.5.29.19\") continue;\n const octet = extKids[extKids.length - 1];\n const bcSeq = readTLV(b, octet.contentStart);\n const bcKids = children(b, bcSeq);\n isCA = !!(bcKids[0] && bcKids[0].tag === 1 && b[bcKids[0].contentStart] !== 0);\n }\n }\n return {\n tbs: b.subarray(tbsT.start, tbsT.contentEnd),\n sig: derSigToRaw(sigDer, curve.size),\n sigHash: sigAlg.hash,\n spki: b.slice(spkiT.start, spkiT.contentEnd),\n // copy: this is handed to WebCrypto, which wants its own buffer\n curve: curve.curve,\n size: curve.size,\n issuer: b.subarray(issuerT.start, issuerT.contentEnd),\n subject: b.subarray(subjectT.start, subjectT.contentEnd),\n notBefore: parseTime(b, nbT),\n notAfter: parseTime(b, naT),\n isCA\n };\n}\nfunction bytesEqual(a, b) {\n if (!a || !b || a.length !== b.length) return false;\n let d = 0;\n for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];\n return d === 0;\n}\nasync function importSpki(cert) {\n return crypto.subtle.importKey(\"spki\", cert.spki, { name: \"ECDSA\", namedCurve: cert.curve }, false, [\"verify\"]);\n}\nasync function verifyChain(chainDer, { now = Date.now() } = {}) {\n if (!Array.isArray(chainDer) || chainDer.length < 2) throw new Error(\"chain: need an anchor and at least one certificate\");\n const certs = chainDer.map((d, i) => {\n try {\n return parseCertificate(d);\n } catch (e) {\n throw new Error(`chain: certificate ${i} unparseable: ${e.message}`);\n }\n });\n for (let i = 1; i < certs.length; i++) {\n const child = certs[i];\n const parent = certs[i - 1];\n if (!bytesEqual(child.issuer, parent.subject)) throw new Error(`chain: certificate ${i} was not issued by certificate ${i - 1}`);\n if (i > 1 && !parent.isCA) throw new Error(`chain: certificate ${i - 1} signs but is not a CA`);\n if (now < child.notBefore) throw new Error(`chain: certificate ${i} is not yet valid`);\n if (now > child.notAfter) throw new Error(`chain: certificate ${i} has expired`);\n const ok = await crypto.subtle.verify({ name: \"ECDSA\", hash: child.sigHash }, await importSpki(parent), child.sig, child.tbs);\n if (!ok) throw new Error(`chain: certificate ${i} has a bad signature`);\n }\n return certs[certs.length - 1];\n}\nvar TAG2, SIG_OIDS, CURVE_OIDS;\nvar init_x509 = __esm({\n \"spaces/public/sdk/4.7.1/x509.js\"() {\n TAG2 = { INT: 2, BITSTRING: 3, OID: 6, SEQ: 48, UTCTIME: 23, GENTIME: 24 };\n SIG_OIDS = /* @__PURE__ */ new Map([\n [\"1.2.840.10045.4.3.2\", { hash: \"SHA-256\" }],\n [\"1.2.840.10045.4.3.3\", { hash: \"SHA-384\" }],\n [\"1.2.840.10045.4.3.4\", { hash: \"SHA-512\" }]\n ]);\n CURVE_OIDS = /* @__PURE__ */ new Map([\n [\"1.2.840.10045.3.1.7\", { curve: \"P-256\", size: 32 }],\n [\"1.3.132.0.34\", { curve: \"P-384\", size: 48 }],\n [\"1.3.132.0.35\", { curve: \"P-521\", size: 66 }]\n ]);\n }\n});\n\n// spaces/public/sdk/4.7.1/nitroVerify.js\nfunction b64ToBytes(b6410) {\n const s = String(b6410).replace(/-/g, \"+\").replace(/_/g, \"/\").replace(/\\s+/g, \"\");\n const bin = atob(s);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\nfunction sigStructure(protectedBytes, payloadBytes) {\n return encodeArray([\n encodeText(\"Signature1\"),\n encodeBytes(protectedBytes),\n encodeBytes(new Uint8Array(0)),\n // external_aad — always empty for Nitro\n encodeBytes(payloadBytes)\n ]);\n}\nfunction parseDocument(payloadBytes) {\n const m = decode(payloadBytes);\n if (!(m instanceof Map)) throw new Error(\"attestation: payload is not a map\");\n const moduleId = m.get(\"module_id\");\n if (typeof moduleId !== \"string\" || !moduleId || moduleId.length > MAX_FIELD) throw new Error(\"attestation: bad module_id\");\n const digest = m.get(\"digest\");\n if (digest !== \"SHA384\") throw new Error(`attestation: unexpected digest ${digest}`);\n const timestamp = m.get(\"timestamp\");\n if (typeof timestamp !== \"number\" || !(timestamp > 0)) throw new Error(\"attestation: bad timestamp\");\n const pcrsMap = m.get(\"pcrs\");\n if (!(pcrsMap instanceof Map) || pcrsMap.size < 1 || pcrsMap.size > 32) throw new Error(\"attestation: bad pcrs\");\n const pcrs = {};\n for (const [k, v] of pcrsMap) {\n if (!Number.isInteger(k) || k < 0 || k > 31) throw new Error(\"attestation: bad PCR index\");\n if (!isBytes(v) || v.length !== 32 && v.length !== 48 && v.length !== 64) throw new Error(`attestation: bad PCR${k}`);\n pcrs[k] = toHex(v);\n }\n const certificate = m.get(\"certificate\");\n if (!isBytes(certificate) || !certificate.length) throw new Error(\"attestation: missing certificate\");\n const cabundle = m.get(\"cabundle\");\n if (!Array.isArray(cabundle) || !cabundle.length || cabundle.length > MAX_CABUNDLE) throw new Error(\"attestation: bad cabundle\");\n for (const c of cabundle) if (!isBytes(c) || !c.length) throw new Error(\"attestation: bad cabundle entry\");\n return {\n moduleId,\n timestamp,\n digest,\n pcrs,\n certificate,\n cabundle,\n publicKey: optBytes(m, \"public_key\"),\n userData: optBytes(m, \"user_data\"),\n nonce: optBytes(m, \"nonce\")\n };\n}\nfunction acceptedSet(pin, label = \"pin\") {\n const list = (Array.isArray(pin) ? pin : [pin]).map((h) => String(h).toLowerCase());\n if (!list.length) throw new Error(`attestation: ${label} pins an empty set — that is not a check`);\n if (list.length > MAX_PIN_SET) throw new Error(`attestation: ${label} pins ${list.length} values; at most ${MAX_PIN_SET} (a rollover is {outgoing, incoming})`);\n return list;\n}\nasync function verifyAttestation(cose, { root, now = Date.now(), maxAgeMs = 0, expectedPCRs = null, nonce = null, atDocTime = false, clockBoundMs = 0 } = {}) {\n const raw = cose instanceof Uint8Array ? cose : new Uint8Array(cose);\n if (!raw.length || raw.length > MAX_DOC) throw new Error(\"attestation: implausible document size\");\n const cs = decode(raw);\n if (!Array.isArray(cs) || cs.length !== 4) throw new Error(\"attestation: not a COSE_Sign1 structure\");\n const [protectedBytes, unprotected, payloadBytes, signature] = cs;\n if (!isBytes(protectedBytes) || !isBytes(payloadBytes) || !isBytes(signature)) throw new Error(\"attestation: malformed COSE_Sign1\");\n if (!(unprotected instanceof Map)) throw new Error(\"attestation: malformed COSE header\");\n const ph = protectedBytes.length ? decode(protectedBytes) : /* @__PURE__ */ new Map();\n if (!(ph instanceof Map) || ph.get(1) !== COSE_ALG_ES384) throw new Error(\"attestation: protected header must specify ES384\");\n if (signature.length !== 96) throw new Error(\"attestation: ES384 signature must be 96 bytes\");\n const doc = parseDocument(payloadBytes);\n const anchor = root ? root instanceof Uint8Array ? root : new Uint8Array(root) : b64ToBytes(NITRO_ROOT_G1_B64);\n const leaf = await verifyChain([anchor, ...doc.cabundle.slice(1), doc.certificate], { now: atDocTime && Number.isFinite(doc.timestamp) ? doc.timestamp : now });\n const ok = await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-384\" },\n await importSpki(leaf),\n signature,\n sigStructure(protectedBytes, payloadBytes)\n );\n if (!ok) throw new Error(\"attestation: COSE signature does not verify under the leaf certificate\");\n if (atDocTime && clockBoundMs > 0 && Number.isFinite(doc.timestamp) && Math.abs(now - doc.timestamp) > clockBoundMs) {\n const h = Math.round(Math.abs(now - doc.timestamp) / 36e5);\n const e = new Error(`attestation: this device's clock is about ${h} hour${h === 1 ? \"\" : \"s\"} off the enclave's — check the date and time settings`);\n e.code = \"clock_off\";\n throw e;\n }\n if (maxAgeMs > 0 && now - doc.timestamp > maxAgeMs) {\n throw new Error(`attestation: document is ${Math.round((now - doc.timestamp) / 1e3)}s old`);\n }\n if (nonce) {\n const want = typeof nonce === \"string\" ? new TextEncoder().encode(nonce) : new Uint8Array(nonce);\n if (!doc.nonce || !bytesEqual(doc.nonce, want)) throw new Error(\"attestation: nonce does not match the challenge\");\n }\n if (expectedPCRs) {\n const wanted = Object.entries(expectedPCRs);\n if (!wanted.length) throw new Error(\"attestation: expectedPCRs was empty — that is not a check\");\n for (const [idx, pin] of wanted) {\n const n = Number(idx);\n if (!Number.isInteger(n) || n < 0 || n > 31) {\n throw new Error(`attestation: expectedPCRs key ${JSON.stringify(idx)} is not a PCR index (0-31)`);\n }\n const accepted = acceptedSet(pin, `PCR${idx}`);\n const got = doc.pcrs[n];\n if (!got) throw new Error(`attestation: PCR${idx} is absent from the document`);\n if (!accepted.includes(got)) throw new Error(`attestation: PCR${idx} mismatch\n expected ${accepted.join(\" or \")}\n got ${got}`);\n }\n }\n return { ok: true, ...doc, leaf };\n}\nvar NITRO_ROOT_G1_B64, COSE_ALG_ES384, MAX_DOC, MAX_FIELD, MAX_CABUNDLE, toHex, isBytes, optBytes, MAX_PIN_SET;\nvar init_nitroVerify = __esm({\n \"spaces/public/sdk/4.7.1/nitroVerify.js\"() {\n init_cbor();\n init_x509();\n NITRO_ROOT_G1_B64 = \"MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTELMAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYDVQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4MTQyODA1WjBJMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEGBSuBBAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSksfbb48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ3BABIeTPYwEoCWZEh8l5YoQwTcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkFR+eWw5b6cp3PmanfS5YwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPWrfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6NIwLz3/Y=\";\n COSE_ALG_ES384 = -35;\n MAX_DOC = 1 << 20;\n MAX_FIELD = 1024;\n MAX_CABUNDLE = 8;\n toHex = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n isBytes = (x) => x instanceof Uint8Array;\n optBytes = (m, k) => {\n const v = m.get(k);\n if (v === null || v === void 0) return null;\n if (!isBytes(v) || v.length > MAX_FIELD) throw new Error(`attestation: bad ${k}`);\n return v.length ? v : null;\n };\n MAX_PIN_SET = 2;\n }\n});\n\n// spaces/public/sdk/4.7.1/sealShare.js\nasync function sealTo2(enclaveKey, nonce, bundle) {\n const eph = await crypto.subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-384\" }, true, [\"deriveBits\"]);\n const shared = await crypto.subtle.deriveBits({ name: \"ECDH\", public: enclaveKey }, eph.privateKey, 384);\n const hk = await crypto.subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n const key = await crypto.subtle.deriveKey({ name: \"HKDF\", hash: \"SHA-256\", salt: nonce, info: enc8.encode(\"witbitz-cc share v1\") }, hk, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\"]);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: nonce }, key, enc8.encode(JSON.stringify(bundle))));\n const epk = new Uint8Array(await crypto.subtle.exportKey(\"raw\", eph.publicKey));\n return { epk: b646(epk), iv: b646(iv), ct: b646(ct), nonce: b646(nonce) };\n}\nvar enc8, b646;\nvar init_sealShare = __esm({\n \"spaces/public/sdk/4.7.1/sealShare.js\"() {\n enc8 = new TextEncoder();\n b646 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)));\n }\n});\n\n// spaces/public/sdk/4.7.1/cloudDevicePins.js\nvar CLOUD_DEVICE_PCR0;\nvar init_cloudDevicePins = __esm({\n \"spaces/public/sdk/4.7.1/cloudDevicePins.js\"() {\n CLOUD_DEVICE_PCR0 = Object.freeze([\"d89c0daf2290536038265b116f4e66fd350c342203c6e6624153596d63c96ebcc57e8e9482afd274a6e0c260f2f22829\"]);\n }\n});\n\n// spaces/public/sdk/4.7.1/sentinelRelease.js\nfunction chainFromSite({ fetchFn = typeof fetch === \"function\" ? fetch : null, urls = CHAIN_URLS } = {}) {\n if (!fetchFn) return Promise.resolve([]);\n const own = fetchFn === globalThis.fetch && urls === CHAIN_URLS;\n if (own && typeof process !== \"undefined\" && process.env && process.env.NODE_TEST_CONTEXT) return Promise.resolve([]);\n if (!own) return readChain(fetchFn, urls);\n return _siteChain || (_siteChain = readChain(fetchFn, urls).then((l) => {\n if (!l.length) _siteChain = null;\n return l;\n }));\n}\nfunction readChain(fetchFn, urls) {\n return (async () => {\n for (const u of urls) {\n try {\n const res = await fetchFn(u, { cache: \"no-store\" });\n if (!res || res.status !== 200 || /text\\/html/.test(res.headers && res.headers.get && res.headers.get(\"content-type\") || \"\")) continue;\n const l = linksOfLogText(await res.text());\n if (l.length) return l;\n } catch {\n }\n }\n return [];\n })();\n}\nfunction linksOfLogText(text) {\n const out = [];\n for (const l of String(text || \"\").split(\"\\n\")) {\n try {\n const r = JSON.parse(l);\n if (r && r.subject === \"build-enclave\" && r.verdict === \"pass\") out.push(r);\n } catch {\n }\n }\n return out.reverse();\n}\nasync function trustedBuilders(links = [], { anchors = BUILD_ENCLAVE_PCR0, deny = BUILD_ENCLAVE_DENY, verify = verifyAttestation, max = LINKS_MAX } = {}) {\n const denied = new Set((deny || []).map((x) => String(x).toLowerCase()));\n const trusted = new Set((anchors || []).map((x) => String(x).toLowerCase()).filter((x) => !denied.has(x)));\n const cache = verify === verifyAttestation;\n let pending = Array.isArray(links) ? links.slice(0, max) : [];\n for (let grew = true; grew && pending.length; ) {\n grew = false;\n const left = [];\n for (const l of pending) {\n try {\n const sig = l && l.signature && typeof l.signature.sig === \"string\" ? l.signature.sig : \"\";\n const known = sig && cache ? verified.get(sig) : null;\n let p;\n if (known && trusted.has(known.builder) && String(l.measurement && l.measurement.pcr0 || \"\").toLowerCase() === known.pcr0) p = known.pcr0;\n else {\n const got = await recordPcrBy(l, \"build-enclave\", [...trusted], verify);\n p = got.pcr0;\n if (sig && cache) {\n if (verified.size >= 4096) verified.delete(verified.keys().next().value);\n verified.set(sig, got);\n }\n }\n if (!denied.has(p) && !trusted.has(p)) {\n trusted.add(p);\n grew = true;\n }\n } catch (e) {\n if (/not made by a build enclave this app trusts/.test(String(e && e.message || e))) left.push(l);\n }\n }\n pending = left;\n }\n return [...trusted];\n}\nasync function recordPcrBy(r, subject, builders, verify = verifyAttestation) {\n if (!r || typeof r !== \"object\") throw new Error(\"no release record came with the attestation\");\n if (r.subject !== subject || r.verdict !== \"pass\") throw new Error(`the record is not a passing ${subject} release`);\n const repro = Array.isArray(r.checks) && r.checks.find((c) => c && c.name === \"reproducible-build\");\n if (!repro || repro.ok !== true) throw new Error(\"the record does not say the image was rebuilt from its source\");\n const pcr0 = String(r.measurement && r.measurement.pcr0 || \"\").toLowerCase();\n if (!/^[0-9a-f]{96}$/.test(pcr0) || r.claim && String(r.claim.pcr0 || \"\").toLowerCase() !== pcr0) throw new Error(\"the record names no single PCR0\");\n if (!r.attestation || !r.attestation.doc || !r.signature || !r.signature.key || !r.signature.sig) throw new Error(\"the record carries no proof\");\n const rest = {};\n for (const [k, v] of Object.entries(r)) if (!PROOFS.includes(k)) rest[k] = v;\n const art = enc9.encode(JSON.stringify(rest));\n const doc = await verify(unb642(r.attestation.doc), { atDocTime: true });\n const builder = String(doc.pcrs && doc.pcrs[0] || \"\").toLowerCase();\n if (!builders.includes(builder)) throw new Error(\"the record was not made by a build enclave this app trusts\");\n const want = enc9.encode(JSON.stringify({ role: \"build-enclave\", verdict: hex3(await crypto.subtle.digest(\"SHA-256\", art)) }));\n if (!doc.userData || !same(new Uint8Array(doc.userData), want)) throw new Error(\"the build enclave's attestation is not for this record\");\n const spki = unb642(r.signature.key);\n if (!doc.publicKey || !same(new Uint8Array(doc.publicKey), spki)) throw new Error(\"the record is not signed by the key the build enclave attested\");\n const key = await crypto.subtle.importKey(\"spki\", spki, { name: \"ECDSA\", namedCurve: \"P-256\" }, false, [\"verify\"]);\n const ok = await crypto.subtle.verify({ name: \"ECDSA\", hash: \"SHA-256\" }, key, derSigToRaw(unb642(r.signature.sig), 32), art);\n if (!ok) throw new Error(\"the record's signature does not verify\");\n return { pcr0, builder };\n}\nvar BUILD_ENCLAVE_PCR0, enc9, unb642, hex3, same, PROOFS, _siteChain, CHAIN_URLS, BUILD_ENCLAVE_DENY, LINKS_MAX, verified;\nvar init_sentinelRelease = __esm({\n \"spaces/public/sdk/4.7.1/sentinelRelease.js\"() {\n init_nitroVerify();\n init_x509();\n BUILD_ENCLAVE_PCR0 = Object.freeze([\n \"c6a8cbd0c05d8e003e75b266f1dde2a6426b7cd61f845e4b128e59063e40968b44f30d934bbe1925582fe33bbdd0b1d7\",\n \"f490096d57e4287146e8b8d7bf4c75f423984ca52199efab0ee8684fbee6cfe6ab82c72d54f05a38f24a0d4ad6e2f557\",\n \"41ec7e0e54beac5759fba7efa06c48081dbd96c7299c29c92a9c619036ce057cec357ad4ad71a165d7f881df120b043b\",\n \"9f0801335a952bdbac70b6793150738d7ce30bc3a0d520fec6f573de22a822aa5ef762f78648bc8608ca0b2eeccda556\",\n \"a145e8524bbe8764d4db6b81b4e18d72eae42e8b9e1c834e62e22aba18cce318f9eaa84942671c688c3eeb89ec30b0e8\",\n \"5d29c3691cd38f6c6ce0da2b2f9d1da82712d9da12a89c99d38a03cae6369ebe6ba7a1ab1060cfa9daf6a19228c7a2dc\",\n \"6c962286faed81c395bcf3d319011f91893cfec723c2dc7069ad8805980d77e99f75c94671881cc793794521fe5d2ff0\",\n \"578945d0342d346d72e50b36ffe74a3631e53e111bc010394108457e362d10830ebadcc7ec5ffa4445d5b10b9c522d28\",\n \"7e9f760db923c6f31fd18db06f6b60a53902beb6b0d80b91b5355d33c461e43bcddc31c08e2380ff9dc75c10909e6acb\",\n \"5b6bffe6953eef271a69e453072b6e202ae024cd3983fff3a637b7421a60ad92ab3fd19f8ae809e19182a3feebbe94c2\",\n \"551006e397efd43a619b370ef336a6a594d8a8338cd49860e54845330354c73afd3ba673360d50f78e5f1d702e19946b\",\n \"eecf817c561e633b30632ca434a28ad56ed46395d765172fedcc0742d8d5c9982845d6ce32b6451b943f4b6f0a55ea36\",\n \"3df18dce5385b467208bfa325d2f812bd622ef6def87ef97e63116310a896427db9f2c69d7c2631bccc9c65549b3d512\",\n \"a51fcaeafa6d188b46d11710442f981169304aa4feecc4b40263943966c3dd8ff9b986d30989b4152fa1540c85a76b5e\",\n \"f977e0490f5abfc77c311b426399bddd6909848bb8175db4142885c839e9cc23c3ca0047317b039883dce4b1a2efe096\",\n \"d5f13dff5647f5f4ee351dd9e1ba9348ecd39da88acd6ffd9c324897b0ca7563da974b08c2e84504a76dc98b48700b74\",\n \"2babe4262b2a00949eeef5b04a81327eb606dc347caaf507527d04f8847730a31dd26d6d7be3e0a672c537b51c914133\",\n \"25a0967ec1366bc0ec43e45e2f89c435adb1a3e54d8702d89599acb442337afcb36f8f64d51a6608cefb3bb1e4f6b8ed\",\n \"8665867cbb86ea3178f4179cf040fdec9e6df22bdd4f1e3d8df6b2d9096db5aecd8420b42203969bbe9446b585c78870\",\n \"ef738ca713ddc39dc29505d857c2aac22a0598a714163ae01e2879085e1c262cc5bde3c239b7ce76385d10c5910ed487\",\n \"41de07c0c12f388f9dc7d87cfa835edce2c58be42f6893f227002329d263285bf78bb209cd69c384dd7566097f2a3d47\",\n \"a77141c4ac00099cbdd9053e0190b70234aa2eccdb22cb358e9b8b0fef5bef6b7ad6d9b5eb73137244a3790f98869505\",\n \"70dde35fed128d1cb007f8c6edfa3de70e991955e1748aa500ad4685d1c752b1775565fb9a6d11c483969d5596e3b159\",\n \"f0ea83ee58b3a4a9ebe7c8c74f102eba17118711573b6ce773b6f31ed223564cbf215992b5a7a30462b70281ae624453\",\n \"f7adfbec8cf3a014f9585c7decc21bb03a50484339811ea3b44947d23fc16aff8eedb56346915b816e83fc5faad55e7a\",\n \"917f7d95eabd64eabd1145cc0898c08ff414037775fd416162002c4783b4f95dcb550c3c5493baadaf41eaceb0e7da0d\",\n \"74b1cbd4398f319a636de05d36eaa40953df4dc0bb86769f7ac4e0fe2c576f55b3c4a15a5583048ded80b0b4d303f55e\",\n \"420088665bd62edcba51dfbcc55cbc85611529985fde54b655a3476198a8f9421e02d1898db28180b153550ceeb66798\"\n ]);\n enc9 = new TextEncoder();\n unb642 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0));\n hex3 = (u8) => [...new Uint8Array(u8)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);\n PROOFS = [\"attestation\", \"signature\", \"rekor\"];\n _siteChain = null;\n CHAIN_URLS = Object.freeze([\"https://api.witbitz.chat/v1/trust/build-enclave.jsonl\", \"/audit/releases/build-enclave.jsonl\"]);\n BUILD_ENCLAVE_DENY = Object.freeze([]);\n LINKS_MAX = 4;\n verified = /* @__PURE__ */ new Map();\n }\n});\n\n// spaces/public/sdk/4.7.1/followImage.js\nfunction recordsOfLogText(text, subject) {\n const out = [];\n for (const l of String(text || \"\").split(\"\\n\")) {\n try {\n const r = JSON.parse(l);\n if (r && typeof r === \"object\" && r.subject === subject && r.verdict === \"pass\") out.push(r);\n } catch {\n }\n }\n return out.reverse();\n}\nfunction subjectLog(subject, { fetchFn = typeof fetch === \"function\" ? fetch : null } = {}) {\n if (!fetchFn || !FOLLOWED_SUBJECTS.includes(subject)) return Promise.resolve([]);\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_TEST_CONTEXT && fetchFn === globalThis.fetch) return Promise.resolve([]);\n if (!_logs.has(subject)) {\n _logs.set(subject, (async () => {\n for (const u of [TRUST_BASE + subject + \".jsonl\", \"/audit/releases/\" + subject + \".jsonl\"]) {\n try {\n const res = await fetchFn(u, { cache: \"no-store\" });\n if (!res || res.status !== 200 || /text\\/html/.test(res.headers && res.headers.get && res.headers.get(\"content-type\") || \"\")) continue;\n const l = recordsOfLogText(await res.text(), subject);\n if (l.length) return l;\n } catch {\n }\n }\n return [];\n })().then((l) => {\n if (!l.length) _logs.delete(subject);\n return l;\n }));\n }\n return _logs.get(subject);\n}\nasync function followedImageRecords(subject, { window: window2 = FOLLOW_WINDOW, fetchFn, verify = verifyAttestation, builders = null, records = null } = {}) {\n try {\n const recs = records || await subjectLog(subject, fetchFn ? { fetchFn } : {});\n if (!recs.length) return [];\n const trusted = builders || await trustedBuilders(await chainFromSite(fetchFn ? { fetchFn } : {}), { anchors: BUILD_ENCLAVE_PCR0, verify, max: Infinity });\n const deny = IMAGE_DENY[subject] || [];\n const out = [];\n for (const r of recs) {\n if (out.length >= window2) break;\n try {\n const { pcr0 } = await recordPcrBy(r, subject, trusted, verify);\n if (!deny.includes(pcr0) && !out.some((x) => x.pcr0 === pcr0)) out.push({ pcr0, measurement: r.measurement || {} });\n } catch {\n }\n }\n return out;\n } catch {\n return [];\n }\n}\nasync function followedImages(subject, opts = {}) {\n return (await followedImageRecords(subject, opts)).map((x) => x.pcr0);\n}\nvar FOLLOW_WINDOW, FOLLOWED_SUBJECTS, IMAGE_DENY, TRUST_BASE, _logs;\nvar init_followImage = __esm({\n \"spaces/public/sdk/4.7.1/followImage.js\"() {\n init_sentinelRelease();\n init_nitroVerify();\n FOLLOW_WINDOW = 2;\n FOLLOWED_SUBJECTS = Object.freeze([\"cloud-device\", \"tools-enclave\"]);\n IMAGE_DENY = Object.freeze({ \"cloud-device\": Object.freeze([]), \"tools-enclave\": Object.freeze([]) });\n TRUST_BASE = \"https://api.witbitz.chat/v1/trust/\";\n _logs = /* @__PURE__ */ new Map();\n }\n});\n\n// spaces/public/sdk/4.7.1/cloudDeviceSeal.js\nvar cloudDeviceSeal_exports = {};\n__export(cloudDeviceSeal_exports, {\n cloudDeviceCall: () => cloudDeviceCall\n});\nasync function cloudDeviceCall(post, cd, idToken, { pins = CLOUD_DEVICE_PCR0, verify = verifyAttestation, now, follow = followedImages } = {}) {\n if (!pins || !pins.length) return refuse(\"no_pins\", \"This app names no cloud device build, so nothing was sent to it.\");\n const nonce = crypto.getRandomValues(new Uint8Array(32));\n const a = await post({ op: \"clouddevice\", cd: { t: \"attest\", nonce: b647(nonce) }, idToken });\n if (!a || a.status !== 200 || typeof a.doc !== \"string\") return a && a.status && a.status !== 200 ? a : refuse(a && a.error || \"attest_failed\", \"The cloud device could not show what it runs.\");\n let doc;\n const check = (list) => verify(unb643(a.doc), { nonce, expectedPCRs: { 0: [...list] }, maxAgeMs: 5 * 6e4, ...now ? { now } : {} });\n try {\n doc = await check(pins);\n } catch (e) {\n const more = follow ? (await follow(\"cloud-device\")).filter((p) => !pins.includes(p)) : [];\n let last = e;\n for (const p of more) {\n try {\n doc = await check([p]);\n break;\n } catch (ex) {\n last = ex;\n }\n }\n try {\n if (!doc) throw last;\n } catch (e2) {\n return refuse(\"attestation\", \"The cloud device is not running the published Witbitz image, so nothing was sent to it.\", 502, e2 && e2.message || e2);\n }\n }\n let said = null;\n try {\n said = JSON.parse(new TextDecoder().decode(doc.userData || new Uint8Array(0)));\n } catch {\n said = null;\n }\n if (!said || said.role !== \"clouddevice\" || !doc.publicKey) return refuse(\"attestation\", \"The attestation does not name a cloud device, so nothing was sent to it.\", 502, \"role \" + (said && said.role));\n const key = await crypto.subtle.importKey(\"spki\", doc.publicKey, { name: \"ECDH\", namedCurve: \"P-384\" }, false, []);\n const answerRaw = crypto.getRandomValues(new Uint8Array(32));\n const hint = a.hint && typeof a.hint === \"object\" ? a.hint : null;\n const sealed = await sealTo2(key, nonce, { ...cd, idToken, ...hint ? { hint } : {}, answerKey: b647(answerRaw) });\n const r = await post({ op: \"clouddevice\", cd: { t: \"sealed\", sealed }, idToken });\n if (!r || r.status !== 200) return r;\n if (!r.sealed || typeof r.sealed.iv !== \"string\" || typeof r.sealed.ct !== \"string\") return r.ok === false ? { status: 200, ok: false, error: r.error, message: r.message } : refuse(\"unsealed\", \"The cloud device's answer was not sealed to this request.\");\n let ans;\n try {\n const k = await crypto.subtle.importKey(\"raw\", answerRaw, \"AES-GCM\", false, [\"decrypt\"]);\n ans = JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: unb643(r.sealed.iv) }, k, unb643(r.sealed.ct))));\n } catch {\n return refuse(\"unsealed\", \"The cloud device's answer did not open.\");\n }\n const { re: _re, ...rest } = ans || {};\n return { status: 200, ...rest };\n}\nvar b647, unb643, refuse;\nvar init_cloudDeviceSeal = __esm({\n \"spaces/public/sdk/4.7.1/cloudDeviceSeal.js\"() {\n init_nitroVerify();\n init_sealShare();\n init_cloudDevicePins();\n init_followImage();\n b647 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)));\n unb643 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0));\n refuse = (error, message, status = 502, detail = \"\") => ({ status, ok: false, error, message, ...detail ? { detail: String(detail).slice(0, 200) } : {} });\n }\n});\n\n// spaces/public/sdk/4.7.1/opRouting.js\nfunction routingIndex(op) {\n switch (op) {\n case \"turn\":\n return 2;\n case \"decide\":\n return 3;\n case \"carry\":\n case \"toolRules\":\n return 0;\n default:\n return -1;\n }\n}\n\n// spaces/public/sdk/4.7.1/prefetchPoll.js\nvar PREFETCH_MAX_AGE_MS = 15 * 60 * 1e3;\nasync function prefetchHashKey(room) {\n const d = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(\"wb-prefetch\\n\" + String(room || \"\"))));\n return \"prefetch:h:\" + Array.from(d.slice(0, 16), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\nfunction prefetchUsable(pf, sinceCount, now = Date.now()) {\n if (!pf || typeof pf !== \"object\" || !pf.r || typeof pf.r !== \"object\") return \"none\";\n if (!Number.isFinite(pf.at) || now - pf.at > PREFETCH_MAX_AGE_MS) return \"stale\";\n if (pf.tail) {\n if (!Number.isInteger(pf.sinceCount) || pf.sinceCount > (sinceCount | 0) || !Number.isInteger(pf.r.count) || (sinceCount | 0) > pf.r.count) return \"position moved\";\n } else if (!Number.isInteger(pf.sinceCount) || pf.sinceCount !== (sinceCount | 0)) return \"position moved\";\n if (!pf.r.changed || typeof pf.r.sealed !== \"string\") return \"nothing new in it\";\n return \"\";\n}\nfunction positionOf(result) {\n if (!result || result.status !== 200 || !Number.isInteger(result.version)) return null;\n return { etag: typeof result.etag === \"string\" ? result.etag : \"\", count: result.version, at: Date.now() };\n}\nfunction prefetchAnswer(pf, sinceCount) {\n let r0 = pf && pf.r && typeof pf.r === \"object\" ? pf.r : null;\n if (!r0) return null;\n if (pf.tail && Number.isInteger(sinceCount) && sinceCount > pf.sinceCount) {\n let sl = null;\n try {\n sl = JSON.parse(r0.sealed);\n } catch {\n return null;\n }\n if (!sl || !Array.isArray(sl.boxes) || sl.from !== pf.sinceCount || sinceCount > sl.from + sl.boxes.length) return null;\n r0 = { ...r0, sealed: JSON.stringify({ ...sl, boxes: sl.boxes.slice(sinceCount - sl.from), from: sinceCount }), from: sinceCount };\n }\n const { partialStatus, partial, partialSeq, ...r } = r0;\n return Number.isInteger(r.status) ? r : { status: 200, ...r };\n}\n\n// spaces/public/sdk/4.7.1/connectionEntry.js\nvar MCP_TOOLS_PER_SERVER = 40;\nvar TOOL_NAME = /^[A-Za-z0-9_.-]{1,64}$/;\nvar isObj = (v) => v && typeof v === \"object\" && !Array.isArray(v);\nfunction roomTool(t) {\n if (!isObj(t) || !TOOL_NAME.test(String(t.name || \"\"))) return null;\n const schema = isObj(t.inputSchema) && JSON.stringify(t.inputSchema).length <= 8192 ? t.inputSchema : { type: \"object\", properties: {} };\n return { name: String(t.name), title: String(t.title || \"\").slice(0, 120), description: String(t.description || \"\").slice(0, 1e3), inputSchema: schema, readOnly: t.readOnly === true };\n}\nvar JOB_FIELD = /^[A-Za-z_][A-Za-z0-9_]{0,23}$/;\nvar JOB_HEADER = /^[a-z0-9][a-z0-9-]{0,39}$/;\nvar JOB_HEADER_DROP = /* @__PURE__ */ new Set([\"authorization\", \"cookie\", \"host\", \"connection\", \"content-length\", \"transfer-encoding\", \"x-api-key\", \"webhook-id\", \"webhook-timestamp\", \"webhook-signature\"]);\nfunction roomJob(j) {\n if (!isObj(j)) return null;\n const headers = {};\n for (const [k, v] of Object.entries(isObj(j.headers) ? j.headers : {}).slice(0, 6)) {\n const lk = String(k).toLowerCase();\n if (JOB_HEADER.test(lk) && !JOB_HEADER_DROP.has(lk) && !lk.startsWith(\"x-witbitz-\") && typeof v === \"string\" && v.length <= 200 && !/[\\r\\n]/.test(v)) headers[lk] = v;\n }\n return { field: JOB_FIELD.test(String(j.field || \"\")) ? String(j.field) : \"text\", headers };\n}\nfunction roomConnection(x) {\n if (!isObj(x) || !x.id || !x.account || !x.callKey) return null;\n const out = { account: String(x.account), id: String(x.id), callKey: String(x.callKey), label: String(x.label || \"\").slice(0, 80), host: String(x.host || \"\") };\n if (typeof x.webhook === \"string\" && /^\\/[^\\s?#]{1,199}$/.test(x.webhook)) out.webhook = x.webhook;\n if (out.webhook && isObj(x.job)) out.job = roomJob(x.job);\n if (isObj(x.mcp) && Array.isArray(x.mcp.tools)) {\n const tools = x.mcp.tools.map(roomTool).filter(Boolean).slice(0, MCP_TOOLS_PER_SERVER);\n const names = new Set(tools.map((t) => t.name));\n if (tools.length) {\n out.mcp = {\n tools,\n auto: (Array.isArray(x.mcp.auto) ? x.mcp.auto.map(String) : []).filter((n) => names.has(n)),\n ...x.mcp.own === true ? { own: true } : {},\n ...Number.isFinite(x.mcp.listedAt) ? { listedAt: x.mcp.listedAt } : {},\n // THE TOOL BOOK (agent/toolBook.mjs): the tools' descriptions and schemas, stored once in the room — the entry keeps names\n ...isObj(x.mcp.book) && /^i_[A-Za-z0-9_-]{8,64}$/.test(String(x.mcp.book.ref || \"\")) && /^[0-9a-f]{64}$/.test(String(x.mcp.book.sha256 || \"\")) ? { book: { ref: x.mcp.book.ref, sha256: x.mcp.book.sha256 } } : {}\n };\n }\n }\n if (x.reads === \"auto\" && !out.mcp) out.reads = \"auto\";\n return out;\n}\nfunction applyConnectionsPatch(cur, c) {\n const list = Array.isArray(cur) ? cur : [];\n const v = c == null ? null : Array.isArray(c) ? c : c.add ? [...list.filter((x) => x && x.id !== c.add.id), c.add] : c.remove ? list.filter((x) => x && x.id !== c.remove) : c.update && c.update.id ? list.map((x) => x && x.id === c.update.id ? { ...x, ...\"mcp\" in c.update ? { mcp: c.update.mcp } : {}, ...\"reads\" in c.update ? { reads: c.update.reads } : {} } : x) : list;\n return v == null ? void 0 : v.map(roomConnection).filter(Boolean).slice(0, 32);\n}\n\n// spaces/public/sdk/4.7.1/e2ee.js\nvar VERSION = 1;\nvar enc = new TextEncoder();\nvar dec = new TextDecoder();\nvar ledgerAad = (room, index) => enc.encode(\"v3\u001f\" + String(room) + \"\u001f\" + String(index));\nfunction b64(bytes3) {\n const b = bytes3 instanceof Uint8Array ? bytes3 : new Uint8Array(bytes3);\n let s = \"\";\n for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\nfunction ub64(str) {\n let s = String(str || \"\").replace(/-/g, \"+\").replace(/_/g, \"/\");\n s += \"=\".repeat((4 - s.length % 4) % 4);\n const bin = atob(s);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\nasync function roomWrapKey(mk) {\n const ikm = await crypto.subtle.importKey(\"raw\", ub64(mk), \"HKDF\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: enc.encode(\"memwrap\") }, ikm, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n}\nfunction newKey() {\n return b64(crypto.getRandomValues(new Uint8Array(32)));\n}\nasync function commit(mk) {\n const h = await crypto.subtle.digest(\"SHA-256\", enc.encode(String(mk || \"\")));\n return b64(new Uint8Array(h));\n}\nfunction splitKey(mk) {\n const k = ub64(mk);\n if (!k.length) throw new Error(\"splitKey needs a key\");\n const a = crypto.getRandomValues(new Uint8Array(k.length));\n const b = new Uint8Array(k.length);\n for (let i = 0; i < k.length; i++) b[i] = k[i] ^ a[i];\n return { shareA: b64(a), shareB: b64(b) };\n}\nfunction combineShares(shareA, shareB) {\n const a = ub64(shareA || \"\");\n const b = ub64(shareB || \"\");\n if (!a.length || a.length !== b.length) return null;\n const mk = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) mk[i] = a[i] ^ b[i];\n return b64(mk);\n}\nasync function wrapSym(key, cek) {\n const wk = await roomWrapKey(key);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const w = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, wk, cek));\n return { iv: b64(iv), w: b64(w) };\n}\nasync function seal(plaintext, recipients = {}) {\n const entries = Object.entries(recipients).filter(([, k]) => typeof k === \"string\" && k);\n if (!entries.length) throw new Error(\"seal needs at least one recipient key, e.g. { room: mk }\");\n const cek = crypto.getRandomValues(new Uint8Array(32));\n const cekKey = await crypto.subtle.importKey(\"raw\", cek, { name: \"AES-GCM\" }, false, [\"encrypt\"]);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, cekKey, enc.encode(String(plaintext))));\n const out = {};\n for (const [slot, key] of entries) out[slot] = await wrapSym(key, cek);\n return { v: VERSION, iv: b64(iv), ct: b64(ct), recipients: out };\n}\nasync function open(envelope, { mk, aad = null } = {}) {\n if (!isEnvelope(envelope) || !mk) return null;\n if (envelope.aad && !aad) return null;\n const wk = await roomWrapKey(mk);\n for (const slot of Object.keys(envelope.recipients)) {\n const r = envelope.recipients[slot];\n if (!r || typeof r.iv !== \"string\" || typeof r.w !== \"string\") continue;\n try {\n const cek = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: ub64(r.iv) }, wk, ub64(r.w)));\n const cekKey = await crypto.subtle.importKey(\"raw\", cek, { name: \"AES-GCM\" }, false, [\"decrypt\"]);\n const p = { name: \"AES-GCM\", iv: ub64(envelope.iv) };\n if (envelope.aad) p.additionalData = aad;\n const pt = new Uint8Array(await crypto.subtle.decrypt(p, cekKey, ub64(envelope.ct)));\n return dec.decode(pt);\n } catch {\n }\n }\n return null;\n}\nfunction isEnvelope(o) {\n return !!(o && typeof o === \"object\" && o.v === VERSION && typeof o.iv === \"string\" && typeof o.ct === \"string\" && o.recipients && typeof o.recipients === \"object\" && Object.values(o.recipients).some((r) => r && typeof r.iv === \"string\" && typeof r.w === \"string\"));\n}\nvar EC = { name: \"ECDH\", namedCurve: \"P-256\" };\nasync function boxKey(priv, pubJwk) {\n const privKey = priv && priv.kty ? await crypto.subtle.importKey(\"jwk\", priv, EC, false, [\"deriveBits\"]) : priv;\n const pub = await crypto.subtle.importKey(\"jwk\", pubJwk, EC, false, []);\n const bits = await crypto.subtle.deriveBits({ name: \"ECDH\", public: pub }, privKey, 256);\n const ikm = await crypto.subtle.importKey(\"raw\", bits, \"HKDF\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: enc.encode(\"sealedbox\") }, ikm, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n}\nasync function sealTo(plaintext, recipientPublicJwk) {\n if (!recipientPublicJwk) throw new Error(\"sealTo needs the recipient public key\");\n const eph = await crypto.subtle.generateKey(EC, true, [\"deriveBits\"]);\n const key = await boxKey(eph.privateKey, recipientPublicJwk);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, enc.encode(String(plaintext))));\n const epk = await crypto.subtle.exportKey(\"jwk\", eph.publicKey);\n return { v: VERSION, alg: \"box\", epk: { x: epk.x, y: epk.y }, iv: b64(iv), ct: b64(ct) };\n}\n\n// spaces/public/sdk/4.7.1/shamir.js\nvar b642 = (bytes3) => btoa(String.fromCharCode.apply(null, Array.from(bytes3))).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\nvar ub642 = (s) => {\n const bin = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const a = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) a[i] = bin.charCodeAt(i);\n return a;\n};\nvar EXP = new Uint8Array(512);\nvar LOG = new Uint8Array(256);\n(function initField() {\n let x = 1;\n for (let i = 0; i < 255; i++) {\n EXP[i] = x;\n LOG[x] = i;\n let x2 = x << 1;\n if (x2 & 256) x2 ^= 283;\n x = (x2 ^ x) & 255;\n }\n for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];\n})();\nvar mul = (a, b) => a === 0 || b === 0 ? 0 : EXP[LOG[a] + LOG[b]];\nvar div = (a, b) => a === 0 ? 0 : EXP[LOG[a] + 255 - LOG[b]];\nvar rand = (n) => crypto.getRandomValues(new Uint8Array(n));\nfunction shamirSplit(mk, k, n) {\n const secret = ub642(mk);\n if (!secret.length) throw new Error(\"shamirSplit needs a key\");\n if (!(k >= 2 && k <= n && n <= 255)) throw new Error(\"need 2 ≤ k ≤ n ≤ 255\");\n const shares = [];\n for (let j = 1; j <= n; j++) shares.push({ x: j, y: new Uint8Array(secret.length) });\n for (let bi = 0; bi < secret.length; bi++) {\n const coeffs = new Uint8Array(k);\n coeffs[0] = secret[bi];\n const rc = rand(k - 1);\n for (let c = 1; c < k; c++) coeffs[c] = rc[c - 1];\n for (const s of shares) {\n let y = 0;\n for (let c = k - 1; c >= 0; c--) y = mul(y, s.x) ^ coeffs[c];\n s.y[bi] = y;\n }\n }\n return shares.map((s) => b642(Uint8Array.of(s.x, ...s.y)));\n}\nfunction shamirCombine(shareStrings) {\n const pts = (shareStrings || []).map((s) => {\n const a = ub642(s);\n return { x: a[0], y: a.slice(1) };\n }).filter((p) => p.x);\n if (pts.length < 2) return null;\n const xs = pts.map((p) => p.x);\n if (new Set(xs).size !== xs.length) return null;\n const len = pts[0].y.length;\n const out = new Uint8Array(len);\n for (let bi = 0; bi < len; bi++) {\n let acc = 0;\n for (let j = 0; j < pts.length; j++) {\n let num = 1;\n let den = 1;\n for (let m = 0; m < pts.length; m++) {\n if (m === j) continue;\n num = mul(num, pts[m].x);\n den = mul(den, pts[j].x ^ pts[m].x);\n }\n acc ^= mul(pts[j].y[bi], div(num, den));\n }\n out[bi] = acc;\n }\n return b642(out);\n}\n\n// spaces/public/sdk/4.7.1/regions.js\nvar DEFAULT_REGION = \"eu\";\nvar REGIONS = Object.freeze({\n eu: Object.freeze({ aws: \"eu-central-1\" }),\n us: Object.freeze({ aws: \"us-east-1\" })\n});\nvar MARKED = /^(?:sp|tmp)-([a-z]{2})-[0-9a-z]+$/;\nfunction roomRegion(room) {\n const m = MARKED.exec(typeof room === \"string\" ? room : \"\");\n return m && Object.prototype.hasOwnProperty.call(REGIONS, m[1]) ? m[1] : DEFAULT_REGION;\n}\nfunction newRoomId(region, { prefix = \"sp\", rand: rand2 = () => crypto.getRandomValues(new Uint8Array(8)) } = {}) {\n const tail = Array.from(rand2()).map((x) => x.toString(36)).join(\"\").slice(0, 12);\n const marked = region && region !== DEFAULT_REGION && Object.prototype.hasOwnProperty.call(REGIONS, region);\n return `${prefix}-${marked ? region + \"-\" : \"\"}${tail}`;\n}\n\n// spaces/public/sdk/4.7.1/spaceConfig.js\nvar enc2 = (s) => encodeURIComponent(String(s));\nfunction normalizeKeyModel(km) {\n if (km == null || km === \"1-of-1\") return { k: 1, n: 1 };\n if (km === \"2-of-2\") return { k: 2, n: 2 };\n if (km && Number.isInteger(km.k) && Number.isInteger(km.n) && km.k >= 1 && km.k <= km.n) return { k: km.k, n: km.n };\n throw new Error(\"bad keyModel\");\n}\nasync function createConfiguredSpace(config = {}, { base = \"\" } = {}) {\n const { k, n } = normalizeKeyModel(config.keyModel);\n const mk = n === 1 && typeof config.mk === \"string\" && config.mk.length >= 40 ? config.mk : newKey();\n const room = config.room || newRoomId(config.region);\n const c = await commit(mk);\n const link = (frag) => `${String(base).replace(/\\/+$/, \"\")}/space?room=${enc2(room)}#${frag}`;\n let links;\n if (n === 1) {\n links = [link(`mk=${enc2(mk)}`)];\n } else if (k === 2 && n === 2) {\n const { shareA, shareB } = splitKey(mk);\n links = [link(`s=${enc2(shareA)}`), link(`s=${enc2(shareB)}`)];\n } else {\n links = shamirSplit(mk, k, n).map((s) => link(`s=${enc2(s)}`));\n }\n return { room, commit: c, keyModel: { k, n }, links };\n}\nasync function assembleConfiguredKey(pieces, config, expectedCommit) {\n const { k, n } = normalizeKeyModel(config && config.keyModel);\n const arr = Array.isArray(pieces) ? pieces.filter(Boolean) : pieces ? [pieces] : [];\n let mk = null;\n if (n === 1) mk = arr[0] || null;\n else if (k === 2 && n === 2) mk = arr.length >= 2 ? combineShares(arr[0], arr[1]) : null;\n else mk = arr.length >= k ? shamirCombine(arr) : null;\n if (mk == null) return null;\n if (n > 1 && !expectedCommit) return null;\n if (expectedCommit && await commit(mk) !== expectedCommit) return null;\n return mk;\n}\nfunction parseConfiguredLink(url) {\n try {\n const u = new URL(url);\n const raw = (u.hash || \"\").replace(/^#/, \"\");\n const q = raw.indexOf(\"?\");\n const frag = new URLSearchParams(q >= 0 ? raw.slice(0, q) : raw);\n return { room: u.searchParams.get(\"room\") || \"\", share: frag.get(\"s\") || \"\", mk: frag.get(\"mk\") || \"\" };\n } catch {\n return { room: \"\", share: \"\", mk: \"\" };\n }\n}\n\n// spaces/public/sdk/4.7.1/invite.js\nvar enc3 = new TextEncoder();\nvar dec2 = new TextDecoder();\nfunction newCode() {\n const A = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\n const r = crypto.getRandomValues(new Uint8Array(12));\n const s = [].slice.call(r).map((x) => A[x % A.length]).join(\"\");\n return s.slice(0, 4) + \"-\" + s.slice(4, 8) + \"-\" + s.slice(8, 12);\n}\nvar normCode = (code) => String(code || \"\").toUpperCase().replace(/[^A-Z0-9]/g, \"\");\nasync function keyFromCode(code, salt) {\n const base = await crypto.subtle.importKey(\"raw\", enc3.encode(normCode(code)), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey(\n { name: \"PBKDF2\", salt, iterations: 21e4, hash: \"SHA-256\" },\n // slow: the code is low-entropy, so make guessing costly\n base,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"]\n );\n}\nvar b643 = (bytes3) => btoa(String.fromCharCode(...bytes3)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\nvar ub643 = (s) => {\n const b = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const a = new Uint8Array(b.length);\n for (let i = 0; i < b.length; i++) a[i] = b.charCodeAt(i);\n return a;\n};\nasync function sealUnderCode(plaintext, code) {\n const salt = crypto.getRandomValues(new Uint8Array(16));\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const key = await keyFromCode(code, salt);\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, enc3.encode(String(plaintext))));\n const out = new Uint8Array(16 + 12 + ct.length);\n out.set(salt);\n out.set(iv, 16);\n out.set(ct, 28);\n return b643(out);\n}\nasync function openUnderCode(blob, code) {\n try {\n const raw = ub643(blob);\n const key = await keyFromCode(code, raw.slice(0, 16));\n const pt = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: raw.slice(16, 28) }, key, raw.slice(28));\n return dec2.decode(pt);\n } catch {\n return null;\n }\n}\n\n// spaces/public/sdk/4.7.1/enclaveAccept.js\nvar HEX48 = /^[0-9a-f]{96}$/;\nvar MODES = /* @__PURE__ */ new Set([\"follow\", \"pin\"]);\nvar STAGES = [[\"kernel\", \"0\"], [\"payload\", \"16\"], [\"policy\", \"17\"]];\nvar hex = (v, what) => {\n const h = String(v).toLowerCase();\n if (!HEX48.test(h)) throw new Error(`enclave acceptance: ${what} is not a SHA-384 hex digest`);\n return h;\n};\nvar version = (v, what) => {\n if (v === void 0 || v === null) return 0;\n if (typeof v !== \"number\" || !Number.isInteger(v) || v < 0) throw new Error(`enclave acceptance: ${what} must be a non-negative integer`);\n return v;\n};\nfunction tripleOf(att) {\n const p = att && att.pcrs || {};\n const t = {};\n for (const [name, idx] of STAGES) if (p[idx]) t[name] = String(p[idx]).toLowerCase();\n return t;\n}\nvar sameTriple = (a, b) => STAGES.every(([name]) => (a[name] || null) === (b[name] || null));\nfunction parseAcceptance(raw) {\n if (raw === void 0 || raw === null) return null;\n if (typeof raw !== \"object\") throw new Error(\"enclave acceptance: block must be an object\");\n if (!MODES.has(raw.mode)) throw new Error(`enclave acceptance: unknown mode ${JSON.stringify(raw.mode)}`);\n const minPolicyVersion = version(raw.minPolicyVersion, \"minPolicyVersion\");\n const accepted = Array.isArray(raw.accepted) ? raw.accepted.map((e, i) => {\n if (!e || typeof e !== \"object\") throw new Error(`enclave acceptance: accepted[${i}] is not an object`);\n const out = { kernel: hex(e.kernel, `accepted[${i}].kernel`) };\n if (e.payload !== void 0 && e.payload !== null) out.payload = hex(e.payload, `accepted[${i}].payload`);\n if (e.policy !== void 0 && e.policy !== null) out.policy = hex(e.policy, `accepted[${i}].policy`);\n out.policyVersion = version(e.policyVersion, `accepted[${i}].policyVersion`);\n out.label = String(e.label || \"\").slice(0, 64);\n out.at = typeof e.at === \"number\" ? e.at : 0;\n return out;\n }) : [];\n if (raw.mode === \"pin\" && !accepted.length) throw new Error(\"enclave acceptance: a pinned Space that accepts nothing can never seal its key\");\n return { mode: raw.mode, minPolicyVersion, accepted };\n}\nfunction acceptsMeasurement(cfg, attested, platform) {\n const c = parseAcceptance(cfg) || { mode: \"follow\", minPolicyVersion: 0, accepted: [] };\n const live = tripleOf(attested);\n if (!live.kernel) return { ok: false, reason: \"no_attestation\", live };\n const pv = attested && typeof attested.policyVersion === \"number\" ? attested.policyVersion : null;\n if (c.minPolicyVersion > 0 && !(pv !== null && pv >= c.minPolicyVersion)) return { ok: false, reason: \"floor\", live, floor: c.minPolicyVersion, policyVersion: pv };\n if (c.mode === \"pin\") {\n const matched = c.accepted.find((e) => sameTriple(e, live));\n return matched ? { ok: true, matched, live } : { ok: false, reason: \"not_accepted\", live };\n }\n const want = pinSetsOf(platform);\n if (!want.kernel.length) return { ok: false, reason: \"no_platform_claim\", live };\n for (const [name] of STAGES) {\n const ok = want[name].length ? want[name].includes(live[name] || \"\") : !live[name];\n if (!ok) return { ok: false, reason: name, live, platform: want };\n }\n return { ok: true, matched: { ...live }, live };\n}\nfunction pinSetsOf(att) {\n const p = att && att.pcrs || {};\n const t = {};\n for (const [name, idx] of STAGES) t[name] = (Array.isArray(p[idx]) ? p[idx] : p[idx] ? [p[idx]] : []).map((v) => String(v).toLowerCase());\n return t;\n}\nfunction parseTrusted(raw) {\n const out = [];\n for (const e of Array.isArray(raw) ? raw : []) {\n try {\n if (!e || typeof e !== \"object\") continue;\n const t = { kernel: hex(e.kernel, \"kernel\") };\n if (e.payload) t.payload = hex(e.payload, \"payload\");\n if (e.policy) t.policy = hex(e.policy, \"policy\");\n t.at = typeof e.at === \"number\" && Number.isFinite(e.at) ? e.at : 0;\n if (!out.some((x) => sameTriple(x, t))) out.push(t);\n } catch {\n }\n }\n return out;\n}\nfunction userVerdict(trusted, attested, platform) {\n const pub = acceptsMeasurement(null, attested, platform);\n if (!pub.ok) return pub;\n if (trusted === void 0) return { ok: false, reason: \"unknown\", live: pub.live };\n return parseTrusted(trusted).some((e) => sameTriple(e, pub.live)) ? { ok: true, matched: pub.live, live: pub.live } : { ok: false, reason: \"not_accepted\", live: pub.live };\n}\nfunction gatedKey({ key, trusted, attested, platform, room } = {}) {\n if (!key) return null;\n const verdict = userVerdict(trusted, attested, platform);\n if (verdict.ok) return key;\n const err = new Error(`enclave_not_accepted: you have not accepted the enclave build this Space runs on (${verdict.reason})`);\n err.code = \"enclave_not_accepted\";\n err.verdict = verdict;\n err.room = room || null;\n throw err;\n}\n\n// spaces/public/sdk/4.7.1/entrySig.js\nvar enc4 = new TextEncoder();\nvar dec3 = new TextDecoder();\nvar toB64 = (u8) => btoa(String.fromCharCode(...u8)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\nvar ECDSA = { name: \"ECDSA\", namedCurve: \"P-256\" };\nvar SIGN = { name: \"ECDSA\", hash: \"SHA-256\" };\nvar importPriv = (jwk) => crypto.subtle.importKey(\"jwk\", jwk, ECDSA, false, [\"sign\"]);\nfunction canon(o) {\n if (o === null || typeof o !== \"object\") return JSON.stringify(o);\n if (Array.isArray(o)) return \"[\" + o.map(canon).join(\",\") + \"]\";\n return \"{\" + Object.keys(o).sort().map((k) => JSON.stringify(k) + \":\" + canon(o[k])).join(\",\") + \"}\";\n}\nvar entryCore = (e) => ({ room: e.room, author: e.author, ts: e.ts, kind: e.kind, id: e.id, text: e.text, ...e.chal !== void 0 ? { chal: e.chal } : {} });\nasync function signEntry(memberPrivJwk, entry) {\n const sig = toB64(new Uint8Array(await crypto.subtle.sign(SIGN, await importPriv(memberPrivJwk), enc4.encode(canon(entryCore(entry))))));\n return { ...entry, sig };\n}\n\n// spaces/public/sdk/4.7.1/mkseal.js\nvar VERSION2 = 1;\nvar enc5 = new TextEncoder();\nvar MAX_CLOCK_OFFSET_MS = 864e5;\nvar CLOCK = globalThis.__wbSealClock = globalThis.__wbSealClock || { offset: 0 };\nvar sealNow = () => Date.now() + CLOCK.offset;\nfunction noteServerClock(serverNow, localNow = Date.now()) {\n const t = Number(serverNow);\n if (!Number.isFinite(t) || t <= 0) return false;\n const d = Math.max(-MAX_CLOCK_OFFSET_MS, Math.min(MAX_CLOCK_OFFSET_MS, Math.round(t - localNow)));\n const moved = Math.abs(d - CLOCK.offset) > 1e3;\n CLOCK.offset = d;\n return moved;\n}\nfunction b644(bytes3) {\n const b = bytes3 instanceof Uint8Array ? bytes3 : new Uint8Array(bytes3);\n let s = \"\";\n for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\nfunction mkAad({ room, op, ts, nonce } = {}) {\n return `mkseal-v1|${room || \"\"}|${op || \"\"}|${ts || 0}|${nonce || \"\"}`;\n}\nfunction newNonce() {\n return b644(crypto.getRandomValues(new Uint8Array(12)));\n}\nasync function sealMk(mk, publicJwk, aad) {\n const pub = await crypto.subtle.importKey(\"jwk\", publicJwk, { name: \"ECDH\", namedCurve: \"P-256\" }, false, []);\n const eph = await crypto.subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, false, [\"deriveBits\"]);\n const epk = new Uint8Array(await crypto.subtle.exportKey(\"raw\", eph.publicKey));\n const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: \"ECDH\", public: pub }, eph.privateKey, 256));\n const key = await deriveKey(shared, epk);\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: enc5.encode(String(aad || \"\")) },\n key,\n enc5.encode(String(mk))\n ));\n return { v: VERSION2, epk: b644(epk), iv: b644(iv), ct: b644(ct) };\n}\nasync function deriveKey(shared, epk) {\n const ikm = await crypto.subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n const info = new Uint8Array([...enc5.encode(\"mkseal-v1\"), ...epk]);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info },\n ikm,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"]\n );\n}\n\n// spaces/public/sdk/4.7.1/reqEnvelope.js\nvar PLAIN_OPS = /* @__PURE__ */ new Set([\n \"create\",\n \"pollsealed\",\n \"blob\",\n \"policy\",\n \"touch\",\n \"purge\",\n \"drop\",\n \"pushdrop\",\n \"user\",\n \"enclaveattest\",\n \"wake\",\n \"changes\",\n \"changesub\",\n \"changemark\",\n \"attest-accept\",\n \"deviceverify\",\n \"receipts\",\n \"receiptsack\",\n // the Lambda answers these itself (agent/enclaveRelay.mjs FRONT_OPS): sealed, it could not read them — device enrollment in an\n // attested confidential room failed (sweep 11-06 #5). spaces/test/frontOpsPlain.test.mjs covers every client-originated front op.\n \"attest-enroll\",\n \"device-verify\",\n \"device-verify-result\",\n // report: what a member CHOSE to show Witbitz (agent/reportOp.mjs — stored and mailed to reports@, never the enclave); the\n // Lambda must read it, so sealed to the enclave it never arrived from a confidential room (CI 2026-11-07, frontOpsPlain)\n \"report\"\n]);\nvar opensEnvelopes = (attested) => {\n if (!attested || !attested.policy || typeof attested.policy !== \"object\") return null;\n return !!(attested.policy.env && attested.policy.env.SEALED_REQUESTS === \"1\");\n};\nvar sealsIdentity = (attested) => !!(attested && attested.policy && attested.policy.env && attested.policy.env.SEALED_IDENTITY === \"1\");\nvar IDENTITY_PLAIN_OPS = /* @__PURE__ */ new Set([\"pollsealed\", \"blob\", \"policy\", \"purge\", \"attest-accept\"]);\nvar READ_OUTSIDE = [\"sinceEtag\", \"sinceCount\", \"changeInbox\"];\nvar carriesIdentity = (body) => !!(body && (typeof body.idToken === \"string\" || body.message && typeof body.message === \"object\" && typeof body.message.idToken === \"string\"));\nvar b645 = (u) => {\n let s = \"\";\n for (const x of u) s += String.fromCharCode(x);\n return btoa(s);\n};\nvar unb64 = (s) => Uint8Array.from(atob(String(s || \"\")), (c) => c.charCodeAt(0));\nvar answerAad = ({ room, op, nonce }) => new TextEncoder().encode(`witbitz-answer|v1|${room}|${op}|${nonce}`);\nfunction outsideOf(body, identity) {\n const o = { op: body.op, room: body.room, enclave: true };\n if (!identity && typeof body.idToken === \"string\") o.idToken = body.idToken;\n if (body.op === \"pollsealed\" || body.op === \"blob\") {\n for (const k of READ_OUTSIDE) if (body[k] !== void 0) o[k] = body[k];\n }\n if (typeof body.bridgeRoom === \"string\") o.bridgeRoom = body.bridgeRoom;\n if (body.op === \"decide\" && typeof body.approve === \"boolean\") o.approve = body.approve;\n if (body.op === \"state\" && body.patch !== void 0) o.patch = null;\n const ra = body.readAttestation && typeof body.readAttestation === \"object\" ? body.readAttestation.attestation : null;\n const plat = (x) => typeof x.platform === \"string\" && /^[a-z]{2,16}$/.test(x.platform) ? { platform: x.platform } : {};\n if (ra && typeof ra === \"object\" && typeof ra.keyId === \"string\") o.readAttestation = { attestation: { keyId: ra.keyId, ...plat(ra) } };\n const m = body.message;\n if (m && typeof m === \"object\") {\n const stub = {};\n if (!identity && typeof m.idToken === \"string\") stub.idToken = m.idToken;\n if (m.attestation && typeof m.attestation === \"object\" && typeof m.attestation.keyId === \"string\") stub.attestation = { keyId: m.attestation.keyId, ...plat(m.attestation) };\n if (Object.keys(stub).length || !identity) o.message = stub;\n }\n return o;\n}\nasync function sealRequest(body, publicJwk, { identity = false, extras = null } = {}) {\n const key = crypto.getRandomValues(new Uint8Array(32));\n const ts = sealNow(), nonce = newNonce();\n const inner = { ...body, answerKey: b645(key) };\n if (identity && extras && typeof extras === \"object\") {\n if (Array.isArray(extras.userHints) && extras.userHints.length) inner.userHints = extras.userHints;\n if (extras.issuerCfg && typeof extras.issuerCfg === \"object\") inner.issuerCfg = extras.issuerCfg;\n if (Array.isArray(extras.boundHints) && extras.boundHints.length) inner.boundHints = extras.boundHints.slice(0, 4);\n }\n delete inner.op;\n delete inner.room;\n delete inner.enclave;\n const envSealed = await sealMk(JSON.stringify(inner), publicJwk, mkAad({ room: body.room, op: body.op + \":env\", ts, nonce }));\n return { outer: { ...outsideOf(body, identity), envSealed, envTs: ts, envNonce: nonce }, answer: { key, aad: answerAad({ room: body.room, op: body.op, nonce }) } };\n}\nvar REFUSAL_FIELDS = [\"error\", \"reason\", \"detail\"];\nasync function openAnswer(reply, answer) {\n const status = reply && Number.isInteger(reply.status) ? reply.status : 0;\n const sa = reply && reply.sealedAnswer;\n if (!sa || typeof sa !== \"object\") {\n if (status >= 200 && status < 300) return { status: 502, ok: false, error: \"answer_unsealed\", reason: \"the answer to a sealed request came back unsealed — not from the enclave\" };\n const out = { status, ok: false };\n for (const k of REFUSAL_FIELDS) if (reply && typeof reply[k] === \"string\") out[k] = reply[k].slice(0, 300);\n if (reply && reply.warming === true) out.warming = true;\n if (reply && reply.confidential === true) out.confidential = true;\n if (reply && Number.isFinite(reply.now)) out.serverNow = reply.now;\n if (!out.error && !(status >= 500)) out.error = \"refused\";\n return out;\n }\n try {\n const k = await crypto.subtle.importKey(\"raw\", answer.key, \"AES-GCM\", false, [\"decrypt\"]);\n const pt = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: unb64(sa.iv), additionalData: answer.aad }, k, unb64(sa.ct));\n const inner = JSON.parse(new TextDecoder().decode(pt));\n return { status, ...inner && typeof inner === \"object\" && !Array.isArray(inner) ? inner : {}, ...reply.confidential === true ? { confidential: true } : {} };\n } catch {\n return { status, ok: false, error: \"answer_unopenable\", reason: \"the enclave's answer could not be opened on this device\" };\n }\n}\n\n// spaces/public/sdk/4.7.1/ownerPolicy.js\nvar enc6 = new TextEncoder();\nvar ECDSA2 = { name: \"ECDSA\", namedCurve: \"P-256\" };\nvar SIGN2 = { name: \"ECDSA\", hash: \"SHA-256\" };\nvar bytesToB64u = (bytes3) => {\n let s = \"\";\n for (const b of bytes3) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar b64uToBytes = (str) => {\n const bin = atob(String(str).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const u = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);\n return u;\n};\nfunction canon2(o) {\n if (o === null || typeof o !== \"object\") return JSON.stringify(o);\n if (Array.isArray(o)) return \"[\" + o.map(canon2).join(\",\") + \"]\";\n return \"{\" + Object.keys(o).sort().map((k) => JSON.stringify(k) + \":\" + canon2(o[k])).join(\",\") + \"}\";\n}\nvar sha256b64u = async (s) => bytesToB64u(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", enc6.encode(s))));\nvar sameKey = (a, b) => !!a && !!b && canon2({ kty: a.kty, crv: a.crv, x: a.x, y: a.y }) === canon2({ kty: b.kty, crv: b.crv, x: b.x, y: b.y });\nasync function ownerKeyId(jwk) {\n return (await sha256b64u(canon2({ kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y }))).slice(0, 22);\n}\nasync function policyHash(policy) {\n return sha256b64u(canon2(policy));\n}\nasync function verifyPolicy(signed, { ownerKey = null, now = Date.now() } = {}) {\n const policy = signed && typeof signed === \"object\" ? signed.policy : null;\n if (!policy || typeof policy !== \"object\" || typeof signed.sig !== \"string\") return { ok: false, reason: \"malformed\" };\n const declared = policy.ownerKey;\n if (!declared || typeof declared !== \"object\") return { ok: false, reason: \"no_owner_key\" };\n if (ownerKey && !sameKey(declared, ownerKey)) return { ok: false, reason: \"owner_mismatch\" };\n let valid = false;\n try {\n valid = await crypto.subtle.verify(SIGN2, await crypto.subtle.importKey(\"jwk\", ownerKey || declared, ECDSA2, false, [\"verify\"]), b64uToBytes(signed.sig), enc6.encode(canon2(policy)));\n } catch {\n valid = false;\n }\n if (!valid) return { ok: false, reason: \"bad_sig\" };\n const nowSec = Math.floor(now / 1e3);\n if (typeof policy.notBefore === \"number\" && nowSec < policy.notBefore) return { ok: false, reason: \"not_yet_valid\" };\n if (typeof policy.notAfter === \"number\" && nowSec >= policy.notAfter) return { ok: false, reason: \"expired\" };\n return { ok: true, policy };\n}\nasync function verifyRoomPolicy({ marker = null, sealed = null, ownerKey = null, required = false, now = Date.now() } = {}) {\n if (!marker) return required ? { ok: false, governed: true, reason: \"policy_required\" } : { ok: true, governed: false };\n if (!sealed || !sealed.policy) return { ok: false, governed: true, reason: \"policy_missing\" };\n const v = await verifyPolicy(sealed, { ownerKey, now });\n if (!v.ok) return { ok: false, governed: true, reason: v.reason };\n if (String(v.policy.app || \"\") !== String(marker.app || \"\")) return { ok: false, governed: true, reason: \"app_mismatch\" };\n if (await policyHash(v.policy) !== marker.policyHash) return { ok: false, governed: true, reason: \"hash_mismatch\" };\n if (await ownerKeyId(v.policy.ownerKey) !== marker.ownerKeyId) return { ok: false, governed: true, reason: \"owner_mismatch\" };\n return { ok: true, governed: true, policy: v.policy };\n}\nfunction qualifies(admit, { authenticated = false, issuer = null, claims = {} } = {}) {\n if (admit === \"anonymous\" || admit && admit.anonymous) return true;\n if (!admit || typeof admit !== \"object\" || !admit.issuer) return false;\n if (!authenticated || issuer !== admit.issuer) return false;\n if (admit.any) return true;\n if (admit.claim && typeof admit.claim === \"object\") {\n return Object.entries(admit.claim).every(([k, val]) => {\n const c = claims && claims[k];\n if (Array.isArray(c)) return c.includes(val);\n if (k === \"group\" && Array.isArray(claims && claims.groups)) return claims.groups.includes(val);\n return c === val;\n });\n }\n return false;\n}\nfunction resolveTier(policy, { authenticated = false, issuer = null, claims = {}, roomTier = null } = {}) {\n const tiers = Array.isArray(policy && policy.tiers) ? policy.tiers : [];\n if (!tiers.length) return { tier: null };\n const ceilingName = roomTier || policy.roomTiers && policy.roomTiers.default || tiers[tiers.length - 1].name;\n const ceilingRank = Math.max(0, tiers.findIndex((t) => t.name === ceilingName));\n let best = -1;\n for (let i = 0; i <= ceilingRank && i < tiers.length; i++) if (qualifies(tiers[i].admit, { authenticated, issuer, claims })) best = i;\n return best < 0 ? { tier: null } : { tier: tiers[best].name, caps: tiers[best].caps || {}, limits: tiers[best].limits || null };\n}\nasync function verifyRoomGovernance({ room, mk, ownerKey = null, fetchPolicy, openConfig, member = null, now = Date.now() } = {}) {\n let marker = null, configSealed = null, key = ownerKey;\n try {\n const r = await fetchPolicy(room) || {};\n marker = r.policy;\n configSealed = r.configSealed;\n if (!key) key = r.ownerKey || null;\n } catch {\n return { ok: false, governed: true, reason: \"fetch_failed\" };\n }\n if (!marker) return { ok: true, governed: false };\n if (!key) return { ok: true, governed: false };\n let sealed = null;\n try {\n const cfg = await openConfig(configSealed, mk);\n sealed = cfg && cfg.ownerPolicy;\n } catch {\n }\n const rp = await verifyRoomPolicy({ marker, sealed, ownerKey: key, now });\n if (!rp.ok) return { ok: false, governed: true, reason: rp.reason };\n const tier = member ? resolveTier(rp.policy, { ...member }).tier : void 0;\n return { ok: true, governed: true, policy: rp.policy, ...tier ? { tier } : {} };\n}\n\n// spaces/public/sdk/4.7.1/roomRoles.js\nvar lc = (s) => String(s || \"\").trim().toLowerCase();\nvar TAG = /^[A-Za-z0-9_-]{16,128}$/;\nvar roleOf = (emails, tags) => {\n const t = [...new Set((tags || []).filter((x) => typeof x === \"string\" && TAG.test(x)))];\n return { emails: [...new Set((emails || []).map(lc).filter(Boolean))], ...t.length ? { tags: t } : {} };\n};\n\n// spaces/public/sdk/4.7.1/roomName.js\nvar staysDirect = (allow) => {\n const a = allow || {}, n = (k) => Array.isArray(a[k]) ? a[k].filter(Boolean).length : 0;\n return !n(\"domains\") && n(\"emails\") + n(\"mh\") + n(\"hidden\") + n(\"users\") <= 2;\n};\n\n// spaces/public/sdk/4.7.1/mirrorBatch.js\nvar encoder = new TextEncoder();\nasync function stageMirrorAttachments(entries, send) {\n if (encoder.encode(JSON.stringify(entries)).length < 21e5) return { entries };\n const prepared = [];\n for (const entry of entries) {\n const copy = { ...entry };\n for (const field of [\"images\", \"files\"]) {\n if (!Array.isArray(entry[field])) continue;\n copy[field] = [];\n for (const attachment of entry[field]) {\n if (!attachment?.b64) {\n copy[field].push(attachment);\n continue;\n }\n const { b64: b6410, ref, parts: oldParts, ...metadata } = attachment;\n const data = b6410.replace(/^data:[^,]*;base64,/, \"\");\n const parts = [];\n let size = 0;\n for (let offset = 0; offset < data.length; offset += 12e5) {\n const r = await send([{ kind: \"mirror-part\", id: entry.id, mime: metadata.mime, b64: data.slice(offset, offset + 12e5) }]);\n if (r?.status === 200 && typeof r.ref !== \"string\") return { entries };\n if (r?.status !== 200 || !Number.isInteger(r.size)) return { error: r?.status && r.status !== 200 ? r : { status: 503, error: \"mirror_part_unconfirmed\" } };\n parts.push(r.ref);\n size += r.size;\n }\n copy[field].push({ ...metadata, size, ...parts.length === 1 ? { ref: parts[0] } : { parts } });\n }\n }\n prepared.push(copy);\n }\n return { entries: prepared };\n}\n\n// spaces/public/sdk/4.7.1/rosterHash.js\nvar enc7 = new TextEncoder();\nvar b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\nvar norm = (s) => String(s == null ? \"\" : s).normalize(\"NFKC\").trim().toLowerCase();\nasync function memberHash(identity, roomSalt) {\n const digest = await crypto.subtle.digest(\"SHA-256\", enc7.encode(`${norm(identity)}|${roomSalt}`));\n return b64url(digest);\n}\n\n// spaces/public/sdk/4.7.1/spaceClient.js\nfunction embedAttribution() {\n try {\n if (typeof location === \"undefined\") return {};\n const tid = new URLSearchParams(location.search).get(\"tid\") || \"\";\n const embedOrigin = typeof document !== \"undefined\" && document.referrer ? new URL(document.referrer).origin : \"\";\n return tid && embedOrigin ? { tid: tid.slice(0, 64), embedOrigin } : {};\n } catch {\n return {};\n }\n}\nasync function directRoster(allow, room) {\n if (!Array.isArray(allow?.emails) || !Array.isArray(allow?.mh) || !allow.mh.length) return allow;\n const shown = new Set(await Promise.all(allow.emails.map((email) => memberHash(email, room))));\n return { ...allow, mh: allow.mh.filter((hash) => !shown.has(hash)) };\n}\nvar sealConfig = async (config, mk) => JSON.stringify(await seal(JSON.stringify({\n tools: config.tools,\n immediateTools: config.immediateTools,\n clientTools: config.clientTools,\n persona: config.persona,\n agentName: config.agentName,\n ...config.appId ? { appId: String(config.appId).slice(0, 40) } : {},\n // §APP STORE Stage 1: the Space's chosen app — an ID, never a URL (the store origin resolves it against its catalog)\n // The DECLARED MCP server (name → typed input schema) — sealed like the rest, so the platform can't read the app's\n // skill surface at rest; the turn op reads it in the mk-scoped decrypt to type-check + admit an app→agent mcp call.\n skills: config.skills,\n // BYO model — {provider, key, model, baseUrl}. Sealed like the rest of the config, so the tenant's credential is\n // ciphertext at rest and the platform cannot read it outside a turn.\n model: config.model,\n // Admission policy + allow-list ride INSIDE the sealed config → the platform can't read a Space's gate or who's\n // allowed at rest; the turn op reads them only in the mk-scoped decrypt (spaceHandler create → spaceService turn).\n // JSON.stringify drops undefined keys, so an open Space seals exactly as before (backward compatible).\n admission: config.admission,\n allow: config.allow,\n requireChallenge: config.requireChallenge,\n agentKeys: config.agentKeys,\n usernames: config.usernames,\n // usernames:false = the room opted out of the server-stamped @username on verified entries (docs/spaces-usernames.md §7)\n // Owner rule (docs/the-owner-rule.md): the owner-SIGNED App Policy + this room's tier, sealed like the rest — so the\n // render enforces it and a joining client can open + peer-verify governance against the pinned owner key. Undefined\n // (ungoverned room) ⇒ JSON.stringify drops them ⇒ sealed exactly as before.\n ownerPolicy: config.ownerPolicy,\n roomTier: config.roomTier,\n // Private lane (docs/spaces-private-lane.md): `bridge` = a private lane's link to its shared room; `agentReplies`\n // = false for a Bridge SHARED room (an observer venue — the agent doesn't auto-reply). Sealed like the rest, so\n // both are content-blind at rest; undefined (a normal Space) ⇒ JSON.stringify drops them ⇒ sealed exactly as before.\n bridge: config.bridge,\n agentReplies: config.agentReplies,\n // THE ROOM AS A STORE (agent/dataTools.mjs): the app's declared collections + field rules. Sealed like the rest; a\n // room without one sees no data tools. Undefined ⇒ dropped ⇒ sealed exactly as before.\n dataSchema: config.dataSchema,\n // WHICH PLATFORM TOOLS the assistant gets (agent/spaceService.mjs normPlatformTools): absent = all, false = none, a list =\n // only those. Undefined ⇒ dropped ⇒ sealed exactly as before.\n platformTools: config.platformTools === false || Array.isArray(config.platformTools) ? config.platformTools : void 0,\n // BUILDER MODE (Tomer, 2026-10-10): `framing: 'builder'` = the prompt is the app's persona and tools only — no Spaces\n // framing; `dataWrites: false` = the room store offers data_query only. Undefined ⇒ dropped ⇒ sealed exactly as before.\n framing: config.framing === \"builder\" ? \"builder\" : void 0,\n // A PURGEABLE room (docs/room-messages.md § Retention): its handled rows may be purged (op 'purge'). Create-time only,\n // and only the account's own control rooms — the server refuses it on any room with an assistant or admission.\n retention: config.retention === \"purgeable\" ? \"purgeable\" : void 0,\n dataWrites: config.dataWrites === false ? false : void 0,\n // SAFE MEDIA (docs/safe-media.md): photos and PDFs here are shown from copies the tools enclave made safe. Undefined ⇒ dropped ⇒ sealed exactly as before.\n safeMedia: config.safeMedia === true ? true : void 0,\n // Private lanes for EVERYONE (create checkbox): a create-time room property every joiner learns from the room —\n // this whitelist silently DROPPED it, which is why an invitee whose link lost the one-shot &lanes=1 hint could\n // never self-heal (the sealed config genuinely lacked the field). Undefined ⇒ dropped ⇒ sealed exactly as before.\n lanes: config.lanes === true ? true : void 0,\n lane: config.lane === true ? true : void 0,\n // A PRIVATE LANE SAYS SO (laneConfig.js `lane: true`): this whitelist dropped it, so the server and the cloud device never saw it (sync sweep 11-19 P1)\n // Membership fork (docs/spaces-membership-fork.md): the epoch's admitted ROSTER (name+spk per keeper), stamped by\n // forkRoom. Since membership only changes via a fork (add = fork), this stays authoritative between forks — so the\n // NEXT fork reads it instead of re-deriving from the ledger (whose carried history still holds removed members'\n // spks). Absent on an original room ⇒ dropped by JSON.stringify ⇒ sealed exactly as before (roster derived from the\n // ledger as the bootstrap). Sealed under mk like the rest — the platform can't read who's in.\n roster: config.roster,\n // `forkAuthority` = the spk allowed to publish a membership-fork notice for this room (the creator, then carried\n // across forks). A keeper AUTO-FOLLOWS a fork only if the notice is signed by this key — the hijack defense, since\n // anyone holding mk could otherwise read keeper spks from the ledger and forge a fork to a room they control.\n forkAuthority: config.forkAuthority,\n // `parent` = { room } of the PRIOR epoch, set by a LINK fork (P4, epoch-keyed): history lives in the parent chain\n // rather than being re-sealed here, so a fork is O(1). readEpochChain walks it with the ancestor keys from the\n // pointer. Absent on a normal/full-fork room ⇒ dropped by JSON.stringify ⇒ sealed exactly as before.\n parent: config.parent,\n // Enclave acceptance (docs/enclave-room-acceptance.md): what THIS Space accepts from the confidential tier —\n // `{mode: follow|pin, minPolicyVersion, accepted:[{kernel,payload,policy,…}]}`. Sealed under mk like the rest, so\n // every member (and the enclave, which re-opens the config) reads the same declaration; create-once, so a change\n // is a fork. Validated here so garbage is refused at mint rather than guessed about by every opener. Absent\n // (a normal Space, or a pre-P2 confidential one ⇒ follow) ⇒ dropped by JSON.stringify ⇒ sealed exactly as before.\n enclave: parseAcceptance(config.enclave) || void 0,\n // ROOM GOVERNANCE (2026-10-02). `admins` ({ emails }) and `approve` ('admins'|'members') are enforced by the SERVER\n // (spaceService hasAdmins/isRoomAdmin/cardNeedsAdmin) — and were MISSING from this list, so an SDK room declared them\n // and sealed without them: no admins, approvals by any member (a builder measured it on production). `forkedFrom` is\n // where a fork came from; `connections` are the grants a fork carries. Undefined ⇒ dropped ⇒ sealed exactly as before.\n admins: config.admins && Array.isArray(config.admins.emails) ? roleOf(config.admins.emails, config.admins.tags) : void 0,\n // tags: an admin by @username tag (docs/spaces-usernames.md § 13.1)\n owners: config.owners && Array.isArray(config.owners.emails) ? roleOf(config.owners.emails, config.owners.tags) : void 0,\n // OWNERS (2026-10-03): above admins, enforced by the room\n forkedFrom: typeof config.forkedFrom === \"string\" && config.forkedFrom ? config.forkedFrom.slice(0, 120) : void 0,\n connections: Array.isArray(config.connections) && config.connections.length ? config.connections : void 0,\n direct: config.direct === true ? true : void 0,\n // a DIRECT chat (directChat.js): the server refuses its rename, the other side files it by this\n help: config.help === true ? true : void 0\n // the account's HELP SPACE (helpSpace.js): the server runs its built-in help configuration\n}), { room: mk }));\nvar invitePad = () => {\n const r = crypto.getRandomValues(new Uint8Array(90));\n return btoa(String.fromCharCode(...r)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar DEFAULT_ENDPOINT = \"/space\";\nvar originBase = () => typeof location !== \"undefined\" && location.origin || \"\";\nvar _ohttp = null;\nasync function readSealedArchive(read) {\n const first = await read(0);\n if (!first?.more) return first;\n const boxes = [], revision = (etag) => String(etag || \"\").replace(/#\\d+$/, \"\");\n let page = first;\n for (let i = 0; i < 400; i++) {\n let slice;\n try {\n slice = JSON.parse(page?.sealed);\n } catch {\n }\n if (page?.status !== 200 || revision(page.etag) !== revision(first.etag) || slice?.v !== 3 || !Array.isArray(slice.boxes) || slice.from !== boxes.length || slice.count !== boxes.length + slice.boxes.length) break;\n for (const box of slice.boxes) boxes.push(box);\n if (!page.more) return { ...page, from: 0, count: boxes.length, sealed: JSON.stringify({ ...slice, from: 0, count: boxes.length, boxes }) };\n if (!slice.boxes.length) break;\n page = await read(boxes.length);\n }\n return { status: 409, error: \"archive_incomplete\" };\n}\nvar _ohttpPending = null;\nasync function awaitOhttpReady() {\n const p = _ohttpPending;\n if (p) {\n try {\n await p;\n } catch {\n }\n }\n}\nvar _ohttpMod = null;\nvar ohttpMod = async () => _ohttpMod || (_ohttpMod = await Promise.resolve().then(() => (init_ohttp(), ohttp_exports)));\nasync function ohttpCall(body, fetchImpl) {\n const O = await ohttpMod();\n const inner = O.encodeRequest({\n method: \"POST\",\n scheme: \"https\",\n authority: _ohttp.gatewayAuthority,\n path: _ohttp.gatewayPath || \"/\",\n headers: { \"content-type\": \"application/json\" },\n body: new TextEncoder().encode(JSON.stringify(body))\n });\n const { encRequest, ks, enc: enc15 } = await O.encapsulateRequest(_ohttp.keyConfig, inner);\n const b6410 = (u8) => {\n let s = \"\";\n for (const b of u8) s += String.fromCharCode(b);\n return btoa(s);\n };\n const ub646 = (s) => {\n const bin = atob(s);\n const u = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);\n return u;\n };\n const res = await fetchImpl(_ohttp.relay, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ op: \"ohttp\", enc: b6410(encRequest) }) });\n if (!res.ok) return { status: res.status };\n let env = {};\n try {\n env = await res.json();\n } catch {\n return { status: res.status };\n }\n if (!env.res) return { status: env.status || res.status, ...env.error ? { error: env.error } : {} };\n const respBhttp = await O.decapsulateResponse(ks, enc15, ub646(env.res));\n const resp = O.decodeResponse(respBhttp);\n let data = {};\n try {\n data = JSON.parse(new TextDecoder().decode(resp.body) || \"{}\");\n } catch {\n }\n return { status: resp.status, ...data };\n}\nasync function call(endpoint, body, fetchImpl) {\n await awaitOhttpReady();\n if (_ohttp) {\n try {\n return _ohttp.send ? await _ohttp.send(body) : await ohttpCall(body, fetchImpl);\n } catch (e) {\n return { status: 0, error: \"ohttp: \" + String(e && e.message || e).slice(0, 120) };\n }\n }\n const res = await fetchImpl(endpoint, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) });\n let data = {};\n try {\n data = await res.json();\n } catch {\n }\n return { status: res.status, ...data };\n}\nvar _pushSelf = \"\";\nfunction setPushSelf(endpoint) {\n _pushSelf = String(endpoint || \"\");\n}\nvar pushSelf = () => _pushSelf;\nasync function crossingPush(room) {\n if (!room) return {};\n return { crossingPush: { room, ...pushSelf() ? { pushSelf: pushSelf() } : {}, ...await pushAcctField(room) } };\n}\nasync function viewingTag(room) {\n if (!_pushSelf || !room || !(globalThis.crypto && crypto.subtle)) return \"\";\n try {\n const k = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(_pushSelf), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return b64u(new Uint8Array(await crypto.subtle.sign(\"HMAC\", k, new TextEncoder().encode(\"witbitz-viewing|\" + room))).slice(0, 16));\n } catch {\n return \"\";\n }\n}\nvar _pushAcct = \"\";\nvar _acctTags = /* @__PURE__ */ new Map();\nfunction setPushAcct(secret) {\n const s = String(secret || \"\");\n if (s !== _pushAcct) {\n _pushAcct = s;\n _acctTags.clear();\n }\n}\nvar b64u = (u8) => {\n let s = \"\";\n for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nasync function pushAcctField(room) {\n if (!_pushAcct || !room || !(globalThis.crypto && crypto.subtle)) return {};\n try {\n let t = _acctTags.get(room);\n if (!t) {\n const k = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(_pushAcct), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n t = b64u(new Uint8Array(await crypto.subtle.sign(\"HMAC\", k, new TextEncoder().encode(\"witbitz-push-acct|\" + room))).slice(0, 16));\n _acctTags.set(room, t);\n }\n return { pushAcct: t };\n } catch {\n return {};\n }\n}\nasync function pushAcctSecretOf(indexMk) {\n const k = typeof indexMk === \"string\" ? indexMk : \"\";\n if (!k || !(globalThis.crypto && crypto.subtle)) return \"\";\n return b64u(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(\"witbitz-push-acct-secret|\" + k))));\n}\nvar _attestProvider = null;\nfunction setAttestProvider(fn) {\n _attestProvider = typeof fn === \"function\" ? fn : null;\n}\nvar _readProvider = null;\nvar readAttestProvider = () => _readProvider || _attestProvider;\nvar attestProvider = () => _attestProvider || (typeof window !== \"undefined\" && typeof window.__vcAttestProvider === \"function\" ? window.__vcAttestProvider : null);\nfunction withSignIn(b, fresh) {\n if (!b || !fresh || typeof fresh.idToken !== \"string\" || !fresh.idToken || !fresh.spk) return null;\n const same2 = (a) => {\n try {\n return JSON.stringify(a) === JSON.stringify(fresh.spk);\n } catch {\n return false;\n }\n };\n if (b.message && typeof b.message === \"object\" && b.message.idToken) return same2(b.message.spk) ? { ...b, message: { ...b.message, idToken: fresh.idToken } } : null;\n if (b.idToken) return { ...b, idToken: fresh.idToken, spk: fresh.spk };\n return null;\n}\nvar SPEND_OPS = /* @__PURE__ */ new Set([\"turn\", \"title\", \"decide\", \"import\"]);\nvar VOICE_OPS = /* @__PURE__ */ new Set([\"stt\", \"tts\"]);\nvar TIER_PROBE_WAITS = [500, 1500];\nvar tierFault = (r) => !r || !r.status || r.status === 429 || r.status >= 500;\nfunction makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl, auth: auth2, mkPub, app, enclave = false, envelope = false, identity = false, tenant, userToken, delCommit, roomPass = null, renewSignIn = null, onConfidential = null, tierWaits = TIER_PROBE_WAITS } = {}) {\n const tenantHint = tenant ? { tid: String(tenant).slice(0, 64) } : {};\n const f = fetchImpl || (typeof fetch !== \"undefined\" ? fetch : null);\n if (!f) throw new Error(\"no fetch available — pass { fetch }\");\n const enclaveFor = (room) => {\n try {\n return typeof enclave === \"function\" ? !!enclave(room) : !!enclave;\n } catch {\n return false;\n }\n };\n const mkPubFor = (room) => {\n try {\n return typeof mkPub === \"function\" ? mkPub(room) || null : mkPub || null;\n } catch (e) {\n if (e && e.code === \"enclave_not_accepted\") throw e;\n return null;\n }\n };\n const envelopeFor = (room) => {\n try {\n const v = typeof envelope === \"function\" ? envelope(room) : envelope;\n return v === true ? true : (v === null || v === void 0) && typeof envelope === \"function\" ? null : false;\n } catch {\n return null;\n }\n };\n const identityFor = (room) => {\n try {\n return (typeof identity === \"function\" ? identity(room) : identity) === true;\n } catch {\n return false;\n }\n };\n const extrasCache = /* @__PURE__ */ new Map();\n const EXTRAS_REFRESH_MS = 36e5;\n const tokenClaims = (tok) => {\n try {\n const p = JSON.parse(atob(String(tok).split(\".\")[1].replace(/-/g, \"+\").replace(/_/g, \"/\")));\n return p && typeof p === \"object\" ? p : null;\n } catch {\n return null;\n }\n };\n const fetchExtras = async (key, tok) => {\n let r = await call(endpoint, { op: \"idextras\", idToken: tok }, f).catch(() => null);\n if (!r || r.status !== 200 && r.status !== 401) {\n await new Promise((ok) => setTimeout(ok, 400));\n r = await call(endpoint, { op: \"idextras\", idToken: tok }, f).catch(() => null);\n }\n if (!r || r.status !== 200 || r.ok !== true || !Number.isFinite(r.exp)) {\n extrasCache.delete(key);\n return null;\n }\n const v = { ...Array.isArray(r.userHints) ? { userHints: r.userHints } : {}, ...r.issuerCfg && typeof r.issuerCfg === \"object\" ? { issuerCfg: r.issuerCfg } : {}, ...Array.isArray(r.boundHints) && r.boundHints.length ? { boundHints: r.boundHints.slice(0, 4) } : {} };\n extrasCache.set(key, { v, exp: r.exp, at: Date.now() });\n return v;\n };\n const extrasFor = async (tok, { fresh = false } = {}) => {\n const c = tokenClaims(tok);\n const email = c && typeof c.email === \"string\" ? c.email.trim().toLowerCase() : \"\";\n if (!email) return {};\n const key = String(c.iss || \"\") + \"|\" + email, now = Date.now();\n if (fresh && !(extrasCache.get(key) || {}).p) extrasCache.delete(key);\n const hit = extrasCache.get(key);\n if (hit && hit.v && now < hit.exp - 6e4) {\n if (now > hit.at + EXTRAS_REFRESH_MS && !hit.p) {\n hit.p = fetchExtras(key, tok).finally(() => {\n const h = extrasCache.get(key);\n if (h) delete h.p;\n });\n }\n return hit.v;\n }\n if (hit && hit.p) return hit.p;\n const p = fetchExtras(key, tok);\n extrasCache.set(key, { p });\n return p;\n };\n const tokenOfBody = (b) => typeof b.idToken === \"string\" ? b.idToken : b.message && typeof b.message.idToken === \"string\" ? b.message.idToken : \"\";\n const tokenFor = async (op) => {\n if (!userToken || !(SPEND_OPS.has(op) || VOICE_OPS.has(op))) return \"\";\n try {\n const t = typeof userToken === \"function\" ? await userToken() : userToken;\n return typeof t === \"string\" ? t : \"\";\n } catch {\n return \"\";\n }\n };\n const post = async (body, billingToken) => {\n const tok = typeof billingToken === \"string\" ? billingToken : body && !body.userToken ? await tokenFor(body.op) : \"\";\n let tokFields = {};\n if (tok) {\n if (body.room && enclaveFor(body.room)) {\n try {\n tokFields = await sealField(body.room, body.op + \":ut\", tok, \"userToken\") || {};\n } catch {\n tokFields = {};\n }\n } else tokFields = { userToken: tok };\n }\n let b0 = tok ? { ...body, ...tokFields } : body;\n const attested = !!(b0 && b0.room && !ATTEST_OWN_OPS.has(b0.op) && !b0.readAttestation);\n const send = async () => {\n let b = attested ? { ...b0, ...passFor(b0.room, b0.op, b0) || await readAttestFor(b0.room) } : b0;\n if (roomPass && b && typeof roomPass.fieldsFor === \"function\") {\n let pf = {};\n try {\n pf = await roomPass.fieldsFor(b, { ts: sealNow() }) || {};\n } catch {\n pf = {};\n }\n if (pf.pass && pf.psig) b = { ...b, pass: pf.pass, psig: pf.psig };\n }\n const body2 = b && (b.enclave === true || enclaveFor(b.room) || learnedConfidential(b)) ? { enclave: true, ...b } : b;\n const enc15 = body2 && body2.enclave === true && typeof body2.room === \"string\";\n const idWay = enc15 && identityFor(body2.room) && carriesIdentity(body2);\n const sealedWay = !enc15 ? false : !PLAIN_OPS.has(body2.op) ? envelopeFor(body2.room) : idWay && IDENTITY_PLAIN_OPS.has(body2.op) && envelopeFor(body2.room) === true;\n if (sealedWay === null) return { status: 503, ok: false, error: \"enclave_policy_unknown\", retryable: true, reason: \"this confidential Space's enclave could not be fully checked yet, so nothing was sent — try again\" };\n const idOnly = sealedWay === true && PLAIN_OPS.has(body2.op) && !gatedRooms.has(body2.room);\n const plainNoId = () => {\n const { idToken: _t, spk: _s, pass: _p, psig: _q, ...rest } = body2;\n return call(endpoint, rest, f);\n };\n if (idOnly && (asleepPlain.get(body2.room) || 0) > Date.now()) return plainNoId();\n if (sealedWay === true) {\n const pub = mkPubFor(body2.room);\n if (!pub) throw new Error(\"enclave key unavailable for this room — refusing to send the request to the relay\");\n let extras = idWay ? await extrasFor(tokenOfBody(body2)) : null;\n const sealedSend = async (ex, bd = body2) => {\n const { outer, answer } = await sealRequest(bd, pub, { identity: idWay, extras: ex || {} });\n return openAnswer(await call(endpoint, outer, f), answer);\n };\n let out = await sealedSend(extras);\n if (idWay && !extras && out && (out.status === 403 && out.error === \"not_authorized\" || out.status === 503 && typeof out.error === \"string\" && out.error)) {\n extras = await extrasFor(tokenOfBody(body2));\n if (extras) out = await sealedSend(extras);\n } else if (idWay && extras && out && out.status === 403 && /^pass: bound_unknown/.test(String(out.reason || \"\"))) {\n const ex = await extrasFor(tokenOfBody(body2), { fresh: true });\n if (ex && Array.isArray(ex.boundHints) && ex.boundHints.length) {\n extras = ex;\n out = await sealedSend(extras);\n }\n }\n if (out && out.error === \"envelope_stale\" && noteServerClock(out.serverNow)) {\n const again = await resealBody(body2);\n if (again) out = await sealedSend(extras, again);\n }\n if (idOnly && out && out.error === \"answer_unsealed\") {\n asleepPlain.set(body2.room, Date.now() + ASLEEP_PLAIN_MS);\n return plainNoId();\n }\n return out;\n }\n if (!enc15 && body2 && typeof body2.room === \"string\") {\n const keyFor = async (room) => {\n const t = await tierOf(room);\n return t === \"enclave\" ? tierRefusal(body2) : t === \"unknown\" ? tierUnknown() : null;\n };\n if (typeof body2.mk === \"string\" && body2.mk) {\n const no = await keyFor(body2.room);\n if (no) return no;\n }\n if (typeof body2.bridgeMk === \"string\" && body2.bridgeMk && typeof body2.bridgeRoom === \"string\" && body2.bridgeRoom) {\n const no = await keyFor(body2.bridgeRoom);\n if (no) return no;\n }\n }\n return call(endpoint, body2, f);\n };\n let r = await send();\n if (r && r.error === \"confidential_room\" && b0 && typeof b0.room === \"string\" && !b0.enclave && !enclaveFor(b0.room) && PLAIN_OPS.has(b0.op) && keyless(b0)) {\n noteTier(b0.room, r);\n if (learnedConfidential(b0)) {\n r = await send();\n if (r && typeof r === \"object\" && !r.tier) r = { ...r, tier: \"enclave\" };\n }\n }\n const passRefused = (re) => !!(r && (r.status === 403 || r.status === 401) && re.test(String(r.reason || \"\")));\n if (renewSignIn && passRefused(/^pass: app_unnamed/)) {\n let fresh = null;\n try {\n fresh = await renewSignIn(b0);\n } catch {\n fresh = { retryable: true };\n }\n const nb = withSignIn(b0, fresh);\n if (nb) {\n b0 = nb;\n r = await send();\n } else if (fresh?.retryable) r = { ...r, passRetryable: true };\n }\n if (roomPass && typeof roomPass.renew === \"function\" && passRefused(/^pass: (pass_expired|pass_required)/)) {\n let renewal;\n try {\n renewal = await roomPass.renew(b0);\n } catch {\n renewal = { retryable: true };\n }\n r = await send();\n if (renewal?.retryable && passRefused(/^pass: pass_required/)) r = { ...r, passRetryable: true };\n }\n if (roomPass && passRefused(/^pass: psig_stale/) && noteServerClock(r.serverNow)) r = await send();\n if (attested) notePass(b0.room, r);\n if (attested && r && r.error === \"attest_required\" && typeof r.challenge === \"string\") {\n attestReadRooms.set(b0.room, r.challenge);\n if (r.reason) attestReadWhy.set(b0.room, String(r.reason));\n r = await send();\n }\n if (attested) {\n notePass(b0.room, r);\n noteReadChal(b0.room, r);\n }\n return r;\n };\n const tierKnown = /* @__PURE__ */ new Map();\n const keyless = (x) => !(typeof x.mk === \"string\" && x.mk) && !(typeof x.bridgeMk === \"string\" && x.bridgeMk) && !x.userShare;\n const learnedConfidential = (x) => !!x && typeof x.room === \"string\" && PLAIN_OPS.has(x.op) && keyless(x) && tierKnown.get(x.room) === \"enclave\";\n const tierAsk = /* @__PURE__ */ new Map();\n const TIER_RETRY_MS = 1e4;\n const noteTier = (room, r) => {\n if (!room || !r || tierKnown.get(room) === \"enclave\") return;\n if (r.tier === \"enclave\" || r.error === \"confidential_room\") {\n tierKnown.set(room, \"enclave\");\n if (!enclaveFor(room) && typeof onConfidential === \"function\") {\n try {\n onConfidential(room);\n } catch {\n }\n }\n } else if (saysStandard(r)) tierKnown.set(room, \"standard\");\n else if (tierKnown.get(room) !== \"standard\") tierKnown.set(room, { until: Date.now() + TIER_RETRY_MS });\n };\n const saysStandard = (r) => r.error !== \"tier_unknown\" && (r.status === 200 || r.status === 401 || r.status === 403);\n const saysTier = (r) => !!r && (r.tier === \"enclave\" || r.error === \"confidential_room\" || saysStandard(r));\n const tierOf = async (room) => {\n if (enclaveFor(room)) return \"enclave\";\n const k = tierKnown.get(room);\n if (k === \"standard\" || k === \"enclave\") return k;\n if (k && k.until > Date.now()) return \"unknown\";\n if (!tierAsk.has(room)) {\n tierAsk.set(room, (async () => {\n try {\n let r = null;\n for (let i = 0; ; i++) {\n try {\n r = await call(endpoint, { op: \"policy\", room, ...await authFor(room) }, f);\n } catch {\n r = { status: 0 };\n }\n if (saysTier(r) || i >= tierWaits.length || !tierFault(r)) break;\n await new Promise((res) => setTimeout(res, tierWaits[i] * (0.5 + Math.random())));\n }\n noteTier(room, r);\n } finally {\n tierAsk.delete(room);\n }\n })());\n }\n await tierAsk.get(room);\n const v = tierKnown.get(room);\n return v === \"standard\" || v === \"enclave\" ? v : \"unknown\";\n };\n const TIER_READS = /* @__PURE__ */ new Set([\"poll\", \"pollsealed\"]);\n const tierRefusal = (body) => TIER_READS.has(body.op) ? { status: 200, ok: true, changed: false, tier: \"enclave\", ...body.sinceEtag ? { etag: body.sinceEtag } : {} } : { status: 409, ok: false, error: \"confidential_room\", tier: \"enclave\", reason: \"this Space is confidential: its requests go to the enclave — nothing was sent. Reopen the Space.\" };\n const tierUnknown = () => ({ status: 503, ok: false, error: \"tier_unknown\", retry: true, reason: \"could not tell yet whether this Space is confidential, so its key was not sent — trying again in a moment\" });\n const ATTEST_OWN_OPS = /* @__PURE__ */ new Set([\"turn\", \"policy\", \"attest-accept\"]);\n const asleepPlain = /* @__PURE__ */ new Map();\n const ASLEEP_PLAIN_MS = 2e4;\n const readAttestFor = async (room) => {\n if (!attestReadRooms.has(room)) return {};\n try {\n const p = readAttestProvider();\n const why = takeReadWhy(room);\n const att = p ? await p(room, { read: true, challenge: attestReadRooms.get(room), ...why ? { refused: why } : {} }) : null;\n return att && att.read ? { readAttestation: att.read } : {};\n } catch {\n return {};\n }\n };\n const authFor = async (room) => {\n if (!auth2) return {};\n try {\n const a = await auth2(room);\n return a && a.idToken && a.spk ? { idToken: a.idToken, spk: a.spk } : {};\n } catch {\n return {};\n }\n };\n const otherAuth = async (rooms) => {\n for (const r of rooms) {\n if (!r) continue;\n const a = await authFor(r);\n if (a.idToken) return a;\n }\n return {};\n };\n const withTurnStatus = async (out, r, mk) => {\n if (typeof r.partialStatus !== \"string\") return out;\n try {\n const st2 = JSON.parse(await open(JSON.parse(r.partialStatus), { mk }));\n const ok = st2 && typeof st2 === \"object\" && (st2.phase === \"thinking\" || st2.phase === \"writing\" || st2.phase === \"deciding\" || typeof st2.tool === \"string\" && /^[a-z0-9_]{1,64}$/.test(st2.tool));\n const since = Number.isFinite(st2.since) ? { since: st2.since } : {};\n return ok ? { ...out, partialStatus: { ...st2.tool ? { tool: st2.tool } : { phase: st2.phase }, ...since }, partialSeq: r.partialSeq || out.partialSeq || 0 } : out;\n } catch {\n return out;\n }\n };\n const withStreamGrants = async (out, r, mk) => {\n let g = Array.isArray(r.stream) ? r.stream : null;\n if (typeof r.streamSealed === \"object\" && r.streamSealed && mk) {\n try {\n g = JSON.parse(await open(r.streamSealed, { mk }));\n } catch {\n g = null;\n }\n }\n const ok = Array.isArray(g) && g.length <= 4 && g.every((x) => x && Number.isInteger(x.e) && typeof x.g === \"string\" && x.g.length <= 64);\n return ok ? { ...out, streamGrants: g.map((x) => ({ e: x.e, g: x.g })) } : out;\n };\n const _reseal = /* @__PURE__ */ new Map();\n const resealable = (nonce, again) => {\n _reseal.set(nonce, again);\n const t = setTimeout(() => _reseal.delete(nonce), 12e4);\n if (t && t.unref) t.unref();\n };\n const resealBody = async (body) => {\n if (!body || body.newMkSealed !== void 0 || body.idSealed !== void 0) return null;\n let out = { ...body };\n for (const [k, v] of Object.entries(body)) {\n if (!/Nonce$/.test(k) || typeof v !== \"string\") continue;\n const again = _reseal.get(v);\n if (!again) return null;\n out = { ...out, ...await again() };\n }\n return out;\n };\n const keyFields = async (room, op, mk) => {\n const pub = mkPubFor(room);\n if (enclaveFor(room) && !pub) throw new Error(\"enclave key unavailable for this room — refusing to send the room key to the relay\");\n if (!pub || !mk) return { mk };\n try {\n const ts = sealNow();\n const nonce = newNonce();\n resealable(nonce, () => keyFields(room, op, mk));\n return { mkSealed: await sealMk(mk, pub, mkAad({ room, op, ts, nonce })), mkTs: ts, mkNonce: nonce };\n } catch (e) {\n if (enclaveFor(room)) throw e;\n return { mk };\n }\n };\n const sealField = async (room, aadOp, plaintext, base) => {\n const pub = mkPubFor(room);\n if (enclaveFor(room) && !pub) throw new Error(\"enclave key unavailable for this room — refusing to send bridged data to the relay\");\n if (!pub) return null;\n const ts = sealNow();\n const nonce = newNonce();\n resealable(nonce, () => sealField(room, aadOp, plaintext, base));\n return { [`${base}Sealed`]: await sealMk(plaintext, pub, mkAad({ room, op: aadOp, ts, nonce })), [`${base}Ts`]: ts, [`${base}Nonce`]: nonce };\n };\n const bridgeFields = async (room, op, bridgeMk) => await sealField(room, op + \":bridge\", bridgeMk, \"bridgeMk\") || { bridgeMk };\n const healEnclaveConfig = async (room, mk) => {\n if (!mk || !enclaveFor(room)) return null;\n let s = null;\n try {\n s = await call(endpoint, { op: \"policy\", room }, f);\n } catch {\n return null;\n }\n if (!s || typeof s.configSealed !== \"string\" || !s.configSealed) return null;\n let cfg = null;\n try {\n cfg = JSON.parse(await open(JSON.parse(s.configSealed), { mk }));\n } catch {\n cfg = null;\n }\n if (!cfg || typeof cfg !== \"object\" || Array.isArray(cfg)) return null;\n let r = null;\n try {\n r = await post({ op: \"config\", room, ...await keyFields(room, \"config\", mk), configSealed: s.configSealed, ...await authFor(room) });\n } catch {\n r = null;\n }\n return { cfg, configSealed: s.configSealed, saved: !!(r && r.status === 200) };\n };\n const policyPost = async (room, mk) => post({ op: \"policy\", room, ...mk ? await keyFields(room, \"policy\", mk) : {}, ...await authFor(room) });\n const linksFields = async (room, op, links) => await sealField(room, op + \":links\", JSON.stringify(links), \"links\") || { links };\n const mkFromLinks = async (links, config, commit2) => {\n const pieces = (Array.isArray(links) ? links : [links]).map((l) => {\n const p = parseConfiguredLink(l);\n return p.share || p.mk;\n }).filter(Boolean);\n return assembleConfiguredKey(pieces, config, commit2);\n };\n const gatedRooms = /* @__PURE__ */ new Set();\n const gatedRefusal = (r) => !!(r && r.reason === \"gated_read_requires_key\" && (r.status === 401 || r.error === \"need_identity\"));\n const sealedRead = async (room, mk, op, fields, { proveKey = false, sent = null } = {}) => {\n const keyed = async () => {\n if (enclaveFor(room) && !mkPubFor(room)) return { status: 503, ok: false, error: \"enclave_warming\", retry: true, reason: \"this confidential Space's enclave is asleep — nothing was sent\" };\n if (sent) sent.keyed = true;\n const k = await post({ op, room, ...fields, ...await keyFields(room, op, mk), ...await authFor(room), ...await attestFor(room) });\n if (k && k.status === 200) keyedOk.add(room);\n return k;\n };\n if (mk && (proveKey || gatedRooms.has(room) && (enclaveFor(room) || keyFirstNow(room)))) return keyed();\n const r = await post({ op, room, ...fields, ...await authFor(room), ...await attestFor(room, op, fields) });\n notePass(room, r);\n if (!enclaveFor(room)) noteTier(room, r);\n if (!mk) return r;\n if (gatedRefusal(r)) {\n if (gatedRooms.has(room) && keyedOk.has(room)) keyFirst.set(room, Date.now() + KEY_FIRST_MS);\n gatedRooms.add(room);\n return keyed();\n }\n if (r && (r.status === 403 || r.status === 200) && r.error === \"not_authorized\") {\n gatedRooms.add(room);\n return keyed();\n }\n return r;\n };\n const keyedOk = /* @__PURE__ */ new Set();\n const keyFirst = /* @__PURE__ */ new Map();\n const KEY_FIRST_MS = 10 * 6e4;\n const keyFirstNow = (room) => {\n const t = keyFirst.get(room);\n return t === Infinity || typeof t === \"number\" && Date.now() < t;\n };\n const verifiedRefusal = (r) => !!(r && r.error === \"no_verified_client\" && (r.status === 403 || r.status === 200));\n const verifiedRooms = /* @__PURE__ */ new Set();\n const attestReadRooms = /* @__PURE__ */ new Map();\n const attestReadWhy = /* @__PURE__ */ new Map();\n const takeReadWhy = (room) => {\n const w = attestReadWhy.get(room);\n attestReadWhy.delete(room);\n return w;\n };\n const attPasses = /* @__PURE__ */ new Map();\n const PASS_USE_MS = 1e5;\n const PASS_OPS = /* @__PURE__ */ new Set([\"poll\", \"pollsealed\", \"blob\", \"pending\"]);\n const passFor = (room, op, body) => {\n const p = attPasses.get(room);\n if (!p || !attestReadRooms.has(room) || Date.now() - p.at > PASS_USE_MS) return null;\n return PASS_OPS.has(op) || op === \"state\" && (!body || body.patch === void 0) ? { readAttestation: { pass: p.pass } } : null;\n };\n const notePass = (room, r) => {\n if (!room || !r) return;\n if (typeof r.attPass === \"string\" && r.attPass) attPasses.set(room, { pass: r.attPass, at: Date.now() });\n else if (r.error === \"attest_required\" && /^attestation: (pass |missing)/.test(String(r.reason || \"\"))) attPasses.delete(room);\n };\n const noteReadChal = (room, r) => {\n if (attestReadRooms.has(room) && r && typeof r.challenge === \"string\" && r.challenge) attestReadRooms.set(room, r.challenge);\n };\n const attestFor = async (room, op = \"\", body = null) => {\n if (attestReadRooms.has(room)) {\n const pass = op ? passFor(room, op, body) : null;\n if (pass) return pass;\n try {\n const p = readAttestProvider();\n const why = takeReadWhy(room);\n const att = p ? await p(room, { read: true, challenge: attestReadRooms.get(room), ...why ? { refused: why } : {} }) : null;\n return att && att.read ? { readAttestation: att.read } : {};\n } catch {\n return {};\n }\n }\n if (!verifiedRooms.has(room)) return {};\n try {\n const p = attestProvider();\n const att = p ? await p(room) : null;\n return att ? { clientAttestation: att } : {};\n } catch {\n return {};\n }\n };\n const withVerified = async (room, doPost) => {\n let r = await doPost();\n notePass(room, r);\n if (verifiedRefusal(r) && !verifiedRooms.has(room)) {\n verifiedRooms.add(room);\n r = await doPost();\n notePass(room, r);\n }\n if (r && r.error === \"attest_required\" && typeof r.challenge === \"string\") {\n attestReadRooms.set(room, r.challenge);\n if (r.reason) attestReadWhy.set(room, String(r.reason));\n r = await doPost();\n }\n notePass(room, r);\n noteReadChal(room, r);\n return r;\n };\n const chains = /* @__PURE__ */ new Map();\n const chainFor = async (room, mk, requireKnown = false) => {\n const k = room + \"|\" + await commit(mk);\n if (chains.has(k)) return chains.get(k);\n let keys = [], known = false;\n try {\n const r = await policyPost(room, mk);\n const cfg = r && r.status === 200 && r.configSealed ? JSON.parse(await open(JSON.parse(r.configSealed), { mk }) || \"null\") : null;\n if (cfg && typeof cfg === \"object\") {\n known = true;\n if (Array.isArray(cfg.keyChain)) keys = cfg.keyChain.filter((x) => x && typeof x.key === \"string\" && x.key && x.key !== mk).map((x) => x.key).reverse();\n }\n } catch {\n keys = [];\n }\n if (known) chains.set(k, keys);\n return known || !requireKnown ? keys : null;\n };\n const openAny = async (room, env, mk, aad = null) => {\n const pt = await open(env, { mk, aad });\n if (pt != null || !room || !mk) return pt;\n for (const k of await chainFor(room, mk)) {\n const o = await open(env, { mk: k, aad });\n if (o != null) return o;\n }\n return null;\n };\n const editField = (opts) => opts && typeof opts.sinceEdit === \"string\" && opts.sinceEdit.length <= 64 ? { sinceEdit: opts.sinceEdit } : {};\n const decodeSealed = async (room, mk, sinceCount, r) => {\n const withPartial = async (o) => {\n let out = o || {};\n if (Array.isArray(r.removed)) out = { ...out, removed: r.removed.filter((x) => x && x.id != null && x.ts != null).slice(0, 500).map((x) => ({ id: String(x.id), ts: Number(x.ts) })) };\n if (typeof r.partial === \"string\") {\n try {\n out = { ...out, partialText: await open(JSON.parse(r.partial), { mk }), partialSeq: r.partialSeq || 0 };\n } catch {\n }\n }\n out = await withTurnStatus(out, r, mk);\n out = await withStreamGrants(out, r, mk);\n if (typeof r.deviceCall === \"string\") {\n try {\n out = { ...out, deviceCall: JSON.parse(await open(JSON.parse(r.deviceCall), { mk })), deviceCallSeq: r.deviceCallSeq || 0 };\n } catch {\n }\n }\n return out;\n };\n if (r.status !== 200 || !r.changed) return await withPartial(r);\n let wrap = null;\n try {\n wrap = JSON.parse(r.sealed);\n } catch {\n wrap = null;\n }\n if (wrap && wrap.v === 3 && Array.isArray(wrap.boxes)) {\n const entries = [];\n const base = Number.isInteger(wrap.from) ? wrap.from : sinceCount;\n let unopenable = 0;\n for (let j = 0; j < wrap.boxes.length; j++) {\n try {\n const pt = await openAny(room, JSON.parse(wrap.boxes[j]), mk, ledgerAad(room, base + j));\n if (pt == null) {\n unopenable++;\n continue;\n }\n entries.push(JSON.parse(pt));\n } catch {\n unopenable++;\n }\n }\n if (wrap.boxes.length && !entries.length && unopenable === wrap.boxes.length) return await withPartial({ status: 422, etag: r.etag, changed: true, reason: \"undecodable\", boxes: wrap.boxes.length, challenge: r.challenge });\n const total = Number.isInteger(r.count) ? r.count : sinceCount + entries.length;\n let edits;\n if (r.edits && typeof r.edits === \"object\" && typeof r.edits.tag === \"string\") {\n const got = [], have = /* @__PURE__ */ new Set();\n for (const pair of Array.isArray(r.edits.boxes) ? r.edits.boxes : []) {\n const i = Array.isArray(pair) ? pair[0] : null;\n if (!Number.isInteger(i) || typeof pair[1] !== \"string\") continue;\n try {\n const pt = await openAny(room, JSON.parse(pair[1]), mk, ledgerAad(room, i));\n if (pt != null) {\n got.push(JSON.parse(pt));\n have.add(i);\n }\n } catch {\n }\n }\n const missing = (Array.isArray(r.edits.at) ? r.edits.at : []).filter((i) => Number.isInteger(i) && !have.has(i));\n edits = { since: typeof r.edits.since === \"string\" ? r.edits.since : void 0, tag: r.edits.tag, entries: got, missing, ...r.edits.lost === true ? { lost: true } : {} };\n }\n return await withPartial({ status: 200, etag: r.etag, changed: true, version: total, entries, ...r.more ? { more: true, ...Number.isInteger(r.total) ? { total: r.total } : {} } : {}, challenge: r.challenge, done: r.done, partial: r.partial, partialSeq: r.partialSeq, boxes: wrap.boxes.length, ...unopenable ? { refused: unopenable } : {}, ...edits ? { edits } : {} });\n }\n let all = null;\n try {\n all = JSON.parse(await openAny(room, JSON.parse(r.sealed), mk));\n } catch {\n all = null;\n }\n if (all && !Array.isArray(all) && Array.isArray(all.entries)) all = all.entries;\n if (!Array.isArray(all)) return { status: 422, etag: r.etag, changed: true, reason: \"undecodable\", challenge: r.challenge };\n const from = Number.isInteger(sinceCount) && sinceCount > 0 ? Math.min(sinceCount, all.length) : 0;\n return await withPartial({ status: 200, etag: r.etag, changed: true, version: all.length, entries: all.slice(from), challenge: r.challenge, partial: r.partial, partialSeq: r.partialSeq });\n };\n const archiveAttachments = async (room, mk, ledger, budget) => {\n const blobs = {}, stats = { total: 0, included: 0, tooLarge: 0, failed: 0, bytes: 0 };\n let entries = [];\n if (ledger && ledger.v === 3 && Array.isArray(ledger.boxes)) {\n const base = Number(ledger.from) || 0;\n for (let j = 0; j < ledger.boxes.length; j++) {\n try {\n const box = ledger.boxes[j], pt = await openAny(room, typeof box === \"string\" ? JSON.parse(box) : box, mk, ledgerAad(room, base + j));\n if (pt != null) entries.push(JSON.parse(pt));\n } catch {\n }\n }\n } else {\n try {\n let all = JSON.parse(await openAny(room, ledger, mk));\n if (all && !Array.isArray(all)) all = all.entries;\n if (Array.isArray(all)) entries = all;\n } catch {\n entries = [];\n }\n }\n const seen = /* @__PURE__ */ new Set(), list = [];\n for (const e of entries) {\n for (const k of [\"images\", \"files\"]) {\n for (const a of e && Array.isArray(e[k]) ? e[k] : []) {\n if (!a || typeof a.b64 === \"string\" && a.b64) continue;\n const refs = Array.isArray(a.parts) && a.parts.length ? a.parts : typeof a.ref === \"string\" && a.ref ? [a.ref] : [];\n if (!refs.length || refs.some((x) => typeof x !== \"string\" || !x)) continue;\n const id = refs.join(\" \");\n if (seen.has(id)) continue;\n seen.add(id);\n list.push({ refs, size: Number(a.size) || 0 });\n }\n }\n }\n stats.total = list.length;\n for (const { refs, size } of list) {\n if (size > 0 && stats.bytes + Math.ceil(size * 4 / 3) > budget) {\n stats.tooLarge++;\n continue;\n }\n const got = [];\n let n = 0, failed = false;\n for (const ref of refs) {\n let r = null;\n try {\n r = await withVerified(room, async () => sealedRead(room, mk, \"blob\", { ref }));\n } catch {\n r = null;\n }\n if (!r || r.status !== 200 || r.sealed == null) {\n failed = true;\n break;\n }\n got.push([ref, r.sealed]);\n n += (typeof r.sealed === \"string\" ? r.sealed : JSON.stringify(r.sealed)).length;\n }\n if (failed) {\n stats.failed++;\n continue;\n }\n if (stats.bytes + n > budget) {\n stats.tooLarge++;\n continue;\n }\n for (const [ref, sealed] of got) blobs[ref] = sealed;\n stats.bytes += n;\n stats.included++;\n }\n return { blobs, stats };\n };\n const api = {\n _openAny: openAny,\n // internal: a box opened with the room's key or, after an in-place change, an earlier one (tests)\n /** Mint a Space from a config, register its PUBLIC record (commit + config) with the server, and return\n * { room, mk, commit, links, keyModel }. `mk` is reconstructed locally from the minted pieces — it is NEVER sent\n * to the server (only its commitment is). The `links` are what you hand to members. */\n async create(config = {}, { base = originBase(), gk, enclave: enclaveOpt, split = false, via = null, lapseDays } = {}) {\n const space = await createConfiguredSpace(config, { base });\n const mk = await mkFromLinks(space.links, config, space.commit);\n if (config && config.admission === \"email\" && config.allow) {\n const a = config.allow;\n const dom = Array.isArray(a.domains) ? a.domains.filter(Boolean) : [];\n const handles = (Array.isArray(a.handles) ? a.handles : []).filter((h) => typeof h === \"string\" && h);\n const hashOf = async (list) => {\n const mh2 = [];\n for (const em of list || []) {\n const h = await memberHash(em, space.room);\n if (h && !mh2.includes(h)) mh2.push(h);\n }\n return mh2;\n };\n const shown = Array.isArray(a.hidden) ? (Array.isArray(a.emails) ? a.emails : []).filter(Boolean) : [];\n const toHash = [...Array.isArray(a.hidden) ? a.hidden : Array.isArray(a.emails) ? a.emails : [], ...handles];\n const mh = await hashOf(toHash);\n for (const u of Array.isArray(a.tagUsers) ? a.tagUsers : []) {\n const r2 = await post({ op: \"user\", mode: \"tag\", username: u, room: space.room });\n if (!r2 || r2.status !== 200 || typeof r2.tag !== \"string\" || !r2.tag) throw Object.assign(new Error(\"@\" + u + \" could not be added (\" + (r2 && (r2.error || r2.status) || \"no answer\") + \")\"), { status: r2 && r2.status || 0, code: \"user_tag\" });\n if (!mh.includes(r2.tag)) mh.push(r2.tag);\n }\n if (shown.length || mh.length || dom.length) config = { ...config, allow: { ...shown.length ? { emails: shown } : {}, ...mh.length ? { mh } : {}, ...dom.length ? { domains: dom } : {} } };\n }\n let ownerFields = {};\n if (config && (config.requireApp === \"served\" || config.requireApp === \"emulated\" || typeof config.ownerFor === \"function\")) throw Object.assign(new Error(\"a Space only a web page served as an app may use is retired — attested Spaces are made in the Witbitz app on iPhone, Android or Mac\"), { status: 410, code: \"level_retired\" });\n if (config && (config.requireApp === \"android\" || config.requireApp === \"app\" || config.requireApp === \"windows\")) {\n const g = await post({ op: \"owner-policy\", room: space.room, level: config.requireApp });\n if (!g || g.status !== 200 || !g.ownerPolicy || !g.roomAuth) throw Object.assign(new Error(\"the Witbitz app requirement could not be set (\" + (g && (g.error || g.status) || \"no answer\") + \")\"), { status: g && g.status || 503 });\n const { requireApp: _r, requireAppId: _ra, attestAccept: acc, ...rest } = config;\n config = { ...rest, ownerPolicy: g.ownerPolicy };\n ownerFields = { ownerPolicy: g.ownerPolicy, roomAuth: g.roomAuth, ...acc ? { attestAccept: acc } : {} };\n }\n const configSealed = await sealConfig(config, mk);\n const sp = split ? splitKey(mk) : null;\n const send = typeof via === \"function\" ? via : post;\n const dc = typeof delCommit === \"function\" ? await delCommit(space.room).catch(() => null) : null;\n const r = await send({ op: \"create\", ...app ? { app } : {}, room: space.room, commit: space.commit, configSealed, invite: invitePad(), ...Number.isInteger(lapseDays) && lapseDays >= 1 && lapseDays <= 7 ? { lapseDays } : {}, ...ownerFields, ...dc ? { delCommit: dc } : {}, ...sp ? { appShare: sp.shareB } : {}, ...embedAttribution(), ...tenantHint, ...config.admission === \"email\" ? { gated: true } : {}, ...config.requireVerifiedClient ? { requireVerifiedClient: true } : {}, ...gk ? { gk } : {}, ...enclaveOpt ? { enclave: true } : {}, ...config.help === true && config.install === true ? { installHelp: true } : {} });\n if (r.status !== 200) throw Object.assign(new Error(`create failed: ${r.status} ${r.error || \"\"}${r.reason ? \" — \" + r.reason : \"\"}`), { status: r.status, ...r.error ? { code: String(r.error) } : {}, ...r.reason ? { reason: r.reason } : {} });\n if (config.admission === \"email\") {\n gatedRooms.add(space.room);\n if (config.ownerPolicy) keyFirst.set(space.room, Infinity);\n }\n if (config.requireVerifiedClient) verifiedRooms.add(space.room);\n return { room: space.room, mk, commit: space.commit, links: space.links, keyModel: space.keyModel, configSealed, ...sp ? { userShare: sp.shareA } : {}, ...enclaveOpt && r.created === true ? { enclaveCreated: true } : {} };\n },\n /** The app half of a SPLIT room, for a page on an origin the room's tenant declared (op:'appshare-page'). → { status, appShare, commit } */\n appSharePage: async (room) => post({ op: \"appshare-page\", room }),\n /** Open a Space from the member link(s) this client actually holds → { room, mk }. `mk` is null below the key\n * threshold (e.g. one partner's link alone in a 2-of-2 Space — the other share must be combined first). */\n async open(links, config = {}, commit2) {\n const arr = Array.isArray(links) ? links : [links];\n const room = parseConfiguredLink(arr[0] || \"\").room;\n if (config && config.admission === \"email\" && room) gatedRooms.add(room);\n return { room, mk: await mkFromLinks(arr, config, commit2) };\n },\n // ── 2-of-2 (couple), async code-sealed handshake ──────────────────────────────────────────────────────────────\n /** Create a 2-of-2 Space. Returns { room, mk, partnerLink, code, commit }. The creator holds `mk`; hand the partner\n * `partnerLink` (their share) + `code` (out of band). shareA is SEALED under the code and registered as the room's\n * invite — the server only ever stores ciphertext. */\n async createCouple(config = {}, { base = originBase(), gk } = {}) {\n const cfg = { ...config, keyModel: \"2-of-2\" };\n const space = await createConfiguredSpace(cfg, { base });\n const shareA = parseConfiguredLink(space.links[0]).share;\n const partnerLink = space.links[1];\n const code = newCode();\n const invite = await sealUnderCode(shareA, code);\n const mk = await assembleConfiguredKey([shareA, parseConfiguredLink(partnerLink).share], cfg, space.commit);\n const r = await post({ op: \"create\", ...app ? { app } : {}, ...tenantHint, room: space.room, commit: space.commit, invite, configSealed: await sealConfig(config, mk), ...gk ? { gk } : {} });\n if (r.status !== 200) throw Object.assign(new Error(`create failed: ${r.status} ${r.error || \"\"}${r.reason ? \" — \" + r.reason : \"\"}`), { status: r.status, ...r.error ? { code: String(r.error) } : {}, ...r.reason ? { reason: r.reason } : {} });\n return { room: space.room, mk, partnerLink, code, commit: space.commit };\n },\n /** Join a 2-of-2 Space from a partner's share-link + the code → { room, mk }. Fetches the sealed shareA, unseals it\n * with the code, and combines with this link's share. `mk` is null on a wrong code or a commitment mismatch. */\n async joinWithCode(link, code) {\n const p = parseConfiguredLink(link);\n if (!p.room || !p.share) return { room: p.room || \"\", mk: null, error: \"bad_link\" };\n const r = await post({ op: \"invite\", room: p.room });\n if (r.status !== 200 || !r.invite) return { room: p.room, mk: null, error: \"no_invite\" };\n const shareA = await openUnderCode(r.invite, code);\n if (!shareA) return { room: p.room, mk: null, error: \"bad_code\" };\n const mk = await assembleConfiguredKey([shareA, p.share], { keyModel: \"2-of-2\" }, r.mkCommit);\n return { room: p.room, mk, error: mk ? void 0 : \"mismatch\" };\n },\n /** Post a turn. `identity` SIGNS it (the entry is signed over its core; the server verifies in-render). Two shapes:\n * • EMAIL gate: `{ email, sign:{priv,pub}, googleIdToken }` → sends `{ from:email, ts, id, kind, sig, spk, idToken }`.\n * The Google token proves the email (bound to `spk` via its nonce); the server checks it against the sealed\n * allow-list and DISCARDS it.\n * • INVITE gate: `{ name, sign:{priv}, grant }` → sends `{ from:name, ts, id, kind, sig, grant }` (Kibitz invite).\n * • ATTESTED-ROOM KEY: `{ name, sign:{priv,pub}, attestKey:true }` → sends `{ from:name, ts, id, kind, sig, spk }` — a\n * member who joined an attested room through its box holds no grant; the server checks the signature against `spk`.\n * Omit `identity` → an unsigned turn (open/legacy rooms), unchanged.\n * `bridgeMk` (private-lane turns only, docs/spaces-private-lane.md): the SHARED room's key, so the runtime can\n * fold the shared negotiation into the agent's context (it OBSERVES the shared room). Ignored by normal rooms. */\n // ONE SIGN-IN PER TURN (2026-11-21): a lane's turn whose message carries its own sign-in sends no second one for the Space it\n // reads (otherAuth) — the server checks the shared room with the message's (spaceService otherRoomAdmits: req.idToken ||\n // m.idToken), and the room pass's psig binds ONE sign-in key: with two (one per room) it covered the top-level one while the\n // turn was checked with the message's, and every first message in a private assistant of a verified group was refused\n // `pass: psig_signature` (\"Your sign-in expired\").\n async turn(room, mk, message, identity2, { bridgeMk, bridgeRoom, viewSource, mode, links, context, instructions, clientTools, clientGuidance, call: call2, stopKey, model, receipt, showPrompt, run, schema } = {}, billingToken) {\n let m = message;\n const text = String(message && message.text || \"\");\n if (identity2 && identity2.googleIdToken && identity2.sign && identity2.sign.priv && identity2.sign.pub) {\n const ts = Date.now();\n const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`;\n const author = message && typeof message.from === \"string\" && message.from.trim() ? message.from : identity2.email;\n const { sig } = await signEntry(identity2.sign.priv, { room, author, ts, kind: \"text\", id, text, ...message && message.chal ? { chal: message.chal } : {} });\n m = { ...message, from: author, ts, id, kind: \"text\", sig, spk: identity2.sign.pub, idToken: identity2.googleIdToken };\n } else if (identity2 && identity2.grant && identity2.sign && identity2.sign.priv) {\n const ts = Date.now();\n const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`;\n const { sig } = await signEntry(identity2.sign.priv, { room, author: identity2.name, ts, kind: \"text\", id, text, ...message && message.chal ? { chal: message.chal } : {} });\n m = { ...message, from: identity2.name, ts, id, kind: \"text\", sig, grant: identity2.grant };\n } else if (identity2 && identity2.attestKey === true && identity2.sign && identity2.sign.priv && identity2.sign.pub) {\n const ts = Date.now();\n const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`;\n const { sig } = await signEntry(identity2.sign.priv, { room, author: identity2.name, ts, kind: \"text\", id, text, ...message && message.chal ? { chal: message.chal } : {} });\n m = { ...message, from: identity2.name, ts, id, kind: \"text\", sig, spk: identity2.sign.pub };\n }\n return post({ op: \"turn\", room, ...await keyFields(room, \"turn\", mk), message: m, ...viewSource ? { viewSource } : {}, ...pushSelf() ? { pushSelf: pushSelf() } : {}, ...await pushAcctField(room), ...await crossingPush(bridgeRoom), ...bridgeMk ? await bridgeFields(room, \"turn\", bridgeMk) : {}, ...bridgeRoom ? { bridgeRoom } : {}, ...m && m.idToken ? {} : await otherAuth([bridgeRoom, ...Array.isArray(links) ? links.map((l) => l && l.room) : []]), ...mode ? { mode } : {}, ...Array.isArray(links) && links.length ? await linksFields(room, \"turn\", links) : {}, ...context ? { context } : {}, ...instructions ? { instructions: String(instructions) } : {}, ...Array.isArray(clientTools) && clientTools.length ? { clientTools } : {}, ...clientGuidance ? { clientGuidance } : {}, ...call2 ? { call: 1 } : {}, ...stopKey ? { stopKey } : {}, ...model ? { model } : {}, ...receipt && receipt.drop ? { receipt } : {}, ...showPrompt === true ? { showPrompt: true } : {}, ...run === true ? { run: true } : {}, ...run === true && schema ? { schema } : {} }, billingToken);\n },\n // USAGE RECEIPTS (docs/usage-receipts.md): this account's sealed receipts in a room, at its per-room drop, and the trim\n // once they are folded into the account's sidecar. Keyless: the drop is the capability; every box is sealed to us.\n receipts: async (room, drop, since = 0) => post({ op: \"receipts\", room, drop, sinceCount: since }),\n receiptsAck: async (room, drop, upTo) => post({ op: \"receiptsack\", room, drop, upTo }),\n // STRAY NOTIFICATIONS (strayPush.js, agent/pushDrop.mjs): this device has no key for the room; ask for its own push\n // address to come off the room's list. Keyless — the address is the capability, and only its hash is kept.\n pushDrop: async (room, subscription) => post({ op: \"pushdrop\", room, subscription: { endpoint: subscription && subscription.endpoint } }),\n // MEMBERSHIP MARK (docs/user-erasure.md § Authority): this account opened the room — a creator's delete then sees it was shared\n mark: async (room, mk, drop) => post({ op: \"mark\", room, ...await keyFields(room, \"mark\", mk), drop, ...await authFor(room) }),\n /** LEAVE A VERIFIED ROOM (agent/roomLeave.mjs): hands over this account's marks ({drops}) and delete secrets ({dels}) → { status, left, last, drops?, dels? } — `last`: no one who joined is left, delete it with what came back. */\n leave: async (room, mk, leave) => post({ op: \"leave\", room, ...await keyFields(room, \"leave\", mk), leave: { drops: [...leave && leave.drops || []].slice(0, 16), dels: [...leave && leave.dels || []].slice(0, 8) }, ...await authFor(room) }),\n // Seed the Space from a PUBLIC ChatGPT share link → continue a one-on-one chat together. The Lambda fetches +\n // parses it (SSRF-guarded) and seals the history into the ledger; the URL is public so this carries no secret.\n importChat: async (room, mk, chatgptUrl, billingToken) => post({ op: \"import\", room, ...await keyFields(room, \"import\", mk), chatgptUrl, ...await authFor(room) }, billingToken),\n // `hints` { tz, order }: the client's time zone (getTimezoneOffset) and date order — each message keeps its own WhatsApp time (side\n // sweep: sdk-whatsapp-import-restamps-message-times); an older server ignores them\n importWhatsApp: async (room, mk, whatsappText, billingToken, hints) => post({ op: \"import\", room, ...await keyFields(room, \"import\", mk), whatsappText, ...hints && Number.isInteger(hints.tz) ? { whatsappTz: hints.tz } : {}, ...hints && typeof hints.zone === \"string\" && /^[A-Za-z0-9_+\\-/]{1,64}$/.test(hints.zone) ? { whatsappZone: hints.zone } : {}, ...hints && (hints.order === \"mdy\" || hints.order === \"dmy\") ? { whatsappOrder: hints.order } : {}, ...await authFor(room) }, billingToken),\n // WhatsApp export: client unzipped the _chat.txt → server parses + seals\n // MIRROR — append entries this device copied from a LINKED room (docs/spaces-private-lane.md) into THIS room's ledger,\n // no agent turn. Deduped by entry id server-side. Files/images ride along so the assistant reads them natively.\n mirror: async (room, mk, entries) => {\n const send = async (batch2) => {\n const kf = await keyFields(room, \"mirror\", mk);\n const ef = enclaveFor(room) ? await sealField(room, \"mirror:entries\", JSON.stringify(batch2), \"mirror\") : { entries: batch2 };\n return post({ op: \"mirror\", room, ...kf, ...ef, ...await authFor(room) });\n };\n const batch = entries || [];\n const prepared = await stageMirrorAttachments(batch, send);\n return prepared.error || send(prepared.entries);\n },\n // CARRY — a verified room's MOVE: the SERVER copies the old room's history into this one (minted with forkedFrom = that\n // room), keeping each entry's verified mark as `carried` (agent/spaceService.mjs op 'carry'). One page per call → { carried,\n // next, total }; loop while `next` is a number. The old room's key rides like a lane's bridge key: sealed to the\n // enclave on a confidential room (AAD op 'carry:bridge'), and filled in by the room worker when only bridgeRoom is given.\n carry: async (room, mk, { bridgeRoom, bridgeMk, cursor = 0 } = {}) => post({ op: \"carry\", room, ...await keyFields(room, \"carry\", mk), ...bridgeMk ? await bridgeFields(room, \"carry\", bridgeMk) : {}, bridgeRoom, ...Number.isInteger(cursor) && cursor > 0 ? { sinceCount: cursor } : {}, ...await authFor(room) }),\n // Generate (or fetch) a real one-line conversation title, sealed to the room so both members share it.\n // `set` = { title, by }: a member RENAMES the room — the server appends it to the room's log (spaces/public/roomName.js).\n title: async (room, mk, recheck, set, billingToken) => post({ op: \"title\", room, ...await keyFields(room, \"title\", mk), ...recheck ? { recheck: true } : {}, ...set && set.title ? { set: String(set.title), ...set.by ? { by: String(set.by).slice(0, 80) } : {}, ...pushSelf() ? { pushSelf: pushSelf() } : {}, ...await pushAcctField(room) } : {}, ...await authFor(room) }, billingToken),\n // The DEFAULT loop. Opens the in-progress reply the same way pollSealed does — the server passes it through\n // sealed on both paths, so the two stay drop-in interchangeable mid-session.\n decodeSealed,\n poll: async (room, mk, sinceEtag, sinceCount = 0, opts = {}) => {\n const ci = opts && typeof opts.changeInbox === \"string\" ? { changeInbox: opts.changeInbox } : {};\n const ed = editField(opts);\n if (enclaveFor(room)) return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, ...ed });\n return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, ...ed, proveKey: !!ci.changeInbox });\n },\n /** CONTENT-BLIND poll — the same contract as `poll`, but `mk` NEVER leaves this device. The server returns the\n * sealed ledger and we open it here, so the hot loop (a poll every ~600ms while the Space is on screen) stops\n * carrying the room key; only `turn` still does, because the agent genuinely needs plaintext.\n * Returns the IDENTICAL shape to `poll` — { status, etag, changed, version, entries } — so it is a drop-in swap\n * and the caller's render path is unchanged. A key that doesn't fit surfaces as the same 422/'undecodable' the\n * server used to return, except now the CLIENT proves it rather than being told. */\n async pollSealed(room, mk, sinceEtag, sinceCount = 0, opts = {}) {\n const ci = opts && typeof opts.changeInbox === \"string\" ? { changeInbox: opts.changeInbox } : {};\n const sent = { keyed: false };\n const send = async () => sealedRead(room, mk, \"pollsealed\", { sinceEtag, sinceCount, ...ci, ...editField(opts) }, { proveKey: !!(opts && opts.proveKey && mk && !enclaveFor(room)), sent });\n const r = await withVerified(room, send);\n const out = await decodeSealed(room, mk, sinceCount, r);\n if (out && out.status === 422 && out.reason === \"undecodable\" && mk && !sent.keyed) {\n const r2 = await withVerified(room, async () => sealedRead(room, mk, \"pollsealed\", { sinceEtag, sinceCount, ...ci, ...editField(opts) }, { proveKey: true }));\n return decodeSealed(room, mk, sinceCount, r2);\n }\n return out;\n },\n // Full SEALED ledger (ciphertext) for a durable LOCAL backup — the raw stored blob (v1/v2 whole, or the v3\n // { v:3, boxes:[…] } wrapper), NOT opened here. sinceCount:0 ⇒ everything. Same gated-retry as pollSealed. The\n // downloaded file carries no plaintext — it is only readable with the room key, via the offline decryptor\n // (/decrypt.html). Returns { status, sealed, count, etag }.\n // `opts.attachments = { budget }` (bytes, > 0): the OFFLINE COPY also carries the attachments stored out of line\n // (agent/attachmentBlobs.mjs) — their sealed envelopes exactly as stored, under `blobs` beside the boxes, up to `budget`;\n // the answer's `attachments` says how many went in and how many were left out (archiveAttachments below). Without it the\n // answer is unchanged — sealedProof hashes it (witbitz-sdk.js receipt).\n exportSealed: async (room, mk, opts = {}) => {\n const archive = await readSealedArchive((sinceCount) => withVerified(room, () => sealedRead(room, mk, \"pollsealed\", { sinceCount })));\n if (archive?.status !== 200 || !archive.sealed) return archive;\n const ledger = JSON.parse(archive.sealed);\n if (ledger.v === 3 && Array.isArray(ledger.boxes)) {\n const previous = await chainFor(room, mk, true);\n if (!previous) {\n for (const [index, item] of ledger.boxes.entries()) {\n let box;\n try {\n box = typeof item === \"string\" ? JSON.parse(item) : item;\n } catch {\n }\n if (await open(box, { mk, aad: ledgerAad(room, (ledger.from || 0) + index) }) == null) return { status: 409, error: \"archive_incomplete\" };\n }\n }\n if (previous?.length) ledger.keyHistory = await seal(JSON.stringify({ room, keys: previous }), { room: mk });\n }\n const budget = Number(opts && opts.attachments && opts.attachments.budget);\n if (!(budget > 0)) return { ...archive, sealed: JSON.stringify(ledger) };\n const { blobs, stats } = await archiveAttachments(room, mk, ledger, budget);\n if (Object.keys(blobs).length) ledger.blobs = blobs;\n return { ...archive, sealed: JSON.stringify(ledger), attachments: stats };\n },\n pending: async (room, mk) => post({ op: \"pending\", room, ...await keyFields(room, \"pending\", mk), ...await authFor(room) }),\n /** APPROVAL REMINDERS for Code (agent/approvalRemind.mjs): this device's push address, signed by the server, for the\n * computer to name when an approval waits there → { status, grant }. `endpointUrl` = where the computer sends it. */\n /** OPTION B: fetch this sign-in's hints ahead of need (at sign-in, on launch), so the fetch is not tied to a room request. */\n prefetchIdentity: async (idToken) => {\n try {\n if (typeof idToken === \"string\" && idToken) await extrasFor(idToken);\n } catch {\n }\n },\n remindGrant: async (subscription, others) => post({ op: \"remindgrant\", subscription, ...Array.isArray(others) && others.length ? { subscriptions: others.slice(0, 16) } : {} }),\n // others: the account's other devices (approvalRemind.makeGrant)\n endpointUrl: () => {\n try {\n return new URL(endpoint, typeof location !== \"undefined\" ? location.href : void 0).href;\n } catch {\n return \"\";\n }\n },\n /** Fetch an OUT-OF-LINE image blob by its ledger pointer and open it here → { status, b64, mime }.\n * The request carries no key (the bytes are sealed; serving ciphertext reveals nothing) — `mk` is used locally to\n * open the envelope, exactly like pollSealed. Blobs are content-addressed and immutable, so a caller may cache the\n * result against `ref` forever without revalidating. */\n /** A connection's TOOL BOOK (agent/toolBook.mjs): its full tool list sealed once into the room → { status, ref, sha256, n }. */\n // carries the member's sign-in like setConfig (authFor): a verified Space refuses it without — the app then saved the whole list (2026-11-17)\n /** THE ROOM'S TOOLS for its ⋯ → Tools sheet (agent/spaceService.mjs op toolrules; toolRules.js) → { status, tools: [{ name, about,\n * default, now, rule? }], rules }. The rules themselves are written with state(…, 'toolrules', …). */\n toolRules: async (room, mk, { bridgeRoom, bridgeMk } = {}) => post({\n op: \"toolrules\",\n room,\n ...await keyFields(room, \"toolrules\", mk),\n ...bridgeRoom ? { bridgeRoom, ...bridgeMk ? await bridgeFields(room, \"toolrules\", bridgeMk) : {} } : {},\n ...await otherAuth([bridgeRoom]),\n ...await authFor(room)\n }),\n toolBook: async (room, mk, tools) => post({ op: \"toolbook\", room, ...await keyFields(room, \"toolbook\", mk), toolbook: { tools: Array.isArray(tools) ? tools.slice(0, 400) : [] }, ...await authFor(room) }),\n async blob(room, mk, ref) {\n const r = await withVerified(room, async () => sealedRead(room, mk, \"blob\", { ref }));\n if (r.status !== 200 || !r.sealed) return r;\n try {\n const o = JSON.parse(await openAny(room, r.sealed, mk));\n if (!o || typeof o.b64 !== \"string\") return { status: 422, reason: \"undecodable\" };\n return { status: 200, ref, b64: o.b64, mime: o.mime || \"image/jpeg\" };\n } catch {\n return { status: 422, reason: \"undecodable\" };\n }\n },\n /** Register this device for push. The subscription is sealed into the room's doc server-side (it is room metadata:\n * which devices care about this room), so it needs mk like any other sealed write. */\n // mk goes through keyFields() like every other material op (turn/import/mirror/title/poll) — so on an ENCLAVE room it\n // is SEALED to the enclave key and the parent relay never sees the raw key (fail-closed for an enclave room with no\n // key). Default tier: keyFields is the identity function → raw {mk}, unchanged. (Was: raw mk in the body — the one\n // material op that skipped the seal, leaking the room key to the parent relay on enclave rooms. Security review #2.)\n subscribe: async (room, mk, subscription, by, quiet) => post({ op: \"subscribe\", room, ...await keyFields(room, \"subscribe\", mk), subscription, by, ...await pushAcctField(room), ...quiet ? { quiet: true } : {}, ...await authFor(room) }),\n // quiet: a bulk or automatic registration — store it, no confirmation push\n /** Turn notifications off for this device. Sends the subscription so the server can drop it by endpoint. */\n unsubscribe: async (room, mk, subscription) => post({ op: \"unsubscribe\", room, ...await keyFields(room, \"unsubscribe\", mk), subscription, ...await authFor(room) }),\n // Content-blind transparency read (the \"trust receipt\"): the EXACT ciphertext the server stores for this room +\n // its recipients. No mk sent — reading ciphertext reveals nothing. → { alg, bytes, sha256, recipients, sealed }.\n sealed: async (room) => post({ op: \"sealed\", room }),\n // VERIFIED-CLIENT capability blob (spaces/public/capLink.js). vcput MINTS: store the OPAQUE {mk}-sealed-under-token\n // ciphertext under a one-way capId — mk-commit gated server-side (only an mk-holder may write it), content-blind\n // (the server sees only id + ciphertext, never the token or mk). vcget RESOLVES: fetch it, ATTESTATION-gated (the\n // gateway withholds without a fresh, approved client-release attestation); carries NO mk — the token off the ?vc=\n // link (never sent to the server with the extension) is what opens the blob, unsealed by L1 locally.\n vcput: async (room, mk, capId, capSealed) => post({ op: \"vcput\", room, capId, capSealed, ...await keyFields(room, \"vcput\", mk), ...await authFor(room) }),\n // email-gated like every keyed write\n vcget: async (room, capId, attestation) => post({ op: \"vcget\", room, capId, ...attestation ? { clientAttestation: attestation } : {} }),\n // The attested client's DEVICE enrollment (docs/the-attested-client.md § The wire; deviceAttest.js): a new hardware key's\n // platform attestation, bound to THIS room's fresh challenge and the member's signing key. Account-level — no mk.\n attestEnroll: async ({ room, chal, spk, enroll }) => post({ op: \"attest-enroll\", room, chal, ...spk ? { spk } : {}, enroll }),\n // A WINDOWS DEVICE'S ACTIVATION BY AN ENCLAVE (agent/winActivation.mjs): `to` 'turn' (confidential rooms) | 'sentinel' (the backup's\n // K_att); `start` → { activate, ticket }, `finish` (the TPM's answer + the ticket) → { ok }. The front keeps the sealed record.\n winAct: async ({ to, step, keyId, activation, ticket }) => post({ op: \"winact\", winact: { to, step, keyId, ...activation ? { activation } : {}, ...ticket ? { ticket } : {} } }),\n // \"Verify this device\" (agent/deviceVerify.mjs, docs/device-verify.md): the hardware key's signature over a CHECKER's nonce.\n // The answer is only the key code — the verdict is collected and checked by the checker, never shown here.\n // Witbitz Mail's receive prototype (agent/mailIntake.mjs): a mail address that drops into this Space's intake.\n mailRoute: async (intake, space) => post({ op: \"mail-route\", mail: { intake, space } }),\n mailRevoke: async (intake, space) => post({ op: \"mail-revoke\", mail: { intake, space } }),\n // stop receiving: the enclave ends the address (agent/mailIntake.mjs revokeOp)\n deviceVerify: async ({ platform, keyId, nonce, assertion, sig, integrity }) => post({ op: \"device-verify\", device: { platform, keyId, nonce, ...assertion ? { assertion } : {}, ...sig ? { sig } : {}, ...integrity ? { integrity } : {} } }),\n // the ATTESTED BACKUP (agent/attestedBackup.mjs): op 'attested-chal' | 'attested-get' | 'attested-put', the fields in `attested`\n attestedOp: async (op, attested, chal) => post({ op, attested, ...chal ? { chal } : {} }),\n // the record of the account's EARLIER keys beside it (agent/attestedPrev.mjs): `mode` chal | get (attested) | put (the new master's proof)\n attestedPrevOp: async (mode, prev, chal) => post({ op: \"attested-prev\", prev: { ...prev || {}, mode }, ...chal ? { chal } : {} }),\n // K_att (infra/cloud-computer/sentinel/attkey.mjs): `mode` chal | get — the standing Sentinel's challenge, then the secret sealed to\n // the device's one-time key (attested.epk), after the attestation it verifies itself. The Space Lambda only relays.\n attkeyOp: async (mode, attested, chal) => post({ op: \"attkey\", ...mode === \"chal\" ? { mode: \"chal\" } : {}, attested, ...chal ? { chal } : {} }),\n // DEVICE tool result — return a client-executed tool's answer (e.g. a calendar read the agent asked for) to the\n // blocked turn. The result is SEALED HERE under mk (content-blind at rest, opened only by the turn); mk never leaves.\n // `{ claim }` instead of a result: claim the call for this device before a tool with a side effect (G#3) — no result,\n // nothing sealed; → { ok, claimed } (claimed false: another device runs it).\n toolResult: async (room, mk, callId, result, opts = {}) => {\n if (opts && opts.claim) return post({ op: \"toolresult\", room, callId, toolClaim: String(opts.claim) });\n const resBox = JSON.stringify(await seal(typeof result === \"string\" ? result : JSON.stringify(result), { room: mk }));\n return post({ op: \"toolresult\", room, callId, resBox });\n },\n // KEEP-ALIVE (docs user-data-lifecycle): extend the idle-expiry of rooms THIS device holds. Called once per open\n // with room ids from the device's OWN recents list — no mk, no content — so the server never learns which rooms are\n // whose (the client does the fan-out; the server just pushes each `lapsesAt` out). Bounded here and again server-side;\n // best-effort by contract → a Space's life must never hinge on this succeeding. → { ok, rooms }.\n touch: async (rooms) => post({ op: \"touch\", rooms: (Array.isArray(rooms) ? rooms : [rooms]).filter((r) => typeof r === \"string\" && r).slice(0, 200) }),\n // §APP STORE Stage 2: the PUBLIC registry-backed app catalog (no room/mk/auth) → { status, apps:[…] }.\n apps: async () => post({ op: \"apps\" }),\n // The create-screen capability probe (model catalog + whether temporary Spaces are supported) — same keyless shape\n // as `apps` above, and it belongs here for the same reason: `post` is the transport that actually works everywhere.\n // The picker used to call `fetch(endpoint, …)` directly, which (a) is not the path a VAULT-framed tenant app uses,\n // so the Model row silently never appeared there while the App row — routed through here — did, and (b) bypasses\n // the OHTTP relay, so with \"Hide my IP\" on, merely opening New Space leaked the device IP to the API.\n models: async () => post({ op: \"models\" }),\n // Stop a running turn (docs/spaces-stop-turn.md). Keyless — the per-turn nonce IS the authorization — but it must\n // still go through `post` for the same two reasons as `models`: it has to work in a vault-framed tenant app, and a\n // direct fetch would step outside the OHTTP relay (leaking the IP on the very op that says \"stop reading me\").\n stop: async (room, key) => post({ op: \"stop\", room, key }),\n // Tier-2 server-blind email invites (docs/spaces-email-invite.md) — identity-plane, no room/mk.\n // oprf: evaluate a blinded point → { z, proof, kpub } (the client verifies the DLEQ + unblinds to a handle).\n // dirGet: public lookup of a handle → { entry:{ boxPub, inbox } } or 404. dirPut: publish/rotate this user's own\n // slot, authenticated by the email-login idToken (the server checks OPRF(email)==handle so nobody can squat a slot).\n oprf: async (blinded) => post({ op: \"oprf\", blinded }),\n // dirGet: public lookup of a handle → { entry:{ boxPub, inbox } } or 404. A member who closed the EMAIL door (Settings →\n // \"People can find me by my email address\", off) answers 404 like an unknown address — except to THEMSELF: pass the\n // sign-in `idToken` (+ the tenant `scope`, as dirPut does) and the row answers its owner (sign-in's \"welcome back\",\n // recovery's duplicate guard). dirDiscoverable: that switch — the row is named by the token, not a handle.\n dirGet: async (handle, { idToken, scope, app: app2 } = {}) => post({ op: \"dir\", mode: \"get\", handle, ...idToken ? { idToken } : {}, ...scope ? { dirScope: scope } : {}, ...app2 ? { app: app2 } : {} }),\n // app: another slot of the account (an attested box, attestedBox.js)\n dirDiscoverable: async (discoverable, idToken, scope) => post({ op: \"dir\", mode: \"discoverable\", discoverable: discoverable !== false, idToken, ...scope ? { dirScope: scope } : {} }),\n dirPut: async (handle, entry, idToken, scope, app2) => post({ op: \"dir\", mode: \"put\", handle, entry, idToken, ...scope ? { dirScope: scope } : {}, ...app2 ? { app: app2 } : {} }),\n // dirScope: the per-tenant handle namespace — the server re-derives OPRF(scope·email) to match (else a scoped account's put is handle_mismatch)\n // USERNAMES (docs/spaces-usernames.md §4): a public \"@name\" → the account's directory HANDLE (never its email).\n // resolve is public; whoami/claim/release prove the account with the same sign-in token the directory put uses.\n userResolve: async (username, app2) => post({ op: \"user\", mode: \"resolve\", username, ...app2 ? { app: app2 } : {} }),\n // app: which of the account's slots comes back with the handle\n // A member by @username, as the room-bound TAG no guessed email can be linked to (docs/spaces-usernames.md §12)\n userTag: async (username, room) => call(endpoint, { op: \"user\", mode: \"tag\", username, room }, f),\n // a DIRECTORY op (the room is only its salt): the Lambda answers it for a room of either tier — through post() a confidential room's went to the enclave, which has no directory (sync sweep 10-21 #5)\n userWhoami: async (idToken) => post({ op: \"user\", mode: \"whoami\", idToken }),\n userAsUser: async (asUser, idToken) => extrasCache.clear() || post({ op: \"user\", mode: \"asuser\", asUser: asUser !== false, idToken }),\n // \"Add me to Spaces as @username\" (docs/spaces-usernames.md § 13); the hints carry it, so they are asked again\n userClaim: async (username, idToken, { name, publish } = {}) => extrasCache.clear() || post({ op: \"user\", mode: \"claim\", username, idToken, ...publish ? { publish: true, ...name ? { name } : {} } : {} }),\n userRelease: async (idToken, username) => extrasCache.clear() || post({ op: \"user\", mode: \"release\", idToken, ...username ? { username } : {} }),\n // username (optional): only that name — the server refuses 'changed' when the account holds another now\n dirErase: async (idToken, scope) => post({ op: \"dir\", mode: \"erase\", idToken, ...scope ? { dirScope: scope } : {} }),\n // DELETE MY ACCOUNT (docs/user-erasure.md): the token's own directory row + inboxes\n // The invite inbox: drop a sealed box into a recipient's mailbox; inboxFetch reads YOUR mailbox (openBox with boxPriv).\n drop: async (inbox, box) => post({ op: \"drop\", inbox, box }),\n inboxFetch: async (inbox, since) => post({ op: \"inbox\", inbox, ...since ? { since } : {} }),\n // \"Which of my rooms changed since `since`?\" — the change inbox, standard tier (docs/change-inbox.md). Keyless.\n changes: async (inbox, since = 0) => post({ op: \"changes\", inbox, since }),\n inboxSubscribe: async (inbox, subscription) => post({ op: \"inboxsub\", inbox, subscription }),\n // register this device for a real-time invite tickle\n // a signed-out device's address off the invite inbox's list (the endpoint alone; an older server answers 400 — never an add)\n inboxUnsubscribe: async (inbox, subscription) => post({ op: \"inboxsub\", inbox, remove: true, subscription: { endpoint: subscription && subscription.endpoint } }),\n decide: async (room, mk, id, approve, by, { bridgeMk, bridgeRoom, editText, deviceExec, recordResult } = {}, billingToken) => post({ op: \"decide\", room, ...await keyFields(room, \"decide\", mk), id, approve, by, ...await crossingPush(bridgeRoom), ...await otherAuth([bridgeRoom]), ...await authFor(room), ...bridgeMk ? await bridgeFields(room, \"decide\", bridgeMk) : {}, ...bridgeRoom ? { bridgeRoom } : {}, ...editText ? { editText } : {}, ...deviceExec ? { deviceExec } : {}, ...recordResult === false ? { recordResult: false } : {} }, billingToken),\n // editText: the approver's edit of the pending crossing // bridgeMk: approving a cross_to_shared posts into the linked shared room // deviceExec: a client-executed action (calendar write) — the server must skip its executor\n // Shared WIDGET state (co-edited by members; the agent reads its `summary` on turns). SET with a `patch` (+ a short\n // `summary`); READ with no patch → { v, state, summary }. The blob is mk-sealed server-side — never sent in clear.\n /** THE ROOM AS A STORE — write rows: ONE sealed ledger entry carrying put/delete ops, ordered by the server without\n * reading it. `ops` = [{ op:'put', collection, id?, row } | { op:'del', collection, id }]; `by` names the writer in\n * the system line every member sees. → { status, id, ops:[{op,collection,id}], text, entries } */\n // `file` (optional, ONE beside one put — a mail's attachment): { b64, mime, name } — the server stores it out of line\n // and the row's `file` field names it (agent/spaceService.mjs op data).\n data: async (room, mk, ops, by, file) => post({ op: \"data\", room, ...await keyFields(room, \"data\", mk), ops: Array.isArray(ops) ? ops.slice(0, 50) : [], ...by ? { by: String(by).slice(0, 80) } : {}, ...file && file.b64 ? { file: { b64: String(file.b64), mime: String(file.mime || \"\"), name: String(file.name || \"file\").slice(0, 120) } } : {}, ...await authFor(room) }),\n // `ifV` (optional): the version this write was built on — the server writes only if the doc is still there (409\n // version_conflict otherwise, with the current `v`), so two devices cannot silently overwrite each other.\n state: async (room, mk, name, patch, summary, by, ifV) => post({ op: \"state\", room, ...await keyFields(room, \"state\", mk), name, ...patch !== void 0 ? { patch, summary, by, ...Number.isInteger(ifV) ? { ifV } : {} } : {}, ...await authFor(room) }),\n // An emoji on one message. `react` is {target, emoji, off} — target is the entryKey the server recomputes from the\n // ledger, so a client cannot react to something that is not there. Never a turn: the assistant stays quiet.\n /** PURGE a purgeable room's handled rows (docs/room-messages.md § Retention) — `ids` = row ids no collection still\n * holds. → { status, purged, live } */\n purge: async (room, mk, ids2) => post({ op: \"purge\", room, ...await keyFields(room, \"purge\", mk), ops: Array.isArray(ids2) ? ids2.slice(0, 50).map(String) : [], ...await authFor(room) }),\n /** DELETE FORWARDED MAIL FOR REAL (agent/mailPurge.mjs): the `mail`/`mailfile` rows named — already deleted with `data` —\n * leave the ledger and their files are overwritten. Only in a solo verified Space, by its member. → { status, purged, files, live } */\n mailPurge: async (room, mk, ids2) => post({ op: \"mailpurge\", room, ...await keyFields(room, \"mailpurge\", mk), ops: Array.isArray(ids2) ? ids2.slice(0, 50).map(String) : [], ...await authFor(room) }),\n /** THE MESSAGE INTAKE (docs/message-intake.md, roomIntake.js). `intakeDrop` is a PRODUCER's call — keyless: a drop\n * token and a box sealed to the intake's public key. The rest are the account's devices (keyed). */\n intakeDrop: async (room, drop, box) => post({ op: \"intakedrop\", room, drop, box }),\n intakeReg: async (room, mk, ops) => post({ op: \"intakereg\", room, ...await keyFields(room, \"intakereg\", mk), ops: Array.isArray(ops) ? ops.slice(0, 50) : [] }),\n intakePush: async (room, mk, subscription, remove = false) => post({ op: \"intakepush\", room, ...await keyFields(room, \"intakepush\", mk), subscription, ...remove ? { remove: true } : {} }),\n // this device on the intake's wake list (messageIntake.mjs)\n intakeDeviceWake: async (room, mk, remove = false) => post({ op: \"intakepush\", room, ...await keyFields(room, \"intakepush\", mk), cloudDevice: true, ...remove ? { remove: true } : {} }),\n // the cloud device on the wake list (docs/cloud-device.md § 12)\n // `from` { drop, n }: start the read at that position (a later page past boxes that must stay — roomIntake.js collect)\n intake: async (room, mk, from) => post({ op: \"intake\", room, ...from && typeof from === \"object\" ? { from: { drop: String(from.drop), n: Number(from.n) } } : {}, ...await keyFields(room, \"intake\", mk) }),\n intakeAck: async (room, mk, items) => post({ op: \"intakeack\", room, ...await keyFields(room, \"intakeack\", mk), ops: Array.isArray(items) ? items.slice(0, 50) : [] }),\n // SAFE MEDIA (docs/safe-media.md § 5): the safe copy a device made of a photo or PDF in the room → stored beside it (agent/safeCopy.mjs)\n safeCopy: async (room, mk, safe, by) => post({ op: \"safe\", room, ...await keyFields(room, \"safe\", mk), safe, ...by ? { by: String(by).slice(0, 80) } : {}, ...await authFor(room) }),\n react: async (room, mk, react, by) => post({ op: \"react\", room, ...await keyFields(room, \"react\", mk), react, ...by ? { by: String(by).slice(0, 80) } : {}, ...await authFor(room) }),\n // OWNER RULE (docs/the-owner-rule.md) — the JOIN-flow peer check. `policyOf` fetches the room's cleartext marker +\n // sealed config (op:'policy', public). `verifyGovernance` opens the config with mk and verifies the owner-signed\n // policy against the PINNED owner key (from /space-config) — so the client trusts a governed room only if it's a\n // genuine room of that owner, not the server's word. Called only when a key is pinned (single-owner deployment);\n // the generic multi-tenant PWA passes no key ⇒ { ok:true, governed:false }.\n // op:'policy' carries the room key and the member's sign-in: an EMAIL-GATED room serves its sealed config only to an\n // allowed member (agent/spaceService.mjs, 2026-10-02) and otherwise answers just { gated: true }.\n policyOf: (room, mk) => policyPost(room, mk),\n /** Does this room require an attested app? (a refusal already said so, or op 'policy' does) → boolean. */\n // a read that FAILED throws — never 'not attested' (sync sweep 11-08: the SDK and the vault made an open lane of an attested Space on a failed read)\n // …and neither is the FRONT'S answer for a confidential room this client had not marked (sync sweep 2026-11-12 #4): a keyless ask\n // then reaches the front, which answers from its mirror row — the tier, never the enclave's `attested` mark (agent/tierGuard.mjs).\n // \"No\" from there was remembered and an ordinary lane made of an attested confidential Space. Only \"yes\", or the answer of the\n // tier the room is on, counts; the page marks the room from the tier this answer carries and the next ask goes to its enclave.\n attestedRoom: async (room, mk) => {\n if (attestReadRooms.has(room)) return true;\n const marked = enclaveFor(room);\n const r = await policyPost(room, mk);\n if (!r || r.status !== 200) throw Object.assign(new Error(\"policy read failed\" + (r && r.status ? \" (HTTP \" + r.status + \")\" : \"\")), { code: \"policy_unreadable\" });\n if (r.attested === true) return true;\n if (!marked && r.tier === \"enclave\") throw Object.assign(new Error(\"policy read: a confidential room answered by the front — its enclave was not asked\"), { code: \"policy_unreadable\" });\n return false;\n },\n /** The room's PUBLIC key commitment (op 'invite', keyless) → string | null (none) | undefined (could not ask). Lets a device\n * check a key it was handed before keeping it (emailInvites.js keyOpens). */\n roomCommit: async (room) => {\n const r = await post({ op: \"invite\", room });\n return r && r.status === 200 ? r.mkCommit || null : void 0;\n },\n // Fetch + decrypt this room's sealed agent CONFIG (persona/tools/agentName/admission/allow/agentKeys/model/…) with\n // mk → the plaintext config, or null. The config ciphertext is content-blind (sealed under mk, served by op:'policy'\n // which already returns it for governance). A membership fork uses this to carry the agent's behavior into the new\n // room (spaceFork.js) — the forking client holds the OLD mk, so it can decrypt without exposing the new key.\n // `{ plainMark: true }`: a PLAIN room (a read that worked, nothing sealed, no lanes bit) answers `{ plain: true }`, so null\n // means only that the read failed — a private lane waits on that, never inherits \"nothing\" (sync sweep 2026-11-03)\n getConfig: async (room, mk, o) => {\n const r = await policyPost(room, mk);\n if (!r || r.status !== 200 || r.error || r.ok === false) return null;\n if (!r.configSealed && r.gated === true) {\n gatedRooms.add(room);\n return { admission: \"email\", gated: true };\n }\n if (!r.configSealed) {\n const h = await healEnclaveConfig(room, mk);\n if (h) return h.cfg;\n }\n if (!r.configSealed) return typeof r.lanes === \"boolean\" ? { lanes: r.lanes } : o && o.plainMark === true ? { plain: true } : null;\n let cfg = null;\n try {\n cfg = JSON.parse(await open(JSON.parse(r.configSealed), { mk }));\n } catch {\n return null;\n }\n if (cfg && typeof cfg === \"object\" && cfg.admission === \"email\") {\n gatedRooms.add(room);\n if (cfg.ownerPolicy) keyFirst.set(room, Infinity);\n }\n return cfg;\n },\n /** Change the assistant IN PLACE — its name, instructions (persona) and model — visibly: the server appends a system\n * line to the ledger (\"⚙️ Dana changed the assistant's instructions\") that every member sees. Only those three\n * fields move; the sealed config is re-sealed WHOLE with them applied, so tools, admission, the owner policy and the\n * enclave block travel byte-identical (the server opens both versions and refuses anything else — those stay\n * fork-and-replay). `by` is the display name for the line. → { status, changed:[…], recorded } */\n /** The standing Sentinel's door (docs/standing-sentinel.md §2): attest / credgrant / credlist / credrevoke, as the\n * signed-in account (the token's email — the server never reads an account the page names). A pipe: the grant\n * inside is sealed to the Sentinel's attested key. → the Sentinel's answer, or { error }. */\n sentinel: async (sentinel, idToken) => post({ op: \"sentinel\", sentinel, idToken }),\n /** The cloud device through the API (agent/cloudDeviceRoute.mjs): `cd` = { t, … }, the account = the verified idToken's. */\n cloudDevice: async (cd, idToken, opts) => (await Promise.resolve().then(() => (init_cloudDeviceSeal(), cloudDeviceSeal_exports))).cloudDeviceCall(post, cd, idToken, opts || void 0),\n // sealed to its enclave once pinned; opts: the dev server's root and pins (witbitz-sdk.js _cloudDeviceOpts)\n // press-to-talk's cloud engine (agent/sttKey.mjs): a short-lived, capped Tinfoil key for this signed-in account\n // SAFE MEDIA (docs/safe-media.md): the tools enclave's attestation for a nonce, then a sealed box to make a file safe\n safeMedia: async (idToken, safemedia) => post({ op: \"safemedia\", idToken, safemedia }),\n stt: async (idToken, userToken2) => post({ op: \"stt\", ...idToken ? { idToken } : {}, ...userToken2 ? { userToken: userToken2 } : {} }),\n // userToken: the SDK's tenant-vouched user (wb.dictation)\n // Report (docs/report-and-block.md §3): what the member chose to show Witbitz — the front stores and mails it (agent/reportOp.mjs)\n report: async (idToken, body, memberToken) => post({ op: \"report\", idToken, room: body.room, report: body, ...memberToken ? { memberToken } : {} }),\n // a MEMBER's token for a report (agent/spaceService.mjs op membertoken): issued only to the room's CURRENT key and, in a verified\n // room, to a sign-in its gate admits (it rides with the request) — sealed to the turn enclave for a confidential room, like any\n // keyed op, so the key never reaches the Lambda\n memberToken: async (room, mk) => post({ op: \"membertoken\", room, ...await keyFields(room, \"membertoken\", mk), ...await authFor(room) }),\n // the sign-in: a verified room issues it only past its email gate (sync sweep 11-11 #2)\n tts: async (idToken, userToken2) => post({ op: \"tts\", ...idToken ? { idToken } : {}, ...userToken2 ? { userToken: userToken2 } : {} }),\n // \"Play aloud\": a capped Tinfoil key for speech OUTPUT (agent/sttKey.mjs § SPEECH OUTPUT)\n /** Witbitz's signed rule + room signature for a NEW room that requires an app (op owner-policy, agent/witbitzOwnerPolicy.mjs) — for\n * a create that is not this client's own (the hosted app's split create, space.js createSplitLocal). */\n ownerPolicyFor: async (room, _mk, level) => post({ op: \"owner-policy\", room, level }),\n setConfig: async (room, mk, patch, by) => {\n let r = await policyPost(room, mk);\n if (!r || r.status !== 200) return { status: r && r.status || 502, error: r && r.error || \"policy_unavailable\" };\n if (!r.configSealed && r.gated !== true) {\n const h = await healEnclaveConfig(room, mk);\n if (h && h.saved) r = { ...r, configSealed: h.configSealed };\n }\n let cur = {};\n if (r.configSealed) {\n let pt = null;\n try {\n pt = await open(JSON.parse(r.configSealed), { mk });\n } catch {\n pt = null;\n }\n if (pt == null) return { status: 409, error: \"config_unreadable\" };\n try {\n cur = JSON.parse(pt) || {};\n } catch {\n return { status: 409, error: \"config_unreadable\" };\n }\n }\n const p = patch && typeof patch === \"object\" ? patch : {};\n const next = { ...cur };\n if (\"persona\" in p) next.persona = p.persona == null ? void 0 : String(p.persona).slice(0, 4e3);\n if (\"agentName\" in p) next.agentName = p.agentName == null ? void 0 : String(p.agentName).slice(0, 80);\n if (\"model\" in p) next.model = p.model == null ? void 0 : p.model;\n if (\"funding\" in p) next.funding = p.funding && typeof p.funding.grant === \"string\" ? { grant: p.funding.grant.slice(0, 1200), perMemberUsd: Number(p.funding.perMemberUsd) || void 0 } : void 0;\n if (\"dataSchema\" in p) next.dataSchema = p.dataSchema == null ? void 0 : p.dataSchema;\n if (\"platformTools\" in p) next.platformTools = p.platformTools === false || Array.isArray(p.platformTools) ? p.platformTools : void 0;\n if (\"framing\" in p) next.framing = p.framing === \"builder\" ? \"builder\" : void 0;\n for (const k of [\"admins\", \"owners\"]) if (k in p) {\n const tags = p[k] && Array.isArray(p[k].tags) ? p[k].tags : cur[k] && Array.isArray(cur[k].tags) ? cur[k].tags : [];\n next[k] = roleOf(p[k] && p[k].emails || [], tags);\n }\n if (\"lanes\" in p) next.lanes = p.lanes === true;\n if (\"dataWrites\" in p) next.dataWrites = p.dataWrites === false ? false : void 0;\n if (\"safeMedia\" in p) next.safeMedia = p.safeMedia === true ? true : void 0;\n if (\"connections\" in p) {\n next.connections = applyConnectionsPatch(next.connections, p.connections);\n }\n const configSealed = JSON.stringify(await seal(JSON.stringify(next), { room: mk }));\n return post({ op: \"config\", room, ...await keyFields(room, \"config\", mk), configSealed, ...by ? { by: String(by).slice(0, 80) } : {}, ...await authFor(room) });\n },\n /** A VERIFIED ROOM RE-KEYED IN PLACE (docs/key-rotation-design.md § (b); agent/roomRekey.mjs has the server's rules).\n * `members` = the new { allow, owners, admins } (absent = a pure rotation, \"Rotate keys now\"); `recipients` = one\n * { mh: memberHash(email, room), boxPub } per member who stays (the caller included). Here, in the realm that holds the\n * key: a NEW key is minted; the config is read under the current key, its members replaced, the current key appended\n * to its chain, and it is sealed under the new key; the new key is sealed to each recipient's invite key; one request.\n * → the server's answer, plus `newMk` on success (the caller keeps it — the worker: l1-worker op 'rekey'). */\n // A SPLIT room (mk = userShare ⊕ appShare; the hosted app): `split.userShare` is the share held now. Only the USER half\n // rotates (§ Split-key rooms): appShare = mk ⊕ userShare, a fresh random userShare', mk' = userShare' ⊕ appShare — the\n // builder's half and its seal stay as they are. The grants carry userShare' (never mk'); the answer carries newShare.\n rekey: async (room, mk, { members = null, recipients = [], pending = [], by = \"\", split = null, creatorPriv = null, link = null, expectEpoch: wantEpoch = null } = {}) => {\n const r = await policyPost(room, mk);\n if (!r || r.status !== 200) return { status: r && r.status || 502, error: r && r.error || \"policy_unavailable\" };\n if (!r.configSealed) return { status: 502, error: \"policy_unavailable\" };\n let cur = null;\n try {\n cur = JSON.parse(await open(JSON.parse(r.configSealed), { mk }) || \"null\");\n } catch {\n cur = null;\n }\n if (!cur || typeof cur !== \"object\") return { status: 409, error: \"config_unreadable\" };\n const chain = Array.isArray(cur.keyChain) ? cur.keyChain : [];\n const epoch = chain.length;\n if (Number.isInteger(wantEpoch) && wantEpoch !== epoch) return { status: 409, error: \"stale_epoch\" };\n let newMk = newKey(), newShare = null;\n if (split && split.userShare) {\n const app2 = combineShares(mk, split.userShare);\n if (!app2) return { status: 400, error: \"bad_split\", reason: \"the held share does not pair with this key\" };\n const s2 = splitKey(app2);\n newShare = s2.shareA;\n newMk = s2.shareB;\n }\n const newCommit = await commit(newMk);\n const next = { ...cur, ...members ? { allow: members.allow, owners: members.owners, admins: members.admins } : {}, ...link ? { admission: \"invite\", roster: link.roster, gk: link.gk } : {}, keyChain: [...chain, { epoch, commit: await commit(mk), key: mk }] };\n for (const k of [\"owners\", \"admins\"]) if (next[k] === void 0) delete next[k];\n if (next.direct === true && members && !staysDirect(await directRoster(next.allow, room))) delete next.direct;\n const configSealed = JSON.stringify(await seal(JSON.stringify(next), { room: newMk }));\n const grant = JSON.stringify(newShare ? { v: 1, kind: \"room-split-key\", room, epoch: epoch + 1, userShare: newShare, commit: newCommit } : { v: 1, kind: \"room-key\", room, epoch: epoch + 1, mk: newMk });\n const grants = {};\n for (const x of recipients || []) {\n const id = x && (x.mh || x.id);\n if (id && x.boxPub && !grants[id]) grants[id] = JSON.stringify(await sealTo(x.extra ? JSON.stringify({ ...JSON.parse(grant), ...x.extra }) : grant, x.boxPub));\n }\n for (const mh of pending || []) {\n if (typeof mh === \"string\" && mh && !grants[mh]) grants[mh] = \"pending\";\n }\n const kf = await keyFields(room, \"rekey\", mk);\n let nf = { newMk };\n if (kf.mkSealed) {\n const pub = mkPubFor(room);\n nf = { newMkSealed: await sealMk(newMk, pub, mkAad({ room, op: \"rekey:new\", ts: kf.mkTs, nonce: kf.mkNonce })) };\n }\n const creatorSig = creatorPriv ? (await signEntry(creatorPriv, { room, kind: \"rekey\", id: newCommit, text: String(epoch), ts: 0, author: \"\" })).sig : void 0;\n const out = await post({ op: \"rekey\", room, ...kf, ...nf, newCommit, expectEpoch: epoch, configSealed, grants, ...creatorSig ? { creatorSig } : {}, ...by ? { by: String(by).slice(0, 80) } : {}, ...await authFor(room) });\n return out && out.status === 200 ? { ...out, newMk, newCommit, ...newShare ? { newShare } : {} } : out;\n },\n /** This member's new key after a rotation: the grant sealed to their account's invite key (op 'grant'), asked with the\n * sign-in alone — the old key opens nothing now. → { status:200, grant, epoch, commit } | { status:404, error:'no_grant' } */\n grant: async (room, _mk, keyProof = null) => post({ op: \"grant\", room, ...keyProof && keyProof.spk && keyProof.keySig ? { spk: keyProof.spk, keySig: keyProof.keySig } : await authFor(room) }),\n // keyProof: a LINK Space's member proves its signing key (no account)\n verifyGovernance: (room, mk, ownerKey, member) => verifyRoomGovernance({ room, mk, ownerKey, member, fetchPolicy: (r) => policyPost(r, r === room ? mk : null), openConfig: async (ct, m) => JSON.parse(await open(JSON.parse(ct), { mk: m })) })\n };\n return api;\n}\n\n// spaces/public/sdk/4.7.1/deviceKeyCore.js\nvar DEVKEY_IDB = \"devkey:v1\";\nvar localWrites = Promise.resolve();\nvar validKeyRecord = (rec) => !!(rec?.spk && (typeof CryptoKey === \"undefined\" || rec.priv instanceof CryptoKey));\nfunction keepKeyRequest(objectStore, key, candidate) {\n const kept = { result: candidate };\n const read = objectStore.get(key);\n read.onsuccess = () => {\n if (validKeyRecord(read.result)) kept.result = read.result;\n else objectStore.put(candidate, key);\n };\n return kept;\n}\n\n// spaces/public/sdk/4.7.1/deviceSeal.js\nvar enc10 = new TextEncoder();\nvar dec4 = new TextDecoder();\nvar INFO = enc10.encode(\"witbitz-device-seal-v1\");\nvar SALT = enc10.encode(\"witbitz-device-seal\");\nvar SEAL_V = 1;\nvar subtle2 = () => {\n const s = globalThis.crypto && globalThis.crypto.subtle;\n if (!s) throw new Error(\"no WebCrypto\");\n return s;\n};\nvar b648 = (u8) => {\n let s = \"\";\n for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]);\n return btoa(s);\n};\nvar fromB64 = (s) => {\n const b = atob(String(s));\n const u = new Uint8Array(b.length);\n for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i);\n return u;\n};\nvar bytes = (x) => x instanceof Uint8Array ? x : x instanceof ArrayBuffer ? new Uint8Array(x) : Array.isArray(x) ? Uint8Array.from(x) : null;\nasync function importRaw(raw) {\n const r = bytes(raw);\n if (!r || r.length !== 32) throw new Error(\"seal key must be 32 bytes\");\n return subtle2().importKey(\"raw\", r, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n}\nasync function seal2(key, value) {\n if (!key) throw new Error(\"no seal key\");\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await subtle2().encrypt({ name: \"AES-GCM\", iv }, key, enc10.encode(JSON.stringify(value === void 0 ? null : value))));\n const out = new Uint8Array(iv.length + ct.length);\n out.set(iv, 0);\n out.set(ct, iv.length);\n return { v: SEAL_V, s: b648(out) };\n}\nasync function open2(key, blob) {\n if (!key) throw new Error(\"no seal key\");\n if (!isSealed(blob)) throw new Error(\"not a sealed blob\");\n const all = fromB64(blob.s);\n if (all.length < 12 + 16) throw new Error(\"sealed blob too short\");\n const pt = await subtle2().decrypt({ name: \"AES-GCM\", iv: all.subarray(0, 12) }, key, all.subarray(12));\n return JSON.parse(dec4.decode(pt));\n}\nvar isSealed = (x) => !!(x && typeof x === \"object\" && !Array.isArray(x) && x.v === SEAL_V && typeof x.s === \"string\" && x.s.length > 0);\nvar sealIf = async (key, value) => key ? seal2(key, value) : value;\nvar openIf = async (key, stored) => isSealed(stored) ? open2(key, stored) : stored;\n\n// spaces/public/sdk/4.7.1/sealedNames.js\nvar enc11 = new TextEncoder();\nvar dec5 = new TextDecoder();\nvar SALT2 = enc11.encode(\"witbitz-sealed-names\");\nvar NAME_PREFIX = \"p:\";\nvar isOpaqueName = (k) => typeof k === \"string\" && k.startsWith(NAME_PREFIX);\nvar subtle3 = () => {\n const s = globalThis.crypto && globalThis.crypto.subtle;\n if (!s) throw new Error(\"no WebCrypto\");\n return s;\n};\nvar toB64u = (u8) => {\n let s = \"\";\n for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar fromB64u = (s) => {\n const b = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const u = new Uint8Array(b.length);\n for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i);\n return u;\n};\nvar bytes2 = (x) => x instanceof Uint8Array ? x : x instanceof ArrayBuffer ? new Uint8Array(x) : Array.isArray(x) ? Uint8Array.from(x) : null;\nasync function nameKeys(raw) {\n const r = bytes2(raw);\n if (!r || r.length < 16) throw new Error(\"bad device key\");\n const base = await subtle3().importKey(\"raw\", r, \"HKDF\", false, [\"deriveKey\"]);\n const hk = (info) => ({ name: \"HKDF\", hash: \"SHA-256\", salt: SALT2, info: enc11.encode(info) });\n const mac = await subtle3().deriveKey(hk(\"witbitz-names-v1-mac\"), base, { name: \"HMAC\", hash: \"SHA-256\", length: 256 }, false, [\"sign\"]);\n const aes = await subtle3().deriveKey(hk(\"witbitz-names-v1-enc\"), base, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n return { mac, aes };\n}\nasync function ivFor(keys, name) {\n return new Uint8Array(await subtle3().sign(\"HMAC\", keys.mac, enc11.encode(name))).slice(0, 12);\n}\nasync function opaqueName(keys, name) {\n const iv = await ivFor(keys, String(name));\n const ct = new Uint8Array(await subtle3().encrypt({ name: \"AES-GCM\", iv }, keys.aes, enc11.encode(String(name))));\n const out = new Uint8Array(iv.length + ct.length);\n out.set(iv);\n out.set(ct, iv.length);\n return NAME_PREFIX + toB64u(out);\n}\nasync function realName(keys, stored) {\n if (!isOpaqueName(stored)) return null;\n try {\n const all = fromB64u(stored.slice(NAME_PREFIX.length));\n if (all.length < 29) return null;\n const iv = all.slice(0, 12);\n const name = dec5.decode(await subtle3().decrypt({ name: \"AES-GCM\", iv }, keys.aes, all.slice(12)));\n const want = await ivFor(keys, name);\n for (let i = 0; i < 12; i++) if (want[i] !== iv[i]) return null;\n return name;\n } catch {\n return null;\n }\n}\nasync function makeNamer(raw) {\n const keys = await nameKeys(raw);\n const fwd = /* @__PURE__ */ new Map(), back = /* @__PURE__ */ new Map();\n return {\n async opaque(name) {\n const n = String(name);\n let o = fwd.get(n);\n if (!o) {\n o = await opaqueName(keys, n);\n fwd.set(n, o);\n back.set(o, n);\n }\n return o;\n },\n async real(stored) {\n if (back.has(stored)) return back.get(stored);\n const n = await realName(keys, stored);\n if (n != null) {\n back.set(stored, n);\n fwd.set(n, stored);\n }\n return n;\n },\n known(name) {\n return fwd.get(String(name)) || null;\n }\n // synchronous: the stored name if computed before\n };\n}\n\n// spaces/public/sdk/4.7.1/idbSeal.js\nvar IDB_SHARED_NAMES = Object.freeze([\"notifTap\", \"notifPreview\", \"protectedNames\", \"swTrail\", \"codeRemindKey\", \"devkey:v1\", \"blocks:sw\", \"chatlocked:sw\"]);\nvar naming = { on: false, key: null, namer: null };\nfunction setIdbNaming({ on = false, key = null, namer = null } = {}) {\n naming.on = !!on;\n naming.key = key;\n naming.namer = namer;\n}\nvar idbNamingState = () => naming;\nasync function armIdbNaming(rawKey) {\n setIdbNaming({ on: true, key: await importRaw(rawKey), namer: await makeNamer(rawKey) });\n}\nvar IDB_PROTECTED_PREFIXES = Object.freeze([\"chat:\", \"wstate:\", \"blob:\", \"code:\", \"vchat:\", \"vblob:\", \"vblobidx\", \"hidx:\", \"zoom:\", \"outbox:\", \"mailpend:\"]);\nvar isProtectedIdbKey = (k) => {\n const s = String(k);\n return IDB_PROTECTED_PREFIXES.some((p) => s.startsWith(p));\n};\nvar st = { active: false, key: null };\nfunction setIdbProtection({ active = st.active, key = st.key } = {}) {\n st.active = !!active;\n st.key = key || null;\n if (!st.active) setIdbNaming({ on: false });\n else if (!st.key) setIdbNaming({ on: true });\n}\nasync function wrapForStore(k, v) {\n if (!st.active || !isProtectedIdbKey(k)) return v;\n if (!st.key) return void 0;\n return sealIf(st.key, v);\n}\nasync function unwrapFromStore(k, v) {\n if (!isProtectedIdbKey(k) || !isSealed(v)) return v;\n if (!st.key) return null;\n try {\n return await openIf(st.key, v);\n } catch {\n return null;\n }\n}\nasync function unwrapStrict(k, v) {\n if (!isProtectedIdbKey(k) || !isSealed(v)) return v;\n if (!st.key) throw new Error(\"Unlock device storage to read this entry\");\n return openIf(st.key, v);\n}\nvar protectedKeys = async (idb2) => {\n const out = [];\n for (const pfx of IDB_PROTECTED_PREFIXES) {\n if (typeof idb2.keysRaw === \"function\") out.push(...await idb2.keysRaw(pfx));\n else for (const [k] of await idb2.entriesRaw(pfx)) out.push(k);\n }\n return out;\n};\nasync function armIdbProtection(rawKey) {\n const key = await importRaw(rawKey);\n setIdbProtection({ active: true, key });\n setIdbNaming({ on: true, key, namer: await makeNamer(rawKey) });\n}\nasync function moveToOpaqueNames(idb2) {\n const { key, namer } = naming;\n if (!key || !namer) return 0;\n try {\n await idb2.setRaw(\"protectedNames\", true);\n } catch {\n }\n let n = 0;\n for (const k of await idb2.keysRaw(\"\")) {\n if (isOpaqueName(k) || IDB_SHARED_NAMES.includes(k) || k.startsWith(\"nk:\")) continue;\n let v = await idb2.getRaw(k);\n if (v === void 0 || v === null) continue;\n if (isProtectedIdbKey(k) && isSealed(v)) {\n try {\n v = await openIf(st.key || key, v);\n } catch {\n continue;\n }\n }\n const o = await namer.opaque(k);\n if (await idb2.getRaw(o) == null) await idb2.setRaw(o, await seal2(key, v));\n if (await idb2.getRaw(o) == null) continue;\n await idb2.delRaw(k);\n n++;\n }\n return n;\n}\nasync function migrateIdbProtection(idb2, rawKey) {\n await armIdbProtection(rawKey);\n return moveToOpaqueNames(idb2);\n}\nasync function unprotectIdb(idb2, rawKey) {\n const key = await importRaw(rawKey), namer = await makeNamer(rawKey);\n for (const o of await idb2.keysRaw(\"p:\")) {\n const name = await namer.real(o);\n const v = await idb2.getRaw(o);\n if (name != null && v != null) {\n let back;\n try {\n back = await open2(key, v);\n } catch {\n back = void 0;\n }\n if (back !== void 0) {\n await idb2.setRaw(name, back);\n if (await idb2.getRaw(name) == null) continue;\n }\n }\n await idb2.delRaw(o);\n }\n for (const k of await protectedKeys(idb2)) {\n const v = await idb2.getRaw(k);\n if (isSealed(v)) {\n try {\n await idb2.setRaw(k, await openIf(key, v));\n } catch {\n await idb2.delRaw(k);\n }\n }\n }\n try {\n await idb2.delRaw(\"protectedNames\");\n } catch {\n }\n setIdbProtection({ active: false, key: null });\n}\ntry {\n if (typeof window !== \"undefined\" && typeof localStorage !== \"undefined\") {\n const rawGet0 = (k) => {\n try {\n return typeof Storage !== \"undefined\" ? Storage.prototype.getItem.call(localStorage, k) : localStorage.getItem(k);\n } catch {\n return null;\n }\n };\n const cfgOn = (k) => {\n try {\n const c = JSON.parse(rawGet0(k) || \"null\");\n return !!(c && c.on && c.protect && c.protect.on);\n } catch {\n return false;\n }\n };\n let sameOriginFramed = false;\n try {\n sameOriginFramed = window.top !== window && window.parent.location.origin === location.origin;\n } catch {\n sameOriginFramed = false;\n }\n const on = window.top === window || sameOriginFramed ? cfgOn(\"space:lock\") || cfgOn(\"vault:lock\") || rawGet0(\"space:protected\") === \"1\" || window.top === window && rawGet0(\"vault:atrest\") === \"1\" || rawGet0(\"space:atrest\") === \"1\" : rawGet0(\"space:protected\") === \"1\";\n if (on) setIdbProtection({ active: true, key: null });\n }\n} catch {\n}\n\n// spaces/public/sdk/4.7.1/idb.js\nvar isNamed = (k) => {\n const n = idbNamingState();\n return n.on && !IDB_SHARED_NAMES.includes(String(k)) && !isOpaqueName(String(k)) && !String(k).startsWith(\"nk:\");\n};\nvar idbMemory = { on: false };\nvar idb = /* @__PURE__ */ (() => {\n let dbp, mem = null;\n const memory = () => {\n if (!mem) {\n mem = /* @__PURE__ */ new Map();\n idbMemory.on = true;\n }\n return mem;\n };\n const copy = (v) => v == null ? v : typeof structuredClone === \"function\" ? structuredClone(v) : v;\n const open3 = () => dbp || (dbp = new Promise((res, rej) => {\n if (typeof indexedDB === \"undefined\" || !indexedDB) {\n rej(Object.assign(new Error(\"no IndexedDB\"), { noIdb: true }));\n return;\n }\n let r;\n try {\n r = indexedDB.open(\"spaces\", 1);\n } catch (e) {\n rej(Object.assign(e instanceof Error ? e : new Error(String(e)), { noIdb: true }));\n return;\n }\n r.onupgradeneeded = () => r.result.createObjectStore(\"kv\");\n r.onsuccess = () => {\n const db = r.result;\n db.onversionchange = () => {\n db.close();\n dbp = null;\n };\n res(db);\n };\n r.onerror = () => rej(Object.assign(r.error || new Error(\"open failed\"), { noIdb: true }));\n }));\n const tx = (mode, fn, onMem) => open3().then(\n (db) => new Promise((res, rej) => {\n const t = db.transaction(\"kv\", mode), rq = fn(t.objectStore(\"kv\"));\n t.oncomplete = () => res(rq && rq.result);\n t.onerror = t.onabort = () => rej(t.error || new Error(\"IndexedDB transaction aborted\"));\n }),\n (e) => {\n if (e && e.noIdb && onMem) return onMem(memory());\n throw e;\n }\n );\n const inRange = (k, pfx) => !pfx || String(k).startsWith(pfx);\n const vault = () => typeof globalThis !== \"undefined\" && typeof globalThis.__wbAppIdb === \"function\" ? globalThis.__wbAppIdb : null;\n const getRaw = (k) => (vault() ? vault()(\"get\", k).then((v) => v === void 0 ? null : v) : tx(\"readonly\", (s) => s.get(k), (m) => copy(m.get(k)))).catch(() => null);\n const setRawStrict = (k, v) => vault() ? vault()(\"set\", k, v) : tx(\"readwrite\", (s) => s.put(v, k), (m) => {\n m.set(k, copy(v));\n });\n const setRaw = (k, v) => setRawStrict(k, v).catch(() => {\n });\n const range = (pfx) => pfx ? IDBKeyRange.bound(pfx, pfx + \"\", false, true) : void 0;\n const entriesRaw = (pfx) => vault() ? vault()(\"entries\", pfx || \"\").then((es) => (es || []).map(([k, v]) => [String(k), v])).catch(() => []) : open3().then((db) => new Promise((res, rej) => {\n const t = db.transaction(\"kv\", \"readonly\"), s = t.objectStore(\"kv\"), ks = s.getAllKeys(range(pfx)), vs = s.getAll(range(pfx));\n t.oncomplete = () => {\n const keys = ks.result || [], vals = vs.result || [], out = [];\n for (let i = 0; i < keys.length; i++) if (String(keys[i]).startsWith(pfx)) out.push([String(keys[i]), vals[i]]);\n res(out);\n };\n t.onerror = () => rej(t.error);\n }), (e) => {\n if (e && e.noIdb) return [...memory()].filter(([k]) => inRange(k, pfx)).map(([k, v]) => [String(k), copy(v)]);\n throw e;\n }).catch(() => []);\n const keysRaw = (pfx) => (vault() ? vault()(\"keys\", pfx || \"\") : tx(\"readonly\", (s) => s.getAllKeys(range(pfx)), (m) => [...m.keys()])).then((ks) => (ks || []).map(String).filter((k) => k.startsWith(pfx))).catch(() => []);\n const delRawStrict = (k) => vault() ? vault()(\"del\", k) : tx(\"readwrite\", (s) => s.delete(k), (m) => {\n m.delete(k);\n });\n const delRaw = (k) => delRawStrict(k).catch(() => {\n });\n const delStrict = async (k) => {\n if (isNamed(k)) {\n const namer = idbNamingState().namer;\n if (!namer) throw new Error(\"cannot delete a protected key before unlocking\");\n await delRawStrict(await namer.opaque(k));\n }\n await delRawStrict(k);\n };\n const delPrefixRaw = (pfx) => (vault() ? vault()(\"delPrefix\", pfx || \"\") : tx(\n \"readwrite\",\n (s) => {\n const rq = s.getAllKeys(range(pfx));\n rq.onsuccess = () => {\n for (const k of rq.result || []) if (String(k).startsWith(pfx)) s.delete(k);\n };\n },\n (m) => {\n for (const k of [...m.keys()]) if (String(k).startsWith(pfx)) m.delete(k);\n }\n )).catch(() => {\n });\n const nameIndex = async () => {\n const nm = idbNamingState().namer;\n if (!nm) return [];\n const out = [];\n for (const o of await keysRaw(\"p:\")) {\n const n = await nm.real(o);\n if (n != null) out.push([o, n]);\n }\n return out;\n };\n const legacyGet = (k) => getRaw(k).then((v) => v == null ? v : unwrapFromStore(k, v));\n const getRawStrict = (k) => vault() ? vault()(\"get\", k).then((v) => v === void 0 ? null : v) : tx(\"readonly\", (s) => s.get(k), (m) => copy(m.get(k)));\n const self2 = {\n async keepDeviceKey(k, candidate, allowMemory = true) {\n if (k !== DEVKEY_IDB) throw new Error(\"not the device key\");\n if (vault()) {\n try {\n return await vault()(\"keepDeviceKey\", k, candidate);\n } catch (e) {\n if (e?.message !== \"unknown op keepDeviceKey\") throw e;\n const existing = await getRawStrict(k);\n if (validKeyRecord(existing)) return existing;\n await vault()(\"set\", k, candidate);\n return candidate;\n }\n }\n return tx(\"readwrite\", (s) => keepKeyRequest(s, k, candidate), allowMemory && ((m) => {\n if (!validKeyRecord(m.get(k))) m.set(k, candidate);\n return copy(m.get(k));\n }));\n },\n get: (k) => (!isNamed(k) ? legacyGet(k) : !idbNamingState().namer ? Promise.resolve(null) : (async () => {\n const v = await getRaw(await idbNamingState().namer.opaque(k));\n return v != null ? open2(idbNamingState().key, v) : legacyGet(k);\n })()).catch(() => null),\n set: (k, v) => (!isNamed(k) ? wrapForStore(k, v).then((stored) => stored === void 0 ? void 0 : setRaw(k, stored)) : !idbNamingState().namer ? Promise.resolve(void 0) : (async () => {\n const nm = idbNamingState().namer, key = idbNamingState().key;\n const o = await nm.opaque(k);\n const stored = await seal2(key, v);\n await setRaw(o, stored);\n await delRaw(k);\n })()).catch(() => {\n }),\n async clearStrict() {\n if (vault()) return vault()(\"delPrefix\", \"\");\n if (typeof indexedDB === \"undefined\" || !indexedDB) {\n memory().clear();\n return;\n }\n await tx(\"readwrite\", (store) => store.clear());\n if (mem) mem.clear();\n },\n delStrict,\n del: (k) => (!isNamed(k) || !idbNamingState().namer ? delRaw(k) : idbNamingState().namer.opaque(k).then((o) => Promise.all([delRaw(o), delRaw(k)]))).catch(() => {\n }),\n delPrefix: (pfx) => (!idbNamingState().on || !idbNamingState().namer ? delPrefixRaw(pfx) : nameIndex().then((ix) => Promise.all([...ix.filter(([, n]) => n.startsWith(pfx)).map(([o]) => delRaw(o)), delPrefixRaw(pfx)]))).catch(() => {\n }),\n // All [key, value] pairs whose key starts with pfx. Used by the L1 worker to load its room→mk map.\n entries: (pfx) => (async () => {\n const legacy = await entriesRaw(pfx).then((es) => Promise.all(es.map(async ([k, v]) => [k, await unwrapFromStore(k, v)])));\n if (!idbNamingState().on || pfx.startsWith(\"nk:\") || IDB_SHARED_NAMES.some((n) => n.startsWith(pfx) || pfx.startsWith(n))) return legacy;\n if (!idbNamingState().namer) return [];\n const key = idbNamingState().key, seen = /* @__PURE__ */ new Set(), out = [];\n for (const [o, n] of await nameIndex()) {\n if (!n.startsWith(pfx)) continue;\n const v = await getRaw(o);\n if (v == null) continue;\n try {\n out.push([n, await open2(key, v)]);\n seen.add(n);\n } catch {\n }\n }\n for (const [k, v] of legacy) if (!seen.has(k)) out.push([k, v]);\n return out;\n })().catch(() => []),\n // §NAMES: the real names under a prefix, values never read (the protection migration and listings).\n names: (pfx) => (idbNamingState().on && idbNamingState().namer ? nameIndex().then(async (ix) => [...ix.map(([, n]) => n).filter((n) => n.startsWith(pfx)), ...await keysRaw(pfx)]) : keysRaw(pfx)).catch(() => []),\n getRaw,\n setRaw,\n setRawStrict,\n delRaw,\n entriesRaw,\n keysRaw,\n nameIndex,\n /** A read that THROWS when it failed (never null for an error) — for a value that must not be replaced on a failed read. */\n async getStrict(k) {\n if (isNamed(k)) {\n const { namer, key } = idbNamingState();\n if (!namer) throw new Error(\"Unlock device storage to read this entry\");\n const v = await getRawStrict(await namer.opaque(k));\n if (v != null) return open2(key, v);\n }\n return unwrapStrict(k, await getRawStrict(k));\n },\n // §PROTECT: switch on / unlock (seal the clear content in place) and switch off (write it back) — the lock hooks call these.\n protect: (rawKey) => migrateIdbProtection(self2, rawKey),\n unprotect: (rawKey) => unprotectIdb(self2, rawKey)\n };\n return self2;\n})();\n\n// spaces/public/sdk/4.7.1/compress.js\nvar _jsonBytes = (v) => {\n try {\n return new TextEncoder().encode(JSON.stringify(v ?? null)).length;\n } catch {\n return Infinity;\n }\n};\nasync function _streamToU8(stream) {\n const reader = stream.getReader();\n const chunks = [];\n let n = 0;\n for (; ; ) {\n const { value, done } = await reader.read();\n if (done) break;\n chunks.push(value);\n n += value.length;\n }\n const out = new Uint8Array(n);\n let o = 0;\n for (const c of chunks) {\n out.set(c, o);\n o += c.length;\n }\n ;\n return out;\n}\nfunction _b64ToU8(b6410) {\n const s = atob(b6410);\n const u8 = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) u8[i] = s.charCodeAt(i);\n return u8;\n}\nasync function gunzipB64(b6410) {\n const stream = new Response(_b64ToU8(b6410)).body.pipeThrough(new DecompressionStream(\"gzip\"));\n return JSON.parse(new TextDecoder().decode(await _streamToU8(stream)));\n}\n\n// spaces/public/sdk/4.7.1/notifKey.js\nvar enc12 = new TextEncoder();\nvar b649 = (u8) => {\n const b = u8 instanceof Uint8Array ? u8 : new Uint8Array(u8);\n let s = \"\";\n for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar ub644 = (str) => {\n let s = String(str || \"\").replace(/-/g, \"+\").replace(/_/g, \"/\");\n s += \"=\".repeat((4 - s.length % 4) % 4);\n const bin = atob(s);\n const o = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) o[i] = bin.charCodeAt(i);\n return o;\n};\nasync function deriveNotifKey(mk) {\n if (!mk || typeof mk !== \"string\") throw new Error(\"deriveNotifKey needs the room mk\");\n const ikm = await crypto.subtle.importKey(\"raw\", ub644(mk), \"HKDF\", false, [\"deriveBits\"]);\n const bits = await crypto.subtle.deriveBits({ name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: enc12.encode(\"notif\") }, ikm, 256);\n return b649(new Uint8Array(bits));\n}\n\n// spaces/public/sdk/4.7.1/accountSeal.js\nvar enc13 = new TextEncoder();\nvar dec6 = new TextDecoder();\nvar ub645 = (s) => {\n const b = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const u = new Uint8Array(b.length);\n for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i);\n return u;\n};\nvar b64url2 = (u8) => {\n let s = \"\";\n for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar canZip = typeof CompressionStream === \"function\" && typeof DecompressionStream === \"function\";\nasync function pipeThrough(bytes3, stream) {\n return new Uint8Array(await new Response(new Blob([bytes3]).stream().pipeThrough(stream)).arrayBuffer());\n}\nasync function sealDoc(key, obj) {\n let bytes3 = enc13.encode(JSON.stringify(obj)), z = false;\n if (canZip) {\n bytes3 = await pipeThrough(bytes3, new CompressionStream(\"gzip\"));\n z = true;\n }\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, key, bytes3));\n const buf = new Uint8Array(12 + ct.length);\n buf.set(iv);\n buf.set(ct, 12);\n return { v: 1, z, s: b64url2(buf) };\n}\nasync function openDoc(key, doc) {\n const buf = ub645(doc.s);\n let bytes3 = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: buf.slice(0, 12) }, key, buf.slice(12)));\n if (doc.z) bytes3 = await pipeThrough(bytes3, new DecompressionStream(\"gzip\"));\n return JSON.parse(dec6.decode(bytes3));\n}\nvar isSealedDoc = (d) => !!(d && typeof d === \"object\" && typeof d.s === \"string\" && d.v === 1);\nvar _rawKeys = /* @__PURE__ */ new Map();\nfunction rawSealKey(b6410) {\n if (!_rawKeys.has(b6410)) _rawKeys.set(b6410, crypto.subtle.importKey(\"raw\", ub645(b6410), { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]));\n return _rawKeys.get(b6410);\n}\n\n// spaces/public/sdk/4.7.1/tempList.js\nvar TEMP_LIST_MAX = 100;\nvar isTempRoomId = (r) => typeof r === \"string\" && r.startsWith(\"tmp-\") && r.length <= 64;\nasync function editTempList(store, room, mk, change, by = \"\") {\n for (let i = 0; i < 3; i++) {\n const r = await store.get(room, mk, \"rooms\");\n if (!(r && r.status === 200)) return null;\n const cur = r.state && Array.isArray(r.state.rooms) ? r.state.rooms : [];\n const next = change(cur);\n if (!next) return cur;\n const w = await store.put(room, mk, \"rooms\", { rooms: next }, \"temp rooms\", by || \"\", Number.isInteger(r.v) ? { ifV: r.v } : {});\n if (w && w.status === 409) continue;\n return w && w.status === 200 ? next : null;\n }\n return null;\n}\nfunction addToTempList(all, { room, title, fresh }) {\n const was = all.find((r) => r && r.room === room);\n const reopen = fresh && fresh.mk ? { mk: fresh.mk } : fresh && fresh.userShare ? { userShare: fresh.userShare, commit: fresh.commit || \"\" } : was && was.mk ? { mk: was.mk } : was && was.userShare ? { userShare: was.userShare, commit: was.commit } : null;\n if (!reopen) return null;\n const prev = all.filter((r) => r && r.room !== room);\n const entry = { room, title: title || was && was.title || \"Space\", at: was && was.at || Date.now(), ...reopen };\n return [entry, ...prev].slice(0, TEMP_LIST_MAX);\n}\nvar removeFromTempList = (all, rooms) => {\n const gone = new Set(rooms);\n return all.filter((r) => r && !gone.has(r.room));\n};\nvar keylessTempList = (list) => (Array.isArray(list) ? list : []).filter((e) => e && isTempRoomId(e.room)).map(({ mk: _mk, userShare: _us, commit: _c, ...rest }) => ({ ...rest, held: 1 }));\n\n// spaces/public/sdk/4.7.1/roomDefaultPrefs.js\nvar ROOM_DEFAULTS_DOC = \"room-defaults\";\nvar BOOLS = [\"quick\", \"enclave\", \"verified\", \"lanes\", \"temporary\"];\nvar STRINGS = [\"assistant\", \"model\"];\nvar FIELDS = [...BOOLS, ...STRINGS];\nfunction cleanRoomDefaults(value) {\n if (!value || typeof value !== \"object\" || value.v !== 1) return null;\n const out = { v: 1, mods: {} };\n for (const key of FIELDS) {\n if (BOOLS.includes(key) ? typeof value[key] !== \"boolean\" : typeof value[key] !== \"string\" || value[key].length > 200) continue;\n out[key] = value[key];\n const at = value.mods?.[key];\n out.mods[key] = Number.isSafeInteger(at) && at >= 0 ? at : 0;\n }\n return FIELDS.some((key) => key in out) ? out : null;\n}\nfunction mergeRoomDefaults(a, b) {\n a = cleanRoomDefaults(a);\n b = cleanRoomDefaults(b);\n if (!a) return b;\n if (!b) return a;\n const out = { v: 1, mods: {} };\n for (const key of FIELDS) {\n const winner = !(key in a) ? b : !(key in b) ? a : a.mods[key] > b.mods[key] ? a : a.mods[key] < b.mods[key] ? b : JSON.stringify(a[key]) >= JSON.stringify(b[key]) ? a : b;\n if (key in winner) {\n out[key] = winner[key];\n out.mods[key] = winner.mods[key];\n }\n }\n if (out.temporary && out.lanes) {\n if (out.mods.temporary >= out.mods.lanes) out.lanes = false;\n else out.temporary = false;\n }\n return out;\n}\n\n// spaces/public/sdk/4.7.1/accountStores.js\nvar SEALED = (name) => \"x\" + name;\nvar MOVED = \"sealed\";\nvar MAPS = [\"rooms\", \"pipes\"];\nvar REGISTRIES = { computers: \"computers\" };\nfunction mergeRegistryMap(a, b) {\n const out = /* @__PURE__ */ Object.create(null);\n const mod = (e) => e && typeof e === \"object\" && typeof e.mod === \"number\" && Number.isFinite(e.mod) && e.mod > 0 ? e.mod : 0;\n for (const src of [a, b]) {\n if (!src || typeof src !== \"object\" || Array.isArray(src)) continue;\n for (const id of Object.keys(src)) {\n const e = src[id], cur = out[id];\n if (!mod(e)) continue;\n if (!cur || mod(e) > mod(cur) || mod(e) === mod(cur) && e.removed && !cur.removed) out[id] = e;\n }\n }\n return out;\n}\nfunction carryMissing(mine, cur, name = \"\") {\n if (!cur || typeof cur !== \"object\" || !mine || typeof mine !== \"object\") return mine;\n const out = { ...mine };\n if (name === \"kept-agent-links\") {\n const links = { ...cur.links || {} };\n for (const [id, link] of Object.entries(mine.links || {})) if (!links[id] || link.at > links[id].at || link.at === links[id].at && link.gone) links[id] = link;\n return { ...out, links };\n }\n if (name === ROOM_DEFAULTS_DOC) return mergeRoomDefaults(mine, cur) || mine;\n if (/^usage-\\d{4}-(0[1-9]|1[0-2])$/.test(name)) {\n const rows = (r) => r && typeof r === \"object\" && !Array.isArray(r) ? r : {};\n return { ...out, r: { ...rows(cur.r), ...rows(mine.r) } };\n }\n const reg = REGISTRIES[name];\n if (reg) {\n out[reg] = mergeRegistryMap(cur[reg], mine[reg]);\n return out;\n }\n for (const m of MAPS) {\n const c = cur[m];\n if (!c || typeof c !== \"object\" || Array.isArray(c) || Array.isArray(mine[m])) continue;\n const have = mine[m] && typeof mine[m] === \"object\" ? mine[m] : {};\n const add = {};\n for (const id of Object.keys(c)) if (!(id in have) && !(m === \"rooms\" && id.startsWith(\"tmp-\"))) add[id] = c[id];\n if (Object.keys(add).length) out[m] = { ...add, ...have };\n }\n return out;\n}\nfunction makeAccountStore({ call: call2, key, oldKeys = async () => [] }) {\n const openAny = async (k, sealed) => {\n try {\n return { st: await openDoc(k, sealed), old: false };\n } catch {\n }\n let olds = [];\n try {\n olds = await oldKeys() || [];\n } catch {\n olds = [];\n }\n for (const ok of olds) {\n try {\n return { st: await openDoc(ok, sealed), old: true };\n } catch {\n }\n }\n return null;\n };\n const cleared = /* @__PURE__ */ new Set();\n const plainSeen = /* @__PURE__ */ new Map();\n const read = async (room, mk, name) => {\n try {\n return await call2(room, mk, name);\n } catch {\n return { status: 0 };\n }\n };\n const removalsToPlain = async (room, mk, name, reg, body) => {\n try {\n const pr = await read(room, mk, name);\n const cur = pr && pr.status === 200 && pr.state && typeof pr.state === \"object\" && !pr.state.z ? pr.state : null;\n const map = cur && cur[reg] && typeof cur[reg] === \"object\" ? cur[reg] : null;\n if (!map) return;\n const gone = {};\n for (const [id, e] of Object.entries(body && body[reg] || {})) if (e && e.removed && map[id] && !map[id].removed && mergeRegistryMap({ [id]: map[id] }, { [id]: e })[id] === e) gone[id] = e;\n if (Object.keys(gone).length) await call2(room, mk, name, { ...cur, [reg]: { ...map, ...gone } }, \"computer removed\", \"\", Number.isInteger(pr.v) ? pr.v : 0);\n } catch {\n }\n };\n return {\n /** → { status, state, sealed: bool, v? } — status 200 only for a DEFINITIVE read. `v`: the sealed doc's version, for a\n * write that must not land over a change it never merged (put's `ifV`). */\n async get(room, mk, name, { plainOpen = (s) => s } = {}) {\n const k = await key();\n const plainR = await read(room, mk, name);\n const pk = room + \"|\" + name;\n if (plainR && plainR.status === 200 && !plainSeen.has(pk)) plainSeen.set(pk, Number.isInteger(plainR.v) ? plainR.v : null);\n const plain = plainR && plainR.status === 200 && plainR.state && typeof plainR.state === \"object\" ? await plainOpen(plainR.state) : null;\n if (plain && plain.moved === MOVED) cleared.add(room + \"|\" + name);\n if (!k) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false };\n const sr = await read(room, mk, SEALED(name));\n if (!(sr && sr.status === 200)) return { status: sr && sr.status || 0, state: null, sealed: false };\n if (!isSealedDoc(sr.state)) return { status: plainR ? plainR.status : 0, state: plain && plain.moved !== MOVED ? plain : null, sealed: false, ...Number.isInteger(sr.v) ? { v: sr.v } : {} };\n const opened = await openAny(k, sr.state);\n if (!opened) return { status: 0, state: null, sealed: true, unopenable: true };\n let st2 = opened.st;\n let v = Number.isInteger(sr.v) ? { v: sr.v } : {};\n if (opened.old) {\n try {\n const w = await call2(room, mk, SEALED(name), await sealDoc(k, st2), \"sealed under the new account key\", \"\", Number.isInteger(sr.v) ? sr.v : 0);\n if (w && w.status === 200 && Number.isInteger(w.v)) v = { v: w.v };\n } catch {\n }\n }\n const reg = REGISTRIES[name];\n if (reg) return { status: 200, state: plain && plain.moved !== MOVED ? { ...st2, [reg]: mergeRegistryMap(st2[reg], plain[reg]) } : st2, sealed: true, ...v };\n if (plain && plain.moved !== MOVED) {\n st2 = { ...st2 };\n for (const m of MAPS) {\n if (Array.isArray(plain[m])) {\n const have = new Set((Array.isArray(st2[m]) ? st2[m] : []).map((e) => e && e.room));\n st2[m] = [...Array.isArray(st2[m]) ? st2[m] : [], ...plain[m].filter((e) => e && e.room && !have.has(e.room))];\n } else if (plain[m] && typeof plain[m] === \"object\") st2[m] = { ...plain[m], ...st2[m] || {} };\n }\n cleared.delete(room + \"|\" + name);\n }\n return { status: 200, state: st2, sealed: true, ...v };\n },\n /** Write sealed; then empty the plain doc (once). → { status } — 0 + error 'no_account_key' without the key.\n * ⛔ TWO DEVICES MUST NOT OVERWRITE EACH OTHER (a reviewer's finding, 2026-10-05): re-read the CURRENT sealed doc,\n * carry over the map entries this write lacks (carryMissing — rooms/pipes are tombstoned, never dropped by\n * omission), and write only if the doc has not moved since that read (ifV → 409 → again). A current doc that cannot\n * be read or opened is NOT written over. spaces/test/accountStoresConcurrent.test.mjs.\n * ⛔ `ifV` — THE VERSION THE CALLER MERGED (2026-11-07, the implicit-state-machine review): the re-read above carries over\n * only the room/pipe maps; a list (contacts, events, to-dos), the device registry or the read positions written by\n * another device between the CALLER's read and this one was replaced. With `ifV` the write lands only over that version:\n * anything else answers 409 { error: 'moved' } and the caller reads and merges again. Without it: as before. */\n async put(room, mk, name, obj, summary, by, { ifV } = {}) {\n const pinned = Number.isInteger(ifV);\n const k = await key();\n if (!k) return { status: 0, error: \"no_account_key\" };\n for (let i = 0; i < 5; i++) {\n const sr = await read(room, mk, SEALED(name));\n if (!(sr && sr.status === 200)) return { status: sr && sr.status || 0, error: \"unread\" };\n if (pinned && (isSealedDoc(sr.state) || Number.isInteger(sr.v)) && sr.v !== ifV) return { status: 409, error: \"moved\" };\n let body = obj;\n if (isSealedDoc(sr.state)) {\n const opened = await openAny(k, sr.state);\n if (!opened) return { status: 0, error: \"unopenable\" };\n body = carryMissing(obj, opened.st, name);\n }\n const r = await call2(room, mk, SEALED(name), await sealDoc(k, body), summary, by, Number.isInteger(sr.v) ? sr.v : 0);\n const status = r && r.status || 0;\n if (status === 409 && pinned) return { status: 409, error: \"moved\" };\n if (status === 409) {\n await new Promise((res) => setTimeout(res, 20 + Math.floor(Math.random() * 80) * (i + 1)));\n continue;\n }\n if (status === 200 && REGISTRIES[name]) await removalsToPlain(room, mk, name, REGISTRIES[name], body);\n if (status === 200 && !REGISTRIES[name] && !cleared.has(room + \"|\" + name)) {\n const pk = room + \"|\" + name, read0 = plainSeen.has(pk), pv = plainSeen.get(pk);\n plainSeen.delete(pk);\n let w = null;\n if (read0) {\n try {\n w = await call2(room, mk, name, { v: 2, moved: MOVED }, summary, by, ...Number.isInteger(pv) ? [pv] : []);\n } catch {\n }\n }\n if (w && w.status === 200) cleared.add(pk);\n }\n return { status };\n }\n return { status: 409, error: \"busy\" };\n }\n };\n}\n\n// spaces/public/sdk/4.7.1/changePush.js\nvar RELAY_URL = \"wss://code-relay.witbitz.chat\";\nvar RELAY_PING = '{\"t\":\"relay-ping\"}';\nvar RELAY_PONG = '{\"t\":\"relay-pong\"}';\nvar HEARTBEAT_MS = 25e3;\nvar PONG_WAIT_MS = 1e4;\nvar te2 = new TextEncoder();\n\n// spaces/public/sdk/4.7.1/roomStreamClient.js\nvar STREAM_EPOCH_MS = 10 * 60 * 1e3;\nvar te3 = new TextEncoder();\nvar b64u2 = (u) => {\n let s = \"\";\n for (const b of u) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\nvar sha = async (s) => new Uint8Array(await crypto.subtle.digest(\"SHA-256\", te3.encode(s)));\nvar streamChannel = async (mk, grant = \"\") => b64u2(await sha(\"witbitz-room-stream|\" + mk + (grant ? \"|\" + grant : \"\")));\nvar streamKey = async (mk, grant = \"\") => grant ? b64u2(await sha(\"witbitz-room-stream-key|\" + mk + \"|\" + grant)) : mk;\nfunction currentGrant(grants, now = Date.now()) {\n const e = Math.floor(now / STREAM_EPOCH_MS);\n const g = (Array.isArray(grants) ? grants : []).find((x) => x && x.e === e && typeof x.g === \"string\");\n return g ? g.g : null;\n}\nfunction frameReader() {\n let text = \"\", valid = true, lastSeq = 0, owedPoll = false, turn = null;\n const poll = (why) => {\n if (owedPoll) return null;\n owedPoll = true;\n return { k: \"poll\", why };\n };\n return {\n // A poll's text REPAIRS a reader that lost its place; it never overrides one that has not. The writer stores each\n // step and THEN posts its frame, so a poll can be ahead of the frames or behind them — the frames are the authority\n // while they are whole (the page's renderPartial orders the two by sequence number).\n sync(t) {\n if (valid) return;\n text = String(t || \"\");\n valid = true;\n owedPoll = false;\n },\n apply(f) {\n if (!f || typeof f !== \"object\") return null;\n const tail = Number.isInteger(f.count) && f.count > 0 && typeof f.box === \"string\" ? { tail: { count: f.count, box: f.box } } : {};\n if (f.oob) return f.k === \"entries\" ? { k: \"poll\", why: \"changed\", ...tail, ...typeof f.doc === \"string\" && /^[A-Za-z0-9]{1,24}$/.test(f.doc) ? { doc: f.doc } : {} } : f.k === \"views\" ? { k: \"views\" } : null;\n if (f.seq === 1) {\n lastSeq = 0;\n text = \"\";\n valid = true;\n owedPoll = false;\n turn = typeof f.tid === \"string\" ? f.tid : null;\n } else if (turn && typeof f.tid === \"string\" && f.tid !== turn) {\n valid = false;\n return poll(\"other turn\");\n }\n const gap = lastSeq && f.seq !== lastSeq + 1;\n lastSeq = Number(f.seq) || lastSeq;\n if (gap) {\n valid = false;\n return poll(\"gap\");\n }\n if (f.k === \"entries\") {\n if (tail.tail) {\n owedPoll = true;\n return { k: \"poll\", why: \"entries\", ...tail };\n }\n return poll(\"entries\");\n }\n if (f.k === \"resync\") {\n valid = false;\n return poll(\"resync\");\n }\n if (f.k === \"end\") {\n owedPoll = false;\n return { k: \"end\" };\n }\n if (f.k !== \"partial\") return null;\n const add = typeof f.add === \"string\" ? f.add : \"\";\n if (f.from === 0) {\n text = add;\n valid = true;\n owedPoll = false;\n } else if (valid && f.from <= text.length) text = text.slice(0, f.from) + add;\n else {\n valid = false;\n return poll(\"gap\");\n }\n return { k: \"partial\", text, pseq: f.pseq, step: f.step || null };\n }\n };\n}\nfunction openRoomStream({ mk, grants = null, tag = \"\", onEvent = () => {\n}, onState = () => {\n}, relay = RELAY_URL, path = \"c\", WebSocketImpl = globalThis.WebSocket, now = () => Date.now(), heartbeatMs = HEARTBEAT_MS, pongWaitMs = PONG_WAIT_MS } = {}) {\n if (!mk || typeof WebSocketImpl !== \"function\") return { up: () => false, sync() {\n }, setGrants() {\n }, stop() {\n } };\n const reader = frameReader();\n let ws = null, up = false, stopped = false, backoff = 1e3, retry = null, beat = null, pongTimer = null, epochTimer = null, key = null, gs = grants;\n const setUp = (v) => {\n if (v !== up) {\n up = v;\n try {\n onState(v);\n } catch {\n }\n }\n };\n const drop = () => {\n clearInterval(beat);\n clearTimeout(pongTimer);\n clearTimeout(epochTimer);\n beat = pongTimer = epochTimer = null;\n setUp(false);\n if (ws) {\n try {\n ws.onclose = ws.onerror = ws.onmessage = null;\n ws.close();\n } catch {\n }\n }\n ws = null;\n };\n const schedule = () => {\n if (stopped || retry) return;\n retry = setTimeout(() => {\n retry = null;\n connect();\n }, backoff);\n backoff = Math.min(backoff * 2, 3e4);\n };\n async function connect() {\n if (stopped || ws) return;\n const grant = gs ? currentGrant(gs, now()) : \"\";\n if (gs && !grant) return;\n key = await streamKey(mk, grant);\n let s;\n try {\n s = new WebSocketImpl(String(relay).replace(/\\/+$/, \"\") + \"/\" + path + \"/\" + await streamChannel(mk, grant) + (tag ? \"?v=\" + encodeURIComponent(tag) : \"\"));\n } catch {\n schedule();\n return;\n }\n if (stopped) {\n try {\n s.close();\n } catch {\n }\n return;\n }\n ws = s;\n s.onopen = () => {\n backoff = 1e3;\n setUp(true);\n beat = setInterval(() => {\n if (!ws || pongTimer) return;\n try {\n ws.send(RELAY_PING);\n } catch {\n drop();\n schedule();\n return;\n }\n pongTimer = setTimeout(() => {\n pongTimer = null;\n drop();\n schedule();\n }, pongWaitMs);\n }, heartbeatMs);\n if (gs) {\n const t = now();\n epochTimer = setTimeout(() => {\n drop();\n connect();\n }, (Math.floor(t / STREAM_EPOCH_MS) + 1) * STREAM_EPOCH_MS - t + 50);\n }\n };\n s.onmessage = async (ev) => {\n const text = typeof ev.data === \"string\" ? ev.data : \"\";\n if (text === RELAY_PONG) {\n clearTimeout(pongTimer);\n pongTimer = null;\n return;\n }\n if (!text || text.startsWith('{\"t\":')) return;\n let f = null;\n try {\n f = JSON.parse(await open(JSON.parse(text), { mk: key }) || \"null\");\n } catch {\n f = null;\n }\n const e = f && reader.apply(f);\n if (e) {\n try {\n onEvent(e);\n } catch {\n }\n }\n };\n s.onclose = s.onerror = () => {\n if (ws === s) {\n drop();\n schedule();\n }\n };\n }\n connect();\n return {\n up: () => up,\n sync: (t) => reader.sync(t),\n /** Fresh grants from a poll (a gated room): reconnect only if the current epoch's grant changed (a rotation). */\n setGrants(next) {\n if (!Array.isArray(next)) return;\n const changed = currentGrant(next, now()) !== currentGrant(gs, now());\n gs = next;\n if (changed || !ws) {\n drop();\n clearTimeout(retry);\n retry = null;\n connect();\n }\n },\n stop() {\n stopped = true;\n clearTimeout(retry);\n drop();\n }\n };\n}\n\n// spaces/public/sdk/4.7.1/roomPass.js\nvar enc14 = new TextEncoder();\nvar unb64uText = (s) => {\n const b = atob(String(s).replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return new TextDecoder().decode(Uint8Array.from(b, (c) => c.charCodeAt(0)));\n};\nfunction signInOf(body) {\n const m = body && body.message && typeof body.message === \"object\" ? body.message : null;\n const tok = body && typeof body.idToken === \"string\" && body.idToken || m && typeof m.idToken === \"string\" && m.idToken || \"\";\n const spk = body && body.idToken && body.spk || m && m.idToken && m.spk || null;\n if (!tok || !spk) return null;\n try {\n const p = JSON.parse(unb64uText(tok.split(\".\")[1]));\n const email = typeof p.email === \"string\" ? p.email.trim().toLowerCase() : \"\";\n return email.includes(\"@\") ? { email, spk } : null;\n } catch {\n return null;\n }\n}\nvar REVOKED_RETRY_MS = 5 * 6e4;\nvar SIGNIN_RENEW_AUTH = \"#signin-renew\";\n\n// spaces/public/sdk/4.7.1/l1-worker.js\nvar frameTails = /* @__PURE__ */ new Map();\nvar FRAME_TAIL_MS = 3e4;\nfunction openStreamHere(room, mk, grants, tag) {\n return openRoomStream({ mk, grants: Array.isArray(grants) ? grants : null, tag, onEvent: (ev) => {\n if (ev && ev.tail) {\n frameTails.set(room, { ...ev.tail, at: Date.now() });\n const { tail, ...rest } = ev;\n ev = rest;\n }\n self.postMessage({ t: \"stream\", room, ev });\n }, onState: (up) => self.postMessage({ t: \"stream\", room, up }) });\n}\nvar client = null;\nvar clientRealm = \"\";\nvar acctKey = null;\nvar oldAcctKeys = [];\nvar unzipDoc = async (st2) => st2 && typeof st2 === \"object\" && typeof st2.z === \"string\" ? await gunzipB64(st2.z).catch(() => null) : st2;\nvar acct = makeAccountStore({ call: (...a) => client.state(...a), key: async () => acctKey, oldKeys: async () => oldAcctKeys });\nvar tempPtr = null;\nvar tempStore = makeAccountStore({ call: (...a) => client.state(...a), key: async () => tempPtr && tempPtr.sk ? rawSealKey(tempPtr.sk) : null });\nvar TEMP_SK = /^[A-Za-z0-9_-]{43}$/;\nvar grantsByRoom = /* @__PURE__ */ new Map();\nvar streams = /* @__PURE__ */ new Map();\nfunction rekeyStream(room, mk) {\n const held = streams.get(room);\n if (!held?.s || held.mk === mk) return;\n held.s.stop();\n grantsByRoom.delete(room);\n held.mk = mk;\n held.grants = null;\n held.s = openStreamHere(room, mk, null, held.tag);\n}\nvar streamFeed = (room, result) => {\n const h = streams.get(room);\n if (!result || result.status !== 200) return;\n if (Array.isArray(result.streamGrants)) grantsByRoom.set(room, result.streamGrants);\n if (!h) return;\n if (Array.isArray(result.streamGrants)) {\n h.s?.setGrants(result.streamGrants);\n h.grants = result.streamGrants;\n }\n h.s?.sync(typeof result.partialText === \"string\" ? result.partialText : \"\");\n};\nvar mks = /* @__PURE__ */ new Map();\nvar splits = /* @__PURE__ */ new Map();\nvar sealKey = null;\nvar pushAcctRoom = \"\";\nvar derivePendingAcct = async () => {\n const mk = pushAcctRoom && mks.get(pushAcctRoom);\n if (!mk) return;\n pushAcctRoom = \"\";\n try {\n setPushAcct(await pushAcctSecretOf(mk));\n } catch {\n }\n};\nvar storageEpoch = 0;\nvar storageWiped = false;\nvar nkClear = false;\nvar protectedAtRest = false;\nvar parked = /* @__PURE__ */ new Map();\nvar volatile = /* @__PURE__ */ new Set();\nvar postAttNk = (room, nk) => {\n if (!room || !nk || String(room).startsWith(\"tmp-\")) return;\n try {\n self.postMessage({ t: \"attNk\", room, nk });\n } catch {\n }\n};\nvar roomOfKey = (k) => String(k).slice(String(k).indexOf(\":\") + 1);\nvar memOnlyRoom = (room) => volatile.has(room) || String(room).startsWith(\"tmp-\");\nvar persist = (k, v) => {\n const epoch = storageEpoch;\n return storageWiped || memOnlyRoom(roomOfKey(k)) ? Promise.resolve() : keysReady.then(() => !sealKey && protectedAtRest ? void 0 : sealIf(sealKey, v).then((stored) => epoch === storageEpoch && !storageWiped ? idb.set(k, stored) : void 0)).catch(() => {\n });\n};\nvar persistNk = (room, nk) => storageWiped ? Promise.resolve() : volatile.has(room) ? (postAttNk(room, nk), Promise.resolve()) : memOnlyRoom(room) ? Promise.resolve() : nkClear ? keysReady.then(() => storageWiped ? void 0 : idb.set(\"nk:\" + room, nk)).catch(() => {\n}) : protectedAtRest ? keysReady.then(() => idb.delRaw(\"nk:\" + room)).catch(() => {\n}) : persist(\"nk:\" + room, nk);\nvar eps = /* @__PURE__ */ new Map();\nvar noteEp = (room, ep) => {\n const n = Number(ep) || 0;\n if (room && n > (eps.get(room) || 0)) {\n eps.set(room, n);\n if (!memOnlyRoom(room)) idb.set(\"ep:\" + room, n).catch(() => {\n });\n }\n};\nvar backwards = (room, held, incoming, ep) => held !== incoming && (Number(ep) || 0) < (eps.get(room) || 0);\nvar tellEpoch = (room, ep, key) => {\n if (volatile.has(room) || String(room).startsWith(\"tmp-\")) return;\n try {\n self.postMessage({ t: \"keyEpoch\", room, ep, ...key });\n } catch {\n }\n};\nvar keep = (room, mk, ep) => {\n if (backwards(room, mks.get(room), mk, ep)) return false;\n if ((Number(ep) || 0) > 0 && (mks.get(room) !== mk || Number(ep) > (eps.get(room) || 0))) tellEpoch(room, Number(ep), { mk });\n if (ep) noteEp(room, ep);\n mks.set(room, mk);\n rekeyStream(room, mk);\n persist(\"mk:\" + room, mk);\n deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {\n });\n};\nvar APPSHARE_URL = (() => {\n try {\n const o = self.location && self.location.origin;\n return o && o !== \"null\" ? o + \"/api/appshare\" : \"/api/appshare\";\n } catch (e) {\n return \"/api/appshare\";\n }\n})();\nvar noKeyWhy = /* @__PURE__ */ new Map();\nvar noKeyReason = (room) => \"no key on this device\" + (noKeyWhy.has(room) ? \" — \" + noKeyWhy.get(room) : \"\");\nvar splitAlts = /* @__PURE__ */ new Map();\nvar heldOk = /* @__PURE__ */ new Map();\nasync function heldMatchesShare(room, have) {\n const sp = splits.get(room);\n if (!sp || !sp.commit || !((eps.get(room) || 0) > 0) || heldOk.get(room) === have) return true;\n let ok = false;\n try {\n ok = await commit(have) === sp.commit;\n } catch {\n ok = false;\n }\n if (ok) {\n heldOk.set(room, have);\n return true;\n }\n dropOldKey(room);\n return false;\n}\nvar dropOldKey = (room) => {\n if (!mks.has(room)) return;\n const h = streams.get(room);\n if (h) {\n h.s?.stop();\n h.mk = null;\n h.grants = null;\n }\n ;\n grantsByRoom.delete(room);\n mks.delete(room);\n keysReady.then(() => idb.del(\"mk:\" + room)).catch(() => {\n });\n};\nvar keepSplit = (room, sp, ep) => {\n if (backwards(room, splits.get(room) && splits.get(room).userShare, sp.userShare, ep)) return false;\n if ((Number(ep) || 0) > 0 && ((splits.get(room) || {}).userShare !== sp.userShare || Number(ep) > (eps.get(room) || 0))) {\n tellEpoch(room, Number(ep), { split: { userShare: sp.userShare, commit: sp.commit || \"\" } });\n if (Number(ep) > (eps.get(room) || 0) || (splits.get(room) || {}).userShare !== sp.userShare) dropOldKey(room);\n }\n if (ep) noteEp(room, ep);\n const held = splits.get(room);\n if (held && held.userShare !== sp.userShare) {\n const alts = splitAlts.get(room) || [];\n if (!alts.some((a) => a.userShare === held.userShare)) splitAlts.set(room, [held, ...alts].slice(0, 4));\n }\n splits.set(room, sp);\n persist(\"us:\" + room, sp);\n};\nvar forget = (room) => {\n grantsByRoom.delete(room);\n streams.get(room)?.s?.stop();\n streams.delete(room);\n mks.delete(room);\n splits.delete(room);\n eps.delete(room);\n for (const prefix of [\"mk:\", \"us:\", \"nk:\"]) parked.delete(prefix + room);\n lastPos.delete(room);\n heldOk.delete(room);\n splitAlts.delete(room);\n return Promise.all([\"mk:\", \"nk:\", \"us:\", \"ep:\", \"cnt:\"].map((prefix) => idb.delStrict(prefix + room)));\n};\nasync function resolveMk(room) {\n try {\n await keysReady;\n } catch {\n }\n const have = mks.get(room);\n if (have && await heldMatchesShare(room, have)) return have;\n const sp = splits.get(room);\n if (!sp) {\n noKeyWhy.set(room, \"no split share held\");\n return void 0;\n }\n let r = null;\n try {\n const x = await fetch(APPSHARE_URL, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ op: \"get\", room }) });\n if (!x.ok) {\n noKeyWhy.set(room, \"app half: HTTP \" + x.status);\n return void 0;\n }\n r = await x.json();\n } catch (e) {\n noKeyWhy.set(room, \"app half: \" + String(e && e.message || e).slice(0, 60));\n return void 0;\n }\n if (!r || !r.appShare) {\n noKeyWhy.set(room, \"app half: no share in the answer\");\n return void 0;\n }\n const cands = [sp, ...splitAlts.get(room) || []];\n for (const c of cands) {\n const mk = combineShares(c.userShare, r.appShare);\n if (mk && (!c.commit || await commit(mk) === c.commit)) {\n if (c !== sp) keepSplit(room, c);\n keep(room, mk, c === sp ? eps.get(room) : 0);\n noKeyWhy.delete(room);\n return mk;\n }\n }\n noKeyWhy.set(room, \"commitment mismatch: \" + cands.length + \" share(s) tried against the server half\" + (r.commit ? \" (server commit \" + String(r.commit).slice(0, 8) + \"…)\" : \"\"));\n return void 0;\n}\nvar ids = /* @__PURE__ */ new Map();\nvar encKey = null;\nvar encKeys = {};\nvar encAttested = null;\nvar encTrusted;\nvar encRooms = /* @__PURE__ */ new Set();\nvar authWaiters = /* @__PURE__ */ new Map();\nvar aseq = 0;\nvar attestWaiters = /* @__PURE__ */ new Map();\nvar delWaiters = /* @__PURE__ */ new Map();\nvar dseq = 0;\nvar delAsking = 0;\nvar askDel = (room) => new Promise((resolve) => {\n const a = ++dseq;\n delWaiters.set(a, resolve);\n self.postMessage({ delReq: a, room });\n setTimeout(() => {\n if (delWaiters.delete(a)) resolve(null);\n }, 5e3);\n});\nvar atseq = 0;\nvar publishPresence = () => self.postMessage({ t: \"presence\", rooms: [.../* @__PURE__ */ new Set([...mks.keys(), ...splits.keys()])], rk: 2, tl: 1 });\nvar dropTempCopy = (k) => {\n const room = k.slice(3);\n for (const pfx of [\"mk:\", \"us:\", \"nk:\", \"ep:\"]) idb.del(pfx + room).catch(() => {\n });\n};\nvar namesReady = Promise.all([idb.getRaw(\"protectedNames\"), idb.keysRaw(\"p:\")]).then(([f, ks]) => {\n if (f || ks && ks.length) {\n setIdbNaming({ on: true });\n protectedAtRest = true;\n }\n}).catch(() => {\n});\nvar keysReady = namesReady.then(() => Promise.all([\n idb.entries(\"mk:\").then((es) => {\n let n = 0;\n for (const [k, v] of es) if (k.startsWith(\"mk:tmp-\")) dropTempCopy(k);\n else if (isSealed(v)) {\n parked.set(k, v);\n protectedAtRest = true;\n } else if (v) {\n mks.set(k.slice(3), v);\n n++;\n }\n if (n) publishPresence();\n }).catch(() => {\n }),\n // a sealed entry waits for the device key (§PROTECT)\n idb.entries(\"ep:\").then((es) => {\n for (const [k, v] of es) {\n const n = Number(v);\n if (n > 0) eps.set(k.slice(3), n);\n }\n }).catch(() => {\n }),\n // key epochs (noteEp)\n idb.entries(\"us:\").then((es) => {\n let n = 0;\n for (const [k, v] of es) if (k.startsWith(\"us:tmp-\")) dropTempCopy(k);\n else if (isSealed(v)) {\n parked.set(k, v);\n protectedAtRest = true;\n } else if (v && v.userShare) {\n splits.set(k.slice(3), v);\n n++;\n }\n if (n) publishPresence();\n }).catch(() => {\n })\n // reload the split shares too — the reclaim-window fix\n]));\nvar AUTH_WAIT_MS = 2e4;\nvar auth = (room) => {\n const id = ids.get(room);\n if (id && id.googleIdToken && id.sign && id.sign.pub) return Promise.resolve({ idToken: id.googleIdToken, spk: id.sign.pub });\n return new Promise((resolve) => {\n const a = ++aseq;\n authWaiters.set(a, resolve);\n self.postMessage({ authReq: a, room });\n setTimeout(() => {\n const w = authWaiters.get(a);\n if (w) {\n authWaiters.delete(a);\n w({});\n }\n }, AUTH_WAIT_MS);\n });\n};\nvar attestShim = (room, o) => new Promise((resolve) => {\n const a = ++atseq;\n attestWaiters.set(a, resolve);\n self.postMessage({ attestReq: a, room, ...o && typeof o === \"object\" ? { o: { read: o.read === true, challenge: typeof o.challenge === \"string\" ? o.challenge : void 0 } } : {} });\n});\nsetAttestProvider(attestShim);\nvar IDB_WAIT = 2500;\nvar idbOpen = () => new Promise((res) => {\n const t = setTimeout(() => res(null), IDB_WAIT);\n try {\n const r = indexedDB.open(\"spaces\", 1);\n r.onupgradeneeded = () => {\n try {\n r.result.createObjectStore(\"kv\");\n } catch {\n }\n };\n r.onsuccess = () => {\n clearTimeout(t);\n const db = r.result;\n db.onversionchange = () => db.close();\n res(db);\n };\n r.onerror = () => {\n clearTimeout(t);\n res(null);\n };\n } catch {\n clearTimeout(t);\n res(null);\n }\n});\nvar idbGet = async (k) => {\n try {\n const db = await idbOpen();\n if (!db) return null;\n return await new Promise((res) => {\n const t = setTimeout(() => res(null), IDB_WAIT);\n const q = db.transaction(\"kv\", \"readonly\").objectStore(\"kv\").get(k);\n q.onsuccess = () => {\n clearTimeout(t);\n res(q.result || null);\n };\n q.onerror = () => {\n clearTimeout(t);\n res(null);\n };\n });\n } catch {\n return null;\n }\n};\nvar idbSet = async (k, v) => {\n try {\n const db = await idbOpen();\n if (!db) return false;\n return await new Promise((res) => {\n const t = setTimeout(() => res(false), IDB_WAIT);\n const q = db.transaction(\"kv\", \"readwrite\").objectStore(\"kv\").put(v, k);\n q.onsuccess = () => {\n clearTimeout(t);\n res(true);\n };\n q.onerror = () => {\n clearTimeout(t);\n res(false);\n };\n });\n } catch {\n return false;\n }\n};\nvar idbDel = async (k) => {\n try {\n const db = await idbOpen();\n if (!db) return false;\n return await new Promise((res) => {\n const t = setTimeout(() => res(false), IDB_WAIT);\n const q = db.transaction(\"kv\", \"readwrite\").objectStore(\"kv\").delete(k);\n q.onsuccess = () => {\n clearTimeout(t);\n res(true);\n };\n q.onerror = () => {\n clearTimeout(t);\n res(false);\n };\n });\n } catch {\n return false;\n }\n};\nvar lastPos = /* @__PURE__ */ new Map();\nvar prefetchChecked = /* @__PURE__ */ new Set();\nvar prefetchFlag = /* @__PURE__ */ new Set();\nvar prefetchLookUntil = 0;\ntry {\n const pfc = new BroadcastChannel(\"wb-prefetch\");\n pfc.onmessage = (e) => {\n const r = e && e.data && e.data.room;\n if (typeof r === \"string\") prefetchFlag.add(r);\n };\n} catch {\n}\nself.onmessage = async (e) => {\n const m = e.data || {};\n switch (m.t) {\n case \"delRes\": {\n const w = delWaiters.get(m.a);\n if (w) {\n delWaiters.delete(m.a);\n w(typeof m.v === \"string\" ? m.v : null);\n }\n return;\n }\n case \"authRes\": {\n const w = authWaiters.get(m.a);\n if (w) {\n authWaiters.delete(m.a);\n w(m.v || {});\n }\n return;\n }\n case \"attestRes\": {\n const w = attestWaiters.get(m.a);\n if (w) {\n attestWaiters.delete(m.a);\n w(m.v || null);\n }\n return;\n }\n case \"enclave\": {\n encKey = m.key || null;\n encAttested = m.attested || null;\n encKeys = m.keys && typeof m.keys === \"object\" ? m.keys : {};\n const snap = m.acceptance && typeof m.acceptance === \"object\" ? m.acceptance : {};\n encTrusted = Array.isArray(snap.trusted) ? snap.trusted : void 0;\n encRooms.clear();\n for (const r of m.rooms || []) encRooms.add(r);\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n // ── §PROTECT (docs/device-storage-protection.md): the device key arrives as 32 raw bytes, is imported non-extractable, and lives only here.\n case \"seal\": {\n try {\n sealKey = await importRaw(m.key);\n protectedAtRest = true;\n nkClear = !!m.previews;\n await keysReady;\n for (const k of parked.keys()) {\n try {\n await idb.delRaw(k);\n } catch {\n }\n }\n parked.clear();\n for (const [k, v] of await idb.entries(\"nk:\")) if (isSealed(v)) {\n try {\n await idb.delRaw(k);\n } catch {\n }\n }\n await armIdbNaming(m.key);\n let n = 0;\n for (const [room, mk] of mks) {\n await persist(\"mk:\" + room, mk);\n n++;\n try {\n await persistNk(room, await deriveNotifKey(mk));\n } catch {\n }\n }\n for (const [room, sp] of splits) {\n await persist(\"us:\" + room, sp);\n n++;\n }\n self.postMessage({ id: m.id, result: { sealed: n } });\n } catch (err) {\n sealKey = null;\n self.postMessage({ id: m.id, error: \"seal: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"unseal\": {\n try {\n const t0 = performance.now(), ms = {};\n const key = await importRaw(m.key);\n nkClear = !!m.previews;\n await keysReady;\n ms.ready = performance.now() - t0;\n await armIdbNaming(m.key);\n ms.names = performance.now() - t0;\n if ((await idb.keysRaw(\"p:\")).length && !(await idb.nameIndex()).length) {\n setIdbNaming({ on: true });\n throw new Error(\"this key opens nothing here\");\n }\n ms.check = performance.now() - t0;\n if (!parked.size) {\n for (const pfx of [\"mk:\", \"us:\", \"nk:\"]) for (const [k, v] of await idb.entries(pfx)) if (isSealed(v)) parked.set(k, v);\n }\n for (const k of [...parked.keys()]) if (/^(?:mk|us|nk):tmp-/.test(k)) {\n parked.delete(k);\n dropTempCopy(k);\n }\n ms.read = performance.now() - t0;\n ms.n = parked.size;\n let n = 0;\n const all = [...parked], vals = await Promise.all(all.map(([, blob]) => open2(key, blob)));\n all.forEach(([k], i) => {\n const v = vals[i];\n if (k.startsWith(\"mk:\")) {\n mks.set(k.slice(3), v);\n n++;\n } else if (k.startsWith(\"us:\")) {\n if (v && v.userShare) {\n splits.set(k.slice(3), v);\n n++;\n }\n }\n });\n parked.clear();\n sealKey = key;\n protectedAtRest = true;\n derivePendingAcct();\n for (const [room, mk] of mks) {\n persist(\"mk:\" + room, mk);\n deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {\n });\n }\n for (const [room, sp] of splits) persist(\"us:\" + room, sp);\n ms.open = performance.now() - t0;\n if (n) publishPresence();\n self.postMessage({ id: m.id, result: { opened: n, ms } });\n } catch (err) {\n self.postMessage({ id: m.id, error: \"unseal: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"previews\": {\n nkClear = !!m.on;\n try {\n if (sealKey) for (const [room, mk] of mks) {\n try {\n await persistNk(room, await deriveNotifKey(mk));\n } catch {\n }\n }\n } catch {\n }\n if (m.id != null) self.postMessage({ id: m.id, result: { previews: nkClear } });\n return;\n }\n case \"memoryOnly\": {\n protectedAtRest = true;\n sealKey = null;\n setIdbNaming({ on: true });\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"relock\": {\n if (sealKey) {\n mks.clear();\n splits.clear();\n parked.clear();\n sealKey = null;\n setIdbNaming({ on: true });\n publishPresence();\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"unprotect\": {\n try {\n const key = await importRaw(m.key);\n await keysReady;\n await armIdbNaming(m.key);\n const held = [];\n for (const pfx of [\"mk:\", \"us:\"]) for (const [k, v] of await idb.entries(pfx)) {\n held.push([k, v]);\n await idb.del(k);\n }\n setIdbNaming({ on: false });\n for (const [k, v] of await idb.entries(\"nk:\")) if (isSealed(v)) held.push([k, v]);\n for (const [k, v] of held) {\n const clear = isSealed(v) ? await open2(key, v) : v;\n await idb.set(k, clear);\n if (k.startsWith(\"mk:\")) mks.set(k.slice(3), clear);\n else if (k.startsWith(\"us:\") && clear && clear.userShare) splits.set(k.slice(3), clear);\n }\n parked.clear();\n sealKey = null;\n protectedAtRest = false;\n nkClear = false;\n publishPresence();\n for (const [room, mk] of mks) deriveNotifKey(mk).then((nk) => persistNk(room, nk)).catch(() => {\n });\n self.postMessage({ id: m.id, result: true });\n } catch (err) {\n self.postMessage({ id: m.id, error: \"unprotect: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"presenceQuery\": {\n await keysReady;\n publishPresence();\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"wipeKeys\": {\n storageWiped = true;\n storageEpoch++;\n await keysReady;\n for (const h of streams.values()) h.s?.stop();\n streams.clear();\n grantsByRoom.clear();\n mks.clear();\n splits.clear();\n parked.clear();\n splitAlts.clear();\n eps.clear();\n heldOk.clear();\n lastPos.clear();\n ids.clear();\n try {\n await idb.clearStrict();\n self.postMessage({ id: m.id, result: true });\n } catch (error) {\n self.postMessage({ id: m.id, error: String(error?.message || error) });\n } finally {\n publishPresence();\n }\n return;\n }\n case \"volatile\": {\n for (const r of Array.isArray(m.rooms) ? m.rooms : []) if (typeof r === \"string\" && r && !volatile.has(r)) {\n volatile.add(r);\n keysReady.then(() => Promise.all([idb.del(\"mk:\" + r), idb.del(\"us:\" + r)])).catch(() => {\n });\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"remember\": {\n keysReady.then(() => {\n if (m.room && m.mk) {\n keep(m.room, m.mk, m.ep);\n publishPresence();\n if (m.room === pushAcctRoom) derivePendingAcct();\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n });\n return;\n }\n case \"create\": {\n try {\n if (!client) throw new Error(\"l1-worker: create before open\");\n const via = m.split ? async (body) => {\n const x = await fetch(APPSHARE_URL, { method: \"POST\", credentials: \"same-origin\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify(body) });\n const j = await x.json().catch(() => ({}));\n return { ...j && typeof j === \"object\" ? j : {}, status: x.status };\n } : null;\n if (m.delAsk) delAsking++;\n let r;\n try {\n r = await client.create(m.cfg || {}, { base: m.base || void 0, ...m.enclave ? { enclave: true } : {}, ...via ? { split: true, via } : {} });\n } finally {\n if (m.delAsk) delAsking--;\n }\n if (!r || !r.room || !r.mk) throw new Error(\"create: \" + String(r && (r.error || r.status) || \"no room\"));\n if (m.split) {\n if (!r.userShare) throw new Error(\"create: the app-half function gave no share\");\n keepSplit(r.room, { userShare: r.userShare, commit: r.commit || \"\" });\n }\n keep(r.room, r.mk);\n publishPresence();\n const link0 = r.links && r.links[0] || null;\n const link = m.split && link0 ? String(link0).split(\"#\")[0] + \"#us=\" + encodeURIComponent(r.userShare) + (r.commit ? \"&spc=\" + encodeURIComponent(r.commit) : \"\") : link0;\n self.postMessage({ id: m.id, result: { room: r.room, link, ...r.enclaveCreated === true ? { enclaveCreated: true } : {}, commit: r.commit || null, ...r.configSealed ? { configSealed: r.configSealed } : {}, ...m.returnMk ? { mk: r.mk } : {} } });\n } catch (err) {\n self.postMessage({ id: m.id, error: String(err && err.message || err) });\n }\n return;\n }\n case \"forget\": {\n try {\n await keysReady;\n if (m.room) await forget(m.room);\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n } catch (error) {\n if (m.id != null) self.postMessage({ id: m.id, error: String(error?.message || error) });\n } finally {\n publishPresence();\n }\n return;\n }\n case \"setPushAcct\": {\n try {\n if (typeof m.secret === \"string\") {\n pushAcctRoom = \"\";\n if (m.secret === \"\" || /^[A-Za-z0-9_-]{43}$/.test(m.secret)) setPushAcct(m.secret);\n } else {\n const mk = m.room ? mks.get(m.room) || await resolveMk(m.room) : \"\";\n pushAcctRoom = m.room && !mk ? String(m.room) : \"\";\n setPushAcct(await pushAcctSecretOf(mk || \"\"));\n }\n } catch {\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"prefetchIdentity\": {\n try {\n if (client && typeof client.prefetchIdentity === \"function\") await client.prefetchIdentity(String(m.token || \"\"));\n } catch {\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"setPushSelf\": {\n try {\n setPushSelf(m.endpoint || \"\");\n } catch {\n }\n for (const [room, h] of streams) {\n try {\n const tag = await viewingTag(room);\n if (streams.get(room) !== h) continue;\n if (tag && tag !== h.tag && h.mk) {\n h.s?.stop();\n h.s = openStreamHere(room, h.mk, h.grants || null, tag);\n h.tag = tag;\n }\n } catch {\n }\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"serveKeyPort\": {\n const sp = e.ports && e.ports[0];\n if (sp && m.room) {\n try {\n const mk = mks.get(m.room) || await resolveMk(m.room);\n sp.postMessage({ room: m.room, mk: mk || null });\n } catch {\n try {\n sp.postMessage({ room: m.room, mk: null });\n } catch {\n }\n }\n }\n return;\n }\n case \"adoptKeyPort\": {\n const { id: aid, room: aroom } = m;\n const ap = e.ports && e.ports[0];\n if (!ap || !aroom) {\n if (aid != null) self.postMessage({ id: aid, result: { ok: false } });\n return;\n }\n let settled = false;\n const settle = (ok) => {\n if (settled) return;\n settled = true;\n try {\n ap.close();\n } catch {\n }\n if (aid != null) self.postMessage({ id: aid, result: { ok } });\n };\n ap.onmessage = (ev) => {\n const d = ev && ev.data || {};\n if (d.mk && d.room === aroom) {\n keep(aroom, d.mk);\n publishPresence();\n settle(true);\n } else settle(false);\n };\n setTimeout(() => settle(false), m.timeoutMs > 0 ? m.timeoutMs : 8e3);\n return;\n }\n case \"wakeup\": {\n prefetchLookUntil = Date.now() + 8e3;\n return;\n }\n // the page came to the foreground (vault-loader.js / space.js onVisibility): look for a push-time prefetch on the polls that follow\n case \"ping\": {\n self.postMessage({ t: \"pong\", n: m.n | 0 });\n return;\n }\n // liveness heartbeat — the vault detects a RECLAIMED worker (iOS memory pressure) and recreates it; without this a dead handle ate every message silently and rooms stopped opening\n case \"rememberSplit\": {\n keysReady.then(() => {\n if (m.room && m.userShare) {\n keepSplit(m.room, { userShare: m.userShare, commit: m.commit || \"\" }, m.ep);\n publishPresence();\n }\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n });\n return;\n }\n case \"rememberId\": {\n if (m.room && m.identity && m.identity.sign && m.identity.sign.priv) ids.set(m.room, m.identity);\n if (m.id != null) self.postMessage({ id: m.id, result: true });\n return;\n }\n case \"ensureMk\": {\n const { id, room } = m;\n try {\n const mk = await resolveMk(room);\n self.postMessage({ id, result: { ok: !!mk } });\n } catch (err) {\n self.postMessage({ id, error: \"ensureMk: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"inviteLink\": {\n const { id, room, base, suffix } = m;\n try {\n const sp = splits.get(room), held = !(sp && sp.userShare) && m.plain === true && typeof mks.get(room) === \"string\" ? mks.get(room) : \"\";\n const link = sp && sp.userShare ? base + \"#us=\" + encodeURIComponent(sp.userShare) + (sp.commit ? \"&spc=\" + encodeURIComponent(sp.commit) : \"\") + (suffix || \"\") : held ? base + \"#mk=\" + held + (suffix || \"\") : null;\n self.postMessage({ id, result: { link } });\n } catch (err) {\n self.postMessage({ id, error: \"inviteLink: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"open\": {\n try {\n if (m.room && m.mk) keep(m.room, m.mk);\n const realm = JSON.stringify([m.endpoint || \"/space\", m.app || \"\", m.tenant || \"\"]);\n if (client && clientRealm === realm) {\n publishPresence();\n self.postMessage({ id: m.id, result: true });\n return;\n }\n clientRealm = \"\";\n client = makeSpaceClient({\n endpoint: m.endpoint || \"/space\",\n app: m.app,\n ...m.tenant ? { tenant: m.tenant } : {},\n // a builder's vault (vault-core.js): the Spaces it creates are its tenant's\n auth,\n mkPub: (r) => encRooms.has(r) ? (() => {\n const e2 = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { key: encKey, attested: encAttested } : {});\n return gatedKey({ key: e2.key || null, trusted: encTrusted, attested: e2.attested || null, platform: e2.attested && e2.attested.platform, room: r });\n })() : null,\n // r's OWN region's key; another region's is never borrowed // trusted undefined until the account's list is known → the gate refuses\n enclave: (r) => encRooms.has(r),\n envelope: (r) => {\n if (!encRooms.has(r)) return false;\n const e2 = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { attested: encAttested } : {});\n return opensEnvelopes(e2.attested);\n },\n // the sealed request envelope (reqEnvelope.js): this room's live enclave opens it\n identity: (r) => {\n if (!encRooms.has(r)) return false;\n const e2 = encKeys[roomRegion(r)] || (roomRegion(r) === DEFAULT_REGION ? { attested: encAttested } : {});\n return sealsIdentity(e2.attested);\n },\n // option B: it takes the sign-in from inside\n // A Spaces ACCOUNT's turn token (accountBilling.js) — asked of the page through the auth channel under a reserved\n // name, only when an op can spend. No answer / no session ⇒ '' ⇒ the turn bills as before.\n userToken: async () => {\n const v = await auth(\"#account-billing\");\n return v && typeof v.userToken === \"string\" ? v.userToken : \"\";\n },\n // A builder's VAULT (vault-core.js) with an account backup: a create carries the deletion commitment, which only the\n // vault can make (it holds the erase key — sdkErase.js). Asked only while a create that said `delAsk` runs.\n delCommit: (r) => delAsking > 0 ? askDel(r) : Promise.resolve(null),\n // a promise either way: spaceClient .catch()es it\n // THE ROOM PASS (docs/device-gate-design.md): the page holds it (roomPassWiring.js) — asked under the reserved name\n // '#room-pass' with this request's op, room and sign-in (its email and key, never the token); {} = none (off)\n roomPass: {\n fieldsFor: async (body, o) => {\n const si = signInOf(body);\n if (!si) return {};\n const v = await auth(\"#room-pass:\" + JSON.stringify({ op: body.op, room: body.room, email: si.email, spk: si.spk, ...o && Number.isFinite(o.ts) ? { ts: o.ts } : {} }));\n return v && v.pass && v.psig ? { pass: v.pass, psig: v.psig } : {};\n },\n // ts: this realm's sealNow — the server's clock as learned here\n renew: async (body) => {\n const si = signInOf(body);\n if (si) return auth(\"#room-pass:\" + JSON.stringify({ renew: true, email: si.email }));\n }\n },\n // A SIGN-IN THAT NAMES NO APP (docs/device-gate-design.md § 12.1, `pass: app_unnamed`): renewed by whoever holds it — the\n // page, or the vault for an identity it seeded here — and, when it is one held here, kept here renewed too\n renewSignIn: async (body) => {\n const room = body && body.room;\n if (!room || !signInOf(body)) return null;\n const v = await auth(SIGNIN_RENEW_AUTH + \":\" + room);\n if (v?.retryable) return { retryable: true };\n if (!v || typeof v.idToken !== \"string\" || !v.spk) return null;\n const id = ids.get(room);\n if (id && id.sign && JSON.stringify(id.sign.pub) === JSON.stringify(v.spk)) ids.set(room, { ...id, googleIdToken: v.idToken });\n return { idToken: v.idToken, spk: v.spk };\n }\n });\n clientRealm = realm;\n publishPresence();\n self.postMessage({ id: m.id, result: true });\n } catch (err) {\n self.postMessage({ id: m.id, error: \"open: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"acctSeal\":\n // {obj} → a doc sealed under the ACCOUNT key (the server never holds it) · null without the key\n case \"acctOpen\": {\n ;\n (async () => {\n try {\n if (!acctKey) return self.postMessage({ id: m.id, result: null });\n const result = m.t === \"acctSeal\" ? await sealDoc(acctKey, m.obj) : isSealedDoc(m.doc) ? await openDoc(acctKey, m.doc) : null;\n self.postMessage({ id: m.id, result });\n } catch {\n self.postMessage({ id: m.id, result: null });\n }\n })();\n return;\n }\n case \"acctKey\": {\n acctKey = m.key || null;\n oldAcctKeys = Array.isArray(m.old) ? m.old.filter(Boolean) : [];\n if (m.id != null) self.postMessage({ id: m.id, result: { ok: !!acctKey } });\n return;\n }\n case \"indexRead\": {\n const { id, indexRoom, indexMk, name } = m;\n const keylessAsk = !!m.keyless;\n try {\n if (!client) throw new Error(\"l1-worker: indexRead before open\");\n await keysReady;\n if (indexMk && !mks.get(indexRoom)) {\n keep(indexRoom, indexMk);\n publishPresence();\n }\n const r = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc });\n if (!(r && r.status === 200 && r.state)) {\n self.postMessage({ id, result: { status: r && r.status || 0, state: null, ...r && Number.isInteger(r.v) ? { v: r.v } : {} } });\n return;\n }\n let st2 = r.state;\n const mirror = {};\n const splitRooms = {};\n if (st2 && typeof st2 === \"object\" && st2.rooms && typeof st2.rooms === \"object\") {\n const keyless = {};\n let replaced = 0;\n for (const rm of Object.keys(st2.rooms)) {\n const e2 = st2.rooms[rm] || {};\n if (e2.deleted) {\n const { mk: _dmk, ep: _dep, split: _ds, userShare: _du, commit: _dc, ...rest } = e2;\n keyless[rm] = rest;\n continue;\n }\n if (e2.split && e2.userShare) {\n const held = splits.get(rm);\n if (keepSplit(rm, { userShare: e2.userShare, commit: e2.commit || \"\" }, e2.ep) !== false) {\n if (held && held.userShare !== e2.userShare) replaced++;\n mirror[rm] = { split: true, userShare: e2.userShare, commit: e2.commit || \"\" };\n }\n splitRooms[rm] = String((splits.get(rm) || {}).commit || e2.commit || \"\");\n const { split: _s, userShare: _u, commit: _c, ep: _sep, ...rest } = e2;\n keyless[rm] = rest;\n } else {\n if (e2.mk && (mks.get(rm) === e2.mk || (Number(e2.ep) || 0) >= (eps.get(rm) || 0))) {\n keep(rm, e2.mk, e2.ep);\n mirror[rm] = { mk: e2.mk };\n }\n const { mk, ep: _ep, ...rest } = e2;\n keyless[rm] = rest;\n }\n }\n publishPresence();\n {\n const all = Object.keys(st2.rooms);\n const bare = all.filter((rm) => {\n const e2 = st2.rooms[rm] || {};\n return !e2.deleted && !(e2.split && e2.userShare) && !e2.mk && !mks.has(rm) && !splits.has(rm);\n });\n self.postMessage({ t: \"note\", line: \"index read: \" + all.length + \" rooms · \" + (all.length - bare.length) + \" with a key here · \" + (bare.length ? \"NO KEY for \" + bare.map((rm) => rm.slice(0, 10)).join(\" \") : \"none keyless\") + (replaced ? \" · \" + replaced + \" held share(s) differ from the index copy\" : \"\") });\n }\n st2 = { ...st2, rooms: keyless };\n }\n if (name === \"index\" && st2 && typeof st2 === \"object\") {\n for (const field of [\"pipesRoom\", \"msgsRoom\"]) {\n const ptr = st2[field];\n if (!ptr?.room) continue;\n if (ptr.mk) keep(ptr.room, ptr.mk);\n if (keylessAsk) st2 = { ...st2, [field]: { room: ptr.room } };\n }\n publishPresence();\n }\n self.postMessage({ id, result: { status: 200, state: st2, splits: splitRooms, ...keylessAsk ? {} : { mkeys: mirror }, ...Number.isInteger(r.v) ? { v: r.v } : {} } });\n } catch (err) {\n self.postMessage({ id, error: \"indexRead: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"indexWrite\": {\n const { id, indexRoom, indexMk, name, patch, summary, by, ifV } = m;\n try {\n if (!client) throw new Error(\"l1-worker: indexWrite before open\");\n await keysReady;\n if (indexMk && !mks.get(indexRoom)) {\n keep(indexRoom, indexMk);\n publishPresence();\n }\n let p = { ...patch || {} };\n let previousIndex;\n if (p.rooms && typeof p.rooms === \"object\") {\n let cur = {};\n try {\n let s = null;\n const rr = await acct.get(indexRoom, mks.get(indexRoom) || indexMk, name, { plainOpen: unzipDoc, notePlain: false });\n if (rr && rr.status === 200 && rr.state) s = rr.state;\n previousIndex = s;\n if (s && s.rooms && typeof s.rooms === \"object\") cur = s.rooms;\n } catch {\n }\n const rooms = {};\n for (const rm of Object.keys(p.rooms)) {\n const e2 = p.rooms[rm] || {};\n if (e2.deleted) {\n const { mk: _dmk, ep: _dep, split: _ds, userShare: _du, commit: _dc, ...rest } = e2;\n rooms[rm] = rest;\n continue;\n }\n if (splits.has(rm)) {\n const sp = splits.get(rm);\n rooms[rm] = { ...e2, split: true, userShare: sp.userShare, ...sp.commit ? { commit: sp.commit } : {}, ...eps.get(rm) ? { ep: eps.get(rm) } : {} };\n continue;\n }\n const mk = mks.get(rm);\n if (mk) {\n rooms[rm] = { ...e2, mk, ...eps.get(rm) ? { ep: eps.get(rm) } : {} };\n continue;\n }\n const prev = cur[rm];\n if (prev && prev.split && prev.userShare) {\n keepSplit(rm, { userShare: prev.userShare, commit: prev.commit || \"\" }, prev.ep);\n rooms[rm] = { ...e2, split: true, userShare: prev.userShare, ...prev.commit ? { commit: prev.commit } : {}, ...prev.ep ? { ep: prev.ep } : {} };\n continue;\n }\n if (prev && prev.mk) {\n keep(rm, prev.mk, prev.ep);\n rooms[rm] = { ...e2, mk: prev.mk, ...prev.ep ? { ep: prev.ep } : {} };\n continue;\n }\n }\n p.rooms = rooms;\n publishPresence();\n }\n if (name === \"index\") for (const field of [\"pipesRoom\", \"msgsRoom\"]) {\n const ptr = p[field];\n if (!ptr?.room || ptr.mk) continue;\n const saved = previousIndex?.[field];\n const mk = saved?.room === ptr.room && saved.mk || mks.get(ptr.room);\n if (!mk) throw new Error(\"The account room key is unavailable. Retry sync.\");\n p[field] = { room: ptr.room, mk };\n }\n const r = await acct.put(indexRoom, mks.get(indexRoom) || indexMk, name, p, summary, by, { ifV });\n self.postMessage({ id, result: { status: r && r.status || 0, bytes: _jsonBytes(p), z: true, ...r && r.error ? { error: r.error } : {} } });\n } catch (err) {\n self.postMessage({ id, error: \"indexWrite: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"pipesRead\": {\n const { id, pipesRoom, pipesMk, name } = m;\n try {\n if (!client) throw new Error(\"l1-worker: pipesRead before open\");\n if (pipesMk && !mks.get(pipesRoom)) {\n keep(pipesRoom, pipesMk);\n publishPresence();\n }\n const r = await acct.get(pipesRoom, mks.get(pipesRoom) || pipesMk, name);\n if (!(r && r.status === 200 && r.state)) {\n self.postMessage({ id, result: { status: r && r.status || 0, state: null, ...r && Number.isInteger(r.v) ? { v: r.v } : {} } });\n return;\n }\n let st2 = r.state;\n if (st2 && typeof st2 === \"object\" && st2.pipes && typeof st2.pipes === \"object\") {\n const keyless = {};\n for (const s of Object.keys(st2.pipes)) {\n const pp = st2.pipes[s] || {};\n const out = { ...pp };\n if (pp.shared && pp.shared.room) {\n if (pp.shared.mk) keep(pp.shared.room, pp.shared.mk);\n const { mk, ...rest } = pp.shared;\n out.shared = rest;\n }\n if (pp.lane && pp.lane.room) {\n if (pp.lane.mk) keep(pp.lane.room, pp.lane.mk);\n const { mk, ...rest } = pp.lane;\n out.lane = rest;\n }\n for (const k of [\"laneA\", \"laneB\"]) {\n const ep = pp[k];\n if (ep && ep.room) {\n if (ep.mk) keep(ep.room, ep.mk);\n const { mk, ...rest } = ep;\n out[k] = rest;\n }\n }\n keyless[s] = out;\n }\n publishPresence();\n st2 = { ...st2, pipes: keyless };\n }\n self.postMessage({ id, result: { status: 200, state: st2, ...Number.isInteger(r.v) ? { v: r.v } : {} } });\n } catch (err) {\n self.postMessage({ id, error: \"pipesRead: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"pipesWrite\": {\n const { id, pipesRoom, pipesMk, name, patch, summary, by, ifV } = m;\n try {\n if (!client) throw new Error(\"l1-worker: pipesWrite before open\");\n if (pipesMk && !mks.get(pipesRoom)) {\n keep(pipesRoom, pipesMk);\n publishPresence();\n }\n let pp = { ...patch || {} };\n if (pp.pipes && typeof pp.pipes === \"object\") {\n const pipes = {};\n for (const s of Object.keys(pp.pipes)) {\n const e2 = pp.pipes[s] || {};\n const out = { ...e2 };\n if (e2.shared && e2.shared.room) {\n const mk = mks.get(e2.shared.room);\n out.shared = mk ? { ...e2.shared, mk } : e2.shared;\n }\n if (e2.lane && e2.lane.room) {\n const mk = mks.get(e2.lane.room);\n out.lane = mk ? { ...e2.lane, mk } : e2.lane;\n }\n for (const k of [\"laneA\", \"laneB\"]) {\n const ep = e2[k];\n if (ep && ep.room) {\n const mk = mks.get(ep.room);\n out[k] = mk ? { ...ep, mk } : ep;\n }\n }\n pipes[s] = out;\n }\n pp.pipes = pipes;\n }\n const r = await acct.put(pipesRoom, mks.get(pipesRoom) || pipesMk, name, pp, summary, by, { ifV });\n self.postMessage({ id, result: { status: r && r.status || 0, ...r && r.error ? { error: r.error } : {} } });\n } catch (err) {\n self.postMessage({ id, error: \"pipesWrite: \" + String(err && err.message || err) });\n }\n return;\n }\n case \"tempHold\": {\n const p = m.ptr || {};\n const ok = isTempRoomId(p.room) && typeof p.mk === \"string\" && !!p.mk && typeof p.sk === \"string\" && TEMP_SK.test(p.sk);\n keysReady.then(() => {\n if (ok) {\n keep(p.room, p.mk);\n tempPtr = { room: p.room, sk: p.sk };\n publishPresence();\n }\n if (m.id != null) self.postMessage({ id: m.id, result: { ok, room: ok ? p.room : null } });\n });\n return;\n }\n case \"tempList\": {\n const { id } = m;\n const answer = (result) => self.postMessage({ id, result });\n (async () => {\n try {\n if (!client) throw new Error(\"l1-worker: tempList before open\");\n await keysReady;\n if (!tempPtr) return answer({ status: 0, error: \"no_pointer\" });\n const p = tempPtr, pmk = mks.get(p.room) || await resolveMk(p.room).catch(() => null);\n if (!pmk) return answer({ status: 0, error: \"no_key\", room: p.room });\n const absorb = (list2) => {\n for (const e2 of list2) {\n if (!e2 || !isTempRoomId(e2.room)) continue;\n if (e2.mk) keep(e2.room, e2.mk);\n else if (e2.userShare) keepSplit(e2.room, { userShare: e2.userShare, commit: e2.commit || \"\" });\n }\n publishPresence();\n };\n let list = null;\n if (m.do === \"read\") {\n const r = await tempStore.get(p.room, pmk, \"rooms\");\n if (!(r && r.status === 200)) return answer({ status: r && r.status || 0, room: p.room });\n list = r.state && Array.isArray(r.state.rooms) ? r.state.rooms : null;\n } else if (m.do === \"add\") {\n const a = m.add || {}, room = a.room;\n if (!isTempRoomId(room)) return answer({ status: 0, error: \"not_temp\", room: p.room });\n const sp = splits.get(room);\n const fresh = a.mk ? { mk: a.mk } : a.userShare ? { userShare: a.userShare, commit: a.commit || \"\" } : sp && sp.userShare ? { userShare: sp.userShare, commit: sp.commit || \"\" } : mks.get(room) ? { mk: mks.get(room) } : null;\n list = await editTempList(tempStore, p.room, pmk, (all) => addToTempList(all, { room, title: typeof a.title === \"string\" ? a.title.slice(0, 120) : \"\", fresh }), m.by);\n if (!list) return answer({ status: 0, room: p.room });\n } else if (m.do === \"remove\") {\n const rooms = (Array.isArray(m.rooms) ? m.rooms : []).filter(isTempRoomId);\n list = await editTempList(tempStore, p.room, pmk, (all) => removeFromTempList(all, rooms), m.by);\n if (!list) return answer({ status: 0, room: p.room });\n } else throw new Error(\"tempList: unknown \" + String(m.do));\n if (list) absorb(list);\n answer({ status: 200, room: p.room, rooms: list ? keylessTempList(list) : null });\n } catch (err) {\n self.postMessage({ id, error: \"tempList: \" + String(err && err.message || err) });\n }\n })();\n return;\n }\n case \"streamOpen\": {\n const { room } = m;\n const grants = m.grants || grantsByRoom.get(room);\n let held = streams.get(room);\n if (held) {\n held.holders++;\n if (Array.isArray(grants)) {\n held.grants = grants;\n held.s?.setGrants(grants);\n }\n return;\n }\n held = { holders: 1, mk: null, s: null, tag: \"\", grants: Array.isArray(grants) ? grants : null };\n streams.set(room, held);\n try {\n await keysReady;\n const mk = typeof m.mk === \"string\" && m.mk || mks.get(room) || await resolveMk(room);\n if (streams.get(room) !== held) return;\n if (!mk) {\n streams.delete(room);\n return;\n }\n const tag = await viewingTag(room).catch(() => \"\");\n if (streams.get(room) !== held) return;\n held.tag = tag;\n held.mk = mks.get(room) || mk;\n held.s = openStreamHere(room, held.mk, held.grants, tag);\n } catch (error) {\n if (streams.get(room) === held) streams.delete(room);\n }\n return;\n }\n case \"streamClose\": {\n const held = streams.get(m.room);\n if (held && --held.holders <= 0) {\n held.s?.stop();\n streams.delete(m.room);\n }\n return;\n }\n case \"op\": {\n const { id, op, room, args } = m;\n try {\n if (!client) throw new Error(\"l1-worker: op before open\");\n try {\n await keysReady;\n } catch {\n }\n if (typeof client[op] !== \"function\") throw new Error(\"l1-worker: unknown op \" + op);\n const aa = args || [];\n if (op === \"turn\" && aa[1] == null && ids.has(room)) aa[1] = ids.get(room);\n const index = routingIndex(op);\n if (index >= 0 && aa[index] && typeof aa[index] === \"object\") {\n const route = { ...aa[index] };\n aa[index] = route;\n if (route.bridgeRoom && !route.bridgeMk) {\n const key = mks.get(route.bridgeRoom) || await resolveMk(route.bridgeRoom);\n if (key) route.bridgeMk = key;\n }\n if (op === \"turn\" && Array.isArray(route.links)) {\n route.links = await Promise.all(route.links.map(async (link) => {\n if (!link?.room || link.mk) return link;\n const key = mks.get(link.room) || await resolveMk(link.room).catch(() => null);\n return key ? { ...link, mk: key } : link;\n }));\n }\n }\n const mkHere = await resolveMk(room);\n let result = null;\n let pfNote = \"\";\n const afterTap = !!(aa[2] && typeof aa[2] === \"object\" && aa[2].afterTap);\n if ((op === \"poll\" || op === \"pollSealed\") && mkHere && typeof client.decodeSealed === \"function\" && (afterTap || Date.now() < prefetchLookUntil || prefetchFlag.has(room) || !prefetchChecked.has(room))) {\n prefetchChecked.add(room);\n prefetchFlag.delete(room);\n let pfKey = \"prefetch:\" + room, pf = await idbGet(pfKey);\n if (!pf) {\n pfKey = await prefetchHashKey(room);\n pf = await idbGet(pfKey);\n }\n if (!pf) pfNote = \"none stored\";\n else {\n idbDel(pfKey);\n const why = prefetchUsable(pf, aa[1] | 0);\n if (why) pfNote = why + (why === \"position moved\" ? \" (stored since \" + pf.sinceCount + \", asked since \" + (aa[1] | 0) + \")\" : \"\");\n else {\n const pfAns = prefetchAnswer(pf, aa[1] | 0);\n if (!pfAns) pfNote = \"the tail does not reach this position\";\n else try {\n const out = await client.decodeSealed(room, mkHere, aa[1] | 0, pfAns);\n if (out && out.status === 200) {\n result = { ...out, prefetched: true };\n pfNote = pf.tail ? \"used (a tail from \" + pf.sinceCount + \")\" : \"used\";\n client[op](room, mkHere, ...aa).catch(() => {\n });\n } else pfNote = \"decoded to status \" + (out && out.status);\n } catch (e2) {\n result = null;\n pfNote = \"decode failed: \" + String(e2 && e2.message || e2).slice(0, 60);\n }\n }\n }\n }\n if (!result && (op === \"poll\" || op === \"pollSealed\") && mkHere && typeof client.decodeSealed === \"function\" && frameTails.has(room)) {\n const ft = frameTails.get(room);\n frameTails.delete(room);\n if (ft && Date.now() - ft.at < FRAME_TAIL_MS && (aa[1] | 0) === ft.count - 1) {\n try {\n const out = await client.decodeSealed(room, mkHere, ft.count - 1, { status: 200, changed: true, count: ft.count, from: ft.count - 1, sealed: JSON.stringify({ v: 3, from: ft.count - 1, count: ft.count, boxes: [ft.box] }) });\n if (out && out.status === 200) {\n result = { ...out, fromFrame: true };\n client[op](room, mkHere, ...aa).catch(() => {\n });\n }\n } catch {\n }\n }\n }\n if (!result && op === \"poll\" && !mkHere) result = { status: 401, error: \"no_key\", reason: noKeyReason(room) };\n if (op === \"rekey\" && splits.has(room)) aa[0] = { ...aa[0] || {}, split: { userShare: splits.get(room).userShare } };\n if (!result) result = await client[op](room, mkHere, ...aa);\n if (op === \"rekey\" && result && result.status === 200 && result.newShare) {\n keepSplit(room, { userShare: result.newShare, commit: result.newCommit }, result.epoch);\n keep(room, result.newMk, result.epoch);\n publishPresence();\n const { newMk: _nm, ...up } = result;\n result = { ...up, split: true };\n } else if (op === \"rekey\" && result && result.status === 200 && result.newMk) {\n keep(room, result.newMk, result.epoch);\n publishPresence();\n }\n if (op === \"pollSealed\" && !mkHere && result && result.status === 422) result = { ...result, error: \"no_key\", reason: noKeyReason(room) };\n if ((op === \"poll\" || op === \"pollSealed\") && result && result.status === 422 && result.reason === \"undecodable\" && splits.has(room) && mks.has(room)) {\n const stale = mks.get(room);\n mks.delete(room);\n idb.del(\"mk:\" + room).catch(() => {\n });\n const fresh = await resolveMk(room).catch(() => void 0);\n if (fresh && fresh !== stale) {\n const again = await client[op](room, fresh, ...aa);\n if (again && typeof again === \"object\") result = { ...again, rekeyed: true };\n } else if (stale) keep(room, stale);\n }\n if (pfNote && result && typeof result === \"object\") result = { ...result, prefetchNote: pfNote };\n if (op === \"poll\" || op === \"pollSealed\") {\n const pos = positionOf(result);\n const last = lastPos.get(room);\n if (pos && (!last || last.etag !== pos.etag || last.count !== pos.count)) {\n lastPos.set(room, pos);\n if (!protectedAtRest) idbSet(\"cnt:\" + room, pos);\n }\n }\n if (op === \"poll\" || op === \"pollSealed\") streamFeed(room, result);\n try {\n self.postMessage({ id, result });\n } catch (ce) {\n self.postMessage({ id, error: \"result-clone(\" + op + \"): \" + String(ce && ce.message || ce) });\n }\n } catch (err) {\n self.postMessage({ id, error: op + \": \" + String(err && err.message || err), ...err && err.code ? { code: err.code, verdict: err.verdict || null, room: err.room || null } : {} });\n }\n return;\n }\n }\n};\n"
|