@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/sdkA2A.js CHANGED
@@ -28,7 +28,7 @@ import { readAllPages } from './ledgerView.js'
28
28
  import { sealTo as sealToEnclave } from './sealShare.js'
29
29
  // The rules — the record, letting a peer in, the Sentinel calls, opening a collected message — are a2aCore.js, which the
30
30
  // Spaces app's a2aLane.js shares. This module is the SDK's classes and storage around them.
31
- import { A2A_COLLECT_WINDOW_MS, finishedTask, replyNotDelivered, A2A_ENDPOINT, a2aTokenHash, cardUrlOf, mcpUrlOf, normA2A, mergeA2ARecords, peersOf, applyRemovals, removalIntents, pruneGoneIn, enableLaneIn, addPeerIn, setPeerReplyIn, removePeerIn, disableLaneIn, clearLanesIn, recordFor, withIntake, sentinelCalls, openItem, a2aMessage, a2aInstructions, isJobPeer } from './a2aCore.js'
31
+ import { A2A_COLLECT_WINDOW_MS, finishedTask, replyNotDelivered, A2A_ENDPOINT, a2aTokenHash, cardUrlOf, mcpUrlOf, normA2A, mergeA2ARecords, peersOf, applyRemovals, removalIntents, heldHandles, rehandleIn, applyRehandles, rehandledRemovals, pruneGoneIn, enableLaneIn, addPeerIn, setPeerReplyIn, removePeerIn, disableLaneIn, clearLanesIn, recordFor, withIntake, sentinelCalls, openItem, a2aMessage, a2aInstructions, isJobPeer } from './a2aCore.js'
32
32
  import { isLaneCopy } from './roomName.js' // a lane's copy of its shared room's line is never a draft
33
33
  import { A2A_PENDING_DOC, A2A_PEERS_DOC, peersFromDoc, pendingFromDoc, withoutShared } from './a2aShared.js'
34
34
  /** The Sentinel's answer for a task that already has its reply (infra/cloud-computer/sentinel/a2a.mjs). */
@@ -37,6 +37,7 @@ export { A2A_ENDPOINT, a2aTokenHash }
37
37
  /** Persisted state → its checked form (a2aCore.normA2A — the app's rules: room, handle and key shapes, ≤ 32 lanes and peers). */
38
38
  export const a2aStateOf = normA2A
39
39
  const fail = (code, msg, details = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...details })
40
+ const HANDLE_TAKEN = 'another account (the person’s other Witbitz app) holds this lane’s address, and the Sentinel refused a new one too — outside agents cannot reach it yet; try again later'
40
41
  /** The pending tasks as a snapshot carries them (JSON-safe, bounded): a lane's snapshot() / resume (sync sweep 10-24 #17). */
41
42
  export const pendingOf = (xs) => (Array.isArray(xs) ? xs : []).filter((p) => p && typeof p.taskId === 'string' && p.taskId && p.peer && typeof p.peer === 'object').slice(-50)
