@witbitz/sdk 4.5.0 → 4.7.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
@@ -50,6 +50,8 @@ import { Speech, tokenPayer } from './sdkSpeech.js' // wb.speak(): text read alo
50
50
  import { Dictation, voiceForDictation } from './sdkDictation.js' // wb.dictation(): press-to-talk, the mic straight to Tinfoil's realtime enclave
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
+ 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)
53
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)
54
56
  import { deleteOwnRoom } from './roomDelete.js'
55
57
  import { sealTo, openBox, commit as keyCommit } from './e2ee.js'
@@ -199,7 +201,7 @@ const perTurn = (instructions) => (typeof instructions === 'string' && instructi
199
201
  /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
200
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)
201
203
  export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
202
- export const SDK_VERSION = '4.5.0'
204
+ export const SDK_VERSION = '4.7.0'
203
205
  // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
204
206
  const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
205
207
  /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
@@ -1077,6 +1079,9 @@ export class Witbitz {
1077
1079
  // A DIRECT CHAT (the Spaces app's, directChat.js): a verified Space with exactly you and one other person, you its owner,
1078
1080
  // `direct: true` sealed in — the server refuses its rename and each side calls it by the other person (space.directPeer).
1079
1081
  if (direct !== undefined) admission = directAdmission(direct, admission, this._session)
1082
+ // The account this create began under: a restore or sign-in that lands while the room is being made — the invitee lookups below
1083
+ // 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).
1084
+ const began = { generation: this._archiveGeneration, email: this._session?.email || '', master: this.backup._s?.master || null }
1080
1085
  // ★ THE CREATOR IS THE OWNER, as in the app (space.js gatedBase; docs/verified-room-members.md): a verified room names its
1081
1086
  // signed-in creator as its first owner when they are on its list and no owners were given — authority then follows that
1082
1087
  // email onto every device (sync sweep, 10-12). Not on the list, or not signed in: unchanged (an owner who cannot open it
@@ -1085,12 +1090,10 @@ export class Witbitz {
1085
1090
  const listed = admission && typeof admission === 'object' && Array.isArray(admission.emails) ? admission.emails.map((e) => String(e).trim().toLowerCase()) : []
1086
1091
  if (me && listed.includes(me) && !(Array.isArray(admission.owners) && admission.owners.length)) admission = { ...admission, owners: [me] } }
1087
1092
  const gate = normAdmission(admission)
1093
+ if (gate && direct === undefined) await this._addAsPreferred(gate)
1088
1094
  const enc = tierIsEnclave(tier)
1089
1095
  const split = splitKeyChoice(key)
1090
1096
  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' })
1091
- // The account this create began under: a restore or sign-in that lands while the room is being made must not have the new
1092
- // room's link recorded in ITS backup (side sweep: sdk-pending-create-follows-account-switch).
1093
- const began = { generation: this._archiveGeneration, email: this._session?.email || '', master: this.backup._s?.master || null }
1094
1097
  await this._checkModel(model || agent.model)
1095
1098
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
1096
1099
  applySkills(cfg, skills)
@@ -1106,6 +1109,7 @@ export class Witbitz {
1106
1109
  if (!(all && all.tempRooms)) throw sdkError('witbitz: temporary rooms are not available on this deployment', 'temporary_unavailable')
1107
1110
  cfg.room = newRoomId(cfg.region, { prefix: 'tmp' }) // the whole stack keys off the prefix (the app's tempRooms.js mints the same shape)
1108
1111
  }
1112
+ if (gate) await this._rolesAsPreferred(cfg) // owners and admins who prefer their @username are named by its tag (§ 13.1)
1109
1113
  // Attest FIRST (a configuration failure is loud, a cold enclave is not — _encAttestSoft); mint; only then wake and hand
1110
1114
  // the enclave its config.
1111
1115
  if (enc) await this._encAttestSoft()
@@ -1129,6 +1133,60 @@ export class Witbitz {
1129
1133
  return made // an enclave room's link says so, or a fresh client cannot know (see ENC_MARK)
1130
1134
  }
1131
1135
 
1136
+ /** @private "ADD ME TO SPACES AS @USERNAME" (docs/spaces-usernames.md § 13): a new Space's HIDDEN addresses — not yours, not an owner's or
1137
+ * an admin's (roles name an email), not advertised — whose person prefers their @username (the email door names it, only where
1138
+ * "find me by email" is on) go on the list as that name's tag (spaceClient create's `tagUsers`): the other members never get the
1139
+ * email. Changes `gate` in place; any lookup that fails leaves the address as it was. */
1140
+ async _addAsPreferred(gate) {
1141
+ const al = gate && gate.allow
1142
+ if (!al || gate.admission !== 'email') return
1143
+ const me = String(this._session?.email || '').trim().toLowerCase()
1144
+ const managers = new Set([...((gate.owners && gate.owners.emails) || []), ...((gate.admins && gate.admins.emails) || [])])
1145
+ const field = Array.isArray(al.hidden) ? 'hidden' : 'emails' // with `hidden`, `emails` are the advertised ones (normAdmission)
1146
+ const cand = (al[field] || []).filter((e) => e !== me && !managers.has(e))
1147
+ if (!cand.length) return
1148
+ const pref = await preferredAddresses(cand, { client: this._client }).catch(() => null)
1149
+ const learned = (pref && pref.learned) || []
1150
+ if (!learned.length) return
1151
+ const conv = new Set(learned.map((x) => x.email))
1152
+ al[field] = al[field].filter((e) => !conv.has(e))
1153
+ al.tagUsers = [...new Set([...(al.tagUsers || []), ...learned.map((x) => x.username)])]
1154
+ }
1155
+
1156
+ /** @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
1157
+ * address is HIDDEN (not advertised) and who prefers their @username — the signed-in creator by whoami, anyone else past the email door
1158
+ * (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
1159
+ * both. Only where the server takes tag roles (roomRoles.roleTagFor: `roles: true`); otherwise the role names the email, as before.
1160
+ * 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. */
1161
+ async _rolesAsPreferred(cfg) {
1162
+ const al = cfg && cfg.admission === 'email' && cfg.allow
1163
+ if (!al) return
1164
+ const lc = (x) => String(x || '').trim().toLowerCase()
1165
+ const hidden = new Set((Array.isArray(al.hidden) ? al.hidden : (al.emails || [])).map(lc)) // with `hidden`, `emails` are the advertised ones (normAdmission)
1166
+ 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))
1167
+ if (!mgr.length) return
1168
+ const me = lc(this._session && !(this._session.exp && this._session.exp <= Date.now()) ? this._session.email : '')
1169
+ const people = []
1170
+ if (me && mgr.some((m) => m.email === me)) {
1171
+ const w = await this.usernames.mine().catch(() => null)
1172
+ if (w && w.username && w.addAsUsername !== false) people.push(...mgr.filter((m) => m.email === me).map((m) => ({ ...m, username: w.username })))
1173
+ }
1174
+ const others = mgr.filter((m) => m.email !== me)
1175
+ if (others.length) {
1176
+ const pref = await preferredAddresses([...new Set(others.map((m) => m.email))], { client: this._client }).catch(() => null)
1177
+ const name = new Map(((pref && pref.learned) || []).map((x) => [x.email, x.username]))
1178
+ for (const m of others) if (name.has(m.email)) people.push({ ...m, username: name.get(m.email) })
1179
+ }
1180
+ if (!people.length) return
1181
+ const room = cfg.room || newRoomId(cfg.region)
1182
+ const pr = await placeRoles({ room, owners: cfg.owners, admins: cfg.admins, allow: al }, people, { client: this._client }).catch(() => null)
1183
+ if (!pr || !pr.placed.length) return
1184
+ cfg.room = room
1185
+ cfg.allow = pr.allow
1186
+ cfg.owners = pr.owners
1187
+ if (cfg.admins || pr.admins.emails.length || pr.admins.tags) cfg.admins = pr.admins
1188
+ }
1189
+
1132
1190
  /** @private how a split room is created: through the builder's function when there is one (`via`), else here. */
