@witbitz/sdk 4.7.0 → 4.8.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.
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,7 +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 { placeRoles, roleEmails, rolesOf, roleTagHolders } from './roomRoles.js' // owners and admins by @username tag (docs/spaces-usernames.md § 13.1)
54
+ import { signedInRoomTags, placeRoles, roleEmails, rolesOf, roleTagHolders } from './roomRoles.js' // owners and admins by @username tag (docs/spaces-usernames.md § 13.1)
55
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)
56
56
  import { deleteOwnRoom } from './roomDelete.js'
57
57
  import { sealTo, openBox, commit as keyCommit } from './e2ee.js'
@@ -201,7 +201,7 @@ const perTurn = (instructions) => (typeof instructions === 'string' && instructi
201
201
  /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
202
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)
203
203
  export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
204
- export const SDK_VERSION = '4.7.0'
204
+ export const SDK_VERSION = '4.8.0'
205
205
  // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
206
206
  const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
207
207
  /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
@@ -1038,13 +1038,20 @@ export class Witbitz {
1038
1038
  if (this.vault) return this.vault._c.account('backup', 'exportArchive', recoveryKeys === true, rooms?.map(sp => sp.room), ...(destination === 'clipboard' ? [destination] : []))
1039
1039
  const { saveAccountArchive } = await import('./sdkExports.js')
1040
1040
  const session = this._session, generation = this._archiveGeneration, backup = this.backup._s
1041
- 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 }]))
1042
1043
  const opened = [...(this._archiveHandles || [])].filter(sp => sp._archiveGeneration === this._archiveGeneration && sp._archiveEmail === (session?.email || '') && sp._archiveMaster === (backup?.master || null))
1043
1044
  if (rooms?.some(sp => !opened.includes(sp))) throw sdkError('select Spaces opened for this account', 'invalid_argument')
1044
1045
  for (const sp of rooms ?? opened) {
1045
1046
  if (!sp || sp._wb !== this || sp._stopped || !sp.shareLink) throw sdkError('select open Spaces from this SDK client', 'invalid_argument')
1046
1047
  selected.set(sp.room, { room: sp.room, link: sp.shareLink, title: sp.title, held: sp })
1047
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
+ }
1048
1055
  return saveAccountArchive([...selected.values()], async (r, keysOnly, attachments) => {
1049
1056
  const { room, mk } = r.held?._mk ? { room: r.room, mk: r.held._mk } : await this._openLink(r.link)
1050
1057
  if (room !== r.room) throw sdkError('witbitz: a saved link opens another Space', 'wrong_room')
@@ -1052,7 +1059,7 @@ export class Witbitz {
1052
1059
  const saved = await this._client.exportSealed(room, mk, { attachments }) // + the stored attachments, sealed (sdkExports.js)
1053
1060
  if (saved?.status !== 200) throw sdkError('witbitz: this Space\u2019s history could not be read just now', 'unavailable')
1054
1061
  return { key: mk, ledger: saved.sealed, count: saved.count, attachments: saved.attachments }
1055
- }, recoveryKeys === true, () => this._archiveGeneration === generation && (this.backup._s?.master || null) === (backup?.master || null), destination)
1062
+ }, recoveryKeys === true, current, destination)
1056
1063
  }
