@witbitz/sdk 4.6.0 → 4.7.1

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.
package/witbitz-sdk.js CHANGED
@@ -22,7 +22,7 @@ import { memberHash } from './rosterHash.js'
22
22
  import { verifyAttestation } from './nitroVerify.js' // devRoot: the dev server's Sentinel, checked under its root
23
23
  import { AccountBackup } from './sdkBackup.js'
24
24
  import { linkLanes, laneLinkTool } from './sdkLaneLink.js' // lane.link(other): two of a member's assistants ask each other
25
- import { InviteAccount, adoptGrant as adoptRoomGrant, changeMembers as changeMembersInPlace, rotateKey as rotateKeyInPlace, relink } from './sdkRekey.js' // a verified room changes its members in place (https://witbitz.chat/docs/sdk-people.md#members)
25
+ import { InviteAccount, adoptGrant as adoptRoomGrant, changeMembers as changeMembersInPlace, rotateKey as rotateKeyInPlace, sessionRole, relink } from './sdkRekey.js' // a verified room changes its members in place (https://witbitz.chat/docs/sdk-people.md#members)
26
26
  import { TemporaryRooms } from './sdkTemporaryRooms.js'
27
27
  import { Computers } from './sdkComputers.js' // wb.computers: the person's cloud computers (docs/sdk-cloud-computers.md)
28
28
  import { opensEnvelopes, sealsIdentity } from './reqEnvelope.js' // the sealed request envelope: does a live enclave open it
@@ -51,6 +51,7 @@ import { Dictation, voiceForDictation } from './sdkDictation.js' // wb.dictation
51
51
  import { Protect } from './sdkProtect.js' // wb.protect: what the app keeps on the device, sealed under a passkey-derived key
52
52
  import { boxesHash, bareEC, jkey } from './spaceFork.js' // the membership fork's notice format, shared with the app
53
53
  import { preferredAddresses } from './addPreferred.js' // "Add me to Spaces as @username" (docs/spaces-usernames.md § 13)
54
+ import { signedInRoomTags, placeRoles, roleEmails, rolesOf, roleTagHolders } from './roomRoles.js' // owners and admins by @username tag (docs/spaces-usernames.md § 13.1)
54
55
  import { normAdmission, checkAdminCollections, judgeMove, newRoomKeepsGov } from './emailFork.js' // the gate's rules with the app; following a move an OLDER client made (a Space no longer moves: #members)
55
56
  import { deleteOwnRoom } from './roomDelete.js'
56
57
  import { sealTo, openBox, commit as keyCommit } from './e2ee.js'
@@ -200,7 +201,7 @@ const perTurn = (instructions) => (typeof instructions === 'string' && instructi
200
201
  /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
201
202
  export { isLaneCopy } from './roomName.js' // is this message a lane's copy of its shared room's line? (the app's own test, sdk-agents.md#lanes)
202
203
  export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
203
- export const SDK_VERSION = '4.6.0'
204
+ export const SDK_VERSION = '4.7.1'
204
205
  // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
205
206
  const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
206
207
  /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
@@ -1037,13 +1038,20 @@ export class Witbitz {
1037
1038
  if (this.vault) return this.vault._c.account('backup', 'exportArchive', recoveryKeys === true, rooms?.map(sp => sp.room), ...(destination === 'clipboard' ? [destination] : []))
1038
1039
  const { saveAccountArchive } = await import('./sdkExports.js')
1039
1040
  const session = this._session, generation = this._archiveGeneration, backup = this.backup._s
1040
- const selected = new Map((rooms === undefined ? this.backup.rooms : []).map(r => [r.room, r]))
1041
+ const savedLinks = new Map(this.backup.rooms.map(r => [r.room, r.link]))
1042
+ const selected = new Map((rooms === undefined ? this.backup.rooms : []).map(r => [r.room, { ...r }]))
1041
1043
  const opened = [...(this._archiveHandles || [])].filter(sp => sp._archiveGeneration === this._archiveGeneration && sp._archiveEmail === (session?.email || '') && sp._archiveMaster === (backup?.master || null))
1042
1044
  if (rooms?.some(sp => !opened.includes(sp))) throw sdkError('select Spaces opened for this account', 'invalid_argument')
1043
1045
  for (const sp of rooms ?? opened) {
1044
1046
  if (!sp || sp._wb !== this || sp._stopped || !sp.shareLink) throw sdkError('select open Spaces from this SDK client', 'invalid_argument')
1045
1047
  selected.set(sp.room, { room: sp.room, link: sp.shareLink, title: sp.title, held: sp })
1046
1048
  }
1049
+ const current = () => {
1050
+ if (this._archiveGeneration !== generation || (this._session?.email || '') !== (session?.email || '') || (this.backup._s?.master || null) !== (backup?.master || null)) return false
1051
+ const live = new Map(this.backup.rooms.map(r => [r.room, r.link]))
1052
+ return [...selected.values()].every(r => (!savedLinks.has(r.room) || live.get(r.room) === savedLinks.get(r.room)) &&
1053
+ (!r.held || (this._archiveHandles?.has(r.held) && !r.held._stopped && r.held.shareLink === r.link)))
1054
+ }
1047
1055
  return saveAccountArchive([...selected.values()], async (r, keysOnly, attachments) => {
1048
1056
  const { room, mk } = r.held?._mk ? { room: r.room, mk: r.held._mk } : await this._openLink(r.link)
1049
1057
  if (room !== r.room) throw sdkError('witbitz: a saved link opens another Space', 'wrong_room')
@@ -1051,7 +1059,7 @@ export class Witbitz {
1051
1059
  const saved = await this._client.exportSealed(room, mk, { attachments }) // + the stored attachments, sealed (sdkExports.js)
1052
1060
  if (saved?.status !== 200) throw sdkError('witbitz: this Space\u2019s history could not be read just now', 'unavailable')
1053
1061
  return { key: mk, ledger: saved.sealed, count: saved.count, attachments: saved.attachments }
1054
- }, recoveryKeys === true, () => this._archiveGeneration === generation && (this.backup._s?.master || null) === (backup?.master || null), destination)
1062
+ }, recoveryKeys === true, current, destination)
1055
1063
  }
