@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/spaceClient.js ADDED
@@ -0,0 +1,1429 @@
1
+ // witz/public/spaceClient.js — the THIN async-Space client (docs/async-spaces-m2.md).
2
+ //
3
+ // The client holds `mk` (reconstructed LOCALLY from the link fragment). TWO read paths exist:
4
+ // • pollSealed (preferred) — the server returns the SEALED ledger and we open it here. `mk` never leaves the device
5
+ // on the hot loop, which fires every ~600ms while a Space is on screen.
6
+ // • poll (legacy) — `mk` is sent and the Lambda decrypts inside the AWS boundary, returning plaintext.
7
+ // `turn` still sends `mk`, because the agent genuinely needs plaintext to think; that window is bounded and per-request
8
+ // rather than continuous. So this module is transport + the client-side KEY math (mint / reconstruct / open). `fetch`
9
+ // is injectable so the whole thing is testable without a network. All the crypto lives in spaceConfig.js/e2ee.js.
10
+ import { applyConnectionsPatch } from './connectionEntry.js' // what a room keeps about a connection (docs/mcp-connections.md)
11
+ import { createConfiguredSpace, assembleConfiguredKey, parseConfiguredLink } from './spaceConfig.js'
12
+ import { newCode, sealUnderCode, openUnderCode } from './invite.js'
13
+ import { seal, open, ledgerAad, sealTo, genRecipientKey, splitKey, combineShares, newKey, commit as keyCommit } from './e2ee.js'
14
+ import { parseAcceptance } from './enclaveAccept.js'
15
+ import { signEntry } from './entrySig.js'
16
+ import { sealMk, mkAad, newNonce, sealNow, noteServerClock } from './mkseal.js'
17
+ import { sealRequest, openAnswer, PLAIN_OPS, IDENTITY_PLAIN_OPS, carriesIdentity } from './reqEnvelope.js' // the sealed request envelope (confidential rooms)
18
+
19
+ // SELF-SERVE EMBED attribution (demo tier): when the app runs at /embed-create?tid=…, carry the tenant id + the EMBEDDER
20
+ // origin (document.referrer — browser-set; the iframe can't forge its own referrer) so the server can adopt the new room
21
+ // to that tenant IFF the origin is one it DECLARED. Omitted (→ {}) outside the embed-create flow, so behavior is unchanged.
22
+ function embedAttribution() {
23
+ try {
24
+ if (typeof location === 'undefined') return {}
25
+ const tid = new URLSearchParams(location.search).get('tid') || ''
26
+ const embedOrigin = (typeof document !== 'undefined' && document.referrer) ? new URL(document.referrer).origin : ''
27
+ return (tid && embedOrigin) ? { tid: tid.slice(0, 64), embedOrigin } : {}
28
+ } catch { return {} }
29
+ }
30
+ import { verifyRoomGovernance } from './ownerPolicy.js'
31
+ import { staysDirect } from './roomName.js' // a direct chat that gains a third member is a group (rekey)
32
+ import { stageMirrorAttachments } from './mirrorBatch.js'
33
+ import { memberHash } from './rosterHash.js' // hash the email allow-list (room-bound) before sealing → co-members can't read addresses
34
+
35
+ async function directRoster(allow, room) {
36
+ if (!Array.isArray(allow?.emails) || !Array.isArray(allow?.mh) || !allow.mh.length) return allow
37
+ const shown = new Set(await Promise.all(allow.emails.map(email => memberHash(email, room))))
38
+ return { ...allow, mh: allow.mh.filter(hash => !shown.has(hash)) }
39
+ }
40
+
41
+ // Seal the agent CONFIG (persona/tools/…) under mk so it's ciphertext at rest — the server can't read what a Space is
42
+ // for; it decrypts-once per turn (same discipline as the ledger). Wire-compatible with the Lambda's envelope.open.
43
+ const sealConfig = async (config, mk) =>
44
+ JSON.stringify(await seal(JSON.stringify({
45
+ tools: config.tools, immediateTools: config.immediateTools, clientTools: config.clientTools, persona: config.persona, agentName: config.agentName,
46
+ ...(config.appId ? { appId: String(config.appId).slice(0, 40) } : {}), // §APP STORE Stage 1: the Space's chosen app — an ID, never a URL (the store origin resolves it against its catalog)
47
+ // The DECLARED MCP server (name → typed input schema) — sealed like the rest, so the platform can't read the app's
48
+ // skill surface at rest; the turn op reads it in the mk-scoped decrypt to type-check + admit an app→agent mcp call.
49
+ skills: config.skills,
50
+ // BYO model — {provider, key, model, baseUrl}. Sealed like the rest of the config, so the tenant's credential is
51
+ // ciphertext at rest and the platform cannot read it outside a turn.
52
+ model: config.model,
53
+ // Admission policy + allow-list ride INSIDE the sealed config → the platform can't read a Space's gate or who's
54
+ // allowed at rest; the turn op reads them only in the mk-scoped decrypt (spaceHandler create → spaceService turn).
55
+ // JSON.stringify drops undefined keys, so an open Space seals exactly as before (backward compatible).
56
+ admission: config.admission, allow: config.allow, requireChallenge: config.requireChallenge, agentKeys: config.agentKeys, usernames: config.usernames, // usernames:false = the room opted out of the server-stamped @username on verified entries (docs/spaces-usernames.md §7)
57
+ // Owner rule (docs/the-owner-rule.md): the owner-SIGNED App Policy + this room's tier, sealed like the rest — so the
58
+ // render enforces it and a joining client can open + peer-verify governance against the pinned owner key. Undefined
59
+ // (ungoverned room) ⇒ JSON.stringify drops them ⇒ sealed exactly as before.
60
+ ownerPolicy: config.ownerPolicy, roomTier: config.roomTier,
61
+ // Private lane (docs/spaces-private-lane.md): `bridge` = a private lane's link to its shared room; `agentReplies`
62
+ // = false for a Bridge SHARED room (an observer venue — the agent doesn't auto-reply). Sealed like the rest, so
63
+ // both are content-blind at rest; undefined (a normal Space) ⇒ JSON.stringify drops them ⇒ sealed exactly as before.
64
+ bridge: config.bridge, agentReplies: config.agentReplies,
65
+ // THE ROOM AS A STORE (agent/dataTools.mjs): the app's declared collections + field rules. Sealed like the rest; a
66
+ // room without one sees no data tools. Undefined ⇒ dropped ⇒ sealed exactly as before.
67
+ dataSchema: config.dataSchema,
68
+ // WHICH PLATFORM TOOLS the assistant gets (agent/spaceService.mjs normPlatformTools): absent = all, false = none, a list =
69
+ // only those. Undefined ⇒ dropped ⇒ sealed exactly as before.
70
+ platformTools: config.platformTools === false || Array.isArray(config.platformTools) ? config.platformTools : undefined,
71
+ // BUILDER MODE (Tomer, 2026-10-10): `framing: 'builder'` = the prompt is the app's persona and tools only — no Spaces
72
+ // framing; `dataWrites: false` = the room store offers data_query only. Undefined ⇒ dropped ⇒ sealed exactly as before.
73
+ framing: config.framing === 'builder' ? 'builder' : undefined,
74
+ // A PURGEABLE room (docs/room-messages.md § Retention): its handled rows may be purged (op 'purge'). Create-time only,
75
+ // and only the account's own control rooms — the server refuses it on any room with an assistant or admission.
76
+ retention: config.retention === 'purgeable' ? 'purgeable' : undefined,
77
+ dataWrites: config.dataWrites === false ? false : undefined,
78
+ // 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.
79
+ safeMedia: config.safeMedia === true ? true : undefined,
80
+ // Private lanes for EVERYONE (create checkbox): a create-time room property every joiner learns from the room —
81
+ // this whitelist silently DROPPED it, which is why an invitee whose link lost the one-shot &lanes=1 hint could
82
+ // never self-heal (the sealed config genuinely lacked the field). Undefined ⇒ dropped ⇒ sealed exactly as before.
83
+ lanes: config.lanes === true ? true : undefined,
84
+ lane: config.lane === true ? true : undefined, // 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)
85
+ // Membership fork (docs/spaces-membership-fork.md): the epoch's admitted ROSTER (name+spk per keeper), stamped by
86
+ // forkRoom. Since membership only changes via a fork (add = fork), this stays authoritative between forks — so the
87
+ // NEXT fork reads it instead of re-deriving from the ledger (whose carried history still holds removed members'
88
+ // spks). Absent on an original room ⇒ dropped by JSON.stringify ⇒ sealed exactly as before (roster derived from the
89
+ // ledger as the bootstrap). Sealed under mk like the rest — the platform can't read who's in.
90
+ roster: config.roster,
91
+ // `forkAuthority` = the spk allowed to publish a membership-fork notice for this room (the creator, then carried
92
+ // across forks). A keeper AUTO-FOLLOWS a fork only if the notice is signed by this key — the hijack defense, since
93
+ // anyone holding mk could otherwise read keeper spks from the ledger and forge a fork to a room they control.
94
+ forkAuthority: config.forkAuthority,
95
+ // `parent` = { room } of the PRIOR epoch, set by a LINK fork (P4, epoch-keyed): history lives in the parent chain
96
+ // rather than being re-sealed here, so a fork is O(1). readEpochChain walks it with the ancestor keys from the
97
+ // pointer. Absent on a normal/full-fork room ⇒ dropped by JSON.stringify ⇒ sealed exactly as before.
98
+ parent: config.parent,
99
+ // Enclave acceptance (docs/enclave-room-acceptance.md): what THIS Space accepts from the confidential tier —
100
+ // `{mode: follow|pin, minPolicyVersion, accepted:[{kernel,payload,policy,…}]}`. Sealed under mk like the rest, so
101
+ // every member (and the enclave, which re-opens the config) reads the same declaration; create-once, so a change
102
+ // is a fork. Validated here so garbage is refused at mint rather than guessed about by every opener. Absent
103
+ // (a normal Space, or a pre-P2 confidential one ⇒ follow) ⇒ dropped by JSON.stringify ⇒ sealed exactly as before.
104
+ enclave: parseAcceptance(config.enclave) || undefined,
105
+ // ROOM GOVERNANCE (2026-10-02). `admins` ({ emails }) and `approve` ('admins'|'members') are enforced by the SERVER
106
+ // (spaceService hasAdmins/isRoomAdmin/cardNeedsAdmin) — and were MISSING from this list, so an SDK room declared them
107
+ // and sealed without them: no admins, approvals by any member (a builder measured it on production). `forkedFrom` is
108
+ // where a fork came from; `connections` are the grants a fork carries. Undefined ⇒ dropped ⇒ sealed exactly as before.
109
+ admins: config.admins && Array.isArray(config.admins.emails) ? { emails: config.admins.emails.map((x) => String(x).toLowerCase()) } : undefined,
110
+ owners: config.owners && Array.isArray(config.owners.emails) ? { emails: config.owners.emails.map((x) => String(x).toLowerCase()) } : undefined, // OWNERS (2026-10-03): above admins, enforced by the room
111
+ forkedFrom: typeof config.forkedFrom === 'string' && config.forkedFrom ? config.forkedFrom.slice(0, 120) : undefined,
112
+ connections: Array.isArray(config.connections) && config.connections.length ? config.connections : undefined,
113
+ direct: config.direct === true ? true : undefined, // a DIRECT chat (directChat.js): the server refuses its rename, the other side files it by this
114
+ help: config.help === true ? true : undefined, // the account's HELP SPACE (helpSpace.js): the server runs its built-in help configuration
115
+ }), { room: mk }))
116
+ // A random pad the same shape as a real 2-of-2 invite → a SOLO record carries one too, so the stored record doesn't
117
+ // reveal the key model (couple vs solo).
118
+ const invitePad = () => { const r = crypto.getRandomValues(new Uint8Array(90)); return btoa(String.fromCharCode(...r)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
119
+
120
+ const DEFAULT_ENDPOINT = '/space'
121
+ const originBase = () => (typeof location !== 'undefined' && location.origin) || ''
122
+
123
+ // ── OHTTP (RFC 9458) — flag-gated oblivious transport ────────────────────────────────────────────────────────────
124
+ // When a client is configured with an OHTTP relay + the gateway's key config, every op is encapsulated to the
125
+ // gateway's public key and POSTed through the RELAY: the relay sees this device's IP but only ciphertext, the gateway
126
+ // decrypts the op but sees only the relay's IP — so neither alone links a device to its room. Behaviour-neutral when
127
+ // unset: `call()` posts JSON to the endpoint exactly as before. The crypto lives in ohttp.js (RFC-vector-tested).
128
+ // Two OHTTP modes, one seam. `{ send }` = the L1.5 mode: the app hands the raw op to a pinned, separate-origin frame
129
+ // (spaces/ohttp-l1) that encapsulates + fetches the attested relay itself, so the ENCAPSULATION runs in code the app
130
+ // can't tamper with (the verifiable-client property). `{ relay, keyConfig }` = the direct mode: the app encapsulates
131
+ // in-process (simpler; used by tests / the non-framed path). Unset ⇒ plain JSON POST (behaviour-neutral).
132
+ let _ohttp = null
133
+ export function configureOhttp(cfg) { _ohttp = (cfg && (typeof cfg.send === 'function' || (cfg.relay && cfg.keyConfig))) ? cfg : null }
134
+ export async function readSealedArchive(read) {
135
+ const first = await read(0)
136
+ if (!first?.more) return first
137
+ const boxes = [], revision = etag => String(etag || '').replace(/#\d+$/, '')
138
+ let page = first
139
+ for (let i = 0; i < 400; i++) {
140
+ let slice
141
+ try { slice = JSON.parse(page?.sealed) } catch { /* incomplete read */ }
142
+ if (page?.status !== 200 || revision(page.etag) !== revision(first.etag) || slice?.v !== 3 ||
143
+ !Array.isArray(slice.boxes) || slice.from !== boxes.length || slice.count !== boxes.length + slice.boxes.length) break
144
+ for (const box of slice.boxes) boxes.push(box)
145
+ if (!page.more) return { ...page, from: 0, count: boxes.length, sealed: JSON.stringify({ ...slice, from: 0, count: boxes.length, boxes }) }
146
+ if (!slice.boxes.length) break
147
+ page = await read(boxes.length)
148
+ }
149
+ return { status: 409, error: 'archive_incomplete' }
150
+ }
151
+ export function ohttpActive() { return !!_ohttp }
152
+
153
+ // OHTTP-PENDING GATE. When "Hide my IP" is ON, its setup (frame the L1.5 shim → attest the relay → fetch the key config)
154
+ // takes a beat, and NO op may fire direct meanwhile or it leaks the device IP the toggle exists to hide. The old code
155
+ // bought that guarantee by AWAITing setup in boot — which held the whole UI hostage for the full setup (seconds, and up
156
+ // to the 25s timeout on a bad network), the "blank for 30s then the app appears" bug. Instead: boot marks OHTTP pending
157
+ // SYNCHRONOUSLY (before op one) and stops awaiting, so views resolve instantly; each network op below awaits this gate,
158
+ // so it still never fires before OHTTP is up (success ⇒ routed oblivious) or has definitively given up (failure ⇒ direct,
159
+ // the unchanged fail-open-to-direct posture). Untouched when OHTTP is off: _ohttpPending stays null → zero added latency.
160
+ let _ohttpPending = null // a Promise (with its resolver stapled on) while setup is in flight; null otherwise
161
+ export function markOhttpPending() { let done; _ohttpPending = new Promise((r) => { done = r }); _ohttpPending._done = done }
162
+ export function resolveOhttpPending() { const p = _ohttpPending; _ohttpPending = null; if (p && p._done) p._done() }
163
+ async function awaitOhttpReady() { const p = _ohttpPending; if (p) { try { await p } catch { /* setup rejects are swallowed → fall through to the _ohttp check */ } } }
164
+
165
+ // Route ONE raw op through the ACTIVE OHTTP channel (the exact seam call() uses) and resolve the parsed JSON — or null
166
+ // when OHTTP is inactive, so a caller that does its own direct POST (the enclave attest/wake path, which bypasses the
167
+ // mk-sealing client) can fall back. This lets those non-sealing transports ALSO hide the device IP when "Hide my IP" is
168
+ // on: null ⇒ toggle off ⇒ direct POST (unchanged); an object (even {status:0,error}) ⇒ toggle on ⇒ NEVER a direct
169
+ // leak — fail-closed on IP exactly like call().
170
+ export async function ohttpSend(body, fetchImpl = (typeof fetch !== 'undefined' ? fetch : null)) {
171
+ await awaitOhttpReady() // hold until "Hide my IP" setup settles, so this never picks the direct path while OHTTP is still coming up
172
+ if (!_ohttp) return null
173
+ try { return _ohttp.send ? await _ohttp.send(body) : await ohttpCall(body, fetchImpl) }
174
+ catch (e) { return { status: 0, error: 'ohttp: ' + String((e && e.message) || e).slice(0, 120) } }
175
+ }
176
+
177
+ // VERIFY the relay's attestation, THEN enable OHTTP — fail-closed (an unverifiable relay is never used). The gateway
178
+ // key config is fetched THROUGH the relay (a plain {op:'ohttp-config'} the relay forwards), so even that first fetch
179
+ // never reveals the device IP to the gateway. `expect` pins the relay's Confidential Space identity (aud, operator
180
+ // project, hwmodel, optional image digest). Returns true when OHTTP is now active. Behaviour-neutral on failure.
181
+ export async function verifyAndEnableOhttp(relayBase, expect = {}, gateway = { authority: 'api.witbitz.chat', path: '/v1/space' }, fetchImpl) {
182
+ const f = fetchImpl || (typeof fetch !== 'undefined' ? fetch : null); if (!f) return false
183
+ try {
184
+ const cs = await import('./csAttest.js')
185
+ const nonce = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join('')
186
+ const att = await (await f(relayBase + '/attestation?nonce=' + nonce)).text()
187
+ const v = await cs.verifyCsToken(att, { ...expect, nonce }, { hwmodel: expect.hwmodel || 'GCP_AMD_SEV' })
188
+ if (!v.ok) { try { console.warn('ohttp: relay attestation refused —', v.error) } catch { /* */ } return false }
189
+ const cfg = await (await f(relayBase + '/relay', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'ohttp-config' }) })).json()
190
+ if (!cfg || !cfg.publicKey) return false
191
+ const bin = atob(String(cfg.publicKey).replace(/-/g, '+').replace(/_/g, '/')); const pk = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) pk[i] = bin.charCodeAt(i)
192
+ configureOhttp({ relay: relayBase + '/relay', gatewayAuthority: gateway.authority, gatewayPath: gateway.path, keyConfig: { keyId: cfg.keyId, publicKey: pk } })
193
+ try { console.log('ohttp: enabled via attested relay', v.imageReference) } catch { /* */ }
194
+ return true
195
+ } catch (e) { try { console.warn('ohttp enable failed:', (e && e.message) || e) } catch { /* */ } return false }
196
+ }
197
+ let _ohttpMod = null
198
+ const ohttpMod = async () => (_ohttpMod || (_ohttpMod = await import('./ohttp.js')))
199
+
200
+ async function ohttpCall(body, fetchImpl) {
201
+ const O = await ohttpMod()
202
+ const inner = O.encodeRequest({
203
+ method: 'POST', scheme: 'https', authority: _ohttp.gatewayAuthority, path: _ohttp.gatewayPath || '/',
204
+ headers: { 'content-type': 'application/json' }, body: new TextEncoder().encode(JSON.stringify(body)),
205
+ })
206
+ const { encRequest, ks, enc } = await O.encapsulateRequest(_ohttp.keyConfig, inner)
207
+ // Send the encapsulated request THROUGH the relay as { op:'ohttp', enc:<base64> } — the relay forwards this opaque
208
+ // envelope to the gateway verbatim (it can't read enc: ciphertext) and returns { res:<base64> }. Relay sees our IP
209
+ // but not the room; the gateway decrypts the room but sees the relay's IP, not ours.
210
+ const b64 = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s) }
211
+ const ub64 = (s) => { const bin = atob(s); const u = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i); return u }
212
+ const res = await fetchImpl(_ohttp.relay, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'ohttp', enc: b64(encRequest) }) })
213
+ if (!res.ok) return { status: res.status }
214
+ let env = {}; try { env = await res.json() } catch { return { status: res.status } }
215
+ if (!env.res) return { status: env.status || res.status, ...(env.error ? { error: env.error } : {}) }
216
+ const respBhttp = await O.decapsulateResponse(ks, enc, ub64(env.res))
217
+ const resp = O.decodeResponse(respBhttp)
218
+ let data = {}
219
+ try { data = JSON.parse(new TextDecoder().decode(resp.body) || '{}') } catch { /* status only */ }
220
+ return { status: resp.status, ...data }
221
+ }
222
+
223
+ async function call(endpoint, body, fetchImpl) {
224
+ await awaitOhttpReady() // hold until "Hide my IP" setup settles, so an op never leaks direct while OHTTP is still coming up
225
+ if (_ohttp) { try { return _ohttp.send ? await _ohttp.send(body) : await ohttpCall(body, fetchImpl) } catch (e) { return { status: 0, error: 'ohttp: ' + String((e && e.message) || e).slice(0, 120) } } }
226
+ const res = await fetchImpl(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
227
+ let data = {}
228
+ try { data = await res.json() } catch { /* non-JSON → status only */ }
229
+ return { status: res.status, ...data }
230
+ }
231
+
232
+ /** A space client bound to an endpoint. `create`/`open` do the KEY math locally; turn/poll/pending/decide are transport. */
233
+ // `app` — a short tag naming the app that creates rooms with this client ('spaces' for the first-party PWA, a
234
+ // third party's own tag when they embed). Sent on create only, so every room is attributable to its origin. It is
235
+ // self-declared and the server treats it as a hint, never as authorization — see the note in spaceHandler's create.
236
+ // Set it once here rather than at each call site, so no future create can forget it.
237
+ // This device's own push endpoint, if it has one. Sent with a turn so the server skips THIS DEVICE rather than every
238
+ // subscription whose stored name matches the author's — which fails in both directions: one person on two devices
239
+ // notifies neither, and two people who share a display name notify neither. Absent is fine; the server falls back to
240
+ // the old name rule for clients that predate this.
241
+ let _pushSelf = ''
242
+ export function setPushSelf(endpoint) { _pushSelf = String(endpoint || '') }
243
+ const pushSelf = () => _pushSelf
244
+ async function crossingPush(room) {
245
+ if (!room) return {}
246
+ return { crossingPush: { room, ...(pushSelf() ? { pushSelf: pushSelf() } : {}), ...(await pushAcctField(room)) } }
247
+ }
248
+ /** THIS device's VIEWING TAG for a room (agent/roomStream.mjs viewingTagFor — the same HMAC): its push endpoint as the key,
249
+ * so the server can recompute it from the subscription, per room so the relay cannot link the device across rooms. The
250
+ * room's stream socket carries it; while that socket is open, the server does not tickle this device for this room.
251
+ * '' when this device has no push endpoint (nothing to suppress). */
252
+ export async function viewingTag(room) {
253
+ if (!_pushSelf || !room || !(globalThis.crypto && crypto.subtle)) return ''
254
+ try {
255
+ const k = await crypto.subtle.importKey('raw', new TextEncoder().encode(_pushSelf), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
256
+ return b64u(new Uint8Array(await crypto.subtle.sign('HMAC', k, new TextEncoder().encode('witbitz-viewing|' + room))).slice(0, 16))
257
+ } catch { return '' }
258
+ }
259
+ // …and this device's ACCOUNT, so the server skips the poster's OTHER devices too (2026-10-03, the owner: "the other device
260
+ // started a round, I still get the tickle"). The secret is derived from the key of the account's INDEX ROOM — the room
261
+ // that syncs the account's room list, so every synced device of the account holds the same key, and no other member
262
+ // does (an account recovery key would have done too, but many accounts never set one up); what goes on the wire
263
+ // is HMAC(secret, room) — per room, so it never links one account across rooms. No secret ⇒ no field ⇒ as before.
264
+ let _pushAcct = ''
265
+ const _acctTags = new Map()
266
+ export const hasPushAcct = () => !!_pushAcct // export diagnostics: does this device tag its subscribes with an account?
267
+ export function setPushAcct(secret) { const s = String(secret || ''); if (s !== _pushAcct) { _pushAcct = s; _acctTags.clear() } }
268
+ const b64u = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
269
+ async function pushAcctField(room) {
270
+ if (!_pushAcct || !room || !(globalThis.crypto && crypto.subtle)) return {}
271
+ try {
272
+ let t = _acctTags.get(room)
273
+ if (!t) {
274
+ const k = await crypto.subtle.importKey('raw', new TextEncoder().encode(_pushAcct), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
275
+ t = b64u(new Uint8Array(await crypto.subtle.sign('HMAC', k, new TextEncoder().encode('witbitz-push-acct|' + room))).slice(0, 16))
276
+ _acctTags.set(room, t)
277
+ }
278
+ return { pushAcct: t }
279
+ } catch { return {} }
280
+ }
281
+ /** The push secret of the account, from its index room's key (`mk`), or '' — a one-way derivation, never the key. */
282
+ export async function pushAcctSecretOf(indexMk) {
283
+ const k = typeof indexMk === 'string' ? indexMk : ''
284
+ if (!k || !(globalThis.crypto && crypto.subtle)) return ''
285
+ return b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode('witbitz-push-acct-secret|' + k))))
286
+ }
287
+
288
+ // VERIFIED-CLIENT attestation provider (docs/verified-client-design.md, Phase 2 S3b). A requireVerifiedClient room
289
+ // withholds material reads unless the request carries a client-release attestation. The attestation is minted by the
290
+ // L1 vault (its install-time key), so L3 REQUESTS one per read via this injectable provider: `provider(room)` →
291
+ // attestation object (or null). Set by the extension/vault (setAttestProvider), or read from `window.__vcAttestProvider`.
292
+ // Unset ⇒ material reads on a verified room stay withheld (fail-closed — a non-verified client can't open one).
293
+ let _attestProvider = null
294
+ export function setAttestProvider(fn) { _attestProvider = typeof fn === 'function' ? fn : null }
295
+ export const getAttestProvider = () => _attestProvider // so the L1 façade can serve the WORKER realm's attestation requests from the main-thread provider
296
+ // THE READ PROOF provider — its own slot, so the verified-client provider (the vault's
297
+ // release attestation) is never replaced by it. In the worker realm both are the main-thread shim (attestShim forwards `o`).
298
+ let _readProvider = null
299
+ export function setReadAttestProvider(fn) { _readProvider = typeof fn === 'function' ? fn : null }
300
+ export const getReadAttestProvider = () => _readProvider
301
+ const readAttestProvider = () => _readProvider || _attestProvider
302
+ const attestProvider = () => _attestProvider || ((typeof window !== 'undefined' && typeof window.__vcAttestProvider === 'function') ? window.__vcAttestProvider : null)
303
+
304
+ // `tenant` — the PUBLIC id of the tenant this page belongs to (never a key). A create carries it as `tid`, and the
305
+ // server adopts the room to that tenant iff this page's origin is one the tenant declared. A page on an undeclared
306
+ // origin gains nothing by naming a tenant; a declared origin needs no credential.
307
+ // `userToken` — PER-USER BILLING (docs/tenant-billing.md § 13 3a): a short-lived token the TENANT'S BACKEND minted for one
308
+ // of its users (POST /v1/tenant/users/{id}/token). A value, or a function (sync or async) the app uses to refresh it. It
309
+ // rides ONLY on ops that can spend (SPEND_OPS): the server refuses a request whose token does not hold, and a page left
310
+ // open past the token's expiry must still be able to READ its rooms. Absent ⇒ nothing is sent, exactly as before.
311
+ /** A request body with its sign-in's token replaced by a renewed one → the new body, or null (no sign-in here, or the renewal is
312
+ * for another key: a turn's entry is signed by its key, so its token can be replaced only by one bound to the same key). */
313
+ export function withSignIn(b, fresh) {
314
+ if (!b || !fresh || typeof fresh.idToken !== 'string' || !fresh.idToken || !fresh.spk) return null
315
+ const same = (a) => { try { return JSON.stringify(a) === JSON.stringify(fresh.spk) } catch { return false } }
316
+ if (b.message && typeof b.message === 'object' && b.message.idToken) return same(b.message.spk) ? { ...b, message: { ...b.message, idToken: fresh.idToken } } : null
317
+ if (b.idToken) return { ...b, idToken: fresh.idToken, spk: fresh.spk } // a read: the key may change with the token (psig names it afresh)
318
+ return null
319
+ }
320
+ export const SPEND_OPS = new Set(['turn', 'title', 'decide', 'import'])
321
+ // VOICE ON CREDITS (docs/spaces-plans.md § 4a escape 9): press-to-talk and read-aloud keys are billed to the account whose
322
+ // token comes with the request — the account's own is attached here too (never over one the caller passed: the SDK's user).
323
+ const VOICE_OPS = new Set(['stt', 'tts'])
324
+ // THE ROOM PASS (docs/device-gate-design.md; roomPass.js): `roomPass` — { fieldsFor(body) → { pass, psig } | {}, renew?(body) } —
325
+ // adds an active device's pass and its session key's signature to every request that carries a sign-in. Unset ⇒ as before.
326
+ // `renewSignIn(body)` → { idToken, spk } | null: a fresh token for the request's sign-in (the same key: a turn's entry stays signed).
327
+ // The keyless tier probe's waits before it asks again after a FAULT (spaceClient tierOf): a 429 from the route's shared limit, a
328
+ // 5xx, no network. Jittered ×0.5–1.5. After the last, the room is "could not tell" for TIER_RETRY_MS.
329
+ const TIER_PROBE_WAITS = [500, 1500] // spread wide: a burst of rooms probing together must not retry together into the same limit
330
+ const tierFault = (r) => !r || !r.status || r.status === 429 || r.status >= 500
331
+ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl, auth, mkPub, app, enclave = false, envelope = false, identity = false, tenant, userToken, delCommit, roomPass = null, renewSignIn = null, onConfidential = null, tierWaits = TIER_PROBE_WAITS } = {}) {
332
+ const tenantHint = tenant ? { tid: String(tenant).slice(0, 64) } : {}
333
+ const f = fetchImpl || (typeof fetch !== 'undefined' ? fetch : null)
334
+ if (!f) throw new Error('no fetch available — pass { fetch }')
335
+ // ENCLAVE TIER. `enclave` and `mkPub` may EACH be a value OR a per-room function (room) => …, so ONE client can run
336
+ // some rooms in the enclave and others normally (a room's tier is fixed at creation). For an enclave room, post()
337
+ // marks the op enclave:true (the backend relays it to the Nitro enclave) and keyFields() seals mk to the room's
338
+ // ATTESTED enclave key (mkPub) — so the relay only ever sees opaque bytes. FAIL-CLOSED: an enclave room with no key
339
+ // throws rather than send raw mk to the relay. Both unset ⇒ identity, unchanged behavior.
340
+ const enclaveFor = (room) => { try { return typeof enclave === 'function' ? !!enclave(room) : !!enclave } catch { return false } }
341
+ // A thrown `enclave_not_accepted` (enclaveAccept.js gatedKey: the Space refuses THIS enclave build) must surface as
342
+ // itself — the UI shows the mismatch sheet on that code; any other mkPub failure still flattens to "no key".
343
+ const mkPubFor = (room) => { try { return typeof mkPub === 'function' ? (mkPub(room) || null) : (mkPub || null) } catch (e) { if (e && e.code === 'enclave_not_accepted') throw e; return null } }
344
+ // THE SEALED REQUEST ENVELOPE (reqEnvelope.js; docs/confidential-path-sweep-2026-11-05.md option A): `envelope` — a value or
345
+ // (room) => bool — says the room's LIVE enclave opens envelopes (its measured policy: reqEnvelope.opensEnvelopes). Then every
346
+ // content op goes sealed WHOLE to the enclave, and its answer comes back sealed under a one-time key. Unset ⇒ as before.
347
+ // → true | false | null (UNKNOWN: the live enclave's policy is not known here). Unknown is never "plaintext" (reqEnvelope.opensEnvelopes).
348
+ const envelopeFor = (room) => { try { const v = typeof envelope === 'function' ? envelope(room) : envelope; return v === true ? true : (v === null || v === undefined) && typeof envelope === 'function' ? null : false } catch { return null } }
349
+ // OPTION B (docs/confidential-identity-option-b.md): `identity` — a value or (room) => bool — says the room's live enclave takes
350
+ // WHO YOU ARE from inside the envelope (reqEnvelope.sealsIdentity). Then the sign-in token rides inside, with the hints the
351
+ // front would have added (op `idextras`, fetched apart from any room request and kept until they near their end).
352
+ const identityFor = (room) => { try { return (typeof identity === 'function' ? identity(room) : identity) === true } catch { return false } }
353
+ const extrasCache = new Map() // issuer|email → { v, exp } | { p } (in flight)
354
+ const EXTRAS_REFRESH_MS = 3_600_000 // refreshed in the background once an hour old: a changed @username reaches rooms within the hour
355
+ const tokenClaims = (tok) => { try { const p = JSON.parse(atob(String(tok).split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))); return p && typeof p === 'object' ? p : null } catch { return null } }
356
+ const fetchExtras = async (key, tok) => {
357
+ let r = await call(endpoint, { op: 'idextras', idToken: tok }, f).catch(() => null)
358
+ if (!r || (r.status !== 200 && r.status !== 401)) { await new Promise((ok) => setTimeout(ok, 400)); r = await call(endpoint, { op: 'idextras', idToken: tok }, f).catch(() => null) } // once more before the token goes outside
359
+ if (!r || r.status !== 200 || r.ok !== true || !Number.isFinite(r.exp)) { extrasCache.delete(key); return null }
360
+ // boundHints (sync sweep 2026-11-16 #6): the room-pass cutoff's word for this address, signed by the front for ten minutes — the enclave
361
+ // takes no other (agent/roomPass.mjs boundFromHints). They were dropped here, so with the cutoff on every confidential verified room
362
+ // refused a request without a pass. The front caps `exp` at theirs, so the cache below asks again before they end.
363
+ 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) } : {}) }
364
+ extrasCache.set(key, { v, exp: r.exp, at: Date.now() })
365
+ return v
366
+ }
367
+ /** The extras for this sign-in → {userHints?, issuerCfg?, boundHints?}, or null when they could not be had (the token then still rides
368
+ * INSIDE, with no hints — post() sends a refused request again once with fresh ones; state machines pass 7). `fresh`: past the cache. */
369
+ const extrasFor = async (tok, { fresh = false } = {}) => {
370
+ const c = tokenClaims(tok)
371
+ const email = c && typeof c.email === 'string' ? c.email.trim().toLowerCase() : ''
372
+ if (!email) return {} // a token with no email claim gets no hint from the front either
373
+ const key = String(c.iss || '') + '|' + email, now = Date.now()
374
+ if (fresh && !(extrasCache.get(key) || {}).p) extrasCache.delete(key)
375
+ const hit = extrasCache.get(key)
376
+ if (hit && hit.v && now < hit.exp - 60_000) {
377
+ if (now > hit.at + EXTRAS_REFRESH_MS && !hit.p) { hit.p = fetchExtras(key, tok).finally(() => { const h = extrasCache.get(key); if (h) delete h.p }) }
378
+ return hit.v
379
+ }
380
+ if (hit && hit.p) return hit.p
381
+ const p = fetchExtras(key, tok)
382
+ extrasCache.set(key, { p })
383
+ return p
384
+ }
385
+ const tokenOfBody = (b) => (typeof b.idToken === 'string' ? b.idToken : (b.message && typeof b.message.idToken === 'string' ? b.message.idToken : ''))
386
+ const tokenFor = async (op) => {
387
+ if (!userToken || !(SPEND_OPS.has(op) || VOICE_OPS.has(op))) return ''
388
+ try { const t = typeof userToken === 'function' ? await userToken() : userToken; return typeof t === 'string' ? t : '' } catch { return '' }
389
+ }
390
+ const post = async (body, billingToken) => {
391
+ const tok = typeof billingToken === 'string' ? billingToken : body && !body.userToken ? await tokenFor(body.op) : '' // a token the caller passed (the SDK's user) is never replaced
392
+ // In a CONFIDENTIAL room the token rides SEALED to the attested enclave (turn.mjs opens it; docs/tenant-billing.md
393
+ // § 12.2) — the relay must neither read nor swap who pays. A seal that cannot be made sends no token at all.
394
+ let tokFields = {}
395
+ if (tok) {
396
+ if (body.room && enclaveFor(body.room)) { try { tokFields = (await sealField(body.room, body.op + ':ut', tok, 'userToken')) || {} } catch { tokFields = {} } }
397
+ else tokFields = { userToken: tok }
398
+ }
399
+ let b0 = tok ? { ...body, ...tokFields } : body // let: a renewed sign-in replaces its token (app_unnamed, below)
400
+ // ★ EVERY OP OF AN ATTESTED ROOM CARRIES A FRESH PROOF (step 2b; agent/spaceService.mjs
401
+ // ATTEST_READ_OPS): a room this client knows answers `attest_required` gets one on every request, and a refusal from a
402
+ // room it did not yet know is signed and retried once. Turns (their own attestation), `policy` and `attest-accept`
403
+ // are left alone; a body that already carries a proof (the read paths, withVerified) is too.
404
+ const attested = !!(b0 && b0.room && !ATTEST_OWN_OPS.has(b0.op) && !b0.readAttestation)
405
+ const send = async () => {
406
+ let b = attested ? { ...b0, ...(passFor(b0.room, b0.op, b0) || await readAttestFor(b0.room)) } : b0 // a plain read: the device pass while it lasts
407
+ if (roomPass && b && typeof roomPass.fieldsFor === 'function') { let pf = {}; try { pf = (await roomPass.fieldsFor(b, { ts: sealNow() })) || {} } catch { pf = {} } if (pf.pass && pf.psig) b = { ...b, pass: pf.pass, psig: pf.psig } } // signed afresh on every send, at the server's clock as learned here (sealNow; sync sweep 11-16 #8)
408
+ // …or a KEYLESS content-free request (PLAIN_OPS) for a Space a `confidential_room` refusal already named (tierKnown, below):
409
+ // it goes to the enclave too — this device does not mark the Space, and every such request went to the standard tier again
410
+ const body = (b && (b.enclave === true || enclaveFor(b.room) || learnedConfidential(b))) ? { enclave: true, ...b } : b
411
+ const enc = body && body.enclave === true && typeof body.room === 'string'
412
+ const idWay = enc && identityFor(body.room) && carriesIdentity(body)
413
+ // a verified room's read carries a token: sealed under option B when the live enclave opens envelopes (unknown → plain, as before)
414
+ const sealedWay = !enc ? false : !PLAIN_OPS.has(body.op) ? envelopeFor(body.room) : (idWay && IDENTITY_PLAIN_OPS.has(body.op) && envelopeFor(body.room) === true)
415
+ 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' } // 503, never 0: nothing was sent, so it is not "maybe posted" (sweep 11-06 #8)
416
+ // ONLY THE SIGN-IN made this read sealed (a content-blind read of a room that is not gated): while the room's enclave
417
+ // sleeps, the front serves such a read itself — readable, so the sealed request gets 502 answer_unsealed and an open
418
+ // confidential room showed nothing to a signed-in SDK (sweep 11-07 #4; the app sends no sign-in for an open room). The
419
+ // read needs no sign-in: it goes plain WITHOUT it for a short while — the sign-in never goes outside an envelope.
420
+ const idOnly = sealedWay === true && PLAIN_OPS.has(body.op) && !gatedRooms.has(body.room)
421
+ const plainNoId = () => { const { idToken: _t, spk: _s, pass: _p, psig: _q, ...rest } = body; return call(endpoint, rest, f) }
422
+ if (idOnly && (asleepPlain.get(body.room) || 0) > Date.now()) return plainNoId()
423
+ if (sealedWay === true) {
424
+ const pub = mkPubFor(body.room) // fail CLOSED: an enclave that opens envelopes but no attested key here → nothing is sent
425
+ if (!pub) throw new Error('enclave key unavailable for this room — refusing to send the request to the relay')
426
+ // ⛔ THE SIGN-IN NEVER GOES OUTSIDE AN ENVELOPE THAT TAKES IT (owner, state machines pass 7): when the hints could not be
427
+ // had (the front's idextras failed), the token still rides INSIDE, with no hints. A member the enclave admits only by
428
+ // a hint (an @username tag, a non-Google issuer) is then refused — the refused request ran nothing, so it is sent
429
+ // again ONCE after a fresh fetch of the hints, and the refusal stands if they still cannot be had.
430
+ let extras = idWay ? await extrasFor(tokenOfBody(body)) : null
431
+ const sealedSend = async (ex, bd = body) => { const { outer, answer } = await sealRequest(bd, pub, { identity: idWay, extras: ex || {} }); return openAnswer(await call(endpoint, outer, f), answer) }
432
+ let out = await sealedSend(extras)
433
+ // …only a refusal that NAMES itself ran nothing: a bare 5xx is the gateway's 30 s cut-off of a turn the Lambda is still
434
+ // running — sent again, the message was posted twice (sync sweep 2026-11-13, P2)
435
+ if (idWay && !extras && out && ((out.status === 403 && out.error === 'not_authorized') || (out.status === 503 && typeof out.error === 'string' && out.error))) {
436
+ extras = await extrasFor(tokenOfBody(body))
437
+ if (extras) out = await sealedSend(extras)
438
+ } else if (idWay && extras && out && out.status === 403 && /^pass: bound_unknown/.test(String(out.reason || ''))) {
439
+ // the enclave had no word on this address's room passes (sync sweep 2026-11-16 #6): hints kept from before the cutoff, or
440
+ // ended — fetched afresh past the cache and sent ONCE more (a refused request ran nothing); the refusal stands if none come
441
+ const ex = await extrasFor(tokenOfBody(body), { fresh: true })
442
+ if (ex && Array.isArray(ex.boundHints) && ex.boundHints.length) { extras = ex; out = await sealedSend(extras) }
443
+ }
444
+ // T#2: the enclave refused the envelope as stale and said its time — learn the offset and send it ONCE more, every seal
445
+ // made again at the enclave's clock. Only when the offset moved (a stale envelope at the right clock is something else).
446
+ if (out && out.error === 'envelope_stale' && noteServerClock(out.serverNow)) {
447
+ const again = await resealBody(body)
448
+ if (again) out = await sealedSend(extras, again)
449
+ }
450
+ if (idOnly && out && out.error === 'answer_unsealed') { asleepPlain.set(body.room, Date.now() + ASLEEP_PLAIN_MS); return plainNoId() }
451
+ return out
452
+ }
453
+ // ⛔ A ROOM KEY GOES READABLE ONLY TO A ROOM KNOWN TO BE STANDARD (state machines pass 7, T#1): a device with no tier mark
454
+ // for a confidential room (restored, a joiner's link without enc=1, a protected device before its unlock, a lane in the
455
+ // negative cache) sent the key in the clear on its first keyed read or write, and learned the tier only from the answer.
456
+ // …and NOT KNOWN is not standard either (sync sweep 2026-11-11 #1): the probe failing (a store fault answers 503 tier_unknown,
457
+ // or no network) left 'unknown', and the key went readable anyway. Now it waits: a retryable refusal, nothing sent.
458
+ if (!enc && body && typeof body.room === 'string') {
459
+ const keyFor = async (room) => { const t = await tierOf(room); return t === 'enclave' ? tierRefusal(body) : t === 'unknown' ? tierUnknown() : null }
460
+ if (typeof body.mk === 'string' && body.mk) { const no = await keyFor(body.room); if (no) return no }
461
+ if (typeof body.bridgeMk === 'string' && body.bridgeMk && typeof body.bridgeRoom === 'string' && body.bridgeRoom) { const no = await keyFor(body.bridgeRoom); if (no) return no }
462
+ }
463
+ return call(endpoint, body, f)
464
+ }
465
+ let r = await send()
466
+ // A KEYLESS REQUEST REFUSED AS CONFIDENTIAL (agent/tierGuard.mjs: `409 confidential_room` — the refused request ran nothing): this
467
+ // device does not mark the Space as confidential, so it went to the standard tier. Noted, and sent ONCE more — to the enclave,
468
+ // as every later one for that Space (the owner's devices, 2026-11-23: usage receipts for 43 confidential Spaces went to the
469
+ // standard tier every run — 6,808 refusals in a day, and those Spaces' usage was never collected).
470
+ if (r && r.error === 'confidential_room' && b0 && typeof b0.room === 'string' && !b0.enclave && !enclaveFor(b0.room) && PLAIN_OPS.has(b0.op) && keyless(b0)) {
471
+ noteTier(b0.room, r)
472
+ // the answer keeps saying the tier: a caller that learns from it (l1.js learnTier, through the key worker) still marks the Space
473
+ if (learnedConfidential(b0)) { r = await send(); if (r && typeof r === 'object' && !r.tier) r = { ...r, tier: 'enclave' } }
474
+ }
475
+ // A SIGN-IN THAT NAMES NO APP where a room pass is required (docs/device-gate-design.md § 12.1: a token from before `asc`, a raw
476
+ // Google one): renewed ONCE — the renewal names the app — and the request sent once more, never a loop and never a prompt.
477
+ // (401 too: op `grant` answered every refusal 401 until the sync sweep of 2026-11-16 #7, and a Lambda not yet redeployed still does)
478
+ const passRefused = (re) => !!(r && (r.status === 403 || r.status === 401) && re.test(String(r.reason || '')))
479
+ if (renewSignIn && passRefused(/^pass: app_unnamed/)) {
480
+ let fresh = null; try { fresh = await renewSignIn(b0) } catch { fresh = { retryable: true } }
481
+ const nb = withSignIn(b0, fresh)
482
+ if (nb) { b0 = nb; r = await send() }
483
+ else if (fresh?.retryable) r = { ...r, passRetryable: true }
484
+ }
485
+ // a pass that ended, or none where one is required now: a fresh one and ONE more try (a refused request ran nothing)
486
+ if (roomPass && typeof roomPass.renew === 'function' && passRefused(/^pass: (pass_expired|pass_required)/)) {
487
+ let renewal
488
+ try { renewal = await roomPass.renew(b0) } catch { renewal = { retryable: true } }
489
+ r = await send()
490
+ if (renewal?.retryable && passRefused(/^pass: pass_required/)) r = { ...r, passRetryable: true }
491
+ }
492
+ // THE CLOCK (sync sweep 2026-11-16 #8): psig's ts was more than 2 minutes from the server's, which said its time — learned (the same
493
+ // offset every seal uses, mkseal.js) and signed again ONCE. Only when the offset moved: a stale psig at the right clock is something else.
494
+ if (roomPass && passRefused(/^pass: psig_stale/) && noteServerClock(r.serverNow)) r = await send()
495
+ if (attested) notePass(b0.room, r)
496
+ if (attested && r && r.error === 'attest_required' && typeof r.challenge === 'string') { attestReadRooms.set(b0.room, r.challenge); if (r.reason) attestReadWhy.set(b0.room, String(r.reason)); r = await send() }
497
+ if (attested) { notePass(b0.room, r); noteReadChal(b0.room, r) }
498
+ return r
499
+ }
500
+ // THE TIER OF A ROOM THIS CLIENT HAS NOT MARKED (T#1 above): learned from any answer that says it (the front's tier hint, a
501
+ // `confidential_room` refusal, a plain 200 of a key-free read), else asked ONCE with the keyless `policy` op — which the
502
+ // front answers with `tier: 'enclave'` for a confidential room (agent/tierGuard.mjs) and which carries no key.
503
+ const tierKnown = new Map() // room → 'standard' | 'enclave' | { until } (could not tell; asked again after TIER_RETRY_MS)
504
+ const keyless = (x) => !(typeof x.mk === 'string' && x.mk) && !(typeof x.bridgeMk === 'string' && x.bridgeMk) && !x.userShare
505
+ // a content-free request for a Space a refusal named confidential goes to the enclave (send, above) — keyed ones never: they wait for
506
+ // the device's own mark (tierRefusal), as before
507
+ const learnedConfidential = (x) => !!x && typeof x.room === 'string' && PLAIN_OPS.has(x.op) && keyless(x) && tierKnown.get(x.room) === 'enclave'
508
+ const tierAsk = new Map() // room → the probe in flight
509
+ const TIER_RETRY_MS = 10_000 // could not tell: keyed requests wait (tierUnknown), so ask again soon
510
+ const noteTier = (room, r) => {
511
+ if (!room || !r || tierKnown.get(room) === 'enclave') return
512
+ // …and a Space the device's own list did not name is REPORTED (onConfidential; the page marks it — enclave.js markEnclaveRoom, durable
513
+ // and mirrored to the hosted app's vault): the learning lived only in this client's memory, so every launch went to the standard
514
+ // tier again (2026-11-23: one device's list lacked 43 confidential Spaces)
515
+ if (r.tier === 'enclave' || r.error === 'confidential_room') { tierKnown.set(room, 'enclave'); if (!enclaveFor(room) && typeof onConfidential === 'function') { try { onConfidential(room) } catch { /* the next refusal reports it again */ } } }
516
+ // the front's tier guard runs right before the room code and marks EVERY answer for a confidential room (agent/tierGuard.mjs
517
+ // withTier, any status) — so the room's own answer with no tier is the guard saying "standard": a 200, or the room's gate
518
+ // refusing the keyless probe (401/403, or need_identity in a 200 — a gated standard room). A fault (503 tier_unknown, other
519
+ // 5xx, 429, no network) is not an answer about the tier: asked again soon, and the key waits meanwhile.
520
+ else if (saysStandard(r)) tierKnown.set(room, 'standard')
521
+ else if (tierKnown.get(room) !== 'standard') tierKnown.set(room, { until: Date.now() + TIER_RETRY_MS })
522
+ }
523
+ const saysStandard = (r) => r.error !== 'tier_unknown' && (r.status === 200 || r.status === 401 || r.status === 403)
524
+ const saysTier = (r) => !!r && (r.tier === 'enclave' || r.error === 'confidential_room' || saysStandard(r))
525
+ const tierOf = async (room) => {
526
+ if (enclaveFor(room)) return 'enclave'
527
+ const k = tierKnown.get(room)
528
+ if (k === 'standard' || k === 'enclave') return k
529
+ if (k && k.until > Date.now()) return 'unknown'
530
+ if (!tierAsk.has(room)) {
531
+ tierAsk.set(room, (async () => {
532
+ // A FAULT IS ASKED AGAIN AT ONCE (e2e 2026-11-24: a fresh restore's burst met the route's shared limit, the probe got a 429, and
533
+ // the Space's first read was held back 10 s as tier_unknown): a 429, a 5xx or no network, a few times, jittered — the limit
534
+ // refills within a second. Only then "could not tell".
535
+ try {
536
+ let r = null
537
+ for (let i = 0; ; i++) {
538
+ try { r = await call(endpoint, { op: 'policy', room, ...(await authFor(room)) }, f) } catch { r = { status: 0 } }
539
+ if (saysTier(r) || i >= tierWaits.length || !tierFault(r)) break
540
+ await new Promise((res) => setTimeout(res, tierWaits[i] * (0.5 + Math.random())))
541
+ }
542
+ noteTier(room, r)
543
+ } finally { tierAsk.delete(room) }
544
+ })())
545
+ }
546
+ await tierAsk.get(room)
547
+ const v = tierKnown.get(room)
548
+ return v === 'standard' || v === 'enclave' ? v : 'unknown'
549
+ }
550
+ // Nothing was sent. A read answers like the front's tier hint (an unchanged 200 that says the tier — the page marks the room
551
+ // and re-reads it in the enclave); anything else like the front's own refusal, so every caller's existing path follows it.
552
+ const TIER_READS = new Set(['poll', 'pollsealed'])
553
+ const tierRefusal = (body) => TIER_READS.has(body.op)
554
+ ? { status: 200, ok: true, changed: false, tier: 'enclave', ...(body.sinceEtag ? { etag: body.sinceEtag } : {}) }
555
+ : { 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.' }
556
+ 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' })
557
+ const ATTEST_OWN_OPS = new Set(['turn', 'policy', 'attest-accept'])
558
+ const asleepPlain = new Map() // room → until when its sign-in-only sealed reads go plain without the sign-in (#4 above)
559
+ const ASLEEP_PLAIN_MS = 20_000
560
+ // The attested half of attestFor alone: a proof for a room known to need one, nothing for any other room.
561
+ const readAttestFor = async (room) => {
562
+ if (!attestReadRooms.has(room)) return {}
563
+ try { const p = readAttestProvider(); const why = takeReadWhy(room); const att = p ? await p(room, { read: true, challenge: attestReadRooms.get(room), ...(why ? { refused: why } : {}) }) : null; return att && att.read ? { readAttestation: att.read } : {} } catch { return {} }
564
+ }
565
+ // For an EMAIL-gated room the SERVER gates every op — reads too — so attach the caller's cached Google identity
566
+ // ({idToken, spk}) to read/other ops. `auth(room)` returns it (or null) without prompting; a non-gated room → {}.
567
+ // `turn` is exempt: its caller passes the full email identity in `message`. Fail-open to {} so open rooms are unaffected.
568
+ const authFor = async (room) => {
569
+ if (!auth) return {}
570
+ try { const a = await auth(room); return a && a.idToken && a.spk ? { idToken: a.idToken, spk: a.spk } : {} } catch { return {} }
571
+ }
572
+ // A request that opens ANOTHER room (a lane turn reading its shared room, a crossing into it, personal-agent links)
573
+ // must pass THAT room's gate too (agent/spaceService.mjs otherRoomAdmits, 2026-10-02). A private lane is usually not
574
+ // gated itself, so its own auth is {} — attach the member's sign-in for the first other room that has one. The
575
+ // sign-in is bound to the device key, not to a room, so one identity proves the member wherever their email is listed.
576
+ const otherAuth = async (rooms) => {
577
+ for (const r of rooms) { if (!r) continue; const a = await authFor(r); if (a.idToken) return a }
578
+ return {}
579
+ }
580
+
581
+ // KEY TRANSPORT. With a service public key configured (`mkPub`), every op that must carry the room key sends it
582
+ // SEALED and bound to this exact request (room|op|ts|nonce) instead of in the clear — so a body-logging capture
583
+ // yields ciphertext, and a captured body can't be replayed as another op or after the freshness window. Without
584
+ // `mkPub` this is the identity function and the raw key is sent, exactly as before: the server accepts both, so an
585
+ // old client and a new one work against the same deployment. See spaces/public/mkseal.js for the limits of the claim
586
+ // — this hides the key from LOGS, not from the service.
587
+ // TURN PROGRESS (docs/turn-progress.md): what the turn is doing right now — { phase:'thinking'|'writing' } or
588
+ // { tool } — sealed like the reply text and opened the same way. Only a well-formed step is passed on; anything else
589
+ // is dropped, never fatal, and never shown.
590
+ const withTurnStatus = async (out, r, mk) => {
591
+ if (typeof r.partialStatus !== 'string') return out
592
+ try {
593
+ const st = JSON.parse(await open(JSON.parse(r.partialStatus), { mk }))
594
+ const ok = st && typeof st === 'object' && ((st.phase === 'thinking' || st.phase === 'writing' || st.phase === 'deciding') || (typeof st.tool === 'string' && /^[a-z0-9_]{1,64}$/.test(st.tool)))
595
+ const since = Number.isFinite(st.since) ? { since: st.since } : {} // when the turn started (asyncTurn) — the seconds count from it
596
+ return ok ? { ...out, partialStatus: { ...(st.tool ? { tool: st.tool } : { phase: st.phase }), ...since }, partialSeq: r.partialSeq || out.partialSeq || 0 } : out
597
+ } catch { return out }
598
+ }
599
+ // ROOM STREAMS (docs/change-inbox.md § Room streams): a GATED room's poll that passed the gate brings the stream grants
600
+ // — sealed under the room key when the request carried it, plain on a keyless read. Only well-formed ones pass on
601
+ // (`streamGrants`); the page hands them to the stream client (roomStreamClient.js), which needs them AND the key.
602
+ const withStreamGrants = async (out, r, mk) => {
603
+ let g = Array.isArray(r.stream) ? r.stream : null
604
+ if (typeof r.streamSealed === 'object' && r.streamSealed && mk) { try { g = JSON.parse(await open(r.streamSealed, { mk })) } catch { g = null } }
605
+ const ok = Array.isArray(g) && g.length <= 4 && g.every((x) => x && Number.isInteger(x.e) && typeof x.g === 'string' && x.g.length <= 64)
606
+ return ok ? { ...out, streamGrants: g.map((x) => ({ e: x.e, g: x.g })) } : out
607
+ }
608
+ // A SEAL CAN BE MADE AGAIN (state machines pass 7, T#2): a request refused `envelope_stale` (this device's clock is off the
609
+ // enclave's) is sent once more with the learned offset — and every field sealed inside it carries its own ts, checked
610
+ // too, so each is sealed again. Kept by nonce for a couple of minutes; a body holding a seal not kept here is not retried.
611
+ const _reseal = new Map() // nonce → () => Promise<fields>
612
+ const resealable = (nonce, again) => { _reseal.set(nonce, again); const t = setTimeout(() => _reseal.delete(nonce), 120_000); if (t && t.unref) t.unref() }
613
+ const resealBody = async (body) => {
614
+ if (!body || body.newMkSealed !== undefined || body.idSealed !== undefined) return null // bound to the key seal's own ts/nonce: not rebuilt here
615
+ let out = { ...body }
616
+ for (const [k, v] of Object.entries(body)) {
617
+ if (!/Nonce$/.test(k) || typeof v !== 'string') continue
618
+ const again = _reseal.get(v); if (!again) return null
619
+ out = { ...out, ...(await again()) }
620
+ }
621
+ return out
622
+ }
623
+ const keyFields = async (room, op, mk) => {
624
+ const pub = mkPubFor(room)
625
+ if (enclaveFor(room) && !pub) throw new Error('enclave key unavailable for this room — refusing to send the room key to the relay')
626
+ if (!pub || !mk) return { mk }
627
+ try {
628
+ const ts = sealNow() // the enclave's clock as far as known (mkseal.js, T#2)
629
+ const nonce = newNonce()
630
+ resealable(nonce, () => keyFields(room, op, mk))
631
+ return { mkSealed: await sealMk(mk, pub, mkAad({ room, op, ts, nonce })), mkTs: ts, mkNonce: nonce }
632
+ } catch (e) { if (enclaveFor(room)) throw e; return { mk } } // enclave room MUST seal; a normal room may fall back to the plain path
633
+ }
634
+ // A private-lane turn carries the SHARED room's key (bridgeMk) so the agent can observe it, and a mirror carries the
635
+ // shared room's PLAINTEXT messages. For an enclave-tier lane both must be sealed to the enclave too — else the relay
636
+ // would see the shared room's key/content even though the lane itself is sealed. Same fail-closed rule as keyFields.
637
+ const sealField = async (room, aadOp, plaintext, base) => {
638
+ const pub = mkPubFor(room)
639
+ if (enclaveFor(room) && !pub) throw new Error('enclave key unavailable for this room — refusing to send bridged data to the relay')
640
+ if (!pub) return null // not an enclave room → caller sends the field raw, unchanged
641
+ const ts = sealNow(); const nonce = newNonce() // T#2: the enclave's clock as far as known
642
+ resealable(nonce, () => sealField(room, aadOp, plaintext, base))
643
+ // Field names MUST match what the enclave reads (infra/enclave/node/turn.mjs): `${base}Sealed`/`${base}Ts`/`${base}Nonce`.
644
+ return { [`${base}Sealed`]: await sealMk(plaintext, pub, mkAad({ room, op: aadOp, ts, nonce })), [`${base}Ts`]: ts, [`${base}Nonce`]: nonce }
645
+ }
646
+ const bridgeFields = async (room, op, bridgeMk) => (await sealField(room, op + ':bridge', bridgeMk, 'bridgeMk')) || { bridgeMk }
647
+ // The LINKED rooms' keys (a lane's setLinks) seal the same way, as one field (AAD op + ':links') — on a confidential room
648
+ // they never cross the relay in the clear (2026-10-02; they used to, while bridgeMk was sealed).
649
+ // A CONFIDENTIAL ROOM WHOSE ENCLAVE HOLDS NO CONFIG heals on first read (2026-10-03, the owner's trip room ran the
650
+ // default assistant and showed empty instructions): its create-time seal into the enclave never landed. The standard
651
+ // tier keeps a copy; fetch it WITHOUT the key (mk never goes to the standard tier for a confidential room), keep it
652
+ // only if it opens with mk, and give it to the enclave as the room's first config. A gated copy is not served keyless,
653
+ // so a gated room is not healed here. → { cfg, configSealed, saved } or null.
654
+ const healEnclaveConfig = async (room, mk) => {
655
+ if (!mk || !enclaveFor(room)) return null
656
+ let s = null
657
+ try { s = await call(endpoint, { op: 'policy', room }, f) } catch { return null }
658
+ if (!s || typeof s.configSealed !== 'string' || !s.configSealed) return null
659
+ let cfg = null
660
+ try { cfg = JSON.parse(await open(JSON.parse(s.configSealed), { mk })) } catch { cfg = null }
661
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) return null
662
+ let r = null
663
+ try { r = await post({ op: 'config', room, ...(await keyFields(room, 'config', mk)), configSealed: s.configSealed, ...(await authFor(room)) }) } catch { r = null }
664
+ return { cfg, configSealed: s.configSealed, saved: !!(r && r.status === 200) }
665
+ }
666
+ const policyPost = async (room, mk) => post({ op: 'policy', room, ...(mk ? await keyFields(room, 'policy', mk) : {}), ...(await authFor(room)) })
667
+ const linksFields = async (room, op, links) => (await sealField(room, op + ':links', JSON.stringify(links), 'links')) || { links }
668
+
669
+ // reconstruct mk from the pieces carried in a set of links (a share `#s=` each, or `#mk=` for solo)
670
+ const mkFromLinks = async (links, config, commit) => {
671
+ const pieces = (Array.isArray(links) ? links : [links]).map((l) => { const p = parseConfiguredLink(l); return p.share || p.mk }).filter(Boolean)
672
+ return assembleConfiguredKey(pieces, config, commit)
673
+ }
674
+
675
+ // Rooms the server READ-gates (email admission): carry the SEALED mk on the otherwise-keyless reads (pollsealed/blob)
676
+ // so the server can run the email gate. Learned from the config at create/open, plus a 401 gated_read_requires_key.
677
+ const gatedRooms = new Set()
678
+ // ⛔ RECOGNISE A REFUSAL BY ITS OWN CODE, NOT ONLY BY THE STATUS LINE (2026-09-29, a builder: an enclave-tier gated room
679
+ // read back EMPTY). On the confidential tier the enclave's host front forwarded only the response BODY and answered
680
+ // 200 for everything, so `gated_read_requires_key` arrived as a 200 and this client — which learned the gate only from a
681
+ // 401 — never retried with the key. The error code survives every hop; the status line did not.
682
+ const gatedRefusal = (r) => !!(r && r.reason === 'gated_read_requires_key' && (r.status === 401 || r.error === 'need_identity'))
683
+ // A SEALED READ (pollsealed, blob) — WITHOUT THE ROOM KEY whenever it can be (regular rooms read sealed; step 2, the owner,
684
+ // 2026-11-07: "Fix it"). A VERIFIED room's server checks the sign-in against its own sealed copy of the member list
685
+ // (agent/gateCopy.mjs), so the key need not ride. It rides ONCE, sealed, only when: the read must prove it (proveKey — the
686
+ // change inbox's registration); the server has no copy of the room's current list yet (gated_read_requires_key — that keyed
687
+ // read writes one); or the sign-in was refused (a member removed in place hears stale_key only from the key, and goes for
688
+ // its grant as before). A CONFIDENTIAL verified room keeps sending it, sealed to its attested enclave.
689
+ // `sent.keyed` (when given) is set when the key rode — pollSealed then knows a 422 was already asked WITH the key.
690
+ const sealedRead = async (room, mk, op, fields, { proveKey = false, sent = null } = {}) => {
691
+ // the enclave ASLEEP with no attested key here: the keyed retry cannot go (keyFields fails closed) — it threw, the poll swallowed
692
+ // it and no banner showed until a wake (sync sweep 11-08/11-09). Answer what it is instead: the enclave is starting, nothing sent.
693
+ const keyed = async () => { 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' }; if (sent) sent.keyed = true; const k = await post({ op, room, ...fields, ...(await keyFields(room, op, mk)), ...(await authFor(room)), ...(await attestFor(room)) }); if (k && k.status === 200) keyedOk.add(room); return k }
694
+ if (mk && (proveKey || (gatedRooms.has(room) && (enclaveFor(room) || keyFirstNow(room))))) return keyed()
695
+ const r = await post({ op, room, ...fields, ...(await authFor(room)), ...(await attestFor(room, op, fields)) })
696
+ notePass(room, r)
697
+ if (!enclaveFor(room)) noteTier(room, r) // a key-free read that says the tier (or answers a plain 200) spares the probe
698
+ if (!mk) return r
699
+ if (gatedRefusal(r)) {
700
+ // AN OWNER-GOVERNED verified room (sweep 11-07 #5): its server never reads the gate copy (its sealed owner policy opens only
701
+ // with the key — agent/spaceRoom.mjs), so every key-free read was refused and sent again. Refused key-free right after a
702
+ // keyed read WORKED (which writes an ordinary room's copy) = such a room: the key rides up front for a while, then one
703
+ // key-free read asks again (a changed room's copy is written by that keyed read).
704
+ if (gatedRooms.has(room) && keyedOk.has(room)) keyFirst.set(room, Date.now() + KEY_FIRST_MS)
705
+ gatedRooms.add(room); return keyed()
706
+ }
707
+ // refused for the sign-in: a member REMOVED in place hears stale_key only from the key (sweep 11-07 #1: also for a room this
708
+ // client never learned was gated — a key-free read is refused that way only by a verified room's gate)
709
+ if (r && (r.status === 403 || r.status === 200) && r.error === 'not_authorized') { gatedRooms.add(room); return keyed() }
710
+ return r
711
+ }
712
+ const keyedOk = new Set() // rooms whose keyed sealed read was served (their gate copy, if any, is written)
713
+ const keyFirst = new Map() // room → until when its reads carry the key up front (an owner-governed verified room)
714
+ const KEY_FIRST_MS = 10 * 60_000
715
+ const keyFirstNow = (room) => { const t = keyFirst.get(room); return t === Infinity || (typeof t === 'number' && Date.now() < t) }
716
+ const verifiedRefusal = (r) => !!(r && r.error === 'no_verified_client' && (r.status === 403 || r.status === 200))
717
+
718
+ // Rooms that require a VERIFIED CLIENT: attach a client-release attestation to the material reads. Learned at create
719
+ // (config.requireVerifiedClient) or LAZILY from a 403 no_verified_client — mirrors gatedRooms/gated_read_requires_key.
720
+ const verifiedRooms = new Set()
721
+ // ATTESTED READS: a room that answered `attest_required` is learned here with the
722
+ // challenge it sent; every later read of it carries a fresh proof over the newest challenge it handed back.
723
+ const attestReadRooms = new Map() // room → the newest challenge
724
+ // room → why its last attested read was refused, handed to the provider ONCE with the retry (the app sends Play Integrity's token
725
+ // at once on `integrity_required` — deviceAttest.js integrityDueFor; 2026-11-20)
726
+ const attestReadWhy = new Map()
727
+ const takeReadWhy = (room) => { const w = attestReadWhy.get(room); attestReadWhy.delete(room); return w }
728
+ // THE DEVICE PASS (agent/spaceChallenge.mjs issueAttPass; the owner, 2026-11-24: "They feel slow" — every read of an attested room
729
+ // carried a fresh hardware signature, many a second): a proven read is answered with `attPass`; the plain reads of that room carry
730
+ // it instead of a new signature while it is under PASS_USE_MS (the server takes it for 120 s — the margin covers a slow request).
731
+ // Anything that writes signs as before; a refused pass is dropped and the read signs again (the retry below).
732
+ const attPasses = new Map() // room → { pass, at }
733
+ const PASS_USE_MS = 100_000
734
+ const PASS_OPS = new Set(['poll', 'pollsealed', 'blob', 'pending'])
735
+ const passFor = (room, op, body) => {
736
+ const p = attPasses.get(room)
737
+ if (!p || !attestReadRooms.has(room) || Date.now() - p.at > PASS_USE_MS) return null
738
+ return PASS_OPS.has(op) || (op === 'state' && (!body || body.patch === undefined)) ? { readAttestation: { pass: p.pass } } : null
739
+ }
740
+ const notePass = (room, r) => {
741
+ if (!room || !r) return
742
+ if (typeof r.attPass === 'string' && r.attPass) attPasses.set(room, { pass: r.attPass, at: Date.now() })
743
+ else if (r.error === 'attest_required' && /^attestation: (pass |missing)/.test(String(r.reason || ''))) attPasses.delete(room)
744
+ }
745
+ const noteReadChal = (room, r) => { if (attestReadRooms.has(room) && r && typeof r.challenge === 'string' && r.challenge) attestReadRooms.set(room, r.challenge) }
746
+ const attestFor = async (room, op = '', body = null) => {
747
+ if (attestReadRooms.has(room)) {
748
+ const pass = op ? passFor(room, op, body) : null
749
+ if (pass) return pass
750
+ try { const p = readAttestProvider(); const why = takeReadWhy(room); const att = p ? await p(room, { read: true, challenge: attestReadRooms.get(room), ...(why ? { refused: why } : {}) }) : null; return att && att.read ? { readAttestation: att.read } : {} } catch { return {} }
751
+ }
752
+ if (!verifiedRooms.has(room)) return {}
753
+ try { const p = attestProvider(); const att = p ? await p(room) : null; return att ? { clientAttestation: att } : {} } catch { return {} }
754
+ }
755
+ // Run a material-read post; on a 403 no_verified_client for a room we didn't yet know was verified, learn it and retry
756
+ // once — the retry's attestFor now yields the attestation. `doPost` rebuilds the body each call (so the attestation is
757
+ // picked up on the retry). Fail-closed: with no provider the retry still 403s and the caller sees the withheld read.
758
+ const withVerified = async (room, doPost) => {
759
+ let r = await doPost()
760
+ notePass(room, r)
761
+ if (verifiedRefusal(r) && !verifiedRooms.has(room)) { verifiedRooms.add(room); r = await doPost(); notePass(room, r) }
762
+ if (r && r.error === 'attest_required' && typeof r.challenge === 'string') { attestReadRooms.set(room, r.challenge); if (r.reason) attestReadWhy.set(room, String(r.reason)); r = await doPost() } // an attested read: sign the challenge it sent, once
763
+ notePass(room, r); noteReadChal(room, r)
764
+ return r
765
+ }
766
+
767
+ // A ROOM RE-KEYED IN PLACE (docs/key-rotation-design.md § (b)): what was written before the rotation is sealed under an
768
+ // EARLIER key, which the room's config — sealed under the current key — carries (`keyChain`). A box the current key does
769
+ // not open is tried with those, newest first. The chain is read once per room and key, and only when a box needs it.
770
+ const chains = new Map() // room|commit-prefix of the key → the older keys
771
+ const chainFor = async (room, mk, requireKnown = false) => {
772
+ const k = room + '|' + await keyCommit(mk)
773
+ if (chains.has(k)) return chains.get(k)
774
+ let keys = [], known = false
775
+ try {
776
+ const r = await policyPost(room, mk)
777
+ const cfg = r && r.status === 200 && r.configSealed ? JSON.parse((await open(JSON.parse(r.configSealed), { mk })) || 'null') : null
778
+ if (cfg && typeof cfg === 'object') { known = true; 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() }
779
+ } catch { keys = [] }
780
+ // only a DEFINITIVE read is kept — a failed one (the enclave asleep, a network fault) cached "no older keys" for the session,
781
+ // and the history before an in-place change stayed unreadable until a reload (sweep 10-23 #19)
782
+ if (known) chains.set(k, keys)
783
+ return known || !requireKnown ? keys : null
784
+ }
785
+ const openAny = async (room, env, mk, aad = null) => {
786
+ const pt = await open(env, { mk, aad })
787
+ if (pt != null || !room || !mk) return pt
788
+ for (const k of await chainFor(room, mk)) { const o = await open(env, { mk: k, aad }); if (o != null) return o }
789
+ return null
790
+ }
791
+
792
+ // ONE DECODER for a sealed poll answer (the v3 per-entry wrapper, or a whole v1/v2 blob): pollSealed runs it on the
793
+ // network's answer, and the L1 worker runs it on an answer the service worker PREFETCHED when the push arrived
794
+ // (prefetchPoll.js) — so a room opened from a notification shows the new message without waiting for a round trip.
795
+ const decodeSealed = async (room, mk, sinceCount, r) => {
796
+ const withPartial = async (o) => {
797
+ let out = o || {}
798
+ // WITBITZ REMOVED these messages (agent/moderation.mjs; docs/report-and-block.md §5): ids and times, plaintext, on every answer
799
+ 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) })) }
800
+ // Both the in-progress reply (partial) AND a parked device-call ride EVERY response (from `r`); open them here so
801
+ // every return path carries them, whichever object it built.
802
+ if (typeof r.partial === 'string') { try { out = { ...out, partialText: await open(JSON.parse(r.partial), { mk }), partialSeq: r.partialSeq || 0 } } catch { /* unopenable partial dropped, never fatal */ } }
803
+ out = await withTurnStatus(out, r, mk)
804
+ out = await withStreamGrants(out, r, mk)
805
+ if (typeof r.deviceCall === 'string') { try { out = { ...out, deviceCall: JSON.parse(await open(JSON.parse(r.deviceCall), { mk })), deviceCallSeq: r.deviceCallSeq || 0 } } catch { /* unopenable device-call → ignore */ } }
806
+ return out
807
+ }
808
+ if (r.status !== 200 || !r.changed) return await withPartial(r) // 403 gate / 404 / unchanged → pass through untouched
809
+ // v3 per-entry ledger (agent/spaceLedgerV3.mjs): r.sealed is a PLAINTEXT wrapper { v:3, boxes:[sealed…] } the server
810
+ // ALREADY sliced to boxes[sinceCount:] — open each box individually; r.count is the new total (our next sinceCount).
811
+ // Distinguished by the `boxes` array (a whole-blob envelope has no `boxes`), so v1/v2 fall through to the path below.
812
+ let wrap = null
813
+ try { wrap = JSON.parse(r.sealed) } catch { wrap = null }
814
+ if (wrap && wrap.v === 3 && Array.isArray(wrap.boxes)) {
815
+ const entries = []
816
+ // M4: the server sliced to boxes[sinceCount:], so box j is at ABSOLUTE index base+j — the aad a bound box needs.
817
+ // wrap.from (sliceRawV3) is authoritative when present; else it's exactly sinceCount. A legacy box ignores the aad.
818
+ const base = Number.isInteger(wrap.from) ? wrap.from : sinceCount
819
+ let unopenable = 0
820
+ for (let j = 0; j < wrap.boxes.length; j++) {
821
+ // open() answers NULL for a wrong key (it never throws) — and JSON.parse(null) is null, so this used to push a null
822
+ // ENTRY per box and report "N entries": a blank room, a green badge, no banner (the owner's screenshot, 2026-10-03).
823
+ try { const pt = await openAny(room, JSON.parse(wrap.boxes[j]), mk, ledgerAad(room, base + j)); if (pt == null) { unopenable++; continue } entries.push(JSON.parse(pt)) } catch { unopenable++ /* skip an unopenable box, keep the rest */ }
824
+ }
825
+ // EVERY box refused = this is not an empty room, it is the WRONG KEY (the owner's screenshot, 2026-10-03: a confidential
826
+ // room with ten entries drawn as a blank page under a green ENCLAVE badge — the content-blind read swallowed each
827
+ // box and answered "nothing new"). Say so, the way the server's own path does: 422 lifts the couldn't-unlock banner.
828
+ 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 })
829
+ const total = Number.isInteger(r.count) ? r.count : sinceCount + entries.length
830
+ // `done` — entries that have been through a COMPLETED turn (agent/spaceLedgerV3.mjs). Plaintext on the
831
+ // wrapper, so it costs no key. A turn the agent answers with SILENCE appends nothing, so this
832
+ // advancing is the ONLY event it produces, and it is what lets a peer stop showing "thinking".
833
+ // `more`: another page follows from `version` (ledgerView.readAllPages; sync sweep, 2026-10-10)
834
+ return await withPartial({ status: 200, etag: r.etag, changed: true, version: total, entries, ...(r.more ? { more: true } : {}), challenge: r.challenge, done: r.done, partial: r.partial, partialSeq: r.partialSeq, boxes: wrap.boxes.length, ...(unopenable ? { refused: unopenable } : {}) })
835
+ }
836
+ let all = null
837
+ try { all = JSON.parse(await openAny(room, JSON.parse(r.sealed), mk)) } catch { all = null }
838
+ // LEDGER FORMAT (agent/sessionStore.mjs): v1 is a bare array — everything written to date. v2+ is
839
+ // { v, entries }. Accepting both HERE, before anything writes v2, is what makes that change possible
840
+ // later: this runs in the browser behind a service worker, so a client that cannot read v2 lingers in
841
+ // the field for days after the server flips. Reader-first, always.
842
+ if (all && !Array.isArray(all) && Array.isArray(all.entries)) all = all.entries
843
+ if (!Array.isArray(all)) return { status: 422, etag: r.etag, changed: true, reason: 'undecodable', challenge: r.challenge }
844
+ const from = Number.isInteger(sinceCount) && sinceCount > 0 ? Math.min(sinceCount, all.length) : 0
845
+ 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 })
846
+ }
847
+ const api = {
848
+ _openAny: openAny, // internal: a box opened with the room's key or, after an in-place change, an earlier one (tests)
849
+ /** Mint a Space from a config, register its PUBLIC record (commit + config) with the server, and return
850
+ * { room, mk, commit, links, keyModel }. `mk` is reconstructed locally from the minted pieces — it is NEVER sent
851
+ * to the server (only its commitment is). The `links` are what you hand to members. */
852
+ async create(config = {}, { base = originBase(), gk, enclave: enclaveOpt, split = false, via = null, lapseDays } = {}) {
853
+ const space = await createConfiguredSpace(config, { base })
854
+ const mk = await mkFromLinks(space.links, config, space.commit)
855
+ // Prepare the email allow-list for sealing. Co-members hold mk and can decrypt the config, so HIDDEN addresses are
856
+ // stored as OPAQUE room-bound memberHash values (salted by the room id, kibitz-compatible); the server gate hashes
857
+ // the verified email the same way. ADVERTISED addresses stay plaintext in `emails` (the gate already matches those)
858
+ // so co-members can see who's on the list. Domains stay plaintext (a domain isn't a person). `allow` doesn't feed
859
+ // mk/commit and the room id exists now (space.room), so transforming it here is safe.
860
+ if (config && config.admission === 'email' && config.allow) {
861
+ const a = config.allow
862
+ const dom = Array.isArray(a.domains) ? a.domains.filter(Boolean) : []
863
+ // @usernames (the owner, 2026-10-11: "The allow list should only be by email. The username is just for the other
864
+ // users … just a redirect"): an @username is resolved ONCE, at invite, to its account's HANDLE — a server-keyed hash
865
+ // of the email — and the list stores only a room-bound hash of it, like a hidden email. No username is stored, and
866
+ // nothing matches or moves by one. `handles` = such entries (a legacy room's advertised { handle } carried by a move).
867
+ const handles = (Array.isArray(a.handles) ? a.handles : []).filter((h) => typeof h === 'string' && h)
868
+ const hashOf = async (list) => { const mh = []; for (const em of (list || [])) { const h = await memberHash(em, space.room); if (h && !mh.includes(h)) mh.push(h) } return mh }
869
+ const shown = Array.isArray(a.hidden) ? (Array.isArray(a.emails) ? a.emails : []).filter(Boolean) : [] // show-aware: `emails` = ADVERTISED (plaintext), `hidden` = HIDDEN
870
+ const toHash = [...(Array.isArray(a.hidden) ? a.hidden : (Array.isArray(a.emails) ? a.emails : [])), ...handles] // no show info → every email hashed: private by default
871
+ const mh = await hashOf(toHash)
872
+ // ★ @USERNAMES AS TAGS (docs/spaces-usernames.md §12, 2026-10-20): `tagUsers` = the names the creator added; each is
873
+ // stored as the server's tag for THIS room — bound to the account like a handle hash, but no guessed email can be
874
+ // compared with it. A name that does not tag refuses the create: a person must never silently drop off the list.
875
+ for (const u of (Array.isArray(a.tagUsers) ? a.tagUsers : [])) {
876
+ const r = await post({ op: 'user', mode: 'tag', username: u, room: space.room })
877
+ if (!r || r.status !== 200 || typeof r.tag !== 'string' || !r.tag) throw Object.assign(new Error('@' + u + ' could not be added (' + ((r && (r.error || r.status)) || 'no answer') + ')'), { status: (r && r.status) || 0, code: 'user_tag' })
878
+ if (!mh.includes(r.tag)) mh.push(r.tag)
879
+ }
880
+ if (shown.length || mh.length || dom.length) config = { ...config, allow: { ...(shown.length ? { emails: shown } : {}), ...(mh.length ? { mh } : {}), ...(dom.length ? { domains: dom } : {}) } }
881
+ }
882
+ // AN ATTESTED ROOM (`requireApp: 'app'` — the Witbitz app on iPhone, Android or Mac): Witbitz's own owner key signs a policy
883
+ // requiring that app and a room-auth for THIS room id (op 'owner-policy') — sealed into the config, sent with the create.
884
+ // (Retired 2026-11-22, "We dont need any emulation rooms": the Witbitz-served level `served` / `emulated` and a builder's own
885
+ // signed rule, `ownerFor` — a web page vouching for itself.)
886
+ let ownerFields = {}
887
+ 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' })
888
+ if (config && (config.requireApp === 'android' || config.requireApp === 'app' || config.requireApp === 'windows')) { // app: the Witbitz app on iPhone, Android or Mac (2026-11-19; a 'windows' ask is refused by the server now) // windows: the Windows app's TPM key (docs/windows-attestation.md) // android: the native app (agent/witbitzOwnerPolicy.mjs) // emulated: the emulated attested room (docs/emulated-attested-rooms.md)
889
+ // CONFIDENTIAL + ATTESTED (docs/confidential-attested-rooms.md): the enclave verifies the app level itself (it checks the signed
890
+ // rule at create and the relayed device evidence on every read).
891
+ // windows in a CONFIDENTIAL room (the owner, 2026-11-09: "do confidential rooms"): the enclave trusts the Windows key by its OWN
892
+ // activation of it (agent/winActivation.mjs) — deviceAttest.js runs that once, before the first confidential proof
893
+ const g = await post({ op: 'owner-policy', room: space.room, level: config.requireApp })
894
+ 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 })
895
+ const { requireApp: _r, requireAppId: _ra, attestAccept: acc, ...rest } = config // attestAccept: the versions it takes — the record's, not the sealed config's
896
+ config = { ...rest, ownerPolicy: g.ownerPolicy }
897
+ ownerFields = { ownerPolicy: g.ownerPolicy, roomAuth: g.roomAuth, ...(acc ? { attestAccept: acc } : {}) }
898
+ }
899
+ // `gk` (the room invite PUBLIC key, JWK) is registered so per-member turns can be attribution-verified in-render.
900
+ // Public → storing it doesn't dent blindness. Omit → the Space stays capability-only (unsigned turns).
901
+ const configSealed = await sealConfig(config, mk)
902
+ // SPLIT (docs/sdk-split-key.md): mk = userShare ⊕ appShare. The RAW app half rides this create once; the server seals
903
+ // it under the page's tenant's K_eco (platform custody) and never stores it in the clear. userShare goes back to the
904
+ // caller for the room's #us= link and is never sent.
905
+ const sp = split ? splitKey(mk) : null
906
+ // `via` (2026-10-02): a BUILDER-HOSTED app-half function. The create goes to the builder's own function, which seals
907
+ // the half under ITS K_eco and registers the room through the tenant door with its tenant key — the same path our
908
+ // vault's /api/appshare takes. Witbitz then stores a half it cannot open. Absent ⇒ this endpoint, as before.
909
+ const send = typeof via === 'function' ? via : post
910
+ const dc = typeof delCommit === 'function' ? await delCommit(space.room).catch(() => null) : null // only the creating account can later delete this room (docs/user-erasure.md)
911
+ 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 } : {}) /* a temporary room kept days after its last question (docs/visitor-limits.md) — beside the sealed config, never in it */, ...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 } : {}) }) // installHelp: the front marks the room's record — its turns get the front's ticket (docs/install-help.md)
912
+ 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 } : {}) }) // the server's code on the error (config_too_large, tenant_required, …) — sync sweep, 2026-10-10
913
+ if (config.admission === 'email') { gatedRooms.add(space.room); if (config.ownerPolicy) keyFirst.set(space.room, Infinity) } // owner-governed: its reads carry the key (sweep 11-07 #5)
914
+ if (config.requireVerifiedClient) verifiedRooms.add(space.room)
915
+ // ⚑ configSealed rides back so an ENCLAVE-tier caller can hand the SAME sealed config to the enclave's own store
916
+ // before the first turn (the enclave keeps only the mk-commitment otherwise, and the turn falls back to a default
917
+ // agent). The app does this inline; the SDK needs it too, and re-sealing outside would be a second source of truth.
918
+ // `enclaveCreated`: the CONFIDENTIAL create was answered `created: true` — by the enclave, whose create keeps configSealed in
919
+ // the room's record (agent/spaceRoom.mjs). The SDK then skips handing it over a second time (witbitz-sdk _encSealConfig).
920
+ 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 } : {}) }
921
+ },
922
+ /** The app half of a SPLIT room, for a page on an origin the room's tenant declared (op:'appshare-page'). → { status, appShare, commit } */
923
+ appSharePage: async (room) => post({ op: 'appshare-page', room }),
924
+
925
+ /** Open a Space from the member link(s) this client actually holds → { room, mk }. `mk` is null below the key
926
+ * threshold (e.g. one partner's link alone in a 2-of-2 Space — the other share must be combined first). */
927
+ async open(links, config = {}, commit) {
928
+ const arr = Array.isArray(links) ? links : [links]
929
+ const room = parseConfiguredLink(arr[0] || '').room
930
+ if (config && config.admission === 'email' && room) gatedRooms.add(room)
931
+ return { room, mk: await mkFromLinks(arr, config, commit) }
932
+ },
933
+
934
+ // ── 2-of-2 (couple), async code-sealed handshake ──────────────────────────────────────────────────────────────
935
+ /** Create a 2-of-2 Space. Returns { room, mk, partnerLink, code, commit }. The creator holds `mk`; hand the partner
936
+ * `partnerLink` (their share) + `code` (out of band). shareA is SEALED under the code and registered as the room's
937
+ * invite — the server only ever stores ciphertext. */
938
+ async createCouple(config = {}, { base = originBase(), gk } = {}) {
939
+ const cfg = { ...config, keyModel: '2-of-2' }
940
+ const space = await createConfiguredSpace(cfg, { base })
941
+ const shareA = parseConfiguredLink(space.links[0]).share
942
+ const partnerLink = space.links[1]
943
+ const code = newCode()
944
+ const invite = await sealUnderCode(shareA, code)
945
+ const mk = await assembleConfiguredKey([shareA, parseConfiguredLink(partnerLink).share], cfg, space.commit)
946
+ const r = await post({ op: 'create', ...(app ? { app } : {}), ...tenantHint, room: space.room, commit: space.commit, invite, configSealed: await sealConfig(config, mk), ...(gk ? { gk } : {}) })
947
+ 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 } : {}) }) // the server's code on the error (config_too_large, tenant_required, …) — sync sweep, 2026-10-10
948
+ return { room: space.room, mk, partnerLink, code, commit: space.commit }
949
+ },
950
+
951
+ /** Join a 2-of-2 Space from a partner's share-link + the code → { room, mk }. Fetches the sealed shareA, unseals it
952
+ * with the code, and combines with this link's share. `mk` is null on a wrong code or a commitment mismatch. */
953
+ async joinWithCode(link, code) {
954
+ const p = parseConfiguredLink(link)
955
+ if (!p.room || !p.share) return { room: p.room || '', mk: null, error: 'bad_link' }
956
+ const r = await post({ op: 'invite', room: p.room })
957
+ if (r.status !== 200 || !r.invite) return { room: p.room, mk: null, error: 'no_invite' }
958
+ const shareA = await openUnderCode(r.invite, code)
959
+ if (!shareA) return { room: p.room, mk: null, error: 'bad_code' }
960
+ const mk = await assembleConfiguredKey([shareA, p.share], { keyModel: '2-of-2' }, r.mkCommit)
961
+ return { room: p.room, mk, error: mk ? undefined : 'mismatch' }
962
+ },
963
+
964
+ /** Post a turn. `identity` SIGNS it (the entry is signed over its core; the server verifies in-render). Two shapes:
965
+ * • EMAIL gate: `{ email, sign:{priv,pub}, googleIdToken }` → sends `{ from:email, ts, id, kind, sig, spk, idToken }`.
966
+ * The Google token proves the email (bound to `spk` via its nonce); the server checks it against the sealed
967
+ * allow-list and DISCARDS it.
968
+ * • INVITE gate: `{ name, sign:{priv}, grant }` → sends `{ from:name, ts, id, kind, sig, grant }` (Kibitz invite).
969
+ * • ATTESTED-ROOM KEY: `{ name, sign:{priv,pub}, attestKey:true }` → sends `{ from:name, ts, id, kind, sig, spk }` — a
970
+ * member who joined an attested room through its box holds no grant; the server checks the signature against `spk`.
971
+ * Omit `identity` → an unsigned turn (open/legacy rooms), unchanged.
972
+ * `bridgeMk` (private-lane turns only, docs/spaces-private-lane.md): the SHARED room's key, so the runtime can
973
+ * fold the shared negotiation into the agent's context (it OBSERVES the shared room). Ignored by normal rooms. */
974
+ // 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
975
+ // reads (otherAuth) — the server checks the shared room with the message's (spaceService otherRoomAdmits: req.idToken ||
976
+ // 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
977
+ // turn was checked with the message's, and every first message in a private assistant of a verified group was refused
978
+ // `pass: psig_signature` ("Your sign-in expired").
979
+ async turn(room, mk, message, identity, { bridgeMk, bridgeRoom, viewSource, mode, links, context, instructions, clientTools, clientGuidance, call, stopKey, model, receipt, showPrompt, run, schema } = {}, billingToken) {
980
+ let m = message
981
+ const text = String((message && message.text) || '')
982
+ if (identity && identity.googleIdToken && identity.sign && identity.sign.priv && identity.sign.pub) {
983
+ const ts = Date.now()
984
+ const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`
985
+ const { sig } = await signEntry(identity.sign.priv, { room, author: identity.email, ts, kind: 'text', id, text, ...(message && message.chal ? { chal: message.chal } : {}) }) // chal: the room's fresh challenge rides in the signed core when the turn carries one (deviceAttest.js; the server folds it the same way)
986
+ m = { ...message, from: identity.email, ts, id, kind: 'text', sig, spk: identity.sign.pub, idToken: identity.googleIdToken }
987
+ } else if (identity && identity.grant && identity.sign && identity.sign.priv) {
988
+ const ts = Date.now()
989
+ const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}` // client nonce → the signed core's id (anti-replay)
990
+ const { sig } = await signEntry(identity.sign.priv, { room, author: identity.name, ts, kind: 'text', id, text, ...(message && message.chal ? { chal: message.chal } : {}) })
991
+ m = { ...message, from: identity.name, ts, id, kind: 'text', sig, grant: identity.grant }
992
+ } else if (identity && identity.attestKey === true && identity.sign && identity.sign.priv && identity.sign.pub) {
993
+ const ts = Date.now()
994
+ const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`
995
+ const { sig } = await signEntry(identity.sign.priv, { room, author: identity.name, ts, kind: 'text', id, text, ...(message && message.chal ? { chal: message.chal } : {}) })
996
+ m = { ...message, from: identity.name, ts, id, kind: 'text', sig, spk: identity.sign.pub }
997
+ }
998
+ 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 } : {}), ...(call ? { call: 1 } : {}), ...(stopKey ? { stopKey } : {}), ...(model ? { model } : {}), ...(receipt && receipt.drop ? { receipt } : {}), ...(showPrompt === true ? { showPrompt: true } : {}), ...(run === true ? { run: true } : {}), ...(run === true && schema ? { schema } : {}) }, billingToken) // model: the composer's per-room pick ({catalog, wire}), taken over the create-time model server-side // clientTools/clientGuidance: the device's on-device tools for this turn (calendar, …); call:1 flags a "started a call" turn so the room tickle opens the meeting link; stopKey: the prompter's per-turn cancel nonce (op:'stop' matches it — docs/spaces-stop-turn.md)
999
+ },
1000
+ // USAGE RECEIPTS (docs/usage-receipts.md): this account's sealed receipts in a room, at its per-room drop, and the trim
1001
+ // once they are folded into the account's sidecar. Keyless: the drop is the capability; every box is sealed to us.
1002
+ receipts: async (room, drop, since = 0) => post({ op: 'receipts', room, drop, sinceCount: since }),
1003
+ receiptsAck: async (room, drop, upTo) => post({ op: 'receiptsack', room, drop, upTo }),
1004
+ // STRAY NOTIFICATIONS (strayPush.js, agent/pushDrop.mjs): this device has no key for the room; ask for its own push
1005
+ // address to come off the room's list. Keyless — the address is the capability, and only its hash is kept.
1006
+ pushDrop: async (room, subscription) => post({ op: 'pushdrop', room, subscription: { endpoint: subscription && subscription.endpoint } }),
1007
+ // MEMBERSHIP MARK (docs/user-erasure.md § Authority): this account opened the room — a creator's delete then sees it was shared
1008
+ mark: async (room, mk, drop) => post({ op: 'mark', room, ...(await keyFields(room, 'mark', mk)), drop, ...(await authFor(room)) }),
1009
+ /** 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. */
1010
+ 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)) }),
1011
+ // Seed the Space from a PUBLIC ChatGPT share link → continue a one-on-one chat together. The Lambda fetches +
1012
+ // parses it (SSRF-guarded) and seals the history into the ledger; the URL is public so this carries no secret.
1013
+ importChat: async (room, mk, chatgptUrl, billingToken) => post({ op: 'import', room, ...(await keyFields(room, 'import', mk)), chatgptUrl, ...(await authFor(room)) }, billingToken),
1014
+ importWhatsApp: async (room, mk, whatsappText, billingToken) => post({ op: 'import', room, ...(await keyFields(room, 'import', mk)), whatsappText, ...(await authFor(room)) }, billingToken), // WhatsApp export: client unzipped the _chat.txt → server parses + seals
1015
+ // MIRROR — append entries this device copied from a LINKED room (docs/spaces-private-lane.md) into THIS room's ledger,
1016
+ // no agent turn. Deduped by entry id server-side. Files/images ride along so the assistant reads them natively.
1017
+ mirror: async (room, mk, entries) => {
1018
+ const send = async batch => {
1019
+ const kf = await keyFields(room, 'mirror', mk)
1020
+ const ef = enclaveFor(room) ? await sealField(room, 'mirror:entries', JSON.stringify(batch), 'mirror') : { entries: batch }
1021
+ return post({ op: 'mirror', room, ...kf, ...ef, ...(await authFor(room)) })
1022
+ }
1023
+ const batch = entries || []
1024
+ const prepared = await stageMirrorAttachments(batch, send)
1025
+ return prepared.error || send(prepared.entries)
1026
+ },
1027
+ // CARRY — a verified room's MOVE: the SERVER copies the old room's history into this one (minted with forkedFrom = that
1028
+ // room), keeping each entry's verified mark as `carried` (agent/spaceService.mjs op 'carry'). One page per call → { carried,
1029
+ // next, total }; loop while `next` is a number. The old room's key rides like a lane's bridge key: sealed to the
1030
+ // enclave on a confidential room (AAD op 'carry:bridge'), and filled in by the room worker when only bridgeRoom is given.
1031
+ 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)) }),
1032
+ // Generate (or fetch) a real one-line conversation title, sealed to the room so both members share it.
1033
+ // `set` = { title, by }: a member RENAMES the room — the server appends it to the room's log (spaces/public/roomName.js).
1034
+ 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),
1035
+ // The DEFAULT loop. Opens the in-progress reply the same way pollSealed does — the server passes it through
1036
+ // sealed on both paths, so the two stay drop-in interchangeable mid-session.
1037
+ decodeSealed,
1038
+ poll: async (room, mk, sinceEtag, sinceCount = 0, opts = {}) => {
1039
+ // opts.changeInbox — THE CHANGE INBOX (docs/change-inbox.md): this device's inbox id rides the room's first poll of a
1040
+ // session, and the server follows the room for it only if this poll succeeds and proves the key. Plain, outside
1041
+ // the sealed fields — a confidential room's relaying Lambda needs it, and it names no content.
1042
+ const ci = opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {}
1043
+ // ⛔ A CONFIDENTIAL ROOM IS NEVER READ IN PLAINTEXT (docs/confidential-path-sweep-2026-11-05.md, finding B): the server
1044
+ // answers `poll` with the whole DECRYPTED history, and that answer crosses the Lambda and the enclave's parent host in
1045
+ // the clear. Read it sealed and open it here. Every caller (the room loop, the unread sweep, lanes, mail, pins…) comes
1046
+ // through this one function, so none can send the readable read by accident. Same answer shape (pollSealed's contract).
1047
+ if (enclaveFor(room)) return api.pollSealed(room, mk, sinceEtag, sinceCount, ci)
1048
+ // …AND A REGULAR ROOM IS READ SEALED TOO (the owner, 2026-11-06: "Do then regular rooms read sealed too"): `poll` sent the
1049
+ // room key about every 600 ms and the Lambda decrypted the whole history to answer it. The sealed read is opened here; the
1050
+ // key rides only the read that registers this device's CHANGE INBOX (the first of a session — inboxForPoll), because the
1051
+ // server follows the room for it only once that read proves the key (spaceHandler pollProvedKey). A verified room's sealed
1052
+ // read carries no key either: its server checks the sign-in against its sealed copy of the list (sealedRead). Older apps keep `poll`.
1053
+ // (a room re-keyed in place: pollSealed asks once more WITH the key when the boxes do not open — see there)
1054
+ return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, proveKey: !!ci.changeInbox })
1055
+ },
1056
+
1057
+ /** CONTENT-BLIND poll — the same contract as `poll`, but `mk` NEVER leaves this device. The server returns the
1058
+ * sealed ledger and we open it here, so the hot loop (a poll every ~600ms while the Space is on screen) stops
1059
+ * carrying the room key; only `turn` still does, because the agent genuinely needs plaintext.
1060
+ * Returns the IDENTICAL shape to `poll` — { status, etag, changed, version, entries } — so it is a drop-in swap
1061
+ * and the caller's render path is unchanged. A key that doesn't fit surfaces as the same 422/'undecodable' the
1062
+ * server used to return, except now the CLIENT proves it rather than being told. */
1063
+ async pollSealed(room, mk, sinceEtag, sinceCount = 0, opts = {}) {
1064
+ const ci = opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {} // ONLY the inbox id: a plain op carries nothing a caller hands it by mistake (confidentialWire.test.mjs) // ci: { changeInbox } when poll() reads a confidential room sealed — the drawer's follow rides it (agent/changeFeed.mjs pollSubscribeIntent takes both ops)
1065
+ // the key rides only as sealedRead says (proveKey: a regular room's read that registers the change inbox)
1066
+ const sent = { keyed: false }
1067
+ const send = async () => sealedRead(room, mk, 'pollsealed', { sinceEtag, sinceCount, ...ci }, { proveKey: !!(opts && opts.proveKey && mk && !enclaveFor(room)), sent })
1068
+ const r = await withVerified(room, send) // + attach a client-release attestation for a verified room (learned lazily)
1069
+ // The IN-PROGRESS reply, opened here like everything else — the server passed it through sealed. It rides EVERY
1070
+ // response including the unchanged one, which is the whole point: while a reply is still being written the
1071
+ // ledger has not moved, so this is the only thing arriving.
1072
+ const out = await decodeSealed(room, mk, sinceCount, r)
1073
+ // A ROOM RE-KEYED IN PLACE (rekeyMembers): a device on the old key used to learn it from its next read — the key rode it
1074
+ // and the server answered stale_key, which sends the device for its grant. A key-free read cannot be told stale, so the
1075
+ // new boxes simply do not open (422 undecodable). Ask that once more WITH the key (sealed to the enclave in a
1076
+ // confidential room): the server says stale_key and the device follows the change as before. The key leaves only in
1077
+ // this case (linkMembers.test.mjs caught it). HERE, not in poll(): the SDK and a vault read with pollSealed, and an
1078
+ // open confidential room's poll() came straight here — neither ever asked (sweep 11-07 #1, #2).
1079
+ if (out && out.status === 422 && out.reason === 'undecodable' && mk && !sent.keyed) {
1080
+ const r2 = await withVerified(room, async () => sealedRead(room, mk, 'pollsealed', { sinceEtag, sinceCount, ...ci }, { proveKey: true })) // ci kept: this keyed read is the one that can register the inbox (state machines pass 7, T#3)
1081
+ return decodeSealed(room, mk, sinceCount, r2)
1082
+ }
1083
+ return out
1084
+ },
1085
+ // Full SEALED ledger (ciphertext) for a durable LOCAL backup — the raw stored blob (v1/v2 whole, or the v3
1086
+ // { v:3, boxes:[…] } wrapper), NOT opened here. sinceCount:0 ⇒ everything. Same gated-retry as pollSealed. The
1087
+ // downloaded file carries no plaintext — it is only readable with the room key, via the offline decryptor
1088
+ // (/decrypt.html). Returns { status, sealed, count, etag }.
1089
+ exportSealed: async (room, mk) => {
1090
+ const archive = await readSealedArchive(sinceCount => withVerified(room, () => sealedRead(room, mk, 'pollsealed', { sinceCount })))
1091
+ if (archive?.status !== 200 || !archive.sealed) return archive
1092
+ const ledger = JSON.parse(archive.sealed)
1093
+ if (ledger.v === 3 && Array.isArray(ledger.boxes)) {
1094
+ const previous = await chainFor(room, mk, true)
1095
+ if (!previous) {
1096
+ // A legacy room can have no sealed configuration. Confirm its held key opens the archive
1097
+ // before offering a download when the authorized key history could not be read.
1098
+ for (const [index, item] of ledger.boxes.entries()) {
1099
+ let box; try { box = typeof item === 'string' ? JSON.parse(item) : item } catch {}
1100
+ if (await open(box, { mk, aad: ledgerAad(room, (ledger.from || 0) + index) }) == null) return { status: 409, error: 'archive_incomplete' }
1101
+ }
1102
+ }
1103
+ if (previous?.length) ledger.keyHistory = await seal(JSON.stringify({ room, keys: previous }), { room: mk })
1104
+ }
1105
+ return { ...archive, sealed: JSON.stringify(ledger) }
1106
+ },
1107
+ pending: async (room, mk) => post({ op: 'pending', room, ...(await keyFields(room, 'pending', mk)), ...(await authFor(room)) }),
1108
+ /** APPROVAL REMINDERS for Code (agent/approvalRemind.mjs): this device's push address, signed by the server, for the
1109
+ * computer to name when an approval waits there → { status, grant }. `endpointUrl` = where the computer sends it. */
1110
+ /** 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. */
1111
+ prefetchIdentity: async (idToken) => { try { if (typeof idToken === 'string' && idToken) await extrasFor(idToken) } catch { /* the next sealed request fetches them */ } },
1112
+ remindGrant: async (subscription, others) => post({ op: 'remindgrant', subscription, ...(Array.isArray(others) && others.length ? { subscriptions: others.slice(0, 16) } : {}) }), // others: the account's other devices (approvalRemind.makeGrant)
1113
+ endpointUrl: () => { try { return new URL(endpoint, typeof location !== 'undefined' ? location.href : undefined).href } catch { return '' } },
1114
+ /** Fetch an OUT-OF-LINE image blob by its ledger pointer and open it here → { status, b64, mime }.
1115
+ * The request carries no key (the bytes are sealed; serving ciphertext reveals nothing) — `mk` is used locally to
1116
+ * open the envelope, exactly like pollSealed. Blobs are content-addressed and immutable, so a caller may cache the
1117
+ * result against `ref` forever without revalidating. */
1118
+ /** A connection's TOOL BOOK (agent/toolBook.mjs): its full tool list sealed once into the room → { status, ref, sha256, n }. */
1119
+ // 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)
1120
+ /** THE ROOM'S TOOLS for its ⋯ → Tools sheet (agent/spaceService.mjs op toolrules; toolRules.js) → { status, tools: [{ name, about,
1121
+ * default, now, rule? }], rules }. The rules themselves are written with state(…, 'toolrules', …). */
1122
+ toolRules: async (room, mk, { bridgeRoom, bridgeMk } = {}) => post({
1123
+ op: 'toolrules', room, ...(await keyFields(room, 'toolrules', mk)),
1124
+ ...(bridgeRoom ? { bridgeRoom, ...(bridgeMk ? await bridgeFields(room, 'toolrules', bridgeMk) : {}) } : {}),
1125
+ ...(await otherAuth([bridgeRoom])), ...(await authFor(room)),
1126
+ }),
1127
+ 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)) }),
1128
+ async blob(room, mk, ref) { // arg order (room, mk, …) matches the l1 façade convention so blob can route through the worker (A2c)
1129
+ const r = await withVerified(room, async () => sealedRead(room, mk, 'blob', { ref }))
1130
+ if (r.status !== 200 || !r.sealed) return r
1131
+ try {
1132
+ const o = JSON.parse(await openAny(room, r.sealed, mk)) // a photo sent before a rotation: an earlier key (openAny)
1133
+ if (!o || typeof o.b64 !== 'string') return { status: 422, reason: 'undecodable' }
1134
+ return { status: 200, ref, b64: o.b64, mime: o.mime || 'image/jpeg' }
1135
+ } catch { return { status: 422, reason: 'undecodable' } }
1136
+ },
1137
+
1138
+ /** Register this device for push. The subscription is sealed into the room's doc server-side (it is room metadata:
1139
+ * which devices care about this room), so it needs mk like any other sealed write. */
1140
+ // mk goes through keyFields() like every other material op (turn/import/mirror/title/poll) — so on an ENCLAVE room it
1141
+ // is SEALED to the enclave key and the parent relay never sees the raw key (fail-closed for an enclave room with no
1142
+ // key). Default tier: keyFields is the identity function → raw {mk}, unchanged. (Was: raw mk in the body — the one
1143
+ // material op that skipped the seal, leaking the room key to the parent relay on enclave rooms. Security review #2.)
1144
+ 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)) }), // quiet: a bulk or automatic registration — store it, no confirmation push
1145
+
1146
+ /** Turn notifications off for this device. Sends the subscription so the server can drop it by endpoint. */
1147
+ unsubscribe: async (room, mk, subscription) => post({ op: 'unsubscribe', room, ...(await keyFields(room, 'unsubscribe', mk)), subscription, ...(await authFor(room)) }),
1148
+
1149
+ // Content-blind transparency read (the "trust receipt"): the EXACT ciphertext the server stores for this room +
1150
+ // its recipients. No mk sent — reading ciphertext reveals nothing. → { alg, bytes, sha256, recipients, sealed }.
1151
+ sealed: async (room) => post({ op: 'sealed', room }),
1152
+
1153
+ // VERIFIED-CLIENT capability blob (spaces/public/capLink.js). vcput MINTS: store the OPAQUE {mk}-sealed-under-token
1154
+ // ciphertext under a one-way capId — mk-commit gated server-side (only an mk-holder may write it), content-blind
1155
+ // (the server sees only id + ciphertext, never the token or mk). vcget RESOLVES: fetch it, ATTESTATION-gated (the
1156
+ // gateway withholds without a fresh, approved client-release attestation); carries NO mk — the token off the ?vc=
1157
+ // link (never sent to the server with the extension) is what opens the blob, unsealed by L1 locally.
1158
+ vcput: async (room, mk, capId, capSealed) => post({ op: 'vcput', room, capId, capSealed, ...(await keyFields(room, 'vcput', mk)), ...(await authFor(room)) }), // email-gated like every keyed write
1159
+ vcget: async (room, capId, attestation) => post({ op: 'vcget', room, capId, ...(attestation ? { clientAttestation: attestation } : {}) }),
1160
+ // The attested client's DEVICE enrollment (docs/the-attested-client.md § The wire; deviceAttest.js): a new hardware key's
1161
+ // platform attestation, bound to THIS room's fresh challenge and the member's signing key. Account-level — no mk.
1162
+ attestEnroll: async ({ room, chal, spk, enroll }) => post({ op: 'attest-enroll', room, chal, ...(spk ? { spk } : {}), enroll }),
1163
+ // A WINDOWS DEVICE'S ACTIVATION BY AN ENCLAVE (agent/winActivation.mjs): `to` 'turn' (confidential rooms) | 'sentinel' (the backup's
1164
+ // K_att); `start` → { activate, ticket }, `finish` (the TPM's answer + the ticket) → { ok }. The front keeps the sealed record.
1165
+ winAct: async ({ to, step, keyId, activation, ticket }) => post({ op: 'winact', winact: { to, step, keyId, ...(activation ? { activation } : {}), ...(ticket ? { ticket } : {}) } }),
1166
+ // "Verify this device" (agent/deviceVerify.mjs, docs/device-verify.md): the hardware key's signature over a CHECKER's nonce.
1167
+ // The answer is only the key code — the verdict is collected and checked by the checker, never shown here.
1168
+ // Witbitz Mail's receive prototype (agent/mailIntake.mjs): a mail address that drops into this Space's intake.
1169
+ mailRoute: async (intake, space) => post({ op: 'mail-route', mail: { intake, space } }),
1170
+ mailRevoke: async (intake, space) => post({ op: 'mail-revoke', mail: { intake, space } }), // stop receiving: the enclave ends the address (agent/mailIntake.mjs revokeOp)
1171
+ deviceVerify: async ({ platform, keyId, nonce, assertion, sig, integrity }) => post({ op: 'device-verify', device: { platform, keyId, nonce, ...(assertion ? { assertion } : {}), ...(sig ? { sig } : {}), ...(integrity ? { integrity } : {}) } }),
1172
+ // the ATTESTED BACKUP (agent/attestedBackup.mjs): op 'attested-chal' | 'attested-get' | 'attested-put', the fields in `attested`
1173
+ attestedOp: async (op, attested, chal) => post({ op, attested, ...(chal ? { chal } : {}) }),
1174
+ // K_att (infra/cloud-computer/sentinel/attkey.mjs): `mode` chal | get — the standing Sentinel's challenge, then the secret sealed to
1175
+ // the device's one-time key (attested.epk), after the attestation it verifies itself. The Space Lambda only relays.
1176
+ attkeyOp: async (mode, attested, chal) => post({ op: 'attkey', ...(mode === 'chal' ? { mode: 'chal' } : {}), attested, ...(chal ? { chal } : {}) }),
1177
+
1178
+ // DEVICE tool result — return a client-executed tool's answer (e.g. a calendar read the agent asked for) to the
1179
+ // blocked turn. The result is SEALED HERE under mk (content-blind at rest, opened only by the turn); mk never leaves.
1180
+ // `{ claim }` instead of a result: claim the call for this device before a tool with a side effect (G#3) — no result,
1181
+ // nothing sealed; → { ok, claimed } (claimed false: another device runs it).
1182
+ toolResult: async (room, mk, callId, result, opts = {}) => {
1183
+ if (opts && opts.claim) return post({ op: 'toolresult', room, callId, toolClaim: String(opts.claim) })
1184
+ const resBox = JSON.stringify(await seal(typeof result === 'string' ? result : JSON.stringify(result), { room: mk }))
1185
+ return post({ op: 'toolresult', room, callId, resBox })
1186
+ },
1187
+
1188
+ // KEEP-ALIVE (docs user-data-lifecycle): extend the idle-expiry of rooms THIS device holds. Called once per open
1189
+ // with room ids from the device's OWN recents list — no mk, no content — so the server never learns which rooms are
1190
+ // whose (the client does the fan-out; the server just pushes each `lapsesAt` out). Bounded here and again server-side;
1191
+ // best-effort by contract → a Space's life must never hinge on this succeeding. → { ok, rooms }.
1192
+ touch: async (rooms) => post({ op: 'touch', rooms: (Array.isArray(rooms) ? rooms : [rooms]).filter((r) => typeof r === 'string' && r).slice(0, 200) }),
1193
+
1194
+ // §APP STORE Stage 2: the PUBLIC registry-backed app catalog (no room/mk/auth) → { status, apps:[…] }.
1195
+ apps: async () => post({ op: 'apps' }),
1196
+
1197
+ // The create-screen capability probe (model catalog + whether temporary Spaces are supported) — same keyless shape
1198
+ // as `apps` above, and it belongs here for the same reason: `post` is the transport that actually works everywhere.
1199
+ // The picker used to call `fetch(endpoint, …)` directly, which (a) is not the path a VAULT-framed tenant app uses,
1200
+ // so the Model row silently never appeared there while the App row — routed through here — did, and (b) bypasses
1201
+ // the OHTTP relay, so with "Hide my IP" on, merely opening New Space leaked the device IP to the API.
1202
+ models: async () => post({ op: 'models' }),
1203
+
1204
+ // Stop a running turn (docs/spaces-stop-turn.md). Keyless — the per-turn nonce IS the authorization — but it must
1205
+ // still go through `post` for the same two reasons as `models`: it has to work in a vault-framed tenant app, and a
1206
+ // direct fetch would step outside the OHTTP relay (leaking the IP on the very op that says "stop reading me").
1207
+ stop: async (room, key) => post({ op: 'stop', room, key }),
1208
+
1209
+ // Tier-2 server-blind email invites (docs/spaces-email-invite.md) — identity-plane, no room/mk.
1210
+ // oprf: evaluate a blinded point → { z, proof, kpub } (the client verifies the DLEQ + unblinds to a handle).
1211
+ // dirGet: public lookup of a handle → { entry:{ boxPub, inbox } } or 404. dirPut: publish/rotate this user's own
1212
+ // slot, authenticated by the email-login idToken (the server checks OPRF(email)==handle so nobody can squat a slot).
1213
+ oprf: async (blinded) => post({ op: 'oprf', blinded }),
1214
+ // dirGet: public lookup of a handle → { entry:{ boxPub, inbox } } or 404. A member who closed the EMAIL door (Settings →
1215
+ // "People can find me by my email address", off) answers 404 like an unknown address — except to THEMSELF: pass the
1216
+ // sign-in `idToken` (+ the tenant `scope`, as dirPut does) and the row answers its owner (sign-in's "welcome back",
1217
+ // recovery's duplicate guard). dirDiscoverable: that switch — the row is named by the token, not a handle.
1218
+ dirGet: async (handle, { idToken, scope, app } = {}) => post({ op: 'dir', mode: 'get', handle, ...(idToken ? { idToken } : {}), ...(scope ? { dirScope: scope } : {}), ...(app ? { app } : {}) }), // app: another slot of the account (an attested box, attestedBox.js)
1219
+ dirDiscoverable: async (discoverable, idToken, scope) => post({ op: 'dir', mode: 'discoverable', discoverable: discoverable !== false, idToken, ...(scope ? { dirScope: scope } : {}) }),
1220
+ dirPut: async (handle, entry, idToken, scope, app) => post({ op: 'dir', mode: 'put', handle, entry, idToken, ...(scope ? { dirScope: scope } : {}), ...(app ? { app } : {}) }), // dirScope: the per-tenant handle namespace — the server re-derives OPRF(scope·email) to match (else a scoped account's put is handle_mismatch)
1221
+ // USERNAMES (docs/spaces-usernames.md §4): a public "@name" → the account's directory HANDLE (never its email).
1222
+ // resolve is public; whoami/claim/release prove the account with the same sign-in token the directory put uses.
1223
+ userResolve: async (username, app) => post({ op: 'user', mode: 'resolve', username, ...(app ? { app } : {}) }), // app: which of the account's slots comes back with the handle
1224
+ // A member by @username, as the room-bound TAG no guessed email can be linked to (docs/spaces-usernames.md §12)
1225
+ userTag: async (username, room) => call(endpoint, { op: 'user', mode: 'tag', username, room }, f), // 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)
1226
+ userWhoami: async (idToken) => post({ op: 'user', mode: 'whoami', idToken }),
1227
+ userClaim: async (username, idToken, { name, publish } = {}) => extrasCache.clear() || post({ op: 'user', mode: 'claim', username, idToken, ...(publish ? { publish: true, ...(name ? { name } : {}) } : {}) }),
1228
+ userRelease: async (idToken) => extrasCache.clear() || post({ op: 'user', mode: 'release', idToken }),
1229
+ dirErase: async (idToken, scope) => post({ op: 'dir', mode: 'erase', idToken, ...(scope ? { dirScope: scope } : {}) }), // DELETE MY ACCOUNT (docs/user-erasure.md): the token's own directory row + inboxes
1230
+ // The invite inbox: drop a sealed box into a recipient's mailbox; inboxFetch reads YOUR mailbox (openBox with boxPriv).
1231
+ drop: async (inbox, box) => post({ op: 'drop', inbox, box }),
1232
+ inboxFetch: async (inbox, since) => post({ op: 'inbox', inbox, ...(since ? { since } : {}) }),
1233
+ // "Which of my rooms changed since `since`?" — the change inbox, standard tier (docs/change-inbox.md). Keyless.
1234
+ changes: async (inbox, since = 0) => post({ op: 'changes', inbox, since }),
1235
+ inboxSubscribe: async (inbox, subscription) => post({ op: 'inboxsub', inbox, subscription }), // register this device for a real-time invite tickle
1236
+ 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), // 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
1237
+
1238
+ // Shared WIDGET state (co-edited by members; the agent reads its `summary` on turns). SET with a `patch` (+ a short
1239
+ // `summary`); READ with no patch → { v, state, summary }. The blob is mk-sealed server-side — never sent in clear.
1240
+ /** THE ROOM AS A STORE — write rows: ONE sealed ledger entry carrying put/delete ops, ordered by the server without
1241
+ * reading it. `ops` = [{ op:'put', collection, id?, row } | { op:'del', collection, id }]; `by` names the writer in
1242
+ * the system line every member sees. → { status, id, ops:[{op,collection,id}], text, entries } */
1243
+ // `file` (optional, ONE beside one put — a mail's attachment): { b64, mime, name } — the server stores it out of line
1244
+ // and the row's `file` field names it (agent/spaceService.mjs op data).
1245
+ data: async (room, mk, ops, by, file) =>
1246
+ 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)) }),
1247
+ // `ifV` (optional): the version this write was built on — the server writes only if the doc is still there (409
1248
+ // version_conflict otherwise, with the current `v`), so two devices cannot silently overwrite each other.
1249
+ state: async (room, mk, name, patch, summary, by, ifV) =>
1250
+ post({ op: 'state', room, ...(await keyFields(room, 'state', mk)), name, ...(patch !== undefined ? { patch, summary, by, ...(Number.isInteger(ifV) ? { ifV } : {}) } : {}), ...(await authFor(room)) }),
1251
+
1252
+ // An emoji on one message. `react` is {target, emoji, off} — target is the entryKey the server recomputes from the
1253
+ // ledger, so a client cannot react to something that is not there. Never a turn: the assistant stays quiet.
1254
+ /** PURGE a purgeable room's handled rows (docs/room-messages.md § Retention) — `ids` = row ids no collection still
1255
+ * holds. → { status, purged, live } */
1256
+ purge: async (room, mk, ids) =>
1257
+ post({ op: 'purge', room, ...(await keyFields(room, 'purge', mk)), ops: Array.isArray(ids) ? ids.slice(0, 50).map(String) : [], ...(await authFor(room)) }),
1258
+ /** DELETE FORWARDED MAIL FOR REAL (agent/mailPurge.mjs): the `mail`/`mailfile` rows named — already deleted with `data` —
1259
+ * leave the ledger and their files are overwritten. Only in a solo verified Space, by its member. → { status, purged, files, live } */
1260
+ mailPurge: async (room, mk, ids) =>
1261
+ post({ op: 'mailpurge', room, ...(await keyFields(room, 'mailpurge', mk)), ops: Array.isArray(ids) ? ids.slice(0, 50).map(String) : [], ...(await authFor(room)) }),
1262
+ /** THE MESSAGE INTAKE (docs/message-intake.md, roomIntake.js). `intakeDrop` is a PRODUCER's call — keyless: a drop
1263
+ * token and a box sealed to the intake's public key. The rest are the account's devices (keyed). */
1264
+ intakeDrop: async (room, drop, box) => post({ op: 'intakedrop', room, drop, box }),
1265
+ intakeReg: async (room, mk, ops) => post({ op: 'intakereg', room, ...(await keyFields(room, 'intakereg', mk)), ops: Array.isArray(ops) ? ops.slice(0, 50) : [] }),
1266
+ intakePush: async (room, mk, subscription, remove = false) => post({ op: 'intakepush', room, ...(await keyFields(room, 'intakepush', mk)), subscription, ...(remove ? { remove: true } : {}) }), // this device on the intake's wake list (messageIntake.mjs)
1267
+ intakeDeviceWake: async (room, mk, remove = false) => post({ op: 'intakepush', room, ...(await keyFields(room, 'intakepush', mk)), cloudDevice: true, ...(remove ? { remove: true } : {}) }), // the cloud device on the wake list (docs/cloud-device.md § 12)
1268
+ intake: async (room, mk) => post({ op: 'intake', room, ...(await keyFields(room, 'intake', mk)) }),
1269
+ intakeAck: async (room, mk, items) => post({ op: 'intakeack', room, ...(await keyFields(room, 'intakeack', mk)), ops: Array.isArray(items) ? items.slice(0, 50) : [] }),
1270
+ // 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)
1271
+ 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)) }),
1272
+ react: async (room, mk, react, by) =>
1273
+ post({ op: 'react', room, ...(await keyFields(room, 'react', mk)), react, ...(by ? { by: String(by).slice(0, 80) } : {}), ...(await authFor(room)) }),
1274
+
1275
+ // OWNER RULE (docs/the-owner-rule.md) — the JOIN-flow peer check. `policyOf` fetches the room's cleartext marker +
1276
+ // sealed config (op:'policy', public). `verifyGovernance` opens the config with mk and verifies the owner-signed
1277
+ // policy against the PINNED owner key (from /space-config) — so the client trusts a governed room only if it's a
1278
+ // genuine room of that owner, not the server's word. Called only when a key is pinned (single-owner deployment);
1279
+ // the generic multi-tenant PWA passes no key ⇒ { ok:true, governed:false }.
1280
+ // op:'policy' carries the room key and the member's sign-in: an EMAIL-GATED room serves its sealed config only to an
1281
+ // allowed member (agent/spaceService.mjs, 2026-10-02) and otherwise answers just { gated: true }.
1282
+ policyOf: (room, mk) => policyPost(room, mk),
1283
+ /** Does this room require an attested app? (a refusal already said so, or op 'policy' does) → boolean. */
1284
+ // 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)
1285
+ // …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
1286
+ // then reaches the front, which answers from its mirror row — the tier, never the enclave's `attested` mark (agent/tierGuard.mjs).
1287
+ // "No" from there was remembered and an ordinary lane made of an attested confidential Space. Only "yes", or the answer of the
1288
+ // 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.
1289
+ attestedRoom: async (room, mk) => {
1290
+ if (attestReadRooms.has(room)) return true
1291
+ const marked = enclaveFor(room)
1292
+ const r = await policyPost(room, mk)
1293
+ if (!r || r.status !== 200) throw Object.assign(new Error('policy read failed' + (r && r.status ? ' (HTTP ' + r.status + ')' : '')), { code: 'policy_unreadable' })
1294
+ if (r.attested === true) return true
1295
+ 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' })
1296
+ return false
1297
+ },
1298
+ /** The room's PUBLIC key commitment (op 'invite', keyless) → string | null (none) | undefined (could not ask). Lets a device
1299
+ * check a key it was handed before keeping it (emailInvites.js keyOpens). */
1300
+ roomCommit: async (room) => { const r = await post({ op: 'invite', room }); return r && r.status === 200 ? (r.mkCommit || null) : undefined },
1301
+ // Fetch + decrypt this room's sealed agent CONFIG (persona/tools/agentName/admission/allow/agentKeys/model/…) with
1302
+ // mk → the plaintext config, or null. The config ciphertext is content-blind (sealed under mk, served by op:'policy'
1303
+ // which already returns it for governance). A membership fork uses this to carry the agent's behavior into the new
1304
+ // room (spaceFork.js) — the forking client holds the OLD mk, so it can decrypt without exposing the new key.
1305
+ // `{ plainMark: true }`: a PLAIN room (a read that worked, nothing sealed, no lanes bit) answers `{ plain: true }`, so null
1306
+ // means only that the read failed — a private lane waits on that, never inherits "nothing" (sync sweep 2026-11-03)
1307
+ getConfig: async (room, mk, o) => {
1308
+ const r = await policyPost(room, mk)
1309
+ if (!r || r.status !== 200 || r.error || r.ok === false) return null // a refusal is not a plain room (sweep 11-06 #1: an envelope refusal read as { plain: true } → an OPEN lane)
1310
+ if (!r.configSealed && r.gated === true) { gatedRooms.add(room); return { admission: 'email', gated: true } } // a gated room before sign-in: that it is gated, and nothing else
1311
+ if (!r.configSealed) { const h = await healEnclaveConfig(room, mk); if (h) return h.cfg }
1312
+ if (!r.configSealed) return typeof r.lanes === 'boolean' ? { lanes: r.lanes } : (o && o.plainMark === true ? { plain: true } : null) // PLAIN room: preserve an explicit disabled setting too
1313
+ let cfg = null
1314
+ try { cfg = JSON.parse(await open(JSON.parse(r.configSealed), { mk })) } catch { return null }
1315
+ // a VERIFIED room learned from its settings too (sweep 11-07 #1: only create/open/a keyless read taught it, so a removed
1316
+ // member's key-free reads never asked with the key); an owner-governed one reads with the key up front (#5)
1317
+ if (cfg && typeof cfg === 'object' && cfg.admission === 'email') { gatedRooms.add(room); if (cfg.ownerPolicy) keyFirst.set(room, Infinity) }
1318
+ return cfg
1319
+ },
1320
+ /** Change the assistant IN PLACE — its name, instructions (persona) and model — visibly: the server appends a system
1321
+ * line to the ledger ("⚙️ Dana changed the assistant's instructions") that every member sees. Only those three
1322
+ * fields move; the sealed config is re-sealed WHOLE with them applied, so tools, admission, the owner policy and the
1323
+ * enclave block travel byte-identical (the server opens both versions and refuses anything else — those stay
1324
+ * fork-and-replay). `by` is the display name for the line. → { status, changed:[…], recorded } */
1325
+ /** The standing Sentinel's door (docs/standing-sentinel.md §2): attest / credgrant / credlist / credrevoke, as the
1326
+ * signed-in account (the token's email — the server never reads an account the page names). A pipe: the grant
1327
+ * inside is sealed to the Sentinel's attested key. → the Sentinel's answer, or { error }. */
1328
+ sentinel: async (sentinel, idToken) => post({ op: 'sentinel', sentinel, idToken }),
1329
+ /** The cloud device through the API (agent/cloudDeviceRoute.mjs): `cd` = { t, … }, the account = the verified idToken's. */
1330
+ cloudDevice: async (cd, idToken, opts) => (await import('./cloudDeviceSeal.js')).cloudDeviceCall(post, cd, idToken, opts || undefined), // sealed to its enclave once pinned; opts: the dev server's root and pins (witbitz-sdk.js _cloudDeviceOpts)
1331
+ // press-to-talk's cloud engine (agent/sttKey.mjs): a short-lived, capped Tinfoil key for this signed-in account
1332
+ // SAFE MEDIA (docs/safe-media.md): the tools enclave's attestation for a nonce, then a sealed box to make a file safe
1333
+ safeMedia: async (idToken, safemedia) => post({ op: 'safemedia', idToken, safemedia }),
1334
+ stt: async (idToken, userToken) => post({ op: 'stt', ...(idToken ? { idToken } : {}), ...(userToken ? { userToken } : {}) }), // userToken: the SDK's tenant-vouched user (wb.dictation)
1335
+ // Report (docs/report-and-block.md §3): what the member chose to show Witbitz — the front stores and mails it (agent/reportOp.mjs)
1336
+ report: async (idToken, body, memberToken) => post({ op: 'report', idToken, room: body.room, report: body, ...(memberToken ? { memberToken } : {}) }),
1337
+ // a MEMBER's token for a report (agent/spaceService.mjs op membertoken): issued only to the room's CURRENT key and, in a verified
1338
+ // room, to a sign-in its gate admits (it rides with the request) — sealed to the turn enclave for a confidential room, like any
1339
+ // keyed op, so the key never reaches the Lambda
1340
+ memberToken: async (room, mk) => post({ op: 'membertoken', room, ...(await keyFields(room, 'membertoken', mk)), ...(await authFor(room)) }), // the sign-in: a verified room issues it only past its email gate (sync sweep 11-11 #2)
1341
+ tts: async (idToken, userToken) => post({ op: 'tts', ...(idToken ? { idToken } : {}), ...(userToken ? { userToken } : {}) }), // "Play aloud": a capped Tinfoil key for speech OUTPUT (agent/sttKey.mjs § SPEECH OUTPUT)
1342
+ /** Witbitz's signed rule + room signature for a NEW room that requires an app (op owner-policy, agent/witbitzOwnerPolicy.mjs) — for
1343
+ * a create that is not this client's own (the hosted app's split create, space.js createSplitLocal). */
1344
+ ownerPolicyFor: async (room, _mk, level) => post({ op: 'owner-policy', room, level }),
1345
+ setConfig: async (room, mk, patch, by) => {
1346
+ let r = await policyPost(room, mk)
1347
+ if (!r || r.status !== 200) return { status: (r && r.status) || 502, error: (r && r.error) || 'policy_unavailable' }
1348
+ if (!r.configSealed && r.gated !== true) { const h = await healEnclaveConfig(room, mk); if (h && h.saved) r = { ...r, configSealed: h.configSealed } } // edit the healed config, never a config of only the edited fields
1349
+ let cur = {}
1350
+ if (r.configSealed) { // a config that does not open with THIS key is not ours to rewrite — refuse here, before anything is posted
1351
+ let pt = null
1352
+ try { pt = await open(JSON.parse(r.configSealed), { mk }) } catch { pt = null }
1353
+ if (pt == null) return { status: 409, error: 'config_unreadable' }
1354
+ try { cur = JSON.parse(pt) || {} } catch { return { status: 409, error: 'config_unreadable' } }
1355
+ }
1356
+ const p = patch && typeof patch === 'object' ? patch : {}
1357
+ const next = { ...cur }
1358
+ if ('persona' in p) next.persona = p.persona == null ? undefined : String(p.persona).slice(0, 4000)
1359
+ if ('agentName' in p) next.agentName = p.agentName == null ? undefined : String(p.agentName).slice(0, 80)
1360
+ if ('model' in p) next.model = p.model == null ? undefined : p.model
1361
+ 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) || undefined } : undefined // an admin's grant (agent/roomFunding.mjs) — the server lets only an admin change it
1362
+ if ('dataSchema' in p) next.dataSchema = p.dataSchema == null ? undefined : p.dataSchema // the room's declared collections — data, not governance
1363
+ if ('platformTools' in p) next.platformTools = p.platformTools === false || Array.isArray(p.platformTools) ? p.platformTools : undefined // which platform tools the assistant gets; null/true = all again
1364
+ if ('framing' in p) next.framing = p.framing === 'builder' ? 'builder' : undefined // builder mode: the app's prompt only; null = the Spaces framing again
1365
+ // WHO RUNS IT (a role change in place — no new key; the server checks who may: agent/roomRekey.mayChangeRoles)
1366
+ for (const k of ['admins', 'owners']) if (k in p) next[k] = { emails: [...new Set(((p[k] && p[k].emails) || []).map((e) => String(e).trim().toLowerCase()).filter(Boolean))] }
1367
+ if ('lanes' in p) next.lanes = p.lanes === true // "Private assistants" off (or on) in place (docs/always-on-agent-plan.md Phase 0b)
1368
+ if ('dataWrites' in p) next.dataWrites = p.dataWrites === false ? false : undefined // false = data_query only; null/true = writes offered again
1369
+ if ('safeMedia' in p) next.safeMedia = p.safeMedia === true ? true : undefined // SAFE MEDIA on/off (docs/safe-media.md): the admins', any member's where there are none
1370
+ // connections (docs/standing-sentinel.md §3): the API keys members attached, as { account, id, callKey, label, host } —
1371
+ // never a secret. The patch is DECLARATIVE — { add: entry } | { remove: id } | a whole list — because it crosses
1372
+ // the L1 façade by structured clone (a function would not), and it is applied to the room's CURRENT list, read
1373
+ // under its own key at write time, so two members attaching at once do not overwrite each other from a stale read.
1374
+ if ('connections' in p) {
1375
+ next.connections = applyConnectionsPatch(next.connections, p.connections) // connectionEntry.js: bounded; an MCP server's chosen tools + auto list ride too ({ update: { id, mcp } })
1376
+ }
1377
+ const configSealed = JSON.stringify(await seal(JSON.stringify(next), { room: mk })) // the `room` recipient — what sealConfig and the server's open expect
1378
+ return post({ op: 'config', room, ...(await keyFields(room, 'config', mk)), configSealed, ...(by ? { by: String(by).slice(0, 80) } : {}), ...(await authFor(room)) })
1379
+ },
1380
+ /** A VERIFIED ROOM RE-KEYED IN PLACE (docs/key-rotation-design.md § (b); agent/roomRekey.mjs has the server's rules).
1381
+ * `members` = the new { allow, owners, admins } (absent = a pure rotation, "Rotate keys now"); `recipients` = one
1382
+ * { mh: memberHash(email, room), boxPub } per member who stays (the caller included). Here, in the realm that holds the
1383
+ * key: a NEW key is minted; the config is read under the current key, its members replaced, the current key appended
1384
+ * to its chain, and it is sealed under the new key; the new key is sealed to each recipient's invite key; one request.
1385
+ * → the server's answer, plus `newMk` on success (the caller keeps it — the worker: l1-worker op 'rekey'). */
1386
+ // A SPLIT room (mk = userShare ⊕ appShare; the hosted app): `split.userShare` is the share held now. Only the USER half
1387
+ // rotates (§ Split-key rooms): appShare = mk ⊕ userShare, a fresh random userShare', mk' = userShare' ⊕ appShare — the
1388
+ // builder's half and its seal stay as they are. The grants carry userShare' (never mk'); the answer carries newShare.
1389
+ rekey: async (room, mk, { members = null, recipients = [], pending = [], by = '', split = null, creatorPriv = null, link = null, expectEpoch: wantEpoch = null } = {}) => { // link: { roster, gk } — a LINK Space (linkMembers.js): its roster and new invite key; recipients then carry `id` (keyGrantId) and `extra` (their fresh gk grant)
1390
+ const r = await policyPost(room, mk)
1391
+ if (!r || r.status !== 200 || !r.configSealed) return { status: (r && r.status) || 502, error: (r && r.error) || 'policy_unavailable' }
1392
+ let cur = null
1393
+ try { cur = JSON.parse((await open(JSON.parse(r.configSealed), { mk })) || 'null') } catch { cur = null }
1394
+ if (!cur || typeof cur !== 'object') return { status: 409, error: 'config_unreadable' }
1395
+ const chain = Array.isArray(cur.keyChain) ? cur.keyChain : []
1396
+ const epoch = chain.length // each rotation appends the key it retires: the chain's length IS the room's epoch
1397
+ if (Number.isInteger(wantEpoch) && wantEpoch !== epoch) return { status: 409, error: 'stale_epoch' } // the members were computed at another epoch (V#5): a retry with a key adopted meanwhile must not apply them to the newer config
1398
+ let newMk = newKey(), newShare = null
1399
+ if (split && split.userShare) { const app = combineShares(mk, split.userShare); if (!app) return { status: 400, error: 'bad_split', reason: 'the held share does not pair with this key' }; const s2 = splitKey(app); newShare = s2.shareA; newMk = s2.shareB } // shareB = app ⊕ shareA = userShare' ⊕ appShare
1400
+ const newCommit = await keyCommit(newMk)
1401
+ 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 keyCommit(mk), key: mk }] }
1402
+ for (const k of ['owners', 'admins']) if (next[k] === undefined) delete next[k]
1403
+ if (next.direct === true && members && !staysDirect(await directRoster(next.allow, room))) delete next.direct // a third member makes a direct chat a group (roomName.js)
1404
+ const configSealed = JSON.stringify(await seal(JSON.stringify(next), { room: newMk }))
1405
+ 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 })
1406
+ const grants = {}
1407
+ for (const x of recipients || []) {
1408
+ const id = x && (x.mh || x.id) // an account (mh) — or a LINK Space's member key (id: keyGrantId), whose box also carries its fresh invite grant
1409
+ if (id && x.boxPub && !grants[id]) grants[id] = JSON.stringify(await sealTo(x.extra ? JSON.stringify({ ...JSON.parse(grant), ...x.extra }) : grant, x.boxPub))
1410
+ }
1411
+ for (const mh of pending || []) { if (typeof mh === 'string' && mh && !grants[mh]) grants[mh] = 'pending' } // on the list, no invite key yet: told to ask for a fresh link, not that the room went on without them
1412
+ const kf = await keyFields(room, 'rekey', mk)
1413
+ let nf = { newMk }
1414
+ if (kf.mkSealed) { const pub = mkPubFor(room); nf = { newMkSealed: await sealMk(newMk, pub, mkAad({ room, op: 'rekey:new', ts: kf.mkTs, nonce: kf.mkNonce })) } } // sealed like the current key, bound to the same request
1415
+ const creatorSig = creatorPriv ? (await signEntry(creatorPriv, { room, kind: 'rekey', id: newCommit, text: String(epoch), ts: 0, author: '' })).sig : undefined // a room with no owners or admins: its creator's key over this change
1416
+ 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)) })
1417
+ return out && out.status === 200 ? { ...out, newMk, newCommit, ...(newShare ? { newShare } : {}) } : out
1418
+ },
1419
+ /** This member's new key after a rotation: the grant sealed to their account's invite key (op 'grant'), asked with the
1420
+ * sign-in alone — the old key opens nothing now. → { status:200, grant, epoch, commit } | { status:404, error:'no_grant' } */
1421
+ grant: async (room, _mk, keyProof = null) => post({ op: 'grant', room, ...(keyProof && keyProof.spk && keyProof.keySig ? { spk: keyProof.spk, keySig: keyProof.keySig } : await authFor(room)) }), // keyProof: a LINK Space's member proves its signing key (no account)
1422
+ verifyGovernance: (room, mk, ownerKey, member) =>
1423
+ 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 })) }),
1424
+
1425
+ }
1426
+ return api
1427
+ }
1428
+ function cryptoRandom(n) { const u = new Uint8Array(n); (globalThis.crypto || require('crypto').webcrypto).getRandomValues(u); return u }
1429
+ function b64url(u) { let s = ''; for (const b of u) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }