@witbitz/sdk 4.3.0 → 4.5.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 (112) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +41 -5
  3. package/accountErase.js +15 -4
  4. package/accountIndexDoc.js +24 -7
  5. package/accountRecord.js +6 -2
  6. package/accountStores.js +21 -5
  7. package/acctV2App.js +111 -12
  8. package/acctV2Client.js +11 -1
  9. package/acctV2UiCore.js +27 -7
  10. package/agentDoorTools.js +28 -0
  11. package/awsKey.js +3 -1
  12. package/backupRecord.js +3 -0
  13. package/chatLock.js +16 -0
  14. package/cloudDevicePins.js +2 -2
  15. package/codeAttachments.js +101 -0
  16. package/codeCache.js +173 -0
  17. package/codeCloud.js +2 -2
  18. package/codeComputers.js +9 -0
  19. package/codeFolders.js +116 -0
  20. package/codeHistory.js +76 -0
  21. package/codeLanguage.js +54 -0
  22. package/codeModes.js +2 -0
  23. package/codeProgress.js +54 -0
  24. package/codeSent.js +109 -0
  25. package/codeSubagents.js +107 -0
  26. package/codeTransport.js +46 -5
  27. package/connections.js +37 -20
  28. package/decrypt.html +69 -9
  29. package/deviceAttest.js +9 -3
  30. package/eraseFile.js +15 -0
  31. package/idb.js +19 -3
  32. package/idbSeal.js +5 -2
  33. package/inviteReceive.js +44 -0
  34. package/inviteSend.js +8 -2
  35. package/jobAgents.js +2 -2
  36. package/keptMerge.js +9 -2
  37. package/l1-worker-src.js +1 -1
  38. package/l1-worker.js +122 -43
  39. package/laneAssociation.js +78 -0
  40. package/laneConfig.js +4 -3
  41. package/laneLinkCore.js +9 -0
  42. package/ledgerView.js +30 -4
  43. package/manifest.json +112 -87
  44. package/memberChange.js +4 -2
  45. package/mirrorBatch.js +47 -0
  46. package/offlineBundle.js +21 -0
  47. package/opRouting.js +10 -0
  48. package/package.json +27 -2
  49. package/pdfOptions.js +13 -0
  50. package/pdfText.js +107 -0
  51. package/pdfjs.mjs +28 -0
  52. package/pdfjs.worker.mjs +28 -0
  53. package/protectedLocal.js +52 -13
  54. package/reactionHolders.js +86 -0
  55. package/removedMessage.js +1 -1
  56. package/roomEmbed.js +111 -0
  57. package/roomIntake.js +324 -0
  58. package/roomName.js +1 -1
  59. package/roomRoster.js +30 -7
  60. package/rosterCount.js +6 -3
  61. package/scheduleNext.js +60 -0
  62. package/sdkA2A.js +200 -42
  63. package/sdkAccount.js +88 -18
  64. package/sdkAccountDoc.js +13 -5
  65. package/sdkAccountSections.js +172 -23
  66. package/sdkAgui.js +33 -6
  67. package/sdkBackup.js +53 -11
  68. package/sdkBackupV2.js +15 -3
  69. package/sdkCloudDevice.js +20 -5
  70. package/sdkComputers.js +695 -65
  71. package/sdkDictation.js +115 -25
  72. package/sdkErase.js +12 -5
  73. package/sdkExports.js +19 -8
  74. package/sdkInvitations.js +4 -2
  75. package/sdkKeptAgent.js +19 -3
  76. package/sdkKeptIntake.js +100 -0
  77. package/sdkLaneLink.js +8 -9
  78. package/sdkPlan.js +4 -2
  79. package/sdkRekey.js +122 -22
  80. package/sdkReport.js +1 -1
  81. package/sdkSafeMedia.js +1 -1
  82. package/sdkSchedules.js +8 -1
  83. package/sdkSpeech.js +32 -2
  84. package/sdkTemporaryRooms.js +124 -0
  85. package/sdkTurn.js +12 -4
  86. package/sdkVault.js +66 -10
  87. package/sentinelRelease.js +1 -0
  88. package/sharedViews.js +34 -4
  89. package/siri.js +140 -9
  90. package/spaceClient.js +112 -17
  91. package/spaceEmailGate.js +2 -2
  92. package/spaceExport.js +50 -5
  93. package/spaceFork.js +15 -7
  94. package/spaceTemplates.js +99 -0
  95. package/speechOut.js +21 -5
  96. package/store.js +134 -27
  97. package/sw-notif-core.js +11 -8
  98. package/tapTrail.js +58 -0
  99. package/turnVerdict.js +1 -0
  100. package/usageReceipts.js +12 -5
  101. package/vault-core.js +568 -126
  102. package/vault-kit.mjs +3 -3
  103. package/vault-screens.js +30 -18
  104. package/vaultAtRest.js +38 -6
  105. package/vaultCoreLock.js +3 -1
  106. package/vaultCorePush.js +58 -7
  107. package/vaultKeep.js +9 -3
  108. package/vaultWorkerHost.js +32 -7
  109. package/witbitz-admin.d.ts +3 -0
  110. package/witbitz-admin.mjs +12 -11
  111. package/witbitz-sdk.d.ts +170 -43
  112. package/witbitz-sdk.js +833 -203
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.
@@ -74,12 +77,14 @@ export const ACCOUNT_CALLS = {
74
77
  // (SERVICE_CALLS, below: the three that need an account on the service — checked before their confirm)
75
78
  account: { repairNames: {}, previewEmptySpaces: {}, removeEmptySpaces: {}, listDevices: {}, signOutDevice: {}, sync: {}, start: {}, stop: {}, archive: {}, pin: {}, rename: {}, forget: { confirm: true }, signOut: { confirm: true }, noteLink: {}, dropLink: {}, section: {}, usage: {} }, // section: wb.account.contacts / .name / .roomDefaults (sdkAccountSections.js — the person's own data, no key; plan phase 5) // usage: what the account used, from its receipts (2026-10-23) // noteLink/dropLink: lane.link() across devices (sync sweep, 10-17 #6)
76
79
  erasure: { file: {}, status: {} },
80
+ invite: { collect: {} }, // the invitations delivered to this account: the vault asks before joining, the page gets rooms only (inviteCollect)
77
81
  }
78
82
  /** The backup calls that need an account on the Witbitz account service (sync sweep 11-16 #15). */
79
83
  const SERVICE_CALLS = new Set(['manageSecurityKeys', 'signOutOthers', 'newRecoveryCode', 'emailMove', 'requestMoveTime', 'cancelEmailMove'])