1133
1191
  setAssistantMemory(spaces = []) {
1134
1192
  if (!Array.isArray(spaces) || spaces.length > LIMITS.links + 1) throw sdkError('witbitz: choose a bounded list of Spaces for assistant memory', 'invalid_argument')
@@ -1833,7 +1891,11 @@ export class Space {
1833
1891
  const rows = await this._wb.models({ tier: this._isEnclave() ? 'enclave' : 'standard' })
1834
1892
  const row = (rows || []).find((m) => m && m.id === id)
1835
1893
  if (!row) throw sdkError(`witbitz: ${JSON.stringify(id)} is not a model offered for this Space — see wb.models()`, 'unknown_model')
1836
- const pick = { catalog: String(row.id), wire: String(row.wire || ''), label: String(row.label || '') }
1894
+ // 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
1895
+ await this._freshSettings()
1896
+ const was = this._modelPick, efforts = Array.isArray(row.efforts) ? row.efforts.map(String) : []
1897
+ const effort = was && was.effort && efforts.includes(String(was.effort)) ? String(was.effort) : ''
1898
+ const pick = { catalog: String(row.id), wire: String(row.wire || ''), label: String(row.label || ''), ...(effort ? { effort } : {}) }
1837
1899
  this._modelGen = (this._modelGen || 0) + 1
1838
1900
  const r = await this._client.state(this.room, this._mk, 'model', modelDocOf(pick), pick.label || pick.catalog)
1839
1901
  if (!r || r.status !== 200) throw refused('setModel', r)
@@ -2004,7 +2066,10 @@ export class Space {
2004
2066
  if (this._wb?.vault) return this._wb.vault._c.roomAccount(this.room, 'portable', 'export')
2005
2067
  const { saveRoomExport } = await import('./sdkExports.js')
2006
2068
  const generation = this._wb?._archiveGeneration
2007
- return saveRoomExport(this, this._wb?._enc?.rooms.has(this.room) || ENC_MARK.test(this.shareLink || '') ? 'enclave' : 'standard', () => this._wb?._archiveGeneration === generation)
2069
+ // a linked continuation's earlier versions: read with the keys this account's rooms carry (their saved links)
2070
+ const keys = {}
2071
+ 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 }
2072
+ return saveRoomExport(this, this._wb?._enc?.rooms.has(this.room) || ENC_MARK.test(this.shareLink || '') ? 'enclave' : 'standard', () => this._wb?._archiveGeneration === generation, this.title, keys)
2008
2073
  }
2009
2074
  async sealedProof() {
2010
2075
  if (!(this._client && this._client.vault)) this._needKey('sealedProof') // a vault reads the stored boxes for the page (ciphertext only)
@@ -2275,7 +2340,18 @@ export class Space {
2275
2340
  }
2276
2341
  }
2277
2342
  }
