@witbitz/sdk 0.0.0-stage → 4.3.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
package/sdkErase.js ADDED
@@ -0,0 +1,283 @@
1
+ // sdkErase.js — `wb.erasure`: A BUILDER'S USERS' ROOMS CAN BE DELETED WHEN THE USER IS ERASED (https://witbitz.chat/docs/sdk-builder.md#user-erasure; a
2
+ // builder, 2026-10-07: "users.erase finds 0 rooms for a user of ours"). The tenant's erase (`wb.users.erase(email)` on its
3
+ // server → agent/eraseUser.mjs) runs ONLY the list the account FILED with the attested standing Sentinel, and deletes only
4
+ // a room whose create carried a deletion commitment and that nobody else marked. The Witbitz app does all three
5
+ // (roomDelete.js, accountUsage.js, eraseFile.js); the SDK did none. Now, for every room the SDK creates or opens:
6
+ // 1. a CREATE carries delCommit = sha256(HMAC(erase key, 'witbitz-room-delete:' + room)) — only this account can later
7
+ // prove it created the room (the server keeps the commitment, never the secret);
8
+ // 2. the room gets this account's MEMBERSHIP MARK (HMAC(erase key, 'witbitz-usage-drop:' + room)) — so another account's
9
+ // delete of a room this account used is refused (409 shared), and this account's own delete is not;
10
+ // 3. the account's list — per room, the delete secret and the drop — is FILED, sealed to the standing Sentinel, under
11
+ // the app's tenant and the signed-in email (eraseFile.js, unchanged). Automatic, a few seconds after a room is
12
+ // created or opened, and only when the list changed; `wb.erasure.file()` does it on demand.
13
+ // THE ERASE KEY comes from the BACKUP MASTER (wb.backup), which every device of the account restores: the Sentinel keeps one
14
+ // list per account and a filing REPLACES it, so every device must derive the same secrets. No backup → no shared secret →
15
+ // nothing is committed, marked or filed (a room created then can be deleted only by the tenant: wb.rooms.delete(room)).
16
+ // The mark works on rooms created before this, the commitment does not (it is set at create, never after).
17
+ import { delSecretFor, delCommitOf } from './roomDelete.js'
18
+ import { dropFor } from './usageReceipts.js'
19
+ import { fileEraseList } from './eraseFile.js'
20
+ import { attestStandingSentinel } from './connections.js'
21
+ import { sealTo as sealToEnclave } from './sealShare.js'
22
+ import { eraseAccount, stepDone, readAllEntries } from './accountErase.js' // the app's Delete my account — its order and rules, and its one rule for "done"
23
+ import { deleteOwnRoom, leaveAndMaybeDelete, leaveHandover, deleteHandedOver } from './roomDelete.js'
24
+ import { inviteScope } from './sdkRekey.js'
25
+
26
+ const enc = new TextEncoder()
27
+ const ub64 = (s) => { const b = atob(String(s).replace(/-/g, '+').replace(/_/g, '/')); const u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u }
28
+ const b64u = (u8) => { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
29
+ const TENANT = /^t_[0-9a-f]{32}$/ // the Sentinel's (erase.mjs)
30
+ const memStorage = () => { const m = new Map(); return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, v) => { m.set(k, String(v)) } } }
31
+
32
+ /** The erase key every device of the account derives from its backup master: { secret } (43-char base64url). */
33
+ export async function eraseKeyOf (masterB64) {
34
+ const km = await crypto.subtle.importKey('raw', ub64(masterB64), 'HKDF', false, ['deriveBits'])
35
+ const bits = await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: enc.encode('witbitz-sdk-account-v1'), info: enc.encode('erase-key') }, km, 256)
36
+ return { secret: b64u(new Uint8Array(bits)) }
37
+ }
38
+
39
+ export class Erasure {
40
+ /** @param {object} wb the Witbitz client */
41
+ constructor (wb) {
42
+ this._wb = wb
43
+ this._k = { master: null, key: null }
44
+ this._marked = new Set()
45
+ this._opened = [] // rooms this page created or opened, newest last
46
+ this._debounceMs = 4000
47
+ this._timer = null
48
+ this._deps = null // tests: { post, auth, attest, seal }
49
+ let ls = null; try { ls = globalThis.localStorage || null; if (ls) ls.getItem('witbitz:probe') } catch { ls = null }
50
+ this._ls = ls || memStorage() // where eraseFile.js remembers what it filed (skips an unchanged list for 6 h)
51
+ }
52
+
53
+ async _key () {
54
+ const st = this._wb.backup && this._wb.backup.state
55
+ const m = st && st.master
56
+ if (!m) return null
57
+ if (this._k.master !== m) this._k = { master: m, key: await eraseKeyOf(m) }
58
+ return this._k.key
59
+ }
60
+ /** @private the account's USAGE keys (wb.account): its turns' receipts carry drops made with them, so a delete and the
61
+ * filed list present those too — else the server reads this account's own receipts as another's (409 shared; sync sweep 11-08 #3) */
62
+ _dropKeys () { try { const a = this._wb.account; return a && typeof a._usageKeys === 'function' ? a._usageKeys() : [] } catch { return [] } }
63
+ _account () { const s = this._wb._session; return s && s.email && !(s.exp && s.exp <= Date.now()) ? String(s.email).toLowerCase() : '' }
64
+ _tenant () { return TENANT.test(this._wb._tenant || '') ? this._wb._tenant : '' }
65
+
66
+ /** True when this page can file: a tenant app, a live sign-in and a backup (the shared key). */
67
+ get available () { return !!(this._tenant() && this._account() && this._wb.backup && this._wb.backup.enabled) }
68
+
69
+ /** @private the create hook (spaceClient `delCommit`): the commitment for `room`, or null with no backup */
70
+ async _commitFor (room) { const k = await this._key(); return k ? delCommitOf(await delSecretFor(k, room)) : null }
71
+
72
+ /** @private every room the SDK hands back (Witbitz#_backedUp): mark it once per page, and refile soon. Never throws. */
73
+ _seen (sp) {
74
+ if (!sp || !sp.room) return
75
+ if (!this._opened.includes(sp.room)) this._opened.push(sp.room)
76
+ ;(async () => {
77
+ const k = await this._key()
78
+ if (!k || this._marked.has(sp.room) || !sp._mk) return
79
+ this._marked.add(sp.room)
80
+ // A refusal is ANSWERED, not thrown (mark is email-gated: a sign-in may be needed) — so it is let go too, and the room
81
+ // is marked again the next time it is handed back, as the app's accountUsage does (sync sweep, 2026-10-10).
82
+ try { const r = await this._wb._client.mark(sp.room, sp._mk, await dropFor(k, sp.room)); if (!r || r.status !== 200) this._marked.delete(sp.room) } catch { this._marked.delete(sp.room) }
83
+ })().catch(() => {})
84
+ if (this.available) {
85
+ clearTimeout(this._timer)
86
+ this._timer = setTimeout(() => { this.file().catch(() => {}) }, this._debounceMs)
87
+ if (this._timer && typeof this._timer.unref === 'function') this._timer.unref()
88
+ }
89
+ }
90
+
91
+ _rooms () {
92
+ const st = this._wb.backup && this._wb.backup.state
93
+ const kept = (st && Array.isArray(st.rooms) ? st.rooms : []).slice().sort((a, b) => (b.at || 0) - (a.at || 0)).map((r) => r.room)
94
+ return [...new Set([...this._opened.slice().reverse(), ...kept])] // newest first: the Sentinel keeps what fits
95
+ }
96
+ _d () {
97
+ if (this._deps) return this._deps
98
+ const wb = this._wb
99
+ return { post: wb._sentinelPost(), auth: wb._auth('the erase list belongs'), attest: (o) => attestStandingSentinel({ ...o, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow }), seal: sealToEnclave }
100
+ }
101
+
102
+ /** File this account's delete list with the standing Sentinel, for this app's tenant, so `wb.users.erase(email)` on the
103
+ * tenant's server can delete the rooms this account created. Automatic after a room is created or opened; call it after
104
+ * a sign-in or a backup restore to file at once. → `{ filed, rooms?, skipped? }`
105
+ * @param {object} [opts] { force? } — refile even when the list is unchanged */
106
+ async file ({ force = false } = {}) {
107
+ if (!this._tenant()) return { filed: false, skipped: 'not a tenant app: new Witbitz({ tenant })' }
108
+ if (!this._account()) return { filed: false, skipped: 'signed out: ' + (this._wb && this._wb.vault ? 'wb.vault.signIn' : 'wb.signIn') + ' first' }
109
+ const key = await this._key()
110
+ if (!key) return { filed: false, skipped: 'no backup: enable wb.backup so every device of the account shares the erase key' }
111
+ const d = this._d()
112
+ const backup = this._wb.backup
113
+ const stillOurs = backup && typeof backup._checkErased === 'function' ? async () => !(await backup._checkErased()) : null // pass 7, F#10
114
+ return fileEraseList({ tenant: this._tenant(), account: this._account(), rooms: this._rooms(), keys: [key], dropKeys: this._dropKeys(), post: d.post, auth: d.auth, attest: d.attest, seal: d.seal, ls: this._ls, force, stillOurs })
115
+ }
116
+
117
+ /** DELETE MY ACCOUNT — the Witbitz app's Settings → Delete my account (accountErase.js), for a builder's user (the owner's
118
+ * build-later list, 2026-10-28; "Sync the sdk", 2026-11-07). In this order, every step safe to run again:
119
+ * 0. the backup FIRST (its email gate is the step that can refuse — nothing else is deleted until it is through);
120
+ * 1. every room of the account (the backup's list and the rooms this page opened): one ONLY this account used is DELETED
121
+ * — the server checks this account's creation secret; a room someone else used is LEFT (what they wrote with you
122
+ * stays theirs too); an older room with no creation secret lapses when idle;
123
+ * 2. the username (a sign-in made in your app has none — nothing to release) and the directory entry; the app's filed
124
+ * erase list is withdrawn;
125
+ * 3. the account's index LAST, only when every step before it worked; then this client forgets the account
126
+ * (wb.backup.onState(null), signed out).
127
+ * Needs a live sign-in (for 2) and the backup (its key proves which rooms this account created). Billing: a builder's
128
+ * user is the APP's user — your server erases it (`wb.users.erase(email)` with the admin key).
129
+ * → { deleted:[room], left:[room], lapsing:[room], failed:[{room|what, why}], account:{ username, directory, backup } }
130
+ * `failed` not empty: nothing was forgotten here — fix the cause (often a sign-in) and call it again.
131
+ * @param {object} [opts] { onStep?(text) — progress lines to show; names? — the display names this person posts under in
132
+ * your app (`send(text, { from })`): a room whose every message is theirs (by email, or by one of these names) counts as
133
+ * only theirs. Without them a room with a named message is LEFT, never deleted unchecked (the server also refuses a
134
+ * room another account marked); code, ticket, emailCode — a backup set up with an email (wb.backup.gated) is deleted
135
+ * only with its emailed code, as a restore: the first call (with the recovery `code`) mails it and throws
136
+ * `email_code_required` with a `ticket` BEFORE anything is deleted; call again with { code, ticket, emailCode };
137
+ * getCode(address) → the emailed code — an account on the Witbitz account service is deleted there with it (as
138
+ * wb.backup.deleteAccount), as the run's backup step. In a vault the vault runs all of this itself, with its own screens. } */
139
+ async deleteAccount ({ onStep, names = [], code, ticket, emailCode, getCode } = {}) {
140
+ const wb = this._wb
141
+ // IN A VAULT the vault holds the keys and runs the whole erase itself, asking the person on its own screens (vault-core.js
142
+ // backup.deleteAccount; the owner, 2026-11-24) — it answers with the same report
143
+ if (wb.vault) { const r = await wb.backup.deleteAccount({ names }); return (r && r.report) || r }
144
+ const sess = wb._session
145
+ if (!sess || !sess.idToken || (sess.exp && sess.exp <= Date.now())) throw Object.assign(new Error('witbitz: sign in first — deleting the account needs a live sign-in'), { code: 'sign_in_required' })
146
+ const backup = wb.backup
147
+ const key = await this._key()
148
+ if (!key) throw Object.assign(new Error('witbitz: deleting the account needs its backup (wb.backup) — its key proves which rooms this account created'), { code: 'no_backup' })
149
+ // the backup's email gate FIRST: nothing is deleted until the release is in hand (sync sweep 11-08 #1). Asked only while the
150
+ // server still holds a gated backup — a re-run after the backup went (its gate with it) needs no new emailed code; and the
151
+ // backup is the run's FIRST step (accountErase.js), so the 120 s release is spent seconds after it was made, however many
152
+ // rooms follow (sync sweep 11-09 #15).
153
+ let token = null, gone = null
154
+ // AN ACCOUNT ON THE WITBITZ ACCOUNT SERVICE (sync sweep 2026-11-23 follow-up): its backup is the account there — deleted with an
155
+ // emailed code, as the run's backup step. The old store answered "on the account service" and every such run stopped at step 1.
156
+ const onService = !!(backup._s && backup._s.v2 && backup._v2)
157
+ if (onService && !backup._s.erased && typeof getCode !== 'function' && !(this._deleteDeps && this._deleteDeps.deleteBackup)) throw Object.assign(new Error('witbitz: this account is on the Witbitz account service — pass getCode(address) for the emailed code'), { code: 'invalid_argument' })
158
+ if (!onService && backup.gated && !(this._deleteDeps && this._deleteDeps.deleteBackup)) {
159
+ const probe = await backup._deleteRemote(null)
160
+ if (probe.ok || probe.status !== 403) gone = probe // already gone / not enforced (deleted now), or why it could not be asked
161
+ else token = await backup._release({ code, ticket, emailCode })
162
+ }
163
+ const dropKeys = this._dropKeys()
164
+ const st = backup.state || {}
165
+ const kept = Array.isArray(st.rooms) ? st.rooms : []
166
+ // a room's key: the whole key kept for a split room, else the link's own (a plain room's link IS its key — sync sweep 11-08
167
+ // #2: only split rooms had one here, so every plain Space read as shared and was left)
168
+ const keysBefore = new Map(kept.map((r) => [r.room, backup.keyFor(r.room)])) // read now: the service's erase may end the backup's state
169
+ const keyOf = async (room) => {
170
+ const kk = keysBefore.get(room) || backup.keyFor(room); if (kk) return kk
171
+ const r = kept.find((x) => x.room === room)
172
+ if (!r || !r.link || /[#&]us=/.test(r.link)) return null
173
+ try { const o = await wb._client.open(r.link); return o && o.room === room ? o.mk : null } catch { return null }
174
+ }
175
+ const isTemp = (r) => String(r).startsWith('tmp-')
176
+ let indexRoom = null
177
+ try { if (wb.account && wb.account.enabled && typeof wb.account._where === 'function') indexRoom = (await wb.account._where()).room } catch { indexRoom = null }
178
+ const d = this._deleteDeps || {}
179
+ const client = wb._client
180
+ const rep = await eraseAccount({
181
+ me: { email: this._account(), names: (Array.isArray(names) ? names : []).map((n) => String(n || '').trim()).filter(Boolean).slice(0, 20) },
182
+ indexRoom,
183
+ rooms: {
184
+ all: [...new Set([...kept.filter((r) => r.kind !== 'lane').map((r) => r.room), ...this._opened])].filter((r) => r && !isTemp(r)),
185
+ account: kept.filter((r) => r.kind === 'lane').map((r) => r.room), // a lane is the account's own: deleted without a read
186
+ },
187
+ read: d.read || (async (room) => {
188
+ const mk = await keyOf(room)
189
+ if (!mk) return null // a room this client cannot open is treated as shared: never deleted unchecked
190
+ const entries = await readAllEntries((since) => client.poll(room, mk, undefined, since)) // every page, not the first (sync sweep 2026-11-09)
191
+ if (!entries) return null
192
+ let config = null; try { config = await client.getConfig(room, mk) } catch { config = null }
193
+ return { entries, config }
194
+ }),
195
+ deleteRoom: d.deleteRoom || ((room) => deleteOwnRoom(room, { url: wb._roomDeleteEndpoint(), keys: [key], dropKeys, fetchImpl: (...a) => wb._fetch(...a) })),
196
+ // a queued delete is CONFIRMED (this secret's tombstone is down) before the account key goes — asked, never re-queued (state machines pass 9, S#1)
197
+ confirmDeleted: d.confirmDeleted || (d.deleteRoom ? undefined : ((room) => deleteOwnRoom(room, { url: wb._roomDeleteEndpoint(), keys: [key], dropKeys, fetchImpl: (...a) => wb._fetch(...a), check: true }))),
198
+ // a VERIFIED room: hand over this account's marks and delete secrets as it leaves; the last one out deletes it (agent/roomLeave.mjs).
199
+ // What they wrote stays part of the room while anyone who joined is still in it.
200
+ // WHAT THE ACCOUNT KEEPS OUTSIDE ITS ROOMS, as the app's Delete my account takes it (accountEraseUi.js eraseCleanups; sync sweep
201
+ // 2026-11-18 #2: the SDK passed none, and the builder docs promised the app's behaviour) — from this SDK's own handles.
202
+ cleanups: d.cleanups || sdkEraseCleanups(wb),
203
+ // …and the account's OTHER devices: each is signed out through the index before it goes (the app's signOutOthersForErase);
204
+ // one offline meanwhile clears itself on the index's 410s (sdkAccount.js / devices.js indexGoneVerdict).
205
+ signOutOthers: d.signOutOthers || (async () => {
206
+ const a = wb.account; if (!a || !a.enabled) return { ok: true }
207
+ for (const x of a.devices || []) if (x && !x.current && !x.signedOut) { try { a.signOut(x.id, { reason: 'erased' }) } catch { /* gone meanwhile */ } }
208
+ const r = await a.sync().catch(() => null)
209
+ return r && r.ok ? { ok: true } : { ok: false, why: 'the other devices could not be told — they clear themselves when they next find the account gone' }
210
+ }),
211
+ leaveRoom: d.leaveRoom || (async (room) => {
212
+ const mk = await keyOf(room); if (!mk || typeof client.leave !== 'function') return { left: false }
213
+ return leaveAndMaybeDelete(room, { post: (h) => client.leave(room, mk, h), handover: (r) => leaveHandover(r, { keys: [key], dropKeys }), del: (r, h, opts) => deleteHandedOver(r, h, { ...opts, url: wb._roomDeleteEndpoint(), fetchImpl: (...a) => wb._fetch(...a) }) })
214
+ }),
215
+ idToken: async () => sess.idToken,
216
+ // ONE rule for "done" (accountErase.stepDone — sync sweep 11-09 #14); a builder's sign-in owns no @username: the server's
217
+ // first_party_required is nothing to release (#4 — it ended every run here, after the rooms and the backup were gone)
218
+ releaseUsername: d.releaseUsername || (async (t) => stepDone(await client.userRelease(t), { nothing: ['first_party_required'] })),
219
+ eraseDirectory: d.eraseDirectory || (async (t) => { const sc = inviteScope(t); return stepDone(await client.dirErase(t, sc || undefined)) }),
220
+ eraseBilling: async () => ({ ok: true }), // the app's user: the builder's server erases it (wb.users.erase)
221
+ deleteBackup: d.deleteBackup || (onService
222
+ ? async () => { if (backup._s && backup._s.erased) return { ok: true }; try { await backup._v2.deleteAccount(backup, { getCode, keep: true }); return { ok: true } } catch (e) { return { ok: false, reason: (e && (e.code || e.message)) || 'failed' } } }
223
+ : () => (gone || backup._deleteRemote(token))),
224
+ backupGone: () => { if (backup._s) { clearTimeout(backup._timer); backup._timer = null; backup._s.erased = true; backup._changed() } }, // pass 7, F#2: no write re-creates it, even if a later step fails
225
+ withdrawFiled: d.withdrawFiled || (this._tenant() ? async () => { const dd = this._d(); const r = await fileEraseList({ tenant: this._tenant(), account: this._account(), rooms: [], keys: [key], dropKeys, post: dd.post, auth: dd.auth, attest: dd.attest, seal: dd.seal, ls: this._ls, force: true }).catch(() => null); return { ok: !!(r && r.filed) } } : null),
226
+ wipe: async () => {
227
+ this._opened = []; this._marked.clear(); this._k = { master: null, key: null }
228
+ try { if (wb.account && typeof wb.account.stop === 'function') wb.account.stop() } catch { /* */ }
229
+ backup._drop() // onState(null): the builder persists that this client holds no account any more
230
+ wb.signOut()
231
+ },
232
+ onStep,
233
+ })
234
+ delete rep.account.billing
235
+ return rep
236
+ }
237
+
238
+ /** Is a list filed for this account in this app, and how many rooms? Never the secrets. → `{ ok, filed, rooms?, updated? }` */
239
+ async status () {
240
+ if (!this._tenant() || !this._account()) return { ok: true, filed: false }
241
+ const d = this._d()
242
+ return d.post({ op: 'sentinel', sentinel: { mode: 'erasestatus', tenant: this._tenant() }, ...d.auth })
243
+ }
244
+ }
245
+
246
+ /** The SDK's half of the app's eraseCleanups (accountEraseUi.js): connections, Siri, outside agents, cloud computers, then what is left
247
+ * at the Sentinel. Room funding and mail addresses are the app's own (a builder bills through its tenant; mail is app-only). */
248
+ export function sdkEraseCleanups (wb) {
249
+ const why = (e) => String((e && e.message) || e)
250
+ return [
251
+ { what: 'connections', run: async () => { for (const c of await wb.connections.list()) if (c && c.id) await wb.connections.detach(c.id); return { ok: true } } },
252
+ { what: 'your Siri setup', run: async () => { await wb.siri.revoke(); return { ok: true } } },
253
+ { what: 'outside agents', run: async () => { if (wb.a2a && typeof wb.a2a.revoke === 'function') await wb.a2a.revoke(); return { ok: true } } },
254
+ { what: 'the cloud device', run: async () => {
255
+ if (!wb.cloudDevice) return { ok: true }
256
+ try {
257
+ const status = await wb.cloudDevice.status()
258
+ if (status.email || status.registered || status.rooms?.length) await wb.cloudDevice.forget()
259
+ return { ok: true }
260
+ } catch (e) {
261
+ if (['not_enrolled', 'not_available', 'not_in_dev_server', 'cloud_device_unavailable'].includes(e.code)) return { ok: true }
262
+ return { ok: false, why: why(e) }
263
+ }
264
+ } },
265
+ { what: 'your cloud computers', run: async (t) => { // every object of each (controller destroy) — not remove(), which keeps them for a key file
266
+ if (!wb.computers || typeof wb.computers._read !== 'function') return { ok: true }
267
+ const { destroyCloud } = await import('./codeCloud.js')
268
+ const { cloud } = await wb.computers._read()
269
+ for (const [id, e] of Object.entries((cloud && cloud.cloud) || {})) {
270
+ if (!e || e.removed || !e.workspace) continue
271
+ const r = await destroyCloud({ id, cloud: e }, { token: t })
272
+ if (!r.ok) return r
273
+ }
274
+ return { ok: true }
275
+ } },
276
+ { what: 'your account at the Sentinel', run: async (t) => {
277
+ const r = await wb._sentinelPost()({ op: 'sentinel', sentinel: { mode: 'forgetaccount' }, idToken: t }).catch((e) => ({ error: why(e) }))
278
+ if (r && r.ok) return { ok: true }
279
+ if (/unknown op forgetaccount|not an op this front forwards|bad_mode/.test(String((r && r.error) || ''))) return { ok: true } // an older Sentinel (accountEraseUi.js FORGET_UNSUPPORTED): the steps above took every record it keeps
280
+ return { ok: false, why: String((r && r.error) || 'no answer') }
281
+ } },
282
+ ].map((c) => ({ ...c, run: (t) => c.run(t).catch((e) => ({ ok: false, why: why(e) })) }))
283
+ }
package/sdkExports.js ADDED
@@ -0,0 +1,69 @@
1
+ import { exportSpace, recreateSpace } from './spaceExport.js'
2
+ import { makeBundle, sealSpaceMeta, keysFileText } from './offlineBundle.js'
3
+
4
+ // Downloads stay in the document doing the export. A vault never returns the
5
+ // contents or a recovery key to its embedding page.
6
+ export function saveExport(name, contents, type) {
7
+ const url = URL.createObjectURL(new Blob([contents], { type }))
8
+ const a = document.createElement('a')
9
+ a.href = url; a.download = name
10
+ document.body.appendChild(a); a.click(); a.remove()
11
+ setTimeout(() => URL.revokeObjectURL(url), 4000)
12
+ }
13
+
14
+ export async function saveOfflineReader() {
15
+ const response = await fetch(new URL('./decrypt.html', import.meta.url))
16
+ if (!response.ok) throw new Error('The offline reader could not be downloaded.')
17
+ saveExport('witbitz-offline-decryptor.html', await response.text(), 'text/html;charset=utf-8')
18
+ }
19
+
20
+ export async function saveRoomExport(sp, tier, current = () => true, title = sp.title) {
21
+ const reader = Object.fromEntries(['poll', 'getConfig', 'blob', 'state'].map((op) => [
22
+ op, (room, ...args) => sp._client[op](room, sp._mk, ...args),
23
+ ]))
24
+ const bundle = await exportSpace(sp.room, reader, { title })
25
+ if (!current()) throw new Error('account_changed')
26
+ bundle.tier = tier
27
+ saveExport('witbitz-space-' + sp.room + '.json', JSON.stringify(bundle), 'application/json')
28
+ return { count: bundle.count }
29
+ }
30
+
31
+ export async function recreateExport(wb, bundle, { tier = bundle?.tier || (bundle?.device?.confidential === false ? 'standard' : 'enclave') } = {}) {
32
+ const email = wb.vault ? (await wb.vault.whoami())?.email : wb.session?.email
33
+ if (!email) throw Object.assign(new Error('Sign in to recreate a Space for yourself.'), { code: 'sign_in_required' })
34
+ let space
35
+ const result = await recreateSpace(bundle, {
36
+ createSpace: async (cfg) => {
37
+ space = await wb.createSpace({
38
+ agent: { name: cfg.agentName, instructions: cfg.persona }, model: cfg.model, tools: cfg.tools,
39
+ clientTools: cfg.clientTools, agentReplies: cfg.agentReplies,
40
+ immediateTools: cfg.immediateTools, data: cfg.dataSchema, platformTools: cfg.platformTools,
41
+ framing: cfg.framing, dataWrites: cfg.dataWrites, admission: { emails: [email], admins: [email] }, tier,
42
+ })
43
+ return { room: space.room, mk: space._mk, keyless: !!wb.vault }
44
+ },
45
+ mirror: (_room, _mk, entries) => space._client.mirror(space.room, space._mk, entries),
46
+ })
47
+ let titleWarning
48
+ if (bundle.title) { try { await space.rename(bundle.title) } catch { titleWarning = 'The room was copied, but its title could not be saved.' } }
49
+ return { space, carried: result.carried, total: result.total, ...(titleWarning ? { titleWarning } : {}) }
50
+ }
51
+
52
+ export async function saveAccountArchive(rooms, resolveRoom, recoveryKeys, current) {
53
+ const spaces = [], keys = [], unavailable = []
54
+ for (const r of rooms) {
55
+ if (!current()) throw new Error('account_changed')
56
+ try {
57
+ const { key, ledger, count } = await resolveRoom(r, recoveryKeys)
58
+ if (!key || (!recoveryKeys && !ledger)) throw new Error('room_unavailable')
59
+ if (recoveryKeys) keys.push({ room: r.room, title: r.label || r.title || '', key })
60
+ else spaces.push({ meta: await sealSpaceMeta(key, { room: r.room, title: r.label || r.title || '', count }), ledger })
61
+ } catch { unavailable.push(r.room) }
62
+ }
63
+ if (!current()) throw new Error('account_changed')
64
+ const saved = recoveryKeys ? keys.length : spaces.length
65
+ if (!saved) throw Object.assign(new Error('No rooms could be exported.'), { code: 'archive_empty', unavailable })
66
+ if (recoveryKeys) saveExport('witbitz-room-keys.txt', keysFileText(keys), 'text/plain')
67
+ else saveExport('witbitz-spaces.json', JSON.stringify(makeBundle(spaces)), 'application/json')
68
+ return { saved, unavailable }
69
+ }
@@ -0,0 +1,34 @@
1
+ import { sendInvite } from './inviteSend.js'
2
+ import { inviteScope } from './sdkRekey.js'
3
+ import { validUsername } from './address.js'
4
+ import { EMAIL } from './memberChange.js'
5
+ import { boxApp } from './attestedBox.js'
6
+
7
+ const fail = (code, text) => Object.assign(new Error('witbitz: ' + text), { code })
8
+ export async function resendInvitation(sp, { email, username } = {}) {
9
+ if (sp._sharedRoom) throw fail('lane', 'a private lane cannot invite another member')
10
+ if (!!email === !!username || (email && !EMAIL.test(email)) || (username && !validUsername(username))) throw fail('invalid_argument', 'name one recipient by email or username')
11
+ const wb = sp._wb, client = wb && wb._client
12
+ if (!client || !wb._session || !wb._session.idToken) throw fail('sign_in_required', 'sign in before sending an invitation')
13
+ // Never downgrade an attested invitation to a bearer link in a normal directory box.
14
+ let attested
15
+ try { attested = await client.attestedRoom(sp.room, sp._mk) } catch { throw fail('policy_unreadable', 'the device policy could not be read') }
16
+ const cfg = await sp._gateConfig()
17
+ if (cfg.admission === 'email') {
18
+ if (!(await sp.isAdmin(wb._session.email)) && !(await sp.isOwner(wb._session.email))) throw fail('not_admin', 'only an owner or admin may resend an invitation')
19
+ }
20
+ if (attested) {
21
+ if ((sp._client && sp._client.keyless) || typeof client.verifyGovernance !== 'function') throw fail('attested', 'resend this invitation from the attested app that holds its key')
22
+ let verified
23
+ try { verified = await client.verifyGovernance(sp.room, sp._mk, null) } catch { throw fail('policy_unreadable', 'the signed native-app policy could not be read') }
24
+ const platforms = verified && verified.ok && verified.governed && verified.policy && verified.policy.requireAttestation && verified.policy.requireAttestation.platforms
25
+ const kind = Array.isArray(platforms) && platforms.length && platforms.every((p) => ['ios', 'android', 'macos'].includes(p)) ? 'attested' : Array.isArray(platforms) && platforms.length && platforms.every((p) => p === 'windows') ? 'windows' : null
26
+ if (!kind) throw fail('policy_unreadable', 'the signed native-app policy could not be verified')
27
+ const fragment = new URLSearchParams(String(sp.shareLink || '').split('#')[1] || '')
28
+ const us = sp._split ? fragment.get('us') : null, spc = us ? fragment.get('spc') || '' : ''
29
+ if ((sp._split && !us) || (!sp._split && !sp._mk)) throw fail('no_key', 'this device does not hold this attested Space’s key or user share')
30
+ return sendInvite({ email, username, room: sp.room, ...(us ? { us, spc } : { mk: sp._mk }), title: sp.title, from: sp._who(), gate: cfg.admission === 'email' ? 'email' : undefined, client, kind, app: boxApp(kind), scope: '' })
31
+ }
32
+ if (!sp.shareLink) throw fail('no_link', 'this device does not hold the current invitation link')
33
+ return sendInvite({ email, username, room: sp.room, link: sp.shareLink, title: sp.title, from: sp._who(), gate: cfg.admission === 'email' ? 'email' : undefined, client, scope: inviteScope(wb._session.idToken) })
34
+ }
@@ -0,0 +1,188 @@
1
+ import { linkOwnAgent, unlinkOwnAgent } from './ownAgentLink.js'
2
+ import { enableLaneIn, addPeerIn, removePeerIn, peersOf, mcpUrlOf } from './a2aCore.js'
3
+ import { A2A_PEERS_DOC } from './a2aShared.js'
4
+ import { sealDoc } from './accountSeal.js'
5
+
6
+ const fail = (code, text) => Object.assign(new Error('witbitz: ' + text), { code })
7
+ const ID = /^[A-Za-z0-9_-]{1,128}$/
8
+ const validLink = (link, lane, space) => link && link.lane === lane.room && link.space === space.room && ['connId', 'lPeer', 'sPeer'].every((k) => typeof link[k] === 'string' && ID.test(link[k]))
9
+ const queue = (w, fn) => { const out = (w._keptAgentRun || Promise.resolve()).catch(() => {}).then(fn); w._keptAgentRun = out.catch(() => {}); return out }
10
+ const DOC = 'xkept-agent-links' // private account doc: the framed page has no raw account-document API
11
+ const publicLink = (l) => ({ lane: l.lane, space: l.space, connId: l.connId, lPeer: l.lPeer, sPeer: l.sPeer })
12
+ async function readLinks(w, guard) {
13
+ guard()
14
+ if (!w.account.enabled) throw fail('not_enabled', 'enable the account before linking kept assistants')
15
+ const loc = await w.account._where(); guard()
16
+ const got = await w.account._read(loc, DOC, loc.app); guard()
17
+ if (!got.ok) throw fail('unreadable', 'the account’s kept-assistant links could not be read')
18
+ const links = (got.doc && got.doc.links) || {}
19
+ if (got.doc && (got.doc.v !== 1 || typeof links !== 'object' || Array.isArray(links))) throw fail('unopenable', 'the kept-assistant link document is malformed')
20
+ for (const [id, l] of Object.entries(links)) if (!l || id !== l.connId || !['lane', 'space', 'connId', 'lPeer', 'sPeer'].every((k) => typeof l[k] === 'string' && ID.test(l[k]))) throw fail('unopenable', 'a kept-assistant link is malformed')
21
+ return { loc, got, links }
22
+ }
23
+ async function saveLink(w, link, guard) {
24
+ for (let i = 0; i < 5; i++) {
25
+ const { loc, got, links } = await readLinks(w, guard)
26
+ const next = { v: 1, links: { ...links, [link.connId]: { ...link, at: Math.max(Date.now(), (Number(links[link.connId] && links[link.connId].at) || 0) + 1) } } }
27
+ const sealed = await sealDoc(loc.app, next); guard()
28
+ const r = await w.account._client().state(loc.room, loc.mk, DOC, sealed, 'kept assistant links', 'device', got.v); guard()
29
+ if (r && r.status === 409) continue
30
+ if (!r || r.status !== 200) throw fail('save_failed', 'the kept-assistant link could not be saved')
31
+ return
32
+ }
33
+ throw fail('version_conflict', 'the kept-assistant links kept changing')
34
+ }
35
+
36
+ /** Runs the app's complete link/rollback workflow where the credentials live: directly, or INSIDE the vault. */
37
+ function deps(w, lane, space, guard) {
38
+ const a = w.a2a, made = {}, held = new Map(), byRoom = new Map([[lane.room, lane], [space.room, space]])
39
+ const call = async (fn) => { guard(); const r = await fn(); guard(); return r }
40
+ const url = (room) => { const c = a._s.lanes[room]; return c ? mcpUrlOf(a.endpoint, c.handle) : null }
41
+ return {
42
+ unavailable: () => '', hosted: () => false,
43
+ hasLane: (room) => !!a._s.lanes[room],
44
+ enableLane: (room, name) => call(() => a._change((s) => enableLaneIn(s, room, { name }))),
45
+ addPeer: (room, name, opts) => call(async () => { const r = await a._change((s) => addPeerIn(s, room, name, opts, fail)); made[room] = r.id; return r }),
46
+ removePeer: (room, id) => call(async () => { if (peersOf(a._s, room).some((p) => p.id === id)) await a._change((s) => removePeerIn(s, room, id)) }),
47
+ push: async () => {}, // _change already pushes and commits each change only after acknowledgement
48
+ peersOf: (room) => peersOf(a._s, room), mcpUrl: url,
49
+ syncSpaceAgents: (room) => call(async () => {
50
+ const sp = byRoom.get(room)
51
+ for (let i = 0; i < 5; i++) {
52
+ const d = await sp._client.state(room, sp._mk, A2A_PEERS_DOC); guard()
53
+ if (!d || d.status !== 200 || !Number.isInteger(d.v)) throw fail('unreadable', 'the kept assistant’s peer list could not be read')
54
+ const peers = peersOf(a._s, room)
55
+ const r = await sp._client.state(room, sp._mk, A2A_PEERS_DOC, { peers }, `${peers.length} outside agents may write here`, sp._who(), d.v)
56
+ guard()
57
+ if (r && r.status === 409) continue
58
+ if (!r || r.status !== 200) throw fail('save_failed', 'the kept assistant’s peer list could not be saved')
59
+ return
60
+ }
61
+ throw fail('version_conflict', 'the kept assistant’s peer list kept changing')
62
+ }),
63
+ report: (room, peerId, target) => call(async () => { try { return await w.cloudDevice._ask('report', { room, peerId, ...(target ? { url: target.url, token: target.token, name: target.name || '' } : { off: true }) }) } catch (e) { if (target || (e.code !== 'not_enrolled' && e.code !== 'not_kept')) throw e } }), // 11·O#4: off where the device holds no such Space = done
64
+ connect: (spec, input) => call(async () => {
65
+ const conn = await w.connections.attachMcp({ url: spec.url, label: spec.label, token: input.token }); guard()
66
+ const link = { lane: lane.room, space: space.room, lPeer: made[lane.room], sPeer: made[space.room], connId: conn.id, pending: true }
67
+ try {
68
+ await saveLink(w, link, guard)
69
+ if (w._keepAgentConnection) await w._keepAgentConnection(conn, link)
70
+ w._keptAgentConnections = w._keptAgentConnections || new Map()
71
+ w._keptAgentConnections.set(conn.id, { ...conn, ownLink: link }); held.set(conn.id, conn)
72
+ } catch (e) { await w.connections.detach(conn.id).catch(() => {}); throw e }
73
+ return conn
74
+ }),
75
+ disconnect: (id) => call(() => w.connections.detach(id, { spaces: [lane] })),
76
+ useIn: (_room, id) => call(() => lane.connections.grant(held.get(id), { reads: 'auto' })),
77
+ }
78
+ }
79
+
80
+ function checked(lane, space) {
81
+ const w = lane._wb
82
+ if (!w || !lane._sharedRoom || !space || space._sharedRoom || space._wb !== w || space.room === lane.room) throw fail('invalid_argument', 'link a private lane and a kept Space from the same client')
83
+ const session = w._session, state = w.backup._s
84
+ const guard = () => { if (w._session !== session || w.backup._s !== state) throw fail('account_changed', 'the account changed during assistant linking') }
85
+ return { w, guard }
86
+ }
87
+
88
+ export function linkKeptAgent(lane, space, { spaceName = space && space.title, laneName = lane.title } = {}) {
89
+ const { w, guard } = checked(lane, space)
90
+ return queue(w, async () => {
91
+ guard()
92
+ if (!(await space.alwaysOn.status()).on) throw fail('not_always_on', 'keep this Space on the cloud device before linking it')
93
+ guard()
94
+ const { links } = await readLinks(w, guard)
95
+ const existing = Object.values(links).find((l) => l && !l.gone && l.lane === lane.room && l.space === space.room)
96
+ guard()
97
+ if (existing && !existing.pending) {
98
+ if (!w.a2a._s.lanes[lane.room] || !w.a2a._s.lanes[space.room]) throw fail('a2a_state_required', 'restore this account’s A2A state before reopening its kept-assistant link')
99
+ const cfg = await lane._gateConfig({ fresh: true }); guard()
100
+ if (!cfg || cfg.gated && !cfg.allow) throw fail('unreadable', 'the private assistant’s connections could not be read')
101
+ const connections = Array.isArray(cfg?.connections) ? cfg.connections : []
102
+ if (connections.some((c) => c.id === existing.connId)) return publicLink(existing)
103
+ }
104
+ if (existing) await unlinkKnown(w, lane, space, existing, guard)
105
+ const d = deps(w, lane, space, guard)
106
+ const result = await linkOwnAgent({ lane: lane.room, space: space.room, spaceName: String(spaceName || 'Kept assistant').slice(0, 80), laneName: String(laneName || 'Private assistant').slice(0, 80) }, d)
107
+ guard()
108
+ const link = { lane: lane.room, space: space.room, ...result }
109
+ await saveLink(w, link, guard)
110
+ return link
111
+ })
112
+ }
113
+
114
+ export function unlinkKeptAgent(lane, space, link) {
115
+ const { w, guard } = checked(lane, space)
116
+ if (!validLink(link, lane, space)) throw fail('invalid_argument', 'use the link returned by lane.linkKept for these rooms')
117
+ return queue(w, async () => {
118
+ guard()
119
+ const { links } = await readLinks(w, guard), known = links[link.connId]
120
+ if (!known) throw fail('not_in_account', 'that kept-assistant link is not in this account')
121
+ if (known.gone) return { disconnected: true }
122
+ if (!validLink(known, lane, space) || known.lPeer !== link.lPeer || known.sPeer !== link.sPeer) throw fail('not_in_account', 'that kept-assistant link does not belong to these rooms')
123
+ await unlinkKnown(w, lane, space, known, guard)
124
+ return { disconnected: true }
125
+ })
126
+ }
127
+
128
+ async function unlinkKnown(w, lane, space, link, guard) {
129
+ if (!w._agentRoom && (!w.a2a._s.lanes[lane.room] || !w.a2a._s.lanes[space.room])) throw fail('a2a_state_required', 'restore this account’s A2A state before unlinking its kept assistant')
130
+ const missing = [[lane.room, link.lPeer], [space.room, link.sPeer]]
131
+ .filter(([room, id]) => !peersOf(w.a2a._s, room).some((p) => p.id === id))
132
+ if (missing.length) {
133
+ const remote = await w.a2a.status()
134
+ guard()
135
+ if (remote?.ok !== true || !Array.isArray(remote.lanes)) throw fail('unreadable', 'the active outside-agent peers could not be checked')
136
+ for (const [room, id] of missing) {
137
+ const active = remote.lanes.find((l) => l.room === room)
138
+ if (active && (!Array.isArray(active.peers) || active.peers.some((p) => p.id === id))) throw fail('a2a_state_required', 'restore this account’s current A2A state before unlinking its kept assistant')
139
+ }
140
+ }
141
+ await unlinkOwnAgent({ lane: lane.room, space: space.room, lPeer: link.lPeer, sPeer: link.sPeer, connId: link.connId }, deps(w, lane, space, guard))
142
+ guard()
143
+ await saveLink(w, { ...publicLink(link), gone: true }, guard)
144
+ if (w._forgetAgentConnection) await w._forgetAgentConnection(link.connId)
145
+ if (w._keptAgentConnections) w._keptAgentConnections.delete(link.connId)
146
+ }
147
+
148
+ export async function keptAgentSpaceIds(w) {
149
+ const legacy = Object.keys(w.a2a?._s?.lanes || {})
150
+ .filter((room) => peersOf(w.a2a._s, room).some((p) => p.own === true))
151
+ if (!w.account?.enabled || typeof w.account._read !== 'function') return legacy
152
+ const session = w._session, state = w.backup._s
153
+ const guard = () => { if (w._session !== session || w.backup._s !== state) throw fail('account_changed', 'the account changed while reading kept links') }
154
+ const { links } = await readLinks(w, guard)
155
+ return [...new Set([...legacy, ...Object.values(links).filter((l) => !l.gone).map((l) => l.space)])]
156
+ }
157
+
158
+ /** Stop every link to a Space, including links created on another device. Uses the private account doc, not page-supplied ids. */
159
+ export function disconnectKeptSpace(space) {
160
+ const w = space._wb, session = w._session, state = w.backup._s
161
+ const guard = () => { if (w._session !== session || w.backup._s !== state) throw fail('account_changed', 'the account changed while stopping kept assistants') }
162
+ return queue(w, async () => {
163
+ guard()
164
+ const { links } = w.account?.enabled ? await readLinks(w, guard) : { links: {} }
165
+ const errors = []
166
+ for (const link of Object.values(links).filter((l) => l && !l.gone && l.space === space.room)) {
167
+ let lane, close = false
168
+ try {
169
+ if (w._agentRoom) lane = w._agentRoom(link.lane)
170
+ else {
171
+ const rec = w.backup.rooms.find((r) => r.room === link.lane)
172
+ if (!rec) throw fail('not_in_account', 'the private assistant must be restored before unlinking it')
173
+ lane = await w.openSpace(rec.link, { live: false }); close = true
174
+ }
175
+ guard()
176
+ await unlinkKnown(w, lane, space, link, guard)
177
+ } catch (e) { errors.push(e) }
178
+ finally { if (lane && (close || w._agentRoom)) lane.close() }
179
+ }
180
+ if (w.a2a) {
181
+ const d = deps(w, space, space, guard)
182
+ for (const p of d.peersOf(space.room).filter((p) => p.own === true)) {
183
+ try { await unlinkOwnAgent({ space: space.room, sPeer: p.id }, d) } catch (e) { errors.push(e) }
184
+ }
185
+ }
186
+ if (errors.length) throw errors[0]
187
+ })
188
+ }