80
84
  export const ROOM_ACCOUNT_CALLS = {
81
85
  roster: { list: {}, admission: {} },
82
86
  portable: { export: { confirm: true } },
87
+ privateRoom: { link: { confirm: true }, unlink: { confirm: true } },
83
88
  keptAgent: { link: { confirm: true }, unlink: { confirm: true } },
84
89
  alwaysOn: { status: {}, enable: { confirm: true }, disable: { confirm: true }, run: {}, assertNotKept: {} },
85
90
  invitations: { resend: { confirm: true } },
@@ -91,10 +96,20 @@ export const ROOM_ACCOUNT_CALLS = {
91
96
  a2a: { view: {}, enable: {}, addPeer: { confirm: true }, setReply: {}, removePeer: {}, disable: {}, pull: {}, ack: {}, reply: {}, sharedDrafts: {}, reviewDraft: {} },
92
97
  }
93
98
  const ASK_MS = 60_000 // the page's answer to a question the vault asks it (a Siri drop handed to its deliver)
99
+ export function publicVaultRooms(rooms, currentRoom) {
100
+ return rooms.filter(currentRoom).map(({ room, title, at, lane, detachedLane, enc, link }) => ({
101
+ room, title: title || '', at,
102
+ ...(lane ? { lane } : {}),
103
+ ...(detachedLane ? { detachedLane: true } : {}),
104
+ ...(enc ? { tier: 'enclave' } : {}),
105
+ ...(roomInviteFlags(link).lanes ? { lanes: true } : {}),
106
+ })).sort((a, b) => (Number(b.at) || 0) - (Number(a.at) || 0))
107
+ }
108
+
94
109
  // What a page may put in a NEW Space's config — the fields the SDK's createSpace writes (roomConfig + the email gate).
95
110
  // Anything else (a key model, a confidential tier, a direct chat) is refused HERE: the SDK's own refusals run in the
96
111
  // 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)
112
+ 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
113
  const CREATE_LIMIT = { n: 20, ms: 10 * 60_000 } // new Spaces per window, per vault page
99
114
  const SPEECH_LIMIT = { n: 30, ms: 10 * 60_000 } // speech keys (dictation, reading aloud) per window, per vault page
100
115
  const REFRESH_BEFORE_MS = 10 * 60_000 // renew the sign-in this long before it expires
@@ -127,9 +142,19 @@ export function vaultSignInWords(e) {
127
142
  return e
128
143
  }
129
144
 
145
+ /** A JOB AGENT'S TRIGGER for a key adopted after a lost reply (side sweep: sdk-recovered-job-connection-loses-trigger-settings): the
146
+ * Sentinel's listing names a one-path trigger under `rules` and holds no job settings — those were kept with the pending key, as the
147
+ * direct SDK's `connections.recover` reads them. A row that already carries `webhook` is taken as it is. */
148
+ export function adoptedHook(row, k) {
149
+ if (row && typeof row.webhook === 'string') return { webhook: row.webhook, ...(row.webhook && row.job && typeof row.job === 'object' ? { job: row.job } : {}) }
150
+ const path = row && row.sign && Array.isArray(row.rules?.paths) && row.rules.paths.length === 1 ? row.rules.paths[0] : ''
151
+ return path ? { webhook: path, ...(k && k.job && typeof k.job === 'object' ? { job: k.job } : {}) } : {}
152
+ }
153
+
130
154
  export function configForPage(cfg) {
131
155
  if (!cfg || typeof cfg !== 'object') return cfg
132
156
  const out = { ...cfg }
157
+ if (Array.isArray(out.keyChain)) out.keyChain = out.keyChain.map((_, epoch) => ({ epoch }))
133
158
  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
159
  if (out.funding && typeof out.funding === 'object') { const { grant: _g, grantToken: _t, key: _x, token: _y, ...rest } = out.funding; out.funding = rest }
135
160
  return out
@@ -158,6 +183,7 @@ const holdLink = (worker, p) => { if (!p) return; if (p.mk) worker.postMessage({
158
183
  export async function startVault(o = {}) {
159
184
  const pageUrl = new URL(String(o.page || ''))
160
185
  const pageOrigin = pageUrl.origin
186
+ 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
187
  if (!/^https?:$/.test(pageUrl.protocol)) throw new Error('vault: `page` must be an http(s) URL')
162
188
  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
189
  if (globalThis.localStorage?.getItem('witbitz-builder-reset-pending')) {
@@ -191,7 +217,7 @@ export async function startVault(o = {}) {
191
217
  hide: () => { frameHidden = true; if (frameEl) frameEl.style.display = 'none' },
192
218
  show: () => { frameHidden = false; if (frameEl) frameEl.style.display = 'block' },
193
219
  onState: (lock) => { if (frameEl) { emit({ ev: 'lock', lock }); queuePushPrivacy() } },
194
- confirm: (q) => (typeof screens.confirm === 'function' ? screens.confirm(q) : Promise.resolve(window.confirm(q.title))),
220
+ confirm: (q) => (typeof screens.confirm === 'function' ? screens.confirm(q) : Promise.resolve(window.confirm(q.text ? q.title + '\n\n' + q.text : q.title))), // the warning goes with the question, never the title alone (side sweep 11-28)
195
221
  onUnprotected: () => workerAtRest(), // protection off: the worker's store goes back under the device key, never clear
196
222
  beforeProtect: async () => { if (workerDeviceKey) { await unprotectIdb(idb, workerDeviceKey); await wcall({ t: 'unprotect', key: workerDeviceKey }) } }, // remove the old device-key copies before resealing with the passkey
197
223
  })
@@ -200,7 +226,7 @@ export async function startVault(o = {}) {
200
226
  // EVERY SECRET ON DISK SEALED (vaultSealedStore.js; the owner, 2026-11-24, as our hosted vault): the session, the invite key, Siri,
201
227
  // 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
228
  const learnedBlocksKey = 'wbvault:learnedBlockIdentities'
203
- const SEALED_KEYS = [learnedBlocksKey, KEYS.session, KEYS.siri, KEYS.a2a, KEYS.invite, KEYS.connections, KEYS.keep, KEYS.connPending]
229
+ 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
230
  const wipeMarker = 'wbvault:signout-pending'
205
231
  let wipeRun = null, peerSignedOut = false
206
232
  const st = sealedStorage(o.storage || localStorage, SEALED_KEYS)
@@ -213,13 +239,18 @@ export async function startVault(o = {}) {
213
239
  const roomPassClient = { fieldsFor: (b, o) => (roomPass ? roomPass.client.fieldsFor(b, o) : Promise.resolve({})), /* o: { ts } — the request's time (roomPass.js sign; sync sweep 11-16 #8) */ renew: (b) => (roomPass ? roomPass.client.renew(b) : Promise.resolve()) }
214
240
  // A SIGN-IN THAT NAMES NO APP (docs/device-gate-design.md § 12.1, `pass: app_unnamed` — a session token from before `asc`): the
215
241
  // session is renewed once, quietly (its /refresh names this vault's tenant), and the request sent again. One renewal at a time.
216
- let renewing = null
242
+ // A request sent with the old sign-in and refused just AFTER a renewal finished is answered with that renewal, not another one
243
+ // (a burst of refused requests renewed three times under load, 2026-11-28): the session it gave names the app already.
244
+ let renewing = null, renewedAt = 0
245
+ const RENEWED_FRESH_MS = 30000
217
246
  const renewSession = () => {
247
+ if (!renewing && renewedAt && Date.now() - renewedAt < RENEWED_FRESH_MS && signedIn() && sdk.session) return Promise.resolve({ idToken: sdk.session.idToken, spk: sdk.session.sign.pub })
218
248
  if (!renewing) renewing = (async () => {
219
249
  try {
220
250
  if (!signedIn()) return null
221
251
  const renewed = await sdk.refreshSession()
222
252
  if (sdk._session !== renewed) return null
253
+ renewedAt = Date.now()
223
254
  keepSession(); emit({ ev: 'session', keyId: sessionKeyId() }); scheduleRefresh()
224
255
  return { idToken: sdk.session.idToken, spk: sdk.session.sign.pub }
225
256
  } catch (err) {
@@ -254,12 +285,18 @@ export async function startVault(o = {}) {
254
285
  await st.open(wrapKey) // the sealed secrets, opened into memory (and an older clear copy sealed) before anything reads one
255
286
  const savedSession = read(st, KEYS.session, null)
256
287
  if (savedSession) sdk.useSession(savedSession)
257
- const atRest = createAtRest({ storage: st, key: wrapKey })
288
+ const forgetPrefix = 'wbvault:forgot:'
289
+ const forgetMark = room => st.getItem(forgetPrefix + room) || ''
290
+ const currentRoom = row => !!row && (row.forgetMark || '') === forgetMark(row.room)
291
+ const joinedMark = room => { const mark = forgetMark(room); return mark ? { forgetMark: mark } : {} }
292
+ const atRest = createAtRest({ storage: st, key: wrapKey, currentRoom })
258
293
  let rooms = await atRest.loadRooms(KEYS.rooms) // [{ room, link, title, at }] — in memory the link IS the key; it never leaves this origin
294
+ const pendingForget = new Set(read(st, KEYS.pendingForget, []) || [])
295
+ rooms = rooms.filter(r => !pendingForget.has(r.room) && currentRoom(r))
259
296
  let vpush = null // notifications (`push: true`, vaultCorePush.js): every Space held lists this device, kept in step at each save
260
297
  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)
298
+ 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
299
+ sdk._heldLaneRooms = (parent) => rooms.filter((r) => currentRoom(r) && r.lane === parent).map((r) => r.room)
263
300
  sdk._detachHeldLanes = async (parent) => {
264
301
  for (const r of rooms) if (r.lane === parent) { delete r.lane; r.detachedLane = true }
265
302
  await saveRooms()
@@ -267,10 +304,13 @@ export async function startVault(o = {}) {
267
304
  }
268
305
  if (sdk.session?.email) await atRest.claimEmailMove(KEYS.backup, sdk.session.email)
269
306
  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)
307
+ const publicRooms = () => publicVaultRooms(rooms, currentRoom)
271
308
 
272
309
  // ── the key worker ───────────────────────────────────────────────────────────────────────────────────────────────
273
310
  let worker = null, wseq = 0
311
+ const streamGrants = new Map()
312
+ const syncStream = workerStreams()
313
+ const applyStream = (w, room) => syncStream(w, room, streaming.has(room) ? { t: 'streamOpen', room, grants: streamGrants.get(room) } : null)
274
314
  const streaming = new Set() // rooms the page holds a live stream for (CALLS.stream); the socket lives in the worker
275
315
  const wwait = new Map()
276
316
  const signedIn = () => { const s = sdk.session; return !!(s && s.idToken && s.sign && !(s.exp && s.exp <= Date.now())) }
@@ -301,6 +341,11 @@ export async function startVault(o = {}) {
301
341
  const id = ++wseq
302
342
  wwait.set(id, { res, rej })
303
343
  try { target.postMessage({ id, ...msg }) } catch (err) { wwait.delete(id); rej(err) }
344
+ }).then(result => {
345
+ if (msg.t === 'op' && (msg.op === 'poll' || msg.op === 'pollSealed') && target === worker && held(msg.room) && result?.status === 200 && Array.isArray(result.streamGrants)) {
346
+ streamGrants.set(msg.room, result.streamGrants)
347
+ }
348
+ return result
304
349
  })
305
350
  }
306
351
  // 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 +407,15 @@ export async function startVault(o = {}) {
362
407
  workerHost.replay('open', () => wcall({ t: 'open', room: null, mk: null, endpoint, app: o.app || 'vault', ...(o.tenant ? { tenant: o.tenant } : {}) }))
363
408
  workerHost.replay('links', async w => {
364
409
  for (const r of rooms) {
410
+ if (!currentRoom(r)) continue
365
411
  const p = linkParts(r.link)
366
412
  if (!p || p.room !== r.room) continue
367
413
  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 })
414
+ 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
415
  seedIdentity(r.room)
370
416
  }
371
417
  })
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
418
+ 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
419
  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
420
  workerHost.replay('pushAcct', (w) => { if (pushAcctSecret) w.postMessage({ t: 'setPushAcct', secret: pushAcctSecret }) }) // …nor its account's other devices (handDownPushAcct)
375
421
  workerHost.replay('prefetch', () => prefetchWorker())
@@ -406,9 +452,19 @@ export async function startVault(o = {}) {
406
452
  if (!worker) return
407
453
  worker.postMessage(enclaveMsg())
408
454
  }
409
- let encReady = null // one attestation at a time, shared
410
- const encAttest = (room) => (encReady ||= sdk._encAttest(room).then(() => { pushEnclave() }).finally(() => { encReady = null }))
455
+ const pendingAttestations = new Map()
456
+ const encAttest = (room) => {
457
+ const region = roomRegion(room)
458
+ if (!pendingAttestations.has(region)) {
459
+ const pending = sdk._encAttest(room).then(() => { pushEnclave() }).finally(() => pendingAttestations.delete(region))
460
+ pendingAttestations.set(region, pending)
461
+ }
462
+ return pendingAttestations.get(region)
463
+ }
411
464
  await startWorker()
465
+ if (pendingForget.size) {
466
+ await Promise.allSettled([...pendingForget].map(purgeForgotten))
467
+ }
412
468
  if (vlock) vlock.setWorker((m) => wcall(m)) // the lock's seal / unseal / relock / unprotect reach whichever worker is current
413
469
  // ── NOTIFICATIONS, opt-in twice (vaultCorePush.js; 2026-11-13): the builder starts the vault with `push: true`, the person turns
414
470
  // 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,15 +495,46 @@ export async function startVault(o = {}) {
439
495
  if (tapRoom) { try { history.replaceState(null, '', location.pathname) } catch { /* */ } }
440
496
  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
497
  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
498
+ 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
499
  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
500
  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()
501
+ 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
502
  pushEnclave()
447
503
  holdLink(worker, inv); seedIdentity(inv.room); noteRoom(inv.room).catch(() => {})
448
504
  joined = inv.room
449
505
  emit({ ev: 'rooms', rooms: publicRooms() })
450
506
  }
507
+ // THE INVITATIONS DELIVERED TO THIS ACCOUNT (side sweep: sdk-missing-inbox-invite-acceptance): the page's wb.invite.collect() threw
508
+ // vault_unsupported. The vault opens its inbox with ITS invite key, asks the person before joining a Space it does not hold (as an
509
+ // invite link: nothing is joined silently), keeps the links, and tells the page the rooms only — no link, no key; the page opens
510
+ // each with wb.vault.openRoom(room). A held room's key is never replaced by an invitation (as joinInvite).
511
+ async function inviteCollect() {
512
+ const epoch = privacyEpoch, owner = who()
513
+ const changed = () => epoch !== privacyEpoch || owner !== who()
514
+ const gone = () => Object.assign(new Error('the account changed while collecting invitations'), { code: 'account_changed' })
515
+ const got = await sdk.invite.collect()
516
+ if (changed()) throw gone()
517
+ const fresh = got.filter((x) => !held(x.room) && linkParts(x.link) && linkParts(x.link).room === x.room)
518
+ if (fresh.length) {
519
+ const ok = await confirmWith({ title: fresh.length === 1 ? 'Join the Space shared with you?' : 'Join the ' + fresh.length + ' Spaces shared with you?', text: 'Someone invited your account. Join on this device?', ok: 'Join', cancel: 'Not now' }).catch(() => false)
520
+ if (changed()) throw gone()
521
+ if (ok) {
522
+ const joinedNow = []
523
+ for (const x of fresh) {
524
+ if (held(x.room)) continue
525
+ const p = linkParts(x.link)
526
+ rooms = [{ room: x.room, ...joinedMark(x.room), link: x.link, title: '', at: Date.now(), ...(/[?#&]enc=1(?:[&#?]|$)/.test(x.link) ? { enc: true } : {}), ...(p.split ? { split: true } : {}) }, ...rooms]
527
+ holdLink(worker, p); seedIdentity(x.room); joinedNow.push(x.room)
528
+ }
529
+ if (joinedNow.length) {
530
+ await saveRooms(); pushEnclave()
531
+ for (const r of joinedNow) noteRoom(r).catch(() => {})
532
+ emit({ ev: 'rooms', rooms: publicRooms() })
533
+ }
534
+ }
535
+ }
536
+ return got.filter((x) => held(x.room)).map(({ room, title, from, at }) => ({ room, link: '', title, from, at }))
537
+ }
451
538
 
452
539
  // ── the sign-in, kept and renewed here ────────────────────────────────────────────────────────────────────────────
453
540
  const keepSession = () => { write(st, KEYS.session, sdk.session); for (const r of rooms) seedIdentity(r.room); prefetchWorker() }
@@ -483,7 +570,7 @@ export async function startVault(o = {}) {
483
570
  const { genKeypair, spkNonce } = await import('./entrySig.js')
484
571
  const { brokerGoogleToken } = await import('./spaceEmailGate.js')
485
572
  const sign = await genKeypair(), nonce = await spkNonce(sign.pub)
486
- const result = await brokerGoogleToken({ nonce, broker: o.authBroker || 'https://auth.witbitz.chat' })
573
+ const result = await brokerGoogleToken({ nonce, watchPopup: false, broker: o.authBroker || 'https://auth.witbitz.chat' })
487
574
  if (sdk._session !== session) throw Object.assign(new Error('the account changed during sign-in'), { code: 'account_changed' })
488
575
  if (!result || !result.idToken || !result.email) throw Object.assign(new Error('Google sign-in was not completed'), { code: 'sign_in_cancelled' })
489
576
  const { jwtPayload } = await import('./emailSignIn.js')
@@ -500,7 +587,12 @@ export async function startVault(o = {}) {
500
587
 
501
588
  // ── the frame ────────────────────────────────────────────────────────────────────────────────────────────────────
502
589
  const frame = document.createElement('iframe')
503
- frame.src = pageUrl.href
590
+ let launchPage = pageUrl.href
591
+ if (inv && o.hostInviteTemplate && new URL(invLink).searchParams.get('hostInvite') === '1') {
592
+ const locator = new URL(invLink); locator.hash = ''; locator.search = ''; locator.searchParams.set('room', inv.room)
593
+ launchPage = embeddedInvite(o.hostInviteTemplate, locator.href, pageOrigin)
594
+ }
595
+ frame.src = launchPage
504
596
  frame.title = o.title || 'App'
505
597
  frame.setAttribute('allow', "clipboard-write; microphone; publickey-credentials-create 'src'; publickey-credentials-get 'src'")
506
598
  // No allow-top-navigation (security review): the page must not send the whole window — the vault — somewhere else.
@@ -514,6 +606,9 @@ export async function startVault(o = {}) {
514
606
  // (sync sweep 11-08 #28: only the message and code crossed); plain data only, bounded
515
607
  const errExtra = (err) => {
516
608
  const o = {}
609
+ if (err?.code === 'partial_revoke') for (const key of ['removedFrom', 'unchecked']) {
610
+ if (Array.isArray(err[key])) o[key] = err[key].filter(id => typeof id === 'string' && held(id)).slice(0, 1000)
611
+ }
517
612
  if (Array.isArray(err?.unavailable)) o.unavailable = err.unavailable.filter(id => typeof id === 'string' && id.length <= 160).slice(0, 1000)
518
613
  if (err && Number.isInteger(err.status)) o.status = err.status
519
614
  if (err?.code === 'wrong_pin' && Number.isSafeInteger(err.next) && err.next >= 0) o.next = err.next
@@ -523,7 +618,7 @@ export async function startVault(o = {}) {
523
618
  }
524
619
  const refuse = (id, error, code, extra = {}) => toPage({ t: 'res', id, error, code, ...extra })
525
620
 
526
- const held = (room) => typeof room === 'string' && rooms.some((r) => r.room === room)
621
+ const held = (room) => typeof room === 'string' && rooms.some((r) => r.room === room && currentRoom(r))
527
622
  let creates = [] // when this page last created Spaces (CREATE_LIMIT)
528
623
  let speechKeys = [] // when this page last asked for a speech key (SPEECH_LIMIT)
529
624
 
@@ -539,10 +634,33 @@ export async function startVault(o = {}) {
539
634
  const moved = tabs.moved(); if (!moved.length) return
540
635
  if (moved.includes(KEYS.connections)) conns = read(st, KEYS.connections, [])
541
636
  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 */ } }
637
+ 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 */ } }
638
+ 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 */ } }
544
639
  }
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) */ }
640
+ 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) */ }
641
+ let removalWrites = Promise.resolve()
642
+ function connectionChange(acct, id, detached, expected) {
643
+ if (!acct || !id) return Promise.resolve()
644
+ const ownerEpoch = privacyEpoch
645
+ const update = async () => {
646
+ await st.refresh(KEYS.connGone)
647
+ if (privacyEpoch !== ownerEpoch) return
648
+ const all = read(st, KEYS.connGone, {}) || {}
649
+ const gone = { ...all[acct] }
650
+ if (expected !== undefined && gone[id] !== expected) return
651
+ if (detached) gone[id] = Math.max(Date.now(), (Number(gone[id]) || 0) + 1)
652
+ else delete gone[id]
653
+ if (Object.keys(gone).length) all[acct] = gone
654
+ else delete all[acct]
655
+ const saved = JSON.stringify(all)
656
+ st.setItem(KEYS.connGone, saved)
657
+ if (await st.durableItem(KEYS.connGone) !== saved) throw new Error('Could not save the connection removal')
658
+ }
659
+ const next = removalWrites.then(() => globalThis.navigator?.locks ? navigator.locks.request('wbvault:connection-removals', update) : update())
660
+ removalWrites = next.catch(() => {})
661
+ return next
662
+ }
663
+ sdk.connections._bindingFor = (id, account) => conns.find(c => c.id === id && c.account === account)
546
664
  const saveConns = () => { put(KEYS.connections, conns); keepSoon() }
547
665
  // 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
666
  // set here while the answer is out (connections.js postWithPendingKey); a lost answer left a connection the account lists and no key
@@ -562,24 +680,35 @@ export async function startVault(o = {}) {
562
680
  pendingWrites = next.catch(() => {})
563
681
  return next
564
682
  }
565
- setPendingKeyStore({
683
+ sdk.connections._vaultPending = {
566
684
  durable: true,
567
685
  keep: (id, rec) => { const ownerEmail = who(); return updatePending(rows => { rows[id] = { ...rec, ownerEmail, at: Number(rec?.at) || Date.now() } }) },
568
686
  drop: id => updatePending(rows => { delete rows[id] }),
569
- })
570
- const adoptPending = async (listedIds, acct) => {
687
+ }
688
+ setPendingKeyStore(sdk.connections._vaultPending)
689
+ const adoptPending = async (listed, acct) => {
690
+ const byId = new Map(listed.filter(c => c?.id).map(c => [c.id, c]))
571
691
  const epoch = privacyEpoch, ownerEmail = who()
572
692
  await st.refresh(KEYS.connPending)
573
693
  if (epoch !== privacyEpoch || ownerEmail !== who()) return
574
694
  const snapshot = read(st, KEYS.connPending, {}) || {}
575
695
  const eligible = Object.fromEntries(Object.entries(snapshot).filter(([, k]) => !k?.ownerEmail || k.ownerEmail === ownerEmail))
576
- const r = adoptPendingKeys(eligible, listedIds, {})
696
+ const r = adoptPendingKeys(eligible, [...byId.keys()], {})
577
697
  for (const [id, k] of r.adopt) {
578
698
  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]
699
+ const row = byId.get(id)
700
+ 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 } : {}), ...adoptedHook(row, k) }, ...conns]
580
701
  }
581
702
  }
582
- if (r.adopt.length) saveConns()
703
+ let changed = false
704
+ conns = conns.map(c => {
705
+ const row = c.account === acct && byId.get(c.id)
706
+ if (!row) return c
707
+ const next = { ...c, mcp: !!row.mcp, label: row.label || c.label || '', host: row.host || c.host || '', ...(row.provider ? { provider: row.provider } : {}), ...hookOf(row) }
708
+ if (JSON.stringify(next) !== JSON.stringify(c)) changed = true
709
+ return next
710
+ })
711
+ if (changed || r.adopt.length) saveConns()
583
712
  let durable
584
713
  try { durable = JSON.parse(await st.durableItem(KEYS.connections) || '[]') } catch { return }
585
714
  if (epoch !== privacyEpoch || ownerEmail !== who() || !Array.isArray(durable)) return
@@ -587,7 +716,7 @@ export async function startVault(o = {}) {
587
716
  if (epoch !== privacyEpoch || ownerEmail !== who()) return
588
717
  for (const [id, rec] of Object.entries(eligible)) {
589
718
  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
719
+ if (byId.has(id) && !durable.some(c => c.account === acct && c.id === id && c.callKey === rec?.callKey)) continue
591
720
  delete pending[id]
592
721
  }
593
722
  })