2278
- 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)
2343
+ // 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
2344
+ // it — `ownerTags` / `adminTags` (what changeMembers takes back), and `ownerUsers` / `adminUsers`: the @usernames of those the guest book
2345
+ // 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.
2346
+ const rt = rolesOf(cfg)
2347
+ let tagRoles = {}
2348
+ if (rt.ownerTags.length || rt.adminTags.length) {
2349
+ const book = await Promise.resolve().then(() => this._client.state(this.room, this._mk, ROSTER_DOC)).catch(() => null)
2350
+ 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()
2351
+ const names = (tags) => [...new Set(tags.map((t) => held.get(t) && held.get(t).user).filter(Boolean).map((u) => '@' + u))]
2352
+ tagRoles = { ownerTags: rt.ownerTags, adminTags: rt.adminTags, ownerUsers: names(rt.ownerTags), adminUsers: names(rt.adminTags) }
2353
+ }
2354
+ 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)
2279
2355
  }
2280
2356
 
2281
2357
  /** Is `email` one of this room's ADMINS? The room enforces it (2026-10-02): with admins, only they change the
@@ -2286,7 +2362,16 @@ export class Space {
2286
2362
  const e = String(email || '').trim().toLowerCase()
2287
2363
  const cfg = await this._gateConfig({ plainMark: true })
2288
2364
  const has = (o) => !!(o && Array.isArray(o.emails) && o.emails.some((x) => String(x).trim().toLowerCase() === e))
2289
- return has(cfg.admins) || has(cfg.owners) // an owner is an admin
2365
+ 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)
2366
+ }
2367
+
2368
+ /** @private A role held by an @username's tag (docs/spaces-usernames.md § 13.1): `who` = '@name' → 'owner' | 'admin' | ''. */
2369
+ async _roleByTag(cfg, who) {
2370
+ const rt = rolesOf(cfg)
2371
+ if (!String(who).startsWith('@') || !(rt.ownerTags.length || rt.adminTags.length) || typeof this._client.userTag !== 'function') return ''
2372
+ const t = await this._client.userTag(String(who).slice(1), this.room).catch(() => null)
2373
+ const tag = t && t.status === 200 ? t.tag : ''
2374
+ return !tag ? '' : rt.ownerTags.includes(tag) ? 'owner' : rt.adminTags.includes(tag) ? 'admin' : ''
2290
2375
  }
