@witbitz/sdk 4.4.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 (79) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +15 -0
  3. package/accountErase.js +9 -3
  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/awsKey.js +3 -1
  11. package/backupRecord.js +3 -0
  12. package/codeAttachments.js +1 -0
  13. package/codeCache.js +27 -3
  14. package/codeCloud.js +2 -0
  15. package/codeComputers.js +8 -0
  16. package/codeSent.js +43 -2
  17. package/codeTransport.js +24 -5
  18. package/connections.js +21 -3
  19. package/decrypt.html +69 -9
  20. package/eraseFile.js +15 -0
  21. package/idbSeal.js +5 -2
  22. package/inviteReceive.js +44 -0
  23. package/inviteSend.js +8 -2
  24. package/l1-worker-src.js +1 -1
  25. package/l1-worker.js +30 -14
  26. package/laneAssociation.js +11 -1
  27. package/laneLinkCore.js +9 -0
  28. package/ledgerView.js +30 -4
  29. package/manifest.json +78 -72
  30. package/offlineBundle.js +21 -0
  31. package/package.json +8 -2
  32. package/protectedLocal.js +34 -11
  33. package/reactionHolders.js +86 -0
  34. package/roomIntake.js +324 -0
  35. package/roomRoster.js +9 -2
  36. package/scheduleNext.js +60 -0
  37. package/sdkA2A.js +46 -8
  38. package/sdkAccount.js +71 -14
  39. package/sdkAccountDoc.js +3 -3
  40. package/sdkAccountSections.js +58 -18
  41. package/sdkAgui.js +33 -6
  42. package/sdkBackup.js +21 -6
  43. package/sdkBackupV2.js +15 -3
  44. package/sdkCloudDevice.js +12 -3
  45. package/sdkComputers.js +118 -17
  46. package/sdkDictation.js +1 -1
  47. package/sdkErase.js +3 -1
  48. package/sdkExports.js +15 -6
  49. package/sdkInvitations.js +4 -2
  50. package/sdkKeptAgent.js +19 -3
  51. package/sdkKeptIntake.js +100 -0
  52. package/sdkLaneLink.js +5 -6
  53. package/sdkRekey.js +72 -5
  54. package/sdkSchedules.js +8 -1
  55. package/sdkSpeech.js +14 -1
  56. package/sdkTemporaryRooms.js +2 -1
  57. package/sdkTurn.js +12 -4
  58. package/sharedViews.js +17 -1
  59. package/siri.js +29 -5
  60. package/spaceClient.js +96 -12
  61. package/spaceExport.js +50 -5
  62. package/spaceFork.js +15 -7
  63. package/spaceTemplates.js +2 -2
  64. package/speechOut.js +17 -3
  65. package/store.js +51 -13
  66. package/sw-notif-core.js +2 -1
  67. package/tapTrail.js +58 -0
  68. package/usageReceipts.js +12 -5
  69. package/vault-core.js +90 -16
  70. package/vault-kit.mjs +2 -2
  71. package/vault-screens.js +25 -11
  72. package/vaultAtRest.js +3 -2
  73. package/vaultCoreLock.js +3 -1
  74. package/vaultCorePush.js +58 -7
  75. package/vaultWorkerHost.js +9 -3
  76. package/witbitz-admin.d.ts +3 -0
  77. package/witbitz-admin.mjs +10 -10
  78. package/witbitz-sdk.d.ts +59 -23
  79. package/witbitz-sdk.js +271 -64
