@witbitz/sdk 4.3.0 → 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 (80) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +26 -5
  3. package/accountErase.js +6 -1
  4. package/accountRecord.js +2 -2
  5. package/agentDoorTools.js +28 -0
  6. package/chatLock.js +16 -0
  7. package/cloudDevicePins.js +2 -2
  8. package/codeAttachments.js +100 -0
  9. package/codeCache.js +149 -0
  10. package/codeCloud.js +0 -2
  11. package/codeComputers.js +1 -0
  12. package/codeFolders.js +116 -0
  13. package/codeHistory.js +76 -0
  14. package/codeLanguage.js +54 -0
  15. package/codeModes.js +2 -0
  16. package/codeProgress.js +54 -0
  17. package/codeSent.js +68 -0
  18. package/codeSubagents.js +107 -0
  19. package/codeTransport.js +22 -0
  20. package/connections.js +17 -18
  21. package/deviceAttest.js +9 -3
  22. package/idb.js +19 -3
  23. package/jobAgents.js +2 -2
  24. package/keptMerge.js +9 -2
  25. package/l1-worker-src.js +1 -1
  26. package/l1-worker.js +93 -30
  27. package/laneAssociation.js +68 -0
  28. package/laneConfig.js +4 -3
  29. package/manifest.json +80 -61
  30. package/memberChange.js +4 -2
  31. package/mirrorBatch.js +47 -0
  32. package/opRouting.js +10 -0
  33. package/package.json +21 -2
  34. package/pdfOptions.js +13 -0
  35. package/pdfText.js +107 -0
  36. package/pdfjs.mjs +28 -0
  37. package/pdfjs.worker.mjs +28 -0
  38. package/protectedLocal.js +18 -2
  39. package/removedMessage.js +1 -1
  40. package/roomEmbed.js +111 -0
  41. package/roomName.js +1 -1
  42. package/roomRoster.js +21 -5
  43. package/rosterCount.js +6 -3
  44. package/sdkA2A.js +160 -40
  45. package/sdkAccount.js +17 -4
  46. package/sdkAccountDoc.js +11 -3
  47. package/sdkAccountSections.js +117 -8
  48. package/sdkBackup.js +35 -8
  49. package/sdkCloudDevice.js +8 -2
  50. package/sdkComputers.js +582 -53
  51. package/sdkDictation.js +114 -24
  52. package/sdkErase.js +9 -4
  53. package/sdkExports.js +4 -2
  54. package/sdkLaneLink.js +3 -3
  55. package/sdkPlan.js +4 -2
  56. package/sdkRekey.js +50 -17
  57. package/sdkReport.js +1 -1
  58. package/sdkSafeMedia.js +1 -1
  59. package/sdkSpeech.js +19 -2
  60. package/sdkTemporaryRooms.js +123 -0
  61. package/sdkVault.js +66 -10
  62. package/sentinelRelease.js +1 -0
  63. package/sharedViews.js +17 -3
  64. package/siri.js +114 -7
  65. package/spaceClient.js +16 -5
  66. package/spaceEmailGate.js +2 -2
  67. package/spaceTemplates.js +99 -0
  68. package/speechOut.js +4 -2
  69. package/store.js +83 -14
  70. package/sw-notif-core.js +9 -7
  71. package/turnVerdict.js +1 -0
  72. package/vault-core.js +480 -112
  73. package/vault-kit.mjs +2 -2
  74. package/vault-screens.js +5 -7
  75. package/vaultAtRest.js +35 -4
  76. package/vaultKeep.js +9 -3
  77. package/vaultWorkerHost.js +23 -4
  78. package/witbitz-admin.mjs +12 -11
  79. package/witbitz-sdk.d.ts +115 -24
  80. package/witbitz-sdk.js +572 -149
package/vault-core.js CHANGED
@@ -16,6 +16,9 @@ import { spacesUsingConnection } from './connOtherWays.js'
16
16
  // The page may ask for ONLY: the room operations in PAGE_OPS on a room this vault holds, create, rooms, share, signIn,
17
17
  // signOut, whoami, forget, stream, and the account calls in ACCOUNT_CALLS / ROOM_ACCOUNT_CALLS. Everything else the worker can do (remember a key, export, the index, protection) is the
18
18
  // vault's own and is not reachable from the page.
19
+ import { preferredAssociation } from './laneAssociation.js'
20
+ import { embeddedInvite, roomInviteFlags } from './roomEmbed.js'
21
+ import { routingIndex } from './opRouting.js'
19
22
  import { memberHash } from './rosterHash.js'
20
23
  import { Witbitz, Space, Lane } from './witbitz-sdk.js'
21
24
  import { LaneA2A, assertAgentTarget } from './sdkA2A.js'
@@ -37,7 +40,7 @@ import { commit as keyCommit } from './e2ee.js'
37
40
  import { createEnclaveHandoff, enclaveReady, reattestOnce, saysConfidential } from './vaultEnclaveHandoff.js' // what the worker is told of the confidential tier — the same rules as our hosted vault's (C2)
38
41
  import { dropFor, receiptFor } from './usageReceipts.js'
39
42
  import { makeVerifiedWorker } from './vcWorker.js' // the key worker from its PINNED source, never a file fetched by URL
40
- import { createWorkerHost } from './vaultWorkerHost.js' // the key worker's host: load, heartbeat, restart, replay (shared with our hosted vault)
43
+ import { createWorkerHost, workerStreams } from './vaultWorkerHost.js' // the key worker's host: load, heartbeat, restart, replay (shared with our hosted vault)
41
44
  import { keepPass, viewOfKeep, tabStores } from './vaultKeep.js' // connections, Siri and outside agents on every device of the account (sync sweep 2026-11-11 P7)
42
45
  import { laneInherits, gatedStub } from './laneConfig.js' // the heartbeat that finds a worker iOS reclaimed (l1.js and the app's vault use it too)
43
46
  import { sealedStorage } from './vaultSealedStore.js' // the vault's other secrets sealed on disk too (2026-11-24)
@@ -55,7 +58,7 @@ export const VAULT_PROTOCOL = 1
55
58
  // (no 'safeCopy': a safe copy is made only where the sign-in and the key are — space.safeMedia.make is refused in a vault, and
56
59
  // nothing in vault mode posts one; sync sweep backlog P7)
57
60
  export const PAGE_OPS = new Set(['poll', 'pollSealed', 'turn', 'state', 'data', 'title', 'decide', 'pending', 'mirror', 'toolResult', 'getConfig', 'setConfig', 'blob', 'react', 'mark', 'sealed', 'exportSealed', 'stop', 'toolRules', 'importChat', 'importWhatsApp'])
58
- const KEYS = { rooms: 'wbvault:rooms', session: 'wbvault:session', siri: 'wbvault:siri', a2a: 'wbvault:a2a', invite: 'wbvault:invite', connections: 'wbvault:connections', backup: 'wbvault:backup', keep: 'wbvault:keep', connPending: 'wbvault:connPending' }
61
+ const KEYS = { rooms: 'wbvault:rooms', session: 'wbvault:session', siri: 'wbvault:siri', a2a: 'wbvault:a2a', invite: 'wbvault:invite', connections: 'wbvault:connections', backup: 'wbvault:backup', keep: 'wbvault:keep', connPending: 'wbvault:connPending', connGone: 'wbvault:connGone', pendingForget: 'wbvault:pendingForget', pendingGrants: 'wbvault:pendingGrants' }
59
62
  // THE ACCOUNT, through the vault's session (docs/sdk-vault-mode.md § The account). The page asks; the vault runs it on its
60
63
  // own SDK client, which holds the sign-in. What stays here: the session, the Siri inbox's private keys, each connection's
61
64
  // callKey (a grant is made by id). `confirm`: the person says yes in the vault's own pixels first — it acts in their name.