2291
2376
 
2292
2377
  /** Is `email` one of this room's OWNERS (a level above admins, enforced by the room)? An owner can do all an admin can,
@@ -2294,7 +2379,7 @@ export class Space {
2294
2379
  async isOwner(email) {
2295
2380
  const e = String(email || '').trim().toLowerCase()
2296
2381
  const cfg = await this._gateConfig({ plainMark: true })
2297
- return !!(cfg.owners && Array.isArray(cfg.owners.emails) && cfg.owners.emails.some((x) => String(x).trim().toLowerCase() === e))
2382
+ 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)
2298
2383
  }
2299
2384
 
2300
2385
  /** Does this Space's gate admit `email`? Checked on this device against the sealed list: an advertised address, a
@@ -3221,7 +3306,12 @@ export class Lane extends Space {
3221
3306
  const canReadConfig = typeof from._client.getConfig === 'function'
3222
3307
  const cfg = canReadConfig ? await from._client.getConfig(from.room, from._mk, { plainMark: true }) : {}
3223
3308
  if (!cfg || gatedStub(cfg)) return { mirrored: 0 }
3224
- if (cfg.lanes === false) { from._lanesSetting = false; this._detachShared(); return { mirrored: 0 } }
3309
+ if (cfg.lanes === false) {
3310
+ from._lanesSetting = false; this._detachShared()
3311
+ // …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)
3312
+ if (this._wb && !this._wb.vault) disconnectRoomLanes(this._wb, from.room).catch(() => {})
3313
+ return { mirrored: 0 }
3314
+ }
3225
3315
  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)))
3226
3316
  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
3227
3317
  const anchorOf = e => e ? removedEntryKey(e) : null
@@ -3229,6 +3319,8 @@ export class Lane extends Space {
3229
3319
  const anchor = this._mirrorAnchor ? all.findIndex(e => anchorOf(e) === this._mirrorAnchor) : -1
3230
3320
  this._mirrorCursor = anchor + 1
3231
3321
  } // a cursor from another history: start over; the server's id-dedup makes it a resend, never a double
3322
+ const sharedAgent = typeof cfg.agentName === 'string' ? cfg.agentName.trim() : ''
3323
+ const addressedOf = (e) => (sharedAgent && e.self !== true && typeof e.text === 'string' && e.text.trimStart().toLowerCase().startsWith('@' + sharedAgent.toLowerCase()) ? { addressed: sharedAgent.slice(0, 80) } : {})
3232
3324
  const copyEntry = async e => ({
3233
3325
  sourceRoom: from.room,
3234
3326
  id: 'sh:' + (e.id || ('t' + e.ts)), // the entry id alone, no room prefix — stable across a fork (the app's rule)
@@ -3237,6 +3329,7 @@ export class Lane extends Space {
3237
3329
  ...(e.self && Array.isArray(e.sources) ? { sources: e.sources.slice(0, 12) } : {}),
3238
3330
  ...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)
3239
3331
  ...(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)
3332
+ ...addressedOf(e), // the Space's assistant a person's line opens by addressing: the lane strips it before reading the direction (mirrorLoop.js)
3240
3333
  text: e.text, files: await withBytes(from, e.files), images: await withBytes(from, e.images),
3241
3334
  ...(e.removedByWitbitz ? { sourceRemoved: true } : {}),
3242
3335
  })
@@ -3598,20 +3691,32 @@ class Usernames {
3598
3691
  if (!r || r.status !== 200) throw userError(r, 'could not release the username')
3599
3692
  return { username: null }
3600
3693
  }
3601
- /** → { username: string | null, published } */
3694
+ /** → { username: string | null, published, addAsUsername } — addAsUsername: "Add me to Spaces as @username" (on unless switched off) */
3602
3695
  async mine() {
3603
3696
  const { idToken } = this._wb._auth('a username belongs')
3604
3697
  const r = await this._wb._client.userWhoami(idToken)
3605
3698
  if (!r || r.status !== 200) throw userError(r, 'could not read the username')
3606
- return { username: r.username || null, published: r.published === true }
3699
+ return { username: r.username || null, published: r.published === true, addAsUsername: r.asUser !== false }
3700
+ }
3701
+ /** "ADD ME TO SPACES AS @USERNAME" (docs/spaces-usernames.md § 13): how the signed-in member is added and shown — by their @username
3702
+ * (true, the default once they have one) or by their email (false). Published with the name, so other people's apps honour it: an
3703
+ * adder who types the email adds them as @username (only where "find me by email" is on), and the other members see the @username,
3704
+ * not the email. → { addAsUsername } */
3705
+ async addAsUsername(on) {
3706
+ if (typeof on !== 'boolean') throw sdkError('witbitz: addAsUsername takes true or false', 'invalid_argument')
3707
+ const { idToken } = this._wb._auth('a username belongs')
3708
+ if (typeof this._wb._client.userAsUser !== 'function') throw sdkError('witbitz: addAsUsername is not available on this client', 'not_supported')
3709
+ const r = await this._wb._client.userAsUser(on, idToken)
3710
+ if (!r || r.status !== 200) throw userError(r, 'could not change how you are added')
3711
+ return { addAsUsername: r.asUser !== false }
3607
3712
  }
