@witbitz/sdk 0.0.0-stage → 4.4.0

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.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/ohttp.js ADDED
@@ -0,0 +1,177 @@
1
+ // ohttp.js — Oblivious HTTP (RFC 9458) over HPKE (RFC 9180) + Binary HTTP (RFC 9292), isomorphic (browser + Node),
2
+ // zero-dependency (WebCrypto only). This is the CLIENT-side encapsulation and the shared crypto; the gateway
3
+ // (agent/ohttpGateway.mjs) imports the same primitives for decapsulation.
4
+ //
5
+ // WHAT IT BUYS: it splits WHO from WHAT. The client encrypts the whole HTTP request to the GATEWAY's public key and
6
+ // sends it through a RELAY. The relay sees the client IP but only ciphertext; the gateway decrypts but sees only the
7
+ // relay's IP. Neither party alone links a user to their room. (Sizes/timing = the separate shaping axis; not here.)
8
+ //
9
+ // Ciphersuite = the OHTTP-mandatory-to-implement one, chosen for pure-WebCrypto support in every browser TODAY:
10
+ // KEM 0x0010 DHKEM(P-256, HKDF-SHA256) (ECDH P-256 + HKDF; X25519 would be nicer but isn't universal in WebCrypto)
11
+ // KDF 0x0001 HKDF-SHA256
12
+ // AEAD 0x0001 AES-128-GCM
13
+ // Verified byte-for-byte against the official CFRG HPKE test vectors (agent/ohttp.test.mjs).
14
+ const subtle = (globalThis.crypto && globalThis.crypto.subtle)
15
+ if (!subtle) throw new Error('ohttp: WebCrypto subtle unavailable')
16
+
17
+ export const SUITE = { kemId: 0x0010, kdfId: 0x0001, aeadId: 0x0001, Nsecret: 32, Nh: 32, Nk: 16, Nn: 12, Nenc: 65, Npk: 65 }
18
+
19
+ // ── byte helpers ──────────────────────────────────────────────────────────────────────────────────────────────────
20
+ const te = new TextEncoder()
21
+ export const cat = (...as) => { let n = 0; for (const a of as) n += a.length; const o = new Uint8Array(n); let i = 0; for (const a of as) { o.set(a, i); i += a.length } return o }
22
+ export const i2osp = (n, len) => { const o = new Uint8Array(len); for (let i = len - 1; i >= 0; i--) { o[i] = n & 0xff; n = Math.floor(n / 256) } return o }
23
+ export const hex = (u8) => [...u8].map((b) => b.toString(16).padStart(2, '0')).join('')
24
+ export const unhex = (s) => { const o = new Uint8Array(s.length / 2); for (let i = 0; i < o.length; i++) o[i] = parseInt(s.substr(i * 2, 2), 16); return o }
25
+ const eq = (a, b) => a.length === b.length && a.every((x, i) => x === b[i])
26
+
27
+ // ── HKDF (separate Extract/Expand — WebCrypto only exposes the combined form, so build it from HMAC) ────────────────
28
+ async function hmac(key, data) {
29
+ const k = await subtle.importKey('raw', key.length ? key : new Uint8Array(32), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
30
+ return new Uint8Array(await subtle.sign('HMAC', k, data))
31
+ }
32
+ const extract = (salt, ikm) => hmac(salt, ikm)
33
+ async function expand(prk, info, L) {
34
+ const out = []; let t = new Uint8Array(0)
35
+ for (let i = 1; out.reduce((n, b) => n + b.length, 0) < L; i++) { t = await hmac(prk, cat(t, info, new Uint8Array([i]))); out.push(t) }
36
+ return cat(...out).slice(0, L)
37
+ }
38
+ // Labeled variants (RFC 9180 §4). suite_id distinguishes the KEM sub-context from the full HPKE context.
39
+ const kemSuite = cat(te.encode('KEM'), i2osp(SUITE.kemId, 2))
40
+ const hpkeSuite = cat(te.encode('HPKE'), i2osp(SUITE.kemId, 2), i2osp(SUITE.kdfId, 2), i2osp(SUITE.aeadId, 2))
41
+ const labeledExtract = (salt, label, ikm, suite) => extract(salt, cat(te.encode('HPKE-v1'), suite, te.encode(label), ikm))
42
+ const labeledExpand = (prk, label, info, L, suite) => expand(prk, cat(i2osp(L, 2), te.encode('HPKE-v1'), suite, te.encode(label), info), L)
43
+
44
+ // ── DHKEM(P-256, HKDF-SHA256) ───────────────────────────────────────────────────────────────────────────────────────
45
+ const importPub = (raw) => subtle.importKey('raw', raw, { name: 'ECDH', namedCurve: 'P-256' }, true, [])
46
+ async function extractAndExpand(dh, kemContext) {
47
+ const eaePrk = await labeledExtract(new Uint8Array(0), 'eae_prk', dh, kemSuite)
48
+ return labeledExpand(eaePrk, 'shared_secret', kemContext, SUITE.Nsecret, kemSuite)
49
+ }
50
+ export async function kemEncap(pkRraw, ephemeral) {
51
+ const pkR = await importPub(pkRraw)
52
+ const kp = ephemeral || await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits'])
53
+ const dh = new Uint8Array(await subtle.deriveBits({ name: 'ECDH', public: pkR }, kp.privateKey, 256))
54
+ const enc = new Uint8Array(await subtle.exportKey('raw', kp.publicKey))
55
+ const shared = await extractAndExpand(dh, cat(enc, pkRraw))
56
+ return { shared, enc }
57
+ }
58
+ export async function kemDecap(enc, skR, pkRraw) {
59
+ const pkE = await importPub(enc)
60
+ const dh = new Uint8Array(await subtle.deriveBits({ name: 'ECDH', public: pkE }, skR, 256))
61
+ return extractAndExpand(dh, cat(enc, pkRraw))
62
+ }
63
+
64
+ // ── HPKE key schedule (mode_base = 0x00) + single-shot AEAD ──────────────────────────────────────────────────────────
65
+ export async function keySchedule(shared, info) {
66
+ const pskIdHash = await labeledExtract(new Uint8Array(0), 'psk_id_hash', new Uint8Array(0), hpkeSuite)
67
+ const infoHash = await labeledExtract(new Uint8Array(0), 'info_hash', info, hpkeSuite)
68
+ const ctx = cat(new Uint8Array([0x00]), pskIdHash, infoHash)
69
+ const secret = await labeledExtract(shared, 'secret', new Uint8Array(0), hpkeSuite)
70
+ const key = await labeledExpand(secret, 'key', ctx, SUITE.Nk, hpkeSuite)
71
+ const baseNonce = await labeledExpand(secret, 'base_nonce', ctx, SUITE.Nn, hpkeSuite)
72
+ const exporter = await labeledExpand(secret, 'exp', ctx, SUITE.Nh, hpkeSuite)
73
+ return { key, baseNonce, exporter }
74
+ }
75
+ const 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))
76
+ const 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))
77
+ const exportSecret = (ks, ctx, L) => labeledExpand(ks.exporter, 'sec', te.encode(ctx), L, hpkeSuite)
78
+
79
+ // ── OHTTP request/response (RFC 9458 §4.3/§4.4) ──────────────────────────────────────────────────────────────────────
80
+ const 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))
81
+ const hdr = (keyId) => cat(new Uint8Array([keyId]), i2osp(SUITE.kemId, 2), i2osp(SUITE.kdfId, 2), i2osp(SUITE.aeadId, 2))
82
+
83
+ /** Client: wrap a BHTTP request → { encRequest, ks, enc } (keep ks+enc to open the response). */
84
+ export async function encapsulateRequest(keyConfig, bhttp, _ephemeral) {
85
+ const { keyId, publicKey } = keyConfig
86
+ const { shared, enc } = await kemEncap(publicKey, _ephemeral)
87
+ const ks = await keySchedule(shared, reqInfo(keyId))
88
+ const ct = await aeadSeal(ks.key, ks.baseNonce, new Uint8Array(0), bhttp) // seq 0 → nonce = base_nonce
89
+ return { encRequest: cat(hdr(keyId), enc, ct), ks, enc }
90
+ }
91
+ /** Gateway: unwrap → { bhttp, ks, enc } (keep ks+enc to seal the response). skR = P-256 ECDH private CryptoKey. */
92
+ export async function decapsulateRequest(encRequest, skR, pkRraw) {
93
+ const keyId = encRequest[0]
94
+ const enc = encRequest.slice(7, 7 + SUITE.Nenc)
95
+ const ct = encRequest.slice(7 + SUITE.Nenc)
96
+ const shared = await kemDecap(enc, skR, pkRraw)
97
+ const ks = await keySchedule(shared, reqInfo(keyId))
98
+ const bhttp = await aeadOpen(ks.key, ks.baseNonce, new Uint8Array(0), ct)
99
+ return { keyId, bhttp, ks, enc }
100
+ }
101
+ /** Gateway: seal a BHTTP response. Per RFC 9458 §4.4 the response leg re-keys from the exporter with plain HKDF
102
+ * (Extract over enc‖nonce, Expand with the raw 'key'/'nonce' infos — NOT the HPKE labeled variants). */
103
+ export async function encapsulateResponse(ks, enc, bhttpResp, _fixedNonce) {
104
+ const L = Math.max(SUITE.Nn, SUITE.Nk)
105
+ const responseNonce = _fixedNonce || (globalThis.crypto.getRandomValues(new Uint8Array(L)))
106
+ const secret = await exportSecret(ks, 'message/bhttp response', L)
107
+ const prk = await extract(cat(enc, responseNonce), secret)
108
+ const key = await expand(prk, cat(te.encode('key')), SUITE.Nk)
109
+ const nonce = await expand(prk, cat(te.encode('nonce')), SUITE.Nn)
110
+ const ct = await aeadSeal(key, nonce, new Uint8Array(0), bhttpResp)
111
+ return cat(responseNonce, ct)
112
+ }
113
+ /** Client: open the sealed BHTTP response. */
114
+ export async function decapsulateResponse(ks, enc, encResponse) {
115
+ const L = Math.max(SUITE.Nn, SUITE.Nk)
116
+ const responseNonce = encResponse.slice(0, L)
117
+ const ct = encResponse.slice(L)
118
+ const secret = await exportSecret(ks, 'message/bhttp response', L)
119
+ const prk = await extract(cat(enc, responseNonce), secret)
120
+ const key = await expand(prk, cat(te.encode('key')), SUITE.Nk)
121
+ const nonce = await expand(prk, cat(te.encode('nonce')), SUITE.Nn)
122
+ return aeadOpen(key, nonce, new Uint8Array(0), ct)
123
+ }
124
+
125
+ // ── Binary HTTP (RFC 9292), known-length messages, the subset OHTTP needs ────────────────────────────────────────────
126
+ function putVarint(n) {
127
+ if (n < 64) return new Uint8Array([n])
128
+ if (n < 16384) return new Uint8Array([0x40 | (n >> 8), n & 0xff])
129
+ if (n < 1073741824) return new Uint8Array([0x80 | (n >> 24), (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff])
130
+ throw new Error('varint too large')
131
+ }
132
+ function getVarint(b, i) {
133
+ const p = b[i] >> 6, len = 1 << p
134
+ let v = b[i] & 0x3f
135
+ for (let j = 1; j < len; j++) v = v * 256 + b[i + j]
136
+ return [v, i + len]
137
+ }
138
+ const strField = (s) => { const u = te.encode(s); return cat(putVarint(u.length), u) }
139
+ const getStr = (b, i) => { const [n, j] = getVarint(b, i); return [new TextDecoder().decode(b.slice(j, j + n)), j + n] }
140
+
141
+ /** { method, scheme, authority, path, headers:{}, body:Uint8Array } → BHTTP known-length request bytes. */
142
+ export function encodeRequest({ method = 'POST', scheme = 'https', authority, path = '/', headers = {}, body = new Uint8Array(0) }) {
143
+ const control = cat(strField(method), strField(scheme), strField(authority), strField(path))
144
+ let fields = new Uint8Array(0)
145
+ for (const [k, v] of Object.entries(headers)) fields = cat(fields, strField(k.toLowerCase()), strField(String(v)))
146
+ const content = cat(putVarint(body.length), body)
147
+ return cat(new Uint8Array([0]), control, putVarint(fields.length), fields, content, putVarint(0)) // framing 0, …, empty trailers
148
+ }
149
+ export function decodeRequest(b) {
150
+ let i = 1 // framing indicator 0
151
+ let method, scheme, authority, path
152
+ ;[method, i] = getStr(b, i); [scheme, i] = getStr(b, i); [authority, i] = getStr(b, i); [path, i] = getStr(b, i)
153
+ let flen; [flen, i] = getVarint(b, i)
154
+ const fEnd = i + flen; const headers = {}
155
+ while (i < fEnd) { let k, v; [k, i] = getStr(b, i); [v, i] = getStr(b, i); headers[k] = v }
156
+ let clen; [clen, i] = getVarint(b, i)
157
+ const body = b.slice(i, i + clen)
158
+ return { method, scheme, authority, path, headers, body }
159
+ }
160
+ /** { status, headers, body } → BHTTP known-length response bytes. */
161
+ export function encodeResponse({ status = 200, headers = {}, body = new Uint8Array(0) }) {
162
+ let fields = new Uint8Array(0)
163
+ for (const [k, v] of Object.entries(headers)) fields = cat(fields, strField(k.toLowerCase()), strField(String(v)))
164
+ const content = cat(putVarint(body.length), body)
165
+ return cat(new Uint8Array([1]), putVarint(status), putVarint(fields.length), fields, content, putVarint(0)) // framing 1 = response
166
+ }
167
+ export function decodeResponse(b) {
168
+ let i = 1
169
+ let status; [status, i] = getVarint(b, i)
170
+ let flen; [flen, i] = getVarint(b, i)
171
+ const fEnd = i + flen; const headers = {}
172
+ while (i < fEnd) { let k, v; [k, i] = getStr(b, i); [v, i] = getStr(b, i); headers[k] = v }
173
+ let clen; [clen, i] = getVarint(b, i)
174
+ return { status, headers, body: b.slice(i, i + clen) }
175
+ }
176
+
177
+ export { eq as _eq }
package/opRouting.js ADDED
@@ -0,0 +1,10 @@
1
+ // Argument position after the room and its key in the room client.
2
+ export function routingIndex(op) {
3
+ switch (op) {
4
+ case 'turn': return 2
5
+ case 'decide': return 3
6
+ case 'carry':
7
+ case 'toolRules': return 0
8
+ default: return -1
9
+ }
10
+ }
@@ -0,0 +1,282 @@
1
+ // opencodeWire: the PURE OpenCode wire logic — no fetch, no DOM, no node builtins — shared by the Spaces "code"
2
+ // section (browser) and the /rc daemon (node). ONE definition, so the room lane and the attested client can never
3
+ // drift apart on what an event means.
4
+ //
5
+ // ★ EVERY SHAPE HERE WAS MEASURED against a live `opencode serve` v1.18.30 (OpenAPI 3.1 at GET /doc, 162 paths), not
6
+ // read off the docs. See tools/rc-opencode.mjs for the probe log; the load-bearing surprises:
7
+ // · GET /event is a GLOBAL stream (every session on the box) ⇒ a mapper MUST scope by sessionID.
8
+ // · the live stream speaks `message.part.updated`, NOT the prettier `session.next.*` names in the schema's Event
9
+ // union (those belong to the /api v2 stream) — pinning them would ship a mapper that never fires.
10
+ // · the user's OWN prompt comes back as a text part ⇒ roles are learned from message.updated (info.role).
11
+ // · a `file` part with url 'file://<abs>' IS read by the model.
12
+ // · permission.asked carries metadata.command — the human-readable label an approval needs.
13
+
14
+ /** A prompt + staged files → OpenCode message parts. Files ride as `file` parts with a file:// URL (MEASURED to be
15
+ * read), so bytes never enter the prompt text. An absent prompt omits the text part rather than sending "". */
16
+ export function partsFor(prompt, files = []) {
17
+ const text = typeof prompt === 'string' ? prompt.trim() : ''
18
+ const parts = text ? [{ type: 'text', text }] : []
19
+ for (const f of Array.isArray(files) ? files : []) {
20
+ if (!f || !(f.url || f.path)) continue
21
+ // Two origins for the same part: the DAEMON stages to disk and passes a path (file://), the BROWSER has bytes and
22
+ // passes a data: URL. Both MEASURED against a live server — file:// answered "ZUCCHINI", data: reached the model
23
+ // as a synthetic Read result.
24
+ parts.push({ type: 'file', mime: f.mime || 'application/octet-stream', filename: f.name || basename(f.path || 'attachment'), url: f.url || 'file://' + f.path })
25
+ }
26
+ return parts
27
+ }
28
+ const basename = (p) => String(p).split('/').pop() || 'attachment'
29
+
30
+ // Events we deliberately DROP. Named rather than defaulted: a new event type we have never seen should fall through
31
+ // to the unknown branch (also dropped) — but the list documents what the live stream actually carries, which is the
32
+ // part a reader cannot get from the schema.
33
+ const IGNORED = new Set([
34
+ 'server.connected', 'server.heartbeat', 'plugin.added', 'catalog.updated', 'reference.updated', 'integration.updated',
35
+ 'integration.connection.updated', 'models-dev.refreshed', 'session.diff',
36
+ 'message.updated', 'message.removed', 'message.part.removed', 'file.edited', 'file.watcher.updated',
37
+ 'lsp.updated', 'project.updated', 'project.directories.updated', 'vcs.branch.updated', 'installation.updated',
38
+ 'installation.update-available', 'permission.v2.asked', 'permission.v2.replied', 'question.v2.asked', 'question.v2.replied',
39
+ ])
40
+
41
+ // ── the agent's todo list (the measured wire is in codeTodos.js's header) ──
42
+ const STATUSES = ['pending', 'in_progress', 'completed', 'cancelled']
43
+ const PRIORITIES = ['high', 'medium', 'low']
44
+
45
+ /** The list as it can be drawn: the agent's order, known statuses and priorities, no empty items. */
46
+ export function normTodos(list) {
47
+ return (Array.isArray(list) ? list : [])
48
+ .filter((t) => t && typeof t === 'object' && String(t.content || '').trim())
49
+ .map((t) => ({
50
+ content: String(t.content),
51
+ status: STATUSES.includes(t.status) ? t.status : 'pending',
52
+ priority: PRIORITIES.includes(t.priority) ? t.priority : 'medium',
53
+ }))
54
+ }
55
+
56
+ // ── the agent's question tool (the measured wire is in codeQuestions.js's header) ──
57
+ const qstr = (v) => (v == null ? '' : String(v))
58
+
59
+ /** A request from `question.asked` or GET /question → {id, sessionID, callID, questions} — or null when it is not one. */
60
+ /** A session's undo point (opencode 1.18.30: revert {messageID, partID?, snapshot, diff}) — only what the page reads.
61
+ * `files`: OpenCode had a snapshot to put the files back from. Measured: in a folder that is not a git repository the
62
+ * undo still hides the turn, but snapshot is false and the files stay as they are. */
63
+ export function normRevert(r) {
64
+ if (!r || typeof r !== 'object' || typeof r.messageID !== 'string' || !r.messageID) return null
65
+ return { messageID: r.messageID, ...(typeof r.partID === 'string' && r.partID ? { partID: r.partID } : {}), files: !!r.snapshot }
66
+ }
67
+
68
+ export function normQuestionRequest(p) {
69
+ if (!p || typeof p !== 'object' || !p.id || !Array.isArray(p.questions)) return null
70
+ const questions = p.questions
71
+ .filter((q) => q && typeof q === 'object' && qstr(q.question).trim())
72
+ .map((q) => ({
73
+ question: qstr(q.question),
74
+ header: qstr(q.header),
75
+ options: (Array.isArray(q.options) ? q.options : [])
76
+ .filter((o) => o && typeof o === 'object' && o.label != null && qstr(o.label) !== '')
77
+ .map((o) => ({ label: qstr(o.label), description: qstr(o.description) })),
78
+ multiple: q.multiple === true,
79
+ custom: q.custom !== false,
80
+ }))
81
+ if (!questions.length) return null
82
+ // A question with no options and no typing cannot be answered. It is never DROPPED — the reply needs one answer per
83
+ // question, in order — the request is marked, and the card offers only Skip.
84
+ const answerable = questions.every((q) => q.options.length > 0 || q.custom)
85
+ return { id: qstr(p.id), sessionID: qstr(p.sessionID), callID: qstr(p.tool && p.tool.callID), questions, answerable }
86
+ }
87
+
88
+ /** ONE SSE event → the rc events it means (0, 1 or more). `sessionID` scopes it: GET /event is a GLOBAL stream
89
+ * carrying every session on the server, so an unscoped mapper would mix another room's run into this one's pane.
90
+ *
91
+ * `roles` is an optional Map the CALLER owns, filled from `message.updated` (which carries info.role + info.id) and
92
+ * read when a text part arrives. ★ MEASURED: the user's OWN prompt comes back as a `message.part.updated` text part,
93
+ * indistinguishable from the answer without this — the live probe echoed the prompt into the step list before the
94
+ * map existed. Unknown messageID ⇒ KEEP: losing the assistant's answer is far worse than echoing a prompt, so the
95
+ * drop happens only on an explicit 'user'. */
96
+ export function mapEvent(ev, sessionID = '', roles = null, partTypes = null) {
97
+ if (!ev || typeof ev !== 'object') return []
98
+ const type = String(ev.type || '')
99
+ const p = ev.properties || {}
100
+ const sid = p.sessionID || (p.info && p.info.id) || ''
101
+ if (sessionID && sid && sid !== sessionID) return [] // another session's event — not ours to render
102
+ // Learn roles BEFORE the ignore list drops the event: message.updated is noise for the pane and the only place the
103
+ // role is published. (Measured ordering: the user's message.updated precedes its part update.)
104
+ if (type === 'message.updated' && roles) {
105
+ const info = p.info || {}
106
+ if (info.id && info.role) roles.set(info.id, info.role)
107
+ }
108
+ // Part types, for the same reason: a delta names only its part, and reasoning streams on field 'text' exactly like the
109
+ // answer does (measured, opencode 1.18.30: message.part.updated {type:'reasoning'} first, then ~80 text deltas).
110
+ if (type === 'message.part.updated' && partTypes && p.part && p.part.id && p.part.type) partTypes.set(p.part.id, p.part.type)
111
+ if (IGNORED.has(type)) return []
112
+
113
+ if (type === 'session.created') return sid ? [{ kind: 'session', id: sid }] : []
114
+ if (type === 'session.idle') return [{ kind: 'idle' }]
115
+ // Whether the session is running a turn — whoever started it (another device, the TUI). Measured: {status:{type:'busy'}}
116
+ // when a turn starts, {type:'idle'} as it ends; 'retry' carries the provider's message while it waits to try again.
117
+ if (type === 'session.status') {
118
+ const st = p.status || {}
119
+ return st.type ? [{ kind: 'status', busy: st.type !== 'idle', retry: st.type === 'retry' ? String(st.message || '') : '' }] : []
120
+ }
121
+ // An undo or redo made anywhere (the TUI, another device) — the session record carries its undo point, or none.
122
+ if (type === 'session.updated') return sid ? [{ kind: 'revert', revert: normRevert(p.info && p.info.revert) }] : []
123
+ if (type === 'session.compacted') return [{ kind: 'note', text: 'context compacted' }]
124
+ if (type === 'session.error') return [{ kind: 'stderr', text: errText(p) }]
125
+
126
+ // ★ PROGRESSIVE TEXT. Measured payload: {sessionID, messageID, partID, field:'text', delta:'The'} — one token-ish
127
+ // chunk. The full text also arrives later as a part update, so a delta is an OPTIMISATION, never the only copy:
128
+ // a client that drops them still renders everything, just in one go at the end.
129
+ if (type === 'message.part.delta') {
130
+ if (p.field !== 'text' || typeof p.delta !== 'string' || !p.delta) return []
131
+ if (roles && p.messageID && roles.get(p.messageID) === 'user') return [] // our own prompt echoing back
132
+ if (partTypes && partTypes.get(p.partID) === 'reasoning') return [{ kind: 'thinking', id: p.partID, text: p.delta }] // not the answer
133
+ return [{ kind: 'delta', id: p.partID, messageID: p.messageID, text: p.delta }]
134
+ }
135
+
136
+ if (type === 'message.part.updated') {
137
+ const part = p.part || {}
138
+ if (part.type === 'text' && part.text) {
139
+ if (roles && part.messageID && roles.get(part.messageID) === 'user') return [] // our own prompt coming back
140
+ return [{ kind: 'text', id: part.id, text: String(part.text), done: !!(part.time && part.time.end) }]
141
+ }
142
+ if (part.type === 'reasoning') return [{ kind: 'reasoning', id: part.id, text: String(part.text || ''), done: !!(part.time && part.time.end) }]
143
+ if (part.type === 'tool') {
144
+ const st = part.state || {}
145
+ return [{ kind: 'tool', id: part.id, name: part.tool || 'tool', status: st.status || 'pending', input: st.input || {} }]
146
+ }
147
+ return [] // step-start / step-finish carry no content
148
+ }
149
+
150
+ if (type === 'permission.asked') {
151
+ return [{
152
+ kind: 'ask',
153
+ id: p.id,
154
+ permission: p.permission || 'tool',
155
+ // metadata.command is the human-readable form for bash; patterns is what the rule would match. Prefer the
156
+ // command, fall back to the first pattern — the room shows this to a person, so it must never be '[object]'.
157
+ detail: (p.metadata && typeof p.metadata.command === 'string' && p.metadata.command) || (Array.isArray(p.patterns) ? p.patterns[0] : '') || '',
158
+ patterns: Array.isArray(p.patterns) ? p.patterns : [],
159
+ always: Array.isArray(p.always) ? p.always : [],
160
+ callID: (p.tool && p.tool.callID) || '',
161
+ }]
162
+ }
163
+ // The answered ask's id rides as `requestID` (measured, 1.18.30) — reading `id` left a card answered elsewhere on screen.
164
+ if (type === 'permission.replied') { const id = p.requestID || p.id; return id ? [{ kind: 'settled', id: String(id) }] : [] }
165
+ // The agent's question tool (codeQuestions.js has the measured wire). Only the v1 events fire on this stream.
166
+ if (type === 'question.asked') {
167
+ const q = normQuestionRequest(p)
168
+ return q ? [{ kind: 'question', ...q }] : []
169
+ }
170
+ // The agent's todo list: the WHOLE list, every time (an empty one clears it).
171
+ if (type === 'todo.updated') return [{ kind: 'todos', todos: normTodos(p.todos) }]
172
+ if (type === 'question.replied' || type === 'question.rejected') return p.requestID ? [{ kind: 'question-settled', id: String(p.requestID) }] : []
173
+ return []
174
+ }
175
+ export const errText = (p) => {
176
+ const e = p && p.error
177
+ if (!e) return 'session error'
178
+ if (typeof e === 'string') return unwrapJsonMessage(e)
179
+ return unwrapJsonMessage(String((e.data && e.data.message) || e.message || e.name || JSON.stringify(e)).slice(0, 2000))
180
+ }
181
+
182
+ /** An error's words. OpenCode keeps a provider's JSON error body as the message string — the confidential proxy's
183
+ * refusal reached the owner's screen as `{"message":"not confidential: …","type":"receipt_unverified"}` — so a message
184
+ * that is such a body shows its `message`. */
185
+ export function unwrapJsonMessage(s) {
186
+ const str = String(s == null ? '' : s)
187
+ if (!/^\s*\{/.test(str)) return str
188
+ try {
189
+ const j = JSON.parse(str)
190
+ const m = j && ((typeof j.message === 'string' && j.message) || (j.error && typeof j.error.message === 'string' && j.error.message))
191
+ return m || str
192
+ } catch { return str }
193
+ }
194
+
195
+ /** Split an SSE byte stream into events. Kept separate from the transport so it can be tested on a string, and so a
196
+ * chunk boundary mid-event can never drop a tool call (the bug class that ate a streamed reply once already). */
197
+ export function makeSseParser(onData) {
198
+ let buf = ''
199
+ return (chunk) => {
200
+ buf += chunk
201
+ let i
202
+ while ((i = buf.indexOf('\n\n')) !== -1) {
203
+ const frame = buf.slice(0, i); buf = buf.slice(i + 2)
204
+ for (const line of frame.split('\n')) {
205
+ if (!line.startsWith('data:')) continue
206
+ const body = line.slice(5).trim()
207
+ if (!body) continue
208
+ try { onData(JSON.parse(body)) } catch { /* a non-JSON keepalive is not an error */ }
209
+ }
210
+ }
211
+ }
212
+ }
213
+
214
+ /** Model as ONE string, provider first: 'trustedrouter/deepseek/deepseek-v4-flash' → the two fields the API wants.
215
+ * The modelID keeps every remaining segment — TR's ids contain a slash, so splitting on the last one is wrong. */
216
+ export function parseModel(s) {
217
+ const str = String(s || '').trim()
218
+ if (!str) return null
219
+ const i = str.indexOf('/')
220
+ if (i <= 0 || i === str.length - 1) return null
221
+ return { providerID: str.slice(0, i), modelID: str.slice(i + 1) }
222
+ }
223
+
224
+ /** The room's default ruleset. Read-shaped tools auto-pass (a gate that turns a 20-step run into 20 taps gets switched
225
+ * off and protects nothing); everything that writes, executes or LEAVES THE BOX asks a human. Set at session
226
+ * creation, so the box's own opencode config — whose defaults are mostly `allow` — cannot widen it.
227
+ * ⚠ The enclave profile flips webfetch/websearch to 'deny' and offers the attested fetch_url instead: inside a
228
+ * measured boundary an arbitrary outbound URL is an exfiltration channel, not a convenience. */
229
+ export const OC_ASK_PERMISSIONS = ['bash', 'edit', 'webfetch', 'websearch', 'task', 'skill', 'external_directory']
230
+ export const OC_ALLOW_PERMISSIONS = ['read', 'glob', 'grep', 'list', 'lsp']
231
+ export const ocPermissionRuleset = ({ ask = OC_ASK_PERMISSIONS, allow = OC_ALLOW_PERMISSIONS } = {}) => [
232
+ ...allow.map((permission) => ({ permission, pattern: '*', action: 'allow' })),
233
+ ...ask.map((permission) => ({ permission, pattern: '*', action: 'ask' })),
234
+ ]
235
+
236
+ /** The answer is the LAST text part of the assistant message the prompt call returns — there is no `result` event on
237
+ * this wire, and the streamed parts are the same strings. Mirrors the spawn path's finalFromEvent. */
238
+ export const finalTextOf = (reply) => {
239
+ const parts = (reply && reply.json && Array.isArray(reply.json.parts) ? reply.json.parts : []).filter((p) => p && p.type === 'text' && p.text)
240
+ return parts.length ? String(parts[parts.length - 1].text) : ''
241
+ }
242
+
243
+ /** Why a fetch to the server failed, in terms a person can act on. A cross-origin fetch fails with the SAME opaque
244
+ * TypeError whether the server is stopped, CORS refused the origin, or the page is HTTPS and the target is HTTP — and
245
+ * the fix differs for each, so all three are named. Pure (protocol/base/origin are passed in) so it is testable. */
246
+ export function explainFetchFailure({ err, pageProtocol = 'http:', base = '', origin = '' } = {}) {
247
+ if (pageProtocol === 'https:' && /^http:/i.test(base)) {
248
+ return `blocked: this page is HTTPS and ${base} is HTTP, which the browser refuses silently (mixed content). Put an HTTPS front in front of the server — \`tailscale serve\` gives it a real certificate — or open this page over http on the same machine.`
249
+ }
250
+ return `cannot reach ${base} — is \`opencode serve\` running, and does it allow this origin? Start it with: opencode serve --port 4096 --cors ${origin}${err && err.message ? ' (' + err.message + ')' : ''}`
251
+ }
252
+
253
+ /** The server URL to start from. localhost is a fine guess when the page itself is local — and ALWAYS WRONG on a
254
+ * deployed HTTPS page, where it cannot even be fetched (mixed content). ★ Seen on a phone, first load of the
255
+ * deployed section: a wall of red explaining a default the user never chose. Unconfigured ⇒ '' ⇒ the UI asks. */
256
+ export function defaultBase({ stored = '', pageProtocol = 'http:' } = {}) {
257
+ if (stored) return stored
258
+ return pageProtocol === 'https:' ? '' : 'http://127.0.0.1:4096'
259
+ }
260
+
261
+ /** Which model capability a given attachment needs. TEXT NEEDS NONE: measured — the server expands a text file part
262
+ * into a synthetic "Called the Read tool" result, so the bytes arrive as a tool result any model can read. Images,
263
+ * PDFs, audio and video are passed to the MODEL, so the model must declare that input. */
264
+ export function neededCapability(mime) {
265
+ const m = String(mime || '').toLowerCase()
266
+ if (m.startsWith('image/')) return 'image'
267
+ if (m === 'application/pdf') return 'pdf'
268
+ if (m.startsWith('audio/')) return 'audio'
269
+ if (m.startsWith('video/')) return 'video'
270
+ return '' // text and everything else: read as a file, no model capability required
271
+ }
272
+
273
+ /** '' when the model can take it, otherwise a sentence saying what is wrong and what to do. `input` is the model's own
274
+ * declared capabilities.input from GET /api/model — measured: deepseek-v4-flash declares [], i.e. it cannot receive
275
+ * an image at all, which is exactly the "the agent cannot read my file" failure. */
276
+ export function attachmentWarning({ mime, modelLabel = 'this model', input = null }) {
277
+ const need = neededCapability(mime)
278
+ if (!need) return ''
279
+ if (!Array.isArray(input)) return '' // unknown catalog ⇒ say nothing rather than cry wolf
280
+ if (input.includes(need)) return ''
281
+ return `${modelLabel} cannot read ${need === 'pdf' ? 'PDFs' : need + 's'} — pick a model that accepts ${need} input, or attach a text file instead.`
282
+ }
package/oprf.js ADDED
@@ -0,0 +1,70 @@
1
+ // Verifiable OPRF over P-256 (2HashDH) — the WIRE-COMPATIBLE browser port of agent/oprf.mjs (docs/spaces-email-invite.md).
2
+ // Same curve, same DSTs, same encodings, so a `handle` blinded and finalized here in the browser equals the one the
3
+ // server derives with handleFor() (agent/oprf.test.mjs + oprfParity.test.mjs lock it). This is the client half: it turns
4
+ // an email into a directory handle WITHOUT the email leaving the device (the server evaluates a blinded point), and it
5
+ // VERIFIES the server's DLEQ proof so a malicious build/server can't substitute a per-user key to deanonymise lookups.
6
+ //
7
+ // The only dependency is the vendored, self-contained P-256 bundle (WebCrypto can't do scalar-mult / hash-to-curve).
8
+ // It's local JS — nothing leaves the origin, so the egress-lock CSP is untouched.
9
+ import { p256, hashToCurve, sha256 } from './noble-p256.js'
10
+
11
+ const P = p256.Point, Fn = P.Fn
12
+ const DST_H2C = 'WB-OPRF-v1-P256-SHA256'
13
+ const L_DLEQ = 'wb-oprf-dleq-v1'
14
+ const L_HANDLE = 'wb-oprf-handle-v1'
15
+ const enc = new TextEncoder()
16
+ const randBytes = () => (p256.utils.randomSecretKey || p256.utils.randomPrivateKey)()
17
+
18
+ function b64u(bytes) { let s = ''; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
19
+ function ub64u(str) { str = String(str).replace(/-/g, '+').replace(/_/g, '/'); const bin = atob(str); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out }
20
+ function cat(arrs) { let n = 0; for (const a of arrs) n += a.length; const out = new Uint8Array(n); let o = 0; for (const a of arrs) { out.set(a, o); o += a.length } return out }
21
+ function u32(x) { return new Uint8Array([(x >>> 24) & 255, (x >>> 16) & 255, (x >>> 8) & 255, x & 255]) }
22
+
23
+ const toNum = (b) => { let x = 0n; for (const y of b) x = (x << 8n) | BigInt(y); return x }
24
+ const scalar = (bytes) => Fn.create(toNum(bytes))
25
+ const pt = (p) => p.toBytes(true)
26
+ const unpt = (b) => P.fromBytes(b)
27
+ const norm = (email) => String(email).trim().toLowerCase()
28
+ const h2c = (emailNorm) => hashToCurve(enc.encode(emailNorm), { DST: DST_H2C })
29
+ function randScalar() { let s; do { s = scalar(randBytes()) } while (Fn.is0(s)); return s }
30
+
31
+ function dleqChallenge(G, kpub, B, Z, A1, A2) {
32
+ return scalar(sha256(cat([enc.encode(L_DLEQ), pt(G), pt(kpub), pt(B), pt(Z), pt(A1), pt(A2)])))
33
+ }
34
+ function finalizeHandle(emailNorm, N) {
35
+ const e = enc.encode(emailNorm)
36
+ return b64u(sha256(cat([enc.encode(L_HANDLE), u32(e.length), e, pt(N)])))
37
+ }
38
+
39
+ // ── server-shaped helpers (present for tests/parity; the browser normally calls only blind/finalize) ──────────────
40
+ export function generateKey() { return b64u(randBytes()) }
41
+ export function publicKey(kB64) { return b64u(pt(P.BASE.multiply(scalar(ub64u(kB64))))) }
42
+ export function evaluate(bB64, kB64) {
43
+ const k = scalar(ub64u(kB64))
44
+ const B = unpt(ub64u(bB64))
45
+ const Z = B.multiply(k)
46
+ const G = P.BASE, kpub = G.multiply(k)
47
+ const t = randScalar()
48
+ const A1 = G.multiply(t), A2 = B.multiply(t)
49
+ const c = dleqChallenge(G, kpub, B, Z, A1, A2)
50
+ const s = Fn.add(t, Fn.mul(c, k))
51
+ return { z: b64u(pt(Z)), proof: { c: b64u(Fn.toBytes(c)), s: b64u(Fn.toBytes(s)) } }
52
+ }
53
+ export function handleFor(email, kB64) { return finalizeHandle(norm(email), h2c(norm(email)).multiply(scalar(ub64u(kB64)))) }
54
+
55
+ // ── CLIENT (what the PWA actually uses) ──────────────────────────────────────────────────────────────────────────
56
+ export function blind(email) {
57
+ const r = randScalar()
58
+ return { b: b64u(pt(h2c(norm(email)).multiply(r))), r: b64u(Fn.toBytes(r)) }
59
+ }
60
+ export function finalize(email, zB64, rB64, proof, kpubB64) {
61
+ const G = P.BASE, kpub = unpt(ub64u(kpubB64))
62
+ const r = scalar(ub64u(rB64))
63
+ const B = h2c(norm(email)).multiply(r)
64
+ const Z = unpt(ub64u(zB64))
65
+ const c = scalar(ub64u(proof.c)), s = scalar(ub64u(proof.s))
66
+ const A1 = G.multiply(s).subtract(kpub.multiply(c))
67
+ const A2 = B.multiply(s).subtract(Z.multiply(c))
68
+ if (!Fn.eql(c, dleqChallenge(G, kpub, B, Z, A1, A2))) throw new Error('oprf: DLEQ verification failed')
69
+ return finalizeHandle(norm(email), Z.multiply(Fn.inv(r)))
70
+ }
@@ -0,0 +1,96 @@
1
+ // ownAgentLink.js — YOUR ALWAYS-ON SPACE AS AN OUTSIDE AGENT OF ONE OF YOUR PRIVATE ROOMS, AS GROK BOT IS (docs/cloud-device.md § 13.6
2
+ // decision 2; the owner, 2026-11-24: "I meant always on like an outside agent to the private lane" → "Like grokbot"). Two doors, one
3
+ // each way — the same doors Grok Bot uses, so nothing new at the Sentinel:
4
+ // JOBS OUT — the private room gets a CONNECTION (MCP) to the always-on Space's own door, with the token of a peer that Space keeps
5
+ // for it: marked `own` (a2aCore ownInstructions — it is the member asking) and `auto` (the cloud device answers, no draft).
6
+ // The private assistant sends a job with message_member on it; a call asks the member first unless its tool says otherwise.
7
+ // RESULTS IN — the private room keeps a JOB PEER named after the always-on Space (a2aCore jobInstructions: a report, no reply drafted);
8
+ // its token goes to the cloud device with that Space (door.mjs `report`), which sends each answer into the private
9
+ // room with message_member (cloud-device/report.mjs).
10
+ // Undo takes all of it away: both peers (their tokens stop at once), the connection, the device's target. A failure half-way undoes
11
+ // what was done. In the hosted app the vault installs both credentials and the page registers their hashes.
12
+ // `d` = the app's functions (space.js passes them; tests pass fakes).
13
+
14
+ export const ownPeerName = (laneName) => `Your assistant in “${String(laneName || 'a private room').slice(0, 60)}”`
15
+
16
+ /** The link between private room `lane` and always-on Space `space`, as this device's A2A record holds it → { lPeer, sPeer } | null. */
17
+ export function ownAgentLinkOf ({ lane, space, spaceName, laneName }, d) {
18
+ const lp = d.peersOf(lane).find((p) => p.job === true && p.name === spaceName)
19
+ const sp = d.peersOf(space).find((p) => p.own === true && p.name === ownPeerName(laneName))
20
+ return lp && sp ? { lPeer: lp.id, sPeer: sp.id } : null
21
+ }
22
+
23
+ /** Is the private room's connection to the Space's door in place? A link whose two doors exist but whose connection does not
24
+ * (an attach that failed, its undo lost — the owner's iPhone, 2026-11-25: Help said "already set", the assistant could not reach it)
25
+ * is NOT linked. → true / false; null when it cannot be told. */
26
+ export async function ownAgentConnected ({ lane, space, connId }, d) {
27
+ if (!d.connectionsIn) return null
28
+ let u; try { u = new URL(d.mcpUrl(space)) } catch { return null }
29
+ const list = await d.connectionsIn(lane)
30
+ if (!Array.isArray(list)) return null
31
+ return list.some((c) => c && (!connId || c.id === connId) && c.host === u.host && c.mcp && c.mcp.path === u.pathname)
32
+ }
33
+
34
+ /** Set it up. → { lPeer, sPeer, connId } (what Undo needs) — or throws the reason, having undone what it did. */
35
+ export async function linkOwnAgent ({ lane, space, spaceName, laneName }, d) {
36
+ const unavailable = d.unavailable()
37
+ if (unavailable) throw new Error(unavailable)
38
+ let prepared
39
+ const done = { lPeer: '', sPeer: '', connId: '', reported: false }
40
+ try {
41
+ // RESULTS IN: the private room's job peer, named after the always-on Space
42
+ if (!d.hasLane(lane)) await d.enableLane(lane, 'Private assistant')
43
+ if (!d.hasLane(space)) await d.enableLane(space, spaceName)
44
+ if (d.hosted()) prepared = await d.prepare({ space, laneUrl: d.mcpUrl(lane), spaceUrl: d.mcpUrl(space), laneName, spaceName })
45
+ const inTok = await d.addPeer(lane, spaceName, { reply: 'ask', job: true, ...(prepared && { tokenHash: prepared.reportHash }) })
46
+ done.lPeer = inTok.id
47
+ // JOBS OUT: the always-on Space's own door, a peer for this private assistant, answered by the device
48
+ const outTok = await d.addPeer(space, ownPeerName(laneName), { reply: 'auto', own: true, ...(prepared && { tokenHash: prepared.jobHash }) })
49
+ done.sPeer = outTok.id
50
+ await d.push()
51
+ await d.syncSpaceAgents(space) // what the cloud device reads: who may write, answered without asking, as the member's own
52
+ done.reported = true // also clear a target whose acknowledgement was lost
53
+ if (prepared) {
54
+ const conn = await d.install(prepared.jobHash, done.sPeer)
55
+ done.connId = conn.id
56
+ await d.keepHeld(conn)
57
+ } else {
58
+ await d.report(space, done.sPeer, { url: d.mcpUrl(lane), token: inTok.token, name: laneName })
59
+ const conn = await d.connect({ kind: 'mcp', url: d.mcpUrl(space), label: spaceName }, { token: outTok.token })
60
+ done.connId = conn.id
61
+ }
62
+ if (d.keepLink) await d.keepLink({ lane, space, lPeer: done.lPeer, sPeer: done.sPeer, connId: done.connId, pending: true })
63
+ await d.useIn(lane, done.connId)
64
+ if (d.keepLink) await d.keepLink({ lane, space, lPeer: done.lPeer, sPeer: done.sPeer, connId: done.connId })
65
+ return { lPeer: done.lPeer, sPeer: done.sPeer, connId: done.connId }
66
+ } catch (e) {
67
+ if (prepared && !done.connId) {
68
+ const cancelled = await d.cancel(prepared.jobHash).catch(() => null)
69
+ if (cancelled?.connId) done.connId = cancelled.connId
70
+ }
71
+ await unlinkOwnAgent({ lane, space, ...done }, d).catch(() => null)
72
+ throw e
73
+ }
74
+ }
75
+
76
+ /** Take it away (Help's Undo; and a half-done link). Each step on its own: one that fails does not keep the others. → true */
77
+ export async function unlinkOwnAgent ({ lane, space, lPeer, sPeer, connId, reported = true }, d) {
78
+ const errs = []
79
+ const step = async (f) => { try { await f() } catch (e) { errs.push(String((e && e.message) || e)) } }
80
+ if (!connId && lane && space && lPeer && sPeer && d.connectionsIn) {
81
+ const url = new URL(d.mcpUrl(space)), connections = await d.connectionsIn(lane)
82
+ if (!Array.isArray(connections)) throw new Error('the private assistant’s connections could not be read')
83
+ const matches = connections.filter((c) => c && c.host === url.host && c.mcp?.path === url.pathname)
84
+ if (matches.length > 1) throw new Error('more than one connection uses this agent’s address')
85
+ connId = matches[0]?.id
86
+ }
87
+ if (connId) await step(() => d.disconnect(connId))
88
+ if (sPeer && reported) await step(() => d.report(space, sPeer, null))
89
+ if (lPeer) await step(() => d.removePeer(lane, lPeer))
90
+ if (sPeer) await step(() => d.removePeer(space, sPeer))
91
+ if (lPeer || sPeer) await step(() => d.push())
92
+ if (sPeer) await step(() => d.syncSpaceAgents(space))
93
+ if (errs.length) throw new Error(errs[0])
94
+ if (connId && d.keepLink) await d.keepLink({ lane, space, lPeer, sPeer, connId, gone: true })
95
+ return true
96
+ }