@@ -63,8 +66,8 @@ export const ACCOUNT_CALLS = {
63
66
  cloudDevice: { status: {}, enroll: { confirm: true }, register: { confirm: true }, setBuilds: { confirm: true }, forget: { confirm: true } },
64
67
  connections: { catalog: {}, spacesUsing: {}, attach: {}, list: {}, detach: { confirm: true }, startConnect: {}, finishConnect: {}, startMcp: {}, attachMcp: {}, finishMcp: {}, mcpTools: {} }, // MCP servers (2026-10-23): the callKey stays here, as attach's
65
68
  usernames: { claim: { confirm: true }, release: { confirm: true }, mine: {}, resolve: {} },
66
- siri: { status: {}, rotateKey: { confirm: true }, revoke: { confirm: true }, shortcut: {}, showKey: {} },
67
- a2a: { status: {}, revoke: { confirm: true } },
69
+ siri: { status: {}, sync: {}, rotateKey: { confirm: true }, revoke: { confirm: true }, shortcut: {}, showKey: {} },
70
+ a2a: { status: {}, revoke: { confirm: true }, stopJobAgent: { confirm: true } },
68
71
  // the account BACKUP and the account INDEX across devices: the vault's own, over the Spaces it holds. The recovery code
69
72
  // is shown and typed ONLY in the vault's screens (screens.recoveryCode / screens.restore) — a page that saw it would hold
70
73
  // the way back to every key.
@@ -80,6 +83,7 @@ const SERVICE_CALLS = new Set(['manageSecurityKeys', 'signOutOthers', 'newRecove
80
83
  export const ROOM_ACCOUNT_CALLS = {
81
84
  roster: { list: {}, admission: {} },
82
85
  portable: { export: { confirm: true } },
86
+ privateRoom: { link: { confirm: true }, unlink: { confirm: true } },
83
87
  keptAgent: { link: { confirm: true }, unlink: { confirm: true } },
84
88
  alwaysOn: { status: {}, enable: { confirm: true }, disable: { confirm: true }, run: {}, assertNotKept: {} },
85
89
  invitations: { resend: { confirm: true } },
@@ -91,10 +95,20 @@ export const ROOM_ACCOUNT_CALLS = {
91
95
  a2a: { view: {}, enable: {}, addPeer: { confirm: true }, setReply: {}, removePeer: {}, disable: {}, pull: {}, ack: {}, reply: {}, sharedDrafts: {}, reviewDraft: {} },
92
96
  }
93
97
  const ASK_MS = 60_000 // the page's answer to a question the vault asks it (a Siri drop handed to its deliver)
98
+ export function publicVaultRooms(rooms, currentRoom) {
99
+ return rooms.filter(currentRoom).map(({ room, title, at, lane, detachedLane, enc, link }) => ({
100
+ room, title: title || '', at,
101
+ ...(lane ? { lane } : {}),
102
+ ...(detachedLane ? { detachedLane: true } : {}),
103
+ ...(enc ? { tier: 'enclave' } : {}),
104
+ ...(roomInviteFlags(link).lanes ? { lanes: true } : {}),
105
+ })).sort((a, b) => (Number(b.at) || 0) - (Number(a.at) || 0))
106
+ }
107
+
94
108
  // What a page may put in a NEW Space's config — the fields the SDK's createSpace writes (roomConfig + the email gate).
95
109
  // Anything else (a key model, a confidential tier, a direct chat) is refused HERE: the SDK's own refusals run in the
96
110
  // page, and a hostile page skips them (security review, 2026-10-15).
97
- export const CREATE_FIELDS = new Set(['agentName', 'persona', 'tools', 'immediateTools', 'clientTools', 'agentReplies', 'model', 'admission', 'allow', 'advertise', 'admins', 'owners', 'platformTools', 'framing', 'dataWrites', 'dataSchema', 'region', 'direct', 'safeMedia', 'lanes', 'lane']) // lane: a private lane says so (laneConfig.js) — it only takes things away (no schedules, no always on)
111
+ export const CREATE_FIELDS = new Set(['agentName', 'persona', 'tools', 'skills', 'immediateTools', 'clientTools', 'agentReplies', 'model', 'admission', 'allow', 'advertise', 'admins', 'owners', 'platformTools', 'framing', 'dataWrites', 'dataSchema', 'region', 'direct', 'usernames', 'safeMedia', 'lanes', 'lane']) // lane: a private lane says so (laneConfig.js) — it only takes things away (no schedules, no always on)
98
112
  const CREATE_LIMIT = { n: 20, ms: 10 * 60_000 } // new Spaces per window, per vault page
99
113
  const SPEECH_LIMIT = { n: 30, ms: 10 * 60_000 } // speech keys (dictation, reading aloud) per window, per vault page
100
114
  const REFRESH_BEFORE_MS = 10 * 60_000 // renew the sign-in this long before it expires
@@ -130,6 +144,7 @@ export function vaultSignInWords(e) {
130
144
  export function configForPage(cfg) {
131
145
  if (!cfg || typeof cfg !== 'object') return cfg
132
146
  const out = { ...cfg }
147
+ if (Array.isArray(out.keyChain)) out.keyChain = out.keyChain.map((_, epoch) => ({ epoch }))
133
148
  if (Array.isArray(out.connections)) out.connections = out.connections.map((c) => { if (!c || typeof c !== 'object') return c; const { callKey: _k, ...rest } = c; return rest })
134
149
  if (out.funding && typeof out.funding === 'object') { const { grant: _g, grantToken: _t, key: _x, token: _y, ...rest } = out.funding; out.funding = rest }
135
150
  return out
@@ -158,6 +173,7 @@ const holdLink = (worker, p) => { if (!p) return; if (p.mk) worker.postMessage({
158
173
  export async function startVault(o = {}) {
159
174
  const pageUrl = new URL(String(o.page || ''))
160
175
  const pageOrigin = pageUrl.origin
176
+ const recoveryNotice = () => ' To restore in this vault, enter the recovery code' + (sdk.backup.service === 'account' ? ' and verify the account email or Google sign-in' : sdk.backup.gated ? ' and enter the verification code sent to the backup email' : '') + '. Advanced Backup also requires the registered hardware key.'
161
177
  if (!/^https?:$/.test(pageUrl.protocol)) throw new Error('vault: `page` must be an http(s) URL')
162
178
  if (pageOrigin === location.origin) throw new Error('vault: the page must be on ANOTHER origin — that is the wall that keeps the keys out of it')
163
179
  if (globalThis.localStorage?.getItem('witbitz-builder-reset-pending')) {
@@ -200,7 +216,7 @@ export async function startVault(o = {}) {
200
216
  // EVERY SECRET ON DISK SEALED (vaultSealedStore.js; the owner, 2026-11-24, as our hosted vault): the session, the invite key, Siri,
201
217
  // outside agents, connections (and those being granted) and the merged view are kept in memory and sealed to disk under the at-rest key
202
218
  const learnedBlocksKey = 'wbvault:learnedBlockIdentities'
203
- const SEALED_KEYS = [learnedBlocksKey, KEYS.session, KEYS.siri, KEYS.a2a, KEYS.invite, KEYS.connections, KEYS.keep, KEYS.connPending]
219
+ const SEALED_KEYS = [learnedBlocksKey, KEYS.session, KEYS.siri, KEYS.a2a, KEYS.invite, KEYS.connections, KEYS.keep, KEYS.connPending, KEYS.connGone, KEYS.pendingForget, KEYS.pendingGrants]
204
220
  const wipeMarker = 'wbvault:signout-pending'
205
221
  let wipeRun = null, peerSignedOut = false
206
222
  const st = sealedStorage(o.storage || localStorage, SEALED_KEYS)
@@ -254,12 +270,18 @@ export async function startVault(o = {}) {
254
270
  await st.open(wrapKey) // the sealed secrets, opened into memory (and an older clear copy sealed) before anything reads one
255
271
  const savedSession = read(st, KEYS.session, null)
256
272
  if (savedSession) sdk.useSession(savedSession)
257
- const atRest = createAtRest({ storage: st, key: wrapKey })
273
+ const forgetPrefix = 'wbvault:forgot:'
274
+ const forgetMark = room => st.getItem(forgetPrefix + room) || ''
275
+ const currentRoom = row => !!row && (row.forgetMark || '') === forgetMark(row.room)
276
+ const joinedMark = room => { const mark = forgetMark(room); return mark ? { forgetMark: mark } : {} }
277
+ const atRest = createAtRest({ storage: st, key: wrapKey, currentRoom })
258
278
  let rooms = await atRest.loadRooms(KEYS.rooms) // [{ room, link, title, at }] — in memory the link IS the key; it never leaves this origin
279
+ const pendingForget = new Set(read(st, KEYS.pendingForget, []) || [])
280
+ rooms = rooms.filter(r => !pendingForget.has(r.room) && currentRoom(r))
259
281
  let vpush = null // notifications (`push: true`, vaultCorePush.js): every Space held lists this device, kept in step at each save
260
282
  let pushAcctSecret = '' // the account's push tag secret the key worker holds (handDownPushAcct) — '' while no account is here
261
- const saveRooms = () => { if (vpush) vpush.sync(rooms.map((r) => r.room)).catch(() => {}); return atRest.saveRooms(KEYS.rooms, rooms) } // in order; resolves once on disk
262
- sdk._heldLaneRooms = (parent) => rooms.filter((r) => r.lane === parent).map((r) => r.room)
283
+ const saveRooms = (strict = false, replaceAll = false) => { if (vpush) vpush.sync(rooms.filter(currentRoom).map((r) => r.room)).catch(() => {}); return atRest.saveRooms(KEYS.rooms, rooms, strict, replaceAll) } // in order; resolves once on disk
284
+ sdk._heldLaneRooms = (parent) => rooms.filter((r) => currentRoom(r) && r.lane === parent).map((r) => r.room)
263
285
  sdk._detachHeldLanes = async (parent) => {
264
286
  for (const r of rooms) if (r.lane === parent) { delete r.lane; r.detachedLane = true }
265
287
  await saveRooms()
@@ -267,10 +289,13 @@ export async function startVault(o = {}) {
267
289
  }
268
290
  if (sdk.session?.email) await atRest.claimEmailMove(KEYS.backup, sdk.session.email)
269
291
  const backupsAtStart = await atRest.loadBackups(KEYS.backup) // here, before the frame: nothing awaits between the frame and the page's hello listener
270
- const publicRooms = () => rooms.map(({ room, title, at, lane, enc, link }) => ({ room, title: title || '', at, ...(lane ? { lane } : {}), ...(enc ? { tier: 'enclave' } : {}), ...(/[#&]lanes=1(?:&|$)/.test(String(link || '')) ? { lanes: true } : {}) })).sort((a, b) => (Number(b.at) || 0) - (Number(a.at) || 0)) // lane: the Space it is a private lane of; lanes: a private assistant for every member (its link says so — never the link itself)
292
+ const publicRooms = () => publicVaultRooms(rooms, currentRoom)
271
293
 
272
294
  // ── the key worker ───────────────────────────────────────────────────────────────────────────────────────────────
273
295
  let worker = null, wseq = 0
296
+ const streamGrants = new Map()
297
+ const syncStream = workerStreams()
298
+ const applyStream = (w, room) => syncStream(w, room, streaming.has(room) ? { t: 'streamOpen', room, grants: streamGrants.get(room) } : null)
274
299
  const streaming = new Set() // rooms the page holds a live stream for (CALLS.stream); the socket lives in the worker
275
300
  const wwait = new Map()
276
301
  const signedIn = () => { const s = sdk.session; return !!(s && s.idToken && s.sign && !(s.exp && s.exp <= Date.now())) }
@@ -301,6 +326,11 @@ export async function startVault(o = {}) {
301
326
  const id = ++wseq
302
327
  wwait.set(id, { res, rej })
303
328
  try { target.postMessage({ id, ...msg }) } catch (err) { wwait.delete(id); rej(err) }
329
+ }).then(result => {
330
+ if (msg.t === 'op' && (msg.op === 'poll' || msg.op === 'pollSealed') && target === worker && held(msg.room) && result?.status === 200 && Array.isArray(result.streamGrants)) {
331
+ streamGrants.set(msg.room, result.streamGrants)
332
+ }
333
+ return result
304
334
  })
305
335
  }
306
336
  // a call waiting on a worker that is gone fails at once, named (a dead worker, a sign-out's new one): it can never be answered, and
@@ -362,14 +392,15 @@ export async function startVault(o = {}) {
362
392
  workerHost.replay('open', () => wcall({ t: 'open', room: null, mk: null, endpoint, app: o.app || 'vault', ...(o.tenant ? { tenant: o.tenant } : {}) }))
363
393
  workerHost.replay('links', async w => {
364
394
  for (const r of rooms) {
395
+ if (!currentRoom(r)) continue
365
396
  const p = linkParts(r.link)
366
397
  if (!p || p.room !== r.room) continue
367
398
  holdLink(w, p)
368
- if (p.split && r.mk && await keyCommit(r.mk).catch(() => '') === p.commit) w.postMessage({ t: 'remember', room: r.room, mk: r.mk })
399
+ if (p.split && r.mk && await keyCommit(r.mk).catch(() => '') === p.commit && currentRoom(r)) w.postMessage({ t: 'remember', room: r.room, mk: r.mk })
369
400
  seedIdentity(r.room)
370
401
  }
371
402
  })
372
- workerHost.replay('streams', (w) => { for (const room of streaming) w.postMessage({ t: 'streamOpen', room }) }) // a restarted worker (sign-out) picks the page's streams back up
403
+ workerHost.replay('streams', (w) => { for (const room of streaming) applyStream(w, room) }) // a restarted worker (sign-out) picks the page's streams back up
373
404
  workerHost.replay('pushSelf', (w) => { const e = vpush && vpush.endpoint(); if (e) w.postMessage({ t: 'setPushSelf', endpoint: e }) }) // this device's own posts do not tickle it
374
405
  workerHost.replay('pushAcct', (w) => { if (pushAcctSecret) w.postMessage({ t: 'setPushAcct', secret: pushAcctSecret }) }) // …nor its account's other devices (handDownPushAcct)
375
406
  workerHost.replay('prefetch', () => prefetchWorker())
@@ -406,9 +437,19 @@ export async function startVault(o = {}) {
406
437
  if (!worker) return
407
438
  worker.postMessage(enclaveMsg())
408
439
  }
409
- let encReady = null // one attestation at a time, shared
410
- const encAttest = (room) => (encReady ||= sdk._encAttest(room).then(() => { pushEnclave() }).finally(() => { encReady = null }))
440
+ const pendingAttestations = new Map()
441
+ const encAttest = (room) => {
442
+ const region = roomRegion(room)
443
+ if (!pendingAttestations.has(region)) {
444
+ const pending = sdk._encAttest(room).then(() => { pushEnclave() }).finally(() => pendingAttestations.delete(region))
445
+ pendingAttestations.set(region, pending)
446
+ }
447
+ return pendingAttestations.get(region)
448
+ }
411
449
  await startWorker()
450
+ if (pendingForget.size) {
451
+ await Promise.allSettled([...pendingForget].map(purgeForgotten))
452
+ }
412
453
  if (vlock) vlock.setWorker((m) => wcall(m)) // the lock's seal / unseal / relock / unprotect reach whichever worker is current
413
454
  // ── NOTIFICATIONS, opt-in twice (vaultCorePush.js; 2026-11-13): the builder starts the vault with `push: true`, the person turns
414
455
  // them on in the vault's card (wb.vault.showNotifications()). Subscribing a Space is the vault's own worker op — never a page op.
@@ -439,10 +480,10 @@ export async function startVault(o = {}) {
439
480
  if (tapRoom) { try { history.replaceState(null, '', location.pathname) } catch { /* */ } }
440
481
  const confirmWith = (q) => (typeof screens.confirm === 'function' ? screens.confirm(q) : Promise.resolve(window.confirm(q.text ? q.title + '\n\n' + q.text : q.title)))
441
482
  async function joinInvite() {
442
- if (!inv || rooms.some((r) => r.room === inv.room)) { if (inv) joined = inv.room; return } // already held: open it, keep its key
483
+ if (!inv || rooms.some((r) => r.room === inv.room && currentRoom(r))) { if (inv) joined = inv.room; return } // already held: open it, keep its key
443
484
  const ok = await confirmWith({ title: 'Join this Space?', text: 'Someone shared a Space with you. Join it on this device?', ok: 'Join', cancel: 'Not now' }).catch(() => false)
444
485
  if (!ok) return
445
- rooms = [{ room: inv.room, link: invLink, title: '', at: Date.now(), ...(/[?#&]enc=1(?:[&#?]|$)/.test(invLink) ? { enc: true } : {}), ...(inv.split ? { split: true } : {}) }, ...rooms]; await saveRooms()
486
+ rooms = [{ room: inv.room, ...joinedMark(inv.room), link: invLink, title: '', at: Date.now(), ...(/[?#&]enc=1(?:[&#?]|$)/.test(invLink) ? { enc: true } : {}), ...(inv.split ? { split: true } : {}) }, ...rooms]; await saveRooms()
446
487
  pushEnclave()
447
488
  holdLink(worker, inv); seedIdentity(inv.room); noteRoom(inv.room).catch(() => {})
448
489
  joined = inv.room
@@ -483,7 +524,7 @@ export async function startVault(o = {}) {
483
524
  const { genKeypair, spkNonce } = await import('./entrySig.js')
484
525
  const { brokerGoogleToken } = await import('./spaceEmailGate.js')
485
526
  const sign = await genKeypair(), nonce = await spkNonce(sign.pub)
486
- const result = await brokerGoogleToken({ nonce, broker: o.authBroker || 'https://auth.witbitz.chat' })
527
+ const result = await brokerGoogleToken({ nonce, watchPopup: false, broker: o.authBroker || 'https://auth.witbitz.chat' })
487
528
  if (sdk._session !== session) throw Object.assign(new Error('the account changed during sign-in'), { code: 'account_changed' })
488
529
  if (!result || !result.idToken || !result.email) throw Object.assign(new Error('Google sign-in was not completed'), { code: 'sign_in_cancelled' })
489
530
  const { jwtPayload } = await import('./emailSignIn.js')
@@ -500,7 +541,12 @@ export async function startVault(o = {}) {
500
541
 
501
542
  // ── the frame ────────────────────────────────────────────────────────────────────────────────────────────────────
502
543
  const frame = document.createElement('iframe')
503
- frame.src = pageUrl.href
544
+ let launchPage = pageUrl.href
545
+ if (inv && o.hostInviteTemplate && new URL(invLink).searchParams.get('hostInvite') === '1') {
546
+ const locator = new URL(invLink); locator.hash = ''; locator.search = ''; locator.searchParams.set('room', inv.room)
547
+ launchPage = embeddedInvite(o.hostInviteTemplate, locator.href, pageOrigin)
548
+ }
549
+ frame.src = launchPage
504
550
  frame.title = o.title || 'App'
505
551
  frame.setAttribute('allow', "clipboard-write; microphone; publickey-credentials-create 'src'; publickey-credentials-get 'src'")
506
552
  // No allow-top-navigation (security review): the page must not send the whole window — the vault — somewhere else.
@@ -514,6 +560,9 @@ export async function startVault(o = {}) {
514
560
  // (sync sweep 11-08 #28: only the message and code crossed); plain data only, bounded
515
561
  const errExtra = (err) => {
516
562
  const o = {}
563
+ if (err?.code === 'partial_revoke') for (const key of ['removedFrom', 'unchecked']) {
564
+ if (Array.isArray(err[key])) o[key] = err[key].filter(id => typeof id === 'string' && held(id)).slice(0, 1000)
565
+ }
517
566
  if (Array.isArray(err?.unavailable)) o.unavailable = err.unavailable.filter(id => typeof id === 'string' && id.length <= 160).slice(0, 1000)
518
567
  if (err && Number.isInteger(err.status)) o.status = err.status
519
568
  if (err?.code === 'wrong_pin' && Number.isSafeInteger(err.next) && err.next >= 0) o.next = err.next
@@ -523,7 +572,7 @@ export async function startVault(o = {}) {
523
572
  }
524
573
  const refuse = (id, error, code, extra = {}) => toPage({ t: 'res', id, error, code, ...extra })
525
574
 
526
- const held = (room) => typeof room === 'string' && rooms.some((r) => r.room === room)
575
+ const held = (room) => typeof room === 'string' && rooms.some((r) => r.room === room && currentRoom(r))
527
576
  let creates = [] // when this page last created Spaces (CREATE_LIMIT)
528
577
  let speechKeys = [] // when this page last asked for a speech key (SPEECH_LIMIT)
529
578
 
@@ -539,10 +588,33 @@ export async function startVault(o = {}) {
539
588
  const moved = tabs.moved(); if (!moved.length) return
540
589
  if (moved.includes(KEYS.connections)) conns = read(st, KEYS.connections, [])
541
590
  const w = who(); if (!w) return
542
- if (moved.includes(KEYS.siri)) { try { sdk.siri.restore((read(st, KEYS.siri, {}) || {})[w] || null) } catch { /* a malformed copy: keep ours */ } }
543
- if (moved.includes(KEYS.a2a)) { try { sdk.a2a.restore((read(st, KEYS.a2a, {}) || {})[w] || null) } catch { /* as above */ } }
591
+ if (moved.includes(KEYS.siri)) { try { const before = JSON.stringify(siriShortcut()); sdk.siri.restore((read(st, KEYS.siri, {}) || {})[w] || null); if (before !== JSON.stringify(siriShortcut())) emit({ ev: 'siri', siri: siriShortcut() }) } catch { /* a malformed copy: keep ours */ } }
592
+ if (moved.includes(KEYS.a2a)) { try { const before = JSON.stringify(sdk.a2a.state); sdk.a2a.restore((read(st, KEYS.a2a, {}) || {})[w] || null); if (before !== JSON.stringify(sdk.a2a.state)) emit({ ev: 'a2aChanged' }) } catch { /* as above */ } }
593
+ }
594
+ try { if (typeof addEventListener === 'function') addEventListener('storage', (e) => { if (e && (e.key === KEYS.connections || e.key === KEYS.connPending || e.key === KEYS.connGone || e.key === KEYS.siri || e.key === KEYS.a2a)) st.refresh(e.key).then(adoptOtherTab, adoptOtherTab) }) } catch { /* no window (a test) */ }
595
+ let removalWrites = Promise.resolve()
596
+ function connectionChange(acct, id, detached, expected) {
597
+ if (!acct || !id) return Promise.resolve()
598
+ const ownerEpoch = privacyEpoch
599
+ const update = async () => {
600
+ await st.refresh(KEYS.connGone)
601
+ if (privacyEpoch !== ownerEpoch) return
602
+ const all = read(st, KEYS.connGone, {}) || {}
603
+ const gone = { ...all[acct] }
604
+ if (expected !== undefined && gone[id] !== expected) return
605
+ if (detached) gone[id] = Math.max(Date.now(), (Number(gone[id]) || 0) + 1)
606
+ else delete gone[id]
607
+ if (Object.keys(gone).length) all[acct] = gone
608
+ else delete all[acct]
609
+ const saved = JSON.stringify(all)
610
+ st.setItem(KEYS.connGone, saved)
611
+ if (await st.durableItem(KEYS.connGone) !== saved) throw new Error('Could not save the connection removal')
612
+ }
613
+ const next = removalWrites.then(() => globalThis.navigator?.locks ? navigator.locks.request('wbvault:connection-removals', update) : update())
614
+ removalWrites = next.catch(() => {})
615
+ return next
544
616
  }
545
- try { if (typeof addEventListener === 'function') addEventListener('storage', (e) => { if (e && (e.key === KEYS.connections || e.key === KEYS.connPending || e.key === KEYS.siri || e.key === KEYS.a2a)) st.refresh(e.key).then(adoptOtherTab, adoptOtherTab) }) } catch { /* no window (a test) */ }
617
+ sdk.connections._bindingFor = (id, account) => conns.find(c => c.id === id && c.account === account)
546
618
  const saveConns = () => { put(KEYS.connections, conns); keepSoon() }
547
619
  // A CALL KEY WHOSE ATTACH ANSWER WAS LOST (sync sweep 2026-11-14 #5; state machines pass 9, N#7): the SDK keeps it PENDING in the store
548
620
  // set here while the answer is out (connections.js postWithPendingKey); a lost answer left a connection the account lists and no key
@@ -562,24 +634,35 @@ export async function startVault(o = {}) {
562
634
  pendingWrites = next.catch(() => {})
563
635
  return next
564
636
  }
565
- setPendingKeyStore({
637
+ sdk.connections._vaultPending = {
566
638
  durable: true,
567
639
  keep: (id, rec) => { const ownerEmail = who(); return updatePending(rows => { rows[id] = { ...rec, ownerEmail, at: Number(rec?.at) || Date.now() } }) },
568
640
  drop: id => updatePending(rows => { delete rows[id] }),
569
- })
570
- const adoptPending = async (listedIds, acct) => {
641
+ }
642
+ setPendingKeyStore(sdk.connections._vaultPending)
643
+ const adoptPending = async (listed, acct) => {
644
+ const byId = new Map(listed.filter(c => c?.id).map(c => [c.id, c]))
571
645
  const epoch = privacyEpoch, ownerEmail = who()
572
646
  await st.refresh(KEYS.connPending)
573
647
  if (epoch !== privacyEpoch || ownerEmail !== who()) return
574
648
  const snapshot = read(st, KEYS.connPending, {}) || {}
575
649
  const eligible = Object.fromEntries(Object.entries(snapshot).filter(([, k]) => !k?.ownerEmail || k.ownerEmail === ownerEmail))
576
- const r = adoptPendingKeys(eligible, listedIds, {})
650
+ const r = adoptPendingKeys(eligible, [...byId.keys()], {})
577
651
  for (const [id, k] of r.adopt) {
578
652
  if (!conns.some(c => c.account === acct && c.id === id && c.callKey)) {
579
- conns = [{ id, label: k.label || '', host: k.host || '', callKey: k.callKey, account: acct }, ...conns]
653
+ const row = byId.get(id)
654
+ conns = [{ id, label: row.label || k.label || '', host: row.host || k.host || '', callKey: k.callKey, account: acct, ...(row.mcp ? { mcp: true } : {}), ...(row.provider ? { provider: row.provider } : {}), ...hookOf(row) }, ...conns]
580
655
  }
581
656
  }
582
- if (r.adopt.length) saveConns()
657
+ let changed = false
658
+ conns = conns.map(c => {
659
+ const row = c.account === acct && byId.get(c.id)
660
+ if (!row) return c
661
+ const next = { ...c, mcp: !!row.mcp, label: row.label || c.label || '', host: row.host || c.host || '', ...(row.provider ? { provider: row.provider } : {}), ...hookOf(row) }
662
+ if (JSON.stringify(next) !== JSON.stringify(c)) changed = true
663
+ return next
664
+ })
665
+ if (changed || r.adopt.length) saveConns()
583
666
  let durable
584
667
  try { durable = JSON.parse(await st.durableItem(KEYS.connections) || '[]') } catch { return }
585
668
  if (epoch !== privacyEpoch || ownerEmail !== who() || !Array.isArray(durable)) return
@@ -587,7 +670,7 @@ export async function startVault(o = {}) {
587
670
  if (epoch !== privacyEpoch || ownerEmail !== who()) return
588
671
  for (const [id, rec] of Object.entries(eligible)) {
589
672
  if (r.pending[id] || JSON.stringify(pending[id]) !== JSON.stringify(rec)) continue
590
- if (listedIds.includes(id) && !durable.some(c => c.account === acct && c.id === id && c.callKey === rec?.callKey)) continue
673
+ if (byId.has(id) && !durable.some(c => c.account === acct && c.id === id && c.callKey === rec?.callKey)) continue
591
674
  delete pending[id]
592
675
  }
593
676
  })
@@ -595,16 +678,95 @@ export async function startVault(o = {}) {
595
678
  // Siri's state (the inbox private keys) is kept PER ACCOUNT: a second person signing in on this vault never gets the
596
679
  // first one's keys, and the first one's come back when they sign in again.
597
680
  const who = () => (signedIn() ? String(sdk.session.email || '').toLowerCase() : '')
681
+ // The remote inbox must never receive a public key before the matching secret survives a reload.
682
+ const stageInbox = key => async candidate => {
683
+ const owner = who(), epoch = privacyEpoch
684
+ if (!owner) throw Object.assign(new Error('Sign in to save this inbox'), { code: 'sign_in_required' })
685
+ const pending = 'pending:' + owner
686
+ const records = read(st, key, {}) || {}
687
+ const entry = { base: records[owner] || null, next: candidate }
688
+ const serialized = JSON.stringify(entry)
689
+ put(key, { ...records, [pending]: entry })
690
+ const disk = JSON.parse(await st.durableItem(key) || '{}')
691
+ if (owner !== who() || epoch !== privacyEpoch) throw Object.assign(new Error('Account changed during inbox setup'), { code: 'account_changed' })
692
+ if (JSON.stringify(disk[pending]) !== serialized) throw Object.assign(new Error('Could not save the inbox key on this device'), { code: 'save_failed' })
693
+ return accepted => {
694
+ if (owner !== who() || epoch !== privacyEpoch) return
695
+ const latest = read(st, key, {}) || {}
696
+ if (JSON.stringify(latest[pending]) !== serialized) return
697
+ if (accepted) latest[owner] = candidate
698
+ delete latest[pending]
699
+ put(key, latest)
700
+ }
701
+ }
702
+ sdk.siri._stageInbox = stageInbox(KEYS.siri)
703
+ sdk.a2a._stageInbox = stageInbox(KEYS.a2a)
704
+ function recoverInbox(key, owner) {
705
+ const pending = 'pending:' + owner, records = read(st, key, {}) || {}
706
+ const entry = records[pending], committed = records[owner] || null
707
+ if (!entry) return committed
708
+ const api = key === KEYS.siri ? sdk.siri : sdk.a2a
709
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
710
+ // Reapply the user's edit only where the value it replaced is still current.
711
+ const applyEdit = (before, after, current) => {
712
+ if (same(before, after) || same(after, current)) return current
713
+ if (same(before, current)) return after
714
+ if (Array.isArray(before) && Array.isArray(after) && Array.isArray(current) && [...before, ...after, ...current].every(peer => typeof peer?.id === 'string')) {
715
+ const earlier = new Map(before.map(peer => [peer.id, peer])), edits = new Map(after.map(peer => [peer.id, peer]))
716
+ const result = current.map(peer => applyEdit(earlier.get(peer.id), edits.get(peer.id), peer)).filter(Boolean)
717
+ const seen = new Set(current.map(peer => peer.id))
718
+ for (const peer of after) if (!earlier.has(peer.id) && !seen.has(peer.id)) result.push(peer)
719
+ return result
720
+ }
721
+ if (!after || !current || typeof after !== 'object' || typeof current !== 'object' || Array.isArray(current) || Array.isArray(after)) return current
722
+ if (after.pub && current.pub && !same(after.pub, current.pub)) return current
723
+ const out = { ...current }
724
+ for (const k of new Set([...Object.keys(before || {}), ...Object.keys(after)])) {
725
+ const value = applyEdit(before?.[k], after[k], current[k])
726
+ if (value === undefined) delete out[k]; else out[k] = value
727
+ }
728
+ return out
729
+ }
730
+ const replay = async () => {
731
+ const epoch = privacyEpoch
732
+ const get = () => read(st, key, {}) || {}
733
+ const unchanged = () => who() === owner && privacyEpoch === epoch && JSON.stringify(get()[pending]) === JSON.stringify(entry)
734
+ if (!unchanged()) return
735
+ for (let attempt = 0; attempt < 3 && unchanged(); attempt++) {
736
+ const current = get()[owner] || null
737
+ if (key === KEYS.siri && entry.next && ((current?.rev || 0) > (entry.base?.rev || 0) || (entry.base?.token && current?.token && entry.base.token !== current.token) || ((entry.base?.token || entry.base?.tokenHash) && !current?.token && !current?.tokenHash))) {
738
+ const kept = get(); delete kept[pending]; put(key, kept); return
739
+ }
740
+ const next = applyEdit(entry.next ? entry.base : committed, entry.next || entry, current)
741
+ if (!next) return
742
+ try {
743
+ await api._push(next)
744
+ } catch (error) {
745
+ if (unchanged() && error.definiteRefusal) { const kept = get(); delete kept[pending]; put(key, kept) }
746
+ return
747
+ }
748
+ if (!unchanged()) return
749
+ const kept = get()
750
+ if (!same(kept[owner] || null, current)) continue
751
+ kept[owner] = next; delete kept[pending]; put(key, kept)
752
+ api.restore(next); keepSoon()
753
+ emit(key === KEYS.siri ? { ev: 'siri', siri: siriShortcut() } : { ev: 'a2aChanged' })
754
+ return
755
+ }
756
+ }
757
+ api._q = (api._q || Promise.resolve()).then(replay, replay).catch(() => {})
758
+ return committed
759
+ }
598
760
  const saveSiri = () => { const w = who(); if (!w) return; const all = read(st, KEYS.siri, {}); all[w] = sdk.siri.state; put(KEYS.siri, all); keepSoon() }
599
761
  const saveA2A = () => { const w = who(); if (!w) return; const all = read(st, KEYS.a2a, {}); all[w] = sdk.a2a.state; put(KEYS.a2a, all); keepSoon() }
600
762
  // ── THE SAME THREE ON EVERY DEVICE OF THE ACCOUNT (vaultKeep.js; sync sweep 2026-11-11 P7): a second device listed this account's
601
763
  // connections but could not use one (`not_in_vault`), and could not open Siri or an outside agent's message. Synced, sealed,
602
764
  // through the account's index room — only while the backup is on (it is what derives that room). One pass at a time; a pass
603
765
  // that finds another account signed in when it lands keeps nothing.
604
- let keepT = null, keepRun = null, keepAgain = 0, keepMoved = null
766
+ let keepRevision = 0, keepT = null, keepRun = null, keepAgain = 0, keepMoved = null
605
767
  const KEEP_AGAIN_MAX = 3 // passes in a row for a vault that changed while one was out; past it the minute's pass takes over
606
768
  let lastKeepFailure = null
607
- function keepSoon (ms = 1500) { clearTimeout(keepT); keepT = setTimeout(() => { keepSync().catch(() => {}) }, ms) }
769
+ function keepSoon (ms = 1500) { keepRevision++; clearTimeout(keepT); keepT = setTimeout(() => { keepSync().catch(() => {}) }, ms) }
608
770
  async function keepSync () {
609
771
  if (keepRun) return keepRun
610
772
  const owner = who(), master = sdk.backup._s?.master
@@ -623,14 +785,24 @@ export async function startVault(o = {}) {
623
785
  // save the next pass deleted the other devices' connections, Siri and outside agents on every device — and applied over
624
786
  // a connection attached meanwhile.
625
787
  keepMoved = null
626
- const p = await keepPass({ loc, client: sdk._client, prev, read: () => { adoptOtherTab(); return { conns: conns.filter((c) => c.account === acct), siri: sdk.siri.state, a2a: sdk.a2a.state } },
788
+ await removalWrites
789
+ await st.refresh(KEYS.connGone)
790
+ if (who() !== w) return { ok: false, why: 'moved' }
791
+ const p = await keepPass({ loc, client: sdk._client, prev, read: () => { adoptOtherTab(); return { connGone: read(st, KEYS.connGone, {})?.[acct] || {}, conns: conns.filter((c) => c.account === acct), siri: sdk.siri.state, a2a: sdk.a2a.state } },
627
792
  settle: (p) => { // in keepPass's own step, right after it looked at the stores: no attach or detach can land in between
628
793
  if (who() !== w || !p.record) return
629
- if (p.apply) applyKeep(acct, p.apply) // into the stores FIRST: were it to throw, `prev` stays what the stores hold
794
+ if (p.apply) {
795
+ applyKeep(acct, p.apply)
796
+ const pending = read(st, KEYS.connGone, {})?.[acct] || {}
797
+ for (const [id, at] of Object.entries(pending)) {
798
+ const tomb = p.record.conns?.[id]
799
+ if (tomb?.gone && tomb.at >= at) connectionChange(acct, id, false, at).catch(() => keepSoon())
800
+ }
801
+ } // into the stores FIRST: were it to throw, `prev` stays what the stores hold
630
802
  const all2 = read(st, KEYS.keep, {}) || {}; all2[w] = p.record; write(st, KEYS.keep, all2)
631
803
  } })
632
804
  if (who() !== w) return { ok: false, why: 'moved' }
633
- const ch = keepMoved; keepMoved = null; if (ch) pushAfterApply(w, ch) // what the apply moved at the Sentinel's side (K#8)
805
+ const ch = keepMoved; keepMoved = null; await pushAfterApply(w, ch) // what the apply moved at the Sentinel's side (K#8)
634
806
  if (p.again && keepAgain < KEEP_AGAIN_MAX) { keepAgain++; keepSoon(300) } else if (!p.again) keepAgain = 0 // what changed meanwhile: now, not at the minute
635
807
  return p
636
808
  })()
@@ -653,27 +825,44 @@ export async function startVault(o = {}) {
653
825
  // delete would have granted the old key again).
654
826
  const a2aSent = () => { try { return JSON.stringify(Object.entries(sdk.a2a._s.lanes).sort(([a], [b]) => (a < b ? -1 : 1)).map(([room, l]) => [room, l.handle, l.name, l.description, l.pub, l.peers.map((p) => [p.id, p.tokenHash, p.reply, !!p.job])])) } catch { return '' } }
655
827
  const siriSent = () => { try { const s = sdk.siri.state; return JSON.stringify([s.token, s.defaultRoom, Object.entries(s.rooms).sort(([a], [b]) => (a < b ? -1 : 1)).map(([r, v]) => [r, v.alias, v.label, v.pub])]) } catch { return '' } }
656
- function pushAfterApply (w, ch) { // after the pass, never inside it: the answer is the Sentinel's, the keep is already settled
828
+ async function pushAfterApply (w, ch) { // after the pass, never inside it: the answer is the Sentinel's, the keep is already settled
657
829
  if (who() !== w) return
658
- if (ch.a2a) sdk.a2a._push().catch(() => { /* the next change, or the next apply that moves it, pushes again */ })
659
- if (ch.siri) {
660
- if (sdk.siri.state.token) sdk.siri._push().catch(() => { /* as above */ })
661
- else if (ch.hadKey) sdk.siri.revoke().then(() => saveSiri(), () => { /* as above */ })
830
+ const byOwner = read(st, KEYS.pendingGrants, {}) || {}
831
+ const previous = byOwner[w] || {}
832
+ const pending = { a2a: previous.a2a || !!ch?.a2a, siri: previous.siri || !!ch?.siri, hadKey: previous.hadKey || !!(ch?.siri && ch.hadKey) }
833
+ if (!pending.a2a && !pending.siri) return
834
+ const save = () => {
835
+ const all = read(st, KEYS.pendingGrants, {}) || {}
836
+ if (pending.a2a || pending.siri) all[w] = { ...pending }; else delete all[w]
837
+ write(st, KEYS.pendingGrants, all)
662
838
  }
839
+ save(); await st.flushed()
840
+ if (who() !== w) return
841
+ if (pending.a2a) { try { await sdk.a2a._push(); pending.a2a = false } catch { /* retry on the next account sync */ } }
842
+ if (who() !== w) return
843
+ if (pending.siri) {
844
+ try {
845
+ if (sdk.siri.state.token || sdk.siri.state.tokenHash) await sdk.siri._push()
846
+ else if (pending.hadKey) { await sdk.siri.revoke(); if (who() === w) saveSiri() }
847
+ pending.siri = false
848
+ } catch { /* retry on the next account sync */ }
849
+ }
850
+ if (who() === w) { save(); if (pending.siri || pending.a2a) keepSoon(30000) }
663
851
  }
664
852
  function applyKeep (acct, keep) { // the merged view into this vault — written straight to storage (no new stamp: it IS the merged state)
665
853
  const v = viewOfKeep(keep), w = who()
666
854
  const was = { a2a: a2aSent(), siri: siriSent(), hadKey: !!sdk.siri.state.token }
667
855
  conns = [...v.conns.map((c) => ({ ...c, account: acct })), ...conns.filter((c) => c.account !== acct)]
668
856
  put(KEYS.connections, conns)
669
- if (v.siri) { try { sdk.siri.restore(v.siri); const all = read(st, KEYS.siri, {}); all[w] = sdk.siri.state; put(KEYS.siri, all) } catch { /* a malformed copy: keep ours */ } }
670
- try { sdk.a2a.restore(v.a2a); const all = read(st, KEYS.a2a, {}); all[w] = sdk.a2a.state; put(KEYS.a2a, all) } catch { /* as above */ }
857
+ if (v.siri) { try { const hadKey = !!sdk.siri.shortcut.key; sdk.siri.restore(v.siri); if (hadKey !== !!sdk.siri.shortcut.key) emit({ ev: 'siri', siri: siriShortcut() }); const all = read(st, KEYS.siri, {}); all[w] = sdk.siri.state; put(KEYS.siri, all) } catch { /* a malformed copy: keep ours */ } }
858
+ const priorA2A = JSON.stringify(sdk.a2a.state)
859
+ try { sdk.a2a.restore(v.a2a); if (JSON.stringify(sdk.a2a.state) !== priorA2A) emit({ ev: 'a2aChanged' }); const all = read(st, KEYS.a2a, {}); all[w] = sdk.a2a.state; put(KEYS.a2a, all) } catch { /* as above */ }
671
860
  keepMoved = { a2a: a2aSent() !== was.a2a, siri: siriSent() !== was.siri, hadKey: was.hadKey } // read by keepSync after the pass (K#8)
672
861
  }
673
862
  const loadSiri = () => { // and A2A's: the same rule
674
863
  const w = who()
675
- sdk.siri.restore(w ? (read(st, KEYS.siri, {}) || {})[w] || null : null)
676
- sdk.a2a.restore(w ? (read(st, KEYS.a2a, {}) || {})[w] || null : null)
864
+ sdk.siri.restore(w ? recoverInbox(KEYS.siri, w) : null)
865
+ sdk.a2a.restore(w ? recoverInbox(KEYS.a2a, w) : null)
677
866
  // and the account's INVITE KEY for this vault's app (sdkRekey.js): kept here, never shown to the page; published once per launch
678
867
  const inv = w ? (read(st, KEYS.invite, {}) || {})[w] || null : null
679
868
  if (inv) { try { sdk.invite.restore(inv) } catch { /* a malformed copy: the next sign-in publishes a fresh one */ } }
@@ -698,14 +887,17 @@ export async function startVault(o = {}) {
698
887
  for (const x of Array.isArray(r.items) ? r.items : []) { const o = await openItem(c, x); if (o) result.push({ taskId: x.taskId, n: x.n, m: o.m, peer: { id: o.peer.id, name: o.peer.name, reply: o.peer.reply, ...(o.peer.job ? { job: true } : {}), ...(o.peer.own ? { own: true } : {}) } }) }
699
888
  }
700
889
  } else if (m === 'ack') { const a = args[0] || {}; result = await sdk.a2a._plain('a2aack', { items: [{ taskId: String(a.taskId || ''), n: Number(a.n) || 0 }] }) }
701
- else if (m === 'reply') result = await shim.reply(args[0], args[1], args[2] || {})
890
+ else if (m === 'reply') {
891
+ const id = args[2]?.autoPeerId
892
+ result = id && !shim.peers.some(p => p.id === id && p.reply === 'auto') ? { held: true } : await shim.reply(args[0], args[1], args[2] || {})
893
+ }
702
894
  else result = await shim[m](...args)
703
895
  // THE TOKEN STAYS IN THE VAULT (sync sweep 2026-11-14 #3): it is the outside agent's bearer for as long as it lives, so it is shown
704
896
  // once on the vault's own screen and the page gets the id only — as the Siri key (siriShortcut) and the hosted vault (vaultPeerTokens.js)
705
897
  if (m === 'addPeer' && result) {
706
898
  const v = a2aView(room), show = await screenFor('peerToken')
707
899
  if (show && result.token) await show({ name: String(args[0] || ''), token: result.token, ...(v && v.handle ? { cardUrl: cardUrlOf(v.endpoint, v.handle), mcpUrl: mcpUrlOf(v.endpoint, v.handle) } : {}) })
708
- result = { id: result.id, token: null, shown: !!(show && result.token) }
900
+ result = { id: result.id, ...(Array.isArray(result.moved) ? { moved: result.moved.map(({ source, id }) => ({ source, id })) } : {}), token: null, shown: !!(show && result.token), ...(result.roomListPending ? { roomListPending: true } : {}) }
709
901
  }
710
902
  else if (result && typeof result === 'object' && 'cardUrl' in result) result = {}
711
903
  saveA2A()
@@ -745,7 +937,7 @@ export async function startVault(o = {}) {
745
937
  const p = (async () => {
746
938
  const g = await wcall({ t: 'op', op: 'grant', room, args: [] }).catch(() => null)
747
939
  const it0 = rooms.find((x) => x.room === room)
748
- const k = await openGrant(g, room, sdk.invite._key(), { gated: !!(it0 && /[#&]gate=email(?:&|$)/.test(String(it0.link || ''))) }) // a link Space: 'link_changed', never 'removed'
940
+ const k = await openGrant(g, room, sdk.invite._key(), { gated: !!(it0 && roomInviteFlags(it0.link).gated) }) // a link Space: 'link_changed', never 'removed'
749
941
  if (k.removed || k.wait) {
750
942
  const why = k.removed ? 'removed' : k.wait
751
943
  const was = keyWaits.get(room); keyWaits.set(room, { at: Date.now(), why })
@@ -754,7 +946,7 @@ export async function startVault(o = {}) {
754
946
  }
755
947
  if (k.userShare) await wcall({ t: 'rememberSplit', room, userShare: k.userShare, commit: k.commit, ep: k.epoch })
756
948
  else await wcall({ t: 'remember', room, mk: k.mk, ep: k.epoch })
757
- keyWaits.delete(room); relinkRoom(room, k)
949
+ streamGrants.delete(room); keyWaits.delete(room); relinkRoom(room, k)
758
950
  emit({ ev: 'key', room, kind: 'rekeyed', epoch: k.epoch })
759
951
  return true
760
952
  })().catch(() => false).finally(() => keyAdopting.delete(room))
@@ -768,7 +960,7 @@ export async function startVault(o = {}) {
768
960
  const learnTier = (room, r) => {
769
961
  if (!room || !saysConfidential(r)) return
770
962
  const it = rooms.find((x) => x.room === room); if (!it || it.enc) return
771
- it.enc = true; saveRooms(); try { pushEnclave() } catch { /* the next op re-sends the snapshot */ }
963
+ it.enc = true; saveRooms(); noteRoom(room).catch(() => {}); emit({ ev: 'rooms', rooms: publicRooms() }); try { pushEnclave() } catch { /* the next op re-sends the snapshot */ }
772
964
  }
773
965
  const opHealed = async (op, room, args) => {
774
966
  const r = await wcall({ t: 'op', op, room, args })
@@ -781,9 +973,13 @@ export async function startVault(o = {}) {
781
973
  // bridge to its shared room and none of the lane's actions or links. Keyless both ways — the worker holds both keys.
782
974
  const roomSpace = (room) => {
783
975
  const it = rooms.find((x) => x.room === room)
784
- if (it && it.lane) return new Lane(workerClient, { room, mk: null, link: null, wb: sdk, live: false, poll: false, sharedRoom: it.lane, sharedMk: null })
785
- return new Space(workerClient, { room, mk: null, link: null, wb: sdk, live: false, poll: false })
976
+ const sp = it?.lane ? new Lane(workerClient, { room, mk: null, link: null, wb: sdk, live: false, poll: false, sharedRoom: it.lane, sharedMk: null })
977
+ : new Space(workerClient, { room, mk: null, link: null, wb: sdk, live: false, poll: false })
978
+ if (it?.title) sp._title = { title: it.title }
979
+ return sp
786
980
  }
981
+ sdk._scopedRoom = roomSpace
982
+ sdk._siriLane = room => rooms.find(r => r.lane === room && !r.detachedLane)?.room
787
983
  sdk._agentRoom = roomSpace
788
984
  sdk._keepAgentConnection = async (conn, ownLink) => {
789
985
  const session = sdk._session
@@ -792,7 +988,7 @@ export async function startVault(o = {}) {
792
988
  conns = [{ ...conn, account, ownLink }, ...conns.filter((c) => c.id !== conn.id || c.account !== account)]
793
989
  saveConns()
794
990
  }
795
- sdk._forgetAgentConnection = async (id) => { const session = sdk._session, account = await sdk._account(); if (sdk._session !== session) throw Object.assign(new Error('the account changed during assistant cleanup'), { code: 'account_changed' }); conns = conns.filter((c) => c.id !== id || c.account !== account); saveConns() }
991
+ sdk._forgetAgentConnection = async (id) => { const session = sdk._session, account = await sdk._account(); if (sdk._session !== session) throw Object.assign(new Error('the account changed during assistant cleanup'), { code: 'account_changed' }); await connectionChange(account, id, true); conns = conns.filter((c) => c.id !== id || c.account !== account); saveConns() }
796
992
  const wop = (op, room, ...args) => opHealed(op, room, args)
797
993
  // ── a move (fork): the SDK's own fork(), run HERE over the worker — it needs the room's key (the new room's goes in the
798
994
  // notice, sealed to each keeper's device) and the session's signing key, both the vault's
@@ -805,7 +1001,6 @@ export async function startVault(o = {}) {
805
1001
  if (!signedIn()) throw Object.assign(new Error('vault: sign in first'), { code: 'sign_in_required' })
806
1002
  const it = rooms.find((x) => x.room === room)
807
1003
  const parts = linkParts(it.link) || {}
808
- const emails = rotate ? [] : (admission && Array.isArray(admission.emails) ? admission.emails : []).map((x) => String(x).slice(0, 80))
809
1004
  const sp = new Space(keyedClient, { room, mk: parts.mk || null, link: it.link, wb: sdk, live: false, poll: false, gated: true, split: !!parts.split }) // a split room: no key here — the worker holds it
810
1005
  if (!rotate) { try { await assertNotKept(sp) } catch (e) { sp.close(); throw e } }
811
1006
  // A SLEEPING CONFIDENTIAL SPACE (sweep 10-25 #1): the SDK wakes one before its first read only when its OWN enclave list
@@ -822,16 +1017,24 @@ export async function startVault(o = {}) {
822
1017
  let plan = null
823
1018
  try { plan = rotate ? null : await planMembers(sp, admission, cur && cur.cfg) } catch (e) { sp.close(); throw e }
824
1019
  const roleOnly = !!(plan && plan.roles)
1020
+ const summary = plan ? [
1021
+ 'Members: ' + plan.emails.join(', '),
1022
+ 'Domains: ' + ((plan.m.allow.domains || []).join(', ') || 'none'),
1023
+ 'Owners: ' + (plan.want.owners.join(', ') || 'none'),
1024
+ 'Admins: ' + (plan.want.admins.join(', ') || 'none'),
1025
+ ...(plan.m.allow.users?.length ? ['Usernames: ' + plan.m.allow.users.map(u => u.handle).join(', ')] : []),
1026
+ ...(plan.m.allow.mh?.length ? ['Private membership entries: ' + plan.m.allow.mh.length] : []),
1027
+ ].join('\n') : ''
825
1028
  const ok = await confirmWith(roleOnly
826
- ? { title: 'Change who manages ' + titleOf(room) + '?', text: 'Its members stay the same, and so does its key: only who may manage it changes.', ok: 'Change', cancel: 'Cancel' }
1029
+ ? { title: 'Change who manages ' + titleOf(room) + '?', text: summary, ok: 'Change', cancel: 'Cancel' }
827
1030
  : rotate
828
1031
  ? { title: 'Change the key of ' + titleOf(room) + '?', text: 'Everyone in it gets the new key. A copy of the old key opens nothing written from now on.', ok: 'Change the key', cancel: 'Cancel' }
829
- : { title: 'Change the members of ' + titleOf(room) + '?', text: 'Its members will be: ' + (emails.slice(0, 6).join(', ') || 'only you') + (emails.length > 6 ? ' and ' + (emails.length - 6) + ' more' : '') + '. Anyone else can no longer read what is written from now on.', ok: 'Change', cancel: 'Cancel' }).catch(() => false)
1032
+ : { title: 'Change the members of ' + titleOf(room) + '?', text: summary, ok: 'Change', cancel: 'Cancel' }).catch(() => false)
830
1033
  if (!ok) { sp.close(); throw Object.assign(new Error('cancelled'), { code: 'cancelled' }) }
831
1034
  try {
832
- const r = rotate ? await rotateKey(sp) : await changeMembers(sp, admission)
1035
+ const r = rotate ? await rotateKey(sp) : await changeMembers(sp, admission, plan)
833
1036
  it.link = sp.shareLink; saveRooms(); noteRoom(room).catch(() => {})
834
- if (!r.roles) emit({ ev: 'key', room, kind: 'rekeyed', epoch: r.epoch })
1037
+ if (!r.roles) { streamGrants.delete(room); emit({ ev: 'key', room, kind: 'rekeyed', epoch: r.epoch }) }
835
1038
  const { link: _l, ...out } = r // the link carries the key: the page asks for it with share()
836
1039
  return out
837
1040
  } finally { sp.close() }
@@ -874,7 +1077,7 @@ export async function startVault(o = {}) {
874
1077
  if (gv !== 'keeps') { await wcall({ t: 'forget', room: o.room }).catch(() => null); return gv === 'unreadable' ? { refused: 'the new room could not be read yet — try again', code: 'unreadable' } : { refused: 'the new room\'s owners or admins are not what the move declared' } }
875
1078
  }
876
1079
  const was = rooms.find((x) => x.room === room)
877
- rooms = [{ room: o.room, link: o.link, title: (was && was.title) || '', at: Date.now(), ...(lp.split ? { split: true } : {}) }, ...rooms]; saveRooms(); noteRoom(o.room).catch(() => {})
1080
+ rooms = [{ room: o.room, ...joinedMark(o.room), link: o.link, title: (was && was.title) || '', at: Date.now(), ...(lp.split ? { split: true } : {}) }, ...rooms]; saveRooms(); noteRoom(o.room).catch(() => {})
878
1081
  emit({ ev: 'rooms', rooms: publicRooms() })
879
1082
  return { room: o.room }
880
1083
  }
@@ -892,7 +1095,7 @@ export async function startVault(o = {}) {
892
1095
  if (!r || r.status !== 200 || sessionKeyId() !== identity || !held(room)) return { announced: false }
893
1096
  const { roster, changed } = ensureSelf(r.state, self)
894
1097
  if (!changed && !unseenIn(r.seen, self.id) && !entriesMissing(r.seen, self.id, room)) { announced.add(whoKey); return { announced: true } } // entries: one more announce per page, never retried
895
- const written = await wop('state', room, ROSTER_DOC, { people: roster }, '', 'member', r.v || 0).catch(() => null)
1098
+ const written = await wop('state', room, ROSTER_DOC, Array.isArray(r.state) ? roster : { people: roster }, '', 'member', r.v || 0).catch(() => null) // the shape the room already has (witbitz-sdk.js _announce says why)
896
1099
  if (written?.status === 409) continue
897
1100
  if (written?.status !== 200) return { announced: false }
898
1101
  announcedIn(room, self.id)
@@ -906,20 +1109,21 @@ export async function startVault(o = {}) {
906
1109
  const confirmCall = async (ns, m, args, room, kept = false) => {
907
1110
  const a = args[0], q = {
908
1111
  'portable.export': { title: 'Download this Space?', text: 'The unencrypted JSON file contains this Space’s conversation, attachments and settings.', ok: 'Download' },
909
- 'backup.exportArchive': a === true ? { title: 'Download recovery keys?', text: 'Anyone with these keys can read the archived conversations. Store this file separately from the archive.', ok: 'Download keys' } : { title: 'Download encrypted conversations?', text: 'The file contains the encrypted ledgers for this account. Download the keys separately to read them offline.', ok: 'Download' },
1112
+ 'backup.exportArchive': a === true && args[2] === 'clipboard' ? { title: 'Copy recovery keys?', text: 'Anyone with access to the clipboard can read these Spaces with their archives. Paste the keys into your password manager.', ok: 'Copy keys' } : a === true ? { title: 'Download recovery keys?', text: 'Anyone with these keys can read the archived conversations. Store this file separately from the archive.', ok: 'Download keys' } : { title: 'Download encrypted conversations?', text: 'The file contains the encrypted ledgers for this account. Download the keys separately to read them offline.', ok: 'Download' },
910
1113
  'connections.detach': { title: 'Remove this connection?', text: 'Every Space that uses it stops being able to.', ok: 'Remove' },
911
1114
  'usernames.claim': { title: 'Take the username @' + String(a || '').replace(/^@/, '').slice(0, 40) + '?', text: (args[1] && args[1].publish) ? 'It will be listed, so people can find you by it.' : 'It is yours until you release it.', ok: 'Take it' },
912
1115
  'usernames.release': { title: 'Release your username?', text: 'Someone else may take it.', ok: 'Release' },
913
1116
  'siri.rotateKey': { title: 'Make a new Siri key?', text: 'The Shortcut stops working until you give it the new key.', ok: 'New key' },
914
1117
  'siri.revoke': { title: 'Turn the Siri inbox off?', text: 'Siri stops delivering to every Space.', ok: 'Turn off' },
915
- 'a2a.addPeer': { title: 'Let the outside agent “' + String(a || '').slice(0, 40) + '” reach this lane?', text: (args[1] && args[1].job === true) ? 'An agent that takes jobs: it reports here and reads no answer — its reports are told to you.' : (kept || args[1]?.reply === 'auto') ? 'Its messages will be answered by the assistant on its own, without asking you.' : 'You approve every answer before it is sent.', ok: 'Allow' }, // a job agent reads no answers (sweep 10-25 #9)
1118
+ 'a2a.addPeer': { title: (args[1]?.reconnect || args[1]?.previousPeerId) ? 'Move this outside agent here and replace its previous pairing?' : 'Let the outside agent “' + String(a || '').slice(0, 40) + '” reach this lane?', text: (args[1] && args[1].job === true) ? 'An agent that takes jobs: it reports here and reads no answer — its reports are told to you.' : (kept || args[1]?.reply === 'auto') ? 'Its messages will be answered by the assistant on its own, without asking you.' : 'You approve every answer before it is sent.', ok: 'Allow' }, // a job agent reads no answers (sweep 10-25 #9)
1119
+ 'a2a.stopJobAgent': { title: 'Disconnect this job agent?', text: 'Remove every pairing for ' + String(a || '').slice(0, 80) + ' on this account.', ok: 'Disconnect' },
916
1120
  'a2a.revoke': { title: 'Turn outside agents off?', text: 'Every lane\'s card and every agent\'s token stop working.', ok: 'Turn off' },
917
1121
  'backup.remove': { title: 'Remove ' + titleOf(a) + ' from your account?', text: 'It goes from every device that keeps this account.', ok: 'Remove' },
918
1122
  'account.forget': { title: 'Remove ' + titleOf(a) + ' from your account?', text: 'It goes from every device that keeps this account.', ok: 'Remove' },
919
1123
  // on the account service it is revoked at once, after the emailed code (accountCall's signOut, 94c06f12b); else it is marked in
920
1124
  // the index — either way it forgets the account the next time it is online (sync sweep 11-22 #17: it said "at its next sync")
921
- 'account.signOut': { title: 'Sign that device out of your account?', text: (revokesAtService(a) ? 'It is signed out of your account at once — we email you a code to confirm — and forgets ' : 'It forgets your account and ') + 'your Spaces the next time it is online.', ok: 'Sign out' },
922
- 'backup.signOutOthers': { title: 'Sign out all your other devices?', text: 'Every other device forgets your account and its Spaces the next time it opens. This device stays signed in. We email you a code to confirm.', ok: 'Sign them out' },
1125
+ 'account.signOut': { title: 'Sign that device out of your account?', text: (revokesAtService(a) ? 'It is signed out of your account at once — we email you a code to confirm — and forgets ' : 'It forgets your account and ') + 'your Spaces the next time it is online.' + recoveryNotice(), ok: 'Sign out' },
1126
+ 'backup.signOutOthers': { title: 'Sign out all your other devices?', text: 'Every other device forgets your account and its Spaces the next time it opens. This device stays signed in. We email you a code to confirm.' + recoveryNotice(), ok: 'Sign them out' },
923
1127
  'backup.newRecoveryCode': { title: 'Make a new recovery code?', text: 'Your current code stops working, and every other device is signed out. We email you a code to confirm, then show the new recovery code once.', ok: 'New code' },
924
1128
  'backup.migrate': a?.silent === true || sdk.backup._s?.v2?.moveMode === 'signed' ? { title: 'Move this account with its signing key?', text: 'Your Spaces and recovery code stay the same. Other eligible devices can join using their existing account keys.', ok: 'Move account' } : { title: 'Move to the new account service?', text: 'Your Spaces and recovery code stay the same. Other devices are signed out and can restore on the new service. This legacy backup has no account key, so it moves with email-only trust; Advanced Backup remains unavailable.', ok: 'Move account' },
925
1129
  'cloudDevice.enroll': { title: 'Sign the cloud device in?', text: 'We email a code so this secure cloud device can sign in to this app’s account. No Space is handed over yet.', ok: 'Send code' },
@@ -928,6 +1132,8 @@ export async function startVault(o = {}) {
928
1132
  'cloudDevice.forget': { title: 'Sign out the cloud device?', text: 'It forgets this app’s account and stops keeping its Spaces always on. The Spaces and their history stay.', ok: 'Sign out' },
929
1133
  'alwaysOn.enable': { title: 'Keep this Space always on?', text: 'Give its current link to your attested cloud device so it can run schedules and answer here while your devices are away.' + (a && a.disconnectLanes ? ' Its private assistants will disconnect.' : ''), ok: 'Keep always on' },
930
1134
  'alwaysOn.disable': { title: 'Stop keeping this Space always on?', text: 'The cloud device stops its schedules and linked assistants disconnect. The Space and history stay.', ok: 'Stop keeping' },
1135
+ 'privateRoom.link': { title: 'Link this private room?', text: 'Messages from this Space can be copied into the selected room on your account. People in that room can read them.', ok: 'Link rooms' },
1136
+ 'privateRoom.unlink': { title: 'Unlink this private room?', text: 'Both rooms stay in your account. New messages stop being copied between them.', ok: 'Unlink rooms' },
931
1137
  'keptAgent.link': { title: 'Link this kept assistant?', text: 'Your private assistant can send it jobs you approve. The always-on Space reports results back through your private assistant’s agent door. Both credentials stay in this vault.', ok: 'Link assistants' },
932
1138
  'keptAgent.unlink': { title: 'Disconnect these assistants?', text: 'Both peer credentials and the connection are revoked. Rooms and history stay.', ok: 'Disconnect' },
933
1139
  'backup.beginEmailMove': { title: 'Move your email to a new account?', text: 'Use this if you lost your recovery code and all your devices. After a waiting period you can start an empty account. Your old Spaces stay with the old account.', ok: 'Start email move' },
@@ -959,7 +1165,7 @@ export async function startVault(o = {}) {
959
1165
  const syncError = a.lastError || (lastKeepFailure?.owner === who() && lastKeepFailure?.master === b._s?.master ? lastKeepFailure?.error : null)
960
1166
  return {
961
1167
  enabled: b.enabled, format: b.format, service: b.service, deviceId: a.deviceId, // service: 'account' (the Witbitz account service) | 'legacy' | null
962
- rooms: b.rooms.map(({ room, kind, label, shared, archived, pinned }) => ({ room, kind, ...(pinned ? { pinned: true } : {}), ...(label ? { label } : {}), ...(shared ? { shared } : {}), ...(archived ? { archived: true } : {}) })),
1168
+ rooms: b.rooms.map(({ room, kind, label, shared, detachedLane, archived, pinned }) => ({ room, kind, ...(detachedLane ? { detachedLane: true } : {}), ...(pinned ? { pinned: true } : {}), ...(label ? { label } : {}), ...(shared ? { shared } : {}), ...(archived ? { archived: true } : {}) })),
963
1169
  devices: a.devices, links: a.links, lastError: syncError ? { message: String(syncError.message || syncError).slice(0, 200), ...(typeof syncError.code === 'string' ? { code: syncError.code.slice(0, 60) } : {}), ...(Number.isInteger(syncError.status) ? { status: syncError.status } : {}) } : null,
964
1170
  erasure: sdk.erasure.available,
965
1171
  gated: !!b.gated, // a restore and deleting the account need the emailed code as well (sync sweep 11-09 #24)
@@ -1045,6 +1251,7 @@ export async function startVault(o = {}) {
1045
1251
  try { if (typeof addEventListener === 'function') addEventListener('storage', (e) => { if (e && e.key === KEYS.backup) atRest.flushed().then(() => atRest.loadBackups(KEYS.backup)).then((b) => { backupMem = b }, () => {}) }) } catch { /* no window (a test) */ }
1046
1252
  let adopting = false
1047
1253
  let erasingHere = false // deleteAccount is running in this vault (its own sign-out is not announced twice)
1254
+ sdk.backup._restoreIdentity = () => JSON.stringify([privacyEpoch, who()])
1048
1255
  sdk.backup.onState = (s) => { if (adopting) return; const w = who(), all = backups(); if (s) all[w] = s; else delete all[w]; backupMem = all; atRest.putBackup(KEYS.backup, w, s || null); emitAccount() }
1049
1256
  sdk.account._syncSettled = emitAccount
1050
1257
  sdk.account.onChange = () => { fromBackup(); emitAccount(); keepSoon(200) }
@@ -1134,54 +1341,90 @@ export async function startVault(o = {}) {
1134
1341
  mk = it.mk && await keyCommit(it.mk) === p.commit ? it.mk : (await sdk._openLink(it.link)).mk
1135
1342
  if (!mk || await keyCommit(mk) !== p.commit) throw new Error('Could not back up the key for this split Space')
1136
1343
  }
1137
- return { room: it.room, link: it.link, label: it.title, kind: it.lane ? 'lane' : 'space', shared: it.lane, ...(mk ? { mk } : {}) }
1344
+ let link = it.link
1345
+ if (it.enc && !/[?#&]enc=1(?:[&#?]|$)/.test(link)) {
1346
+ link += (link.includes('#') ? '&' : '#') + 'enc=1'
1347
+ }
1348
+ return { room: it.room, link, label: it.title, kind: it.lane ? 'lane' : 'space', shared: it.lane, ...(it.detachedLane ? { detachedLane: true } : {}), ...(mk ? { mk } : {}) }
1138
1349
  }
1139
1350
  async function noteRoom(room) {
1140
- const it = rooms.find((x) => x.room === room); if (!it) return
1351
+ const it = rooms.find((x) => x.room === room); if (!it || !currentRoom(it)) return
1141
1352
  const epoch = privacyEpoch, link = it.link
1142
1353
  if (sdk.backup.enabled) {
1143
1354
  const entry = await backupRoom(it)
1144
1355
  if (epoch !== privacyEpoch || it.link !== link || !rooms.includes(it)) return
1145
- if (entry) sdk.backup.add({ room, shareLink: link, _sharedRoom: it.lane, _split: !!entry.mk, _mk: entry.mk }, { label: sdk.backup.rooms.find(x => x.room === room)?.label || it.title })
1356
+ if (entry) sdk.backup.add({ room, shareLink: entry.link, _sharedRoom: it.lane, _laneOrigin: it.laneOrigin, _mintedFor: it.mintedFor, _associationAt: it.associationAt, _detachedLane: it.detachedLane, _split: !!entry.mk, _mk: entry.mk }, { label: sdk.backup.rooms.find(x => x.room === room)?.label || it.title })
1146
1357
  }
1147
1358
  const k = await eraseKey() // the account's membership mark: another account's delete of this room is refused (sdkErase.js)
1148
1359
  if (k) wop('mark', room, await dropFor(k, room)).catch(() => null)
1149
1360
  sdk.erasure._seen({ room }) // and refile the erase list soon
1150
1361
  }
1362
+ async function purgeForgotten(room) {
1363
+ write(st, KEYS.pendingForget, [...pendingForget])
1364
+ const marked = JSON.parse(await st.durableItem(KEYS.pendingForget) || '[]')
1365
+ if (!marked.includes(room)) throw new Error('vault could not save the pending room removal')
1366
+ await saveRooms(true)
1367
+ await wcall({ t: 'forget', room })
1368
+ pendingForget.delete(room)
1369
+ write(st, KEYS.pendingForget, [...pendingForget])
1370
+ await st.flushed()
1371
+ }
1151
1372
  async function dropRoom(room) {
1152
- if (streaming.delete(room)) worker.postMessage({ t: 'streamClose', room })
1153
- if (vpush) await vpush.drop(room).catch(() => {}) // off its notification list while the worker still holds its key
1154
- await wcall({ t: 'forget', room }).catch(() => null)
1155
- rooms = rooms.filter((x) => x.room !== room); saveRooms()
1373
+ const mark = Date.now() + ':' + crypto.randomUUID()
1374
+ st.setItem(forgetPrefix + room, mark)
1375
+ if (forgetMark(room) !== mark) throw new Error('vault could not save the room removal')
1376
+ pendingForget.add(room)
1377
+ write(st, KEYS.pendingForget, [...pendingForget])
1378
+ rooms = rooms.filter(r => r.room !== room)
1156
1379
  emit({ ev: 'rooms', rooms: publicRooms() })
1380
+ streamGrants.delete(room)
1381
+ if (streaming.delete(room)) syncStream(worker, room, null)
1382
+ if (vpush) await vpush.drop(room).catch(() => {}) // off its notification list while the worker still holds its key
1383
+ await st.flushed()
1384
+ await purgeForgotten(room)
1157
1385
  }
1158
1386
  async function fromBackup() {
1387
+ if (pendingForget.size) await Promise.allSettled([...pendingForget].map(purgeForgotten))
1159
1388
  if (!sdk.backup.enabled) return
1160
1389
  const epoch = privacyEpoch, accountState = sdk.backup._s
1161
1390
  const inAccount = new Map((sdk.backup._s?.rooms || []).map((b) => [b.room, b]))
1162
1391
  let added = false
1163
1392
  for (const b of inAccount.values()) {
1393
+ if (pendingForget.has(b.room) || (forgetMark(b.room) && Number(b.at || 0) <= Number(forgetMark(b.room).split(':')[0]))) continue
1164
1394
  const p = linkParts(b.link); if (!p || p.room !== b.room) continue // a link that names another room is not taken in
1165
1395
  // a HELD room whose link this vault could not open from disk (its sealed key under a key it no longer has — vaultAtRest.js)
1166
1396
  // takes the account's: a key is never replaced by a link, but a room with none gets its own back
1167
1397
  const restoredMk = p.split && b.mk && await keyCommit(b.mk).catch(() => '') === p.commit ? b.mk : ''
1168
1398
  if (epoch !== privacyEpoch || accountState !== sdk.backup._s) return
1399
+ if (pendingForget.has(b.room) || (forgetMark(b.room) && Number(b.at || 0) <= Number(forgetMark(b.room).split(':')[0]))) continue
1169
1400
  const had = rooms.find((x) => x.room === b.room)
1170
1401
  if (had) {
1171
1402
  if (b.label && b.label !== 'Space' && b.label !== b.room && (!had.title || had.title === 'Space' || had.title === b.room) && !had.renamed) {
1172
1403
  had.title = b.label
1173
1404
  added = true
1174
1405
  }
1175
- if (had.lane && b.kind === 'space' && !b.shared && Number(b.at) > 0) {
1176
- delete had.lane; had.detachedLane = true; added = true
1406
+ const heldAssociation = { ...had, kind: had.lane ? 'lane' : 'space', shared: had.lane }
1407
+ if (preferredAssociation(heldAssociation, b) === b) {
1408
+ const next = b.kind === 'lane' && b.shared !== had.room && !b.detachedLane ? b.shared : undefined
1409
+ const detached = !!b.detachedLane
1410
+ if (b.mintedFor && had.mintedFor !== b.mintedFor) { had.mintedFor = b.mintedFor; added = true }
1411
+ const origin = next && b.laneOrigin === 'minted' ? 'minted' : undefined
1412
+ if (had.laneOrigin !== origin) { if (origin) had.laneOrigin = origin; else delete had.laneOrigin; added = true }
1413
+ if (had.lane !== next || !!had.detachedLane !== detached || had.associationAt !== b.associationAt) {
1414
+ if (next) had.lane = next; else delete had.lane
1415
+ if (detached) had.detachedLane = true; else delete had.detachedLane
1416
+ if (b.associationAt) had.associationAt = b.associationAt; else delete had.associationAt
1417
+ added = true
1418
+ }
1177
1419
  }
1420
+ if (!had.enc && /[?#&]enc=1(?:[&#?]|$)/.test(b.link)) { had.enc = true; added = true }
1178
1421
  if (!had.link) { had.link = b.link; holdLink(worker, p); seedIdentity(b.room); added = true }
1179
1422
  if (restoredMk && had.link === b.link && had.mk !== restoredMk) {
1180
1423
  had.mk = restoredMk; worker.postMessage({ t: 'remember', room: b.room, mk: restoredMk }); added = true
1181
1424
  }
1182
1425
  continue
1183
1426
  }
1184
- rooms.push({ room: b.room, link: b.link, ...(restoredMk ? { mk: restoredMk } : {}), title: b.label || '', at: Number(b.at) || 0, ...(b.kind === 'lane' && b.shared ? { lane: b.shared } : {}), ...(/[?#&]enc=1(?:[&#?]|$)/.test(b.link) ? { enc: true } : {}), ...(p.split ? { split: true } : {}) })
1427
+ rooms.push({ room: b.room, ...joinedMark(b.room), link: b.link, ...(restoredMk ? { mk: restoredMk } : {}), title: b.label || '', at: Number(b.at) || 0, ...(b.mintedFor ? { mintedFor: b.mintedFor } : {}), ...(b.laneOrigin === 'minted' && b.shared && !b.detachedLane ? { laneOrigin: 'minted' } : {}), ...(b.associationAt ? { associationAt: b.associationAt } : {}), ...(b.detachedLane ? { detachedLane: true } : b.kind === 'lane' && b.shared ? { lane: b.shared } : {}), ...(/[?#&]enc=1(?:[&#?]|$)/.test(b.link) ? { enc: true } : {}), ...(p.split ? { split: true } : {}) })
1185
1428
  holdLink(worker, p)
1186
1429
  if (restoredMk) worker.postMessage({ t: 'remember', room: b.room, mk: restoredMk })
1187
1430
  seedIdentity(b.room); added = true
@@ -1219,7 +1462,7 @@ export async function startVault(o = {}) {
1219
1462
  }
1220
1463
  if (m === 'exportArchive') {
1221
1464
  const { saveAccountArchive } = await import('./sdkExports.js')
1222
- const epoch = privacyEpoch, session = sdk._session
1465
+ const epoch = privacyEpoch, generation = sdk._archiveGeneration, owner = who()
1223
1466
  const selection = args[1] === undefined ? null : new Set(Array.isArray(args[1]) ? args[1] : [])
1224
1467
  if (selection && (selection.size > 1000 || [...selection].some(id => typeof id !== 'string' || !id || id.length > 160))) throw Object.assign(new Error('Invalid room selection'), { code: 'invalid_argument' })
1225
1468
  const heldById = new Map(rooms.map(r => [r.room, r]))
@@ -1232,7 +1475,7 @@ export async function startVault(o = {}) {
1232
1475
  const saved = await workerClient.exportSealed(r.room, null)
1233
1476
  if (saved?.status !== 200) throw new Error('unavailable')
1234
1477
  return { key, ledger: saved.sealed, count: saved.count }
1235
- }, args[0] === true, () => epoch === privacyEpoch && session === sdk._session)
1478
+ }, args[0] === true, () => epoch === privacyEpoch && generation === sdk._archiveGeneration && owner === who() && selected.every(r => !r.link || rooms.some(held => held.room === r.room && held.link === r.link)), args[2])
1236
1479
  }
1237
1480
  if (m === 'protectRecoveryEmail') {
1238
1481
  const email = signedIn() && sdk.session.email
@@ -1290,7 +1533,7 @@ export async function startVault(o = {}) {
1290
1533
  // the screen asks for the code (and, where the gate or the account service asks for it, the email and the emailed code) and
1291
1534
  // calls this; the account service's emailed code is asked through the same two calls (sdkBackupV2.js restoreBridge)
1292
1535
  const email = signedIn() ? sdk.session.email : ''
1293
- let attemptedToken
1536
+ let attemptedToken, restoredIdentity
1294
1537
  const run = restoreBridge((q, getCode) => {
1295
1538
  const session = sdk._session
1296
1539
  getCode.choose = async ({ action }) => {
@@ -1300,12 +1543,18 @@ export async function startVault(o = {}) {
1300
1543
  if (proof) attemptedToken = session.idToken
1301
1544
  return proof
1302
1545
  }
1303
- return b.restore({ code: q.code, email: q.email, ticket: q.ticket, emailCode: q.emailCode, ...(b._v2 ? { getCode } : {}) })
1546
+ const identity = b._restoreIdentity()
1547
+ return b.restore({ code: q.code, email: q.email, ticket: q.ticket, emailCode: q.emailCode, ...(b._v2 ? { getCode } : {}) }).then(result => {
1548
+ if (identity !== b._restoreIdentity()) throw Object.assign(new Error('The account changed during recovery'), { code: 'account_changed' })
1549
+ restoredIdentity = identity
1550
+ return result
1551
+ })
1304
1552
  })
1305
1553
  await restoreScreen({ email, signInLabel: (o.googleSignIn === true || o.authBroker) ? 'Continue with Google or email' : 'Continue with email', signIn: async () => (await signIn()).email, restore: async (q) => { await run(q) } })
1306
- if (!b.enabled) throw Object.assign(new Error('not restored'), { code: 'cancelled' })
1554
+ if (!b.enabled || restoredIdentity !== b._restoreIdentity()) throw Object.assign(new Error('not restored'), { code: 'cancelled' })
1307
1555
  noteDeviceSpk() // as after enable (sync sweep 11-22 #16)
1308
1556
  await fromBackup()
1557
+ if (restoredIdentity !== b._restoreIdentity()) throw Object.assign(new Error('The account changed during recovery'), { code: 'account_changed' })
1309
1558
  emitAccount()
1310
1559
  accountStatus()
1311
1560
  return { rooms: accountView().rooms } // the rooms, as outside a vault (an array — a count made `.map` throw; sync sweep 11-09 #24); the view: no link, no key
@@ -1428,7 +1677,7 @@ export async function startVault(o = {}) {
1428
1677
  const epoch = privacyEpoch, id = args[0]
1429
1678
  const row = (await a.listDevices()).find(d => d.id === id && !d.current)
1430
1679
  if (!row || epoch !== privacyEpoch) throw Object.assign(new Error('Choose another device on this account'), { code: 'unknown_device' })
1431
- const ok = await confirmWith({ title: 'Sign out ' + (row.name || 'this device') + '?', text: 'It will lose access to this account and its Spaces.', ok: 'Sign out', cancel: 'Cancel' })
1680
+ const ok = await confirmWith({ title: 'Sign out ' + (row.name || 'this device') + '?', text: 'It clears its local data the next time it comes online.' + recoveryNotice(), ok: 'Sign out', cancel: 'Cancel' })
1432
1681
  if (!ok || epoch !== privacyEpoch) throw Object.assign(new Error('Device sign-out cancelled'), { code: 'cancelled' })
1433
1682
  const result = await a.signOutDevice(id, { getCode: await emailCodeAsker('signout', accountAddress) })
1434
1683
  emitAccount()
@@ -1440,7 +1689,28 @@ export async function startVault(o = {}) {
1440
1689
  const sec = typeof name === 'string' && Object.prototype.hasOwnProperty.call(all, name) ? all[name] : null
1441
1690
  if (!sec || !sec._calls.includes(op)) throw Object.assign(new Error('vault: account.' + String(name).slice(0, 20) + '.' + String(op).slice(0, 20) + ' is not available to the page'), { code: 'vault_refused' })
1442
1691
  if (!watchedSections.has(name)) { watchedSections.add(name); sec.on('change', (value) => emit({ ev: 'accountSection', section: name, value })) } // another device's change reaches the page
1443
- const result = await sec[op](...rest.slice(0, 1))
1692
+ let result
1693
+ if (name === 'chatLocks' && op === 'deleteAll') {
1694
+ const owner = sdk.backup._s, epoch = privacyEpoch, { targets: locks, privateAssistants: assistants } = await sec.previewDeleteAll()
1695
+ if (!locks.length) return []
1696
+ const lockedRooms = new Set(locks.filter(l => l.kind === 'room').map(l => l.target))
1697
+ const extra = assistants.length ? ' Their private assistants will also be removed: ' + assistants.map(r => r.title || r.room).join(', ') + '.' : ''
1698
+ const roomCount = lockedRooms.size
1699
+ const confirmed = await confirmWith({ title: 'Delete all locked chats?', text: 'Remove ' + roomCount + ' locked Spaces from this account and delete ' + (locks.length - roomCount) + ' Code sessions on their computers? Forgetting a Space leaves its sealed messages on the server. Independently linked rooms keep their copies.' + extra, ok: 'Delete all', cancel: 'Cancel' })
1700
+ if (!confirmed) throw Object.assign(new Error('Cancelled'), { code: 'cancelled' })
1701
+ if (epoch !== privacyEpoch || owner !== sdk.backup._s) throw Object.assign(new Error('The account changed.'), { code: 'account_changed' })
1702
+ result = await sec._deleteTargets(locks, owner, async (kind, room) => {
1703
+ if (epoch !== privacyEpoch) throw new Error('Account changed')
1704
+ if (kind === 'room' && held(room)) await dropRoom(room)
1705
+ }, assistants.map(r => r.room))
1706
+ if (epoch === privacyEpoch && owner === sdk.backup._s) {
1707
+ await fromBackup()
1708
+ emit({ ev: 'accountSection', section: name, value: sec.value })
1709
+ }
1710
+ } else {
1711
+ result = await sec[op](...rest.slice(0, 1))
1712
+ if (name === 'chatLocks' && (op === 'match' || op === 'check')) emit({ ev: 'accountSection', section: name, value: sec.value })
1713
+ }
1444
1714
  if (name === 'blocks' || name === 'chatLocks') {
1445
1715
  // A refresh already in flight may have read the list before this change.
1446
1716
  if (privacyRun) await privacyRun.catch(() => {})
@@ -1450,7 +1720,7 @@ export async function startVault(o = {}) {
1450
1720
  }
1451
1721
  if (m === 'usage') { const o = args[0] && typeof args[0] === 'object' ? args[0] : {}; return a.usage(o.month !== undefined ? { month: o.month } : {}) } // folded with the vault's usage key, which the page never holds
1452
1722
  if (m === 'stop') { a.stop(); return {} }
1453
- if (m === 'forget') { const room = String(args[0] || ''); a.forget(room); if (held(room)) await dropRoom(room); emitAccount(); return {} }
1723
+ if (m === 'forget') { const room = String(args[0] || ''); a.forget(room); if (held(room)) await dropRoom(room); await fromBackup(); emitAccount(); return {} }
1454
1724
  if (m === 'noteLink' || m === 'dropLink') { // a link between two lanes THIS vault holds — any other pair is not the page's to record
1455
1725
  const x = String(args[0] || ''), y = String(args[1] || '')
1456
1726
  if (!held(x) || !held(y)) throw Object.assign(new Error('vault: this vault holds no such lanes'), { code: 'not_in_vault' })
@@ -1502,20 +1772,21 @@ export async function startVault(o = {}) {
1502
1772
  ? await spacesUsingConnection(args[0], rooms.map(r => ({ room: r.room, shared: r.lane })), room => wop('getConfig', room, { plainMark: true }))
1503
1773
  : await sdk[ns][m](...args)
1504
1774
  if (callEpoch !== privacyEpoch || callOwner !== who()) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1505
- if (ns === 'connections' && (m === 'attach' || m === 'finishConnect' || m === 'attachMcp' || m === 'finishMcp') && r && r.id) { conns = [{ id: r.id, label: r.label || '', host: r.host || '', callKey: r.callKey, account: r.account || '', ...(r.provider ? { provider: r.provider } : {}), ...(r.mcp ? { mcp: true } : {}), ...hookOf(r) }, ...conns.filter((c) => c.id !== r.id)]; saveConns(); await adoptPending([r.id], r.account || await sdk._account()); return pub(r) }
1506
- if (ns === 'connections' && m === 'detach') { conns = conns.filter((c) => c.id !== String(args[0] || '')); saveConns() }
1775
+ if (ns === 'connections' && m === 'spacesUsing' && !sdk.backup.enabled) r.incomplete = true
1776
+ if (ns === 'connections' && (m === 'attach' || m === 'finishConnect' || m === 'attachMcp' || m === 'finishMcp') && r && r.id) { conns = [{ id: r.id, label: r.label || '', host: r.host || '', callKey: r.callKey, account: r.account || '', ...(r.provider ? { provider: r.provider } : {}), ...(r.mcp ? { mcp: true } : {}), ...hookOf(r) }, ...conns.filter((c) => c.id !== r.id)]; await connectionChange(r.account || await sdk._account(), r.id, false); saveConns(); await adoptPending([r], r.account || await sdk._account()); return pub(r) }
1777
+ if (ns === 'connections' && m === 'detach') { saveA2A(); if (r?.removed?.length) emit({ ev: 'a2aChanged', removed: r.removed }); const acct = await sdk._account(); if (callEpoch !== privacyEpoch || callOwner !== who()) throw Object.assign(new Error('The account changed'), { code: 'account_changed' }); await connectionChange(acct, String(args[0] || ''), true); conns = conns.filter((c) => c.id !== String(args[0] || '')); saveConns() }
1507
1778
  // GRANTABLE HERE (sync sweep 11-13 P7): the Sentinel lists every connection the account has, but a grant needs its callKey,
1508
1779
  // which only this vault's list holds (attached here, or kept from another device with the backup on) — the rest refuse
1509
1780
  // with not_in_vault. Each says which it is, so the page offers to grant only what will work.
1510
1781
  if (ns === 'connections' && m === 'list' && Array.isArray(r)) {
1511
1782
  const acct = await sdk._account()
1512
1783
  if (callEpoch !== privacyEpoch || callOwner !== who()) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1513
- await adoptPending(r.map((x) => x && x.id).filter(Boolean), acct) // a key whose attach answer was lost, now listed (#5)
1784
+ await adoptPending(r, acct) // a key whose attach answer was lost, now listed (#5)
1514
1785
  // MOVE 3: the old-form ones whose key this vault holds are locked under it (connWrap.js) — once a launch, in the background
1515
1786
  if (!_lockedOnce && r.some((x) => x && x.locked === false)) { _lockedOnce = true; sdk.connections.lock(Object.fromEntries(conns.filter((c) => c.account === acct && c.callKey).map((c) => [c.id, c.callKey]))).catch(() => { _lockedOnce = false }) }
1516
1787
  return r.map((x) => (x && typeof x === 'object' ? { ...x, grantable: conns.some((c) => c.id === x.id && c.account === acct) } : x))
1517
1788
  }
1518
- if (ns === 'siri') { saveSiri(); if (m === 'rotateKey') return siriShortcut() }
1789
+ if (ns === 'siri') { saveSiri(); emit({ ev: 'siri', siri: siriShortcut() }); if (m === 'rotateKey') return siriShortcut() }
1519
1790
  if (ns === 'a2a') saveA2A()
1520
1791
  return r
1521
1792
  }
@@ -1531,6 +1802,15 @@ export async function startVault(o = {}) {
1531
1802
  const id = String(args[0] && typeof args[0] === 'object' ? args[0].id : args[0] || '')
1532
1803
  const acct = await sdk._account()
1533
1804
  c = conns.find((x) => x.id === id && x.account === acct) // only this account's own connections
1805
+ if (c && typeof c.mcp !== 'boolean') {
1806
+ const owner = who(), epoch = privacyEpoch
1807
+ const listed = await sdk.connections.list()
1808
+ if (owner !== who() || epoch !== privacyEpoch) throw Object.assign(new Error('the account changed'), { code: 'account_changed' })
1809
+ if (!listed.some(row => row.id === id)) throw Object.assign(new Error('connection no longer attached'), { code: 'not_in_vault' })
1810
+ await adoptPending(listed, acct)
1811
+ if (owner !== who() || epoch !== privacyEpoch) throw Object.assign(new Error('the account changed'), { code: 'account_changed' })
1812
+ c = conns.find(x => x.id === id && x.account === acct)
1813
+ }
1534
1814
  if (!c) throw Object.assign(new Error('vault: no connection ' + id.slice(0, 40) + ' attached in this vault'), { code: 'not_in_vault' })
1535
1815
  }
1536
1816
  if (ns === 'a2a' && (m === 'setReply' || (m === 'addPeer' && args[1]?.reply === 'auto'))) {
@@ -1545,7 +1825,15 @@ export async function startVault(o = {}) {
1545
1825
  const sp = roomSpace(room)
1546
1826
  try { kept = await isKeptSpace(sp) } finally { sp.close() }
1547
1827
  }
1548
- await confirmCall(ns, m, args, room, kept)
1828
+ if (ns === 'privateRoom' && m === 'link') {
1829
+ const source = rooms.find(r => r.room === room && currentRoom(r)), target = rooms.find(r => r.room === args[0] && currentRoom(r))
1830
+ if (!source || !target) throw Object.assign(new Error('Open both rooms in this vault first.'), { code: 'not_in_vault' })
1831
+ const label = r => (r.title || r.room) + ' (' + (r.enc ? 'confidential' : 'standard') + ')'
1832
+ const downgrade = source.enc && !target.enc
1833
+ if (downgrade && args[1]?.allowStandardDestination !== true) throw Object.assign(new Error('Confirm the standard destination before linking.'), { code: 'tier_mismatch' })
1834
+ const ok = await confirmWith({ title: 'Link these rooms?', text: 'Messages from ' + label(source) + ' can be copied to ' + label(target) + '. People in that room can read them.' + (downgrade ? ' Witbitz servers and the regular model provider can read the copied messages, including messages from other members.' : ''), ok: 'Link rooms', cancel: 'Cancel' })
1835
+ if (!ok) throw Object.assign(new Error('Link cancelled'), { code: 'cancelled' })
1836
+ } else await confirmCall(ns, m, args, room, kept)
1549
1837
  if (epoch !== privacyEpoch || owner !== who() || !held(room)) throw Object.assign(new Error('the account or room changed during confirmation'), { code: 'account_changed' })
1550
1838
  }
1551
1839
  if (ns === 'connections' && m === 'grants') {
@@ -1565,6 +1853,25 @@ export async function startVault(o = {}) {
1565
1853
  const epoch = privacyEpoch, it = held(room) && rooms.find((r) => r.room === room)
1566
1854
  return await saveRoomExport(sp, it?.enc ? 'enclave' : 'standard', () => epoch === privacyEpoch && !!held(room), it?.title || '')
1567
1855
  }
1856
+ if (ns === 'privateRoom') {
1857
+ const target = rooms.find(r => currentRoom(r) && r.room === args[0])
1858
+ if (!target || !held(target.room)) throw Object.assign(new Error('The selected room is unavailable.'), { code: 'not_in_vault' })
1859
+ if (target.lane && target.lane !== room) throw Object.assign(new Error('The room is already linked elsewhere.'), { code: 'already_linked' })
1860
+ const other = roomSpace(target.room), epoch = privacyEpoch
1861
+ try {
1862
+ const result = await sp._privateRoomChange(other, m === 'unlink', args[1]?.allowStandardDestination === true)
1863
+ if (epoch !== privacyEpoch || !rooms.includes(target)) throw Object.assign(new Error('The account changed.'), { code: 'account_changed' })
1864
+ const entry = sdk.backup.rooms.find(r => r.room === target.room)
1865
+ if (m === 'unlink') { delete target.lane; target.detachedLane = true }
1866
+ else { target.lane = room; delete target.detachedLane }
1867
+ if (entry?.mintedFor) target.mintedFor = entry.mintedFor
1868
+ if (entry?.laneOrigin === 'minted') target.laneOrigin = 'minted'; else delete target.laneOrigin
1869
+ target.associationAt = entry?.associationAt || entry?.at || Date.now()
1870
+ await saveRooms(true)
1871
+ emit({ ev: 'rooms', rooms: publicRooms() })
1872
+ return result
1873
+ } finally { other.close() }
1874
+ }
1568
1875
  if (ns === 'keptAgent') {
1569
1876
  const kept = roomSpace(args[0])
1570
1877
  try { return m === 'link' ? await sp.linkKept(kept, args[1] || {}) : await sp.unlinkKept(kept, args[1]) }
@@ -1590,7 +1897,7 @@ export async function startVault(o = {}) {
1590
1897
  const r = await sp.siri.collect(deliver ? { deliver } : {}); saveSiri(); return r
1591
1898
  }
1592
1899
  const r = await sp[ns][m](...args)
1593
- if (ns === 'siri') { saveSiri(); if (r && typeof r === 'object' && 'key' in r) return { ...r, key: null, hasKey: !!r.key } } // the key stays in the vault (siri.showKey)
1900
+ if (ns === 'siri') { saveSiri(); emit({ ev: 'siri', siri: siriShortcut() }); if (r && typeof r === 'object' && 'key' in r) return { ...r, key: null, hasKey: !!r.key } } // the key stays in the vault (siri.showKey)
1594
1901
  return r
1595
1902
  } catch (e) { throw vaultSignInWords(e) } finally { sp.close() }
1596
1903
  }
@@ -1631,23 +1938,31 @@ export async function startVault(o = {}) {
1631
1938
  const forgetDevice = sdk.backup._v2?.forgetDevice
1632
1939
  const keyCleanup = (forgetDevice ? forgetDevice(sdk.backup) : idbKeyStore('wbvault-acct').clear()).then(() => null, (e) => e)
1633
1940
  try { sdk.signOut() } catch { /* already */ }
1634
- for (const room of streaming) { try { worker.postMessage({ t: 'streamClose', room }) } catch { /* the worker is replaced below */ } }
1635
- streaming.clear() // the replay re-opened each one in the new worker, and onWorker forwarded its events to the page
1941
+ for (const room of streaming) { try { syncStream(worker, room, null) } catch { /* the worker is replaced below */ } }
1942
+ streaming.clear(); streamGrants.clear() // the replay re-opened each one in the new worker, and onWorker forwarded its events to the page
1636
1943
  const held0 = rooms.map((r) => r.room)
1637
1944
  rooms = []
1638
1945
  write(st, KEYS.session, null)
1639
1946
  if (vpush) await Promise.race([vpush.sync([]), new Promise((r) => setTimeout(r, WIPE_PUSH_MS))]).catch(() => {}) // while the worker still holds the keys
1640
- await saveRooms()
1947
+ // ★ THE WORKER'S KEYS GO WHATEVER THE SAVE DOES (second review, 2026-11-27). A strict save that could not be confirmed threw
1948
+ // here, before the forgets and wipeKeys below — "signed out", with every room key still in the worker's memory and store until
1949
+ // a retry got through. Its error is kept and thrown at the end, with the key store's (the wipe marker stays, so launch retries).
1950
+ const saveError = await saveRooms(true, true).then(() => null, (e) => e)
1641
1951
  await wcall({ t: 'presenceQuery' }).catch(() => null) // which rooms the worker holds a key for (workerRooms) — the list may not name them all
1642
1952
  for (const room of new Set([...held0, ...workerRooms])) await wcall({ t: 'forget', room }).catch(() => null) // memory AND its store (awaited there)
1643
1953
  await wcall({ t: 'wipeKeys' }) // includes sealed keys which were neither listed nor unsealed
1644
- workerRooms = []
1954
+ workerRooms = []; pendingForget.clear()
1645
1955
  failWaiting('signed out — try again') // what waits on the worker that goes (P8): never answered
1646
1956
  conns = []; backupMem = {}; _lockedOnce = false; pageUserToken = ''
1647
1957
  try { sdk.account._spk = null } catch { /* */ } // or the NEXT account's index entry carried this one's device key
1648
1958
  try { sdk.invite._state = null; sdk.invite.status = undefined } catch { /* */ } // …and this one's invite private key (sync sweep 2026-11-23 #12): the next account's held_elsewhere slot saved it under the new address
1649
1959
  mirrorOk.clear(); keyWaits.clear()
1650
1960
  for (const k of Object.values(KEYS)) write(st, k, null)
1961
+ const rawStorage = o.storage || localStorage
1962
+ for (let i = rawStorage.length - 1; i >= 0; i--) {
1963
+ const name = rawStorage.key(i)
1964
+ if (name?.startsWith(forgetPrefix)) rawStorage.removeItem(name)
1965
+ }
1651
1966
  await st.flushed()
1652
1967
  await atRest.flushed()
1653
1968
  write(st, learnedBlocksKey, null)
@@ -1656,18 +1971,29 @@ export async function startVault(o = {}) {
1656
1971
  loadSiri(); loadBackup(); clearTimeout(refreshTimer); await startWorker()
1657
1972
  emit({ ev: 'rooms', rooms: publicRooms() }); emitAccount()
1658
1973
  const keyError = await keyCleanup
1659
- if (keyError) throw keyError
1974
+ if (keyError || saveError) throw (keyError || saveError)
1660
1975
  write(st, wipeMarker, null)
1661
1976
  }
1662
1977
  // WHAT A SIGN-OUT HAS TO FORGET (sync sweep 11-22 #7): a sign-in, live or expired; a held Space; a connection; a backup; any store
1663
1978
  function onPeerSignOut(event) {
1979
+ if (event.key?.startsWith(forgetPrefix) && event.newValue) {
1980
+ const room = event.key.slice(forgetPrefix.length)
1981
+ if (rooms.some(r => r.room === room && !currentRoom(r))) {
1982
+ rooms = rooms.filter(r => r.room !== room || currentRoom(r))
1983
+ streamGrants.delete(room)
1984
+ if (streaming.delete(room)) syncStream(worker, room, null)
1985
+ wcall({ t: 'forget', room }).catch(() => {})
1986
+ emit({ ev: 'rooms', rooms: publicRooms() })
1987
+ }
1988
+ return
1989
+ }
1664
1990
  if (event.key !== wipeMarker) return
1665
1991
  if (event.newValue === 'true' && !peerSignedOut) {
1666
1992
  peerSignedOut = true
1667
1993
  privacyEpoch++
1668
1994
  clearTimeout(refreshTimer); clearTimeout(privacyTimer); clearTimeout(idPrefetchT)
1669
1995
  sdk.account.stop(); sdk.signOut(); clearTimeout(sdk.backup._timer)
1670
- rooms = []; streaming.clear(); conns = []; backupMem = {}
1996
+ rooms = []; streaming.clear(); streamGrants.clear(); conns = []; backupMem = {}
1671
1997
  frame.remove()
1672
1998
  workerHost.drop()
1673
1999
  failWaiting('Signed out in another tab')
@@ -1683,6 +2009,10 @@ export async function startVault(o = {}) {
1683
2009
  async op(op, room, ...args) {
1684
2010
  if (!PAGE_OPS.has(op)) throw Object.assign(new Error('vault: ' + op + ' is not available to the page'), { code: 'vault_refused' })
1685
2011
  if (!held(room)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(room).slice(0, 40)), { code: 'not_in_vault' })
2012
+ if (op === 'state' && args[4] != null && (!Number.isSafeInteger(args[4]) || args[4] < 0)) throw Object.assign(new Error('A state version must be a nonnegative integer.'), { code: 'vault_refused' })
2013
+ if (op === 'state' && args[0] === 'agentmode' && args[1] != null && rooms.some(r => r.room === room && (r.lane || r.detachedLane))) {
2014
+ throw Object.assign(new Error('a private lane always replies'), { code: 'lane' })
2015
+ }
1686
2016
  if (op === 'stop') { if (isEncRoom(room) && !(await encReadyFor(room))) return { status: 503, ok: false, error: 'enclave_unreachable' }; return sdk._client.stop(room, String(args[0] || '').slice(0, 200)) } // a turn's stop: keyless, named by the turn's own random stop key — to the room's own tier (sweep 11-06 #3)
1687
2017
  // AN ATTESTED SPACE IS COPIED ONLY INTO AN ATTESTED LANE (sync sweep 2026-11-15 #5; the app's mirrorLoop.js, the SDK's openLane): the
1688
2018
  // page's lane mirror posts here — refused when the lane's Space requires an attested app and the lane does not; a failed read refuses
@@ -1695,8 +2025,8 @@ export async function startVault(o = {}) {
1695
2025
  if (op === 'setConfig' && args[0] && typeof args[0] === 'object' && ['connections', 'funding', 'forkAuthority', 'admins', 'owners'].some((k) => k in args[0])) throw Object.assign(new Error('vault: connections, funding and who manages a Space go through the vault (changeMembers asks the person first)'), { code: 'vault_refused' }) // admins/owners: a role change in place since 443e1e9d — a page must not make it in the person's name unasked (sweep 10-23 #4)
1696
2026
  if (op === 'setConfig' && args[0]?.lanes === true) { const sp = roomSpace(room); try { await assertNotKept(sp) } finally { sp.close() } }
1697
2027
  const keyIn = (o) => o.bridgeMk != null || o.mk != null || o.identity != null
1698
- for (const a of args) {
1699
- if (!a || typeof a !== 'object') continue
2028
+ const a = args[routingIndex(op)]
2029
+ if (a && typeof a === 'object') {
1700
2030
  if (keyIn(a)) throw Object.assign(new Error('vault: a key or an identity is the vault\'s, not the page\'s'), { code: 'vault_refused' })
1701
2031
  if (a.bridgeRoom != null && !held(a.bridgeRoom)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(a.bridgeRoom).slice(0, 40)), { code: 'not_in_vault' })
1702
2032
  if (op !== 'carry' && (a.bridgeRoom || a.viewSource)) {
@@ -1704,9 +2034,10 @@ export async function startVault(o = {}) {
1704
2034
  if (lane?.detachedLane || !lane?.lane || (a.bridgeRoom && lane.lane !== a.bridgeRoom) || (a.viewSource && lane.lane !== a.viewSource)) throw Object.assign(new Error('vault: this private assistant is disconnected'), { code: 'lanes_disabled' })
1705
2035
  }
1706
2036
  // linked rooms (a lane's tell_lane): each one held here; the worker fills in its key by room
1707
- if (a.links != null) {
2037
+ if (op === 'turn' && a.links != null) {
1708
2038
  if (!Array.isArray(a.links) || a.links.some((l) => !l || typeof l !== 'object')) throw Object.assign(new Error('vault: links are Spaces named by id'), { code: 'invalid_argument' })
1709
2039
  if (a.links.some(keyIn)) throw Object.assign(new Error('vault: a key is the vault\'s, not the page\'s'), { code: 'vault_refused' })
2040
+ if (a.links.some(l => isEncRoom(l.room) !== isEncRoom(room))) throw Object.assign(new Error('vault: linked Spaces must use the same confidentiality tier'), { code: 'tier_mismatch' })
1710
2041
  if (a.links.some((l) => !held(l.room))) throw Object.assign(new Error('vault: a linked room must be a Space this vault holds'), { code: 'not_in_vault' })
1711
2042
  }
1712
2043
  }
@@ -1723,13 +2054,14 @@ export async function startVault(o = {}) {
1723
2054
  // _isEnclave() is always false in a vault, so space.safeMedia.refresh() failed until something else woke it)
1724
2055
  if (op === 'getConfig' && isEnc && r == null) { try { await sdk._encWake(room, { tries: 8 }); pushEnclave(); r = await wcall({ t: 'op', op, room, args }) } catch { /* null: the page says it could not read */ } }
1725
2056
  if (op === 'getConfig') r = configForPage(r)
2057
+ if ((op === 'poll' || op === 'pollSealed') && r?.streamGrants) { const { streamGrants: _grants, ...visible } = r; r = visible }
1726
2058
  const lanes = op === 'getConfig' ? r && r.lanes : op === 'setConfig' && r && r.status === 200 && args[0] ? args[0].lanes : undefined
1727
2059
  if (op === 'setConfig' && lanes === false) await disconnectRoomLanes(sdk, room)
1728
2060
  if (typeof lanes === 'boolean') {
1729
2061
  const it = rooms.find((x) => x.room === room)
1730
- if (it && it.link) { const url = new URL(it.link); const hash = new URLSearchParams(url.hash.slice(1)); if (lanes) hash.set('lanes', '1'); else hash.delete('lanes'); url.hash = hash.toString(); const link = url.href; if (link !== it.link) { it.link = link; await saveRooms(); emit({ ev: 'rooms', rooms: publicRooms() }) } }
2062
+ if (it && it.link) { const url = new URL(it.link); url.searchParams.delete('lanes'); const hash = new URLSearchParams(url.hash.slice(1)); if (lanes) hash.set('lanes', '1'); else hash.delete('lanes'); url.hash = hash.toString(); const link = url.href; if (link !== it.link) { it.link = link; await saveRooms(); emit({ ev: 'rooms', rooms: publicRooms() }) } }
1731
2063
  }
1732
- if (op === 'title' && r && typeof r.title === 'string') { const it = rooms.find((x) => x.room === room); const t = r.title.slice(0, 200); if (it && it.title !== t) { it.title = t; saveRooms() } }
2064
+ if (op === 'title' && r && typeof r.title === 'string') { const it = rooms.find((x) => x.room === room); const t = r.title.slice(0, 200); if (it && it.title !== t) { it.title = t; await saveRooms(); emit({ ev: 'rooms', rooms: publicRooms() }) } }
1733
2065
  return r
1734
2066
  },
1735
2067
  async create(cfg, opts) { // opts { enclave, split }: the confidential tier, a split-key room; anything else is refused, never ignored
@@ -1749,6 +2081,7 @@ export async function startVault(o = {}) {
1749
2081
  const now = Date.now(); creates = creates.filter((t) => now - t < CREATE_LIMIT.ms)
1750
2082
  if (creates.length >= CREATE_LIMIT.n) throw Object.assign(new Error('vault: too many new Spaces — wait a few minutes'), { code: 'rate_limited' })
1751
2083
  creates.push(now)
2084
+ if (cfg.usernames !== undefined && (cfg.usernames !== false || cfg.admission !== 'email')) throw Object.assign(new Error('vault: only verified Spaces can hide usernames'), { code: 'invalid_argument' })
1752
2085
  if (cfg.direct !== undefined && (cfg.direct !== true || cfg.admission !== 'email')) throw Object.assign(new Error('vault: a direct chat is an email-gated Space'), { code: 'invalid_argument' })
1753
2086
  // Attest FIRST — loud on a configuration failure (no published claim: never mint a confidential room that pins
1754
2087
  // nothing), soft on a cold enclave (woken below) — then mint, wake, and hand the enclave its own sealed config.
@@ -1774,7 +2107,7 @@ export async function startVault(o = {}) {
1774
2107
  current()
1775
2108
  const completeKey = split && r.mk && await keyCommit(r.mk) === linkParts(link)?.commit ? r.mk : null
1776
2109
  current()
1777
- rooms = [{ room: r.room, link, ...(completeKey ? { mk: completeKey } : {}), title: '', at: Date.now(), ...(lane ? { lane } : {}), ...(enclave ? { enc: true } : {}), ...(split ? { split: true } : {}) }, ...rooms.filter(x => x.room !== r.room)]
2110
+ rooms = [{ room: r.room, ...joinedMark(r.room), link, ...(completeKey ? { mk: completeKey } : {}), title: '', at: Date.now(), ...(lane ? { lane, mintedFor: lane, laneOrigin: 'minted', associationAt: Date.now() } : {}), ...(enclave ? { enc: true } : {}), ...(split ? { split: true } : {}) }, ...rooms.filter(x => x.room !== r.room)]
1778
2111
  await saveRooms()
1779
2112
  current()
1780
2113
  seedIdentity(r.room); noteRoom(r.room).catch(() => {})
@@ -1807,7 +2140,7 @@ export async function startVault(o = {}) {
1807
2140
  const sh = rooms.find((x) => x.room === shared)
1808
2141
  // A TEMPORARY ROOM HAS NO LANE (as the direct SDK and the app — roomState isTempRoom; sync sweep backlog P7): a lane is a
1809
2142
  // durable room, and its copies of the room would outlive the wipe
1810
- if (sh && sh.lane) throw Object.assign(new Error('vault: a private lane has no lane of its own — ask from its Space'), { code: 'lane_of_lane' }) // as the direct SDK (sweep P1)
2143
+ if (sh && (sh.lane || sh.detachedLane)) throw Object.assign(new Error('vault: a private lane has no lane of its own — ask from its Space'), { code: 'lane_of_lane' }) // as the direct SDK (sweep P1)
1811
2144
  if (String(shared).startsWith('tmp-') || (sh && sh.temporary)) throw Object.assign(new Error('vault: a temporary room has no private lane — the lane is a durable room, and its copies of the room would outlive the wipe'), { code: 'temporary_room' })
1812
2145
  // A VERIFIED SPACE'S LANE ADMITS ITS ONE MEMBER, whatever the page sent (laneConfig.js laneInherits; sync sweep 10-16 #1):
1813
2146
  // the vault decides it, so a page cannot make an open lane of a verified Space.
@@ -1816,7 +2149,7 @@ export async function startVault(o = {}) {
1816
2149
  if (sh && sh.enc) { try { await sdk._encWake(shared, { tries: 8 }); pushEnclave() } catch { /* the read below says what is wrong */ } }
1817
2150
  let scfg = null; try { scfg = await wop('getConfig', shared, { plainMark: true }) } catch { scfg = null }
1818
2151
  // a plain room: read, and it has no settings — never when the vault's own link for it says verified (gate=email)
1819
- const plain = !!(scfg && scfg.plain === true) && !(sh && /[#&]gate=email(?:&|$)/.test(String(sh.link || ''))); if (scfg && scfg.plain === true) scfg = null
2152
+ const plain = !!(scfg && scfg.plain === true) && !(sh && roomInviteFlags(sh.link).gated); if (scfg && scfg.plain === true) scfg = null
1820
2153
  // the placeholder a verified Space's settings read gives before the sign-in admits ({ admission:'email', gated:true },
1821
2154
  // no allow) is not its settings: read as such, the lane got none of its Space's tools (sync sweep 2026-10-29 #9; the app: roomSync gatedStub)
1822
2155
  // …and it says the Space IS verified: wait, whatever the link says — read as "no settings", a verified Space whose link
@@ -1851,6 +2184,18 @@ export async function startVault(o = {}) {
1851
2184
  let attested = false
1852
2185
  try { if (sh.enc) await encReadyFor(shared); attested = !!(await sdk._client.attestedRoom(shared, null)) } catch { throw Object.assign(new Error('vault: whether this Space requires an attested app could not be read, so its private lane waits — try again'), { code: 'lane_wait' }) } // a failed read is not 'not attested' (sync sweep 11-08) // op 'policy' is public: no room key rides (sweep 11-06 #2 — it went to the Lambda READABLE)
1853
2186
  if (laneInherits(scfg, { attested }).wait === 'attested') throw Object.assign(new Error('vault: this Space requires an attested app, so its private lane is made only by that app (the Witbitz app on the device), under the same rule — not by a vault'), { code: 'attested' })
2187
+ const inherited = laneInherits(scfg).config
2188
+ if (o?.inheritCustom || (o?.inheritCustom !== false && !cfg?.tools && !cfg?.immediateTools)) {
2189
+ cfg = { ...cfg }
2190
+ delete cfg.tools; delete cfg.immediateTools
2191
+ if (inherited.tools) cfg.tools = inherited.tools
2192
+ if (inherited.immediateTools) cfg.immediateTools = inherited.immediateTools
2193
+ }
2194
+ if (o?.inheritPlatform || (o?.inheritPlatform !== false && cfg?.platformTools === undefined)) {
2195
+ cfg = { ...cfg }
2196
+ if (inherited.platformTools !== undefined) cfg.platformTools = inherited.platformTools
2197
+ else delete cfg.platformTools
2198
+ }
1854
2199
  cfg = { ...(cfg && typeof cfg === 'object' ? cfg : {}), lane: true, region: roomRegion(shared) } /* region: its Space's, whatever the page sent — as the app and the direct SDK (sync sweep 2026-11-23) */ // a lane says so in its own sealed settings (laneConfig.js; sync sweep 11-19 P1)
1855
2200
  return makeRoom(cfg, shared, { enclave: !!sh.enc, split: !!sh.split }) // a lane is on its Space's tier and key model — never a silent downgrade
1856
2201
  },
@@ -1860,16 +2205,25 @@ export async function startVault(o = {}) {
1860
2205
  // a live stream for a held Space while the page shows it (on: true), or no longer (on: false)
1861
2206
  async stream(room, on) {
1862
2207
  if (!held(room)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(room).slice(0, 40)), { code: 'not_in_vault' })
1863
- if (on && !streaming.has(room)) { streaming.add(room); worker.postMessage({ t: 'streamOpen', room }) }
1864
- else if (!on && streaming.has(room)) { streaming.delete(room); worker.postMessage({ t: 'streamClose', room }) }
2208
+ if (on) streaming.add(room); else streaming.delete(room)
2209
+ const ready = await workerHost.ready()
2210
+ if (ready === worker) applyStream(ready, room)
1865
2211
  return { streaming: streaming.has(room) }
1866
2212
  },
1867
2213
  async share(room, opts = {}) {
1868
2214
  const it = rooms.find((x) => x.room === room)
1869
2215
  if (!it || !it.link) throw Object.assign(new Error('vault: no link for that Space'), { code: 'not_in_vault' })
1870
- if (it.lane) throw Object.assign(new Error('A private lane cannot be shared'), { code: 'private_lane' })
2216
+ if (it.lane || it.detachedLane) throw Object.assign(new Error('A private lane cannot be shared'), { code: 'private_lane' })
1871
2217
  if (typeof screens.share !== 'function') throw Object.assign(new Error('this vault has no share screen'), { code: 'no_screen' })
1872
- await screens.share({ link: it.link, title: String((opts && opts.title) || it.title || '') })
2218
+ let link = it.link
2219
+ if (opts?.hostInviteTemplate !== undefined) {
2220
+ if (!o.hostInviteTemplate || opts.hostInviteTemplate !== o.hostInviteTemplate) throw Object.assign(new Error('This host invite template is not configured in the vault.'), { code: 'invalid_argument' })
2221
+ const url = new URL(it.link)
2222
+ embeddedInvite(o.hostInviteTemplate, url.origin, pageOrigin)
2223
+ url.searchParams.set('hostInvite', '1')
2224
+ link = url.href
2225
+ }
2226
+ await screens.share({ link, gated: it.gated === true || roomInviteFlags(it.link).gated ? true : null, title: String((opts && opts.title) || it.title || '') })
1873
2227
  return { shown: true }
1874
2228
  },
1875
2229
  signIn,
@@ -1890,27 +2244,41 @@ export async function startVault(o = {}) {
1890
2244
  // the PERSON confirms in the vault's own pixels: a page script alone cannot sign them out (security review). Whatever the sign-in:
1891
2245
  // once it had expired this returned at once, and the Spaces, their keys and the page's reach all stayed (sync sweep 11-22 #7)
1892
2246
  if (!holdsAnything()) return { signedIn: false }
1893
- if (!(await confirmWith({ title: 'Sign out?', text: 'This device forgets your Spaces and your account. Your backup brings them back when you sign in again' + (sdk.backup && sdk.backup.enabled ? '.' : ' — and backup is OFF here, so a Space only this device holds is lost.'), ok: 'Sign out', cancel: 'Cancel' }).catch(() => false))) throw Object.assign(new Error('cancelled'), { code: 'cancelled' })
2247
+ const epoch = privacyEpoch, b = sdk.backup
2248
+ if (!(await confirmWith({ title: 'Sign out?', text: 'This device forgets your Spaces and your account.' + (sdk.backup?.enabled ? recoveryNotice() : ' Backup is off here. A Space only this device holds is lost.'), ok: 'Sign out', cancel: 'Cancel' }).catch(() => false))) throw Object.assign(new Error('cancelled'), { code: 'cancelled' })
1894
2249
  // SIGN OUT ENDS THE PAGE'S REACH (docs/sdk-vault-mode.md: "cannot reach rooms after the user signs out in the vault"; sync sweep
1895
2250
  // 11-20 P7/P8): the held Spaces' keys and the account's stores go too — kept, the page still reached every Space, and the next
1896
2251
  // account's backup took them in (noteRoom). Our hosted vault's wipe (vault-loader.js wipeVaultAccount) does the same.
1897
- const epoch = privacyEpoch, b = sdk.backup
2252
+ if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1898
2253
  if (b.enabled) {
1899
- try { await b.save() } catch {
1900
- if (!await confirmWith({ title: 'Discard unsaved changes?', text: 'The final backup did not save. Stay signed in to retry or discard changes on this device.', ok: 'Discard and sign out', cancel: 'Stay signed in' })) throw Object.assign(new Error('Sign-out cancelled'), { code: 'cancelled' })
2254
+ try {
2255
+ if (keepRun) await keepRun
2256
+ let saved = false
2257
+ for (let i = 0; !saved && i <= KEEP_AGAIN_MAX; i++) {
2258
+ const revision = keepRevision
2259
+ const [rooms, kept] = await Promise.allSettled([b.save(), keepSync()])
2260
+ if (rooms.status !== 'fulfilled' || kept.status !== 'fulfilled' || !kept.value?.ok) break
2261
+ saved = revision === keepRevision && !kept.value.again
2262
+ }
2263
+ if (!saved) throw new Error('Account changes could not be saved')
2264
+ } catch {
2265
+ if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
2266
+ if (!await confirmWith({ title: 'Discard unsaved changes?', text: 'Some room or account changes could not be saved. Stay signed in to retry or discard changes on this device.', ok: 'Discard and sign out', cancel: 'Stay signed in' })) throw Object.assign(new Error('Sign-out cancelled'), { code: 'cancelled' })
1901
2267
  }
1902
2268
  }
1903
2269
  if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1904
2270
  await wipeSignedOut(); emit({ ev: 'signedOut' }); return { signedIn: false } },
2271
+ async enclaveAvailable() { return sdk._encClaimDoc().then(() => true, () => false) },
1905
2272
  async whoami() { return signedIn() ? { signedIn: true, email: sdk.session.email, keyId: sessionKeyId() } : { signedIn: false } },
1906
2273
  async forget(room) {
2274
+ if (pendingForget.has(room)) { await purgeForgotten(room); return { forgotten: true } }
1907
2275
  if (!held(room)) return { forgotten: false }
1908
2276
  // removing a Space's key from this device can lose it for good (no other copy): the PERSON confirms it (security review)
1909
2277
  const it = rooms.find((x) => x.room === room)
1910
2278
  const accountWide = sdk.backup.enabled
1911
2279
  if (!(await confirmWith({ title: 'Remove ' + (it && it.title ? '“' + it.title + '”' : 'this Space') + (accountWide ? ' from your account?' : ' from this device?'), text: accountWide ? 'This removes it from every device that syncs this account.' : 'Without its invite link you cannot open it here again.', ok: 'Remove', cancel: 'Keep' }).catch(() => false))) throw Object.assign(new Error('cancelled'), { code: 'cancelled' })
1912
- await dropRoom(room)
1913
- if (accountWide && sdk.backup.enabled) sdk.backup.remove(room) // and from the account, on every device
2280
+ if (accountWide && sdk.backup.enabled) { sdk.account.forget(room); await fromBackup() }
2281
+ await dropRoom(room) // and from the account, on every device
1914
2282
  return { forgotten: true }
1915
2283
  },
1916
2284
  })
@@ -1936,7 +2304,7 @@ export async function startVault(o = {}) {
1936
2304
  const d = e.data
1937
2305
  if (!d || d.ch !== 'wbvault') return
1938
2306
  if (d.t === 'hello') {
1939
- toPage({ t: 'welcome', v: VAULT_PROTOCOL, billingPerCall: true, tenant: o.tenant || '', endpoint, signedIn: signedIn(), email: signedIn() ? sdk.session.email : '', keyId: sessionKeyId(), rooms: publicRooms(), siri: siriShortcut(), account: accountView(), keyStates: keyStatesNow(), ...(vlock ? { lock: vlock.view() } : {}), ...(vpush ? { push: vpush.view() } : {}), ...(tapRoom && held(tapRoom) ? { notifOpen: tapRoom } : {}) }) // lock / push: only a vault that offers them says anything
2307
+ toPage({ t: 'welcome', v: VAULT_PROTOCOL, scopedConnectionRevoke: true, hostInvites: true, tierQuery: true, billingPerCall: true, tenant: o.tenant || '', endpoint, signedIn: signedIn(), email: signedIn() ? sdk.session.email : '', keyId: sessionKeyId(), rooms: publicRooms(), siri: siriShortcut(), account: accountView(), keyStates: keyStatesNow(), ...(vlock ? { lock: vlock.view() } : {}), ...(vpush ? { push: vpush.view() } : {}), ...(tapRoom && held(tapRoom) ? { notifOpen: tapRoom } : {}) }) // lock / push: only a vault that offers them says anything
1940
2308
  if (!greeted) { greeted = true; if (typeof screens.ready === 'function') try { screens.ready() } catch { /* */ } joining.then(() => { if (joined) emit({ ev: 'joined', room: joined }) }) }
1941
2309
  return
1942
2310
  }