3608
- /** Is this @name taken? Public, rate-limited, no sign-in. → { username, exists } */
3713
+ /** Is this @name taken? Public, rate-limited, no sign-in. → { username, exists, addAsUsername? } */
3609
3714
  async resolve(name) {
3610
3715
  const u = bareName(name)
3611
3716
  const r = await this._wb._client.userResolve(u)
3612
3717
  if (r && r.status === 404) return { username: u, exists: false }
3613
3718
  if (!r || r.status !== 200) throw userError(r, `could not look up @${u}`)
3614
- return { username: r.username || u, exists: true }
3719
+ return { username: r.username || u, exists: true, ...(typeof r.asUser === 'boolean' ? { addAsUsername: r.asUser } : {}) }
3615
3720
  }
3616
3721
  }
3617
3722
  const bareName = (n) => String(n || '').trim().replace(/^@/, '').toLowerCase()
@@ -3652,7 +3757,12 @@ function refuseInVault(wb) {
3652
3757
  const vaultLiveLinks = new Set() // the lane links open in THIS page (Lane#link → _noteLink)
3653
3758
  const pairKey = (a, b) => [String(a), String(b)].sort().join('|')
3654
3759
  conn.on((ev) => {
3655
- if (ev?.ev === 'a2aChanged') refreshVaultA2AViews(conn, ev)
3760
+ if (ev?.ev === 'a2aChanged') {
3761
+ refreshVaultA2AViews(conn, ev)
3762
+ // an outside agent's lane given a new address in the vault: the page hears it as outside a vault (sdk-agents.md)
3763
+ 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 })) : []
3764
+ if (moved.length && typeof wb.a2a.onReaddressed === 'function') { try { wb.a2a.onReaddressed(moved) } catch { /* the app's callback */ } }
3765
+ }
3656
3766
  if (ev?.ev === 'siri' && ev.siri) wb._vaultSiri = { ...ev.siri, key: null }
3657
3767
  const expired = ev?.ev === 'signedOut' && ev.reason === 'expired'