1057
1064
  async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, usernames, safeMedia, lanes, owner } = {}) {
1058
1065
  // A TEMPORARY ROOM (docs/visitor-limits.md): a `tmp-` room the deployment wipes when it is idle — `true`: after about half
@@ -1314,7 +1321,7 @@ export class Witbitz {
1314
1321
  const config = await this._client.getConfig(room, mk, { plainMark: true })
1315
1322
  if (current() && (config?.help || config?.lane || config?.bridge)) return { excluded: true }
1316
1323
  const v = await readAllPages(since => this._client.poll(room, mk, undefined, since))
1317
- 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
1318
1325
  },
1319
1326
  prepare: room => remove(room, { check: true, reviewPolicy: true }),
1320
1327
  deleteOnServer: (room, reviewedEtag, reviewedPolicy) => remove(room, { reviewedEtag, reviewedPolicy }),
@@ -2359,6 +2366,7 @@ export class Space {
2359
2366
  * connection. A non-admin's attempt is refused
2360
2367
  * with `code: 'not_admin'`. A room without admins has none (every member may do all of it, as before). */
2361
2368
  async isAdmin(email) {
2369
+ if (this._wb?.vault && String(email || '').trim().startsWith('@')) return this._wb.vault._c.roomAccount(this.room, 'roster', 'isAdmin', email)
2362
2370
  const e = String(email || '').trim().toLowerCase()
2363
2371
  const cfg = await this._gateConfig({ plainMark: true })
2364
2372
  const has = (o) => !!(o && Array.isArray(o.emails) && o.emails.some((x) => String(x).trim().toLowerCase() === e))
@@ -2377,6 +2385,7 @@ export class Space {
2377
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,
2378
2386
  * and only an owner can change the owners or lower or remove an admin when the room is moved ({@link Space#fork}). */
2379
2387
  async isOwner(email) {
2388
+ if (this._wb?.vault && String(email || '').trim().startsWith('@')) return this._wb.vault._c.roomAccount(this.room, 'roster', 'isOwner', email)
2380
2389
  const e = String(email || '').trim().toLowerCase()
2381
2390
  const cfg = await this._gateConfig({ plainMark: true })
2382
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)
@@ -2409,16 +2418,19 @@ export class Space {
2409
2418
  async _gateConfig({ fresh = false, plainMark = false } = {}) {
2410
2419
  const owner = this._wb?.vault ? this._wb._vaultGeneration : this._wb?._session
2411
2420
  const key = this._mk, epoch = this.epoch
2412
- 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
2413
2422
  const cfg = typeof this._client.getConfig === 'function' ? await this._client.getConfig(this.room, this._mk, plainMark ? { plainMark: true } : undefined) : null
2414
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')
2415
2424
  if (cfg && typeof cfg.lanes === 'boolean') this._lanesSetting = cfg.lanes
2416
- 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 }
2417
2425
  // A gated room answers a caller who has not signed in with only { admission: 'email', gated: true } — not the config.
2418
2426
  // That stub is never cached, so the read after sign-in gets the real one.
2419
- 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
+ }
2420
2432
  this._gateOwner = owner
2421
- 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
2422
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
2423
2435
  return cfg
2424
2436
  }
@@ -2740,7 +2752,9 @@ export class Space {
2740
2752
  const sess = this._wb && this._wb._session
2741
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)
2742
2754
  : sess && (!sess.exp || sess.exp > Date.now()) ? String(sess.email || '') : ''
2743
- 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) })
2744
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' } } }
2745
2759
  return out
2746
2760
  }
@@ -4055,12 +4069,18 @@ export class VaultSession {
4055
4069
  const enc = tierIsEnclave(tier) // the vault attests the enclave and keeps the key; the page only asks
4056
4070
  const split = splitKeyChoice(key) // the vault makes it through its app-half function (startVault({ appShare: true }))
4057
4071
  const wb = this._wb
4058
- 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
4059
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 —
4060
4081
  // without it nobody could change the Space's members in place (changeMembers needs an owner or an admin)
4061
4082
  else if (admission && typeof admission === 'object' && Array.isArray(admission.emails) && !(Array.isArray(admission.owners) && admission.owners.length)) {
4062
- const who = await this._c.whoami()
4063
- if (!who || typeof who.signedIn !== 'boolean') throw sdkError('witbitz: the creating member could not be checked', 'identity_unavailable')
4083
+ const who = await readCreator()
4064
4084
  const me = who && who.signedIn ? String(who.email || '').trim().toLowerCase() : ''
4065
4085
  if (me && admission.emails.map((e) => String(e).trim().toLowerCase()).includes(me)) admission = { ...admission, owners: [me] }
4066
4086
  }
@@ -4075,7 +4095,7 @@ export class VaultSession {
4075
4095
  if (usernames === false && gate?.admission === 'email') cfg.usernames = false
4076
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)
4077
4097
  if (lanes === true) cfg.lanes = true
4078
- 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)
4079
4099
  if (enc) wb._enc.rooms.set(room, true)
4080
4100
  const made = refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, wb, gated: !!gate, lanes: lanes === true }))