@@ -595,16 +724,95 @@ export async function startVault(o = {}) {
595
724
  // Siri's state (the inbox private keys) is kept PER ACCOUNT: a second person signing in on this vault never gets the
596
725
  // first one's keys, and the first one's come back when they sign in again.
597
726
  const who = () => (signedIn() ? String(sdk.session.email || '').toLowerCase() : '')
727
+ // The remote inbox must never receive a public key before the matching secret survives a reload.
728
+ const stageInbox = key => async candidate => {
729
+ const owner = who(), epoch = privacyEpoch
730
+ if (!owner) throw Object.assign(new Error('Sign in to save this inbox'), { code: 'sign_in_required' })
731
+ const pending = 'pending:' + owner
732
+ const records = read(st, key, {}) || {}
733
+ const entry = { base: records[owner] || null, next: candidate }
734
+ const serialized = JSON.stringify(entry)
735
+ put(key, { ...records, [pending]: entry })
736
+ const disk = JSON.parse(await st.durableItem(key) || '{}')
737
+ if (owner !== who() || epoch !== privacyEpoch) throw Object.assign(new Error('Account changed during inbox setup'), { code: 'account_changed' })
738
+ if (JSON.stringify(disk[pending]) !== serialized) throw Object.assign(new Error('Could not save the inbox key on this device'), { code: 'save_failed' })
739
+ return accepted => {
740
+ if (owner !== who() || epoch !== privacyEpoch) return
741
+ const latest = read(st, key, {}) || {}
742
+ if (JSON.stringify(latest[pending]) !== serialized) return
743
+ if (accepted) latest[owner] = candidate
744
+ delete latest[pending]
745
+ put(key, latest)
746
+ }
747
+ }
748
+ sdk.siri._stageInbox = stageInbox(KEYS.siri)
749
+ sdk.a2a._stageInbox = stageInbox(KEYS.a2a)
750
+ function recoverInbox(key, owner) {
751
+ const pending = 'pending:' + owner, records = read(st, key, {}) || {}
752
+ const entry = records[pending], committed = records[owner] || null
753
+ if (!entry) return committed
754
+ const api = key === KEYS.siri ? sdk.siri : sdk.a2a
755
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
756
+ // Reapply the user's edit only where the value it replaced is still current.
757
+ const applyEdit = (before, after, current) => {
758
+ if (same(before, after) || same(after, current)) return current
759
+ if (same(before, current)) return after
760
+ if (Array.isArray(before) && Array.isArray(after) && Array.isArray(current) && [...before, ...after, ...current].every(peer => typeof peer?.id === 'string')) {
761
+ const earlier = new Map(before.map(peer => [peer.id, peer])), edits = new Map(after.map(peer => [peer.id, peer]))
762
+ const result = current.map(peer => applyEdit(earlier.get(peer.id), edits.get(peer.id), peer)).filter(Boolean)
763
+ const seen = new Set(current.map(peer => peer.id))
764
+ for (const peer of after) if (!earlier.has(peer.id) && !seen.has(peer.id)) result.push(peer)
765
+ return result
766
+ }
767
+ if (!after || !current || typeof after !== 'object' || typeof current !== 'object' || Array.isArray(current) || Array.isArray(after)) return current
768
+ if (after.pub && current.pub && !same(after.pub, current.pub)) return current
769
+ const out = { ...current }
770
+ for (const k of new Set([...Object.keys(before || {}), ...Object.keys(after)])) {
771
+ const value = applyEdit(before?.[k], after[k], current[k])
772
+ if (value === undefined) delete out[k]; else out[k] = value
773
+ }
774
+ return out
775
+ }
776
+ const replay = async () => {
777
+ const epoch = privacyEpoch
778
+ const get = () => read(st, key, {}) || {}
779
+ const unchanged = () => who() === owner && privacyEpoch === epoch && JSON.stringify(get()[pending]) === JSON.stringify(entry)
780
+ if (!unchanged()) return
781
+ for (let attempt = 0; attempt < 3 && unchanged(); attempt++) {
782
+ const current = get()[owner] || null
783
+ 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))) {
784
+ const kept = get(); delete kept[pending]; put(key, kept); return
785
+ }
786
+ const next = applyEdit(entry.next ? entry.base : committed, entry.next || entry, current)
787
+ if (!next) return
788
+ try {
789
+ await api._push(next)
790
+ } catch (error) {
791
+ if (unchanged() && error.definiteRefusal) { const kept = get(); delete kept[pending]; put(key, kept) }
792
+ return
793
+ }
794
+ if (!unchanged()) return
795
+ const kept = get()
796
+ if (!same(kept[owner] || null, current)) continue
797
+ kept[owner] = next; delete kept[pending]; put(key, kept)
798
+ api.restore(next); keepSoon()
799
+ emit(key === KEYS.siri ? { ev: 'siri', siri: siriShortcut() } : { ev: 'a2aChanged' })
800
+ return
801
+ }
802
+ }
803
+ api._q = (api._q || Promise.resolve()).then(replay, replay).catch(() => {})
804
+ return committed
805
+ }
598
806
  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
807
  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
808
  // ── 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
809
  // connections but could not use one (`not_in_vault`), and could not open Siri or an outside agent's message. Synced, sealed,
602
810
  // 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
811
  // that finds another account signed in when it lands keeps nothing.
604
- let keepT = null, keepRun = null, keepAgain = 0, keepMoved = null
812
+ let keepRevision = 0, keepT = null, keepRun = null, keepAgain = 0, keepMoved = null
605
813
  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
814
  let lastKeepFailure = null
607
- function keepSoon (ms = 1500) { clearTimeout(keepT); keepT = setTimeout(() => { keepSync().catch(() => {}) }, ms) }
815
+ function keepSoon (ms = 1500) { keepRevision++; clearTimeout(keepT); keepT = setTimeout(() => { keepSync().catch(() => {}) }, ms) }
608
816
  async function keepSync () {
609
817
  if (keepRun) return keepRun
610
818
  const owner = who(), master = sdk.backup._s?.master
@@ -623,14 +831,24 @@ export async function startVault(o = {}) {
623
831
  // save the next pass deleted the other devices' connections, Siri and outside agents on every device — and applied over
624
832
  // a connection attached meanwhile.
625
833
  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 } },
834
+ await removalWrites
835
+ await st.refresh(KEYS.connGone)
836
+ if (who() !== w) return { ok: false, why: 'moved' }
837
+ 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
838
  settle: (p) => { // in keepPass's own step, right after it looked at the stores: no attach or detach can land in between
628
839
  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
840
+ if (p.apply) {
841
+ applyKeep(acct, p.apply)
842
+ const pending = read(st, KEYS.connGone, {})?.[acct] || {}
843
+ for (const [id, at] of Object.entries(pending)) {
844
+ const tomb = p.record.conns?.[id]
845
+ if (tomb?.gone && tomb.at >= at) connectionChange(acct, id, false, at).catch(() => keepSoon())
846
+ }
847
+ } // into the stores FIRST: were it to throw, `prev` stays what the stores hold
630
848
  const all2 = read(st, KEYS.keep, {}) || {}; all2[w] = p.record; write(st, KEYS.keep, all2)
631
849
  } })