1056
1064
  async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, usernames, safeMedia, lanes, owner } = {}) {
1057
1065
  // A TEMPORARY ROOM (docs/visitor-limits.md): a `tmp-` room the deployment wipes when it is idle — `true`: after about half
@@ -1078,6 +1086,9 @@ export class Witbitz {
1078
1086
  // A DIRECT CHAT (the Spaces app's, directChat.js): a verified Space with exactly you and one other person, you its owner,
1079
1087
  // `direct: true` sealed in — the server refuses its rename and each side calls it by the other person (space.directPeer).
1080
1088
  if (direct !== undefined) admission = directAdmission(direct, admission, this._session)
1089
+ // The account this create began under: a restore or sign-in that lands while the room is being made — the invitee lookups below
1090
+ // included (sync sweep 11-29 #4) — must not have the new room's link recorded in ITS backup (side sweep: sdk-pending-create-follows-account-switch).
1091
+ const began = { generation: this._archiveGeneration, email: this._session?.email || '', master: this.backup._s?.master || null }
1081
1092
  // ★ THE CREATOR IS THE OWNER, as in the app (space.js gatedBase; docs/verified-room-members.md): a verified room names its
1082
1093
  // signed-in creator as its first owner when they are on its list and no owners were given — authority then follows that
1083
1094
  // email onto every device (sync sweep, 10-12). Not on the list, or not signed in: unchanged (an owner who cannot open it
@@ -1090,9 +1101,6 @@ export class Witbitz {
1090
1101
  const enc = tierIsEnclave(tier)
1091
1102
  const split = splitKeyChoice(key)
1092
1103
  if (split && !this._appShareUrl && !this._clientOpts.tenant) throw Object.assign(new Error("witbitz: a split-key room needs your app-half function — new Witbitz({ appShare: '/api/appshare' }) — or, with the Witbitz-held key, your tenant — new Witbitz({ tenant: 't_…' })"), { code: 'tenant_required' })
1093
- // The account this create began under: a restore or sign-in that lands while the room is being made must not have the new
1094
- // room's link recorded in ITS backup (side sweep: sdk-pending-create-follows-account-switch).
1095
- const began = { generation: this._archiveGeneration, email: this._session?.email || '', master: this.backup._s?.master || null }
1096
1104
  await this._checkModel(model || agent.model)
1097
1105
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
1098
1106
  applySkills(cfg, skills)
@@ -1108,6 +1116,7 @@ export class Witbitz {
1108
1116
  if (!(all && all.tempRooms)) throw sdkError('witbitz: temporary rooms are not available on this deployment', 'temporary_unavailable')
1109
1117
  cfg.room = newRoomId(cfg.region, { prefix: 'tmp' }) // the whole stack keys off the prefix (the app's tempRooms.js mints the same shape)
1110
1118
  }
1119
+ if (gate) await this._rolesAsPreferred(cfg) // owners and admins who prefer their @username are named by its tag (§ 13.1)
1111
1120
  // Attest FIRST (a configuration failure is loud, a cold enclave is not — _encAttestSoft); mint; only then wake and hand
1112
1121
  // the enclave its config.
1113
1122
  if (enc) await this._encAttestSoft()
@@ -1151,6 +1160,40 @@ export class Witbitz {
1151
1160
  al.tagUsers = [...new Set([...(al.tagUsers || []), ...learned.map((x) => x.username)])]
1152
1161
  }
1153
1162
 
1163
+ /** @private OWNERS AND ADMINS AS THEY PREFER (docs/spaces-usernames.md § 13.1; the owner, 2026-11-29): a new Space's owner or admin whose
1164
+ * address is HIDDEN (not advertised) and who prefers their @username — the signed-in creator by whoami, anyone else past the email door
1165
+ * (only where "find me by email" is on) — is named in the role, and put on the list, by the room's tag for that name; the email leaves
1166
+ * both. Only where the server takes tag roles (roomRoles.roleTagFor: `roles: true`); otherwise the role names the email, as before.
1167
+ * The room id is chosen here so the tag can be asked for it. Changes `cfg` in place; a lookup that fails leaves it as it was. */
1168
+ async _rolesAsPreferred(cfg) {
1169
+ const al = cfg && cfg.admission === 'email' && cfg.allow
1170
+ if (!al) return
1171
+ const lc = (x) => String(x || '').trim().toLowerCase()
1172
+ const hidden = new Set((Array.isArray(al.hidden) ? al.hidden : (al.emails || [])).map(lc)) // with `hidden`, `emails` are the advertised ones (normAdmission)
1173
+ const owners = roleEmails(cfg.owners), mgr = [...owners.map((email) => ({ role: 'owners', email })), ...roleEmails(cfg.admins).filter((e) => !owners.includes(e)).map((email) => ({ role: 'admins', email }))].filter((m) => hidden.has(m.email))
1174
+ if (!mgr.length) return
1175
+ const me = lc(this._session && !(this._session.exp && this._session.exp <= Date.now()) ? this._session.email : '')
1176
+ const people = []
1177
+ if (me && mgr.some((m) => m.email === me)) {
1178
+ const w = await this.usernames.mine().catch(() => null)
1179
+ if (w && w.username && w.addAsUsername !== false) people.push(...mgr.filter((m) => m.email === me).map((m) => ({ ...m, username: w.username })))
1180
+ }
1181
+ const others = mgr.filter((m) => m.email !== me)
1182
+ if (others.length) {
1183
+ const pref = await preferredAddresses([...new Set(others.map((m) => m.email))], { client: this._client }).catch(() => null)
1184
+ const name = new Map(((pref && pref.learned) || []).map((x) => [x.email, x.username]))
1185
+ for (const m of others) if (name.has(m.email)) people.push({ ...m, username: name.get(m.email) })
1186
+ }
1187
+ if (!people.length) return
1188
+ const room = cfg.room || newRoomId(cfg.region)
1189
+ const pr = await placeRoles({ room, owners: cfg.owners, admins: cfg.admins, allow: al }, people, { client: this._client }).catch(() => null)
1190
+ if (!pr || !pr.placed.length) return
1191
+ cfg.room = room
1192
+ cfg.allow = pr.allow
1193
+ cfg.owners = pr.owners
1194
+ if (cfg.admins || pr.admins.emails.length || pr.admins.tags) cfg.admins = pr.admins
1195
+ }
1196
+
1154
1197
  /** @private how a split room is created: through the builder's function when there is one (`via`), else here. */
1155
1198
  setAssistantMemory(spaces = []) {
1156
1199
  if (!Array.isArray(spaces) || spaces.length > LIMITS.links + 1) throw sdkError('witbitz: choose a bounded list of Spaces for assistant memory', 'invalid_argument')
@@ -1278,7 +1321,7 @@ export class Witbitz {
1278
1321
  const config = await this._client.getConfig(room, mk, { plainMark: true })
1279
1322
  if (current() && (config?.help || config?.lane || config?.bridge)) return { excluded: true }
1280
1323
  const v = await readAllPages(since => this._client.poll(room, mk, undefined, since))
1281
- return current() && config && !config.help && !config.lane && !config.bridge && v.status === 200 && !v.incomplete ? { config, entries: v.entries, etag: v.etag, selfEntries: await ownAdmissionEntries(config, this.erasure._account(), () => this._client.state(room, mk, 'roster')), selfHash: this.erasure._account() ? await memberHash(this.erasure._account(), room) : null } : null
1324
+ return current() && config && !config.help && !config.lane && !config.bridge && v.status === 200 && !v.incomplete ? { config, entries: v.entries, etag: v.etag, selfEntries: await ownAdmissionEntries(config, this.erasure._account(), () => this._client.state(room, mk, 'roster'), () => signedInRoomTags(this._client, room, session?.idToken)), selfHash: this.erasure._account() ? await memberHash(this.erasure._account(), room) : null } : null
1282
1325
  },
1283
1326
  prepare: room => remove(room, { check: true, reviewPolicy: true }),
1284
1327
  deleteOnServer: (room, reviewedEtag, reviewedPolicy) => remove(room, { reviewedEtag, reviewedPolicy }),
@@ -1855,7 +1898,11 @@ export class Space {
1855
1898
  const rows = await this._wb.models({ tier: this._isEnclave() ? 'enclave' : 'standard' })
1856
1899
  const row = (rows || []).find((m) => m && m.id === id)
1857
1900
  if (!row) throw sdkError(`witbitz: ${JSON.stringify(id)} is not a model offered for this Space — see wb.models()`, 'unknown_model')
1858
- const pick = { catalog: String(row.id), wire: String(row.wire || ''), label: String(row.label || '') }
1901
+ // the room's effort is kept when the new model takes it too, as the app's model chip does (modelChip.js); else the model's own default
1902
+ await this._freshSettings()
1903
+ const was = this._modelPick, efforts = Array.isArray(row.efforts) ? row.efforts.map(String) : []
1904
+ const effort = was && was.effort && efforts.includes(String(was.effort)) ? String(was.effort) : ''
1905
+ const pick = { catalog: String(row.id), wire: String(row.wire || ''), label: String(row.label || ''), ...(effort ? { effort } : {}) }
1859
1906
  this._modelGen = (this._modelGen || 0) + 1
1860
1907
  const r = await this._client.state(this.room, this._mk, 'model', modelDocOf(pick), pick.label || pick.catalog)
1861
1908
  if (!r || r.status !== 200) throw refused('setModel', r)
@@ -2026,7 +2073,10 @@ export class Space {
2026
2073
  if (this._wb?.vault) return this._wb.vault._c.roomAccount(this.room, 'portable', 'export')
2027
2074
  const { saveRoomExport } = await import('./sdkExports.js')
2028
2075
  const generation = this._wb?._archiveGeneration
2029
- return saveRoomExport(this, this._wb?._enc?.rooms.has(this.room) || ENC_MARK.test(this.shareLink || '') ? 'enclave' : 'standard', () => this._wb?._archiveGeneration === generation)
2076
+ // a linked continuation's earlier versions: read with the keys this account's rooms carry (their saved links)
2077
+ const keys = {}
2078
+ for (const r of this._wb?.backup?.rooms || []) { let mk = typeof r.mk === 'string' ? r.mk : ''; try { mk ||= new URLSearchParams(new URL(r.link).hash.slice(1)).get('mk') || '' } catch { /* no key in it */ } if (mk && r.room !== this.room) keys[r.room] = mk }
2079
+ return saveRoomExport(this, this._wb?._enc?.rooms.has(this.room) || ENC_MARK.test(this.shareLink || '') ? 'enclave' : 'standard', () => this._wb?._archiveGeneration === generation, this.title, keys)
2030
2080
  }
2031
2081
  async sealedProof() {
2032
2082
  if (!(this._client && this._client.vault)) this._needKey('sealedProof') // a vault reads the stored boxes for the page (ciphertext only)
@@ -2297,7 +2347,18 @@ export class Space {
2297
2347
  }
2298
2348
  }
2299
2349
  }
2300
- return { ...(unopenedPrivateInvites !== undefined ? { unopenedPrivateInvites } : {}), gated: true, emails: list(a.emails), domains: list(a.domains), hidden: list(a.mh).length + legacy, admins, owners, ...(cfg.lane === true || cfg.bridge ? { lane: true } : {}), ...lanesOn } // lane: a private lane, not a Space (laneConfig.js)
2350
+ // ROLES BY @USERNAME TAG (docs/spaces-usernames.md § 13.1): an owner or admin who prefers their @username is named by the room's tag for
2351
+ // it — `ownerTags` / `adminTags` (what changeMembers takes back), and `ownerUsers` / `adminUsers`: the @usernames of those the guest book
2352
+ // and the names' own tags match (a holder not matched yet is in the tags, not the names). Absent in a room with no tag roles.
2353
+ const rt = rolesOf(cfg)
2354
+ let tagRoles = {}
2355
+ if (rt.ownerTags.length || rt.adminTags.length) {
2356
+ const book = await Promise.resolve().then(() => this._client.state(this.room, this._mk, ROSTER_DOC)).catch(() => null)
2357
+ const held = book && book.status === 200 ? await roleTagHolders(Object.values(book.seen || {}), [...rt.ownerTags, ...rt.adminTags], { room: this.room, userTag: typeof this._client.userTag === 'function' ? (n, r) => this._client.userTag(n, r) : null }).catch(() => new Map()) : new Map()
2358
+ const names = (tags) => [...new Set(tags.map((t) => held.get(t) && held.get(t).user).filter(Boolean).map((u) => '@' + u))]
2359
+ tagRoles = { ownerTags: rt.ownerTags, adminTags: rt.adminTags, ownerUsers: names(rt.ownerTags), adminUsers: names(rt.adminTags) }
2360
+ }
2361
+ return { ...(unopenedPrivateInvites !== undefined ? { unopenedPrivateInvites } : {}), gated: true, emails: list(a.emails), domains: list(a.domains), hidden: list(a.mh).length + legacy, admins, owners, ...tagRoles, ...(cfg.lane === true || cfg.bridge ? { lane: true } : {}), ...lanesOn } // lane: a private lane, not a Space (laneConfig.js)
2301
2362
  }
2302
2363
 
2303
2364
  /** Is `email` one of this room's ADMINS? The room enforces it (2026-10-02): with admins, only they change the
@@ -2305,18 +2366,29 @@ export class Space {
2305
2366
  * connection. A non-admin's attempt is refused
2306
2367
  * with `code: 'not_admin'`. A room without admins has none (every member may do all of it, as before). */
2307
2368
  async isAdmin(email) {
2369
+ if (this._wb?.vault && String(email || '').trim().startsWith('@')) return this._wb.vault._c.roomAccount(this.room, 'roster', 'isAdmin', email)
2308
2370
  const e = String(email || '').trim().toLowerCase()
2309
2371
  const cfg = await this._gateConfig({ plainMark: true })
2310
2372
  const has = (o) => !!(o && Array.isArray(o.emails) && o.emails.some((x) => String(x).trim().toLowerCase() === e))
2311
- return has(cfg.admins) || has(cfg.owners) // an owner is an admin
2373
+ return has(cfg.admins) || has(cfg.owners) || !!(await this._roleByTag(cfg, e)) // an owner is an admin; '@username' — a role held by its tag (§ 13.1)
2374
+ }
2375
+
2376
+ /** @private A role held by an @username's tag (docs/spaces-usernames.md § 13.1): `who` = '@name' → 'owner' | 'admin' | ''. */
2377
+ async _roleByTag(cfg, who) {
2378
+ const rt = rolesOf(cfg)
2379
+ if (!String(who).startsWith('@') || !(rt.ownerTags.length || rt.adminTags.length) || typeof this._client.userTag !== 'function') return ''
2380
+ const t = await this._client.userTag(String(who).slice(1), this.room).catch(() => null)
2381
+ const tag = t && t.status === 200 ? t.tag : ''
2382
+ return !tag ? '' : rt.ownerTags.includes(tag) ? 'owner' : rt.adminTags.includes(tag) ? 'admin' : ''
2312
2383
  }
2313
2384
 
2314
2385
  /** Is `email` one of this room's OWNERS (a level above admins, enforced by the room)? An owner can do all an admin can,
2315
2386
  * and only an owner can change the owners or lower or remove an admin when the room is moved ({@link Space#fork}). */
2316
2387
  async isOwner(email) {
2388
+ if (this._wb?.vault && String(email || '').trim().startsWith('@')) return this._wb.vault._c.roomAccount(this.room, 'roster', 'isOwner', email)
2317
2389
  const e = String(email || '').trim().toLowerCase()
2318
2390
  const cfg = await this._gateConfig({ plainMark: true })
2319
- return !!(cfg.owners && Array.isArray(cfg.owners.emails) && cfg.owners.emails.some((x) => String(x).trim().toLowerCase() === e))
2391
+ return !!(cfg.owners && Array.isArray(cfg.owners.emails) && cfg.owners.emails.some((x) => String(x).trim().toLowerCase() === e)) || (await this._roleByTag(cfg, e)) === 'owner' // '@username': by its tag (§ 13.1)
2320
2392
  }
2321
2393
 
2322
2394
  /** Does this Space's gate admit `email`? Checked on this device against the sealed list: an advertised address, a
@@ -2346,16 +2418,19 @@ export class Space {
2346
2418
  async _gateConfig({ fresh = false, plainMark = false } = {}) {
2347
2419
  const owner = this._wb?.vault ? this._wb._vaultGeneration : this._wb?._session
2348
2420
  const key = this._mk, epoch = this.epoch
2349
- if (!fresh && this._gateCfg && this._gateOwner === owner) return this._gateCfg
2421
+ if (!fresh && this._gateCfg && this._gateOwner === owner && (!this._gated || this._gateCfg.admission === 'email')) return this._gateCfg
2350
2422
  const cfg = typeof this._client.getConfig === 'function' ? await this._client.getConfig(this.room, this._mk, plainMark ? { plainMark: true } : undefined) : null
2351
2423
  if (key !== this._mk || epoch !== this.epoch || owner !== (this._wb?.vault ? this._wb._vaultGeneration : this._wb?._session)) throw sdkError('the room or account changed during the read', 'account_changed')
2352
2424
  if (cfg && typeof cfg.lanes === 'boolean') this._lanesSetting = cfg.lanes
2353
- if (!cfg || typeof cfg !== 'object') { const err = new Error("witbitz: could not read this Space's gate (its sealed config did not load) — try again"); err.code = 'config_unavailable'; throw err }
2354
2425
  // A gated room answers a caller who has not signed in with only { admission: 'email', gated: true } — not the config.
2355
2426
  // That stub is never cached, so the read after sign-in gets the real one.
2356
- if (cfg.gated === true && !cfg.allow) { if (!this._gated) { this._gated = true; if (this._announced) this._announce() } const me = await this._signedInEmail(); const e = new Error(me ? `witbitz: this Space is email-gated and ${me} is not on its list — only its members read its gate` : 'witbitz: this Space is email-gated — sign in (' + signInHow(this._wb) + ') to read its gate'); e.code = 'sign_in_required'; throw e } // signed in but not admitted: the server answers the same stub, and "sign in" was wrong there (sync sweep 11-14 P7: a signed-in vault)
2427
+ if (cfg?.gated === true && !cfg.allow) { if (!this._gated) { this._gated = true; if (this._announced) this._announce() } const me = await this._signedInEmail(); const e = new Error(me ? `witbitz: this Space is email-gated and ${me} is not on its list — only its members read its gate` : 'witbitz: this Space is email-gated — sign in (' + signInHow(this._wb) + ') to read its gate'); e.code = 'sign_in_required'; throw e } // signed in but not admitted: the server answers the same stub, and "sign in" was wrong there (sync sweep 11-14 P7: a signed-in vault)
2428
+ // A known email gate cannot become open on an incomplete policy read. Leave it uncached for the next lookup.
2429
+ if (!cfg || typeof cfg !== 'object' || (this._gated && cfg.admission !== 'email')) {
2430
+ throw sdkError("witbitz: could not read this Space's gate (its sealed config did not load) — try again", 'config_unavailable')
2431
+ }
2357
2432
  this._gateOwner = owner
2358
- this._gateCfg = cfg // the gate is sealed at creation and never changes in place (membership change = a new room)
2433
+ this._gateCfg = cfg // a membership rekey clears this cache
2359
2434
  if (cfg.admission === 'email' && !this._gated) { this._gated = true; if (this._announced) this._announce() } // a room that predates the link marker announces once its gate is read
2360
2435
  return cfg
2361
2436
  }
@@ -2677,7 +2752,9 @@ export class Space {
2677
2752
  const sess = this._wb && this._wb._session
2678
2753
  const me = this._wb && this._wb.vault ? String(((await this._wb.vault.whoami()) || {}).email || '') // in a vault, its signed-in member (sync sweep 10-15 #2)
2679
2754
  : sess && (!sess.exp || sess.exp > Date.now()) ? String(sess.email || '') : ''
2680
- const out = planChange(change, { cfg, me, lane: !!(this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)), activeLane: !!this._sharedRoom, checkData: checkDataSchema, gatedUnread, signIn: signInHow(this._wb) })
2755
+ const roles = rolesOf(cfg), tagged = !!(roles.ownerTags.length || roles.adminTags.length)
2756
+ const role = tagged && me ? (this._wb?.vault ? await this._wb.vault._c.roomAccount(this.room, 'roster', 'sessionRole') : await sessionRole(this, cfg, me)) : undefined
2757
+ const out = planChange(change, { cfg, me, role, lane: !!(this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)), activeLane: !!this._sharedRoom, checkData: checkDataSchema, gatedUnread, signIn: signInHow(this._wb) })
2681
2758
  if (out.how === 'in_place' && change.agent && change.agent.model && this._wb) { try { await this._wb._checkModel(change.agent.model) } catch (e) { return { how: 'refused', history: null, call: null, steps: out.steps, reason: String(e.message || e), code: e.code || 'invalid_model' } } }
2682
2759
  return out
2683
2760
  }
@@ -3243,7 +3320,12 @@ export class Lane extends Space {
3243
3320
  const canReadConfig = typeof from._client.getConfig === 'function'
3244
3321
  const cfg = canReadConfig ? await from._client.getConfig(from.room, from._mk, { plainMark: true }) : {}
3245
3322
  if (!cfg || gatedStub(cfg)) return { mirrored: 0 }
3246
- if (cfg.lanes === false) { from._lanesSetting = false; this._detachShared(); return { mirrored: 0 } }
3323
+ if (cfg.lanes === false) {
3324
+ from._lanesSetting = false; this._detachShared()
3325
+ // …and the account forgets the association, as the app's mirror does (deleteNegotiation) — a vault's lanes are its own (sync sweep 11-27 P1)
3326
+ if (this._wb && !this._wb.vault) disconnectRoomLanes(this._wb, from.room).catch(() => {})
3327
+ return { mirrored: 0 }
3328
+ }
3247
3329
  const all = (from.messages || []).filter((e) => e && !e.sys && !e.mcp && e.kind !== 'mcp' && e.kind !== 'fork' && (e.text || (Array.isArray(e.files) && e.files.length) || (Array.isArray(e.images) && e.images.length)))
3248
3330
  if (from._more || !(from._historyRead || from._hostDriven)) return { mirrored: 0 } // not the whole shared history yet (a failed page leaves _more false) // the shared room is still loading its pages: a cursor past what has arrived is not another history
3249
3331
  const anchorOf = e => e ? removedEntryKey(e) : null
@@ -3251,6 +3333,8 @@ export class Lane extends Space {
3251
3333
  const anchor = this._mirrorAnchor ? all.findIndex(e => anchorOf(e) === this._mirrorAnchor) : -1
3252
3334
  this._mirrorCursor = anchor + 1
3253
3335
  } // a cursor from another history: start over; the server's id-dedup makes it a resend, never a double
3336
+ const sharedAgent = typeof cfg.agentName === 'string' ? cfg.agentName.trim() : ''
3337
+ const addressedOf = (e) => (sharedAgent && e.self !== true && typeof e.text === 'string' && e.text.trimStart().toLowerCase().startsWith('@' + sharedAgent.toLowerCase()) ? { addressed: sharedAgent.slice(0, 80) } : {})
3254
3338
  const copyEntry = async e => ({
3255
3339
  sourceRoom: from.room,
3256
3340
  id: 'sh:' + (e.id || ('t' + e.ts)), // the entry id alone, no room prefix — stable across a fork (the app's rule)
@@ -3259,6 +3343,7 @@ export class Lane extends Space {
3259
3343
  ...(e.self && Array.isArray(e.sources) ? { sources: e.sources.slice(0, 12) } : {}),
3260
3344
  ...mirrorBy(from.room, e), // WHO WROTE IT, as the Space verified them — Block collapses their copy in the lane too (the app's mirrorLoop.js byOf; sync sweep 11-08)
3261
3345
  ...(Number.isFinite(e.ts) ? { ts: e.ts } : {}), ...(e.replyTo && e.replyTo.key ? { replyTo: e.replyTo } : {}), // when it was said, and what it answers (sync sweep, 2026-10-10)
3346
+ ...addressedOf(e), // the Space's assistant a person's line opens by addressing: the lane strips it before reading the direction (mirrorLoop.js)
3262
3347
  text: e.text, files: await withBytes(from, e.files), images: await withBytes(from, e.images),
3263
3348
  ...(e.removedByWitbitz ? { sourceRemoved: true } : {}),
3264
3349
  })
@@ -3686,7 +3771,12 @@ function refuseInVault(wb) {
3686
3771
  const vaultLiveLinks = new Set() // the lane links open in THIS page (Lane#link → _noteLink)
3687
3772
  const pairKey = (a, b) => [String(a), String(b)].sort().join('|')
3688
3773
  conn.on((ev) => {
3689
- if (ev?.ev === 'a2aChanged') refreshVaultA2AViews(conn, ev)
3774
+ if (ev?.ev === 'a2aChanged') {
3775
+ refreshVaultA2AViews(conn, ev)
3776
+ // an outside agent's lane given a new address in the vault: the page hears it as outside a vault (sdk-agents.md)
3777
+ const moved = Array.isArray(ev.addresses) ? ev.addresses.filter((l) => l && typeof l.room === 'string' && typeof l.cardUrl === 'string' && typeof l.mcpUrl === 'string').map(({ room, cardUrl, mcpUrl }) => ({ room, cardUrl, mcpUrl })) : []
3778
+ if (moved.length && typeof wb.a2a.onReaddressed === 'function') { try { wb.a2a.onReaddressed(moved) } catch { /* the app's callback */ } }
3779
+ }
3690
3780
  if (ev?.ev === 'siri' && ev.siri) wb._vaultSiri = { ...ev.siri, key: null }