4081
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)
@@ -4427,18 +4447,20 @@ class SiriAccount {
4427
4447
  // change is made again on top of what landed and that is pushed — at most a few times, then the latest state stands.
4428
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
4429
4449
  // again over it (a rename must not overwrite a newer rename; the app's siri.js editShows): `siri_conflict`
4430
- _change(fn, { guard } = {}) {
4450
+ _change(fn, { guard, guardDefault = false } = {}) {
4431
4451
  const generation = this._wb._archiveGeneration
4432
4452
  const run = async () => {
4433
4453
  if (generation !== this._wb._archiveGeneration) throw sdkError('Account changed before Siri setup', 'account_changed')
4434
4454
  let out
4435
- const guarded = (st) => JSON.stringify((guard || []).map((room) => st.rooms[room] || null))
4455
+ const guarded = (st) => JSON.stringify([guardDefault ? st.defaultRoom || '' : '', ...(guard || []).map(room => st.rooms[room] || null)])
4436
4456
  const began = guarded(this._wb._siri)
4457
+ const stagedRemovals = new Set()
4437
4458
  for (let i = 0; i < 4; i++) {
4438
4459
  const account = await this._wb._account(), base = this._wb._siri
4439
4460
  const conflict = !!(i && guard && guarded(base) !== began) // pushed as it now stands (the Sentinel took this edit's copy), then said
4440
4461
  const next = siriStateOf(JSON.parse(JSON.stringify(base)))
4441
- 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))
4442
4464
  const priorSetup = next.pendingSetup, rotation = next.pendingRotation
4443
4465
  delete next.pendingRotation
4444
4466
  delete next.pendingSetup
@@ -4463,7 +4485,10 @@ class SiriAccount {
4463
4485
  const stageLocal = !this._stageInbox && (removed.length || added.length || priorSetup || next.token !== base.token) && this._wb._siri === base
4464
4486
  if (stageLocal) {
4465
4487
  if (next.token !== base.token && (base.token || !added.length)) base.pendingRotation = { from: base.token, to: next.token }
4466
- 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
+ }
4467
4492
  if (added.length) base.pendingSetup = siriStateOf({ token: next.token, rooms: Object.fromEntries(added), defaultRoom: next.defaultRoom })
4468
4493
  else delete base.pendingSetup
4469
4494
  this._changed()
@@ -4537,6 +4562,8 @@ class SpaceSiri {
4537
4562
  const requested = normSiriAlias(alias)
4538
4563
  if (alias !== undefined && !requested) throw sdkError('witbitz: an alias is needed — the word you will say to Siri', 'invalid_argument')
4539
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
4540
4567
  return wb.siri._change(async (st) => { // kept only once the Sentinel took it (pass 9, K#5)
4541
4568
  const a = requested || st.rooms[sp.room]?.alias || uniqueAlias(label || sp.title || 'Space', new Set(Object.values(st.rooms).map(r => r.alias)))
4542
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')
@@ -4544,15 +4571,14 @@ class SpaceSiri {
4544
4571
  const cur = st.rooms[sp.room]
4545
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)
4546
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() } }
4547
- const lane = includeAssistant && this._assistantRoom()
4548
4574
  if (lane && !st.rooms[lane]) {
4549
4575
  const taken = new Set(Object.values(st.rooms).map(r => r.alias))
4550
4576
  const assistantAlias = uniqueAlias(a.slice(0, 22) + ' assistant', taken), kp = await genRecipientKey()
4551
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() }
4552
4578
  }
4553
- 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 = ''
4554
4580
  return { key: st.token, endpoint: SIRI_ENDPOINT, alias: a }
4555
- }, { guard: [sp.room] })
4581
+ }, { guard: [sp.room, lane].filter(Boolean), guardDefault })
4556
4582
  }
4557
4583
  /** Disable Siri for this Space (other Spaces keep theirs). A push that fails rejects and keeps it on, here as at the Sentinel. */
4558
4584
  async disable({ includeAssistant = false } = {}) {
@@ -4563,7 +4589,7 @@ class SpaceSiri {
4563
4589
  for (const id of targets) delete st.rooms[id]
4564
4590
  if (targets.includes(st.defaultRoom)) st.defaultRoom = ''
4565
4591
  return true
4566
- })
4592
+ }, { guard: targets, guardDefault: true })
4567
4593
  return { disabled: r === true }
4568
4594
  }
4569
4595
  /** Collect: pull the account's drops, open the ones for THIS Space with its inbox key, post each as you (🎙-marked),