632
850
  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)
851
+ const ch = keepMoved; keepMoved = null; await pushAfterApply(w, ch) // what the apply moved at the Sentinel's side (K#8)
634
852
  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
853
  return p
636
854
  })()
@@ -653,27 +871,44 @@ export async function startVault(o = {}) {
653
871
  // delete would have granted the old key again).
654
872
  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
873
  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
874
+ async function pushAfterApply (w, ch) { // after the pass, never inside it: the answer is the Sentinel's, the keep is already settled
657
875
  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 */ })
876
+ const byOwner = read(st, KEYS.pendingGrants, {}) || {}
877
+ const previous = byOwner[w] || {}
878
+ const pending = { a2a: previous.a2a || !!ch?.a2a, siri: previous.siri || !!ch?.siri, hadKey: previous.hadKey || !!(ch?.siri && ch.hadKey) }
879
+ if (!pending.a2a && !pending.siri) return
880
+ const save = () => {
881
+ const all = read(st, KEYS.pendingGrants, {}) || {}
882
+ if (pending.a2a || pending.siri) all[w] = { ...pending }; else delete all[w]
883
+ write(st, KEYS.pendingGrants, all)
662
884
  }
885
+ save(); await st.flushed()
886
+ if (who() !== w) return
887
+ if (pending.a2a) { try { await sdk.a2a._push(); pending.a2a = false } catch { /* retry on the next account sync */ } }
888
+ if (who() !== w) return
889
+ if (pending.siri) {
890
+ try {
891
+ if (sdk.siri.state.token || sdk.siri.state.tokenHash) await sdk.siri._push()
892
+ else if (pending.hadKey) { await sdk.siri.revoke(); if (who() === w) saveSiri() }
893
+ pending.siri = false
894
+ } catch { /* retry on the next account sync */ }
895
+ }
896
+ if (who() === w) { save(); if (pending.siri || pending.a2a) keepSoon(30000) }
663
897
  }
664
898
  function applyKeep (acct, keep) { // the merged view into this vault — written straight to storage (no new stamp: it IS the merged state)
665
899
  const v = viewOfKeep(keep), w = who()
666
900
  const was = { a2a: a2aSent(), siri: siriSent(), hadKey: !!sdk.siri.state.token }
667
901
  conns = [...v.conns.map((c) => ({ ...c, account: acct })), ...conns.filter((c) => c.account !== acct)]
668
902
  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 */ }
903
+ 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 */ } }
904
+ const priorA2A = JSON.stringify(sdk.a2a.state)
905
+ 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
906
  keepMoved = { a2a: a2aSent() !== was.a2a, siri: siriSent() !== was.siri, hadKey: was.hadKey } // read by keepSync after the pass (K#8)
672
907
  }
673
908
  const loadSiri = () => { // and A2A's: the same rule
674
909
  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)
910
+ sdk.siri.restore(w ? recoverInbox(KEYS.siri, w) : null)
911
+ sdk.a2a.restore(w ? recoverInbox(KEYS.a2a, w) : null)
677
912
  // 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
913
  const inv = w ? (read(st, KEYS.invite, {}) || {})[w] || null : null
679
914
  if (inv) { try { sdk.invite.restore(inv) } catch { /* a malformed copy: the next sign-in publishes a fresh one */ } }
@@ -698,14 +933,17 @@ export async function startVault(o = {}) {
698
933
  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
934
  }
700
935
  } 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] || {})
936
+ else if (m === 'reply') {
937
+ const id = args[2]?.autoPeerId
938
+ result = id && !shim.peers.some(p => p.id === id && p.reply === 'auto') ? { held: true } : await shim.reply(args[0], args[1], args[2] || {})
939
+ }
702
940
  else result = await shim[m](...args)
703
941
  // 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
942
  // 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
943
  if (m === 'addPeer' && result) {
706
944
  const v = a2aView(room), show = await screenFor('peerToken')
707
945
  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) }
946
+ 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
947
  }
710
948
  else if (result && typeof result === 'object' && 'cardUrl' in result) result = {}
711
949
  saveA2A()
@@ -745,7 +983,7 @@ export async function startVault(o = {}) {
745
983
  const p = (async () => {
746
984
  const g = await wcall({ t: 'op', op: 'grant', room, args: [] }).catch(() => null)
747
985
  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'
986
+ const k = await openGrant(g, room, sdk.invite._key(), { gated: !!(it0 && roomInviteFlags(it0.link).gated) }) // a link Space: 'link_changed', never 'removed'
749
987
  if (k.removed || k.wait) {
750
988
  const why = k.removed ? 'removed' : k.wait
751
989
  const was = keyWaits.get(room); keyWaits.set(room, { at: Date.now(), why })
@@ -754,7 +992,7 @@ export async function startVault(o = {}) {
754
992
  }
755
993
  if (k.userShare) await wcall({ t: 'rememberSplit', room, userShare: k.userShare, commit: k.commit, ep: k.epoch })
756
994
  else await wcall({ t: 'remember', room, mk: k.mk, ep: k.epoch })
757
- keyWaits.delete(room); relinkRoom(room, k)
995
+ streamGrants.delete(room); keyWaits.delete(room); relinkRoom(room, k)
758
996
  emit({ ev: 'key', room, kind: 'rekeyed', epoch: k.epoch })
759
997
  return true
760
998
  })().catch(() => false).finally(() => keyAdopting.delete(room))
@@ -768,7 +1006,7 @@ export async function startVault(o = {}) {
768
1006
  const learnTier = (room, r) => {
769
1007
  if (!room || !saysConfidential(r)) return
770
1008
  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 */ }
1009
+ it.enc = true; saveRooms(); noteRoom(room).catch(() => {}); emit({ ev: 'rooms', rooms: publicRooms() }); try { pushEnclave() } catch { /* the next op re-sends the snapshot */ }
772
1010
  }
773
1011
  const opHealed = async (op, room, args) => {
774
1012
  const r = await wcall({ t: 'op', op, room, args })
@@ -781,9 +1019,13 @@ export async function startVault(o = {}) {
781
1019
  // bridge to its shared room and none of the lane's actions or links. Keyless both ways — the worker holds both keys.
782
1020
  const roomSpace = (room) => {
783
1021
  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 })
1022
+ const sp = it?.lane ? new Lane(workerClient, { room, mk: null, link: null, wb: sdk, live: false, poll: false, sharedRoom: it.lane, sharedMk: null })
1023
+ : new Space(workerClient, { room, mk: null, link: null, wb: sdk, live: false, poll: false })
1024
+ if (it?.title) sp._title = { title: it.title }
1025
+ return sp
786
1026
  }
1027
+ sdk._scopedRoom = roomSpace
1028
+ sdk._siriLane = room => rooms.find(r => r.lane === room && !r.detachedLane)?.room
787
1029
  sdk._agentRoom = roomSpace
788
1030
  sdk._keepAgentConnection = async (conn, ownLink) => {
789
1031
  const session = sdk._session
@@ -792,7 +1034,7 @@ export async function startVault(o = {}) {
792
1034
  conns = [{ ...conn, account, ownLink }, ...conns.filter((c) => c.id !== conn.id || c.account !== account)]
793
1035
  saveConns()
794
1036
  }
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() }
1037
+ 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
1038
  const wop = (op, room, ...args) => opHealed(op, room, args)
797
1039
  // ── 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
1040
  // notice, sealed to each keeper's device) and the session's signing key, both the vault's
@@ -805,7 +1047,6 @@ export async function startVault(o = {}) {
805
1047
  if (!signedIn()) throw Object.assign(new Error('vault: sign in first'), { code: 'sign_in_required' })
806
1048
  const it = rooms.find((x) => x.room === room)
807
1049
  const parts = linkParts(it.link) || {}
808
- const emails = rotate ? [] : (admission && Array.isArray(admission.emails) ? admission.emails : []).map((x) => String(x).slice(0, 80))
809
1050
  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
1051
  if (!rotate) { try { await assertNotKept(sp) } catch (e) { sp.close(); throw e } }
811
1052
  // A SLEEPING CONFIDENTIAL SPACE (sweep 10-25 #1): the SDK wakes one before its first read only when its OWN enclave list
@@ -822,16 +1063,24 @@ export async function startVault(o = {}) {
822
1063
  let plan = null
823
1064
  try { plan = rotate ? null : await planMembers(sp, admission, cur && cur.cfg) } catch (e) { sp.close(); throw e }
824
1065
  const roleOnly = !!(plan && plan.roles)
1066
+ const summary = plan ? [
1067
+ 'Members: ' + plan.emails.join(', '),
1068
+ 'Domains: ' + ((plan.m.allow.domains || []).join(', ') || 'none'),
1069
+ 'Owners: ' + (plan.want.owners.join(', ') || 'none'),
1070
+ 'Admins: ' + (plan.want.admins.join(', ') || 'none'),
1071
+ ...(plan.m.allow.users?.length ? ['Usernames: ' + plan.m.allow.users.map(u => u.handle).join(', ')] : []),
1072
+ ...(plan.m.allow.mh?.length ? ['Private membership entries: ' + plan.m.allow.mh.length] : []),
1073
+ ].join('\n') : ''
825
1074
  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' }
1075
+ ? { title: 'Change who manages ' + titleOf(room) + '?', text: summary, ok: 'Change', cancel: 'Cancel' }
827
1076
  : rotate
828
1077
  ? { 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)
1078
+ : { title: 'Change the members of ' + titleOf(room) + '?', text: summary, ok: 'Change', cancel: 'Cancel' }).catch(() => false)
830
1079
  if (!ok) { sp.close(); throw Object.assign(new Error('cancelled'), { code: 'cancelled' }) }
831
1080
  try {
832
- const r = rotate ? await rotateKey(sp) : await changeMembers(sp, admission)
1081
+ const r = rotate ? await rotateKey(sp) : await changeMembers(sp, admission, plan)
833
1082
  it.link = sp.shareLink; saveRooms(); noteRoom(room).catch(() => {})
834
- if (!r.roles) emit({ ev: 'key', room, kind: 'rekeyed', epoch: r.epoch })
1083
+ if (!r.roles) { streamGrants.delete(room); emit({ ev: 'key', room, kind: 'rekeyed', epoch: r.epoch }) }
835
1084
  const { link: _l, ...out } = r // the link carries the key: the page asks for it with share()
836
1085
  return out
837
1086
  } finally { sp.close() }
@@ -874,7 +1123,7 @@ export async function startVault(o = {}) {
874
1123
  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
1124
  }
876
1125
  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(() => {})
1126
+ 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
1127
  emit({ ev: 'rooms', rooms: publicRooms() })
879
1128
  return { room: o.room }
880
1129
  }
@@ -892,7 +1141,7 @@ export async function startVault(o = {}) {
892
1141
  if (!r || r.status !== 200 || sessionKeyId() !== identity || !held(room)) return { announced: false }
893
1142
  const { roster, changed } = ensureSelf(r.state, self)
894
1143
  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)
1144
+ 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
1145
  if (written?.status === 409) continue
897
1146
  if (written?.status !== 200) return { announced: false }
898
1147
  announcedIn(room, self.id)
@@ -901,42 +1150,57 @@ export async function startVault(o = {}) {
901
1150
  return { announced: false }
902
1151
  }
903
1152
  const titleOf = (room) => { const it = rooms.find((x) => x.room === room); return it && it.title ? '“' + it.title + '”' : 'this Space' }
1153
+ // TWO ROOMS IN ONE PROMPT are each named, titled or not (side sweep: builder-vault-kept-link-confirmation-omits-rooms): the vault makes
1154
+ // rooms and lanes with no title, and two "this Space" left the pair unidentified. A lane of a titled Space is named by it; else the id.
1155
+ const pairName = (room) => {
1156
+ const it = rooms.find((x) => x.room === room)
1157
+ if (it && it.title) return '“' + it.title + '”'
1158
+ const parent = it && it.lane && rooms.find((x) => x.room === it.lane)
1159
+ if (parent && parent.title) return 'your lane of “' + parent.title + '”'
1160
+ return 'the untitled ' + (it && it.lane ? 'lane ' : 'Space ') + String(room).slice(0, 40)
1161
+ }
904
1162
  // the device whose index entry names its key (spk), on an account on the service: signed out THERE too (accountCall's signOut)
905
1163
  const revokesAtService = (id) => { const b = sdk.backup, d = sdk.account._devices && sdk.account._devices[id]; return !!(d && typeof d.spk === 'string' && d.spk && b._v2 && b.service === 'account' && b.enabled) }
906
1164
  const confirmCall = async (ns, m, args, room, kept = false) => {
907
1165
  const a = args[0], q = {
908
1166
  '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' },
1167
+ '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
1168
  'connections.detach': { title: 'Remove this connection?', text: 'Every Space that uses it stops being able to.', ok: 'Remove' },
911
1169
  '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
1170
  'usernames.release': { title: 'Release your username?', text: 'Someone else may take it.', ok: 'Release' },
913
1171
  'siri.rotateKey': { title: 'Make a new Siri key?', text: 'The Shortcut stops working until you give it the new key.', ok: 'New key' },
914
1172
  '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)
1173
+ '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)
1174
+ 'a2a.stopJobAgent': { title: 'Disconnect this job agent?', text: 'Remove every pairing for ' + String(a || '').slice(0, 80) + ' on this account.', ok: 'Disconnect' },
916
1175
  'a2a.revoke': { title: 'Turn outside agents off?', text: 'Every lane\'s card and every agent\'s token stop working.', ok: 'Turn off' },
917
1176
  'backup.remove': { title: 'Remove ' + titleOf(a) + ' from your account?', text: 'It goes from every device that keeps this account.', ok: 'Remove' },
918
1177
  'account.forget': { title: 'Remove ' + titleOf(a) + ' from your account?', text: 'It goes from every device that keeps this account.', ok: 'Remove' },
919
1178
  // on the account service it is revoked at once, after the emailed code (accountCall's signOut, 94c06f12b); else it is marked in
920
1179
  // 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' },
1180
+ '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' },
1181
+ '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
1182
  '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
- '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' },
1183
+ // a move already under way resumes in ITS saved mode, whatever this call asks (sdkBackupV2.js migrate) — the words say what it will do
1184
+ // (side sweep 2026-11-28: a resumed emailed-code move promised that devices could join, then signed them out)
1185
+ 'backup.migrate': (sdk.backup._s?.v2?.moving ? (sdk.backup._s.v2.moveMode === 'signed' || sdk.backup._s.v2.svc?.silent === 'moved') : a?.silent === true) ? { 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
1186
  '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' },
926
1187
  'cloudDevice.register': { title: 'Add the cloud device to your account?', text: 'Register its public device key on the account service. You can sign it out later from Your devices. We email a code to confirm.', ok: 'Add device' },
927
1188
  'cloudDevice.setBuilds': { title: 'Update the cloud device’s secure builds?', text: 'The cloud device will follow this account’s accepted secure-build list and automatic-acceptance choice.', ok: 'Update' },
928
1189
  '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
1190
  '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
1191
  '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' },