package/awsKey.js CHANGED
@@ -88,7 +88,9 @@ export function awsUsageRow (st) {
88
88
  if (!Number.isFinite(usd) || !(cap > 0)) return null
89
89
  let when = ''
90
90
  try { when = st.resetsAt ? 'starts again on ' + new Date(st.resetsAt).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', timeZone: 'UTC' }) : '' } catch { when = '' }
91
- const note = [st.tier === 'free' ? 'the free allowance' : '', usd >= cap ? 'used up' : '', when].filter(Boolean).join(' · ')
91
+ // held: what a running computer may still spend — admission counts it against the cap (side sweep cloud-allowance-display-omits-active-reservations)
92
+ const held = Number(m.heldUsd) > 0 ? Number(m.heldUsd) : 0
93
+ const note = [st.tier === 'free' ? 'the free allowance' : '', held ? `${creditsText(creditsOf(held))} held by a running computer` : '', usd + held >= cap ? 'used up' : '', when].filter(Boolean).join(' · ')
92
94
  return { label: 'Cloud computers', value: `${creditsNumber(creditsOf(usd))} of ${creditsText(creditsOf(cap))}`, note } // credits (100 = $1); the key keeps dollars
93
95
  }
94
96
 
package/backupRecord.js CHANGED
@@ -30,6 +30,9 @@ export function orphanRows (recents, storageKeys, { mk, us }) {
30
30
  let rm = null
31
31
  if (k && k.indexOf(mk) === 0) rm = k.slice(mk.length)
32
32
  else if (k && k.indexOf(us) === 0) rm = k.slice(us.length)
33
+ // a TEMPORARY room (`tmp-`, roomState.isTempRoom) is never durable: a share an earlier acceptance left in storage must not
34
+ // reach the backup (side sweep: temporary-split-invite-share-enters-backup)
35
+ if (rm && rm.startsWith('tmp-')) continue
33
36
  if (rm && !listed.has(rm)) { orphans.push({ room: rm, title: '', at: 0 }); listed.add(rm) }
34
37
  }
35
38
  return orphans
@@ -46,6 +46,7 @@ export function formatSize(bytes) {
46
46
 
47
47
  const SHOWN_MAX = 200 // a file name is prompt text the model reads — keep it a name, not a paragraph (review finding)
48
48
  const shown = (name) => String(name || 'file').replace(/[\r\n]+/g, ' ').replace(/ — /g, ' - ').slice(0, SHOWN_MAX)
49
+ export const shownName = shown // the form a name takes in the note (codeSent.js compares a sent file's name with the note's in this form)
49
50
 
50
51
  /**
51
52
  * The note that replaces the files in the message. `entries`: {name, size, path, copy?, inline?, noCopy?} — `copy` is the
package/codeCache.js CHANGED
@@ -14,6 +14,7 @@
14
14
  // remembered. It is plaintext at rest on YOUR device, the same trust boundary as the room chat cache, and it is dropped
15
15
  // with the rest of the app's storage on sign-out.
16
16
  import { idb } from './idb.js'
17
+ import { cursorBefore } from './codeHistory.js'
17
18
 
18
19
  const SESS = (cid, sid) => `code:sess:${cid}:${sid}`
19
20
  const LIST = (cid) => `code:list:${cid}`
@@ -70,7 +71,22 @@ export async function saveSession(cid, sid, msgs, meta = {}, store = idb) {
70
71
  if (!cid || !sid) return
71
72
  const kept = trimMessages(msgs)
72
73
  if (!kept.length) return
73
- await store.set(SESS(cid, sid), { msgs: kept, at: Date.now(), trimmed: Array.isArray(msgs) && kept.length < msgs.length, ...meta })
74
+ const trimmed = Array.isArray(msgs) && kept.length < msgs.length
75
+ // A trimmed copy pages back from its OWN oldest message: the page's cursor points before messages it no longer keeps, or is ''
76
+ // at the start, and an offline open then skipped the dropped block or could not page at all (side sweep 2026-11-28)
77
+ if (removed.has(SESS(cid, sid))) return // deleted: a save queued before the delete does not bring it back (side sweep round 2)
78
+ await store.set(SESS(cid, sid), { msgs: kept, at: Date.now(), trimmed, ...meta, ...(trimmed ? { cursor: cursorBefore(kept[0]) } : {}) })
79
+ if (removed.has(SESS(cid, sid))) await store.del(SESS(cid, sid)) // deleted while this write was on its way
80
+ }
81
+ // The sessions deleted while this page lives. A session id is never reused, so the set only grows by what was deleted here.
82
+ const removed = new Set()
83
+
84
+ /** A renamed session's saved copy takes its new title — nothing else changes (its sync time, its "trimmed"). Help reads titles
85
+ * from these copies, and kept the old name until the transcript was saved again (side sweep 2026-11-28). */
86
+ export async function retitleSession(cid, sid, title, store = idb) {
87
+ if (!cid || !sid || typeof title !== 'string') return
88
+ const c = await store.get(SESS(cid, sid))
89
+ if (c && typeof c === 'object' && Array.isArray(c.msgs)) await store.set(SESS(cid, sid), { ...c, title })
74
90
  }
75
91
 
76
92
  /** → { msgs, at, trimmed, … } or null. */
@@ -80,6 +96,7 @@ export async function clearSession(cid, sid, store = idb, strict = false) {
80
96
  }
81
97
 
82
98
  export async function removeCachedSession(cid, sid, store = idb, local) {
99
+ if (cid && sid) removed.add(SESS(cid, sid))
83
100
  await clearSession(cid, sid, store, true)
84
101
  const saved = await loadList(cid, store)
85
102
  if (saved?.list.some(row => row.id === sid)) {
@@ -99,7 +116,10 @@ export async function removeCachedSession(cid, sid, store = idb, local) {
99
116
  export async function loadSession(cid, sid, store = idb) {
100
117
  if (!cid || !sid) return null
101
118
  const c = await store.get(SESS(cid, sid))
102
- return c && Array.isArray(c.msgs) && c.msgs.length ? c : null
119
+ if (!(c && Array.isArray(c.msgs) && c.msgs.length)) return null
120
+ // a TRIMMED copy pages back from its own oldest message — a copy saved before saveSession wrote that cursor kept the page's own
121
+ // (pointing before messages it dropped, or '' — no paging at all) (side sweep: code-trimmed-cache-stale-cursor)
122
+ return c.trimmed ? { ...c, cursor: cursorBefore(c.msgs[0]) } : c
103
123
  }
104
124
 
105
125
  /** The session LIST as the computer last gave it, so the history sheet has something to show when it is away. */
@@ -121,7 +141,8 @@ export async function cachedSessions(cid, store = idb) {
121
141
  const pfx = `code:sess:${cid}:`
122
142
  const rows = await store.entries(pfx)
123
143
  return rows
124
- .map(([k, v]) => ({ id: k.slice(pfx.length), at: (v && v.at) || 0, msgs: (v && Array.isArray(v.msgs) && v.msgs.length) || 0, title: (v && v.title) || '', dir: (v && v.dir) || '' }))
144
+ // `revert`: the session's undo point, kept with its copy — a row rebuilt from the copies alone drew an undone turn as current (side sweep: code-offline-copy-loses-undo-point)
145
+ .map(([k, v]) => ({ id: k.slice(pfx.length), at: (v && v.at) || 0, msgs: (v && Array.isArray(v.msgs) && v.msgs.length) || 0, title: (v && v.title) || '', dir: (v && v.dir) || '', ...(v && v.revert && typeof v.revert === 'object' ? { revert: v.revert } : {}) }))
125
146
  .sort((a, b) => b.at - a.at)
126
147
  }
127
148
 
@@ -145,5 +166,8 @@ export function slimSession(x) {
145
166
  const t = x.time || {}
146
167
  o.time = {}
147
168
  for (const f of ['created', 'updated', 'archived']) if (typeof t[f] === 'number') o.time[f] = t[f]
169
+ // its undo point: without it an offline reopen drew an undone turn as current (side sweep 2026-11-28; read by opencodeWire normRevert)
170
+ const r = x.revert
171
+ if (r && typeof r === 'object' && typeof r.messageID === 'string' && r.messageID) o.revert = { messageID: r.messageID, ...(typeof r.partID === 'string' && r.partID ? { partID: r.partID } : {}), snapshot: !!r.snapshot }
148
172
  return o
149
173
  }
package/codeCloud.js CHANGED
@@ -497,6 +497,8 @@ export async function openCloud(computer, { token, aws = null, onStep = () => {}
497
497
  if (granted.github) { try { onGitHub(granted.github) } catch { /* */ } }
498
498
  assigned = await call({ action: 'op', workspace: c.workspace, cid: opened.cid, req: { op: 'assign', sealed } })
499
499
  }
500
+ // the enclave refused the assign (host.py answers 200 { error } and throws that enclave away): not opened
501
+ if (assigned.error) throw new CloudError(`the cloud computer could not be set up (${assigned.error})`, { code: 'assign' })
500
502
  onStep('connecting')
501
503
  // ★ THE SESSION HANDLE GOES OUT THROUGH A CALLBACK, NOT THE RETURN VALUE. What openCloud RETURNS is merged into the
502
504
  // account's sealed entry, and `normCloudEntry` is an allowlist — a new field there is either dropped silently or
package/codeComputers.js CHANGED
@@ -380,6 +380,14 @@ export async function moveCloudCallKeys ({ hold, load = loadCloud, save = saveCl
380
380
  }
381
381
  export function loadCloud() { try { return normCloud(JSON.parse(localStorage.getItem(CLOUD_KEY) || 'null')) } catch { return normCloud(null) } }
382
382
  export function saveCloud(reg) { try { localStorage.setItem(CLOUD_KEY, JSON.stringify(normCloud(reg))) } catch { /* private mode */ } }
383
+ /** THE ACCOUNT'S cloud computers, for "Delete my account" (side sweep: account-erase-skips-unsynced-cloud-workspace): this device's
384
+ * list merged with the account's synced one (`readRemote()` → its state, null = none) — a workspace made on another device and not
385
+ * synced here yet got no destroy request. → { reg, unread }: `unread` when the account's list could not be read (the step is not
386
+ * done; the ones known here still go); a device with no account (`no_account`) has only its own list. */
387
+ export async function cloudForErase(readRemote) {
388
+ try { return { reg: mergeCloud(loadCloud(), await readRemote()), unread: false } }
389
+ catch (e) { return { reg: loadCloud(), unread: !(e && e.code === 'no_account') } }
390
+ }
383
391
  export function adoptCloud(remote) {
384
392
  const cur = loadCloud()
385
393
  const next = mergeCloud(cur, remote)
package/codeSent.js CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { splitPdfBlocks } from './pdfText.js'
10
10
  import { unwrapJsonMessage } from './opencodeWire.js'
11
+ import { parseAttachmentNote, shownName } from './codeAttachments.js'
11
12
 
12
13
  export function providerRefusal(result) {
13
14
  const err = result?.info?.error
@@ -24,19 +25,59 @@ export const userIds = (messages) => new Set((Array.isArray(messages) ? messages
24
25
  * words, so history alone cannot confirm delivery.) `text` is what the person typed; the message may carry more after it (a PDF's text)
25
26
  * and a language line beside it, never less.
26
27
  */
27
- export function promptLanded(messages, { knownUserIds, text }) {
28
+ // The files a user message carries: its file parts' names, and the PDFs read in the page (their text blocks name them —
29
+ // in a /command's synthetic expansion too).
30
+ /** The names a list of staged files goes out under (opencodeWire.partsFor's filename). */
31
+ export const sentNames = (list) => (Array.isArray(list) ? list : []).map((f) => String((f && f.name) || 'attachment'))
32
+ // …and the files the CONNECTOR saved (side sweep round 5): it replaces a document's file part with its saved-attachment note
33
+ // (codeAttachments.js), so those names are read from the note; an image keeps its part and is listed as `inline` — counted once.
34
+ // Names compare in the note's shown form (shownName), on both sides.
35
+ const namesOf = (m) => {
36
+ const names = []
37
+ for (const p of m.parts || []) {
38
+ if (p?.type === 'file') names.push(shownName(String(p.filename || '')))
39
+ else if (p?.type === 'text') {
40
+ const note = p.synthetic ? parseAttachmentNote(p.text) : null
41
+ if (note) { for (const e of note) if (!e.inline) names.push(e.name); continue }
42
+ for (const d of splitPdfBlocks(words(p.text)).pdfs) names.push(shownName(String(d.name)))
43
+ }
44
+ }
45
+ return names.sort()
46
+ }
47
+ // `files` (optional: the names of the files sent; side sweep round 3, code-attachment-delivery-matched-by-caption): when given,
48
+ // the message must carry exactly those files too — a caption alone confirmed files that never arrived, and a file-only
49
+ // prompt (no words) could never be confirmed. Without it, the words alone decide, as before.
50
+ export function promptLanded(messages, { knownUserIds, text, files }) {
28
51
  const known = knownUserIds instanceof Set ? knownUserIds : new Set()
29
52
  const want = words(text)
53
+ const wantFiles = Array.isArray(files) ? files.map((f) => shownName(String(f || ''))).sort() : null
54
+ if (!want && !(wantFiles && wantFiles.length)) return false
30
55
  const history = Array.isArray(messages) ? messages : []
31
56
  for (let i = history.length - 1; i >= 0; i--) {
32
57
  const m = history[i], info = m?.info
33
58
  if (info?.role !== 'user' || !info.id) continue
34
59
  if (known.has(info.id)) break
35
- if (want && (m.parts || []).some(p => p?.type === 'text' && !p.synthetic && (words(p.text) === want || splitPdfBlocks(words(p.text)).text === want))) return true
60
+ const saidIt = !want || (m.parts || []).some(p => p?.type === 'text' && !p.synthetic && (words(p.text) === want || splitPdfBlocks(words(p.text)).text === want))
61
+ if (!saidIt) continue
62
+ if (!wantFiles) return true
63
+ const got = namesOf(m)
64
+ if (got.length === wantFiles.length && got.every((n, j) => n === wantFiles[j])) return true
36
65
  }
37
66
  return false
38
67
  }
39
68
 
69
+ /**
70
+ * Has the prompt waiting on screen (`state.pending`) come back from the computer? By ITS message — the user ids known at send,
71
+ * its words and files — not by the count of user messages, which another device's message raised as well and so cleared the
72
+ * waiting prompt and its filenames (side sweep round 3: code-pending-attachment-cleared-by-unrelated-message). A pending
73
+ * prompt that carries no `known` set falls back to the count (`shownUsers` = user messages drawn now).
74
+ */
75
+ export function pendingEchoed(messages, pending, shownUsers) {
76
+ if (!pending) return false
77
+ if (!(pending.known instanceof Set)) return shownUsers > pending.users
78
+ return promptLanded(messages, { knownUserIds: pending.known, text: pending.landed != null ? pending.landed : pending.text, files: pending.files })
79
+ }
80
+
40
81
  export function firstOutputStarted(messages) {
41
82
  for (let i = messages.length - 1; i >= 0; i--) {
42
83
  const message = messages[i]
package/codeTransport.js CHANGED
@@ -86,6 +86,7 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
86
86
  let caps = []
87
87
  let omitted = [] // what the connector leaves out on purpose (its hello's `omits`): no update adds it (state machines pass 9, C#8)
88
88
  let autoList = []
89
+ let autoAsk = null // { sid, on, hellos }: a switch of Auto sent, not yet settled by a hello (side sweep: code-auto-choice-before-computer-confirmation)
89
90
  const autoListeners = new Set()
90
91
  const toolWaiters = [] // askTools() calls waiting for the computer's {t:'tools'} answer
91
92
  const tellAuto = (e) => { for (const fn of autoListeners) { try { fn(e) } catch { /* */ } } }
@@ -146,9 +147,22 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
146
147
  const nextCaps = Array.isArray(m.caps) ? m.caps.filter((c) => typeof c === 'string').slice(0, 16) : []
147
148
  omitted = Array.isArray(m.omits) ? m.omits.filter((c) => typeof c === 'string').slice(0, 16) : []
148
149
  const nextAuto = nextCaps.includes('auto') && Array.isArray(m.auto) ? m.auto.filter((s) => typeof s === 'string' && /^ses[A-Za-z0-9_-]{1,80}$/.test(s)) : []
149
- if (nextCaps.join() !== caps.join() || nextAuto.join() !== autoList.join()) { caps = nextCaps; autoList = nextAuto; tellAuto({ kind: 'sessions', sessions: [...autoList] }) }
150
+ const autoChanged = nextCaps.join() !== caps.join() || nextAuto.join() !== autoList.join()
151
+ if (autoChanged) { caps = nextCaps; autoList = nextAuto; tellAuto({ kind: 'sessions', sessions: [...autoList] }) }
152
+ // A SENT SWITCH OF AUTO IS SETTLED HERE (side sweep: code-auto-choice-before-computer-confirmation): applied → confirmed; still
153
+ // not applied two hellos on (the first may have left before the switch arrived) → the page is told, never left showing it.
154
+ if (autoAsk) {
155
+ autoAsk.hellos++
156
+ const done = autoList.includes(autoAsk.sid) === autoAsk.on
157
+ if (done || autoAsk.hellos >= 2) {
158
+ const a = autoAsk; autoAsk = null
159
+ if (!autoChanged) tellAuto({ kind: 'sessions', sessions: [...autoList] })
160
+ if (!done) tellAuto({ kind: 'autoRefused', sid: a.sid, on: a.on })
161
+ }
162
+ }
150
163
  // A NEW nonce = the connector restarted, redialled or rotated: anything it has not answered was refused or lost —
151
164
  // re-ask the reads with the new nonce and renew the streams. (Mutations are never re-sent.)
165
+ if (renewed) dropTurns('reconnected')
152
166
  if (renewed && last === 'online') { resubscribe(); for (const e of pending.values()) if (e.resend) e.resend() }
153
167
  // ★ Only a CHANGE is announced. A hello arrives every 20 s and the browser's row must not be rebuilt under the
154
168
  // owner's finger — `changed()` below has the same discipline for the status string.
@@ -167,7 +181,7 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
167
181
  role: 'client',
168
182
  relay: computer.relay,
169
183
  WebSocketImpl,
170
- onState: (s) => { peersKnown = false; if (s === 'open') { openedAt = now(); peer.send({ t: 'ping' }); setTimeout(changed, PEERS_WAIT_MS + 50) } else { lastHello = 0; nonce = '' } changed() },
184
+ onState: (s) => { peersKnown = false; if (s === 'open') { if (openedAt) dropTurns('reconnected'); openedAt = now(); peer.send({ t: 'ping' }); setTimeout(changed, PEERS_WAIT_MS + 50) } else { lastHello = 0; nonce = '' } changed() },
171
185
  onPeers: (n) => { peersKnown = peer.isOpen; if (n < 2) lastHello = 0; else peer.send({ t: 'ping' }); changed() },
172
186
  onMessage: (m) => {
173
187
  if (m.t === 'hello') { onHello(m); return }
@@ -192,6 +206,10 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
192
206
  }
193
207
  },
194
208
  })
209
+ // A TURN WHOSE ANSWER MAY HAVE BEEN LOST (side sweep 2026-11-28): a turn has no timeout and is never re-sent, so an answer sent while
210
+ // the socket was being redialled (or by a connector that restarted) left it waiting for ever. Settled as failed, the page asks the
211
+ // computer whether the prompt landed (opencodeApp.js promptLanded) — it is never sent twice.
212
+ function dropTurns(why) { for (const [id, e] of pending) if (e.turn) { pending.delete(id); clearTimeout(e.timer); e.resolve({ ok: false, status: 0, json: null, text: why }) } }
195
213
  const resubscribe = () => { if (nonce) for (const p of subs.keys()) peer.send({ t: 'sub', c: cid, k: nonce, p }) }
196
214
  const wake = () => {
197
215
  lastTick = now()
@@ -237,7 +255,7 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
237
255
  egress: () => egressState,
238
256
  onBrowse(fn) { browseListeners.add(fn); return () => browseListeners.delete(fn) },
239
257
  /** Switch Auto for one session on the computer (nonce-checked there). The next hello confirms it. */
240
- setAuto(sid, dir, on) { if (!nonce || !caps.includes('auto')) return false; peer.send({ t: 'auto', k: nonce, sid, dir, on: !!on }); return true },
258
+ setAuto(sid, dir, on) { if (!nonce || !caps.includes('auto')) return false; peer.send({ t: 'auto', k: nonce, sid, dir, on: !!on }); autoAsk = { sid, on: !!on, hellos: 0 }; return true },
241
259
  /** Private browsing for the agent's browser on this computer — only where its browse report says `canPrivate` (an older
242
260
  * witbitz-code never does). Nonce-checked there; the next hello carries the new state. */
243
261
  setBrowsePrivate(on) { if (!nonce || !(browseState && browseState.canPrivate)) return false; peer.send({ t: 'browse', k: nonce, private: !!on }); return true },
@@ -256,7 +274,8 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
256
274
  * was built with and never removes any, so this can only widen what is enforced, never narrow it. */
257
275
  /** "Waiting for your approval" (codeRemind.js): with a prompt, who to tickle when an approval in this session waits — this
258
276
  * device's signed push grant and its own key. Only to a computer that says it can (`remind`). */
259
- sendRemind(sid, dir, r) { if (!nonce || !caps.includes('remind') || !r || !sid) return false; peer.send({ t: 'remind', k: nonce, sid, dir, grant: r.grant, key: r.key, url: r.url }); return true },
277
+ // → the send itself (a promise, truthy): a retiring connection waits for it — sealed and on the wire — before it closes (side sweep round 5)
278
+ sendRemind(sid, dir, r) { if (!nonce || !caps.includes('remind') || !r || !sid) return false; return peer.send({ t: 'remind', k: nonce, sid, dir, grant: r.grant, key: r.key, url: r.url }).then((ok) => ok !== false, () => false) },
260
279
  sendModels(list) { if (!nonce || !Array.isArray(list) || !list.length) return false; peer.send({ t: 'models', k: nonce, confidential: list.slice(0, 100) }); return true },
261
280
  kick: () => { wake(); peer.kick() }, // the page is visible again: ask the computer, and redial a dead socket
262
281
  close() {
@@ -273,7 +292,7 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
273
292
  const msg = () => ({ t: 'req', id, k: nonce, m: method, p, ...b }) // built at send time: always the CURRENT nonce
274
293
  // A turn POST returns only when the model has finished; its progress rides the event stream, so no timeout.
275
294
  const turn = method === 'POST' && /\/message$/.test(p.split('?')[0])
276
- const entry = { resolve, timer: 0, resend: null }
295
+ const entry = { resolve, timer: 0, resend: null, turn }
277
296
  // Reads are safe to re-ask after a reconnect; anything that changes state is never sent twice.
278
297
  if (method === 'GET') entry.resend = () => peer.send(msg())
279
298
  if (!turn) entry.timer = setTimeout(() => { pending.delete(id); resolve({ ok: false, status: 0, json: null, text: 'timeout' }) }, globalThis.__codeRequestMs || REQUEST_TIMEOUT_MS) // __codeRequestMs: tests only (as __codeListMs)
package/connections.js CHANGED
@@ -106,6 +106,18 @@ export async function attestStandingSentinel({ post, auth = {}, pins = STANDING_
106
106
  /** The entry a ROOM keeps (its sealed config): enough to name and spend the connection, never the secret. */
107
107
  export const roomEntry = (c) => ({ account: c.account, id: c.id, callKey: c.callKey, label: c.label || '', host: c.host, ...(c.mcp ? { mcp: c.mcp } : {}), ...(c.webhook ? { webhook: c.webhook } : {}), ...(c.webhook && c.job ? { job: c.job } : {}), ...(c.reads === 'auto' && !c.mcp ? { reads: 'auto' } : {}) }) // reads: a GET through it runs without asking (connectionEntry.js keeps it; agent/connectionTools.mjs readsRunAlone)
108
108
 
109
+ /** A SETUP FORM'S CONNECTION, ATTACHED ONCE (side sweep 2026-11-28): the Grok Bot and job-agent forms saved a new account connection
110
+ * and then asked the room to take it; when the room refused, Connect was enabled again and a retry made a SECOND connection for the
111
+ * same trigger, the first left in the account. `get(key, attach)` hands back the connection already made for the same pasted values;
112
+ * `done()` once the room took it. → { get, done } */
113
+ export function attachOnce () {
114
+ let held = null
115
+ return {
116
+ async get (key, attach) { if (held && held.key === key) return held.conn; const conn = await attach(); held = { key, conn }; return conn },
117
+ done () { held = null },
118
+ }
119
+ }
120
+
109
121
  /**
110
122
  * Attach: seal to the Sentinel, grant, then record in this room through `record(patch, by)` — the shell passes
111
123
  * `(patch, by) => l1.setConfig(room, patch, by)`; the patch is DECLARATIVE ({ add: entry }) because it crosses the L1
@@ -162,10 +174,14 @@ export async function attachConnection({ post, pendingStore, auth = {}, record,
162
174
  // dropped on a definite answer (the caller keeps a granted one), and adopted when the account's list shows it.
163
175
  let _pendingStore = { keep () {}, drop () {} }
164
176
  export const setPendingKeyStore = (s) => { _pendingStore = { keep () {}, drop () {}, ...(s || {}) } }
177
+ // NOT A DEFINITE ANSWER: the relay timed out or could not read the Sentinel's reply, or the gateway failed — the grant may have
178
+ // been filed. The key stays pending (adopted when the account lists it), as for no answer (side sweep 2026-11-28: a timeout dropped it).
179
+ const UNSURE = new Set(['sentinel_timeout', 'sentinel_bad_answer', 'sentinel_error'])
180
+ export const unsureAnswer = (r) => !!r && (UNSURE.has(r.error) || (typeof r.status === 'number' && (r.status === 0 || r.status >= 500)))
165
181
  export async function postWithPendingKey (post, body, id, rec, store = _pendingStore) {
166
182
  try { await store.keep(id, rec) } catch (e) { if (store.durable) throw e }
167
183
  const r = await post(body) // a throw (no answer) leaves it pending
168
- if (r && (r.error || (r.ok && !store.durable))) { try { await store.drop(id, rec?.callKey) } catch { /* */ } }
184
+ if (r && !unsureAnswer(r) && (r.error || (r.ok && !store.durable))) { try { await store.drop(id, rec?.callKey) } catch { /* */ } }
169
185
  return r
170
186
  }
171
187
  export { adoptPendingKeys } // connPending.js — the rule, shared with the hosted app's vault (vaultConnKeys.js)
@@ -193,7 +209,7 @@ async function sealWithCallKey (att, payload, id, rec, minter = _minter) {
193
209
  async function postGrant (post, body, id, rec, sk, filed = (r) => !!(r && r.ok && !r.error), final = () => ({}), pendingStore) {
194
210
  if (!sk.held) return rec ? postWithPendingKey(post, body, id, { ...rec, callKey: sk.callKey }, pendingStore) : post(body)
195
211
  const r = await post(body) // a throw (no answer): the vault keeps it pending, adopted when the account lists it
196
- if (r && (r.ok || r.error)) { let ok = false; try { ok = !!(await sk.settle(filed(r), filed(r) ? final(r) : {})) } catch { ok = false } if (filed(r) && !ok) throw new ConnectionError('the connection was made, but your vault did not keep its key — open Connections again to finish', 'vault') }
212
+ if (r && !unsureAnswer(r) && (r.ok || r.error)) { let ok = false; try { ok = !!(await sk.settle(filed(r), filed(r) ? final(r) : {})) } catch { ok = false } if (filed(r) && !ok) throw new ConnectionError('the connection was made, but your vault did not keep its key — open Connections again to finish', 'vault') }
197
213
  return r
198
214
  }
199
215
 
@@ -207,7 +223,9 @@ export async function listConnections({ post, auth = {}, dispKey }) { // dispKey
207
223
  /** Detach everywhere (the Sentinel forgets it; every room's callKey for it is dead), and drop it from this room. */
208
224
  export async function detachConnection({ post, auth = {}, record, by, id }) {
209
225
  const r = await post({ op: 'sentinel', sentinel: { mode: 'credrevoke', id }, ...auth })
210
- if (!r || r.error) throw new ConnectionError(`could not detach (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
226
+ // only the Sentinel's own "done" counts (side sweep 2026-11-28: a failed request answered with a status alone read as revoked, 0) —
227
+ // an already-removed connection answers { ok: true, revoked: 0 }
228
+ if (!r || r.error || r.ok !== true) throw new ConnectionError(`could not detach (${(r && (r.error || r.status)) || 'no answer'})`, (r && r.error) || 'unreachable')
211
229
  if (typeof record === 'function') await record({ connections: { remove: id } }, by)
212
230
  return { revoked: Number(r.revoked) || 0 }
213
231
  }
package/decrypt.html CHANGED
@@ -149,6 +149,10 @@
149
149
  <script>
150
150
  (function () {
151
151
  'use strict'
152
+ // THE READER AS IT LOADED — before anything below touches the page. "Save this decryptor" saves this, never the live page: after a
153
+ // conversation was read the live page holds its messages and photos in the clear (side sweep 11-28). (This script is the body's
154
+ // last element, so the whole document is parsed here; typed values are never serialised.)
155
+ const PRISTINE = '<!doctype html>\n' + document.documentElement.outerHTML
152
156
  const enc = new TextEncoder(), dec = new TextDecoder()
153
157
  const $ = (id) => document.getElementById(id)
154
158
  const subtle = window.crypto && window.crypto.subtle
@@ -222,18 +226,64 @@
222
226
  } else for (const key of usable) { s = await openEnv(env, key); if (s != null) break }
223
227
  if (s == null) continue; opened++; try { entries.push(JSON.parse(s)) } catch (e) {}
224
228
  }
225
- return { entries, opened, total: ledger.boxes.length, v3: true, needsRoom: bound > 0 && !room && !cands.length }
229
+ return { entries, opened, total: ledger.boxes.length, v3: true, needsRoom: bound > 0 && !room && !cands.length, keys: usable }
226
230
  }
227
231
  const s = await openEnv(ledger, wk); if (s == null) return { entries: null, v3: false }
228
232
  let p; try { p = JSON.parse(s) } catch (e) { return { entries: null, v3: false } }
229
- return { entries: Array.isArray(p) ? p : (p && Array.isArray(p.entries) ? p.entries : null), v3: false }
233
+ return { entries: Array.isArray(p) ? p : (p && Array.isArray(p.entries) ? p.entries : null), v3: false, keys: [wk] }
230
234
  }
231
235
 
236
+ // THE STORED ATTACHMENTS. A photo or document a member shared is stored apart from its message (the message keeps `ref`, or
237
+ // `parts` for a large file). An offline copy made since 2026-11-28 carries their bytes, still SEALED exactly as the Space
238
+ // stored them, under `blobs` = { ref: envelope } (spaceClient.js archiveAttachments); each opens with the keys that opened the
239
+ // messages. One that is not in the file — an older copy, past the copy's size cap, or a read that failed — is marked so the
240
+ // transcript says "not in this copy". Returns NEW entries; the opened ones carry their bytes as an inline attachment does.
241
+ const NOT_IN_COPY = '__wbNotInCopy'
242
+ const storedRefs = (a) => (a && !(typeof a.b64 === 'string' && a.b64)) ? (Array.isArray(a.parts) && a.parts.length ? a.parts : (typeof a.ref === 'string' && a.ref ? [a.ref] : [])) : []
243
+ async function openAttachments(entries, blobs, keys) {
244
+ const have = blobs && typeof blobs === 'object' && !Array.isArray(blobs) ? blobs : {}
245
+ const cache = new Map()
246
+ const openBlob = async (ref) => {
247
+ if (cache.has(ref)) return cache.get(ref)
248
+ let env = Object.prototype.hasOwnProperty.call(have, ref) ? have[ref] : null, out = null
249
+ if (typeof env === 'string') { try { env = JSON.parse(env) } catch (e) { env = null } }
250
+ if (env) for (const k of (keys || [])) { const s = await openEnv(env, k); if (s == null) continue; try { const o = JSON.parse(s); if (o && typeof o.b64 === 'string') out = o } catch (e) { /* not an attachment */ } break }
251
+ cache.set(ref, out); return out
252
+ }
253
+ const one = async (a) => {
254
+ const refs = storedRefs(a); if (!refs.length || refs.some((r) => typeof r !== 'string' || !r)) return a
255
+ const parts = []
256
+ for (const r of refs) { const o = await openBlob(r); if (!o) return { ...a, [NOT_IN_COPY]: true }; parts.push(o) }
257
+ return { ...a, b64: parts.map((p) => p.b64).join(''), mime: a.mime || parts[0].mime || 'application/octet-stream' } // parts' base64 concatenates exactly (agent/attachmentBlobs.mjs PARTS)
258
+ }
259
+ const out = []
260
+ for (const e of entries) {
261
+ if (!e || typeof e !== 'object') { out.push(e); continue }
262
+ const next = { ...e }
263
+ for (const kind of ['images', 'files']) if (Array.isArray(e[kind])) { const list = []; for (const a of e[kind]) list.push(await one(a)); next[kind] = list }
264
+ out.push(next)
265
+ }
266
+ return out
267
+ }
268
+ const notInCopyCount = (entries) => entries.reduce((n, e) => n + (e && typeof e === 'object' ? [].concat(Array.isArray(e.images) ? e.images : [], Array.isArray(e.files) ? e.files : []).filter((a) => a && a[NOT_IN_COPY]).length : 0), 0)
269
+ const notInCopyNote = (entries) => { const n = notInCopyCount(entries || []); return n ? ` ${n} attachment${n === 1 ? ' is' : 's are'} not in this copy.` : '' }
270
+
232
271
  // ── render ──
233
272
  const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]))
234
273
  const fmtTs = (ts) => { const n = Number(ts); if (!Number.isFinite(n) || n <= 0) return ''; try { return new Date(n).toLocaleString() } catch (e) { return '' } }
235
274
  let lastEntries = null, lastTitle = 'Conversation'
236
275
  const looksLikeAgent = (e) => { const n = String((e && e.name) || '').toLowerCase(); return e && (e.agent === true || n === 'assistant' || n === 'agent') }
276
+ // SENDERS AS THE LIVE TRANSCRIPT NAMES THEM (side sweep: offline-reader-omits-message-attribution; messageRender.js addSharedLine and
277
+ // the verified-name line): a private lane's copy of a shared-room message says so, and an email gives way to the @username the Space
278
+ // verified (`by.user` on a lane copy, `user` on a verified entry); a name the person chose stays, with the @username beside it.
279
+ const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
280
+ const isLaneCopy = (e) => e.source === 'shared' && String(e.id == null ? '' : e.id).startsWith('sh:') && !(e.carried && typeof e.carried === 'object') // = laneLinkCore.js
281
+ function whoOf(e) {
282
+ const base = String(e.name || e.from || 'Unknown')
283
+ if (isLaneCopy(e)) { const u = e.by && typeof e.by === 'object' && typeof e.by.user === 'string' ? e.by.user : ''; return { lane: true, name: u && EMAIL_RE.test(base.trim()) ? '@' + u : base, user: '' } }
284
+ if (!looksLikeAgent(e) && e.verified === true && typeof e.user === 'string' && e.user) return EMAIL_RE.test(base.trim()) ? { name: '@' + e.user, user: '' } : { name: base, user: e.user }
285
+ return { name: base, user: '' }
286
+ }
237
287
 
238
288
  function render(entries, title) {
239
289
  lastEntries = entries; lastTitle = title || 'Conversation'
@@ -245,11 +295,20 @@
245
295
  for (const e of entries) {
246
296
  if (!e || typeof e !== 'object') continue
247
297
  const row = document.createElement('div'); row.className = 'msg' + (looksLikeAgent(e) ? ' agent' : '')
248
- let html = `<div><span class="who">${esc(e.name || 'Unknown')}</span><span class="ts">${esc(fmtTs(e.ts))}</span></div>`
298
+ const w = whoOf(e)
299
+ let html = `<div>${w.lane ? '<span class="ts">↩ from the shared room · </span>' : ''}<span class="who">${esc(w.name)}</span>${w.user ? `<span class="ts">@${esc(w.user)}</span>` : ''}<span class="ts">${esc(fmtTs(e.ts))}</span></div>`
249
300
  if (e.text) html += `<div class="body">${esc(e.text)}</div>`
250
301
  row.innerHTML = html
251
- for (const im of (Array.isArray(e.images) ? e.images : [])) { if (im && im.b64 && im.mime) { const img = document.createElement('img'); img.src = `data:${im.mime};base64,${im.b64}`; img.alt = im.name || 'image'; row.appendChild(img) } }
252
- for (const f of (Array.isArray(e.files) ? e.files : [])) { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '📎 ' + ((f && f.name) || 'file'); row.appendChild(c) }
302
+ for (const im of (Array.isArray(e.images) ? e.images : [])) {
303
+ if (im && im.b64 && im.mime) { const img = document.createElement('img'); img.src = `data:${im.mime};base64,${im.b64}`; img.alt = im.name || 'image'; row.appendChild(img) }
304
+ else if (im && im[NOT_IN_COPY]) { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '🖼 ' + (im.name || im.alt || 'photo') + ' — not in this copy'; row.appendChild(c) }
305
+ }
306
+ for (const f of (Array.isArray(e.files) ? e.files : [])) {
307
+ const name = (f && f.name) || 'file'
308
+ if (f && typeof f.b64 === 'string' && f.b64) { // a document with its bytes: a download link under its own name
309
+ const a = document.createElement('a'); a.className = 'chip'; a.download = name; a.href = `data:${f.mime || 'application/octet-stream'};base64,${f.b64}`; a.textContent = '📎 ' + name; row.appendChild(a)
310
+ } else { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '📎 ' + name + (f && f[NOT_IN_COPY] ? ' — not in this copy' : ''); row.appendChild(c) }
311
+ }
253
312
  for (const w of (Array.isArray(e.widgets) ? e.widgets : [])) { const c = document.createElement('span'); c.className = 'chip'; c.textContent = '▦ ' + ((w && (w.title || w.kind)) || 'widget'); row.appendChild(c) }
254
313
  t.appendChild(row)
255
314
  }
@@ -347,13 +406,14 @@
347
406
  for (const key of keys) {
348
407
  try {
349
408
  const rooms = [...(idx >= 0 && bundleRooms[idx] ? [bundleRooms[idx]] : []), ...roomsForKey(key)]
350
- const { entries, opened, total, v3, needsRoom: nr } = await decryptLedger(target, key, rooms, keys.filter(k => roomsForKey(k).some(r => rooms.includes(r)) || !roomsForKey(k).length))
409
+ const { entries: sealedEntries, opened, total, v3, needsRoom: nr, keys: opener } = await decryptLedger(target, key, rooms, keys.filter(k => roomsForKey(k).some(r => rooms.includes(r)) || !roomsForKey(k).length))
351
410
  if (nr) needsRoom = true
352
- if (entries != null && (!v3 || opened === total)) { render(entries, title); return status(`Read ${entries.length} message${entries.length === 1 ? '' : 's'}.`) }
411
+ const entries = sealedEntries ? await openAttachments(sealedEntries, target.blobs, opener) : sealedEntries
412
+ if (entries != null && (!v3 || opened === total)) { render(entries, title); return status(`Read ${entries.length} message${entries.length === 1 ? '' : 's'}.` + notInCopyNote(entries)) }
353
413
  if (opened && (!best || opened > best.opened)) best = { entries, opened, total }
354
414
  } catch (e) { /* try the next key */ }
355
415
  }
356
- if (best) { render(best.entries, title); return status(`Read ${best.opened} of ${best.total} messages (${best.total - best.opened} could not be opened).`) }
416
+ if (best) { render(best.entries, title); return status(`Read ${best.opened} of ${best.total} messages (${best.total - best.opened} could not be opened).` + notInCopyNote(best.entries)) }
357
417
  if (needsRoom) return status('This conversation is tied to its Space. Load the keys file from the same backup, or paste the Space’s link beside the key, then try again.', true)
358
418
  status(keys.length > 1 ? 'Couldn’t decrypt — none of the keys provided match this conversation.' : 'Couldn’t decrypt — the key doesn’t match this conversation (or it isn’t a Witbitz ledger).', true)
359
419
  })
@@ -377,7 +437,7 @@
377
437
  const body = $('transcript').innerHTML
378
438
  download(safeName(lastTitle) + '.html', `<!doctype html><meta charset=utf-8><title>${esc(lastTitle)}</title><style>body{font:15px/1.5 -apple-system,system-ui,sans-serif;max-width:760px;margin:24px auto;padding:0 16px}.msg{padding:10px 0;border-top:1px solid #eee}.who{font-weight:650}.ts{color:#888;font-size:11.5px;margin-left:8px}.body{white-space:pre-wrap;margin-top:3px}img{max-width:100%;border-radius:10px;margin-top:8px;display:block}.chip{display:inline-block;margin:6px 6px 0 0;padding:3px 9px;border-radius:7px;background:#f0f0ec;color:#666;font-size:12px}</style><h2>${esc(lastTitle)}</h2>${body}`, 'text/html;charset=utf-8')
379
439
  })
380
- $('saveSelf').addEventListener('click', () => download('witbitz-offline-decryptor.html', '<!doctype html>\n' + document.documentElement.outerHTML, 'text/html;charset=utf-8'))
440
+ $('saveSelf').addEventListener('click', () => download('witbitz-offline-decryptor.html', PRISTINE, 'text/html;charset=utf-8'))
381
441
  })();
382
442
  </script>
383
443
  </body>
package/eraseFile.js CHANGED
@@ -56,3 +56,18 @@ export async function fileEraseList ({ tenant, account, rooms, post, auth = {},
56
56
  try { ls.setItem(FILED, JSON.stringify({ fp, at: now })) } catch { /* */ }
57
57
  return { filed: true, rooms: rec.items.length }
58
58
  }
59
+
60
+ /** One filing at a time (side sweep: tenant-erase-withdrawal-joins-ordinary-filing). `run(opts)` files; the returned function
61
+ * answers an ORDINARY call (no `items`) with the filing already in flight, but a call that brings its OWN list (Delete my
62
+ * account's withdrawal: `items: []`) waits for that one to end and then files its own — it never takes another filing's
63
+ * `filed: true` as its own, and its list is the one the Sentinel keeps. */
64
+ export function serialFiler (run) {
65
+ let current = null
66
+ return function file (opts = {}) {
67
+ if (current && !opts.items) return current
68
+ const prior = current
69
+ const p = (async () => { if (prior) await prior.catch(() => {}); return run(opts) })().finally(() => { if (current === p) current = null })
70
+ current = p
71
+ return p
72
+ }
73
+ }
package/idbSeal.js CHANGED
@@ -31,7 +31,7 @@ export const idbNamingState = () => naming
31
31
  /** Key worker: the device key's raw bytes → this realm's naming (null = locked; off = unprotected). */
32
32
  export async function armIdbNaming (rawKey) { setIdbNaming({ on: true, key: await importRaw(rawKey), namer: await makeNamer(rawKey) }) }
33
33
 
34
- export const IDB_PROTECTED_PREFIXES = Object.freeze(['chat:', 'wstate:', 'blob:', 'code:', 'vchat:', 'vblob:', 'vblobidx', 'hidx:', 'zoom:', 'mailpend:']) // vchat: = the vault's durable seed of the framed app's chat (slice 4); hidx: = Help search's full-history copy (helpIndex.js); mailpend: = a mail's attachment parts waiting for their mail (mailShare.js)
34
+ export const IDB_PROTECTED_PREFIXES = Object.freeze(['chat:', 'wstate:', 'blob:', 'code:', 'vchat:', 'vblob:', 'vblobidx', 'hidx:', 'zoom:', 'outbox:', 'mailpend:']) // outbox: = a message held for a busy room, with its photos (roomOutbox.js); vchat: = the vault's durable seed of the framed app's chat (slice 4); hidx: = Help search's full-history copy (helpIndex.js); mailpend: = a mail's attachment parts waiting for their mail (mailShare.js)
35
35
  export const isProtectedIdbKey = (k) => { const s = String(k); return IDB_PROTECTED_PREFIXES.some((p) => s.startsWith(p)) }
36
36
 
37
37
  const st = { active: false, key: null }
@@ -74,6 +74,9 @@ export async function moveToOpaqueNames (idb) {
74
74
  if (isProtectedIdbKey(k) && isSealed(v)) { try { v = await openIf(st.key || key, v) } catch { continue } }
75
75
  const o = await namer.opaque(k)
76
76
  if ((await idb.getRaw(o)) == null) await idb.setRaw(o, await seal(key, v))
77
+ // the store may refuse the write and say nothing (a swallowed error, a `false`): the original goes only once its sealed copy
78
+ // is really there — else a later pass moves it (side sweep: device-storage-migration-drops-unsaved-copy)
79
+ if ((await idb.getRaw(o)) == null) continue
77
80
  await idb.delRaw(k); n++
78
81
  }
79
82
  return n
@@ -87,7 +90,7 @@ export async function migrateIdbProtection (idb, rawKey) {
87
90
  /** Switch off: open every sealed protected entry and write it back in the clear, one at a time; then pass-through. */
88
91
  export async function unprotectIdb (idb, rawKey) {
89
92
  const key = await importRaw(rawKey), namer = await makeNamer(rawKey)
90
- for (const o of await idb.keysRaw('p:')) { const name = await namer.real(o); const v = await idb.getRaw(o); if (name != null && v != null) { try { await idb.setRaw(name, await open(key, v)) } catch { /* junk */ } } await idb.delRaw(o) } // back under real names (the key worker opens its own keys after)
93
+ for (const o of await idb.keysRaw('p:')) { const name = await namer.real(o); const v = await idb.getRaw(o); if (name != null && v != null) { let back; try { back = await open(key, v) } catch { back = undefined /* junk: dropped */ } if (back !== undefined) { await idb.setRaw(name, back); if ((await idb.getRaw(name)) == null) continue /* not written: the sealed copy stays (side sweep) */ } } await idb.delRaw(o) } // back under real names (the key worker opens its own keys after)
91
94
  for (const k of await protectedKeys(idb)) { const v = await idb.getRaw(k); if (isSealed(v)) { try { await idb.setRaw(k, await openIf(key, v)) } catch { await idb.delRaw(k) } } } // an entry the key cannot open is junk: drop it
92
95
  try { await idb.delRaw('protectedNames') } catch { /* */ }
93
96
  setIdbProtection({ active: false, key: null })
@@ -0,0 +1,44 @@
1
+ // Tier-2 email invite — RECEIVE (docs/spaces-email-invite.md). Poll YOUR inbox, open each sealed box with your boxPriv,
2
+ // and hand the recovered { room, mk, title, from } to onInvite (which adds it to your Space list when it's new). The
3
+ // inbox is append-only, so this re-reads every box each poll — onInvite MUST be idempotent (no-op a room you already
4
+ // have or have deleted; recents + tombstones are the dedup). onInvite returns truthy when it actually added a room.
5
+ import { openBox } from './e2ee.js'
6
+
7
+ export async function checkInbox({ client, inviteKey, onInvite }) {
8
+ if (!client || !inviteKey || !inviteKey.inbox || !inviteKey.boxPriv || typeof onInvite !== 'function') return 0
9
+ const r = await client.inboxFetch(inviteKey.inbox, 0)
10
+ if (!r || r.status !== 200 || !Array.isArray(r.boxes)) return -1 // NOT READ (offline, refused): -1, so a caller can tell it from "nothing new" (emailInvites.js pollInbox's first pass)
11
+ let added = 0
12
+ for (const box of r.boxes) {
13
+ let plain = null
14
+ try { plain = await openBox(box, inviteKey.boxPriv) } catch { continue } // not sealed to us / corrupt → skip
15
+ if (!plain) continue
16
+ let inv = null
17
+ try { inv = JSON.parse(plain) } catch { continue }
18
+ if (!inv || !inv.room || (!inv.mk && !inv.link && !inv.us)) continue // a SPLIT invite carries the key in `link` (#us=), not `mk` — onInvite reverse-parses it; an ATTESTED split invite carries `us` itself (2026-11-24: skipped here, never reached onInvite)
19
+ try { if (await onInvite(inv)) added++ } catch { /* one bad invite must not stop the rest */ }
20
+ }
21
+ return added
22
+ }
23
+
24
+ // ⛔ STATE MACHINES PASS 8, A#1: the identity a device gives up when it adopts the account's (roomSync.js convergence) stays
25
+ // RETIRED for a week, inside the invite key itself (sealed, backed up, synced), and its inbox is read beside the current one —
26
+ // until the directory names the new inbox, invites still arrive at the old one.
27
+ export const RETIRED_MS = 7 * 24 * 3600 * 1000
28
+ const RETIRED_MAX = 3
29
+ /** The invite identities still to be read besides the current one. */
30
+ export const liveRetired = (id, now = Date.now()) => (Array.isArray(id && id.retired) ? id.retired : [])
31
+ .filter((r) => r && typeof r.inbox === 'string' && r.boxPriv && Number(r.until) > now && r.inbox !== (id && id.inbox))
32
+ /** `next` (the account's identity), with `local` (this device's, being replaced) and what it had retired kept as retired. */
33
+ export function retireInto (local, next, now = Date.now()) {
34
+ const was = local && local.inbox && local.boxPriv && local.inbox !== next.inbox ? [{ inbox: local.inbox, boxPriv: local.boxPriv, boxPub: local.boxPub, until: now + RETIRED_MS }] : []
35
+ const seen = new Set([next.inbox])
36
+ const retired = [...was, ...liveRetired(local, now), ...liveRetired(next, now)].filter((r) => !seen.has(r.inbox) && seen.add(r.inbox)).slice(0, RETIRED_MAX)
37
+ const { retired: _drop, ...rest } = next
38
+ return retired.length ? { ...rest, retired } : rest
39
+ }
40
+
41
+ /** Sent within the last day — only such an invite is announced ("X invited you to …"); an older one, or one with no time (an
42
+ * old sender), is added to the menu quietly (emailInvites.onSpaceInvite; the owner, 2026-11-10: "It is an old invite"). */
43
+ export const ANNOUNCE_MS = 24 * 3600 * 1000
44
+ export const inviteIsFresh = (at, now = Date.now()) => { const t = Number(at) || 0; return t > 0 && now - t >= -60_000 && now - t < ANNOUNCE_MS }