3658
3768
  if (expired) wb.a2a._draftsSuspended = true
@@ -4315,13 +4425,18 @@ class SiriAccount {
4315
4425
  // …and a restore() that landed while the push was out (a vault keep applying the account's merged Siri) is NOT
4316
4426
  // overwritten (sync sweep 2026-11-13 #2: the next keep pass then stamped the other devices' Spaces `gone` everywhere): the
4317
4427
  // change is made again on top of what landed and that is pushed — at most a few times, then the latest state stands.
4318
- _change(fn) {
4428
+ // `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
+ // again over it (a rename must not overwrite a newer rename; the app's siri.js editShows): `siri_conflict`
4430
+ _change(fn, { guard } = {}) {
4319
4431
  const generation = this._wb._archiveGeneration
4320
4432
  const run = async () => {
4321
4433
  if (generation !== this._wb._archiveGeneration) throw sdkError('Account changed before Siri setup', 'account_changed')
4322
4434
  let out
4435
+ const guarded = (st) => JSON.stringify((guard || []).map((room) => st.rooms[room] || null))
4436
+ const began = guarded(this._wb._siri)
4323
4437
  for (let i = 0; i < 4; i++) {
4324
4438
  const account = await this._wb._account(), base = this._wb._siri
4439
+ const conflict = !!(i && guard && guarded(base) !== began) // pushed as it now stands (the Sentinel took this edit's copy), then said
4325
4440
  const next = siriStateOf(JSON.parse(JSON.stringify(base)))
4326
4441
  const pending = next.pendingRemovals || []
4327
4442
  const priorSetup = next.pendingSetup, rotation = next.pendingRotation
@@ -4340,8 +4455,8 @@ class SiriAccount {
4340
4455
  if (next.defaultRoom === room) next.defaultRoom = ''
4341
4456
  }
4342
4457
  if (rotation) next.token = rotation.to
4343
- out = await fn(next, rotation)
4344
- if (out === NO_SIRI_CHANGE && !pending.length && !priorSetup && !rotation) return out
4458
+ out = conflict ? NO_SIRI_CHANGE : await fn(next, rotation)
4459
+ if (out === NO_SIRI_CHANGE && !pending.length && !priorSetup && !rotation && !conflict) return out
4345
4460
  if (generation !== this._wb._archiveGeneration || account !== await this._wb._account()) throw sdkError('Account changed during Siri setup', 'account_changed')
4346
4461
  const removed = Object.keys(base.rooms).filter(room => !next.rooms[room])
4347
4462
  const added = Object.entries(next.rooms).filter(([id]) => !base.rooms[id])
@@ -4371,7 +4486,11 @@ class SiriAccount {
4371
4486
  }
4372
4487
  if (generation !== this._wb._archiveGeneration || account !== await this._wb._account()) throw sdkError('Account changed during Siri setup', 'account_changed')
4373
4488
  finish?.(true)
4374
- if (this._wb._siri === base) { this._wb._siri = next; this._changed(); return out === NO_SIRI_CHANGE ? true : out }
4489
+ if (this._wb._siri === base) {
4490
+ this._wb._siri = next; this._changed()
4491
+ if (conflict) throw sdkError('Another device changed this Siri setting first — check it and try again.', 'siri_conflict')
4492
+ return out === NO_SIRI_CHANGE ? true : out
4493
+ }
4375
4494
  }
4376
4495
  throw sdkError('witbitz: the Siri state kept changing while it was being saved — try again', 'siri_busy')
4377
4496
  }
@@ -4433,7 +4552,7 @@ class SpaceSiri {
4433
4552
  }
4434
4553
  if (makeDefault) st.defaultRoom = sp.room; else if (st.defaultRoom === sp.room) st.defaultRoom = ''
4435
4554
  return { key: st.token, endpoint: SIRI_ENDPOINT, alias: a }
4436
- })
4555
+ }, { guard: [sp.room] })
4437
4556
  }
4438
4557
  /** Disable Siri for this Space (other Spaces keep theirs). A push that fails rejects and keeps it on, here as at the Sentinel. */
4439
4558
  async disable({ includeAssistant = false } = {}) {