931
- '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
- 'keptAgent.unlink': { title: 'Disconnect these assistants?', text: 'Both peer credentials and the connection are revoked. Rooms and history stay.', ok: 'Disconnect' },
1192
+ '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' },
1193
+ 'privateRoom.unlink': { title: 'Unlink this private room?', text: 'Both rooms stay in your account. New messages stop being copied between them.', ok: 'Unlink rooms' },
1194
+ // both rooms named from the vault's own list (side sweep 2026-11-28: every pair read the same)
1195
+ 'keptAgent.link': { title: 'Link the kept assistant in ' + pairName(a) + '?', text: 'Your private assistant in ' + pairName(room) + ' can send it jobs you approve. The always-on Space ' + pairName(a) + ' reports results back through your private assistant’s agent door. Both credentials stay in this vault.', ok: 'Link assistants' },
1196
+ 'keptAgent.unlink': { title: 'Disconnect these assistants?', text: 'The private assistant in ' + pairName(room) + ' and the kept assistant in ' + pairName(a) + ': both peer credentials and the connection are revoked. Rooms and history stay.', ok: 'Disconnect' },
933
1197
  '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' },
934
1198
  'backup.finishEmailMove': { title: 'Create your new account?', text: 'Your address will move to an empty account. Keep the new recovery code shown on this device.', ok: 'Finish email move' },
935
1199
  'backup.cancelPendingEmailMove': { title: 'Cancel this device’s email move?', text: 'The email address stays with the original account.', ok: 'Cancel move' },
936
1200
  'backup.requestMoveTime': { title: 'Ask for more time on the email move?', text: 'The move waits until 30 days after it started, so you can recover your inbox. This can be done once and does not cancel the move.', ok: 'Ask for more time' },
937
1201
  'backup.cancelEmailMove': { title: 'Cancel the email move?', text: 'We email a code to the account address. Proving you can read it cancels the move.', ok: 'Send code' },
938
1202
  'invitations.resend': { title: 'Resend this Space’s invitation?', text: 'Send the current invitation to ' + String(a && (a.email || a.username) || 'this recipient').slice(0, 254) + '. This does not change who is admitted.', ok: 'Send invitation' },
939
- 'backup.deleteAccount': { title: 'Delete your account?', text: 'Your account and its backup are deleted for good, and every device is signed out — this one too: it forgets your Spaces. We email you a code to confirm.', ok: 'Delete' },
1203
+ 'backup.deleteAccount': { title: 'Delete your account?', text: 'Your account and its backup are deleted for good. Spaces only you used are deleted, with their messages and files; in Spaces you share, you leave. Your cloud computers are destroyed with every file on them. Every device is signed out — this one too: it forgets your Spaces. We email you a code to confirm.', ok: 'Delete' },
940
1204
  // an MCP server's chosen tools may run WITHOUT asking (`auto`; the SDK's recommended ones when none are named) — the prompt
941
1205
  // says so instead of "always with your approval" (sweep 10-24 #7)
942
1206
  'connections.grant': { title: 'Let the assistant in ' + titleOf(room) + ' use ' + (conns.find((c) => c.id === (a && a.id ? a.id : a)) || {}).label + '?', text: (conns.find((c) => c.id === (a && a.id ? a.id : a)) || {}).mcp && !(args[1] && Array.isArray(args[1].auto) && !args[1].auto.length) ? 'It can use this server\'s tools — some may run without asking you (the ones marked so) — and never sees the secret.' : 'It can call it — always with your approval — and never sees the secret.', ok: 'Allow' },
@@ -959,7 +1223,7 @@ export async function startVault(o = {}) {
959
1223
  const syncError = a.lastError || (lastKeepFailure?.owner === who() && lastKeepFailure?.master === b._s?.master ? lastKeepFailure?.error : null)
960
1224
  return {
961
1225
  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 } : {}) })),
1226
+ rooms: b.rooms.map(({ room, kind, label, shared, detachedLane, archived, pinned, lastOpenedAt }) => ({ room, kind, ...(detachedLane ? { detachedLane: true } : {}), ...(pinned ? { pinned: true } : {}), ...(label ? { label } : {}), ...(shared ? { shared } : {}), ...(archived ? { archived: true } : {}), ...(lastOpenedAt > 0 ? { lastOpenedAt } : {}), ...(a._keptMarks && a._keptMarks.has(room) ? { alwaysOn: true } : {}) })), // lastOpenedAt: read-only, as the direct SDK (side sweep: sdk-account-room-list-omits-recency)
963
1227
  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
1228
  erasure: sdk.erasure.available,
965
1229
  gated: !!b.gated, // a restore and deleting the account need the emailed code as well (sync sweep 11-09 #24)
@@ -1028,8 +1292,7 @@ export async function startVault(o = {}) {
1028
1292
  async function withdrawPushEverywhere(endpoints) {
1029
1293
  const eps = (endpoints || []).filter((x) => typeof x === 'string' && /^https:\/\//.test(x))
1030
1294
  let failed = 0
1031
- for (const e of eps) for (const { room } of rooms) {
1032
- if (/^tmp-/.test(room)) continue
1295
+ for (const e of eps) for (const { room } of rooms) { // temporary Spaces too: opening one registers there as well (side sweep: device-signout-prunes-only-listed-rooms)
1033
1296
  let ok = false
1034
1297
  try { const r = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op: 'pushdrop', room, subscription: { endpoint: e } }) }); ok = r.status === 200 } catch { ok = false }
1035
1298
  if (!ok) failed++
@@ -1045,6 +1308,7 @@ export async function startVault(o = {}) {
1045
1308
  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
1309
  let adopting = false
1047
1310
  let erasingHere = false // deleteAccount is running in this vault (its own sign-out is not announced twice)
1311
+ sdk.backup._restoreIdentity = () => JSON.stringify([privacyEpoch, who()])
1048
1312
  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
1313
  sdk.account._syncSettled = emitAccount
1050
1314
  sdk.account.onChange = () => { fromBackup(); emitAccount(); keepSoon(200) }
@@ -1060,7 +1324,15 @@ export async function startVault(o = {}) {
1060
1324
  backupMem = { ...backupMem, [w]: state }
1061
1325
  await atRest.putBackup(KEYS.backup, w, state)
1062
1326
  const back = (await atRest.loadBackups(KEYS.backup))[w]
1063
- return !!back && back.master === state.master && JSON.stringify(back.v2) === JSON.stringify(state.v2)
1327
+ if (!(!!back && back.master === state.master && JSON.stringify(back.v2) === JSON.stringify(state.v2))) return false
1328
+ // ON A PROTECTED DEVICE THE READ-BACK ABOVE IS MEMORY (protectedLocal's overlay answers it even when a full store refused the sealed
1329
+ // write): the disk itself must hold what was written (side sweep: builder-restore-success-before-local-save)
1330
+ // (only where the lock is offered — storage protection exists only there, and a vault without `lock` loads none of it)
1331
+ if (!o.storage && vlock) {
1332
+ const { protectedLocalActive, durableEntry } = await import('./protectedLocal.js') // vaultCoreLock.js's specifier: the same module
1333
+ if (protectedLocalActive()) { const v = localStorage.getItem(KEYS.backup); if (v == null || !(await durableEntry(KEYS.backup, v))) return false }
1334
+ }
1335
+ return true
1064
1336
  }
1065
1337
  sdk.backup._v2 = o.accountService === false ? null : accountService({ tenant: o.tenant, legacyRecovery: async email => {
1066
1338
  const session = sdk._session
@@ -1071,7 +1343,7 @@ export async function startVault(o = {}) {
1071
1343
  return sdk._session === session ? held : null
1072
1344
  }, ...(typeof o.accountService === 'string' && o.accountService ? { base: o.accountService } : {}), fetch: (...a) => fetch(...a), keyStore: idbKeyStore('wbvault-acct'), persistNow, onRevoked: () => accountStatus(true), afterSignOut: (address) => { if (roomPass) roomPass.renewNow(address) },
1073
1345
  // the endpoint once the subscription is KNOWN (vpush.ready) — not known within 15 s: undefined, and nothing is sent (Codex 11-16 #2)
1074
- ...(vpush ? { pushEndpoint: async () => ((await Promise.race([vpush.ready.then(() => true), new Promise((r) => setTimeout(() => r(false), 15000))])) ? (vpush.endpoint() || null) : undefined), withdrawPush: withdrawPushEverywhere } : {}) }) // § 8.8, only where this vault sends notifications (sync sweep 11-16 #14)
1346
+ ...(vpush ? { pushEndpoint: async () => ((await Promise.race([vpush.ready.then(() => true), new Promise((r) => setTimeout(() => r(false), 15000))])) ? ((e) => (e === undefined ? undefined : e || null))(vpush.endpoint()) : undefined), /* undefined = not known (on, but not loaded): nothing is sent (side sweep 2026-11-28) */ withdrawPush: withdrawPushEverywhere } : {}) }) // § 8.8, only where this vault sends notifications (sync sweep 11-16 #14)
1075
1347
  roomPass = makeRoomPassHolder({
1076
1348
  on: () => roomPassSwitchOn(st),
1077
1349
  note: (line) => { try { console.info('witbitz vault: ' + line) } catch { /* */ } }, // why a request went without a pass, at most once a while (roomPass.js makeNoter; sync sweep 2026-11-23: this vault said nothing)
@@ -1134,54 +1406,90 @@ export async function startVault(o = {}) {
1134
1406
  mk = it.mk && await keyCommit(it.mk) === p.commit ? it.mk : (await sdk._openLink(it.link)).mk
1135
1407
  if (!mk || await keyCommit(mk) !== p.commit) throw new Error('Could not back up the key for this split Space')
1136
1408
  }
1137
- return { room: it.room, link: it.link, label: it.title, kind: it.lane ? 'lane' : 'space', shared: it.lane, ...(mk ? { mk } : {}) }
1409
+ let link = it.link
1410
+ if (it.enc && !/[?#&]enc=1(?:[&#?]|$)/.test(link)) {
1411
+ link += (link.includes('#') ? '&' : '#') + 'enc=1'
1412
+ }
1413
+ return { room: it.room, link, label: it.title, kind: it.lane ? 'lane' : 'space', shared: it.lane, ...(it.detachedLane ? { detachedLane: true } : {}), ...(mk ? { mk } : {}) }
1138
1414
  }
1139
1415
  async function noteRoom(room) {
1140
- const it = rooms.find((x) => x.room === room); if (!it) return
1416
+ const it = rooms.find((x) => x.room === room); if (!it || !currentRoom(it)) return
1141
1417
  const epoch = privacyEpoch, link = it.link
1142
1418
  if (sdk.backup.enabled) {
1143
1419
  const entry = await backupRoom(it)
1144
1420
  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 })
1421
+ 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
1422
  }
1147
1423
  const k = await eraseKey() // the account's membership mark: another account's delete of this room is refused (sdkErase.js)
1148
1424
  if (k) wop('mark', room, await dropFor(k, room)).catch(() => null)
1149
1425
  sdk.erasure._seen({ room }) // and refile the erase list soon
1150
1426
  }
1427
+ async function purgeForgotten(room) {
1428
+ write(st, KEYS.pendingForget, [...pendingForget])
1429
+ const marked = JSON.parse(await st.durableItem(KEYS.pendingForget) || '[]')
1430
+ if (!marked.includes(room)) throw new Error('vault could not save the pending room removal')
1431
+ await saveRooms(true)
1432
+ await wcall({ t: 'forget', room })
1433
+ pendingForget.delete(room)
1434
+ write(st, KEYS.pendingForget, [...pendingForget])
1435
+ await st.flushed()
1436
+ }
1151
1437
  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()
1438
+ const mark = Date.now() + ':' + crypto.randomUUID()
1439
+ st.setItem(forgetPrefix + room, mark)
1440
+ if (forgetMark(room) !== mark) throw new Error('vault could not save the room removal')
1441
+ pendingForget.add(room)
1442
+ write(st, KEYS.pendingForget, [...pendingForget])
1443
+ rooms = rooms.filter(r => r.room !== room)
1156
1444
  emit({ ev: 'rooms', rooms: publicRooms() })
1445
+ streamGrants.delete(room)
1446
+ if (streaming.delete(room)) syncStream(worker, room, null)
1447
+ if (vpush) await vpush.drop(room).catch(() => {}) // off its notification list while the worker still holds its key
1448
+ await st.flushed()
1449
+ await purgeForgotten(room)
1157
1450
  }
