@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/sdkAgui.js CHANGED
@@ -23,11 +23,12 @@ const contextText = (ctx) => (Array.isArray(ctx) && ctx.length ? 'Context from t
23
23
  * Run one AG-UI run against a Space. → an async iterator of AG-UI 1.0 events, ending with RUN_FINISHED or RUN_ERROR.
24
24
  * @param space a Space (or Lane) from the SDK
25
25
  * @param input an AG-UI RunAgentInput ({ threadId, runId, messages, context?, resume? })
26
- * @param opts { from, mode = 'always', timeoutMs = TURN_TIMEOUT_MS (~16 min, as space.turn()), graceMs = 1500, signal }
26
+ * @param opts { from, mode = 'always', timeoutMs = TURN_TIMEOUT_MS (~16 min, as space.turn()), graceMs = 1500, pendingWaitMs = 15000 (how long the waiting-approvals read may take after the reply; past it the run ends
27
+ * in RUN_ERROR 'pending_unread', never success), signal }
27
28
  */
28
29
  import { isLaneCopy } from './roomName.js'
29
30
  import { TURN_TIMEOUT_MS } from './sdkTurn.js' // the same wait as space.turn() and the app (~16 min) // the one test for a lane's copy of its shared room's line
30
- export function aguiRun(space, input, { from, mode = 'always', timeoutMs = TURN_TIMEOUT_MS, graceMs = 1500, signal } = {}) {
31
+ export function aguiRun(space, input, { from, mode = 'always', timeoutMs = TURN_TIMEOUT_MS, graceMs = 1500, pendingWaitMs = 15_000, signal } = {}) {
31
32
  const queue = [], waiters = []
32
33
  let done = false
33
34
  const push = (e) => { if (done) return; const ev = { ...e, timestamp: now() }; const w = waiters.shift(); if (w) w({ value: ev, done: false }); else queue.push(ev) }
@@ -37,13 +38,28 @@ export function aguiRun(space, input, { from, mode = 'always', timeoutMs = TURN_
37
38
  const listen = (ev, cb) => { space.on(ev, cb); subs.push([ev, cb]) }
38
39
  const unlisten = () => { for (const [ev, cb] of subs.splice(0)) { try { space.off(ev, cb) } catch { /* an older Space without off() */ } } }
39
40
  let timer = null
40
- const finish = (e) => { if (done) return; clearTimeout(timer); unlisten(); push(e); end() }
41
+ // CLOSING THE SPACE ENDS THE RUN (side sweep: agui-run-waits-after-room-close): space.close() settles the handles in its
42
+ // `_turns` set, but this adapter sends with space.send(), so it waited out its own ~16-minute timeout. It joins that set.
43
+ const closeWatch = { _settle: () => fail('the Space was closed before its reply', 'closed') }
44
+ try { if (space && typeof space === 'object' && !space._stopped) (space._turns ||= new Set()).add(closeWatch) } catch { /* a Space without the set */ }
45
+ const finish = (e) => { if (done) return; clearTimeout(timer); unlisten(); try { space._turns?.delete(closeWatch) } catch { /* */ } push(e); end() }
41
46
  const fail = (message, code) => finish({ type: 'RUN_ERROR', message, code })
42
47
 
43
48
  ;(async () => {
44
49
  push({ type: 'RUN_STARTED', threadId, runId })
45
50
  if (signal) { if (signal.aborted) return finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'cancelled' } }); signal.addEventListener('abort', () => finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'cancelled' } }), { once: true }) }
46
51
 
52
+ // 0. THE ROOM'S HISTORY FIRST (side sweep: agui-example-starts-before-room-history): a Space just opened may still be reading
53
+ // it, and an assistant message that read delivers would be taken below as this run's answer. Wait for `ready` (bounded by
54
+ // the run's own timeout); a Space that cannot open its history ends the run, nothing sent.
55
+ if (space && space.ready && typeof space.ready.then === 'function') {
56
+ let cap = null
57
+ const why = await Promise.race([Promise.resolve(space.ready).then(() => null, (e) => e || new Error('cannot_open')), new Promise((r) => { cap = setTimeout(() => r(Object.assign(new Error('the room\'s history was not read in time'), { code: 'timeout' })), timeoutMs) })])
58
+ clearTimeout(cap)
59
+ if (done) return
60
+ if (why) return fail(`the room could not be opened: ${(why && why.message) || why}`, (why && why.code) || 'cannot_open')
61
+ }
62
+
47
63
  // 1. Resume: the person answered an interrupt — approve or deny the proposal in the room.
48
64
  const resume = Array.isArray(input.resume) ? input.resume : []
49
65
  for (const r of resume) {
@@ -53,6 +69,8 @@ export function aguiRun(space, input, { from, mode = 'always', timeoutMs = TURN_
53
69
  else { await space.deny(id); push({ type: 'TOOL_CALL_RESULT', messageId: 'wb-res-' + id, toolCallId: id, role: 'tool', content: JSON.stringify({ approved: false }) }) }
54
70
  } catch (e) { return fail(`the room refused ${r.status === 'resolved' ? 'the approval' : 'the denial'}: ${(e && e.message) || e}`, (e && e.code) || 'refused') }
55
71
  }
72
+ // cancelled (unsubscribed, aborted) while a decision was in flight: no listeners put back, nothing sent (side sweep: agui-unsubscribed-resume-reinstalls-listeners)
73
+ if (done) return
56
74
 
57
75
  // 2. The new user message, if there is one this Space has not been sent yet.
58
76
  const msgs = Array.isArray(input.messages) ? input.messages : []
@@ -77,10 +95,17 @@ export function aguiRun(space, input, { from, mode = 'always', timeoutMs = TURN_
77
95
  start()
78
96
  content(final.startsWith(streamed) ? final.slice(streamed.length) : streamed ? '' : final)
79
97
  push({ type: 'TEXT_MESSAGE_END', messageId: mid })
80
- try { if (typeof space._pollPending === 'function') space._pollPending() } catch { /* the proposals poll still runs */ } // ask NOW: a card made during the turn sits on its own channel
98
+ // ask NOW: a card made during the turn sits on its own channel — and WAIT for the answer (side sweep 2026-11-28: a read slower than
99
+ // the grace ended the run as success, and the UI never saw the approval). A read already out is waited for, then one more.
100
+ let asked = Promise.resolve()
101
+ try { if (typeof space._pollPending === 'function') asked = Promise.resolve(space._inflightPending || null).then(() => space._pollPending()).catch(() => {}) } catch { /* the proposals poll still runs */ }
102
+ let cap = null, read = false
103
+ const answered = Promise.race([asked.then(() => { read = true }), new Promise((r) => { cap = setTimeout(r, pendingWaitMs) })]).then(() => clearTimeout(cap)) // a read that hangs does not hold the run for ever
81
104
  // A proposal made during the turn can reach the device just after the reply (its own channel): wait a beat for it.
82
- setTimeout(() => {
105
+ const decide = () => {
83
106
  if (done) return
107
+ // the read still out at the cap: the list is UNKNOWN, not empty — never "success" on it (side sweep: agui-late-approval-reported-as-success)
108
+ if (!proposals.length && !read) return fail('the reply came, but whether it waits for an approval could not be read — look at the Space', 'pending_unread')
84
109
  if (!proposals.length) return finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'success' } })
85
110
  for (const p of proposals) {
86
111
  push({ type: 'TOOL_CALL_START', toolCallId: p.id, toolCallName: p.action || 'proposal', parentMessageId: mid })
@@ -88,7 +113,9 @@ export function aguiRun(space, input, { from, mode = 'always', timeoutMs = TURN_
88
113
  push({ type: 'TOOL_CALL_END', toolCallId: p.id })
89
114
  }
90
115
  finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'interrupt', interrupts: proposals.map((p) => ({ id: p.id, reason: 'approval_required', toolCallId: p.id, ...(p.text ? { message: String(p.text) } : {}) })) } })
91
- }, proposals.length ? 0 : graceMs)
116
+ }
117
+ if (proposals.length) setTimeout(decide, 0)
118
+ else Promise.all([answered, new Promise((r) => setTimeout(r, graceMs))]).then(decide)
92
119
  })