42
43
  .map((p) => ({ taskId: p.taskId, n: Number(p.n) || 0, peer: { id: String(p.peer.id || ''), name: String(p.peer.name || '').slice(0, 80), reply: p.peer.reply === 'auto' ? 'auto' : 'ask', ...(p.peer.job ? { job: true } : {}) },
@@ -49,6 +50,10 @@ export class A2AAccount {
49
50
  this._wb = wb; this._endpoint = String(endpoint).replace(/\/+$/, ''); this.restore(state); this._deps = deps
50
51
  /** Called with the new state whenever it changes — persist it (it holds the lanes' inbox private keys). */
51
52
  this.onState = null
53
+ /** Called with [{ room, cardUrl, mcpUrl }] when lanes were given a NEW address because the old one was another account's
54
+ * (the Sentinel's `handle_taken` — a backup restored across two apps). Agents set up with the old address need the new one. */
55
+ this.onReaddressed = null
56
+ this._moved = new Map() // old handle → new handle, for removal intents a failed change puts back (_change)
52
57
  }
53
58
  get state() { return JSON.parse(JSON.stringify({ ...this._s, ...(this._removals.length ? { pendingRemovals: this._removals } : {}) })) }
54
59
  restore(state) {
@@ -125,7 +130,7 @@ export class A2AAccount {
125
130
  _changed() { if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback */ } } }
126
131
  _calls() {
127
132
  const { post, auth, attest, seal } = this._d()
128
- return sentinelCalls({ post, auth, attest, seal, err: (kind, m, reply) => fail(kind === 'refused' ? 'sentinel_refused' : 'sentinel_unreachable', m, { definiteRefusal: kind === 'refused' && !!reply && (reply.ok === false || !!reply.error) && !(reply.status >= 500) && !['sentinel_unavailable', 'unreachable', 'timeout', 'busy'].includes(reply.error), ...(reply && typeof reply.state === 'string' ? { taskState: reply.state } : {}) }) })
133
+ return sentinelCalls({ post, auth, attest, seal, err: (kind, m, reply) => fail(kind === 'refused' ? 'sentinel_refused' : 'sentinel_unreachable', m, { definiteRefusal: kind === 'refused' && !!reply && (reply.ok === false || !!reply.error) && !(reply.status >= 500) && !['sentinel_unavailable', 'unreachable', 'timeout', 'busy'].includes(reply.error), ...(reply && typeof reply.state === 'string' ? { taskState: reply.state } : {}), ...(reply && typeof reply.error === 'string' ? { sentinelError: reply.error } : {}) }) })
129
134
  }
130
135
  _sealed(mode, obj) { return this._calls().sealed(mode, obj) }
131
136
  _plain(mode, extra = {}) { return this._calls().plain(mode, extra) }
@@ -141,6 +146,28 @@ export class A2AAccount {
141
146
  const missing = !mine || (Array.isArray(l.peers) ? l.peers : []).some((p) => p && p.id && !mine.peers.some((q) => q.id === p.id) && !mine.removed?.[p.id])
142
147
  if (missing) throw fail('stale_record', 'another device changed this account’s outside agents — sync the account (or restore its latest wb.a2a.state) and try again')
143
148
  }
149
+ return st
150
+ }
151
+ // ★ A HANDLE ANOTHER ACCOUNT HOLDS (`handle_taken`, 2026-11-29; a2aCore rehandleIn — the app's a2aLane.js does the same): the lanes the
152
+ // Sentinel does not hold for this account (`st`, the status just read) get fresh handles, SAVED FIRST — this account's state
153
+ // (onState), its removal intents, and the caller's copy `s` in place (a vault's replay or _change commits it after the push; an
154
+ // old handle there would win the lane back) — then the caller sends the same grant once more. → the rooms that moved
155
+ _readdress(s, candidate, st) {
156
+ const known = new Set([...Object.values(this._s.lanes), ...Object.values(s.lanes || {})].map((l) => l.handle))
157
+ const moves = rehandleIn(candidate, heldHandles(st), known)
158
+ if (!moves.length) return []
159
+ const next = JSON.parse(JSON.stringify(this._s))
160
+ if (applyRehandles(next, moves)) this._s = a2aStateOf(next)
161
+ if (s !== candidate) applyRehandles(s, moves)
162
+ for (const [, from, to] of moves) this._moved.set(from, to)
163
+ this._removals = rehandledRemovals(this._removals, moves)
164
+ this._changed()
165
+ const rooms = moves.map(([room]) => room)
166
+ if (typeof this.onReaddressed === 'function') {
167
+ const list = rooms.map((room) => { const l = this._s.lanes[room] || candidate.lanes[room]; return { room, cardUrl: cardUrlOf(this.endpoint, l.handle), mcpUrl: mcpUrlOf(this.endpoint, l.handle) } })
168
+ try { this.onReaddressed(list) } catch { /* the app's callback */ }
169
+ }
170
+ return rooms
144
171
  }
145
172
  /** Send the whole record (it REPLACES what the Sentinel held) — this account's, or `s`, a changed copy (_change). `intakeOf`
146
173
  * (sdkKeptIntake.js): (record) → { room, pub, drops } — the record then names the account's message intake and those peers'
@@ -148,15 +175,24 @@ export class A2AAccount {
148
175
  async _push(s = this._s, expectedGeneration = this._wb._archiveGeneration, intakeOf = null) {
149
176
  const account = await this._account()
150
177
  if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
151
- const candidate = this._removals.length ? structuredClone(s) : s
178
+ const candidate = structuredClone(s) // always a copy: a new address (handle_taken) is made on it, and saved by _readdress
152
179
  if (this._removals.length) applyRemovals(candidate, this._removals)
153
- await this._assertCovers(candidate)
180
+ const st = await this._assertCovers(candidate)
154
181
  if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
155
182
  const intake = intakeOf ? await intakeOf(candidate) : null
156
183
  if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
157
- const rec = recordFor(candidate, account)
158
- const r = await this._sealed('a2agrant', intake && intake.room && intake.pub ? withIntake(rec, intake) : { ...rec, preserveIntake: true })
159
- if (s === this._s) this._changed()
184
+ const grant = () => { const rec = recordFor(candidate, account); return this._sealed('a2agrant', intake && intake.room && intake.pub ? withIntake(rec, intake) : { ...rec, preserveIntake: true }) }
185
+ const pushedCurrent = s === this._s
186
+ let r
187
+ try { r = await grant() } catch (e) {
188
+ if (!e || e.sentinelError !== 'handle_taken') throw e
189
+ if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
190
+ const rooms = this._readdress(s, candidate, st)
191
+ if (!rooms.length) throw fail('handle_taken', HANDLE_TAKEN, { definiteRefusal: true })
192
+ try { r = await grant() } catch (e2) { if (e2 && e2.sentinelError === 'handle_taken') throw fail('handle_taken', HANDLE_TAKEN, { definiteRefusal: true }); throw e2 }
193
+ r = { ...r, readdressed: rooms }
194
+ }
195
+ if (pushedCurrent) this._changed()
160
196
  return r
161
197
  }
162
198
  // ⛔ A CHANGE IS KEPT ONLY ONCE THE SENTINEL TOOK IT (state machines pass 9, K#5): the record was changed in place and pushed
@@ -181,7 +217,7 @@ export class A2AAccount {
181
217
  if (changed()) throw fail('account_changed', 'the account changed during the agent update')
182
218
  if (added.length) { this._removals.push(...added); this._changed() }
183
219
  const finish = await this._stageInbox?.(next)
184
- try { await this._push(next, generation, intake) } catch (e) { if (!changed() && (e.definiteRefusal || (e.status >= 400 && e.status < 500))) { finish?.(false); if (added.length) { this._removals = previous; this._changed() } } throw e }
220
+ try { await this._push(next, generation, intake) } catch (e) { if (!changed() && (e.definiteRefusal || (e.status >= 400 && e.status < 500))) { finish?.(false); if (added.length) { this._removals = previous.map(([room, handle, id]) => [room, this._moved.get(handle) || handle, id]); this._changed() } } throw e }
185
221
  if (changed()) throw fail('account_changed', 'the account changed during the agent update')
186
222
  finish?.(true)
187
223
  this._removals = []
@@ -418,7 +454,7 @@ export class LaneA2A {
418
454
  async reply(taskId, text, { ask = false, reject = false } = {}) {
419
455
  const a = this._acct()
420
456
  let r
421
- try { r = await a._sealed('a2areply', { account: await a._account(), taskId: String(taskId), text: String(text || ''), ask: !!ask, reject: !!reject }) } catch (e) {
457
+ try { r = await a._sealed('a2areply', { account: await a._account(), taskId: String(taskId), text: reject ? '' : String(text || ''), ask: !!ask, reject: !!reject }) } catch (e) { // a decline carries no text (the app's replyA2A)
422
458
  // a task already answered (a resumed 'auto' task taken mid-send was re-sent on every resume, an error each time —
423
459
  // sync sweep backlog): it is done, not failed — dropped, never offered again
424
460
  if (!finishedTask(e)) throw e
@@ -457,15 +493,23 @@ export class LaneA2A {
457
493
  }
458
494
  /** The drafts held while nobody listened, to the listener that came (Lane.on). */
459
495
  _flushHeld() { const h = this._held.splice(0); for (const t of h) if (this._pending.includes(t)) this._offer(t) }
496
+ /** May an 'auto' draft still go back on its own? Its home must still be a lane or a solo verified Space (unreadable → no). */
497
+ _homeOk() { return assertAgentTarget(this._lane).then(() => true, () => false) }
460
498
  /** A task's draft: 'auto' → sent; 'ask' → an `a2a` event for the member. */
461
499
  _offer(t) {
462
500
  if (this._lane._wb?.a2a?._draftsSuspended) { if (!this._held.includes(t)) this._held.push(t); return }
463
501
  if (t.peer.reply === 'auto' && this.peers.some(peer => peer.id === t.peer.id && peer.reply === 'auto')) {
464
502
  if (this._sendingDrafts.has(t.taskId)) return
465
503
  this._sendingDrafts.add(t.taskId)
466
- this.reply(t.taskId, t.draft, { autoPeerId: t.peer.id }).then(result => {
467
- if (result?.held && this._pending.includes(t)) { t.peer.reply = 'ask'; this._offer(t) }
468
- }).catch(e => this._lane._emit('error', e)).finally(() => this._sendingDrafts.delete(t.taskId))
504
+ // ⛔ ONLY WHILE ITS HOME STILL IS A LANE OR A SOLO VERIFIED SPACE (sync sweep 2026-11-25, "outside agents after a second member
505
+ // joins"): a task delivered before a second member came had its draft matched later — the first assistant line after it, which
506
+ // in a shared Space may answer the new member — and sent unreviewed. Not solo now (or unreadable) → held as an 'ask' draft.
507
+ this._homeOk().then(ok => {
508
+ if (!ok) { this._sendingDrafts.delete(t.taskId); if (this._pending.includes(t)) { t.peer.reply = 'ask'; this._offer(t) } return }
509
+ return this.reply(t.taskId, t.draft, { autoPeerId: t.peer.id }).then(result => {
510
+ if (result?.held && this._pending.includes(t)) { t.peer.reply = 'ask'; this._offer(t) }
511
+ }).finally(() => this._sendingDrafts.delete(t.taskId))
512
+ }).catch(e => this._lane._emit('error', e))
469
513
  return
470
514
  }
471
515
  if (!((this._lane._subs && this._lane._subs.a2a) || []).length) { if (!this._held.includes(t)) this._held.push(t); return } // nobody listens yet: kept for the first
@@ -506,6 +550,7 @@ export class VaultLaneA2A extends LaneA2A {
506
550
  conn.a2aViews ||= new Map()
507
551
  if (!conn.a2aViews.has(lane.room) || conn.a2aViews.get(lane.room).epoch !== conn.a2aEpoch) readVaultA2AView(conn, lane.room)
508
552
  }
553
+ _homeOk() { return Promise.resolve(true) } // the VAULT asks it before an auto reply goes (vault-core.js laneA2A 'reply' → { held })
509
554
  get _view() {
510
555
  const slot = this._conn.a2aViews.get(this._lane.room)
511
556
  return slot?.epoch === this._conn.a2aEpoch ? slot?.view : null
@@ -554,7 +599,7 @@ export class VaultLaneA2A extends LaneA2A {
554
599
  }
555
600
  async reply(taskId, text, { ask = false, reject = false, autoPeerId } = {}) {
556
601
  let r
557
- try { r = await this._call('reply', String(taskId), String(text || ''), { ask: !!ask, reject: !!reject, ...(autoPeerId ? { autoPeerId } : {}) }) } catch (e) { if (!finishedTask(e)) throw e; r = { state: 'completed' } } // already answered: done (see above)
602
+ try { r = await this._call('reply', String(taskId), reject ? '' : String(text || ''), { ask: !!ask, reject: !!reject, ...(autoPeerId ? { autoPeerId } : {}) }) } catch (e) { if (!finishedTask(e)) throw e; r = { state: 'completed' } } // already answered: done (see above)
558
603
  if (r?.held) return r
559
604
  this._pending = this._pending.filter((p) => p.taskId !== taskId)
560
605
  return { state: r && r.state }
package/sdkBackup.js CHANGED
@@ -245,6 +245,7 @@ export class AccountBackup {
245
245
  * (wb.account) — opening the room again later brings it back. */
246
246
  remove(room) {
247
247
  if (!this._s) return this
248
+ for (const child of this._s.rooms.slice()) if (child.kind === 'lane' && child.shared === room) this._detachLane(child.room, room) // a lane of it stays as a room of its own, never one pointing at a removed Space (as account.forget)
248
249
  const n = this._s.rooms.length
249
250
  this._s.rooms = this._s.rooms.filter((x) => x.room !== room)
250
251
  if (this._s.rooms.length !== n) { this._s.tomb = [...(this._s.tomb || []).filter((t) => t.room !== room), { room, at: Date.now() }].slice(-500); this._schedule() }
package/sdkBackupV2.js CHANGED
@@ -19,7 +19,7 @@
19
19
  // old store, as before this release.
20
20
  // Security keys use the shared account-service ceremonies. To add a second device, restore with the
21
21
  // recovery code. Legacy migration and email-move flows reuse the reviewed account-service protocol below.
22
- import { makeAcctV2, STATE_KEY, ERASE_KEY, MOVE_KEY, RESET_KEY } from './acctV2App.js'
22
+ import { makeAcctV2, STATE_KEY, ERASE_KEY, MOVE_KEY, RESET_KEY, RESTORING_KEY } from './acctV2App.js'
23
23
  import { canonicalAddress } from './acctV2Client.js'
24
24
  import { refusedAsRevoked, statusDue } from './acctV2Check.js'
25
25
  import { codeSecret, newRecoveryCode, seal, unseal } from './recovery.js'
@@ -157,6 +157,21 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
157
157
  /** makeAcctV2 over backup state `s` (its `v2` holds what the flows keep). `hooks`: { applyRestored?, wipe?, changed?, current? }
158
158
  * — `current()` false: the vault moved to another account (or state) meanwhile, and a new code is NOT kept (no activation is sent). */
159
159
  const memOf = new WeakMap()
160
+ // A RESTORE'S DRAFT ON THE VAULT'S DISK (side sweep re-check A1): a draft kept only in the page's memory was lost when the vault
161
+ // reopened between a lost finish reply and the retry — a new device key, and two active entries for one vault. Once its finish is
162
+ // sent, the draft's key id and its "finish sent" mark (acctV2App RESTORING_KEY) wait in the key store until the restore succeeds or
163
+ // the mark is dropped (a key the service does not hold active, or another account's: acctV2App freshKeyIfTaken / restoreHere).
164
+ const DRAFT_KEY = 'restore-draft:v1'
165
+ async function draftFromDisk() {
166
+ const s = { v: 1, format: 'account', master: '', rooms: [], v2: {} }
167
+ let d = null
168
+ try { d = await keyStore.get(DRAFT_KEY) } catch { /* unreadable: a new draft, as before */ }
169
+ if (d && typeof d.dk === 'string' && /^[A-Za-z0-9]{1,32}$/.test(d.dk) && typeof d.restoring === 'string' && d.restoring.length <= 2000) {
170
+ s.v2.dk = d.dk
171
+ memOf.set(s, new Map([[RESTORING_KEY, d.restoring]]))
172
+ }
173
+ return s
174
+ }
160
175
  function client(s, hooks = {}) {
161
176
  if (!s.v2) s.v2 = {}
162
177
  if (!s.v2.dk) s.v2.dk = rand(16)
@@ -171,12 +186,12 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
171
186
  return value == null ? null : k === STATE_KEY ? JSON.stringify(value) : value
172
187
  },
173
188
  setItem(k, v) {
174
- if (!fields.has(k)) { mem.set(k, String(v)); return }
189
+ if (!fields.has(k)) { mem.set(k, String(v)); if (k === RESTORING_KEY) hooks.restoringChanged?.(String(v)); return }
175
190
  s.v2[fields.get(k)] = k === STATE_KEY ? v2Of({ svc: JSON.parse(v) })?.svc : String(v)
176
191
  hooks.changed?.()
177
192
  },
178
193
  removeItem(k) {
179
- if (!fields.has(k)) { mem.delete(k); return }
194
+ if (!fields.has(k)) { mem.delete(k); if (k === RESTORING_KEY) hooks.restoringChanged?.(null); return }
180
195
  // Keep this device's request until its new account and first code are both durable.
181
196
  if (k === RESET_KEY && hooks.finishingReset) return
182
197
  delete s.v2[fields.get(k)]
@@ -192,7 +207,7 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
192
207
  return { newCode, newMaster, backupId: loc.id, wrapperId: (await wrapperLocation(cs)).id, backupBlob: utf8(await seal(loc.key, payload)), wrapperBlob: utf8(await sealWrapper(cs, newMaster)) }
193
208
  }
194
209
  return makeAcctV2({
195
- base, fetch: fetchWatched, headers, storage,
210
+ base, fetch: hooks.beforeFetch ? async (...a) => { await hooks.beforeFetch(); return fetchWatched(...a) } : fetchWatched, headers, storage, // beforeFetch: a restore's "finish sent" mark is on disk before the finish goes
196
211
  canApplyStatus: hooks.canApplyStatus,
197
212
  deviceKey,
198
213
  newDeviceKey: async () => { rec = await newKeyRecord(ks); return rec },
@@ -491,9 +506,11 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
491
506
  // ONE DRAFT PER VAULT PAGE, kept until a restore succeeds (side sweep: restore-finish-duplicate-device): each attempt made a fresh
492
507
  // state — a fresh device key (`dk`) and no memory of the finish it had sent — so a retry after a lost finish reply registered a
493
508
  // second active device. The draft keeps the attempt's key and its restoring mark (acctV2App RESTORING_KEY, held per state).
494
- // Held in memory: a reload starts a new draft (its key is not kept), as before.
495
- if (!b._restoreDraft || b._restoreDraft.v2.svc) b._restoreDraft = { v: 1, format: 'account', master: '', rooms: [], v2: {} }
509
+ // Once its finish is sent the draft is on the vault's disk too, so a reopened vault keeps it (side sweep re-check A1: draftFromDisk).
510
+ if (!b._restoreDraft || b._restoreDraft.v2.svc) { const d = await draftFromDisk(); if (!b._restoreDraft || b._restoreDraft.v2.svc) b._restoreDraft = d }
496
511
  const s1 = b._restoreDraft
512
+ let draftWrite = Promise.resolve()
513
+ const keepDraft = (mark) => { draftWrite = draftWrite.then(() => (mark ? keyStore.set(DRAFT_KEY, { dk: s1.v2.dk, restoring: mark }) : typeof keyStore.del === 'function' ? keyStore.del(DRAFT_KEY) : null)).catch(() => { /* not kept: this page's retry still has it */ }) }
497
514
  let found = false, done = null
498
515
  const address = async () => {
499
516
  found = true // the service knows this code
@@ -502,6 +519,7 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
502
519
  return x
503
520
  }
504
521
  const a = client(s1, {
522
+ restoringChanged: keepDraft, beforeFetch: () => draftWrite,
505
523
  applyRestored: async ({ master: bm, payload, legacy }) => {
506
524
  const identity = is32(payload.sdkMaster) ? payload.sdkMaster : legacy && payload.sdkMaster === undefined ? b64(bm) : null
507
525
  if (vaultOwner(payload) !== 'sdk' || !identity) throw fail('not_sdk_backup', 'that code opens a backup made by a different app')
@@ -521,6 +539,7 @@ export function accountService({ tenant, base = ACCOUNT_SERVICE, fetch: f = (...
521
539
  }
522
540
  if (!done) throw fail('unopenable', 'the backup could not be opened')
523
541
  b._restoreDraft = null // restored: the next restore is a new one
542
+ keepDraft(null); await draftWrite // …and its copy on disk goes (its key id is the account's now: done.v2.dk)
524
543
  return done
525
544
  },
526
545
 
@@ -20,6 +20,11 @@ export async function setSessionPrivate(cloud, session, on, { WebSocket: Socket
20
20
  ws.onmessage = async (event) => {
21
21
  if (!sent || done) return
22
22
  const msg = await open(key, event.data), ctl = msg && msg.kind === KIND_CTL && readCtl(msg.bytes)
23
+ if (ctl && ctl.wb === 'session' && ctl.session === session && ctl.separate) {
24
+ // a computer with a browser PER SESSION (docs/cloud-computer.md § 12.w2): every session is separate already, and its
25
+ // profile is kept — there is no "private" to turn on
26
+ return finish(on ? fail('not_supported', 'every Code session on this computer has its own browser and profile; there is no private mode to turn on') : null)
27
+ }
23
28
  if (ctl && ctl.wb === 'session' && ctl.session === session && ctl.private === on) finish()
24
29
  }
25
30
  ws.onerror = ws.onclose = () => finish(fail('offline', 'the browser control channel disconnected'))
package/sdkComputers.js CHANGED
@@ -200,6 +200,7 @@ export class Computers {
200
200
  }
201
201
  const store = {
202
202
  get: async key => { const blob = await idb.get(key); return blob ? open(key, blob) : null },
203
+ getStrict: async key => { const blob = await idb.getStrict(key); return blob ? open(key, blob) : null }, // a failed read throws (codeCache removeCachedSession)
203
204
  set: async (key, value) => { const box = await sealDoc(loc.key, { key, value }); check(); return idb.set(key, { accountBox: box }) },
204
205
  entries: async prefix => Promise.all((await idb.entries(prefix)).map(async ([k, v]) => [k, await open(k, v)])),
205
206
  del: key => idb.del(key),
package/sdkExports.js CHANGED
@@ -1,4 +1,6 @@
1
- import { exportSpace, recreateSpace, missingAttachments, messageCount } from './spaceExport.js'
1
+ import { exportSpace, recreateSpace, missingAttachments, messageCount, inlineEarlier } from './spaceExport.js'
2
+ import { earlierForExport } from './earlierHistory.js'
3
+ import { readEpochChain } from './spaceFork.js'
2
4
  import { makeBundle, sealSpaceMeta, keysFileText, OFFLINE_ATTACHMENTS_MAX_BYTES, addAttachmentStats } from './offlineBundle.js'
3
5
 
4
6
  // Downloads stay in the document doing the export. A vault never returns the
@@ -17,20 +19,26 @@ export async function saveOfflineReader() {
17
19
  saveExport('witbitz-offline-decryptor.html', await response.text(), 'text/html;charset=utf-8')
18
20
  }
19
21
 
20
- export async function saveRoomExport(sp, tier, current = () => true, title = sp.title) {
22
+ // `earlierKeys` ({ room: key } — the account's rooms this client can open): a LINKED CONTINUATION's earlier versions ride along, read
23
+ // as the Spaces app reads them (offlineExport.js, earlierHistory.js); when they cannot be, the result says so (`historyIncomplete`)
24
+ export async function saveRoomExport(sp, tier, current = () => true, title = sp.title, earlierKeys = null) {
21
25
  const reader = Object.fromEntries(['poll', 'getConfig', 'blob', 'state'].map((op) => [
22
26
  op, (room, ...args) => sp._client[op](room, sp._mk, ...args),
23
27
  ]))
24
28
  const bundle = await exportSpace(sp.room, reader, { title })
25
29
  if (!current()) throw new Error('account_changed')
26
30
  bundle.tier = tier
31
+ const keys = earlierKeys && typeof earlierKeys === 'object' ? earlierKeys : {}
32
+ const { earlier, note } = await earlierForExport({ parent: bundle.config?.parent?.room, epochKeys: keys, readChain: (p, mk, ek) => readEpochChain(sp._client, p, mk, ek, 0, { whole: true }) })
33
+ if (earlier) { earlier.entries = await inlineEarlier(earlier.entries, (room, ref) => (room && keys[room] ? sp._client.blob(room, keys[room], ref) : null)); bundle.earlier = earlier }
34
+ if (!current()) throw new Error('account_changed')
27
35
  // A readable file carries no credential (a connection's callKey, the room's earlier keys): exportSpace leaves them out for
28
36
  // every caller — spaceExport.js portableConfig (side sweep: portable-export-includes-room-credentials).
29
37
  saveExport('witbitz-space-' + sp.room + '.json', JSON.stringify(bundle), 'application/json')
30
38
  // the attachments the file still carries only as a pointer to this room (their read failed): said, as the app says it — a
31
39
  // recreated room cannot open them (side sweep: portable-export-silent-attachment-read-failure)
32
40
  const missing = missingAttachments(bundle)
33
- return { count: messageCount(bundle.entries), ...(missing ? { attachmentsMissing: missing } : {}) } // the MESSAGE count: a photo's Safe media copy is not one (side sweep: room-export-counts-hidden-records-as-messages)
41
+ return { count: messageCount(bundle.entries), ...(missing ? { attachmentsMissing: missing } : {}), ...(earlier ? { earlierCount: messageCount(earlier.entries) } : note ? { historyIncomplete: note.trim() } : {}) } // the MESSAGE count: a photo's Safe media copy is not one (side sweep: room-export-counts-hidden-records-as-messages)
34
42
  }
35
43
 
36
44
  export async function recreateExport(wb, bundle, { tier = bundle?.tier || (bundle?.device?.confidential === false ? 'standard' : 'enclave') } = {}) {
package/sdkRekey.js CHANGED
@@ -19,6 +19,9 @@ import { ROSTER_DOC } from './roomRoster.js'
19
19
  import { hide } from './sdkRedact.js'
20
20
  import { assertNotKept } from './sdkCloudDevice.js'
21
21
  import { memberHash } from './rosterHash.js'
22
+ import { preferredAddresses } from './addPreferred.js' // "Add me to Spaces as @username" (docs/spaces-usernames.md § 13)
23
+ import { findInvitee } from './inviteSend.js'
24
+ import { rolesOf, roleFor, hasRoles, roleTagFor, roleTagHolders } from './roomRoles.js' // owners and admins by @username tag (docs/spaces-usernames.md § 13.1)
22
25
 
23
26
  const sdkError = (message, code) => Object.assign(new Error(message), { code })
24
27
 
@@ -117,6 +120,9 @@ export class InviteAccount {
117
120
  const client = wb && wb._client
118
121
  if (!client || typeof client.inboxFetch !== 'function') throw sdkError('witbitz: this client cannot read an invite inbox', 'unsupported')
119
122
  const out = []
123
+ // THE ACCOUNT THAT ASKED (sync sweep 11-29 #2): a sign-out or switch during the read must not hand the previous account's links on
124
+ const whoNow = () => { const s = wb._session; return s && s.email ? lc(s.email) + '|' + inviteScope(s.idToken) : '' }
125
+ const asked = whoNow()
120
126
  // a fetch that rejects before any answer is `unreachable` too, as the types say (side sweep: sdk-invite-collection-network-error)
121
127
  const n = await checkInbox({ client, inviteKey: k, onInvite: (inv) => {
122
128
  if (inv.kind || !inv.room) return false // an attested room's: its native app takes it
@@ -127,6 +133,7 @@ export class InviteAccount {
127
133
  out.push({ room: String(inv.room), link, title: typeof inv.title === 'string' ? inv.title.slice(0, 200) : '', from: typeof inv.from === 'string' ? inv.from.slice(0, 320) : '', at: Math.min(Number(inv.at) || 0, Date.now()) })
128
134
  return true
129
135
  } }).catch(() => -1)
136
+ if (whoNow() !== asked || this._key() !== k) throw sdkError('witbitz: the account changed while collecting invitations', 'account_changed')
130
137
  if (n < 0) throw sdkError('witbitz: the invite inbox could not be read', 'unreachable')
131
138
  const seen = new Set()
132
139
  return out.sort((a, b) => b.at - a.at).filter((x) => !seen.has(x.room) && seen.add(x.room)) // the newest invitation per room
@@ -237,11 +244,22 @@ async function currentMembers (space, cfg) {
237
244
  const onList = await stillOnList(cfg, space.room, Object.values(book.seen || {}).filter((x) => x && x.email && !x.left)).catch(() => null) // the records: a person in by @username is on by the entry they came in by (sync sweep 11-23 #2)
238
245
  const seen = onList ? seen0.filter((e) => onList(e, '')) : seen0
239
246
  const emails = [...new Set([...(Array.isArray(al.emails) ? al.emails : []), ...seen].map(lc))]
240
- return { book, emails, owners: ((cfg.owners && cfg.owners.emails) || []).map(lc), admins: ((cfg.admins && cfg.admins.emails) || []).map(lc) }
247
+ const rt = rolesOf(cfg) // ownerTags/adminTags: the roles held by @username tag (§ 13.1) — a change that does not touch them carries them
248
+ return { book, emails, owners: ((cfg.owners && cfg.owners.emails) || []).map(lc), admins: ((cfg.admins && cfg.admins.emails) || []).map(lc), ownerTags: rt.ownerTags, adminTags: rt.adminTags }
249
+ }
250
+
251
+ /** This session's tag for the Space (its @username's, op user mode tag) — a role it holds by its tag (§ 13.1). → [tag] | [] */
252
+ async function ownTags (space) {
253
+ const wb = space._wb
254
+ const w = wb && wb.usernames ? await wb.usernames.mine().catch(() => null) : null
255
+ if (!w || !w.username) return []
256
+ const c = (wb && wb._client) || space._client
257
+ const t = typeof c.userTag === 'function' ? await c.userTag(w.username, space.room).catch(() => null) : null
258
+ return t && t.status === 200 && typeof t.tag === 'string' && t.tag ? [t.tag] : []
241
259
  }
242
260
 
243
261
  const epochOf = (cfg) => (Array.isArray(cfg && cfg.keyChain) ? cfg.keyChain.length : 0) // the epoch a config was read at (= the app's rekeyToWant)
244
- async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null, book }) {
262
+ async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null, book, extra = [] }) { // extra: grants at a tag (a member added as their @username — § 13)
245
263
  const me = lc(space._wb && space._wb._session && space._wb._session.email)
246
264
  const wb = space._wb
247
265
  const scope = inviteScope(wb._session.idToken)
@@ -251,7 +269,8 @@ async function rekeyNow (space, { members, stay, allowAfter, expectEpoch = null,
251
269
  const domains = new Set(normalizeDomains(allowAfter?.domains))
252
270
  const joined = people.filter(p => p && !p.left && p.email && retained(p.email) &&
253
271
  (domains.has(lc(p.email).split('@')[1]) || p.entries?.some(e => typeof e === 'string' && e.startsWith('u:')))).map(p => lc(p.email))
254
- const { recipients, unreachable, pending } = await recipientsFor(space.room, [...stay, ...joined], wb._client || space._client, { scope, allow: allowAfter, people }) // include observed retained legacy handles, never arbitrary roster emails
272
+ const found = await recipientsFor(space.room, [...stay, ...joined], wb._client || space._client, { scope, allow: allowAfter, people }) // include observed retained legacy handles, never arbitrary roster emails
273
+ const recipients = [...found.recipients, ...extra.filter((x) => !found.recipients.some((r) => r.mh === x.mh))], { unreachable, pending } = found
255
274
  if (!recipients.some((x) => x.email === me)) throw sdkError('witbitz: this account has no invite key for this app yet (wb.invite.status: ' + wb.invite.status + ') — restore wb.invite.state from the device that has it', 'no_invite_key')
256
275
  const split = space._split ? { userShare: fragParam(space.shareLink, 'us') } : null
257
276
  if (space._split && !split.userShare) throw sdkError('witbitz: this split Space was not opened from its link — its user half is unknown here', 'invalid_argument')
@@ -281,9 +300,11 @@ export async function changeable (space, what) {
281
300
  if (!cfg) throw sdkError(`witbitz: couldn’t read this Space’s members — try ${what} again shortly`, 'config_unavailable')
282
301
  if (cfg.admission !== 'email') throw sdkError(`witbitz: only an email-gated Space changes ${what === 'rotateKey' ? 'its key' : 'its members'}`, 'invalid_argument')
283
302
  const me = lc(wb._session.email)
284
- const owners = ((cfg.owners && cfg.owners.emails) || []).map(lc), admins = ((cfg.admins && cfg.admins.emails) || []).map(lc)
285
- if (!owners.length && !admins.length) throw sdkError('witbitz: this Space has no owners or admins — only the Spaces app can change it (its creator)', 'not_admin')
286
- if (!owners.includes(me) && !admins.includes(me)) throw sdkError('witbitz: only an owner or an admin changes this Space', 'not_admin')
303
+ if (!hasRoles(cfg)) throw sdkError('witbitz: this Space has no owners or admins — only the Spaces app can change it (its creator)', 'not_admin')
304
+ // a role held by this account's @username tag (§ 13.1) counts as one held by its email
305
+ const rt = rolesOf(cfg)
306
+ const tags = !roleFor(cfg, { email: me }) && (rt.ownerTags.length || rt.adminTags.length) ? await ownTags(space) : []
307
+ if (!roleFor(cfg, { email: me, tags })) throw sdkError('witbitz: only an owner or an admin changes this Space', 'not_admin')
287
308
  return { cfg, me }
288
309
  }
289
310
 
@@ -353,7 +374,59 @@ export async function planMembers (space, admission = {}, cfg = null) {
353
374
  want[role] = retained
354
375
  }
355
376
  }
356
- const m = await listAfter(cfg, space.room, { ...want, known: cur.emails }, { book: () => cur.book, tagOf })
377
+ // ROLES BY @USERNAME TAG (docs/spaces-usernames.md § 13.1; the owner, 2026-11-29). `admission.ownerTags` / `adminTags` (members()'s) state
378
+ // them in full; unstated, the room's are kept — but where `owners` / `admins` are stated, a tag whose holder the guest book names by an
379
+ // email left out of that list is dropped (lowered), and an email stated for someone who holds the role by tag stays their tag.
380
+ const held = (cur.ownerTags.length || cur.adminTags.length) ? await roleTagHolders(Object.values((cur.book && cur.book.seen) || {}), [...cur.ownerTags, ...cur.adminTags], { room: space.room, userTag: typeof c.userTag === 'function' ? (n, r) => c.userTag(n, r) : null }) : new Map()
381
+ const holderEmail = (t) => (held.get(t) && held.get(t).email) || ''
382
+ const tagWant = {}
383
+ for (const [role, key] of [['owners', 'ownerTags'], ['admins', 'adminTags']]) {
384
+ if (admission[key] !== undefined) {
385
+ if (!Array.isArray(admission[key]) || admission[key].some((t) => typeof t !== 'string' || !t)) throw sdkError(`witbitz: admission.${key} is a list of the tags members() reports`, 'invalid_argument')
386
+ tagWant[key] = [...new Set(admission[key])]
387
+ } else if (Array.isArray(admission[role])) { const stated = new Set(want[role]); tagWant[key] = cur[key].filter((t) => { const e = holderEmail(t); return !e || stated.has(e) }) } else tagWant[key] = [...cur[key]]
388
+ const byTag = new Set(tagWant[key].map(holderEmail).filter(Boolean))
389
+ want[role] = want[role].filter((e) => !byTag.has(e))
390
+ }
391
+ // SOMEONE MADE AN OWNER OR ADMIN NOW, as they prefer: by the room's tag for their @username (the email door names it, only where "find
392
+ // me by email" is on), once the server takes tag roles (roleTagFor: `roles: true`); otherwise by the email, as before.
393
+ {
394
+ const granted = [...want.owners.filter((e) => !cur.owners.includes(e)).map((e) => ['owners', e]), ...want.admins.filter((e) => !cur.admins.includes(e) && !cur.owners.includes(e) && !want.owners.includes(e)).map((e) => ['admins', e])]
395
+ const pref = granted.length ? await preferredAddresses([...new Set(granted.map(([, e]) => e))], { client: c }).catch(() => null) : null
396
+ for (const { email, username } of (pref && pref.learned) || []) {
397
+ const t = await roleTagFor(c, username, space.room)
398
+ if (!t) continue
399
+ for (const [role, e] of granted) if (e === email) { want[role] = want[role].filter((x) => x !== email); tagWant[role === 'owners' ? 'ownerTags' : 'adminTags'].push(t) }
400
+ }
401
+ }
402
+ want.ownerTags = [...new Set(tagWant.ownerTags)]
403
+ want.adminTags = [...new Set(tagWant.adminTags)].filter((t) => !want.ownerTags.includes(t))
404
+ // HOW A NEW MEMBER IS ADDED IS THEIR PREFERENCE (docs/spaces-usernames.md § 13; owner, 2026-11-29): an address NEW to the list
405
+ // (not shown, not a manager, not yours) whose person prefers their @username — the email door names it, only where "find me by
406
+ // email" is on — goes on the list as the room's TAG for that name: the other members never get the email. Its grant is sealed at
407
+ // the tag to the key the name's own door gives (the app's rekeyMembers usersToAdd). Any lookup that fails: the email, as before.
408
+ const asUsers = []
409
+ {
410
+ const hiddenNow = new Set(Array.isArray(cfg.allow?.mh) ? cfg.allow.mh : [])
411
+ const fresh = []
412
+ for (const e of want.emails) {
413
+ if (e === lc(space._wb?._session?.email) || cur.emails.includes(e) || want.owners.includes(e) || want.admins.includes(e) || (want.shown || []).map(lc).includes(e)) continue
414
+ if (hiddenNow.has(await memberHash(e, space.room))) continue
415
+ fresh.push(e)
416
+ }
417
+ const pref = fresh.length ? await preferredAddresses(fresh, { client: c }).catch(() => null) : null
418
+ const scope = space._wb?._session?.idToken ? inviteScope(space._wb._session.idToken) : undefined
419
+ for (const { email, username } of (pref && pref.learned) || []) {
420
+ const tag = await tagOf(username)
421
+ const f = tag ? await findInvitee({ username, ...(scope ? { scope } : {}) }, c).catch(() => null) : null
422
+ if (tag && f && f.ok && f.entry && f.entry.boxPub) asUsers.push({ email, username, tag, boxPub: f.entry.boxPub })
423
+ }
424
+ if (asUsers.length) { const conv = new Set(asUsers.map((x) => x.email)); want.emails = want.emails.filter((e) => !conv.has(e)) }
425
+ }
426
+ const m0 = await listAfter(cfg, space.room, { ...want, known: cur.emails }, { book: () => cur.book, tagOf })
427
+ const m = asUsers.length ? { ...m0, allow: { ...m0.allow, mh: [...new Set([...(Array.isArray(m0.allow.mh) ? m0.allow.mh : []), ...asUsers.map((x) => x.tag)])] } } : m0
428
+ // a STATED role tag is one admission() reported (a role held now) or a tag on the new list — anything else names nobody, refused, never written
429
+ { const known = new Set([...(Array.isArray(m.allow.mh) ? m.allow.mh : []), ...cur.ownerTags, ...cur.adminTags]); const stray = [...(Array.isArray(admission.ownerTags) ? admission.ownerTags : []), ...(Array.isArray(admission.adminTags) ? admission.adminTags : [])].find((t) => !known.has(t)); if (stray) throw sdkError('witbitz: a role tag must be one admission() reports, or name someone on the list (' + String(stray).slice(0, 8) + '…)', 'invalid_argument') }
357
430
  // ⛔ NOT YOURSELF, SILENTLY (second review, 2026-11-27): a manager the new list does not admit is dropped (545f3a97f, so a role cannot
358
431
  // admit anyone) — a manager who leaves THEIR OWN address off the whole list would lose the Space with no word. Refused by name
359
432
  // instead: they add it, or leave the Space. Asked of the change itself (`m.removed`), so a manager who stays by a domain, a
@@ -362,7 +435,7 @@ export async function planMembers (space, admission = {}, cfg = null) {
362
435
  if (actor && (cur.owners.includes(actor) || cur.admins.includes(actor)) && (m.removed || []).map(lc).includes(actor)) {
363
436
  throw sdkError('witbitz: your own address is not on the new list — add it, or leave the Space instead', 'invalid_argument')
364
437
  }
365
- return { emails, cur, want, m, epoch: epochOf(cfg), actor: lc(space._wb?._session?.email), roles: !m.removed.length && sameList(cfg.allow, m.allow) }
438
+ return { emails, cur, want, m, asUsers, epoch: epochOf(cfg), actor: lc(space._wb?._session?.email), roles: !asUsers.length && !m.removed.length && sameList(cfg.allow, m.allow) }
366
439
  }
367
440
 
368
441
  /** space.changeMembers(admission) — `admission`: { emails, domains?, admins?, owners?, advertise? }, the list stated in FULL,
@@ -377,7 +450,7 @@ export async function changeMembers (space, admission = {}, approved = null) {
377
450
  return JSON.stringify({ ...p, cur, admissions })
378
451
  }
379
452
  if (approved && approvalFields(plan) !== approvalFields(approved)) throw sdkError('Space membership changed during confirmation. Review it again.', 'config_changed')
380
- const { emails, cur, want, m, roles } = plan
453
+ const { emails, cur, want, m, roles, asUsers = [] } = plan
381
454
  // A ROLE CHANGE NEEDS NO NEW KEY (the app's decision 4, verifiedMove.js; sweep 10-23 #16): nobody's access changes, so the
382
455
  // room keeps its key and the config changes in place (op 'config'). A server that does not take it yet answers
383
456
  // config_immutable / not_enabled: then the change is made as before, by a re-key.
@@ -388,12 +461,14 @@ export async function changeMembers (space, admission = {}, approved = null) {
388
461
  if (!(r && (r.error === 'config_immutable' || r.error === 'not_enabled'))) throw Object.assign(new Error('witbitz: the roles were not changed — nothing has changed' + (r && r.reason ? ` (${r.reason})` : '')), { code: (r && r.error) || 'config_failed', status: r && r.status })
389
462
  }
390
463
  const stay = [...new Set([...want.emails, ...want.owners, ...want.admins, me])]
391
- const { epoch, unreachable } = await rekeyNow(space, { members: { allow: m.allow, owners: m.owners, admins: m.admins }, stay, allowAfter: m.allow, expectEpoch: epochOf(cfg), book: cur.book })
392
- // added = on neither list before: not an address the room showed or its book knew, and not a hidden address's hash
464
+ const { epoch, unreachable } = await rekeyNow(space, { members: { allow: m.allow, owners: m.owners, admins: m.admins }, stay, allowAfter: m.allow, expectEpoch: epochOf(cfg), book: cur.book, extra: asUsers.map(({ email, tag, boxPub }) => ({ email, mh: tag, boxPub })) })
465
+ // added = on neither list before: not an address the room showed or its book knew, and not a hidden address's hash — an address
466
+ // added as its person's @username (§ 13) is reported by that name
393
467
  const hidden = new Set(Array.isArray(cfg.allow && cfg.allow.mh) ? cfg.allow.mh : [])
394
468
  const before = new Set(cur.emails)
469
+ const byName = new Map(asUsers.map((x) => [x.email, '@' + x.username]))
395
470
  const added = []
396
- for (const e of emails) if (!before.has(e) && !hidden.has(await memberHash(e, space.room))) added.push(e)
471
+ for (const e of emails) if (byName.has(e)) added.push(byName.get(e)); else if (!before.has(e) && !hidden.has(await memberHash(e, space.room))) added.push(e)
397
472
  return { inPlace: true, epoch, link: space.shareLink, removed: m.removed, added, unreachable }
398
473
  }
399
474
 
package/spaceClient.js CHANGED
@@ -31,6 +31,7 @@ import { verifyRoomGovernance } from './ownerPolicy.js'
31
31
  import { staysDirect } from './roomName.js' // a direct chat that gains a third member is a group (rekey)
32
32
  import { stageMirrorAttachments } from './mirrorBatch.js'
33
33
  import { memberHash } from './rosterHash.js' // hash the email allow-list (room-bound) before sealing → co-members can't read addresses
34
+ import { roleOf } from './roomRoles.js' // owners and admins by email or @username tag (docs/spaces-usernames.md § 13.1)
34
35
 
35
36
  async function directRoster(allow, room) {
36
37
  if (!Array.isArray(allow?.emails) || !Array.isArray(allow?.mh) || !allow.mh.length) return allow
@@ -106,8 +107,8 @@ const sealConfig = async (config, mk) =>
106
107
  // (spaceService hasAdmins/isRoomAdmin/cardNeedsAdmin) — and were MISSING from this list, so an SDK room declared them
107
108
  // and sealed without them: no admins, approvals by any member (a builder measured it on production). `forkedFrom` is
108
109
  // where a fork came from; `connections` are the grants a fork carries. Undefined ⇒ dropped ⇒ sealed exactly as before.
109
- admins: config.admins && Array.isArray(config.admins.emails) ? { emails: config.admins.emails.map((x) => String(x).toLowerCase()) } : undefined,
110
- owners: config.owners && Array.isArray(config.owners.emails) ? { emails: config.owners.emails.map((x) => String(x).toLowerCase()) } : undefined, // OWNERS (2026-10-03): above admins, enforced by the room
110
+ admins: config.admins && Array.isArray(config.admins.emails) ? roleOf(config.admins.emails, config.admins.tags) : undefined, // tags: an admin by @username tag (docs/spaces-usernames.md § 13.1)
111
+ owners: config.owners && Array.isArray(config.owners.emails) ? roleOf(config.owners.emails, config.owners.tags) : undefined, // OWNERS (2026-10-03): above admins, enforced by the room
111
112
  forkedFrom: typeof config.forkedFrom === 'string' && config.forkedFrom ? config.forkedFrom.slice(0, 120) : undefined,
112
113
  connections: Array.isArray(config.connections) && config.connections.length ? config.connections : undefined,
113
114
  direct: config.direct === true ? true : undefined, // a DIRECT chat (directChat.js): the server refuses its rename, the other side files it by this
@@ -1305,6 +1306,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1305
1306
  // A member by @username, as the room-bound TAG no guessed email can be linked to (docs/spaces-usernames.md §12)
1306
1307
  userTag: async (username, room) => call(endpoint, { op: 'user', mode: 'tag', username, room }, f), // a DIRECTORY op (the room is only its salt): the Lambda answers it for a room of either tier — through post() a confidential room's went to the enclave, which has no directory (sync sweep 10-21 #5)
1307
1308
  userWhoami: async (idToken) => post({ op: 'user', mode: 'whoami', idToken }),
1309
+ userAsUser: async (asUser, idToken) => extrasCache.clear() || post({ op: 'user', mode: 'asuser', asUser: asUser !== false, idToken }), // "Add me to Spaces as @username" (docs/spaces-usernames.md § 13); the hints carry it, so they are asked again
1308
1310
  userClaim: async (username, idToken, { name, publish } = {}) => extrasCache.clear() || post({ op: 'user', mode: 'claim', username, idToken, ...(publish ? { publish: true, ...(name ? { name } : {}) } : {}) }),
1309
1311
  userRelease: async (idToken, username) => extrasCache.clear() || post({ op: 'user', mode: 'release', idToken, ...(username ? { username } : {}) }), // username (optional): only that name — the server refuses 'changed' when the account holds another now
1310
1312
  dirErase: async (idToken, scope) => post({ op: 'dir', mode: 'erase', idToken, ...(scope ? { dirScope: scope } : {}) }), // DELETE MY ACCOUNT (docs/user-erasure.md): the token's own directory row + inboxes
@@ -1447,7 +1449,9 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1447
1449
  if ('platformTools' in p) next.platformTools = p.platformTools === false || Array.isArray(p.platformTools) ? p.platformTools : undefined // which platform tools the assistant gets; null/true = all again
1448
1450
  if ('framing' in p) next.framing = p.framing === 'builder' ? 'builder' : undefined // builder mode: the app's prompt only; null = the Spaces framing again
1449
1451
  // WHO RUNS IT (a role change in place — no new key; the server checks who may: agent/roomRekey.mayChangeRoles)
1450
- for (const k of ['admins', 'owners']) if (k in p) next[k] = { emails: [...new Set(((p[k] && p[k].emails) || []).map((e) => String(e).trim().toLowerCase()).filter(Boolean))] }
1452
+ // a role names emails and @username tags (docs/spaces-usernames.md § 13.1): `tags` stated → those; unstated → the room's kept (a caller
1453
+ // that knows only emails never drops a role held by a tag)
1454
+ for (const k of ['admins', 'owners']) if (k in p) { const tags = p[k] && Array.isArray(p[k].tags) ? p[k].tags : (cur[k] && Array.isArray(cur[k].tags) ? cur[k].tags : []); next[k] = roleOf((p[k] && p[k].emails) || [], tags) }
1451
1455
  if ('lanes' in p) next.lanes = p.lanes === true // "Private assistants" off (or on) in place (docs/always-on-agent-plan.md Phase 0b)
1452
1456
  if ('dataWrites' in p) next.dataWrites = p.dataWrites === false ? false : undefined // false = data_query only; null/true = writes offered again
1453
1457
  if ('safeMedia' in p) next.safeMedia = p.safeMedia === true ? true : undefined // SAFE MEDIA on/off (docs/safe-media.md): the admins', any member's where there are none