3691
3781
  const expired = ev?.ev === 'signedOut' && ev.reason === 'expired'
3692
3782
  if (expired) wb.a2a._draftsSuspended = true
@@ -3979,12 +4069,18 @@ export class VaultSession {
3979
4069
  const enc = tierIsEnclave(tier) // the vault attests the enclave and keeps the key; the page only asks
3980
4070
  const split = splitKeyChoice(key) // the vault makes it through its app-half function (startVault({ appShare: true }))
3981
4071
  const wb = this._wb
3982
- if (direct !== undefined) { const who = await this._c.whoami(); admission = directAdmission(direct, admission, who && who.signedIn ? { email: who.email } : null, 'wb.vault.signIn') } // the vault's signed-in member
4072
+ let creator
4073
+ const readCreator = async () => {
4074
+ const who = await this._c.whoami({ forCreate: true })
4075
+ if (!who || typeof who.signedIn !== 'boolean' || !Number.isInteger(who.accountEpoch)) throw sdkError('The vault could not confirm the creating account. Update the vault and try again.', 'identity_unavailable')
4076
+ creator = { accountEpoch: who.accountEpoch, email: who.signedIn ? String(who.email).trim().toLowerCase() : '' }
4077
+ return who
4078
+ }
4079
+ if (direct !== undefined) { const who = await readCreator(); admission = directAdmission(direct, admission, who && who.signedIn ? { email: who.email } : null, 'wb.vault.signIn') } // the vault's signed-in member
3983
4080
  // THE CREATOR IS THE OWNER, as outside a vault (createSpace): the vault's signed-in member, when on the list and no owners given —
3984
4081
  // without it nobody could change the Space's members in place (changeMembers needs an owner or an admin)
3985
4082
  else if (admission && typeof admission === 'object' && Array.isArray(admission.emails) && !(Array.isArray(admission.owners) && admission.owners.length)) {
3986
- const who = await this._c.whoami()
3987
- if (!who || typeof who.signedIn !== 'boolean') throw sdkError('witbitz: the creating member could not be checked', 'identity_unavailable')
4083
+ const who = await readCreator()
3988
4084
  const me = who && who.signedIn ? String(who.email || '').trim().toLowerCase() : ''
3989
4085
  if (me && admission.emails.map((e) => String(e).trim().toLowerCase()).includes(me)) admission = { ...admission, owners: [me] }
3990
4086
  }
@@ -3999,7 +4095,7 @@ export class VaultSession {
3999
4095
  if (usernames === false && gate?.admission === 'email') cfg.usernames = false
4000
4096
  if (safeMedia === true) cfg.safeMedia = true // as outside a vault (sync sweep 2026-10-28: it was refused here while configure turned it on)
4001
4097
  if (lanes === true) cfg.lanes = true
4002
- const { room } = await this._c.create(cfg, enc || split ? { ...(enc ? { enclave: true } : {}), ...(split ? { split: true } : {}) } : undefined)
4098
+ const { room } = await this._c.create(cfg, enc || split || creator ? { ...(enc ? { enclave: true } : {}), ...(split ? { split: true } : {}), ...(creator ? { creator } : {}) } : undefined)
4003
4099
  if (enc) wb._enc.rooms.set(room, true)
4004
4100
  const made = refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, wb, gated: !!gate, lanes: lanes === true }))