93
120
  timer = setTimeout(() => fail(`no reply from the room within ${Math.round(timeoutMs / 1000)} s`, 'timeout'), timeoutMs)
94
121
  sent.add(fresh.id)
package/sdkBackup.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { associationTime } from './laneAssociation.js'
1
2
  // spaces/public/sdkBackup.js — `wb.backup`: the ACCOUNT BACKUP for a builder's app, on the SAME vault our own app uses
2
3
  // (2026-10-02, a builder: "a short recovery code instead of the restore link"; the owner: "why not use our account
3
4
  // structure?"). Nothing new is invented here — it is the existing vault, reached from the SDK:
@@ -27,6 +28,7 @@ import { newMasterSecret, backupLocation, wrapperLocation, enrollCredential, ope
27
28
  export const DEFAULT_VAULT_API = 'https://api.witbitz.chat/v1/vault'
28
29
  const KIND = LEGACY_SDK_KIND
29
30
  const MAX_ROOMS = 500
31
+ const OPENED_AT_EVERY_MS = 3600_000 // a reopened room's time moves at most once an hour (add; as the account index — accountIndexDoc.js)
30
32
 
31
33
  const b64 = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s) }
32
34
  const ub64 = (s) => { const b = atob(s); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
@@ -70,7 +72,7 @@ const notOnService = () => fail('not_on_service', 'this call is for an account o
70
72
 
71
73
  /** One room as the backup records it. `link` carries the room key (the fragment), so the whole list is sealed. */
72
74
  const roomOf = (r) => (r && typeof r === 'object' && typeof r.room === 'string' && r.room && typeof r.link === 'string' && r.link
73
- ? { room: r.room.slice(0, 120), ...roomPin(r), ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), ...(Number.isFinite(r.at) && r.at > 0 ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), link: r.link.slice(0, 4000), kind: r.kind === 'lane' ? 'lane' : 'space', ...(r.label ? { label: String(r.label).slice(0, 120) } : {}), ...(r.kind === 'lane' && r.shared ? { shared: String(r.shared).slice(0, 120) } : {}), ...(typeof r.mk === 'string' && r.mk && r.mk.length <= 200 ? { mk: r.mk } : {}) }
75
+ ? { room: r.room.slice(0, 120), ...roomPin(r), ...(typeof r.mintedFor === 'string' && r.mintedFor ? { mintedFor: r.mintedFor } : r.laneOrigin === 'minted' && r.shared ? { mintedFor: r.shared } : {}), ...(r.laneOrigin === 'minted' && !r.detachedLane ? { laneOrigin: 'minted' } : {}), ...(Number(r.associationAt) > 0 ? { associationAt: Number(r.associationAt) } : {}), ...(typeof r.renamed === 'boolean' ? { renamed: r.renamed } : {}), ...(Number.isFinite(r.at) && r.at > 0 ? { at: r.at } : {}), ...(r.archived ? { archived: true } : {}), ...(Number.isFinite(r.labelAt) && r.labelAt > 0 ? { labelAt: r.labelAt } : {}), ...(Number.isFinite(r.archivedAt) && r.archivedAt > 0 ? { archivedAt: r.archivedAt } : {}), ...(r.detachedLane ? { detachedLane: true } : {}), link: r.link.slice(0, 4000), kind: !r.detachedLane && r.kind === 'lane' ? 'lane' : 'space', ...(r.label ? { label: String(r.label).slice(0, 120) } : {}), ...(!r.detachedLane && r.kind === 'lane' && r.shared ? { shared: String(r.shared).slice(0, 120) } : {}), ...(typeof r.mk === 'string' && r.mk && r.mk.length <= 200 ? { mk: r.mk } : {}) }
74
76
  : null)
75
77
 
76
78
  function stateOf(x) {
@@ -83,7 +85,9 @@ function stateOf(x) {
83
85
  const links = (Array.isArray(o.links) ? o.links : []).filter((l) => l && typeof l.a === 'string' && typeof l.b === 'string' && Number.isFinite(l.at)).map((l) => ({ a: l.a.slice(0, 120), b: l.b.slice(0, 120), at: l.at, ...(Number.isFinite(l.cap) ? { cap: l.cap } : {}), ...(l.removed ? { removed: true } : {}) })).slice(-200)
84
86
  // `outs`: sign-outs of OTHER devices this device made, kept until the index carries them (sdkAccount.js signOut; pass 6, K#7)
85
87
  const outs = o.outs && typeof o.outs === 'object' ? Object.fromEntries(Object.entries(o.outs).filter(([id, at]) => typeof id === 'string' && id.length <= 40 && Number.isFinite(at)).slice(-50)) : {}
86
- return { v: 1, ...(o.format === 'account' ? { format: 'account' } : {}), ...(Object.keys(outs).length ? { outs } : {}), master: o.master, ...(typeof o.savedVersion === 'string' && o.savedVersion.length <= 200 ? { savedVersion: o.savedVersion } : {}), rooms: (Array.isArray(o.rooms) ? o.rooms : []).map(roomOf).filter(Boolean).slice(0, MAX_ROOMS), ...(tomb.length ? { tomb } : {}), ...(links.length ? { links } : {}), ...(device ? { device } : {}), ...(o.email ? { email: String(o.email) } : {}), ...(inviteOf(o.invite) ? { invite: inviteOf(o.invite) } : {}), ...(normUsageKey(o.usage) ? { usage: normUsageKey(o.usage) } : {}), ...(usageOldOf(o.usageOld).length ? { usageOld: usageOldOf(o.usageOld) } : {}), ...(o.erased ? { erased: true } : {}), ...(v2Of(o.v2) ? { v2: v2Of(o.v2) } : {}) }
88
+ // `indexGoneAt`: the first 410 on the account's index (indexGone.js) — kept, or each short visit restarted the minute (side sweep:
89
+ // sdk-deleted-account-check-restarts-on-reopen)
90
+ return { v: 1, ...(Number.isSafeInteger(o.chatLockMarkPending) && o.chatLockMarkPending > 0 ? { chatLockMarkPending: o.chatLockMarkPending } : {}), ...(Number.isSafeInteger(o.indexGoneAt) && o.indexGoneAt > 0 ? { indexGoneAt: o.indexGoneAt } : {}), ...(o.savePending ? { savePending: 1 } : {}),...(o.format === 'account' ? { format: 'account' } : {}), ...(Object.keys(outs).length ? { outs } : {}), master: o.master, ...(typeof o.savedVersion === 'string' && o.savedVersion.length <= 200 ? { savedVersion: o.savedVersion } : {}), rooms: (Array.isArray(o.rooms) ? o.rooms : []).map(roomOf).filter(Boolean).slice(0, MAX_ROOMS), ...(tomb.length ? { tomb } : {}), ...(links.length ? { links } : {}), ...(device ? { device } : {}), ...(o.email ? { email: String(o.email) } : {}), ...(inviteOf(o.invite) ? { invite: inviteOf(o.invite) } : {}), ...(normUsageKey(o.usage) ? { usage: normUsageKey(o.usage) } : {}), ...(usageOldOf(o.usageOld).length ? { usageOld: usageOldOf(o.usageOld) } : {}), ...(o.erased ? { erased: true } : {}), ...(v2Of(o.v2) ? { v2: v2Of(o.v2) } : {}) }
87
91
  }
88
92
  // the account's USAGE key (usageReceipts.js; the owner, 2026-10-23: a builder's app records the account's usage too) and the
89
93
  // ones it replaced — kept in step between the devices by the live index (sdkAccount.js)
@@ -115,8 +119,10 @@ export class AccountBackup {
115
119
  * meanwhile is queued in it) but is handed to nobody — not the app (onState), not the live index — until the vault copy,
116
120
  * the recovery code and the gate are all saved. A failed enable then leaves nothing behind that reads "enabled". */
117
121
  _isEnabling() { return !!this._enabling && this._enabling === this._s }
118
- /** The rooms the backup holds: [{ room, link, kind: 'space'|'lane', label?, shared?, archived? }]. */
119
- get rooms() { return this._s ? this._s.rooms.map(({ at, ...r }) => r) : [] } // `at` is the live index's bookkeeping
122
+ /** The rooms the backup holds: [{ room, link, kind: 'space'|'lane', label?, shared?, archived?, pinned?, lastOpenedAt? }]. */
123
+ // `at` is the live index's bookkeeping (the newer of each entry wins); it reaches the app READ-ONLY as `lastOpenedAt` — when the room
124
+ // was last opened or recorded on any of the account's devices, at most an hour behind (side sweep: sdk-account-room-list-omits-recency)
125
+ get rooms() { return this._s ? this._s.rooms.map(({ at, ...r }) => (Number.isFinite(at) && at > 0 ? { ...r, lastOpenedAt: at } : r)) : [] }
120
126
 
121
127
  /** Set up the backup → `{ code }`. Show the code ONCE: it is the only way back if this device is lost. With an email
122
128
  * (default: the signed-in session's), the recovery gate is enrolled too, so a restore can also be made to need it. */
@@ -174,24 +180,50 @@ export class AccountBackup {
174
180
  // a lane opened as a plain Space (wb.openSpace(laneLink)) knows nothing of its Space: the record it already has as a LANE
175
181
  // stays one — a restore must not bring it back as a Space (sync sweep 2026-11-02 #5)
176
182
  const had = this._s.rooms.find((x) => x.room === spaceOrLane.room)
177
- const wasLane = !lane && had && had.kind === 'lane' && had.shared
178
- const r = roomOf({ room: spaceOrLane.room, link: spaceOrLane.shareLink, kind: lane || wasLane ? 'lane' : 'space', label, shared: lane ? spaceOrLane._sharedRoom : wasLane ? had.shared : undefined, mk: spaceOrLane._split ? spaceOrLane._mk : undefined })
183
+ if (lane && (had?.detachedLane || (had?.shared && had.shared !== spaceOrLane._sharedRoom))) return this
184
+ const wasLane = !lane && !spaceOrLane._detachedLane && had && had.kind === 'lane' && had.shared
185
+ const r = roomOf({ room: spaceOrLane.room, link: spaceOrLane.shareLink, mintedFor: had?.mintedFor || spaceOrLane._mintedFor, laneOrigin: spaceOrLane._laneOrigin || had?.laneOrigin, associationAt: spaceOrLane._associationAt || had?.associationAt, kind: lane || wasLane ? 'lane' : 'space', detachedLane: spaceOrLane._detachedLane || had?.detachedLane, label, shared: lane ? spaceOrLane._sharedRoom : wasLane ? had.shared : undefined, mk: spaceOrLane._split ? spaceOrLane._mk : undefined })
179
186
  if (!r) return this
180
187
  const i = this._s.rooms.findIndex((x) => x.room === r.room)
181
188
  const prev = i >= 0 ? this._s.rooms[i] : null
182
- if (prev && prev.link === r.link && prev.kind === r.kind && prev.mk === r.mk && (!label || prev.label === r.label)) return this
189
+ if (prev && prev.link === r.link && prev.kind === r.kind && prev.shared === r.shared && prev.laneOrigin === r.laneOrigin && prev.associationAt === r.associationAt && !!prev.detachedLane === !!r.detachedLane && prev.mk === r.mk && (!label || prev.label === r.label)) {
190
+ // REOPENED, UNCHANGED: its time (`lastOpenedAt`) moves at most once an hour — not a vault and index write per open (side sweep:
191
+ // sdk-account-room-list-omits-recency; it returned before stamping, so the time stayed at the room's first record)
192
+ if (Date.now() - (Number(prev.at) || 0) < OPENED_AT_EVERY_MS) return this
193
+ this._s.rooms[i] = { ...prev, at: Date.now() }
194
+ this._schedule()
195
+ return this
196
+ }
183
197
  const next = { ...(prev ? { ...prev, ...r, ...(label ? {} : prev.label ? { label: prev.label } : {}), ...(prev.archived ? { archived: true } : {}) } : r), at: Date.now() } // `at`: the live index keeps the newer of each entry
198
+ if (next.detachedLane) { delete next.shared; delete next.laneOrigin }
184
199
  if (i >= 0) this._s.rooms[i] = next; else { if (this._s.rooms.length >= MAX_ROOMS) return this; this._s.rooms.push(next) }
185
200
  this._schedule()
186
201
  return this
187
202
  }
188
203
 
204
+ _attachLane(room, parent) {
205
+ const entry = this._s?.rooms.find(r => r.room === room)
206
+ if (!entry) throw Object.assign(new Error('Add the private room to the account first.'), { code: 'not_in_account' })
207
+ if (entry.shared && entry.shared !== parent) throw Object.assign(new Error('Unlink this room from its current Space first.'), { code: 'already_linked' })
208
+ if (entry.laneOrigin === 'minted' && entry.shared) entry.mintedFor ||= entry.shared
209
+ if (entry.mintedFor === parent) entry.laneOrigin = 'minted'
210
+ else delete entry.laneOrigin
211
+ entry.kind = 'lane'
212
+ entry.shared = parent
213
+ delete entry.detachedLane
214
+ entry.at = entry.associationAt = associationTime(entry)
215
+ this._schedule()
216
+ }
217
+
189
218
  _detachLane(room, shared) {
190
219
  const entry = this._s?.rooms.find((r) => r.room === room && r.kind === 'lane' && r.shared === shared)
191
220
  if (!entry) return
221
+ if (entry.laneOrigin === 'minted') entry.mintedFor ||= entry.shared
222
+ delete entry.laneOrigin
192
223
  delete entry.shared
193
224
  entry.kind = 'space'
194
- entry.at = Math.max(Date.now(), (entry.at || 0) + 1)
225
+ entry.detachedLane = true
226
+ entry.at = entry.associationAt = associationTime(entry)
195
227
  this._schedule()
196
228
  }
197
229
 
@@ -301,6 +333,11 @@ export class AccountBackup {
301
333
  * If the vault's gate requires the email, the first call mails a code and throws `code: 'email_code_required'` with
302
334
  * a `ticket`; call again with `{ code, ticket, emailCode }`. `email` defaults to the signed-in address. */
303
335
  async restore({ code, email, ticket, emailCode, getCode, askAddress } = {}) {
336
+ const epoch = this._restoreEpoch = (this._restoreEpoch || 0) + 1
337
+ const owner = this._restoreIdentity?.() ?? this._email(), original = this._s
338
+ const check = () => {
339
+ if (epoch !== this._restoreEpoch || original !== this._s || owner !== (this._restoreIdentity?.() ?? this._email())) throw fail('account_changed', 'The account changed during recovery.')
340
+ }
304
341
  if (this._s?.v2?.resetDraft) throw fail('email_move_pending', 'finish or cancel this device’s email move first')
305
342
  let cs
306
343
  try { cs = codeSecret(code) } catch { throw fail('bad_code', 'that is not a recovery code') }
@@ -308,6 +345,7 @@ export class AccountBackup {
308
345
  // there (or a service that could not say) goes on to the old store below. A ticket of the old store's gate goes straight there.
309
346
  if (this._v2 && !(ticket && emailCode)) {
310
347
  const d = await this._v2.restore(this, { code, email, getCode, askAddress })
348
+ check()
311
349
  if (d) { clearTimeout(this._timer); this._timer = null; this._s = stateOf(d); this._changed(); this._started(); return { rooms: this.rooms } }
312
350
  }
313
351
  const w = await wrapperLocation(cs)
@@ -341,6 +379,7 @@ export class AccountBackup {
341
379
  // is not in the account format: no plan, read as before.
342
380
  const plan = applyPlan(doc, {}, { app: SDK_APP })
343
381
  const invite = plan ? plan.inviteKey : doc.inviteKey
382
+ check()
344
383
  this._s = stateOf({ master: b64(master), savedVersion: b.json.ver, rooms: roomsOfRecord(plan ? { ...doc, recents: plan.add } : doc), tomb: tombOfRecord(doc), ...(doc.email ? { email: doc.email } : {}), ...(invite ? { invite } : {}), ...(doc.kind === KIND ? {} : { format: 'account' }) })
345
384
  this._changed(); this._started()
346
385
  return { rooms: this.rooms }
@@ -368,11 +407,14 @@ export class AccountBackup {
368
407
  // ── internals ──────────────────────────────────────────────────────────────────────────────────────────────────
369
408
  _schedule() { if (this._isEnabling()) { this._enablingDirty = true; return } this._persist(); if (typeof this._onLocal === 'function') { try { this._onLocal() } catch { /* the live index */ } } }
370
409
  /** Write the vault copy soon and hand the app the new state — without telling the live index (it is the caller). */
371
- _persist() { if (this._isEnabling()) { this._enablingDirty = true; return } if (this._s && this._s.erased) { this._changed(); return } clearTimeout(this._timer); this._timer = setTimeout(() => { this._timer = null; if (this._s) this._write().catch((e) => { this.lastError = e }) }, 400); this._changed() }
410
+ _persist() { if (this._isEnabling()) { this._enablingDirty = true; return } if (this._s && this._s.erased) { this._changed(); return } clearTimeout(this._timer); this._timer = setTimeout(() => { this._timer = null; const s0 = this._s; if (s0) this._write().then(() => { if (s0.savePending && this._s === s0) { delete s0.savePending; this._changed() } }).catch((e) => { this.lastError = e; if (this._s === s0 && !s0.erased && !s0.savePending) { s0.savePending = 1; this._changed() } }) }, 400); this._changed() }
411
+ /** @private a scheduled save that failed is OWED (`savePending`, kept in the state): the account's next sync tries it again — the merge
412
+ * alone may change nothing and so schedule nothing (side sweep: sdk-resume-misses-pending-backup-save). */
413
+ _retryOwedSave() { if (this._s && this._s.savePending && !this._timer && !this._isEnabling()) this._persist() }
372
414
  /** This device was signed out of the account (wb.account): forget it here, and tell the app to persist that. */
373
- _drop() { clearTimeout(this._timer); this._timer = null; this._s = null; this._changed() }
415
+ _drop() { this._restoreEpoch = (this._restoreEpoch || 0) + 1; clearTimeout(this._timer); this._timer = null; this._s = null; this._changed() }
374
416
  /** @private take another persisted state in place (a vault switching accounts keeps one backup per account) */
375
- _adopt(state) { clearTimeout(this._timer); this._timer = null; this._s = stateOf(state); this._changed() }
417
+ _adopt(state) { this._restoreEpoch = (this._restoreEpoch || 0) + 1; clearTimeout(this._timer); this._timer = null; this._s = stateOf(state); this._changed() }
376
418
  _started() { if (typeof this._onStart === 'function') { try { this._onStart() } catch { /* the live index */ } } }
377
419
  _changed() { if (this._isEnabling()) return; if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback must not break the backup */ } } }
378
420
  async _write(verification) {
package/sdkBackupV2.js CHANGED
@@ -299,7 +299,7 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
299
299
  const a = client(s, { changed })
300
300
  await save()
301
301
  const existing = a.pendingReset()
302
- if (existing) return moveDates(existing)
302
+ if (existing && existing.expires) return moveDates(existing) // one kept without its dates (its start's answer lost): resetBegin asks the service first (side sweep: email-move-start-reply-loses-pending-request)
303
303
  try {
304
304
  const pending = await a.resetBegin({ address, getCode: screen(getCode) })
305
305
  await save()
@@ -406,7 +406,13 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
406
406
  if (!(await persistNow(s))) throw fail('save_failed', 'the migration state could not be kept on this device')
407
407
  current()
408
408
  if (silent) await a.silentMove({ address })
409
- else await a.migrate({ address, typedCode: code, getCode: async () => { current(); const c = await getCode(); current(); return c } })
409
+ else {
410
+ try { await a.migrate({ address, typedCode: code, getCode: async () => { current(); const c = await getCode(); current(); return c } }) } catch (e) {
411
+ // a wrong or cancelled email code: nothing was committed — drop the move as legacyAborted does, or every later save stops
412
+ if ((e?.code === 'email_code_wrong' || e?.code === 'cancelled') && b._s === s) { delete s.v2; b._changed(); try { await persistNow(s) } catch { /* the error below is the one to tell */ } }
413
+ throw e
414
+ }
415
+ }
410
416
  current(); b._changed()
411
417
  if (!(await persistNow(s))) throw fail('save_failed', 'the migrated account state could not be kept')
412
418
  }
@@ -482,7 +488,12 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
482
488
  let typed
483
489
  try { codeSecret(code); typed = code } catch { throw fail('bad_code', 'that is not a recovery code') }
484
490
  if (typeof getCode !== 'function') return null // no screen for the emailed code (a page outside a vault): the old store only
485
- const s1 = { v: 1, format: 'account', master: '', rooms: [], v2: {} }
491
+ // ONE DRAFT PER VAULT PAGE, kept until a restore succeeds (side sweep: restore-finish-duplicate-device): each attempt made a fresh
492
+ // state — a fresh device key (`dk`) and no memory of the finish it had sent — so a retry after a lost finish reply registered a
493
+ // second active device. The draft keeps the attempt's key and its restoring mark (acctV2App RESTORING_KEY, held per state).
494
+ // Held in memory: a reload starts a new draft (its key is not kept), as before.
495
+ if (!b._restoreDraft || b._restoreDraft.v2.svc) b._restoreDraft = { v: 1, format: 'account', master: '', rooms: [], v2: {} }
496
+ const s1 = b._restoreDraft
486
497
  let found = false, done = null
487
498
  const address = async () => {
488
499
  found = true // the service knows this code
@@ -509,6 +520,7 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
509
520
  throw e
510
521
  }
511
522
  if (!done) throw fail('unopenable', 'the backup could not be opened')
523
+ b._restoreDraft = null // restored: the next restore is a new one
512
524
  return done
513
525
  },
514
526
 
package/sdkCloudDevice.js CHANGED
@@ -6,7 +6,13 @@ const current = (wb, session, state) => { if (wb._session !== session || wb.back
6
6
 
7
7
  /** A kept Space remains solo and has no private lane of its own, on every SDK/vault device. */
8
8
  export async function assertNotKept(space) {
9
- if (space._wb?.vault) return space._wb.vault._c.roomAccount(space.room, 'alwaysOn', 'assertNotKept')
9
+ // ⚑ A VAULT FROM BEFORE THIS CHECK (the 4.2.0 kit) answers `vault_refused` to the unknown call — a 4.3.0 page could then open
10
+ // no private lane and change no members against it (second review, 2026-11-27). No answer there = no check, as before 4.3.0;
11
+ // the cloud device drops a kept Space that gained people or lanes at its next tick either way (cloud-device/scope.mjs).
12
+ if (space._wb?.vault) {
13
+ try { return await space._wb.vault._c.roomAccount(space.room, 'alwaysOn', 'assertNotKept') }
14
+ catch (e) { if (e && e.code === 'vault_refused') return; throw e }
15
+ }
10
16
  if (await isKeptSpace(space)) throw fail('kept_space', 'stop keeping this Space always on before adding people or private lanes')
11
17
  }
12
18
 
@@ -16,14 +22,18 @@ export async function isKeptSpace(space) {
16
22
  if (!w?._session?.email || space._sharedRoom) return false
17
23
  if (!w.cloudDevice) throw fail('index_unavailable', 'the Space’s always-on status could not be checked')
18
24
  try { return (await w.cloudDevice.status()).rooms.some((r) => r.room === space.room) }
19
- catch (e) { if (['not_available', 'cloud_device_unavailable', 'not_enrolled', 'not_in_dev_server'].includes(e.code)) return false; throw e } // cloud_device_unavailable: this deployment runs no cloud device (agent/cloudDeviceRoute.mjs, 501), so nothing here is kept
25
+ catch (e) { if (['not_available', 'cloud_device_unavailable', 'not_enrolled', 'not_in_dev_server', 'sign_in_required'].includes(e.code)) return false; throw e } // sign_in_required: a lapsed sign-in cannot ask — and it blocked every lane and member change of an OPEN room, kept or not (second review, 2026-11-27); // cloud_device_unavailable: this deployment runs no cloud device (agent/cloudDeviceRoute.mjs, 501), so nothing here is kept
20
26
  }
21
- const session = w._session, state = w.backup._s, loc = await a._where()
27
+ return accountMark(w, space.room)
28
+ }
29
+ /** The account's saved always-on mark for `room` (the app's and the SDK's `xindex` row) — the mark assertNotKept refuses on. */
30
+ async function accountMark(w, room) {
31
+ const a = w.account, session = w._session, state = w.backup._s, loc = await a._where()
22
32
  current(w, session, state)
23
33
  const r = await a._read(loc, 'xindex', loc.app)
24
34
  current(w, session, state)
25
35
  if (!r.ok) throw fail('index_unavailable', 'the account’s always-on mark could not be read')
26
- return !!r.doc?.rooms?.[space.room]?.alwaysOn
36
+ return !!r.doc?.rooms?.[room]?.alwaysOn
27
37
  }
28
38
 
29
39
  export async function disconnectRoomLanes(w, room) {
@@ -145,6 +155,7 @@ async function markKept(w, room, on) {
145
155
  current(w, session, s)
146
156
  if (r && r.status === 409) continue
147
157
  if (!r || r.status !== 200) throw fail('save_failed', 'the cloud-device account mark could not be saved')
158
+ if (typeof a._noteKeptMarks === 'function') a._noteKeptMarks(next) // account.rooms shows the mark at once, not at the next sync
148
159
  return
149
160
  }
150
161
  throw fail('version_conflict', 'the account kept changing; check the cloud-device status and retry')
@@ -157,7 +168,11 @@ export class SpaceAlwaysOn {
157
168
  const w = this._client(), s = this._sp
158
169
  if (w.vault) return w.vault._c.roomAccount(s.room, 'alwaysOn', 'status')
159
170
  const h = await w.cloudDevice.status(), entry = h.rooms.find((r) => r.room === s.room)
160
- return { on: !!entry, registered: h.registered, ...(entry && entry.waiting ? { waiting: entry.waiting } : {}) }
171
+ // `marked`: the account's saved mark, beside what the device holds — on: false with marked: true is a Space the device let go
172
+ // while the account still keeps it (the guard still refuses private assistants for it); disable() takes the mark off. Unknown
173
+ // (no account index, or it could not be read) → left out (side sweep: sdk-always-on-status-omits-saved-choice)
174
+ let marked; if (w.account?.enabled && typeof w.account._read === 'function') { try { marked = await accountMark(w, s.room) } catch (e) { if (e && e.code === 'account_changed') throw e } }
175
+ return { on: !!entry, registered: h.registered, ...(entry && entry.waiting ? { waiting: entry.waiting } : {}), ...(typeof marked === 'boolean' ? { marked } : {}) }
161
176
  }
162
177
  async enable({ disconnectLanes = false } = {}) {
163
178
  const w = this._client(), s = this._sp