1158
1451
  async function fromBackup() {
1452
+ if (pendingForget.size) await Promise.allSettled([...pendingForget].map(purgeForgotten))
1159
1453
  if (!sdk.backup.enabled) return
1160
1454
  const epoch = privacyEpoch, accountState = sdk.backup._s
1161
1455
  const inAccount = new Map((sdk.backup._s?.rooms || []).map((b) => [b.room, b]))
1162
1456
  let added = false
1163
1457
  for (const b of inAccount.values()) {
1458
+ if (pendingForget.has(b.room) || (forgetMark(b.room) && Number(b.at || 0) <= Number(forgetMark(b.room).split(':')[0]))) continue
1164
1459
  const p = linkParts(b.link); if (!p || p.room !== b.room) continue // a link that names another room is not taken in
1165
1460
  // 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
1461
  // takes the account's: a key is never replaced by a link, but a room with none gets its own back
1167
1462
  const restoredMk = p.split && b.mk && await keyCommit(b.mk).catch(() => '') === p.commit ? b.mk : ''
1168
1463
  if (epoch !== privacyEpoch || accountState !== sdk.backup._s) return
1464
+ if (pendingForget.has(b.room) || (forgetMark(b.room) && Number(b.at || 0) <= Number(forgetMark(b.room).split(':')[0]))) continue
1169
1465
  const had = rooms.find((x) => x.room === b.room)
1170
1466
  if (had) {
1171
1467
  if (b.label && b.label !== 'Space' && b.label !== b.room && (!had.title || had.title === 'Space' || had.title === b.room) && !had.renamed) {
1172
1468
  had.title = b.label
1173
1469
  added = true
1174
1470
  }
1175
- if (had.lane && b.kind === 'space' && !b.shared && Number(b.at) > 0) {
1176
- delete had.lane; had.detachedLane = true; added = true
1471
+ const heldAssociation = { ...had, kind: had.lane ? 'lane' : 'space', shared: had.lane }
1472
+ if (preferredAssociation(heldAssociation, b) === b) {
1473
+ const next = b.kind === 'lane' && b.shared !== had.room && !b.detachedLane ? b.shared : undefined
1474
+ const detached = !!b.detachedLane
1475
+ if (b.mintedFor && had.mintedFor !== b.mintedFor) { had.mintedFor = b.mintedFor; added = true }
1476
+ const origin = next && b.laneOrigin === 'minted' ? 'minted' : undefined
1477
+ if (had.laneOrigin !== origin) { if (origin) had.laneOrigin = origin; else delete had.laneOrigin; added = true }
1478
+ if (had.lane !== next || !!had.detachedLane !== detached || had.associationAt !== b.associationAt) {
1479
+ if (next) had.lane = next; else delete had.lane
1480
+ if (detached) had.detachedLane = true; else delete had.detachedLane
1481
+ if (b.associationAt) had.associationAt = b.associationAt; else delete had.associationAt
1482
+ added = true
1483
+ }
1177
1484
  }
1485
+ if (!had.enc && /[?#&]enc=1(?:[&#?]|$)/.test(b.link)) { had.enc = true; added = true }
1178
1486
  if (!had.link) { had.link = b.link; holdLink(worker, p); seedIdentity(b.room); added = true }
1179
1487
  if (restoredMk && had.link === b.link && had.mk !== restoredMk) {
1180
1488
  had.mk = restoredMk; worker.postMessage({ t: 'remember', room: b.room, mk: restoredMk }); added = true
1181
1489
  }
1182
1490
  continue
1183
1491
  }
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 } : {}) })
1492
+ 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
1493
  holdLink(worker, p)
1186
1494
  if (restoredMk) worker.postMessage({ t: 'remember', room: b.room, mk: restoredMk })
1187
1495
  seedIdentity(b.room); added = true
@@ -1219,20 +1527,20 @@ export async function startVault(o = {}) {
1219
1527
  }
1220
1528
  if (m === 'exportArchive') {
1221
1529
  const { saveAccountArchive } = await import('./sdkExports.js')
1222
- const epoch = privacyEpoch, session = sdk._session
1530
+ const epoch = privacyEpoch, generation = sdk._archiveGeneration, owner = who()
1223
1531
  const selection = args[1] === undefined ? null : new Set(Array.isArray(args[1]) ? args[1] : [])
1224
1532
  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
1533
  const heldById = new Map(rooms.map(r => [r.room, r]))
1226
1534
  const selected = (selection ? [...selection].map(id => heldById.get(id) || { room: id }) : rooms.slice()).filter(r => !r.room.startsWith('tmp-'))
1227
- return saveAccountArchive(selected, async (r, keysOnly) => {
1535
+ return saveAccountArchive(selected, async (r, keysOnly, attachments) => {
1228
1536
  if (!r.link) return {}
1229
1537
  const parts = linkParts(r.link)
1230
1538
  const key = parts?.split ? (await backupRoom(r))?.mk : parts?.mk
1231
1539
  if (!key || keysOnly) return { key }
1232
- const saved = await workerClient.exportSealed(r.room, null)
1540
+ const saved = await workerClient.exportSealed(r.room, null, { attachments }) // + the stored attachments, sealed (sdkExports.js)
1233
1541
  if (saved?.status !== 200) throw new Error('unavailable')
1234
- return { key, ledger: saved.sealed, count: saved.count }
1235
- }, args[0] === true, () => epoch === privacyEpoch && session === sdk._session)
1542
+ return { key, ledger: saved.sealed, count: saved.count, attachments: saved.attachments }
1543
+ }, 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
1544
  }
1237
1545
  if (m === 'protectRecoveryEmail') {
1238
1546
  const email = signedIn() && sdk.session.email
@@ -1290,7 +1598,7 @@ export async function startVault(o = {}) {
1290
1598
  // 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
1599
  // calls this; the account service's emailed code is asked through the same two calls (sdkBackupV2.js restoreBridge)
1292
1600
  const email = signedIn() ? sdk.session.email : ''
1293
- let attemptedToken
1601
+ let attemptedToken, restoredIdentity
1294
1602
  const run = restoreBridge((q, getCode) => {
1295
1603
  const session = sdk._session
1296
1604
  getCode.choose = async ({ action }) => {
@@ -1300,12 +1608,21 @@ export async function startVault(o = {}) {
1300
1608
  if (proof) attemptedToken = session.idToken
1301
1609
  return proof
1302
1610
  }
1303
- return b.restore({ code: q.code, email: q.email, ticket: q.ticket, emailCode: q.emailCode, ...(b._v2 ? { getCode } : {}) })
1611
+ const identity = b._restoreIdentity()
1612
+ return b.restore({ code: q.code, email: q.email, ticket: q.ticket, emailCode: q.emailCode, ...(b._v2 ? { getCode } : {}) }).then(result => {
1613
+ if (identity !== b._restoreIdentity()) throw Object.assign(new Error('The account changed during recovery'), { code: 'account_changed' })
1614
+ restoredIdentity = identity
1615
+ return result
1616
+ })
1304
1617
  })
1305
1618
  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' })
1619
+ if (!b.enabled || restoredIdentity !== b._restoreIdentity()) throw Object.assign(new Error('not restored'), { code: 'cancelled' })
1307
1620
  noteDeviceSpk() // as after enable (sync sweep 11-22 #16)
1308
1621
  await fromBackup()
1622
+ // read back from this device's storage before saying it is restored (side sweep 2026-11-28: a full store refused the write silently,
1623
+ // and the next launch asked for recovery again) — as a new recovery code is
1624
+ if (restoredIdentity === b._restoreIdentity() && !(await persistNow(JSON.parse(JSON.stringify(b._s))))) throw Object.assign(new Error('Your Spaces were recovered for now, but this device could not keep the account. Free some storage and restore again.'), { code: 'save_failed' })
1625
+ if (restoredIdentity !== b._restoreIdentity()) throw Object.assign(new Error('The account changed during recovery'), { code: 'account_changed' })
1309
1626
  emitAccount()
1310
1627
  accountStatus()
1311
1628
  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 +1745,7 @@ export async function startVault(o = {}) {
1428
1745
  const epoch = privacyEpoch, id = args[0]
1429
1746
  const row = (await a.listDevices()).find(d => d.id === id && !d.current)
1430
1747
  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' })
1748
+ 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
1749
  if (!ok || epoch !== privacyEpoch) throw Object.assign(new Error('Device sign-out cancelled'), { code: 'cancelled' })
1433
1750
  const result = await a.signOutDevice(id, { getCode: await emailCodeAsker('signout', accountAddress) })
1434
1751
  emitAccount()
@@ -1440,7 +1757,28 @@ export async function startVault(o = {}) {
1440
1757
  const sec = typeof name === 'string' && Object.prototype.hasOwnProperty.call(all, name) ? all[name] : null
1441
1758
  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
1759
  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))
1760
+ let result
1761
+ if (name === 'chatLocks' && op === 'deleteAll') {
1762
+ const owner = sdk.backup._s, epoch = privacyEpoch, { targets: locks, privateAssistants: assistants } = await sec.previewDeleteAll()
1763
+ if (!locks.length) return []
1764
+ const lockedRooms = new Set(locks.filter(l => l.kind === 'room').map(l => l.target))
1765
+ const extra = assistants.length ? ' Their private assistants will also be removed: ' + assistants.map(r => r.title || r.room).join(', ') + '.' : ''
1766
+ const roomCount = lockedRooms.size
1767
+ 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' })
1768
+ if (!confirmed) throw Object.assign(new Error('Cancelled'), { code: 'cancelled' })
1769
+ if (epoch !== privacyEpoch || owner !== sdk.backup._s) throw Object.assign(new Error('The account changed.'), { code: 'account_changed' })
1770
+ result = await sec._deleteTargets(locks, owner, async (kind, room) => {
1771
+ if (epoch !== privacyEpoch) throw new Error('Account changed')
1772
+ if (kind === 'room' && held(room)) await dropRoom(room)
1773
+ }, assistants.map(r => r.room))
1774
+ if (epoch === privacyEpoch && owner === sdk.backup._s) {
1775
+ await fromBackup()
1776
+ emit({ ev: 'accountSection', section: name, value: sec.value })
1777
+ }
1778
+ } else {
1779
+ result = await sec[op](...rest.slice(0, 1))
1780
+ if (name === 'chatLocks' && (op === 'match' || op === 'check')) emit({ ev: 'accountSection', section: name, value: sec.value })
1781
+ }
1444
1782
  if (name === 'blocks' || name === 'chatLocks') {
1445
1783
  // A refresh already in flight may have read the list before this change.
1446
1784
  if (privacyRun) await privacyRun.catch(() => {})
@@ -1450,7 +1788,7 @@ export async function startVault(o = {}) {
1450
1788
  }
1451
1789
  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
1790
  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 {} }
1791
+ if (m === 'forget') { const room = String(args[0] || ''); a.forget(room); if (held(room)) await dropRoom(room); await fromBackup(); emitAccount(); return {} }
1454
1792
  if (m === 'noteLink' || m === 'dropLink') { // a link between two lanes THIS vault holds — any other pair is not the page's to record
1455
1793
  const x = String(args[0] || ''), y = String(args[1] || '')
1456
1794
  if (!held(x) || !held(y)) throw Object.assign(new Error('vault: this vault holds no such lanes'), { code: 'not_in_vault' })
@@ -1488,6 +1826,7 @@ export async function startVault(o = {}) {
1488
1826
  if (ns === 'cloudDevice' && (m === 'enroll' || m === 'register')) return sdk.cloudDevice[m]({ getCode: await emailCodeAsker('cloud-device', accountAddress) })
1489
1827
  if (ns === 'backup') return backupCall(m, args)
1490
1828
  if (ns === 'account') return accountCall(m, args)
1829
+ if (ns === 'invite' && m === 'collect') return inviteCollect()
1491
1830
  if (ns === 'siri' && m === 'shortcut') return siriShortcut()
1492
1831
  if (ns === 'siri' && m === 'showKey') {
1493
1832
  const s = sdk.siri.shortcut
@@ -1502,20 +1841,21 @@ export async function startVault(o = {}) {
1502
1841
  ? await spacesUsingConnection(args[0], rooms.map(r => ({ room: r.room, shared: r.lane })), room => wop('getConfig', room, { plainMark: true }))
1503
1842
  : await sdk[ns][m](...args)
1504
1843
  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() }
1844
+ if (ns === 'connections' && m === 'spacesUsing' && !sdk.backup.enabled) r.incomplete = true
1845
+ 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) }
1846
+ 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
1847
  // GRANTABLE HERE (sync sweep 11-13 P7): the Sentinel lists every connection the account has, but a grant needs its callKey,
1508
1848
  // which only this vault's list holds (attached here, or kept from another device with the backup on) — the rest refuse
1509
1849
  // with not_in_vault. Each says which it is, so the page offers to grant only what will work.
1510
1850
  if (ns === 'connections' && m === 'list' && Array.isArray(r)) {
1511
1851
  const acct = await sdk._account()
1512
1852
  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)
1853
+ await adoptPending(r, acct) // a key whose attach answer was lost, now listed (#5)
1514
1854
  // MOVE 3: the old-form ones whose key this vault holds are locked under it (connWrap.js) — once a launch, in the background
1515
1855
  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
1856
  return r.map((x) => (x && typeof x === 'object' ? { ...x, grantable: conns.some((c) => c.id === x.id && c.account === acct) } : x))
1517
1857
  }
1518
- if (ns === 'siri') { saveSiri(); if (m === 'rotateKey') return siriShortcut() }
1858
+ if (ns === 'siri') { saveSiri(); emit({ ev: 'siri', siri: siriShortcut() }); if (m === 'rotateKey') return siriShortcut() }
1519
1859
  if (ns === 'a2a') saveA2A()
1520
1860
  return r
1521
1861
  }
@@ -1531,6 +1871,15 @@ export async function startVault(o = {}) {
1531
1871
  const id = String(args[0] && typeof args[0] === 'object' ? args[0].id : args[0] || '')
1532
1872
  const acct = await sdk._account()
1533
1873
  c = conns.find((x) => x.id === id && x.account === acct) // only this account's own connections
1874
+ if (c && typeof c.mcp !== 'boolean') {
1875
+ const owner = who(), epoch = privacyEpoch
1876
+ const listed = await sdk.connections.list()
1877
+ if (owner !== who() || epoch !== privacyEpoch) throw Object.assign(new Error('the account changed'), { code: 'account_changed' })
1878
+ if (!listed.some(row => row.id === id)) throw Object.assign(new Error('connection no longer attached'), { code: 'not_in_vault' })
1879
+ await adoptPending(listed, acct)
1880
+ if (owner !== who() || epoch !== privacyEpoch) throw Object.assign(new Error('the account changed'), { code: 'account_changed' })
1881
+ c = conns.find(x => x.id === id && x.account === acct)
1882
+ }
1534
1883
  if (!c) throw Object.assign(new Error('vault: no connection ' + id.slice(0, 40) + ' attached in this vault'), { code: 'not_in_vault' })
1535
1884
  }
1536
1885
  if (ns === 'a2a' && (m === 'setReply' || (m === 'addPeer' && args[1]?.reply === 'auto'))) {
@@ -1545,7 +1894,15 @@ export async function startVault(o = {}) {
1545
1894
  const sp = roomSpace(room)
1546
1895
  try { kept = await isKeptSpace(sp) } finally { sp.close() }
1547
1896
  }
1548
- await confirmCall(ns, m, args, room, kept)
1897
+ if (ns === 'privateRoom' && m === 'link') {
1898
+ const source = rooms.find(r => r.room === room && currentRoom(r)), target = rooms.find(r => r.room === args[0] && currentRoom(r))
1899
+ if (!source || !target) throw Object.assign(new Error('Open both rooms in this vault first.'), { code: 'not_in_vault' })
1900
+ const label = r => (r.title || r.room) + ' (' + (r.enc ? 'confidential' : 'standard') + ')'
1901
+ const downgrade = source.enc && !target.enc
1902
+ if (downgrade && args[1]?.allowStandardDestination !== true) throw Object.assign(new Error('Confirm the standard destination before linking.'), { code: 'tier_mismatch' })
1903
+ 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' })
1904
+ if (!ok) throw Object.assign(new Error('Link cancelled'), { code: 'cancelled' })
1905
+ } else await confirmCall(ns, m, args, room, kept)
1549
1906
  if (epoch !== privacyEpoch || owner !== who() || !held(room)) throw Object.assign(new Error('the account or room changed during confirmation'), { code: 'account_changed' })
1550
1907
  }
1551
1908
  if (ns === 'connections' && m === 'grants') {
@@ -1565,6 +1922,25 @@ export async function startVault(o = {}) {
1565
1922
  const epoch = privacyEpoch, it = held(room) && rooms.find((r) => r.room === room)
1566
1923
  return await saveRoomExport(sp, it?.enc ? 'enclave' : 'standard', () => epoch === privacyEpoch && !!held(room), it?.title || '')
1567
1924
  }
1925
+ if (ns === 'privateRoom') {
1926
+ const target = rooms.find(r => currentRoom(r) && r.room === args[0])
1927
+ if (!target || !held(target.room)) throw Object.assign(new Error('The selected room is unavailable.'), { code: 'not_in_vault' })
1928
+ if (target.lane && target.lane !== room) throw Object.assign(new Error('The room is already linked elsewhere.'), { code: 'already_linked' })
1929
+ const other = roomSpace(target.room), epoch = privacyEpoch
1930
+ try {
1931
+ const result = await sp._privateRoomChange(other, m === 'unlink', args[1]?.allowStandardDestination === true)
1932
+ if (epoch !== privacyEpoch || !rooms.includes(target)) throw Object.assign(new Error('The account changed.'), { code: 'account_changed' })
1933
+ const entry = sdk.backup.rooms.find(r => r.room === target.room)
1934
+ if (m === 'unlink') { delete target.lane; target.detachedLane = true }
1935
+ else { target.lane = room; delete target.detachedLane }
1936
+ if (entry?.mintedFor) target.mintedFor = entry.mintedFor
1937
+ if (entry?.laneOrigin === 'minted') target.laneOrigin = 'minted'; else delete target.laneOrigin
1938
+ target.associationAt = entry?.associationAt || entry?.at || Date.now()
1939
+ await saveRooms(true)
1940
+ emit({ ev: 'rooms', rooms: publicRooms() })
1941
+ return result
1942
+ } finally { other.close() }
1943
+ }
1568
1944
  if (ns === 'keptAgent') {
1569
1945
  const kept = roomSpace(args[0])
1570
1946
  try { return m === 'link' ? await sp.linkKept(kept, args[1] || {}) : await sp.unlinkKept(kept, args[1]) }
@@ -1573,6 +1949,7 @@ export async function startVault(o = {}) {
1573
1949
  if (ns === 'invitations') {
1574
1950
  await sp._gateConfig() // heal a stale worker key before reading the vault's current link
1575
1951
  const it = rooms.find((x) => x.room === room)
1952
+ if (it.detachedLane) sp._detachedLane = true // a detached lane is still one member's room: no invitation with its saved link (side sweep: sdk-resend-forgets-private-lane-status)
1576
1953
  sp.shareLink = it.link
1577
1954
  sp._title = it.title ? { title: it.title } : null
1578
1955
  return await sp.resendInvite(args[0])
@@ -1582,6 +1959,7 @@ export async function startVault(o = {}) {
1582
1959
  if (m === 'enable') { await sp._gateConfig(); sp.shareLink = rooms.find((x) => x.room === room).link }
1583
1960
  const result = await sp.alwaysOn[m](...args)
1584
1961
  if (m === 'enable' && args[0]?.disconnectLanes) await CALLS.op('getConfig', room, { plainMark: true })
1962
+ if (m === 'enable' || m === 'disable') emitAccount() // the account view's saved mark moved (rooms[].alwaysOn)
1585
1963
  return result
1586
1964
  }
1587
1965
  if (c) return await sp.connections.grant(c, args[1] || {})
@@ -1590,7 +1968,7 @@ export async function startVault(o = {}) {
1590
1968
  const r = await sp.siri.collect(deliver ? { deliver } : {}); saveSiri(); return r
1591
1969
  }
1592
1970
  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)
1971
+ 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
1972
  return r
1595
1973
  } catch (e) { throw vaultSignInWords(e) } finally { sp.close() }
1596
1974
  }
@@ -1631,23 +2009,34 @@ export async function startVault(o = {}) {
1631
2009
  const forgetDevice = sdk.backup._v2?.forgetDevice
1632
2010
  const keyCleanup = (forgetDevice ? forgetDevice(sdk.backup) : idbKeyStore('wbvault-acct').clear()).then(() => null, (e) => e)
1633
2011
  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
2012
+ for (const room of streaming) { try { syncStream(worker, room, null) } catch { /* the worker is replaced below */ } }
2013
+ streaming.clear(); streamGrants.clear() // the replay re-opened each one in the new worker, and onWorker forwarded its events to the page
1636
2014
  const held0 = rooms.map((r) => r.room)
1637
2015
  rooms = []
1638
2016
  write(st, KEYS.session, null)
1639
- 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()
2017
+ // OFF, as the person's own Off does (side sweep: builder-signout-retains-push-subscription): every held Space takes this device off its
2018
+ // list, the browser's subscription goes and the device's On is cleared — as the regular app's sign-out (devices.js). It kept the
2019
+ // subscription and On: a Space that missed the removal still tickled the device, and the next account's Spaces listed it unasked.
2020
+ if (vpush) await Promise.race([vpush.disable(), new Promise((r) => setTimeout(r, WIPE_PUSH_MS))]).catch(() => {}) // while the worker still holds the keys
2021
+ // ★ THE WORKER'S KEYS GO WHATEVER THE SAVE DOES (second review, 2026-11-27). A strict save that could not be confirmed threw
2022
+ // here, before the forgets and wipeKeys below — "signed out", with every room key still in the worker's memory and store until
2023
+ // 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).
2024
+ const saveError = await saveRooms(true, true).then(() => null, (e) => e)
1641
2025
  await wcall({ t: 'presenceQuery' }).catch(() => null) // which rooms the worker holds a key for (workerRooms) — the list may not name them all
1642
2026
  for (const room of new Set([...held0, ...workerRooms])) await wcall({ t: 'forget', room }).catch(() => null) // memory AND its store (awaited there)
1643
2027
  await wcall({ t: 'wipeKeys' }) // includes sealed keys which were neither listed nor unsealed
1644
- workerRooms = []
2028
+ workerRooms = []; pendingForget.clear()
1645
2029
  failWaiting('signed out — try again') // what waits on the worker that goes (P8): never answered
1646
2030
  conns = []; backupMem = {}; _lockedOnce = false; pageUserToken = ''
1647
2031
  try { sdk.account._spk = null } catch { /* */ } // or the NEXT account's index entry carried this one's device key
1648
2032
  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
2033
  mirrorOk.clear(); keyWaits.clear()
1650
2034
  for (const k of Object.values(KEYS)) write(st, k, null)
2035
+ const rawStorage = o.storage || localStorage
2036
+ for (let i = rawStorage.length - 1; i >= 0; i--) {
2037
+ const name = rawStorage.key(i)
2038
+ if (name?.startsWith(forgetPrefix)) rawStorage.removeItem(name)
2039
+ }
1651
2040
  await st.flushed()
1652
2041
  await atRest.flushed()
1653
2042
  write(st, learnedBlocksKey, null)
@@ -1656,18 +2045,29 @@ export async function startVault(o = {}) {
1656
2045
  loadSiri(); loadBackup(); clearTimeout(refreshTimer); await startWorker()
1657
2046
  emit({ ev: 'rooms', rooms: publicRooms() }); emitAccount()
1658
2047
  const keyError = await keyCleanup
1659
- if (keyError) throw keyError
2048
+ if (keyError || saveError) throw (keyError || saveError)
1660
2049
  write(st, wipeMarker, null)
1661
2050
  }
1662
2051
  // 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
2052
  function onPeerSignOut(event) {
2053
+ if (event.key?.startsWith(forgetPrefix) && event.newValue) {
2054
+ const room = event.key.slice(forgetPrefix.length)
2055
+ if (rooms.some(r => r.room === room && !currentRoom(r))) {
2056
+ rooms = rooms.filter(r => r.room !== room || currentRoom(r))
2057
+ streamGrants.delete(room)
2058
+ if (streaming.delete(room)) syncStream(worker, room, null)
2059
+ wcall({ t: 'forget', room }).catch(() => {})
2060
+ emit({ ev: 'rooms', rooms: publicRooms() })
2061
+ }
2062
+ return
2063
+ }
1664
2064
  if (event.key !== wipeMarker) return
1665
2065
  if (event.newValue === 'true' && !peerSignedOut) {
1666
2066
  peerSignedOut = true
1667
2067
  privacyEpoch++
1668
2068
  clearTimeout(refreshTimer); clearTimeout(privacyTimer); clearTimeout(idPrefetchT)
1669
2069
  sdk.account.stop(); sdk.signOut(); clearTimeout(sdk.backup._timer)
1670
- rooms = []; streaming.clear(); conns = []; backupMem = {}
2070
+ rooms = []; streaming.clear(); streamGrants.clear(); conns = []; backupMem = {}
1671
2071
  frame.remove()
1672
2072
  workerHost.drop()
1673
2073
  failWaiting('Signed out in another tab')
@@ -1683,6 +2083,10 @@ export async function startVault(o = {}) {
1683
2083
  async op(op, room, ...args) {
1684
2084
  if (!PAGE_OPS.has(op)) throw Object.assign(new Error('vault: ' + op + ' is not available to the page'), { code: 'vault_refused' })
1685
2085
  if (!held(room)) throw Object.assign(new Error('vault: this vault holds no Space ' + String(room).slice(0, 40)), { code: 'not_in_vault' })
2086
+ 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' })
2087
+ if (op === 'state' && args[0] === 'agentmode' && args[1] != null && rooms.some(r => r.room === room && (r.lane || r.detachedLane))) {
2088
+ throw Object.assign(new Error('a private lane always replies'), { code: 'lane' })
2089
+ }
1686
2090
  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
2091
  // 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
2092
  // 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 +2099,8 @@ export async function startVault(o = {}) {
1695
2099
  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
2100
  if (op === 'setConfig' && args[0]?.lanes === true) { const sp = roomSpace(room); try { await assertNotKept(sp) } finally { sp.close() } }
1697
2101
  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
2102
+ const a = args[routingIndex(op)]
2103
+ if (a && typeof a === 'object') {
1700
2104
  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
2105
  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
2106
  if (op !== 'carry' && (a.bridgeRoom || a.viewSource)) {
@@ -1704,9 +2108,10 @@ export async function startVault(o = {}) {
1704
2108
  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
2109
  }
1706
2110
  // linked rooms (a lane's tell_lane): each one held here; the worker fills in its key by room
1707
- if (a.links != null) {
2111
+ if (op === 'turn' && a.links != null) {
1708
2112
  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
2113
  if (a.links.some(keyIn)) throw Object.assign(new Error('vault: a key is the vault\'s, not the page\'s'), { code: 'vault_refused' })
2114
+ 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
2115
  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
2116
  }
1712
2117
  }
@@ -1723,13 +2128,14 @@ export async function startVault(o = {}) {
1723
2128
  // _isEnclave() is always false in a vault, so space.safeMedia.refresh() failed until something else woke it)
1724
2129
  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
2130
  if (op === 'getConfig') r = configForPage(r)
2131
+ if ((op === 'poll' || op === 'pollSealed') && r?.streamGrants) { const { streamGrants: _grants, ...visible } = r; r = visible }
1726
2132
  const lanes = op === 'getConfig' ? r && r.lanes : op === 'setConfig' && r && r.status === 200 && args[0] ? args[0].lanes : undefined
1727
2133
  if (op === 'setConfig' && lanes === false) await disconnectRoomLanes(sdk, room)
1728
2134
  if (typeof lanes === 'boolean') {
1729
2135
  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() }) } }
2136
+ 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
2137
  }
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() } }
2138
+ 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
2139
  return r
1734
2140
  },
1735
2141
  async create(cfg, opts) { // opts { enclave, split }: the confidential tier, a split-key room; anything else is refused, never ignored
@@ -1749,6 +2155,7 @@ export async function startVault(o = {}) {
1749
2155
  const now = Date.now(); creates = creates.filter((t) => now - t < CREATE_LIMIT.ms)
1750
2156
  if (creates.length >= CREATE_LIMIT.n) throw Object.assign(new Error('vault: too many new Spaces — wait a few minutes'), { code: 'rate_limited' })
1751
2157
  creates.push(now)
2158
+ 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
2159
  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
2160
  // Attest FIRST — loud on a configuration failure (no published claim: never mint a confidential room that pins
1754
2161
  // nothing), soft on a cold enclave (woken below) — then mint, wake, and hand the enclave its own sealed config.
@@ -1774,7 +2181,7 @@ export async function startVault(o = {}) {
1774
2181
  current()
1775
2182
  const completeKey = split && r.mk && await keyCommit(r.mk) === linkParts(link)?.commit ? r.mk : null
1776
2183
  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)]
2184
+ 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
2185
  await saveRooms()
1779
2186
  current()
1780
2187
  seedIdentity(r.room); noteRoom(r.room).catch(() => {})
@@ -1807,7 +2214,7 @@ export async function startVault(o = {}) {
1807
2214
  const sh = rooms.find((x) => x.room === shared)
1808
2215
  // A TEMPORARY ROOM HAS NO LANE (as the direct SDK and the app — roomState isTempRoom; sync sweep backlog P7): a lane is a
1809
2216
  // 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)
2217
+ 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
2218
  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
2219
  // A VERIFIED SPACE'S LANE ADMITS ITS ONE MEMBER, whatever the page sent (laneConfig.js laneInherits; sync sweep 10-16 #1):
1813
2220
  // the vault decides it, so a page cannot make an open lane of a verified Space.
@@ -1816,7 +2223,7 @@ export async function startVault(o = {}) {
1816
2223
  if (sh && sh.enc) { try { await sdk._encWake(shared, { tries: 8 }); pushEnclave() } catch { /* the read below says what is wrong */ } }
1817
2224
  let scfg = null; try { scfg = await wop('getConfig', shared, { plainMark: true }) } catch { scfg = null }
1818
2225
  // 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
2226
+ const plain = !!(scfg && scfg.plain === true) && !(sh && roomInviteFlags(sh.link).gated); if (scfg && scfg.plain === true) scfg = null
1820
2227
  // the placeholder a verified Space's settings read gives before the sign-in admits ({ admission:'email', gated:true },
1821
2228
  // 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
2229
  // …and it says the Space IS verified: wait, whatever the link says — read as "no settings", a verified Space whose link
@@ -1851,6 +2258,18 @@ export async function startVault(o = {}) {
1851
2258
  let attested = false
1852
2259
  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
2260
  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' })
2261
+ const inherited = laneInherits(scfg).config
2262
+ if (o?.inheritCustom || (o?.inheritCustom !== false && !cfg?.tools && !cfg?.immediateTools)) {
2263
+ cfg = { ...cfg }
2264
+ delete cfg.tools; delete cfg.immediateTools
2265
+ if (inherited.tools) cfg.tools = inherited.tools
2266
+ if (inherited.immediateTools) cfg.immediateTools = inherited.immediateTools
2267
+ }
2268
+ if (o?.inheritPlatform || (o?.inheritPlatform !== false && cfg?.platformTools === undefined)) {
2269
+ cfg = { ...cfg }
2270
+ if (inherited.platformTools !== undefined) cfg.platformTools = inherited.platformTools
2271
+ else delete cfg.platformTools
2272
+ }
1854
2273
  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
2274
  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
2275
  },
@@ -1860,16 +2279,25 @@ export async function startVault(o = {}) {
1860
2279
  // a live stream for a held Space while the page shows it (on: true), or no longer (on: false)
1861
2280
  async stream(room, on) {
1862
2281
  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 }) }
2282
+ if (on) streaming.add(room); else streaming.delete(room)
2283
+ const ready = await workerHost.ready()
2284
+ if (ready === worker) applyStream(ready, room)
1865
2285
  return { streaming: streaming.has(room) }
1866
2286
  },
1867
2287
  async share(room, opts = {}) {
1868
2288
  const it = rooms.find((x) => x.room === room)
1869
2289
  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' })
2290
+ if (it.lane || it.detachedLane) throw Object.assign(new Error('A private lane cannot be shared'), { code: 'private_lane' })
1871
2291
  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 || '') })
2292
+ let link = it.link
2293
+ if (opts?.hostInviteTemplate !== undefined) {
2294
+ 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' })
2295
+ const url = new URL(it.link)
2296
+ embeddedInvite(o.hostInviteTemplate, url.origin, pageOrigin)
2297
+ url.searchParams.set('hostInvite', '1')
2298
+ link = url.href
2299
+ }
2300
+ await screens.share({ link, gated: it.gated === true || roomInviteFlags(it.link).gated ? true : null, title: String((opts && opts.title) || it.title || '') })
1873
2301
  return { shown: true }
1874
2302
  },
1875
2303
  signIn,
@@ -1890,27 +2318,41 @@ export async function startVault(o = {}) {
1890
2318
  // the PERSON confirms in the vault's own pixels: a page script alone cannot sign them out (security review). Whatever the sign-in:
1891
2319
  // 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
2320
  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' })
2321
+ const epoch = privacyEpoch, b = sdk.backup
2322
+ 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
2323
  // 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
2324
  // 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
2325
  // 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
2326
+ if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1898
2327
  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' })
2328
+ try {
2329
+ if (keepRun) await keepRun
2330
+ let saved = false
2331
+ for (let i = 0; !saved && i <= KEEP_AGAIN_MAX; i++) {
2332
+ const revision = keepRevision
2333
+ const [rooms, kept] = await Promise.allSettled([b.save(), keepSync()])
2334
+ if (rooms.status !== 'fulfilled' || kept.status !== 'fulfilled' || !kept.value?.ok) break
2335
+ saved = revision === keepRevision && !kept.value.again
2336
+ }
2337
+ if (!saved) throw new Error('Account changes could not be saved')
2338
+ } catch {
2339
+ if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
2340
+ 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
2341
  }
1902
2342
  }
1903
2343
  if (epoch !== privacyEpoch) throw Object.assign(new Error('The account changed'), { code: 'account_changed' })
1904
2344
  await wipeSignedOut(); emit({ ev: 'signedOut' }); return { signedIn: false } },
2345
+ async enclaveAvailable() { return sdk._encClaimDoc().then(() => true, () => false) },
1905
2346
  async whoami() { return signedIn() ? { signedIn: true, email: sdk.session.email, keyId: sessionKeyId() } : { signedIn: false } },
1906
2347
  async forget(room) {
2348
+ if (pendingForget.has(room)) { await purgeForgotten(room); return { forgotten: true } }
1907
2349
  if (!held(room)) return { forgotten: false }
1908
2350
  // removing a Space's key from this device can lose it for good (no other copy): the PERSON confirms it (security review)
1909
2351
  const it = rooms.find((x) => x.room === room)
1910
2352
  const accountWide = sdk.backup.enabled
1911
2353
  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
2354
+ if (accountWide && sdk.backup.enabled) { sdk.account.forget(room); await fromBackup() }
2355
+ await dropRoom(room) // and from the account, on every device
1914
2356
  return { forgotten: true }
1915
2357
  },
1916
2358
  })
@@ -1936,7 +2378,7 @@ export async function startVault(o = {}) {
1936
2378
  const d = e.data
1937
2379
  if (!d || d.ch !== 'wbvault') return
1938
2380
  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
2381
+ 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
2382
  if (!greeted) { greeted = true; if (typeof screens.ready === 'function') try { screens.ready() } catch { /* */ } joining.then(() => { if (joined) emit({ ev: 'joined', room: joined }) }) }
1941
2383
  return
1942
2384
  }