4005
4101
  made.safeMedia._learn(safeMedia === true, 0) // a new room's setting is what it was made with, as outside a vault (sync sweep 2026-10-28…11-02: it read null)
@@ -4349,15 +4445,22 @@ class SiriAccount {
4349
4445
  // …and a restore() that landed while the push was out (a vault keep applying the account's merged Siri) is NOT
4350
4446
  // overwritten (sync sweep 2026-11-13 #2: the next keep pass then stamped the other devices' Spaces `gone` everywhere): the
4351
4447
  // change is made again on top of what landed and that is pushed — at most a few times, then the latest state stands.
4352
- _change(fn) {
4448
+ // `guard`: the Spaces this edit is about — when another device changed one of them while this edit was out, the edit is not made
4449
+ // again over it (a rename must not overwrite a newer rename; the app's siri.js editShows): `siri_conflict`
4450
+ _change(fn, { guard, guardDefault = false } = {}) {
4353
4451
  const generation = this._wb._archiveGeneration
4354
4452
  const run = async () => {
4355
4453
  if (generation !== this._wb._archiveGeneration) throw sdkError('Account changed before Siri setup', 'account_changed')
4356
4454
  let out
4455
+ const guarded = (st) => JSON.stringify([guardDefault ? st.defaultRoom || '' : '', ...(guard || []).map(room => st.rooms[room] || null)])
4456
+ const began = guarded(this._wb._siri)
4457
+ const stagedRemovals = new Set()
4357
4458
  for (let i = 0; i < 4; i++) {
4358
4459
  const account = await this._wb._account(), base = this._wb._siri
4460
+ const conflict = !!(i && guard && guarded(base) !== began) // pushed as it now stands (the Sentinel took this edit's copy), then said
4359
4461
  const next = siriStateOf(JSON.parse(JSON.stringify(base)))
4360
- const pending = next.pendingRemovals || []
4462
+ // A restore can carry this attempt's local retry marker along with the newer room.
4463
+ const pending = (next.pendingRemovals || []).filter(id => !conflict || !stagedRemovals.has(id))
4361
4464
  const priorSetup = next.pendingSetup, rotation = next.pendingRotation
4362
4465
  delete next.pendingRotation
4363
4466
  delete next.pendingSetup
@@ -4374,15 +4477,18 @@ class SiriAccount {
4374
4477
  if (next.defaultRoom === room) next.defaultRoom = ''
4375
4478
  }
4376
4479
  if (rotation) next.token = rotation.to
4377
- out = await fn(next, rotation)
4378
- if (out === NO_SIRI_CHANGE && !pending.length && !priorSetup && !rotation) return out
4480
+ out = conflict ? NO_SIRI_CHANGE : await fn(next, rotation)
4481
+ if (out === NO_SIRI_CHANGE && !pending.length && !priorSetup && !rotation && !conflict) return out
4379
4482
  if (generation !== this._wb._archiveGeneration || account !== await this._wb._account()) throw sdkError('Account changed during Siri setup', 'account_changed')
4380
4483
  const removed = Object.keys(base.rooms).filter(room => !next.rooms[room])
4381
4484
  const added = Object.entries(next.rooms).filter(([id]) => !base.rooms[id])
4382
4485
  const stageLocal = !this._stageInbox && (removed.length || added.length || priorSetup || next.token !== base.token) && this._wb._siri === base
4383
4486
  if (stageLocal) {
4384
4487
  if (next.token !== base.token && (base.token || !added.length)) base.pendingRotation = { from: base.token, to: next.token }
4385
- if (removed.length) base.pendingRemovals = removed
4488
+ if (removed.length) {
4489
+ for (const id of removed) if (!pending.includes(id)) stagedRemovals.add(id)
4490
+ base.pendingRemovals = removed
4491
+ }
4386
4492
  if (added.length) base.pendingSetup = siriStateOf({ token: next.token, rooms: Object.fromEntries(added), defaultRoom: next.defaultRoom })
4387
4493
  else delete base.pendingSetup
4388
4494
  this._changed()
@@ -4405,7 +4511,11 @@ class SiriAccount {
4405
4511
  }
4406
4512
  if (generation !== this._wb._archiveGeneration || account !== await this._wb._account()) throw sdkError('Account changed during Siri setup', 'account_changed')
4407
4513
  finish?.(true)
4408
- if (this._wb._siri === base) { this._wb._siri = next; this._changed(); return out === NO_SIRI_CHANGE ? true : out }
4514
+ if (this._wb._siri === base) {
4515
+ this._wb._siri = next; this._changed()
4516
+ if (conflict) throw sdkError('Another device changed this Siri setting first — check it and try again.', 'siri_conflict')
4517
+ return out === NO_SIRI_CHANGE ? true : out
4518
+ }
4409
4519
  }
4410
4520
  throw sdkError('witbitz: the Siri state kept changing while it was being saved — try again', 'siri_busy')
4411
4521
  }
@@ -4452,6 +4562,8 @@ class SpaceSiri {
4452
4562
  const requested = normSiriAlias(alias)
4453
4563
  if (alias !== undefined && !requested) throw sdkError('witbitz: an alias is needed — the word you will say to Siri', 'invalid_argument')
4454
4564
  if (/[,:;]/.test(requested)) throw sdkError('witbitz: an alias cannot contain , : or ;', 'invalid_argument')
4565
+ const lane = includeAssistant && this._assistantRoom()
4566
+ const guardDefault = makeDefault || wb._siri.defaultRoom === sp.room
4455
4567
  return wb.siri._change(async (st) => { // kept only once the Sentinel took it (pass 9, K#5)
4456
4568
  const a = requested || st.rooms[sp.room]?.alias || uniqueAlias(label || sp.title || 'Space', new Set(Object.values(st.rooms).map(r => r.alias)))
4457
4569
  for (const [rm, r] of Object.entries(st.rooms)) if (rm !== sp.room && r.alias === a) throw sdkError(`witbitz: "${a}" already names another Space`, 'invalid_argument')
@@ -4459,15 +4571,14 @@ class SpaceSiri {
4459
4571
  const cur = st.rooms[sp.room]
4460
4572
  if (cur) st.rooms[sp.room] = { ...cur, alias: a, label: label || cur.label, at: Date.now() } // the newer copy wins a merge (sync sweep 2026-11-15 #7)
4461
4573
  else { const kp = await genRecipientKey(); st.rooms[sp.room] = { alias: a, label: String(label || ''), pub: { x: kp.publicJwk.x, y: kp.publicJwk.y }, priv: kp.privateJwk, at: Date.now() } }
4462
- const lane = includeAssistant && this._assistantRoom()
4463
4574
  if (lane && !st.rooms[lane]) {
4464
4575
  const taken = new Set(Object.values(st.rooms).map(r => r.alias))
4465
4576
  const assistantAlias = uniqueAlias(a.slice(0, 22) + ' assistant', taken), kp = await genRecipientKey()
4466
4577
  st.rooms[lane] = { alias: assistantAlias, label: (label || a) + ' · assistant', pub: { x: kp.publicJwk.x, y: kp.publicJwk.y }, priv: kp.privateJwk, at: Date.now() }
4467
4578
  }
4468
- if (makeDefault) st.defaultRoom = sp.room; else if (st.defaultRoom === sp.room) st.defaultRoom = ''
4579
+ if (makeDefault) st.defaultRoom = sp.room; else if (guardDefault && st.defaultRoom === sp.room) st.defaultRoom = ''
4469
4580
  return { key: st.token, endpoint: SIRI_ENDPOINT, alias: a }
4470
- })
4581
+ }, { guard: [sp.room, lane].filter(Boolean), guardDefault })
4471
4582
  }
4472
4583
  /** Disable Siri for this Space (other Spaces keep theirs). A push that fails rejects and keeps it on, here as at the Sentinel. */
4473
4584
  async disable({ includeAssistant = false } = {}) {
@@ -4478,7 +4589,7 @@ class SpaceSiri {
4478
4589
  for (const id of targets) delete st.rooms[id]
4479
4590
  if (targets.includes(st.defaultRoom)) st.defaultRoom = ''
4480
4591
  return true
4481
- })
4592
+ }, { guard: targets, guardDefault: true })
4482
4593
  return { disabled: r === true }
4483
4594
  }
4484
4595
  /** Collect: pull the account's drops, open the ones for THIS Space with its inbox key, post each as you (🎙-marked),