@witbitz/sdk 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +26 -5
  3. package/accountErase.js +6 -1
  4. package/accountRecord.js +2 -2
  5. package/agentDoorTools.js +28 -0
  6. package/chatLock.js +16 -0
  7. package/cloudDevicePins.js +2 -2
  8. package/codeAttachments.js +100 -0
  9. package/codeCache.js +149 -0
  10. package/codeCloud.js +0 -2
  11. package/codeComputers.js +1 -0
  12. package/codeFolders.js +116 -0
  13. package/codeHistory.js +76 -0
  14. package/codeLanguage.js +54 -0
  15. package/codeModes.js +2 -0
  16. package/codeProgress.js +54 -0
  17. package/codeSent.js +68 -0
  18. package/codeSubagents.js +107 -0
  19. package/codeTransport.js +22 -0
  20. package/connections.js +17 -18
  21. package/deviceAttest.js +9 -3
  22. package/idb.js +19 -3
  23. package/jobAgents.js +2 -2
  24. package/keptMerge.js +9 -2
  25. package/l1-worker-src.js +1 -1
  26. package/l1-worker.js +93 -30
  27. package/laneAssociation.js +68 -0
  28. package/laneConfig.js +4 -3
  29. package/manifest.json +80 -61
  30. package/memberChange.js +4 -2
  31. package/mirrorBatch.js +47 -0
  32. package/opRouting.js +10 -0
  33. package/package.json +21 -2
  34. package/pdfOptions.js +13 -0
  35. package/pdfText.js +107 -0
  36. package/pdfjs.mjs +28 -0
  37. package/pdfjs.worker.mjs +28 -0
  38. package/protectedLocal.js +18 -2
  39. package/removedMessage.js +1 -1
  40. package/roomEmbed.js +111 -0
  41. package/roomName.js +1 -1
  42. package/roomRoster.js +21 -5
  43. package/rosterCount.js +6 -3
  44. package/sdkA2A.js +160 -40
  45. package/sdkAccount.js +17 -4
  46. package/sdkAccountDoc.js +11 -3
  47. package/sdkAccountSections.js +117 -8
  48. package/sdkBackup.js +35 -8
  49. package/sdkCloudDevice.js +8 -2
  50. package/sdkComputers.js +582 -53
  51. package/sdkDictation.js +114 -24
  52. package/sdkErase.js +9 -4
  53. package/sdkExports.js +4 -2
  54. package/sdkLaneLink.js +3 -3
  55. package/sdkPlan.js +4 -2
  56. package/sdkRekey.js +50 -17
  57. package/sdkReport.js +1 -1
  58. package/sdkSafeMedia.js +1 -1
  59. package/sdkSpeech.js +19 -2
  60. package/sdkTemporaryRooms.js +123 -0
  61. package/sdkVault.js +66 -10
  62. package/sentinelRelease.js +1 -0
  63. package/sharedViews.js +17 -3
  64. package/siri.js +114 -7
  65. package/spaceClient.js +16 -5
  66. package/spaceEmailGate.js +2 -2
  67. package/spaceTemplates.js +99 -0
  68. package/speechOut.js +4 -2
  69. package/store.js +83 -14
  70. package/sw-notif-core.js +9 -7
  71. package/turnVerdict.js +1 -0
  72. package/vault-core.js +480 -112
  73. package/vault-kit.mjs +2 -2
  74. package/vault-screens.js +5 -7
  75. package/vaultAtRest.js +35 -4
  76. package/vaultKeep.js +9 -3
  77. package/vaultWorkerHost.js +23 -4
  78. package/witbitz-admin.mjs +12 -11
  79. package/witbitz-sdk.d.ts +115 -24
  80. package/witbitz-sdk.js +572 -149
package/witbitz-sdk.js CHANGED
@@ -15,6 +15,7 @@
15
15
  // cross-origin import of this one URL pulls the transitive crypto from this origin automatically. The room key never
16
16
  // reaches the server — only its commitment — and reads are content-blind (the client opens the sealed ledger locally).
17
17
  // `space.sealedProof()` returns the exact opaque bytes the server stores, so an app can PROVE that at rest.
18
+ import { mirrorBatches } from './mirrorBatch.js'
18
19
  import { makeSpaceClient } from './spaceClient.js'
19
20
  import { ownAdmissionEntries } from './emptySpaces.js'
20
21
  import { memberHash } from './rosterHash.js'
@@ -22,6 +23,7 @@ import { verifyAttestation } from './nitroVerify.js' // devRoot: the dev server'
22
23
  import { AccountBackup } from './sdkBackup.js'
23
24
  import { linkLanes, laneLinkTool } from './sdkLaneLink.js' // lane.link(other): two of a member's assistants ask each other
24
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)
26
+ import { TemporaryRooms } from './sdkTemporaryRooms.js'
25
27
  import { Computers } from './sdkComputers.js' // wb.computers: the person's cloud computers (docs/sdk-cloud-computers.md)
26
28
  import { opensEnvelopes, sealsIdentity } from './reqEnvelope.js' // the sealed request envelope: does a live enclave open it
27
29
  import { SpaceSafeMedia } from './sdkSafeMedia.js' // space.safeMedia: photos and PDFs shown from copies an attested enclave made safe (docs/safe-media.md)
@@ -35,7 +37,7 @@ import { removedCopy, sharedRemovedCopy } from './removedMessage.js'
35
37
  import { entryKeyOf as removedEntryKey } from './ledgerView.js'
36
38
  import { fileReport, REPORT_REASONS } from './sdkReport.js' // space.report(): the Spaces app's Report (App Store rule 1.2; docs/report-and-block.md §3)
37
39
  import { safeMediaReady } from './safeMedia.js'
38
- import { A2AAccount, LaneA2A, VaultLaneA2A, pendingOf } from './sdkA2A.js' // wb.a2a + lane.a2a: outside agents into a private lane (https://witbitz.chat/docs/sdk-agents.md#a2a)
40
+ import { A2AAccount, LaneA2A, VaultLaneA2A, refreshVaultA2AViews, pendingOf } from './sdkA2A.js' // wb.a2a + lane.a2a: outside agents into a private lane (https://witbitz.chat/docs/sdk-agents.md#a2a)
39
41
  import { makeSdkAttest } from './sdkAttest.js' // attest: { bridge } — a device that proves itself (the cloud device)
40
42
  import { Builds } from './sdkBuilds.js' // wb.builds: which enclave build THIS PERSON accepts ('mine'), or any Witbitz publishes (default)
41
43
  import { Erasure } from './sdkErase.js' // wb.erasure: the deletion commitment, the membership mark, the filed erase list (https://witbitz.chat/docs/sdk-builder.md#user-erasure)
@@ -47,25 +49,26 @@ export { verifyEat, fetchAndVerifyEat, EAT_PROFILE } from './eat.js' // RATS/EAT
47
49
  import { Speech } from './sdkSpeech.js' // wb.speak(): text read aloud, the Spaces app's "Play aloud" player (speechOut.js)
48
50
  import { Dictation, voiceForDictation } from './sdkDictation.js' // wb.dictation(): press-to-talk, the mic straight to Tinfoil's realtime enclave
49
51
  import { Protect } from './sdkProtect.js' // wb.protect: what the app keeps on the device, sealed under a passkey-derived key
50
- import { boxesHash, bareEC, jkey, deriveRoster } from './spaceFork.js' // the membership fork's notice format, shared with the app
52
+ import { boxesHash, bareEC, jkey } from './spaceFork.js' // the membership fork's notice format, shared with the app
51
53
  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)
52
54
  import { deleteOwnRoom } from './roomDelete.js'
53
55
  import { sealTo, openBox, commit as keyCommit } from './e2ee.js'
54
56
  import { roomUsageRecords, summarizeUsage, usageCsv } from './usageSummary.js'
55
57
  import { stillOnList } from './memberChange.js'
56
- import { ROSTER_DOC, selfRow, ensureSelf, unseenIn, entriesMissing, announcedIn, privateInvitationMatches, listRoster, verifiedPosters, membersView } from './roomRoster.js'
58
+ import { ROSTER_DOC, selfRow, ensureSelf, unseenIn, entriesMissing, announcedIn, privateInvitationMatches, listRoster, verifiedPosters, verifiedSigningIds, membersView } from './roomRoster.js'
57
59
  import { reconstructMk } from './splitKeyClient.js' // the split-key combine + the mandatory commitment check
58
60
  // The account half — sign-in, connections, the Siri inbox — reuses the SAME modules the Spaces app runs (nothing
59
61
  // forked): the Sentinel attestation + grant sealing (connections.js), the Siri record and collector (siri.js), and the
60
62
  // sealing primitives. The SDK adds only the session and the state the app used to keep in its own store.
61
- import { attachConnection, listConnections, detachConnection, attestStandingSentinel, roomEntry, CONNECTION_HOST, STANDING_SENTINEL_PCR0, startMcpSignIn, finishMcpSignIn, attachMcp as attachMcpServer, listMcpTools, isCurated } from './connections.js'
63
+ import { postWithPendingKey, attachConnection, listConnections, detachConnection, attestStandingSentinel, roomEntry, CONNECTION_HOST, STANDING_SENTINEL_PCR0, startMcpSignIn, finishMcpSignIn, attachMcp as attachMcpServer, listMcpTools, isCurated } from './connections.js'
64
+ import { listGrantTools } from './agentDoorTools.js'
62
65
  import { readsAutoFor } from './connCatalog.js'
63
66
  import { lockConnections, wrapProof } from './connWrap.js' // move 3: the old-form connections locked under their key
64
67
  import { dispKeyOf, sealDisp } from './connDisp.js' // step 2: a connection's name sealed to the account's devices (docs/standing-sentinel.md)
65
68
  import { recommendedChoice } from './mcpRecommended.js' // an MCP server's recommended tools: reads run on their own, changes ask (as the app)
66
69
  import { roomTool, roomJob } from './connectionEntry.js' // one MCP tool's bounded room form
67
70
  import { withBook, bookTheRest } from './toolBooks.js' // an MCP connection's tools as a sealed tool book, as the app
68
- import { siriRecordFor, collectSiriDrops, newSiriKey, SIRI_ENDPOINT } from './siri.js'
71
+ import { uniqueAlias, siriAliasesDiffer, siriRecordFor, collectSiriDrops, newSiriKey, SIRI_ENDPOINT } from './siri.js'
69
72
  import { sealTo as sealToEnclave } from './sealShare.js'
70
73
  import { genRecipientKey } from './e2ee.js'
71
74
  import { genKeypair, spkNonce } from './entrySig.js'
@@ -88,7 +91,8 @@ import { renderSharedViews, viewsNamedIn, SHARED_VIEWS_DOC } from './sharedViews
88
91
  import { receiptOf } from './sealedReceipt.js' // a verified room's sealedProof, computed by the member
89
92
  import { replyQuote } from './replyQuote.js' // the reply quote — one rule with the app's reply strip
90
93
  import { makeLedgerView, needsTailResync, REACTION_RESYNC_TAIL, entryKeyOf, readAllPages } from './ledgerView.js' // how the Spaces app merges a room's entries
91
- import { turnVerdict, QUEUE_RETRY_MS, QUEUE_MAX_TRIES } from './turnVerdict.js' // the send hold + answer reading the Spaces app uses
94
+ import { roomInviteFlags, applySkills, roomEmbed } from './roomEmbed.js'
95
+ import { turnVerdict, QUEUE_RETRY_MS, QUEUE_MAX_TRIES, CONTINUATION_WINDOW_MS } from './turnVerdict.js' // the send hold + answer reading the Spaces app uses
92
96
  /** A turn's answer with `ok` always a boolean: posted / silent / pending → true; anything with an error, or busy, refused,
93
97
  * failed, no answer → false (Space#_turnHeld). */
94
98
  const withTurnOk = (r) => { const k = turnVerdict(r).kind; return withUsage({ ...(r || {}), ok: !(r && r.error) && (k === 'ok' || k === 'silent' || k === 'pending') }) }
@@ -102,7 +106,8 @@ import { WitbitzAdmin } from './witbitz-admin.js'
102
106
  import { Turn, turnUsage } from './sdkTurn.js' // space.turn(): a turn you can hold (sdk-roadmap item 6)
103
107
  import { planChange } from './sdkPlan.js'
104
108
  import { schemaProblem } from './rowSchema.js' // a collection's row schema — the same verdict as the server
105
- import { scopedAccount, tokenClaims, firstPartyAppOf, sentinelAccount, VAULTED_APP } from './accountScope.js' // the account a sign-in may act on — the same derivation as the Lambda
109
+ export { assistantTemplates } from './spaceTemplates.js'
110
+ import { scopedAccount, tokenApp, tokenClaims, firstPartyAppOf, sentinelAccount, VAULTED_APP } from './accountScope.js' // the account a sign-in may act on — the same derivation as the Lambda
106
111
  import { connectVault } from './sdkVault.js' // a builder-hosted vault holds the keys; this page never does (docs/sdk-vault-mode.md)
107
112
  import { makeTurnFeed } from './turnFeed.js' // one reading of a running turn, shared with the Spaces app
108
113
  import { roomRegion, regionCode, DEFAULT_REGION, newRoomId } from './regions.js' // a room's home region is in its id (docs/multi-region.md)
@@ -189,7 +194,7 @@ const perTurn = (instructions) => (typeof instructions === 'string' && instructi
189
194
  /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
190
195
  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)
191
196
  export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
192
- export const SDK_VERSION = '4.3.0'
197
+ export const SDK_VERSION = '4.4.0'
193
198
  // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
194
199
  const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
195
200
  /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
@@ -252,18 +257,28 @@ function mirrorBy(room, e) {
252
257
  return Object.keys(by).length ? { by } : {}
253
258
  }
254
259
  /** Attachments a COPY must carry as bytes: a stored one points at a blob sealed to the SOURCE room's key, which would
255
- * never open in the room it is copied to. A failed source read leaves the batch pending for the next mirror. */
260
+ * never open in the room it is copied to. A failed source read leaves the batch pending for the next mirror, for a few passes. */
256
261
  async function withBytes(from, list) {
257
262
  if (!Array.isArray(list) || !list.length) return undefined
258
263
  return Promise.all(list.map(async (a) => {
259
264
  if (!a || typeof a !== 'object' || (typeof a.b64 === 'string' && a.b64)) return a
260
265
  const { ref, parts, size, ...rest } = a
261
266
  if (!ref && !parts) return rest
262
- const o = await from.attachment(a)
263
- if (!o?.b64) throw sdkError('attachment bytes could not be copied', 'attachment_unavailable')
264
- return { ...rest, b64: o.b64, mime: a.mime || o.mime }
267
+ const key = ref || (Array.isArray(parts) ? parts.join(',') : '')
268
+ const misses = _copyMisses.get(from) || new Map()
269
+ let o = null
270
+ try { o = await from.attachment(a) } catch { o = null }
271
+ if (o?.b64) { misses.delete(key); return { ...rest, b64: o.b64, mime: a.mime || o.mime } }
272
+ // A few passes, then without the bytes (second review, 2026-11-27; the app's rule, mirrorLoop.js inlineForMirror): a blob that is
273
+ // gone failed every pass, the batch never landed, and no later message reached the lane — with no `error` event either.
274
+ const n = (misses.get(key) || 0) + 1
275
+ misses.set(key, n); _copyMisses.set(from, misses)
276
+ if (n < COPY_TRIES) throw sdkError('attachment bytes could not be copied', 'attachment_unavailable')
277
+ return rest
265
278
  }))
266
279
  }
280
+ const COPY_TRIES = 3
281
+ const _copyMisses = new WeakMap() // per source Space, this page's memory only
267
282
  const withMedia = (msg, images, files) => {
268
283
  const im = mediaList(images, 'images'), fl = mediaList(files, 'files')
269
284
  return { ...msg, ...(im ? { images: im } : {}), ...(fl ? { files: fl } : {}) }
@@ -365,7 +380,7 @@ export class Witbitz {
365
380
  * enclaveClaim?, fetchImpl?, WebSocketImpl? } —
366
381
  * `tenant` is your tenant's PUBLIC id (never a key): Spaces this page creates are attributed to it when the page's origin
367
382
  * is one the tenant declared. The full list, with defaults: https://witbitz.chat/docs/sdk-reference.md#configuration. */
368
- constructor({ endpoint = DEFAULT_ENDPOINT, tenantEndpoint, viewer = DEFAULT_VIEWER, app, tenant, tenantKey, session, loginBase, sentinel, fetchImpl, siri, live, WebSocketImpl, userToken, backup, enclaveClaim: encClaimUrl, vaultApi, appShare, deviceName, a2a, a2aEndpoint, invite, protect, region, builds, attest, client: pluggedClient, _roomPass, _renewSignIn, _appShareMember, devRoot } = {}) {
383
+ constructor({ endpoint = DEFAULT_ENDPOINT, tenantEndpoint, viewer = DEFAULT_VIEWER, app, tenant, tenantKey, session, loginBase, sentinel, fetchImpl, siri, live, WebSocketImpl, userToken, backup, keepTemporaryRooms = false, enclaveClaim: encClaimUrl, vaultApi, appShare, deviceName, a2a, a2aEndpoint, invite, protect, region, builds, attest, client: pluggedClient, _roomPass, _renewSignIn, _appShareMember, devRoot } = {}) {
369
384
  // THE DEV SERVER'S ATTESTATION ROOT (devserver/, the Witbitz dev server with a confidential tier): base64 DER. It REPLACES the
370
385
  // pinned AWS root for this client's confidential tier — so a client given it trusts only that local server's enclave, never
371
386
  // Witbitz's (shipped by mistake, it fails closed). Never set by default; nothing else reads it.
@@ -449,6 +464,7 @@ export class Witbitz {
449
464
  // names. So the SDK signs in the same way the Spaces app's "Email me a code" does — an emailed six-digit code,
450
465
  // any address, any origin (the endpoints answer cross-origin) — and keeps the SESSION the app may persist and hand
451
466
  // back (`new Witbitz({ session })`). `loginBase` is where the code endpoints live (the reference app's origin).
467
+ this.temporaryRooms = new TemporaryRooms(this, keepTemporaryRooms)
452
468
  this._endpoint = endpoint
453
469
  this._tenant = tenant || ''
454
470
  this._tenantKey = tenantKey || '' // SERVER-SIDE ONLY (https://witbitz.chat/docs/connections.md) — a wsk_ key in a page is a leak
@@ -528,6 +544,30 @@ export class Witbitz {
528
544
  /** The account's LIVE index (sdkAccount.js): the rooms, archived/forgotten marks and devices, kept in step between every
529
545
  * device that holds the backup. In a browser it syncs on its own once the backup is on; `sync()` any time. */
530
546
  this.account = new AccountIndex({ backup: this.backup, client: () => this._client, deviceName: deviceName || '', viewer: this._viewer, live: () => this._live, version: SDK_VERSION })
547
+ this.account._deleteLockTarget = async (kind, target, current, approved, afterRemoval) => {
548
+ if (kind === 'code') return this.computers._deleteLockedSession(target, current)
549
+ if (kind !== 'room' || !current()) return false
550
+ const fresh = await this.account.sync()
551
+ if (!current() || !fresh?.ok) return false
552
+ const children = this.backup.rooms.filter(r => r.shared === target && !r.detachedLane)
553
+ if (children.some(r => r.laneOrigin === 'minted' && !approved.has(r.room))) return false
554
+ for (const child of children) {
555
+ if (child.laneOrigin === 'minted') this.account.forget(child.room)
556
+ else this.backup._detachLane(child.room, target)
557
+ }
558
+ this.account.forget(target)
559
+ const synced = await this.account.sync()
560
+ if (!current() || !synced?.ok) return false
561
+ await this.backup.save()
562
+ if (!current() || this.backup.rooms.some(r => r.room === target || r.shared === target)) return false
563
+ if (afterRemoval) for (const child of children) {
564
+ if (!current()) return false
565
+ if (child.laneOrigin === 'minted') await afterRemoval('room', child.room)
566
+ }
567
+ return current()
568
+ }
569
+ this.account._pruneAgents = () => this.a2a._pruneForgotten()
570
+
531
571
  this.account._emptyHooks = () => this._emptySpaceHooks()
532
572
  this.account._readName = async row => {
533
573
  const { mk } = await this._openLink(row.link)
@@ -567,6 +607,8 @@ export class Witbitz {
567
607
  // work in a vault — the keyless client has no enrolment, the vault answers no read proof, and a proof would bind the
568
608
  // page's key, not the vault's (hosting.md § Rooms only your app may use)
569
609
  if (opts && opts.session !== undefined && opts.session !== null) throw sdkError('witbitz: in a vault, the vault keeps the session — do not pass one to Witbitz.inVault (wb.vault.signIn() / wb.vault.info.email)', 'vault_signs_in')
610
+ for (const name of ['devRoot', 'enclaveClaim']) if (opts?.[name] !== undefined) throw sdkError('witbitz: the vault supplies ' + name, 'vault_unsupported')
611
+ if (opts && opts.sentinel !== undefined) throw sdkError('witbitz: the vault supplies the Sentinel trust settings', 'vault_unsupported')
570
612
  if (opts && opts.attest !== undefined) throw sdkError("witbitz: attest is not available in a vault — attest is { bridge }, for a device that proves itself with its own hardware or enclave (a page's own proof, attest: { app }, was retired in 4.0.0)", 'vault_unsupported') // sync sweep 2026-11-23 #19: it pointed to the retired feature
571
613
  // THE ACCOUNT'S STATE IS THE VAULT'S (sync sweep 11-13 P7): a persisted `backup` / `siri` / `a2a` / `invite` state was taken
572
614
  // into the page — the backup's master secret, the Siri and A2A inboxes' private keys, the invite key — and a backup that was
@@ -576,9 +618,11 @@ export class Witbitz {
576
618
  // PER-USER BILLING REACHES THE VAULT (sync sweep, 10-17 #5): the vault's worker asks for the token on each op that can
577
619
  // spend, and the vault had none to give — billing was silently off, and requireUserToken refused every vault turn. The
578
620
  // page hands its current token to the vault right before each such op; the vault keeps it in memory only.
579
- const vc = conn.client
621
+ const vc = conn.client && { ...conn.client }
580
622
  if (vc && typeof conn.userToken === 'function') {
581
- let legacyBilling = Promise.resolve()
623
+ const queueKey = Symbol.for('witbitz.vault.legacyBilling')
624
+ const queues = globalThis[queueKey] ||= new Map()
625
+ const scope = conn.origin || conn
582
626
  const tokenSlot = { turn: 5, title: 4, decide: 6, importChat: 3, importWhatsApp: 3 }
583
627
  for (const op of Object.keys(tokenSlot)) {
584
628
  const orig = vc[op]; if (typeof orig !== 'function') continue
@@ -591,17 +635,19 @@ export class Witbitz {
591
635
  } catch { /* a missing billing token follows this operation's normal authorization rules */ }
592
636
  args[tokenSlot[op]] = token
593
637
  if (conn.info?.billingPerCall) return orig(...args)
594
- const run = legacyBilling.then(async () => {
638
+ const run = (queues.get(scope) || Promise.resolve()).then(async () => {
595
639
  try { await conn.userToken(token) }
596
640
  catch (error) { if (token || error?.code !== 'vault_refused') throw error }
597
641
  return orig(...args)
598
642
  })
599
- legacyBilling = run.catch(() => {})
643
+ const settled = run.catch(() => {})
644
+ queues.set(scope, settled)
645
+ settled.then(() => { if (queues.get(scope) === settled) queues.delete(scope) })
600
646
  return run
601
647
  }
602
648
  }
603
649
  }
604
- const wb = new Witbitz({ ...opts, ...(conn.info && conn.info.endpoint ? { endpoint: conn.info.endpoint } : {}), live: false, client: conn.client })
650
+ const wb = new Witbitz({ ...opts, builds: typeof opts.builds === 'object' && opts.builds ? { mode: opts.builds.mode } : opts.builds, ...(conn.info && conn.info.endpoint ? { endpoint: conn.info.endpoint } : {}), live: false, client: vc })
605
651
  wb._vaultLive = opts.live !== false // the page's own socket stays off (live: false); the vault streams for it unless the page said live: false
606
652
  wb.vault = new VaultSession(wb, conn)
607
653
  refuseInVault(wb)
@@ -612,13 +658,37 @@ export class Witbitz {
612
658
  * `wb.users.token(userId)` — a string, or a function (sync or async) returning a fresh one; null stops sending it.
613
659
  * It is sent only on ops that can spend (a turn, a title, approving an action, an import). A token that does not hold
614
660
  * is REFUSED (code user_token_invalid / user_key_unavailable), never billed to you. */
615
- useUserToken(token) { this._userToken = token || null; return this }
661
+ _forgetVoice() { this._dictation?._resetPayer(); this._speech?._resetPayer() }
662
+ useUserToken(token) { if (this._userToken !== (token || null)) this._forgetVoice(); this._userToken = token || null; return this }
616
663
 
617
664
  /** The signed-in session `{ email, idToken, exp, sign }`, or null. JSON-safe: persist it and pass it back as
618
665
  * `new Witbitz({ session })`. It carries a private signing key — keep it where you keep secrets. */
619
666
  get session() { return this._session }
620
667
  /** Adopt a session persisted earlier (or drop it with null). */
621
- useSession(session) { const next = sessionOf(session); if (this._session?.email !== next?.email) this._archiveGeneration++; this._session = next; if (this._session && this._session.idToken) this._prefetchIdentity(); return this }
668
+ useSession(session) {
669
+ const next = sessionOf(session)
670
+ const scope = s => { const c = tokenClaims(s?.idToken); return firstPartyAppOf(c) === 'vaulted' ? VAULTED_APP : tokenApp(c) }
671
+ if (this._session?.email !== next?.email || scope(this._session) !== scope(next)) {
672
+ // The generation marks handles of the account that is LEAVING, so nothing of it runs on into the next one. A first sign-in
673
+ // (nobody → an account) leaves no account: bumped all the same, every Space opened before signing in — the usual order on a
674
+ // page that opens by link — had its handle closed for embed, assistant memory, linkPrivateRoom and the offline export
675
+ // (second review, 2026-11-27).
676
+ if (this._session) this._archiveGeneration++
677
+ this._forgetVoice()
678
+ if (this._session) { this._forgetSiriAccount(); this.a2a?._resetAccount() }
679
+ }
680
+ this._session = next
681
+ if (next?.idToken) this._prefetchIdentity()
682
+ return this
683
+ }
684
+ _forgetSiriAccount() {
685
+ const backup = this.backup?._s
686
+ if (backup && this._session?.email) {
687
+ this._siriBackupOwners ||= new WeakMap()
688
+ if (!this._siriBackupOwners.has(backup)) this._siriBackupOwners.set(backup, this._session.email)
689
+ }
690
+ this._siri = siriStateOf(null)
691
+ }
622
692
  /** The ACCOUNT this sign-in acts on (accountScope.js): the email for a sign-in made on Witbitz's own pages; an account of
623
693
  * this app's own (`dana@x.com.app-…`) for one made on yours — connections, Siri and A2A here are this app's, and the user's
624
694
  * own Witbitz account is not reachable from your page. '' when nobody is signed in. */
@@ -635,7 +705,7 @@ export class Witbitz {
635
705
  async signIn({ email, code, ticket, room = '' } = {}) {
636
706
  const result = await this._signInResult({ email, code, ticket, room })
637
707
  if (!code) return result
638
- this._session = result
708
+ this.useSession(result)
639
709
  this._enrollInvite()
640
710
  return result
641
711
  }
@@ -699,7 +769,7 @@ export class Witbitz {
699
769
  }
700
770
  _emailPost() { return makeEmailPost(this._loginBase, { fetchImpl: (...a) => this._fetch(...a) }) }
701
771
  /** Forget the session on this client (the token simply expires server-side). */
702
- signOut() { this._archiveGeneration++; this._session = null; return this }
772
+ signOut() { this.a2a?._resetAccount(); this._forgetSiriAccount(); this._forgetVoice(); this._archiveGeneration++; this._session = null; return this }
703
773
 
704
774
  /** Press-to-talk: `const mic = wb.dictation(); await mic.start({ onPartial }); const text = await mic.stop()`. The
705
775
  * microphone streams straight from the page to Tinfoil's confidential realtime enclave — never through Witbitz — on a
@@ -895,8 +965,9 @@ export class Witbitz {
895
965
  * → { sdk, endpoint, features, limits, tiers: { standard, enclave }, models: { regular, confidential } | null } */
896
966
  async capabilities() {
897
967
  const models = await this._modelCatalog().catch(() => null)
898
- let enclave = false
899
- try { await this._encClaimDoc(); enclave = true } catch { /* no published claim: no confidential tier here */ }
968
+ let enclave = this.vault ? null : false
969
+ if (this.vault?._c?.info?.tierQuery) enclave = await this.vault._c.enclaveAvailable().catch(() => null)
970
+ if (!this.vault) try { await this._encClaimDoc(); enclave = true } catch { /* no published claim: no confidential tier here */ }
900
971
  const ids = (l) => (Array.isArray(l) ? l.map((m) => m && m.id).filter(Boolean) : [])
901
972
  return { sdk: SDK_VERSION, endpoint: this._endpoint, features: [...FEATURES], limits: { ...LIMITS }, tiers: { standard: true, enclave }, models: models ? { regular: ids(models.regular), confidential: ids(models.confidential) } : null }
902
973
  }
@@ -933,11 +1004,12 @@ export class Witbitz {
933
1004
  const { saveOfflineReader } = await import('./sdkExports.js')
934
1005
  return saveOfflineReader()
935
1006
  }
936
- async exportOfflineArchive({ recoveryKeys = false, rooms } = {}) {
1007
+ async exportOfflineArchive({ recoveryKeys = false, rooms, destination = 'download' } = {}) {
1008
+ if (!['download', 'clipboard'].includes(destination) || (destination === 'clipboard' && recoveryKeys !== true)) throw sdkError('Clipboard export requires recoveryKeys', 'invalid_argument')
937
1009
  if (rooms !== undefined && (!Array.isArray(rooms) || rooms.some(sp => !sp || sp._wb !== this || sp._stopped || !sp.room))) throw sdkError('select open Spaces from this SDK client', 'invalid_argument')
938
- if (this.vault) return this.vault._c.account('backup', 'exportArchive', recoveryKeys === true, rooms?.map(sp => sp.room))
1010
+ if (this.vault) return this.vault._c.account('backup', 'exportArchive', recoveryKeys === true, rooms?.map(sp => sp.room), ...(destination === 'clipboard' ? [destination] : []))
939
1011
  const { saveAccountArchive } = await import('./sdkExports.js')
940
- const session = this._session, backup = this.backup._s
1012
+ const session = this._session, generation = this._archiveGeneration, backup = this.backup._s
941
1013
  const selected = new Map((rooms === undefined ? this.backup.rooms : []).map(r => [r.room, r]))
942
1014
  const opened = [...(this._archiveHandles || [])].filter(sp => sp._archiveGeneration === this._archiveGeneration && sp._archiveEmail === (session?.email || '') && sp._archiveMaster === (backup?.master || null))
943
1015
  if (rooms?.some(sp => !opened.includes(sp))) throw sdkError('select Spaces opened for this account', 'invalid_argument')
@@ -952,12 +1024,13 @@ export class Witbitz {
952
1024
  const saved = await this._client.exportSealed(room, mk)
953
1025
  if (saved?.status !== 200) throw sdkError('witbitz: this Space\u2019s history could not be read just now', 'unavailable')
954
1026
  return { key: mk, ledger: saved.sealed, count: saved.count }
955
- }, recoveryKeys === true, () => this._session === session && this.backup._s === backup)
1027
+ }, recoveryKeys === true, () => this._archiveGeneration === generation && (this.backup._s?.master || null) === (backup?.master || null), destination)
956
1028
  }
957
- async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, safeMedia, lanes, owner } = {}) {
1029
+ async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, usernames, safeMedia, lanes, owner } = {}) {
958
1030
  // A TEMPORARY ROOM (docs/visitor-limits.md): a `tmp-` room the deployment wipes when it is idle — `true`: after about half
959
1031
  // an hour, as the app's temporary Spaces; `{ days }` (1–7): that many days after its last question (a help desk on a
960
1032
  // public page, kept while the visitor comes back). Refused rather than faked where it cannot be wiped.
1033
+ const temporaryScope = this.vault ? null : this.temporaryRooms._scope()
961
1034
  let lapseDays = 0
962
1035
  if (temporary !== undefined && temporary !== false) {
963
1036
  if (temporary !== true && !(temporary && typeof temporary === 'object' && Number.isInteger(temporary.days) && temporary.days >= 1 && temporary.days <= 7)) throw sdkError('witbitz: temporary takes true or { days } — a whole number of days from 1 to 7', 'invalid_temporary')
@@ -974,7 +1047,7 @@ export class Witbitz {
974
1047
  if (lanes === true && temporary !== undefined && temporary !== false) throw sdkError('witbitz: a temporary room has no private lanes — a lane is a durable room, and its copies would outlive the wipe', 'temporary_room') // as the app (space.js)
975
1048
  if (safeMedia === true && temporary !== undefined && temporary !== false) throw sdkError('witbitz: a temporary room has no Safe media — the Spaces app never offers it there (New Space, ⋯ → This Space)', 'temporary_room') // newSpaceAssistants.js paintSafeOpt (sync sweep 2026-11-13)
976
1049
  if (safeMedia === true && !safeMediaReady()) throw sdkError('witbitz: no safe-media enclave is accepted in this release yet', 'safe_media_unavailable')
977
- if (this.vault) return this.vault._create({ agent, tools, immediateTools, clientTools, agentReplies, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, safeMedia, lanes }) // vault-core CREATE_FIELDS takes safeMedia and lanes
1050
+ if (this.vault) return this.vault._create({ agent, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, usernames, safeMedia, lanes }) // vault-core CREATE_FIELDS takes safeMedia and lanes
978
1051
  // A DIRECT CHAT (the Spaces app's, directChat.js): a verified Space with exactly you and one other person, you its owner,
979
1052
  // `direct: true` sealed in — the server refuses its rename and each side calls it by the other person (space.directPeer).
980
1053
  if (direct !== undefined) admission = directAdmission(direct, admission, this._session)
@@ -991,9 +1064,11 @@ export class Witbitz {
991
1064
  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' })
992
1065
  await this._checkModel(model || agent.model)
993
1066
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
1067
+ applySkills(cfg, skills)
994
1068
  if (Array.isArray(clientTools)) cfg.clientTools = clientTools
995
1069
  if (agentReplies !== undefined) cfg.agentReplies = agentReplies
996
1070
  if (direct !== undefined) cfg.direct = true
1071
+ if (usernames === false && gate?.admission === 'email') cfg.usernames = false
997
1072
  if (safeMedia === true) cfg.safeMedia = true // sealed with the rest (spaceClient.js create); a room without it is sealed exactly as before
998
1073
  if (lanes === true) cfg.lanes = true // every member's app makes them a private lane (roomSync.js ensureOwnLane reads it from the sealed config)
999
1074
  cfg.region = region || this._region // the room's home region is in its id (regions.js, docs/multi-region.md)
@@ -1018,12 +1093,31 @@ export class Witbitz {
1018
1093
  const link = lanes === true ? markLanesLink(gate ? markGateLink(base) : base) : gate ? markGateLink(base) : base // lanes=1: the app's hint — an invitee's app makes their lane without first reading the room's settings
1019
1094
  const sp = new Space(this._client, { room, mk, link: enc ? markEncLink(link) : link, viewer: this._viewer, wb: this, gated: !!gate, split })
1020
1095
  sp.safeMedia._learn(safeMedia === true, 0) // a new room's setting is what it was made with
1096
+ if (sp.temporary) await this.temporaryRooms._remember(sp, temporaryScope, { days: lapseDays, title: temporary?.title })
1021
1097
  const made = String(room).startsWith('tmp-') ? sp : this._backedUp(sp) // a temporary room is never in the account backup (it is wiped), as the app's
1022
1098
  if (direct !== undefined) await made.setReplyMode('ondemand').catch(() => {}) // the assistant is in the chat and answers when @mentioned, as in the app
1023
1099
  return made // an enclave room's link says so, or a fresh client cannot know (see ENC_MARK)
1024
1100
  }
1025
1101
 
1026
1102
  /** @private how a split room is created: through the builder's function when there is one (`via`), else here. */
1103
+ setAssistantMemory(spaces = []) {
1104
+ if (!Array.isArray(spaces) || spaces.length > LIMITS.links + 1) throw sdkError('witbitz: choose a bounded list of Spaces for assistant memory', 'invalid_argument')
1105
+ const group = new Map()
1106
+ for (const sp of spaces) {
1107
+ if (!(sp instanceof Space) || sp._wb !== this || sp._memoryOwner !== (this.vault ? this._memoryGeneration : this._archiveGeneration) || sp._sharedRoom || sp._detachedLane || sp.temporary || wasLaneRoom(this, sp.room)) throw sdkError('witbitz: choose ordinary Spaces opened by this SDK instance', 'invalid_argument')
1108
+ group.set(sp.room, sp)
1109
+ }
1110
+ this._assistantMemory = { group, generation: this._archiveGeneration, vaultGeneration: this._memoryGeneration }
1111
+ }
1112
+
1113
+ _memoryFor(sp) {
1114
+ const m = this._assistantMemory
1115
+ if (!m || sp._memoryOwner !== (this.vault ? this._memoryGeneration : this._archiveGeneration) || m.generation !== this._archiveGeneration || m.vaultGeneration !== this._memoryGeneration || !m.group.has(sp.room) || sp.temporary || sp._sharedRoom || sp._detachedLane) return []
1116
+ return [...m.group.values()].filter(other => other.room !== sp.room && other._isEnclave() === sp._isEnclave() && !other._detachedLane && (this.vault || other._mk)).map(other => ({
1117
+ room: other.room, ...(this.vault ? {} : { mk: other._mk }), label: other.title || 'Space',
1118
+ }))
1119
+ }
1120
+
1027
1121
  _splitOpts() { return { split: true, ...(this._appShareUrl ? { via: (body) => this._appShareCall(body) } : {}) } }
1028
1122
 
1029
1123
  /** @private one call to the builder's app-half function → { status, ...answer }. Same-origin by design: the function
@@ -1053,8 +1147,11 @@ export class Witbitz {
1053
1147
  * have instead of replaying the whole ledger (see `resume` on the {@link Space} constructor). → a live {@link Space}. */
1054
1148
  async openSpace(link, { resume, tier } = {}) {
1055
1149
  if (this.vault) throw sdkError('witbitz: in a vault, a link is opened by the vault (the link points at it) — then wb.vault.openRoom(room)', 'vault_opens_links')
1150
+ const temporaryScope = this.temporaryRooms._scope()
1056
1151
  const { room, mk, link: s, split } = await this._openLink(link, { tier })
1057
- return this._backedUp(new Space(this._client, { room, mk, link: s, viewer: this._viewer, resume, wb: this, split }))
1152
+ const sp = new Space(this._client, { room, mk, link: s, viewer: this._viewer, resume, wb: this, split })
1153
+ if (sp.temporary) await this.temporaryRooms._remember(sp, temporaryScope)
1154
+ return this._backedUp(sp)
1058
1155
  }
1059
1156
 
1060
1157
  /** Reopen a member's existing private lane — the link {@link Space#privateLane} returned (`lane.shareLink`) — on
@@ -1066,7 +1163,7 @@ export class Witbitz {
1066
1163
  async openLane(laneLink, { space, actions, resume, tier, mirror = false } = {}) {
1067
1164
  if (space && !this.vault) await assertNotKept(space)
1068
1165
  if (space && space.temporary) throw sdkError('witbitz: a temporary room has no private lane — the lane is a durable room, and its copies of the room would outlive the wipe', 'temporary_room') // as the app (roomSync.js ensureOwnLane; sync sweep 2026-10-27 #3)
1069
- if (space && (space._sharedRoom || wasLaneRoom(this, space.room))) throw sdkError('witbitz: a private lane has no lane of its own — open the lane on its Space', 'lane_of_lane') // as privateLane (sync sweep 11-08: openLane took a lane as the Space)
1166
+ if (space && (space._sharedRoom || space._detachedLane || wasLaneRoom(this, space.room))) throw sdkError('witbitz: a private lane has no lane of its own — open the lane on its Space', 'lane_of_lane') // as privateLane (sync sweep 11-08: openLane took a lane as the Space)
1070
1167
  if (this.vault) return this.vault._openLane(laneLink, { space, actions, resume, tier, mirror })
1071
1168
  if (!(space instanceof Space) || !space.room || !space._mk) throw sdkError('witbitz: openLane needs `space`, the shared Space the lane belongs to (from createSpace or openSpace) — a lane posts its crossings there', 'invalid_argument')
1072
1169
  if (roomFromLink(String(laneLink)) === space.room) throw sdkError('witbitz: that is the Space\'s own link, not a lane of it — open it with openSpace', 'invalid_argument') // a Space recorded as its own lane (sweep P1)
@@ -1085,6 +1182,10 @@ export class Witbitz {
1085
1182
  const laneIsEnclave = !!(this._enc && this._enc.rooms.has(room))
1086
1183
  const crossTier = laneIsEnclave !== sharedIsEnclave
1087
1184
  await refuseAttestedIntoPlain(this._client, space.room, space._mk, room, mk) // sync sweep 2026-11-15 #5: as the app's mirrorLoop.js
1185
+ const known = this.backup.rooms.find(r => r.room === room)
1186
+ if (space._wb !== this || known?.detachedLane || (known?.shared && known.shared !== space.room)) {
1187
+ throw sdkError('Open this private room with its recorded parent Space.', 'lane_space_mismatch')
1188
+ }
1088
1189
  return this._backedUp(new Lane(this._client, { room, mk, link: s, viewer: this._viewer, sharedRoom: space.room, sharedMk: space._mk, actions, resume, wb: this, shared: space, mirror: crossTier ? (mirror || true) : mirror, split, crossTier }))
1089
1190
  }
1090
1191
 
@@ -1184,10 +1285,13 @@ export class Space {
1184
1285
  this._lanesHint = lanes === true // in a vault the page holds no link: the vault's room list says it (sync sweep 2026-10-29 #3)
1185
1286
  this.epoch = null // latest key rotation observed by this handle
1186
1287
  this._a2aResume = resume && Array.isArray(resume.a2a) ? resume.a2a : null
1187
- this._gated = !!gated || GATE_MARK.test(String(link || '')) // an email-gated room (see markGateLink) — no config fetch to know it
1288
+ this._a2aReceipts = Array.isArray(resume?.a2aReceipts) ? resume.a2aReceipts.filter(key => typeof key === 'string' && key.length < 512).slice(-512) : []
1289
+ if ((this._a2aResume?.length || this._a2aReceipts.length) && wb) (wb._agentHandles ||= new Set()).add(this)
1290
+ this._gated = !!gated || roomInviteFlags(link).gated // an email-gated room (see markGateLink) — no config fetch to know it
1188
1291
  this._split = !!split || SPLIT_MARK.test(String(link || '')) // a split-key room: its link is half a key (https://witbitz.chat/docs/sdk-keys.md#split-key)
1189
1292
  this._liveOpts = live !== undefined ? live : (wb && wb._live) || null // room streams (null → polling only)
1190
1293
  this._stream = null; this._streamFrameAt = 0; this._partial = { text: null }; this._feed = makeTurnFeed() // turnFeed.js: the room's word on a running turn, read the same way the Spaces app reads it
1294
+ this._memoryOwner = wb?.vault ? wb._memoryGeneration : wb?._archiveGeneration
1191
1295
  this._wb = wb // the Witbitz client that opened this Space — its session and Siri state (null for a bare handle)
1192
1296
  /** This Space's connections: what ITS assistant may spend. `grant` needs a connection from `wb.connections`. */
1193
1297
  this.connections = new SpaceConnections(this)
@@ -1351,7 +1455,8 @@ export class Space {
1351
1455
  snapshot() {
1352
1456
  return {
1353
1457
  room: this.room,
1354
- ...(pendingOf(this._a2a ? this._a2a._pending : this._a2aResume).length ? { a2a: pendingOf(this._a2a ? this._a2a._pending : this._a2aResume) } : {}),
1458
+ ...((!this._wb?.a2a?._draftsSuspended && (this._a2a?._posted.size || this._a2aReceipts?.length)) ? { a2aReceipts: [...(this._a2a?._posted || this._a2aReceipts)].slice(-512) } : {}),
1459
+ ...(!this._wb?.a2a?._draftsSuspended && pendingOf(this._a2a ? this._a2a._pending : this._a2aResume).length ? { a2a: pendingOf(this._a2a ? this._a2a._pending : this._a2aResume) } : {}),
1355
1460
  count: this._count,
1356
1461
  etag: this._etag,
1357
1462
  messages: this.messages,
@@ -1398,6 +1503,7 @@ export class Space {
1398
1503
  _setTitle(t) {
1399
1504
  const same = this._title && this._title.title === t.title && this._title.manual === !!t.manual
1400
1505
  this._title = { title: t.title, manual: !!t.manual, by: t.by || '', ts: t.ts }
1506
+ if (!same && this.temporary && this._temporaryScope) this._wb.temporaryRooms._title(this)
1401
1507
  if (!same) this._emit('title', { title: t.title, manual: !!t.manual, by: t.by || '' })
1402
1508
  }
1403
1509
 
@@ -1433,7 +1539,7 @@ export class Space {
1433
1539
  get temporary() { return String(this.room || '').startsWith('tmp-') }
1434
1540
  /** True when this room gives every member a private assistant (`createSpace({ lanes: true })`, or a link that says so): the
1435
1541
  * Spaces app makes its users theirs; in your app, `privateLane()`. */
1436
- get lanes() { return this._lanesSetting === undefined ? this._lanesHint || LANES_MARK.test(String(this.shareLink || '')) : this._lanesSetting }
1542
+ get lanes() { return this._lanesSetting === undefined ? this._lanesHint || roomInviteFlags(this.shareLink).lanes : this._lanesSetting }
1437
1543
  /** Outside-agent door for a solo verified Space; group and open Spaces refuse on enable/collect. */
1438
1544
  get a2a() { return this._a2a || (this._a2a = this._wb && this._wb.vault ? new VaultLaneA2A(this, this._wb.vault._c) : new LaneA2A(this)) }
1439
1545
 
@@ -1471,7 +1577,61 @@ export class Space {
1471
1577
  * date, what is waiting, "answer in Hebrew" — and is NEVER stored, so it is not re-read from old messages every turn.
1472
1578
  * @param {string} text @param {object} [opts] { from, mode, instructions, images, files } — `from`: the display name to sign this
1473
1579
  * message as (default 'You'); `images` (≤ 4) / `files` (≤ 2) are { b64 | bytes, mime, name? }, refused over LIMITS at the call */
1474
- async send(text, { from = 'You', mode, instructions, dictation, images, files, stopKey, showPrompt, replyTo, tools, _onAttempt, _aborted } = {}) {
1580
+ linkPrivateRoom(target, { allowStandardDestination = false } = {}) {
1581
+ return this._privateRoomChange(target, false, allowStandardDestination === true)
1582
+ }
1583
+ unlinkPrivateRoom(target) { return this._privateRoomChange(target, true, false) }
1584
+ async _privateRoomChange(target, unlink, allowStandardDestination) {
1585
+ const wb = this._wb, room = target?.room
1586
+ const generation = () => wb?.vault ? wb._memoryGeneration : wb?._archiveGeneration
1587
+ const check = () => {
1588
+ if (!wb || target?._wb !== wb || target._memoryOwner !== generation() || this._memoryOwner !== generation())
1589
+ throw sdkError('Open both Spaces in the same account', 'account_changed')
1590
+ }
1591
+ check()
1592
+ if (!room || room === this.room || this.temporary || target.temporary || this._sharedRoom || this._detachedLane || wasLaneRoom(wb, this.room))
1593
+ throw sdkError('Choose a parent Space and a different durable private room.', 'invalid_argument')
1594
+ const method = unlink ? 'unlink' : 'link'
1595
+ if (wb.vault) return wb.vault._c.roomAccount(this.room, 'privateRoom', method, room, { allowStandardDestination })
1596
+ if (!wb.account.enabled) throw sdkError('Enable account backup to sync this room link.', 'backup_required')
1597
+ const sync = async () => {
1598
+ const r = await wb.account.sync()
1599
+ check()
1600
+ if (!r?.ok) throw sdkError('The room link could not be synced. Try again.', 'index_unavailable')
1601
+ }
1602
+ await sync()
1603
+ const record = wb.backup.rooms.find(r => r.room === room)
1604
+ if (!record || !wb.backup.rooms.some(r => r.room === this.room)) throw sdkError('Add both Spaces to this account first.', 'not_in_account')
1605
+ if (record.shared && record.shared !== this.room) throw sdkError('This private room is linked to a different Space.', 'already_linked')
1606
+ if (unlink) {
1607
+ if (!record.shared && !record.detachedLane) throw sdkError('This room is not linked to this Space.', 'not_linked')
1608
+ wb.backup._detachLane(room, this.room)
1609
+ for (const lane of wb._openLanes || []) if (lane.room === room && lane._sharedRoom === this.room) lane._detachShared()
1610
+ } else {
1611
+ if (wb.backup.rooms.some(r => r.shared === room && !r.detachedLane)) throw sdkError('A Space with private rooms cannot become a private room.', 'lane_of_lane')
1612
+ const cfg = await this._client.getConfig(this.room, this._mk, { plainMark: true })
1613
+ if (!cfg || gatedStub(cfg)) throw sdkError('Could not read the parent Space settings.', 'lane_wait')
1614
+ if (cfg.lanes === false) throw sdkError('Private assistants are disabled in this Space.', 'lanes_disabled')
1615
+ await assertNotKept(this); await assertNotKept(target)
1616
+ const confidential = sp => wb._enc.rooms.has(sp.room) || ENC_MARK.test(sp.shareLink || '')
1617
+ if (confidential(this) && !confidential(target) && !allowStandardDestination) throw sdkError('The private room uses the standard tier. Confirm before linking it.', 'tier_mismatch')
1618
+ await refuseAttestedIntoPlain(this._client, this.room, this._mk, room, target._mk)
1619
+ check()
1620
+ wb.backup._attachLane(room, this.room)
1621
+ }
1622
+ await sync()
1623
+ const accepted = wb.backup.rooms.find(r => r.room === room)
1624
+ if (!accepted || (unlink ? accepted.shared === this.room : accepted.detachedLane || accepted.shared !== this.room))
1625
+ throw sdkError('A different room link won the account sync. Reopen the room and try again.', 'association_changed')
1626
+ return { room, parent: this.room, linked: !unlink }
1627
+ }
1628
+ get embed() { return (this._embed ||= roomEmbed(this, () => wasLaneRoom(this._wb, this.room))).api }
1629
+ async invokeSkill(name, args = {}) {
1630
+ if (typeof name !== 'string' || !name.trim() || name.trim().length > 64 || !args || typeof args !== 'object' || Array.isArray(args)) throw sdkError('Choose a named skill and supply an arguments object.', 'invalid_argument')
1631
+ return this.send('', { _skill: { name: name.trim(), args } })
1632
+ }
1633
+
1634
+ async send(text, { from = 'You', mode, instructions, dictation, images, files, stopKey, showPrompt, replyTo, tools, _onAttempt, _aborted, _skill } = {}) {
1475
1635
  { const f = arguments[1] && arguments[1].from; if (typeof f === 'string' && !arguments[1]._peerPost) this._who(f) } // remember the name this member uses
1476
1636
  // PER-QUESTION TOOLS on a plain room (docs/visitor-limits.md: a help desk's "search the guide", "which screen am I on"):
1477
1637
  // the same action shape a Lane takes, offered for THIS question only; an `await` action is answered by this page while
@@ -1484,7 +1644,7 @@ export class Space {
1484
1644
  if (extra.defs.length) toolOpts = { clientTools: extra.defs, clientGuidance: extra.guidance }
1485
1645
  }
1486
1646
  if (this._feed) this._feed.sent() // a new turn: its own words are never held back by the previous answer (turnFeed.js; the app does the same — sync sweep 10-16 #10)
1487
- const msg = withMedia({ from, text: String(text), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files) // `images` ≤ 4, `files` ≤ 2 — see LIMITS
1647
+ const msg = withMedia({ from, ...(_skill ? { mcp: _skill } : { text: String(text) }), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files) // `images` ≤ 4, `files` ≤ 2 — see LIMITS
1488
1648
  const rt = replyRef(replyTo); if (rt) msg.replyTo = rt // a reply quotes the message it answers, as the app's do
1489
1649
  await this.safeMedia._prepare(msg) // a Safe media room: its photos' and PDFs' safe copies start now, and go beside it once stored
1490
1650
  const opts = { ...(await this._turnOpts(mode)), ...toolOpts, ...perTurn(instructions), ...stopOpt(stopKey), ...promptOpt(showPrompt) }
@@ -1577,7 +1737,7 @@ export class Space {
1577
1737
  // from the server is { status, error, message } with NO ok, while a success usually carries the server's own ok:true —
1578
1738
  // so `r.ok !== false` read every refusal as a success. Now ok is always a boolean, read as turnVerdict reads the turn:
1579
1739
  // posted, silent and pending are ok; busy, refused, failed and no answer are not; an error field is never ok.
1580
- async _turnHeld(doTurn, onAttempt, aborted, noHold) { // noHold: a link's ask — the first busy answer comes back (the app's tell_lane says "busy"); sync sweep, 2026-10-10 // aborted(): space.turn()'s abort() — a held message is never resent after it (sync sweep, 2026-10-10) // turnVerdict.js — the hold policy and the reading the Spaces app's send uses
1740
+ async _turnHeld(doTurn, onAttempt, aborted, noHold, deadline) { // noHold: a link's ask — the first busy answer comes back (the app's tell_lane says "busy"); sync sweep, 2026-10-10 // aborted(): space.turn()'s abort() — a held message is never resent after it (sync sweep, 2026-10-10) // turnVerdict.js — the hold policy and the reading the Spaces app's send uses
1581
1741
  const run = doTurn
1582
1742
  // A transport failure (no network, an enclave that cannot be reached or verified) is an ANSWER too: `send()` does not
1583
1743
  // throw (sdk.md) — it resolves { ok: false, status: 0, error } (sync sweep, 2026-10-10). Bad arguments still throw
@@ -1588,9 +1748,10 @@ export class Space {
1588
1748
  }
1589
1749
  let r = await doTurn()
1590
1750
  for (let i = 0; turnVerdict(r).kind === 'busy' && !noHold; i++) {
1591
- if (i >= (this._queueMaxTries ?? QUEUE_MAX_TRIES)) return { ...r, ok: false, error: 'busy', detail: 'the assistant was still replying; the message was not stored — send it again' }
1751
+ if (deadline ? Date.now() >= deadline : i >= (this._queueMaxTries ?? QUEUE_MAX_TRIES)) return { ...r, ok: false, error: 'busy', detail: 'the assistant was still replying; the message was not stored — send it again' }
1592
1752
  this._kick()
1593
- await new Promise((res) => setTimeout(res, this._queueRetryMs ?? QUEUE_RETRY_MS))
1753
+ await new Promise((res) => setTimeout(res, Math.min(this._queueRetryMs ?? QUEUE_RETRY_MS, deadline ? deadline - Date.now() : Infinity)))
1754
+ if (deadline && Date.now() >= deadline) return { ...r, ok: false, error: 'busy' }
1594
1755
  if (this._stopped) return { ...r, ok: false, error: 'closed', detail: 'the Space was closed while the assistant was busy — the message was not stored' } // V#17: a closed handle does not keep resending for ~3 min
1595
1756
  if (aborted && aborted()) return { ...r, ok: false, error: 'aborted', detail: 'aborted while the assistant was busy — the message was not stored' }
1596
1757
  r = await doTurn()
@@ -1613,7 +1774,7 @@ export class Space {
1613
1774
  if (!REPLY_MODES.includes(mode)) throw sdkError(`unknown reply mode ${JSON.stringify(mode)} — one of ${REPLY_MODES.join(', ')}`, 'invalid_argument')
1614
1775
  // A PRIVATE LANE ALWAYS REPLIES (the server: spaceService respondMode — a bridged lane is 'always'; the app hides the chip there):
1615
1776
  // a mode stored on it changed nothing and was reported back as if it did (sync sweep 2026-11-14 P1, owner: yes)
1616
- if (this._sharedRoom) throw sdkError('witbitz: a private lane always replies — its reply mode cannot be set', 'lane')
1777
+ if (this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)) throw sdkError('witbitz: a private lane always replies — its reply mode cannot be set', 'lane')
1617
1778
  const r = await this._client.state(this.room, this._mk, 'agentmode', { mode }, REPLY_MODE_LABEL[mode])
1618
1779
  if (!r || r.status !== 200) throw refused('setReplyMode', r) // every error carries a code (sync sweep, 2026-10-10)
1619
1780
  this._mode = mode
@@ -1658,7 +1819,7 @@ export class Space {
1658
1819
  }
1659
1820
 
1660
1821
  async replyMode() {
1661
- if (this._sharedRoom) return 'always' // a private lane: the server always replies there
1822
+ if (this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)) return 'always' // a private lane: the server always replies there
1662
1823
  await this._modeReady
1663
1824
  if (this._mode) return this._mode
1664
1825
  let cfg = null
@@ -1685,6 +1846,8 @@ export class Space {
1685
1846
  // every turn there carries it). The proof binds the member's signing key and the room's fresh challenge; a member with no
1686
1847
  // sign-in signs with a key of this page's own (as the app's attested rooms do). Every other room: exactly as before.
1687
1848
  async _provenTurn(msg, opts) {
1849
+ const live = this._embed?.context()
1850
+ if (live) opts = { ...opts, context: [opts.context, live].filter(Boolean).join('\n\n').slice(0, 4000) }
1688
1851
  const att = this._wb && this._wb._attest
1689
1852
  const send = async () => {
1690
1853
  if (!this._needsProof || !att) return this._client.turn(this.room, this._mk, msg, this._identity(), opts)
@@ -1740,7 +1903,8 @@ export class Space {
1740
1903
  await this._freshSettings()
1741
1904
  const m = mode !== undefined ? mode : this._mode
1742
1905
  const model = turnModelOf(this._modelPick) // the room's model pick (the app's model chip) — over its create-time model, as every app turn does
1743
- return { ...extra, ...(m ? { mode: m } : {}), ...(model ? { model } : {}), ...(await this._receipt()) }
1906
+ const memory = extra.links ? [] : this._wb?._memoryFor?.(this) || []
1907
+ return { ...(memory.length ? { links: memory } : {}), ...extra, ...(m ? { mode: m } : {}), ...(model ? { model } : {}), ...(await this._receipt()) }
1744
1908
  }
1745
1909
  /** @private THE ACCOUNT'S USAGE RECEIPT for a turn here (docs/usage-receipts.md; the owner, 2026-10-23: a builder's app
1746
1910
  * records the account's usage too): the address the server seals this turn's cost to, from the account's usage key
@@ -1770,8 +1934,8 @@ export class Space {
1770
1934
  async exportFile() {
1771
1935
  if (this._wb?.vault) return this._wb.vault._c.roomAccount(this.room, 'portable', 'export')
1772
1936
  const { saveRoomExport } = await import('./sdkExports.js')
1773
- const session = this._wb?._session
1774
- return saveRoomExport(this, this._wb?._enc?.rooms.has(this.room) || ENC_MARK.test(this.shareLink || '') ? 'enclave' : 'standard', () => this._wb?._session === session)
1937
+ const generation = this._wb?._archiveGeneration
1938
+ return saveRoomExport(this, this._wb?._enc?.rooms.has(this.room) || ENC_MARK.test(this.shareLink || '') ? 'enclave' : 'standard', () => this._wb?._archiveGeneration === generation)
1775
1939
  }
1776
1940
  async sealedProof() {
1777
1941
  if (!(this._client && this._client.vault)) this._needKey('sealedProof') // a vault reads the stored boxes for the page (ciphertext only)
@@ -1854,7 +2018,7 @@ export class Space {
1854
2018
  }
1855
2019
 
1856
2020
  async _reattest() {
1857
- if (!this._isEnclave()) return false
2021
+ if (this._client?.keyless || this._client?.vault || !this._isEnclave()) return false
1858
2022
  if (this._reattestP) return this._reattestP
1859
2023
  if (Date.now() - (this._reattestAt || 0) < 10000) return !!this._reattestLast
1860
2024
  this._reattestAt = Date.now()
@@ -1872,6 +2036,7 @@ export class Space {
1872
2036
  /** @private announce this device in the room's guest book under its signing key, once per open: the email gate then
1873
2037
  * vouches for the address behind it (the server's `seen`), which is how a fork finds the remaining members' devices. */
1874
2038
  async _announce() {
2039
+ if (!this._gated && !this._client?.vault) return
1875
2040
  this._announced = true
1876
2041
  if (this._client && this._client.vault && this._wb && this._wb.vault) { if (!this._sharedRoom) this._wb.vault._c.announce(this.room).catch(() => {}); return } // the vault's device, by its own rule
1877
2042
  const sess = this._wb && this._wb._session
@@ -1891,7 +2056,10 @@ export class Space {
1891
2056
  const { roster, changed } = ensureSelf(r.state, self)
1892
2057
  if (!changed && !unseenIn(r.seen, self.id) && !entriesMissing(r.seen, self.id, this.room)) return // entries: one more announce per page, never retried
1893
2058
  if (this._stopped || this._wb._session !== sess) return
1894
- const written = await this._client.state(this.room, this._mk, ROSTER_DOC, { people: roster }, '', 'member', r.v || 0)
2059
+ // THE SHAPE THE ROOM ALREADY HAS (second review, 2026-11-27): the app's book is { people: [...] }, an SDK room's was the list itself.
2060
+ // SDK 4.3.0 wrote the app's shape everywhere (c48d05a35) — but a 4.2.0 page (published, unchangeable) reads only a list: in a
2061
+ // builder's room with both open it saw nobody and wrote back only itself. A list stays a list; anything else is the app's shape.
2062
+ const written = await this._client.state(this.room, this._mk, ROSTER_DOC, Array.isArray(r.state) ? roster : { people: roster }, '', 'member', r.v || 0)
1895
2063
  if (written?.status === 409) continue
1896
2064
  if (written?.status !== 200) return
1897
2065
  announcedIn(this.room, self.id)
@@ -1988,7 +2156,7 @@ export class Space {
1988
2156
  const claims = (Array.isArray(book.state) ? book.state : book.state?.people || []).some(row => row?.verified)
1989
2157
  const history = claims || cfg.admission === 'email' ? await this._roomHistory() : { entries: [] }
1990
2158
  const entries = history.entries || []
1991
- const attested = new Set(deriveRoster(entries, null).map(p => jkey(p.spk)))
2159
+ const attested = verifiedSigningIds(entries)
1992
2160
  const posters = verifiedPosters(entries, book.seen || {})
1993
2161
  const rows = listRoster(book.state, { attested: row => !!seen[row.id] || attested.has(row.id) })
1994
2162
  if (cfg.admission !== 'email') return {
@@ -2015,7 +2183,7 @@ export class Space {
2015
2183
  }
2016
2184
  const cfg = await this._gateConfig({ plainMark: true })
2017
2185
  const lanesOn = cfg.lanes === true ? { lanes: true } : {} // a Space whose members get private lanes (createSpace({ lanes }), the app's option) — sealed
2018
- if (cfg.admission !== 'email') return { gated: false, ...(cfg.lane === true ? { lane: true } : {}), ...lanesOn }
2186
+ if (cfg.admission !== 'email') return { gated: false, ...(cfg.lane === true || cfg.bridge ? { lane: true } : {}), ...lanesOn }
2019
2187
  const a = cfg.allow || {}
2020
2188
  const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [])
2021
2189
  const legacy = Array.isArray(a.users) ? a.users.length : 0 // a legacy room's @username entries: counted as hidden — no username is read back (2026-10-11)
@@ -2061,7 +2229,7 @@ export class Space {
2061
2229
  * hidden (hashed) one, or the address's domain. An open room admits everyone. ⚑ A member admitted by @username alone
2062
2230
  * cannot be checked here — that match needs the server's key — so it reads `false` for them. */
2063
2231
  async admits(email) {
2064
- const e = String(email || '').normalize('NFKC').trim().toLowerCase()
2232
+ const e = String(email || '').trim().toLowerCase()
2065
2233
  const at = e.indexOf('@')
2066
2234
  if (at < 1 || at === e.length - 1) throw sdkError(`witbitz: "${email}" is not an email address`, 'invalid_argument')
2067
2235
  const cfg = await this._gateConfig({ plainMark: true })
@@ -2201,7 +2369,7 @@ export class Space {
2201
2369
  // A LANE HAS NO LANE (sweep P1): a lane of a lane was minted — a third room carrying the member's thinking one hop further,
2202
2370
  // which nothing in the app makes and nothing reads back
2203
2371
  if (this._client && this._client.vault) return this._vaultLane({ agent, actions, tools, immediateTools, model, data, admission, tier, mirror, platformTools, framing, dataWrites }) // the vault refuses a lane of a lane itself (vault-core createLane)
2204
- if (this._sharedRoom || wasLaneRoom(this._wb, this.room)) throw sdkError('witbitz: a private lane has no lane of its own — ask from its Space', 'lane_of_lane') // …nor a room that WAS one, opened as a Space (openSpace(laneLink)) — as the app (roomSync.js isLaneRoom; sync sweep 11-11 #3)
2372
+ if (this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)) throw sdkError('witbitz: a private lane has no lane of its own — ask from its Space', 'lane_of_lane') // …nor a room that WAS one, opened as a Space (openSpace(laneLink)) — as the app (roomSync.js isLaneRoom; sync sweep 11-11 #3)
2205
2373
  await assertNotKept(this)
2206
2374
  this._needKey('privateLane')
2207
2375
  let gate = normAdmission(admission) // a lane can be gated too — it is the member's OWN room
@@ -2258,7 +2426,8 @@ export class Space {
2258
2426
  if (typeof this._client.attestedRoom === 'function') { try { attested = !!(await this._client.attestedRoom(this.room, this._mk)) } catch { throw sdkError("witbitz: whether this Space requires an attested app could not be read, so its private lane waits — try again", 'lane_wait') } } // a failed read is not 'not attested' (sync sweep 11-08)
2259
2427
  const inh = laneInherits(sharedCfg, { email: me, attested })
2260
2428
  if (inh.wait === 'attested') throw sdkError('witbitz: this Space requires an attested app, so its private lane is made only by that app (the Witbitz app on the device), under the same rule — not by the SDK', 'attested')
2261
- if (tools === undefined && immediateTools === undefined) { tools = inh.config.tools; immediateTools = inh.config.immediateTools }
2429
+ if (tools === undefined && immediateTools === undefined && agent?.tools === undefined) { tools = inh.config.tools; immediateTools = inh.config.immediateTools }
2430
+ if (platformTools === undefined) platformTools = inh.config.platformTools
2262
2431
  if (sharedCfg && sharedCfg.admission === 'email') {
2263
2432
  if (admission === undefined) {
2264
2433
  if (inh.wait === 'email') throw sdkError("witbitz: this Space is verified, so its private lane is gated to you — sign in first (" + signInHow(wb) + ")", 'sign_in_required')
@@ -2278,6 +2447,7 @@ export class Space {
2278
2447
  // 2026-10-24 — it sent the standard room as a bridge the enclave could not find, and its assistant never saw the room).
2279
2448
  const crossTier = enc !== sharedIsEnclave
2280
2449
  const lane = new Lane(this._client, { room, mk, link: enc ? markEncLink(laneBase) : laneBase, viewer: this._viewer, sharedRoom: this.room, sharedMk: this._mk, actions, wb: this._wb, shared: this, mirror: crossTier ? (mirror || true) : mirror, split, crossTier })
2450
+ lane._laneOrigin = 'minted'
2281
2451
  return wb ? wb._backedUp(lane) : lane
2282
2452
  }
2283
2453
 
@@ -2292,14 +2462,22 @@ export class Space {
2292
2462
  }
2293
2463
  if (wb) await wb._checkModel(model || agent.model)
2294
2464
  const gate = normAdmission(admission)
2295
- if (tools === undefined && immediateTools === undefined) {
2296
- try { const inh = inheritToolsFrom(await this._client.getConfig(this.room, null)); tools = inh.tools; immediateTools = inh.immediateTools } catch { /* unreadable: the lane gets the defaults */ }
2465
+ const inheritCustom = tools === undefined && immediateTools === undefined && agent?.tools === undefined
2466
+ const inheritPlatform = platformTools === undefined
2467
+ if (inheritCustom || inheritPlatform) {
2468
+ try {
2469
+ const inherited = inheritToolsFrom(await this._client.getConfig(this.room, null))
2470
+ if (inheritCustom) { tools = inherited.tools; immediateTools = inherited.immediateTools }
2471
+ if (inheritPlatform) platformTools = inherited.platformTools
2472
+ } catch { /* the vault reads the settings before creating the lane */ }
2297
2473
  }
2298
2474
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: LANE_AGENT_NAME, persona: framingOpt(framing) ? '' : DEFAULT_ASSIST })
2299
2475
  cfg.region = roomRegion(this.room)
2300
2476
  // an `admission` that opens the lane reaches the vault as `{ open }` (an open room's config names no admission, so the vault
2301
2477
  // could not tell it from none): in a verified Space it is refused by name, as outside a vault (lane_downgrade)
2302
- const { room } = await wb.vault._c.createLane(this.room, cfg, admission !== undefined && !(gate && gate.admission === 'email') ? { open: true } : undefined)
2478
+ const options = { ...(admission !== undefined && !(gate && gate.admission === 'email') ? { open: true } : {}), inheritCustom, inheritPlatform }
2479
+ const { room } = await wb.vault._c.createLane(this.room, cfg, options)
2480
+ if (wb._enc.rooms.has(this.room)) wb._enc.rooms.set(room, true)
2303
2481
  return refuseSpaceInVault(new Lane(this._client, { room, mk: null, link: null, viewer: this._viewer, sharedRoom: this.room, sharedMk: null, actions, wb, shared: this, mirror })) // its connections and Siri go through the vault, as a Space's
2304
2482
  }
2305
2483
 
@@ -2332,7 +2510,7 @@ export class Space {
2332
2510
  if (safeMedia !== undefined) { if (typeof safeMedia !== 'boolean') throw sdkError('witbitz: safeMedia takes true or false', 'invalid_argument'); if (safeMedia && !safeMediaReady()) throw sdkError('witbitz: no safe-media enclave is accepted in this release yet', 'safe_media_unavailable'); patch.safeMedia = safeMedia ? true : null } // as createSpace (sync sweep 2026-10-28) // SAFE MEDIA on/off for everyone (docs/safe-media.md)
2333
2511
  // PRIVATE ASSISTANTS ON OR OFF IN PLACE (docs/always-on-agent-plan.md Phase 0b): a Space made with them can turn them off (and on);
2334
2512
  // members' existing private rooms stay as Spaces of their own. A lane has none of its own.
2335
- if (lanes !== undefined) { if (typeof lanes !== 'boolean') throw sdkError('witbitz: lanes takes true or false', 'invalid_argument'); if (this._sharedRoom) throw sdkError("witbitz: a private lane has no private assistants of its own — set it on the Space", 'lane'); patch.lanes = lanes }
2513
+ if (lanes !== undefined) { if (typeof lanes !== 'boolean') throw sdkError('witbitz: lanes takes true or false', 'invalid_argument'); if (this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)) throw sdkError("witbitz: a private lane has no private assistants of its own — set it on the Space", 'lane'); patch.lanes = lanes }
2336
2514
  if ('name' in agent) patch.agentName = agent.name
2337
2515
  if ('instructions' in agent) patch.persona = agent.instructions
2338
2516
  if ('model' in agent) { if (this._wb) await this._wb._checkModel(agent.model); patch.model = agent.model }
@@ -2356,11 +2534,11 @@ export class Space {
2356
2534
  async plan(change = {}) {
2357
2535
  let cfg = null, gatedUnread = false
2358
2536
  if (change && change.admission !== undefined && !this._sharedRoom) { this._gateCfg = null; try { cfg = await this._gateConfig() } catch (e) { if (e && e.code === 'sign_in_required') gatedUnread = true; else if (e && e.code !== 'config_unavailable') throw e } } // signed out in a gated room: a refusal, not a throw (sdk-assistant.md#changing-the-assistant)
2359
- else if (change && (change.agent || change.data !== undefined || change.platformTools !== undefined || change.framing !== undefined || change.dataWrites !== undefined || change.safeMedia !== undefined) && typeof this._client.getConfig === 'function') { try { const c = await this._client.getConfig(this.room, this._mk); gatedUnread = !!(c && c.gated === true && !c.allow); cfg = c && typeof c === 'object' && !gatedUnread ? c : null } catch { cfg = null } } // the in-place rules need the room's admins (sdkPlan.js)
2537
+ else if (change && (change.agent || change.data !== undefined || change.platformTools !== undefined || change.framing !== undefined || change.dataWrites !== undefined || change.safeMedia !== undefined || change.lanes !== undefined) && typeof this._client.getConfig === 'function') { try { const c = await this._client.getConfig(this.room, this._mk); gatedUnread = !!(c && c.gated === true && !c.allow); cfg = c && typeof c === 'object' && !gatedUnread ? c : null } catch { cfg = null } } // the in-place rules need the room's admins (sdkPlan.js)
2360
2538
  const sess = this._wb && this._wb._session
2361
2539
  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)
2362
2540
  : sess && (!sess.exp || sess.exp > Date.now()) ? String(sess.email || '') : ''
2363
- const out = planChange(change, { cfg, me, lane: !!this._sharedRoom, checkData: checkDataSchema, gatedUnread, signIn: signInHow(this._wb) })
2541
+ 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) })
2364
2542
  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' } } }
2365
2543
  return out
2366
2544
  }
@@ -2378,7 +2556,7 @@ export class Space {
2378
2556
  _runExtra() { return {} } // a Lane adds its bridge fields — a lane's run sees its shared room, as its turns do
2379
2557
 
2380
2558
  /** Stop the poll loop and release the handle. */
2381
- close() { this._stopped = true; this._wb?._archiveHandles?.delete(this); try { if (this._wb && this._wb.invite) this._wb.invite._waiting.delete(this); if (this._vaultKeyOff) this._vaultKeyOff() } catch { /* */ } for (const t of [...(this._turns || [])]) { try { t._settle('failed', { error: 'closed' }) } catch { /* */ } } clearTimeout(this._timer); this._timer = null; if (this._stream) { this._stream.stop(); this._stream = null } if (this._pendingTimer) { clearInterval(this._pendingTimer); this._pendingTimer = null } this._settleReady(Object.assign(new Error('witbitz: the Space was closed before its first poll'), { code: 'closed' })) }
2559
+ close() { this._stopped = true; this._embed?.close(); this._wb?._agentHandles?.delete(this); this._wb?._archiveHandles?.delete(this); try { if (this._wb && this._wb.invite) this._wb.invite._waiting.delete(this); if (this._vaultKeyOff) this._vaultKeyOff() } catch { /* */ } for (const t of [...(this._turns || [])]) { try { t._settle('failed', { error: 'closed' }) } catch { /* */ } } clearTimeout(this._timer); this._timer = null; if (this._stream) { this._stream.stop(); this._stream = null } if (this._pendingTimer) { clearInterval(this._pendingTimer); this._pendingTimer = null } this._settleReady(Object.assign(new Error('witbitz: the Space was closed before its first poll'), { code: 'closed' })) }
2382
2560
  _settleReady(err) { if (!this._readyResolve) return; const [ok, no] = [this._readyResolve, this._readyReject]; this._readyResolve = this._readyReject = null; if (err) no(err); else ok(this) }
2383
2561
 
2384
2562
  async _decide(id, approve, { recordResult, from = 'You' } = {}) {
@@ -2418,8 +2596,9 @@ export class Space {
2418
2596
  }
2419
2597
  /** @private the continuation turn after an approved call ran (see _decide) — the same proofs and options as a send. */
2420
2598
  async _continueAfter(id, from) {
2599
+ const deadline = Date.now() + CONTINUATION_WINDOW_MS
2421
2600
  const opts = await this._turnOpts(undefined, this._runExtra()) // a lane's bridge and links, as its turns
2422
- const r = await this._turnHeld(() => this._provenTurn({ from: String(from || 'You'), text: '', cont: id }, opts))
2601
+ const r = await this._turnHeld(() => this._provenTurn({ from: String(from || 'You'), text: '', cont: id }, opts), undefined, undefined, false, deadline)
2423
2602
  this._kick()
2424
2603
  return r
2425
2604
  }
@@ -2487,6 +2666,7 @@ export class Space {
2487
2666
  try {
2488
2667
  const cfg = await this._client.getConfig(this.room, this._mk, { plainMark: true })
2489
2668
  if (this._stopped) return
2669
+ if (cfg?.admission === 'email' || cfg?.gated === true) this._gated = true
2490
2670
  if (cfg && !gatedStub(cfg) && (typeof cfg.lanes === 'boolean' || cfg.plain === true)) {
2491
2671
  this._lanesSetting = cfg.lanes === true
2492
2672
  if (this._gateCfg && typeof cfg.lanes === 'boolean') this._gateCfg.lanes = cfg.lanes
@@ -2540,7 +2720,10 @@ export class Space {
2540
2720
  if (r.changed && Array.isArray(r.entries)) {
2541
2721
  for (let e of r.entries) {
2542
2722
  if (this._removedMessages && this._removedMessages.has(removedEntryKey(e))) e = removedCopy(e)
2543
- else if (e.sourceRestored === true) this._removedSourceMessages?.delete(removedEntryKey(e))
2723
+ else if (e.sourceRestored === true) {
2724
+ this._removedSourceMessages?.delete(removedEntryKey(e))
2725
+ if (e.id?.startsWith('sh:')) this._removalsMirrored?.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
2726
+ }
2544
2727
  else if (this._removedSourceMessages && this._removedSourceMessages.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2545
2728
  // `from` IS THE DOCUMENTED FIELD (see the header and `on()` below) — the ledger calls it `name`, and this
2546
2729
  // emitted the raw entry, so an author test written from the docs (`m.from === me`) silently matched
@@ -2612,7 +2795,10 @@ export class Space {
2612
2795
  if (!(r && r.status === 200 && Array.isArray(r.entries))) return
2613
2796
  for (let e of r.entries) {
2614
2797
  if (this._removedMessages && this._removedMessages.has(removedEntryKey(e))) e = removedCopy(e)
2615
- else if (e.sourceRestored === true) this._removedSourceMessages?.delete(removedEntryKey(e))
2798
+ else if (e.sourceRestored === true) {
2799
+ this._removedSourceMessages?.delete(removedEntryKey(e))
2800
+ if (e.id?.startsWith('sh:')) this._removalsMirrored?.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
2801
+ }
2616
2802
  else if (this._removedSourceMessages && this._removedSourceMessages.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2617
2803
  if (isTitleEntry(e)) { this._noteTitle(e); continue }
2618
2804
  if (isPurged(e)) continue // a deleted mail's place, written over its entry in that slot: no `update` (sync sweep 11-22 #9)
@@ -2708,6 +2894,7 @@ export class Lane extends Space {
2708
2894
  if (shared instanceof Space) this._sharedOffs.push(shared.on('safeMedia', (e) => { try { this._emit('safeMedia', { ...(e || {}), on: this.safeMedia ? this.safeMedia.on : (e && e.on), via: 'space' }) } catch { /* */ } }))
2709
2895
  // THE MIRROR (2026-10-02) — see _runMirror. The cursor is how many of the shared room's messages this lane already
2710
2896
  // holds; it rides snapshot()/resume as `mirrored`, and the server dedups by id, so a cursor that is off only resends.
2897
+ this._mirrorAnchor = resume?.mirrorAnchor || null
2711
2898
  this._mirrorCursor = resume && Number.isFinite(Number(resume.mirrored)) ? Math.max(0, Number(resume.mirrored)) : 0
2712
2899
  if (mirror && shared instanceof Space) {
2713
2900
  this._mirrorFrom = shared
@@ -2750,7 +2937,7 @@ export class Lane extends Space {
2750
2937
 
2751
2938
  /** Post a private message to your assistant. Its reply is private; anything it wants the shared room to see, or any
2752
2939
  * effectful action, it must PROPOSE (→ the `proposal` event) — the member approves before it happens. */
2753
- async send(text, { from = 'You', mode, tools, dictation, replace = false, instructions, images, files, links, stopKey, showPrompt, replyTo, _onAttempt, _aborted, _linkPost, _peerPost, _noHold } = {}) {
2940
+ async send(text, { from = 'You', mode, tools, dictation, replace = false, instructions, images, files, links, stopKey, showPrompt, replyTo, _onAttempt, _aborted, _linkPost, _peerPost, _noHold, _skill } = {}) {
2754
2941
  if (this._feed) this._feed.sent() // a new turn: its own words are never held back by the previous answer (turnFeed.js; sync sweep 10-16 #10)
2755
2942
  { const f = arguments[1] && arguments[1].from; if (!_linkPost && !_peerPost && typeof f === 'string' && f.trim() && f.trim().toLowerCase() !== 'you') this._memberName = f.trim().slice(0, 80) } // the name this member uses — a crossing they approve lands under it (never a linked room's or an outside agent's post: _linkPost, _peerPost)
2756
2943
  // PER-TURN TOOLS (2026-09-25): `tools` takes the same action shape the constructor takes, offered for THIS turn only
@@ -2759,6 +2946,7 @@ export class Lane extends Space {
2759
2946
  // name wins for the turn); the handlers are registered so a proposal or an in-turn read for them can run.
2760
2947
  // `replace: true` (2026-09-26): the turn is offered ONLY `tools` — a skill runs with its own set — while every
2761
2948
  // standing handler stays registered, so a proposal approved later still runs. `replace` with no tools ⇒ no tools.
2949
+ let additions
2762
2950
  let defs = this._clientTools, guidance = this._guidance
2763
2951
  if (replace) { defs = []; guidance = '' }
2764
2952
  // LINKED LANES (sdkLaneLink.js): while this lane is linked, every turn is offered tell_lane — `replace` included, since
@@ -2770,11 +2958,12 @@ export class Lane extends Space {
2770
2958
  if (extra.defs.length) {
2771
2959
  const names = new Set(extra.defs.map((d) => d.name))
2772
2960
  defs = [...defs.filter((d) => !names.has(d.name)), ...extra.defs]
2773
- Object.assign(this._writes, extra.handlers); Object.assign(this._reads, extra.reads)
2961
+ additions = extra
2774
2962
  guidance = [guidance, extra.guidance].filter(Boolean).join(' ')
2775
2963
  }
2776
2964
  }
2777
2965
  if (defs.length > LIMITS.actions) throw limitError(`${defs.length} actions offered to this turn; the limit is ${LIMITS.actions} per turn — the rest would be dropped (register as many as you like; offer at most ${LIMITS.actions} with send's { tools, replace })`)
2966
+ if (additions) { Object.assign(this._writes, additions.handlers); Object.assign(this._reads, additions.reads) }
2778
2967
  const opts = await this._turnOpts(mode, {
2779
2968
  ...this._bridgeOpts(), // the lane observes the shared room + can cross into it (keyless: the worker holds the shared room's key)
2780
2969
  ...this._linksOpt(links),
@@ -2783,10 +2972,13 @@ export class Lane extends Space {
2783
2972
  ...stopOpt(stopKey),
2784
2973
  ...promptOpt(showPrompt),
2785
2974
  })
2786
- const msg = withMedia({ from, text: String(text), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files)
2975
+ const msg = withMedia({ from, ...(_skill ? { mcp: _skill } : { text: String(text) }), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files)
2787
2976
  { const rt = replyRef(replyTo); if (rt) msg.replyTo = rt }
2788
2977
  await this.safeMedia._prepare(msg)
2789
- const r = await this._turnHeld(() => this._provenTurn(msg, opts), _onAttempt, _aborted, _noHold) // held + resent while the assistant is busy — see Space._turnHeld; with your app's proof where the room requires it, as Space.send (sync sweep 11-09 #18)
2978
+ const r = await this._turnHeld(() => {
2979
+ const { bridgeRoom, bridgeMk, viewSource, links: oldLinks, ...rest } = opts
2980
+ return this._provenTurn(msg, { ...rest, ...this._bridgeOpts(), ...this._linksOpt(links) })
2981
+ }, _onAttempt, _aborted, _noHold) // held + resent while the assistant is busy — see Space._turnHeld; with your app's proof where the room requires it, as Space.send (sync sweep 11-09 #18)
2790
2982
  this._kick()
2791
2983
  if (r && r.ok) this._askName() // a lane is named like any room: the app's roomTitle.js does not skip lanes (sync sweep, 2026-10-10)
2792
2984
  return r
@@ -2871,40 +3063,26 @@ export class Lane extends Space {
2871
3063
  const cfg = canReadConfig ? await from._client.getConfig(from.room, from._mk, { plainMark: true }) : {}
2872
3064
  if (!cfg || gatedStub(cfg)) return { mirrored: 0 }
2873
3065
  if (cfg.lanes === false) { from._lanesSetting = false; this._detachShared(); return { mirrored: 0 } }
2874
- const all = (from.messages || []).filter((e) => e && !e.sys && e.kind !== 'fork' && (e.text || (Array.isArray(e.files) && e.files.length) || (Array.isArray(e.images) && e.images.length)))
3066
+ 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)))
2875
3067
  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
2876
- if (this._mirrorCursor > all.length) this._mirrorCursor = 0 // a cursor from another history: start over; the server's id-dedup makes it a resend, never a double
3068
+ const anchorOf = e => e ? removedEntryKey(e) : null
3069
+ if (this._mirrorCursor && (this._mirrorCursor > all.length || this._mirrorAnchor !== anchorOf(all[this._mirrorCursor - 1]))) {
3070
+ const anchor = this._mirrorAnchor ? all.findIndex(e => anchorOf(e) === this._mirrorAnchor) : -1
3071
+ this._mirrorCursor = anchor + 1
3072
+ } // a cursor from another history: start over; the server's id-dedup makes it a resend, never a double
2877
3073
  const copyEntry = async e => ({
2878
3074
  sourceRoom: from.room,
2879
3075
  id: 'sh:' + (e.id || ('t' + e.ts)), // the entry id alone, no room prefix — stable across a fork (the app's rule)
2880
3076
  from: e.name || e.from || 'party', ...(e.self === true ? { self: true } : {}), ...(e.md === true ? { md: true } : {}),
2881
3077
  ...(typeof e.fr === 'string' ? { fr: e.fr, frRoom: from.room } : {}), // the Space's franking record + which Space: a report of the copy names the ORIGINAL (the app's mirrorLoop.js; sync sweep 11-19 P1)
3078
+ ...(e.self && Array.isArray(e.sources) ? { sources: e.sources.slice(0, 12) } : {}),
2882
3079
  ...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)
2883
3080
  ...(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)
2884
3081
  text: e.text, files: await withBytes(from, e.files), images: await withBytes(from, e.images),
2885
3082
  ...(e.removedByWitbitz ? { sourceRemoved: true } : {}),
2886
3083
  })
2887
- while (this._mirrorCursor < all.length && !from._stopped && !this._stopped) {
2888
- const slice = all.slice(this._mirrorCursor, this._mirrorCursor + 25)
2889
- const batch = this._mirrorData ? slice : slice.filter((e) => e.kind !== 'data')
2890
- if (!batch.length) { this._mirrorCursor += slice.length; continue }
2891
- const entries = await Promise.all(batch.map(copyEntry))
2892
- // A REFUSAL THAT THROWS is still a refusal (sync sweep 11-16 #16): a vault refuses an attested Space's copy into an ordinary
2893
- // lane by throwing, and the timer's catch swallowed it — every message tried again, silently. Said once, like the others.
2894
- let r
2895
- if (from._stopped || this._stopped) break
2896
- if (!attached()) return { mirrored: sent }
2897
- try { r = await this._client.mirror(this.room, this._mk, entries) } catch (e) { r = { status: 0, error: String((e && e.code) || 'mirror_failed'), reason: String((e && e.message) || '').replace(/^witbitz: /, '').slice(0, 300) } }
2898
- if (!r || r.status !== 200) { // the cursor holds; the next pass retries — said ONCE per distinct refusal, as the poll does (sync sweep, 2026-10-10)
2899
- const key = String((r && (r.error || r.status)) || 'no_answer'); if (this._mirrorRefusal !== key) { this._mirrorRefusal = key; this._emit('error', refused('mirror', r)) }
2900
- break
2901
- }
2902
- this._mirrorRefusal = null
2903
- this._mirrorCursor += slice.length; sent += batch.length
2904
- }
2905
- // CAPTION CATCH-UP (the app's rule, mirrorLoop.js): a shared photo is described by the shared room's assistant AFTER
2906
- // it first crossed. Once the description lands, re-send it as a description-only patch so the lane's assistant gets
2907
- // what the shared room has. Recent entries, once per id (sync sweep, 2026-10-10 — the SDK never sent it).
3084
+
3085
+ // Apply removals before fresh attachments, which can fail to load.
2908
3086
  if (!this._stopped && !from._stopped) {
2909
3087
  this._removalsMirrored = this._removalsMirrored || new Set()
2910
3088
  const removed = all.filter((e) => e.removedByWitbitz && (!from._removedMessages || from._removedMessages.has(removedEntryKey(e))) && !this._removalsMirrored.has(removedEntryKey(e)))
@@ -2928,6 +3106,35 @@ export class Lane extends Space {
2928
3106
  }
2929
3107
  this._kick()
2930
3108
  }
3109
+ }
3110
+ while (this._mirrorCursor < all.length && !from._stopped && !this._stopped) {
3111
+ const slice = all.slice(this._mirrorCursor, this._mirrorCursor + 25)
3112
+ const batch = this._mirrorData ? slice : slice.filter((e) => e.kind !== 'data')
3113
+ if (!batch.length) { this._mirrorCursor += slice.length; this._mirrorAnchor = anchorOf(slice.at(-1)); continue }
3114
+ const entries = await Promise.all(batch.map(copyEntry))
3115
+ // A REFUSAL THAT THROWS is still a refusal (sync sweep 11-16 #16): a vault refuses an attested Space's copy into an ordinary
3116
+ // lane by throwing, and the timer's catch swallowed it — every message tried again, silently. Said once, like the others.
3117
+ const start = this._mirrorCursor
3118
+ let accepted = 0
3119
+ for (const part of mirrorBatches(entries)) {
3120
+ if (!attached() || from._stopped || this._stopped) return { mirrored: sent }
3121
+ let r
3122
+ try { r = await this._client.mirror(this.room, this._mk, part) }
3123
+ catch (error) { r = { status: 0, error: error?.code || 'mirror_failed', reason: String(error?.message || '').slice(0, 300) } }
3124
+ if (r?.status !== 200) {
3125
+ const key = String(r?.error || r?.status || 'no_answer')
3126
+ if (this._mirrorRefusal !== key) { this._mirrorRefusal = key; this._emit('error', refused('mirror', r)) }
3127
+ return { mirrored: sent }
3128
+ }
3129
+ this._mirrorRefusal = null
3130
+ accepted += part.length; sent += part.length
3131
+ this._mirrorCursor = start + slice.indexOf(batch[accepted - 1]) + 1
3132
+ this._mirrorAnchor = anchorOf(all[this._mirrorCursor - 1])
3133
+ }
3134
+ this._mirrorCursor = start + slice.length
3135
+ this._mirrorAnchor = anchorOf(slice.at(-1))
3136
+ }
3137
+ if (!this._stopped && !from._stopped) {
2931
3138
  // A cleared moderation list triggers a fresh source read. Cached message text is never a restoration.
2932
3139
  const hiddenCopies = new Set(this.messages.filter(e => e.sourceRemoved).map(removedEntryKey))
2933
3140
  const candidates = all.filter(e => hiddenCopies.has(removedEntryKey({ id: 'sh:' + e.id, ts: e.ts })) && !from._removedMessages?.has(removedEntryKey(e)))
@@ -2938,18 +3145,26 @@ export class Lane extends Space {
2938
3145
  const wanted = new Set(candidates.map(removedEntryKey))
2939
3146
  const originals = history.entries.filter(e => wanted.has(removedEntryKey(e)) && !hidden.has(removedEntryKey(e)) && !e.removedByWitbitz && e.kind !== 'fork')
2940
3147
  for (let i = 0; i < originals.length; i += 25) {
2941
- const entries = await Promise.all(originals.slice(i, i + 25).map(copyEntry))
3148
+ const attempts = await Promise.allSettled(originals.slice(i, i + 25).map(copyEntry))
3149
+ const entries = attempts.filter(result => result.status === 'fulfilled').map(result => result.value)
3150
+ if (!entries.length) continue
2942
3151
  if (!attached()) break
2943
- const r = await this._client.mirror(this.room, this._mk, entries.map(e => ({ ...e, restoreSource: true })))
2944
- if (r?.status !== 200) break
2945
- for (const e of r.sourceRestorations || []) {
2946
- this._removedSourceMessages?.delete(removedEntryKey(e))
2947
- this._removalsMirrored.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
3152
+ for (const part of mirrorBatches(entries.map(e => ({ ...e, restoreSource: true })))) {
3153
+ if (!attached()) return { mirrored: sent }
3154
+ const r = await this._client.mirror(this.room, this._mk, part)
3155
+ if (r?.status !== 200) return { mirrored: sent }
3156
+ for (const e of r.sourceRestorations || []) {
3157
+ this._removedSourceMessages?.delete(removedEntryKey(e))
3158
+ this._removalsMirrored.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
3159
+ }
3160
+ if (r.sourceRestorations?.length) { this._count = 0; this._etag = null; this._kick() }
2948
3161
  }
2949
- if (r.sourceRestorations?.length) { this._count = 0; this._etag = null; this._kick() }
2950
3162
  }
2951
3163
  }
2952
3164
  }
3165
+ // CAPTION CATCH-UP (the app's rule, mirrorLoop.js): a shared photo is described by the shared room's assistant AFTER
3166
+ // it first crossed. Once the description lands, re-send it as a description-only patch so the lane's assistant gets
3167
+ // what the shared room has. Recent entries, once per id (sync sweep, 2026-10-10 — the SDK never sent it).
2953
3168
  this._descMirrored = this._descMirrored || new Set()
2954
3169
  const patches = []
2955
3170
  for (const e of all.slice(-40)) {
@@ -2966,8 +3181,8 @@ export class Lane extends Space {
2966
3181
  this._viewsAt = Date.now()
2967
3182
  try {
2968
3183
  const views = []
2969
- for (const v of viewsNamedIn(from.messages)) { const d = await this._client.state(from.room, from._mk, v.name).catch(() => null); if (!d?.state || (d.status && d.status !== 200)) return; views.push({ label: v.label, state: d.state }) }
2970
- const text = renderSharedViews(views)
3184
+ for (const v of viewsNamedIn(from.messages)) { const d = await this._client.state(from.room, from._mk, v.name).catch(() => null); if (!d?.state || (d.status && d.status !== 200)) { this._viewsAt = 0; throw sdkError('shared view unavailable', 'state_unavailable') } views.push({ label: v.label, state: d.state }) }
3185
+ const text = renderSharedViews(views, from.room)
2971
3186
  if (attached() && (text !== this._sharedViews || this._sharedViewsSource !== from.room)) { const r = await this._client.state(this.room, this._mk, SHARED_VIEWS_DOC, { source: from.room, text }, text.slice(0, 200), 'device'); if (r && r.status === 200) { this._sharedViews = text; this._sharedViewsSource = from.room } }
2972
3187
  } catch { /* never break the mirror */ }
2973
3188
  }
@@ -2980,8 +3195,7 @@ export class Lane extends Space {
2980
3195
  }
2981
3196
 
2982
3197
  snapshot() {
2983
- const a2a = pendingOf(this._a2a ? this._a2a._pending : this._a2aResume) // waiting outside-agent tasks ride along (sync sweep 10-24 #17)
2984
- return { ...super.snapshot(), ...(this._mirrorFrom ? { mirrored: this._mirrorCursor } : {}), ...(a2a.length ? { a2a } : {}) }
3198
+ return { ...super.snapshot(), ...(this._mirrorFrom ? { mirrored: this._mirrorCursor, mirrorAnchor: this._mirrorAnchor } : {}) }
2985
3199
  }
2986
3200
 
2987
3201
  close() {
@@ -3005,6 +3219,7 @@ export class Lane extends Space {
3005
3219
  if (index >= 0) listeners.splice(index, 1)
3006
3220
  }
3007
3221
  if (this._ownsSharedSpace) this._sharedSpace?.close()
3222
+ this._detachedLane = true
3008
3223
  this._sharedRoom = null; this._sharedMk = null; this._mirrorFrom = null; this._sharedSpace = null
3009
3224
  clearTimeout(this._mirrorTimer); clearInterval(this._viewsTick)
3010
3225
  this._emit('disconnected', { reason: 'lanes_disabled' })
@@ -3012,7 +3227,7 @@ export class Lane extends Space {
3012
3227
  _checkShared() {
3013
3228
  if (!this._sharedRoom) return
3014
3229
  const rec = this._wb?.backup?.rooms?.find(r => r.room === this.room)
3015
- if (rec && (rec.kind !== 'lane' || (rec.shared && rec.shared !== this._sharedRoom))) this._detachShared()
3230
+ if (rec && (rec.detachedLane || rec.kind !== 'lane' || (rec.shared && rec.shared !== this._sharedRoom))) this._detachShared()
3016
3231
  }
3017
3232
  _bridgeOpts() { this._checkShared(); if (!this._sharedRoom) return {}; return this._crossTier ? { viewSource: this._sharedRoom } : { ...(this._sharedMk ? { bridgeMk: this._sharedMk } : {}), bridgeRoom: this._sharedRoom } }
3018
3233
  _runExtra() { return { ...this._bridgeOpts(), ...this._linksOpt() } } // sync sweep, 2026-10-10: Lane.run had no bridge, then no linked rooms
@@ -3080,11 +3295,9 @@ const ENC_MARK = /[?#&]enc=1(?:[&#]|$)/ // in the fragment (markEncLink) OR the
3080
3295
  const markEncLink = (l) => (ENC_MARK.test(String(l)) ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'enc=1')
3081
3296
  /** An email-gated room's link says so too (the app's own convention, inviteLinks.js): a client opening it knows to sign
3082
3297
  * in, and the SDK knows to announce its device in the room's guest book (see Space#fork). Never sent to the server. */
3083
- const GATE_MARK = /[#&]gate=email(?:&|$)/
3084
- const markGateLink = (l) => (GATE_MARK.test(String(l)) ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'gate=email')
3298
+ const markGateLink = (l) => (roomInviteFlags(l).gated ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'gate=email')
3085
3299
  /** A room that gives every member a private assistant: its link says so (the app's grammar, inviteLinks.js `&lanes=1`). */
3086
- const LANES_MARK = /[#&]lanes=1(?:&|$)/
3087
- const markLanesLink = (l) => (LANES_MARK.test(String(l)) ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'lanes=1')
3300
+ const markLanesLink = (l) => (roomInviteFlags(l).lanes ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'lanes=1')
3088
3301
  /** SPLIT-KEY links (https://witbitz.chat/docs/sdk-keys.md#split-key) — the app's own grammar (inviteLinks.js): `#us=<userShare>&spc=<commit>` in
3089
3302
  * place of `#mk=`. The link is HALF a key; the other half comes only to a page on an origin the room's tenant declared. */
3090
3303
  const SPLIT_MARK = /[#&]us=/
@@ -3165,16 +3378,19 @@ const sessionOf = (x) => (x && typeof x === 'object' && typeof x.idToken === 'st
3165
3378
  /** Was this room a private lane? The account's backup keeps a lane's kind even after it is re-added as a Space (sdkBackup.js
3166
3379
  * `wasLane`) — the SDK's record, as the app's is `space:lane-rooms`. Without the backup the SDK knows only the Lane handle. */
3167
3380
  function wasLaneRoom (wb, room) {
3168
- try { const b = wb && wb.backup; if (!b || !b.enabled || !room) return false; const r = (b.rooms || []).find((x) => x && x.room === room); return !!(r && r.kind === 'lane') } catch { return false }
3381
+ try { const b = wb && wb.backup; if (!b || !b.enabled || !room) return false; const r = (b.rooms || []).find((x) => x && x.room === room); return !!(r && (r.detachedLane || r.kind === 'lane')) } catch { return false }
3169
3382
  }
3170
- const siriStateOf = (x) => {
3383
+ const siriStateOf = (x, allowPending = true) => {
3171
3384
  const o = x && typeof x === 'object' ? x : {}
3172
3385
  const rooms = {}
3173
3386
  for (const [room, r] of Object.entries(o.rooms && typeof o.rooms === 'object' ? o.rooms : {})) {
3174
3387
  if (!r || typeof r !== 'object' || !r.alias || !r.pub || !r.priv) continue
3175
3388
  rooms[room] = { alias: String(r.alias), label: String(r.label || ''), pub: { x: r.pub.x, y: r.pub.y }, priv: r.priv, at: Number(r.at) || 0 }
3176
3389
  }
3177
- return { token: typeof o.token === 'string' ? o.token : '', defaultRoom: typeof o.defaultRoom === 'string' && rooms[o.defaultRoom] ? o.defaultRoom : '', rooms }
3390
+ const pending = Array.isArray(o.pendingRemovals) ? [...new Set(o.pendingRemovals.filter(id => typeof id === 'string' && Object.hasOwn(rooms, id)))] : []
3391
+ const setup = allowPending && o.pendingSetup ? siriStateOf(o.pendingSetup, false) : null
3392
+ const rotation = allowPending && o.pendingRotation
3393
+ return { ...(rotation && rotation.from === o.token && typeof rotation.to === 'string' && rotation.to ? { pendingRotation: { from: rotation.from, to: rotation.to } } : {}), ...(setup && Object.keys(setup.rooms).length ? { pendingSetup: setup } : {}), ...(pending.length ? { pendingRemovals: pending } : {}), ...(Number(o.rev) > 0 ? { rev: Number(o.rev) } : {}), token: typeof o.token === 'string' ? o.token : '', defaultRoom: typeof o.defaultRoom === 'string' && rooms[o.defaultRoom] ? o.defaultRoom : '', rooms }
3178
3394
  }
3179
3395
 
3180
3396
  /** `wb.usernames` — the member's @username. One name means one person across ALL of Witbitz (not per app): it is
@@ -3250,12 +3466,33 @@ function refuseInVault(wb) {
3250
3466
  // read the vault's last VIEW of them (no link, no key, no master secret); `onChange` fires when it changes.
3251
3467
  wb._vaultAccount = (conn.info && conn.info.account) || { enabled: false, format: null, deviceId: '', rooms: [], devices: [], links: [], lastError: null, erasure: false }
3252
3468
  let accountGeneration = 0
3469
+ let memoryEmail = String(conn.info?.email || '').toLowerCase()
3470
+ wb._memoryGeneration = 0
3253
3471
  const view = () => wb._vaultAccount
3254
3472
  conn.on((ev) => {
3473
+ if (ev?.ev === 'a2aChanged') refreshVaultA2AViews(conn, ev)
3474
+ if (ev?.ev === 'siri' && ev.siri) wb._vaultSiri = { ...ev.siri, key: null }
3475
+ const expired = ev?.ev === 'signedOut' && ev.reason === 'expired'
3476
+ if (expired) wb.a2a._draftsSuspended = true
3477
+ if (ev?.ev === 'signedOut' || ev?.ev === 'accountSignedOut' || ev?.ev === 'signedIn') {
3478
+ const email = ev.ev === 'signedIn' ? String(ev.email || '').toLowerCase() : ''
3479
+ const resumed = wb.a2a._draftsSuspended && email && email === memoryEmail
3480
+ if (!email || email !== memoryEmail) {
3481
+ if (!expired) wb.a2a._dropAllDrafts()
3482
+ wb._forgetVoice(); wb._memoryGeneration++; wb._assistantMemory = null
3483
+ }
3484
+ if (!expired) {
3485
+ memoryEmail = email; wb.a2a._draftsSuspended = false
3486
+ if (resumed) for (const handle of wb._agentHandles || []) handle._a2a?._flushHeld()
3487
+ }
3488
+ }
3255
3489
  if (['signedOut', 'accountSignedOut', 'signedIn'].includes(ev?.ev) || (ev?.ev === 'account' && ev.view?.enabled !== view().enabled)) {
3490
+ if (ev.view?.enabled === false && !expired) wb.a2a._dropAllDrafts()
3256
3491
  wb._vaultGeneration = ++accountGeneration
3492
+ conn.a2aEpoch = (conn.a2aEpoch || 0) + 1
3257
3493
  wb._vaultSiri = { key: null, hasKey: false, endpoint: wb._vaultSiri?.endpoint }
3258
3494
  if (ev.ev !== 'signedOut' && ev.ev !== 'accountSignedOut' && ev.view?.enabled !== false) {
3495
+ refreshVaultA2AViews(conn, ev)
3259
3496
  const generation = accountGeneration
3260
3497
  conn.account('siri', 'shortcut').then(value => { if (generation === accountGeneration) wb._vaultSiri = value }).catch(() => {})
3261
3498
  }
@@ -3291,7 +3528,7 @@ function refuseInVault(wb) {
3291
3528
  const generation = accountGeneration
3292
3529
  const v = await conn.account('account', 'section', name, m, ...a)
3293
3530
  if (generation !== accountGeneration) throw sdkError('the account changed during the call', 'account_changed')
3294
- if (!(name === 'chatLocks' && m === 'check')) sec._seen(v)
3531
+ if (!(name === 'chatLocks' && (m === 'check' || m === 'match' || m === 'previewDeleteAll' || m === 'deleteAll'))) sec._seen(v)
3295
3532
  return v
3296
3533
  }
3297
3534
  const on = sec.on.bind(sec)
@@ -3310,6 +3547,7 @@ function refuseInVault(wb) {
3310
3547
  getters(wb.erasure, { available: () => !!view().erasure })
3311
3548
  for (const name of ['catalog', 'discover']) Object.defineProperty(wb.connections, name, { value: wb.connections[name].bind(wb.connections), configurable: true }) // public picker data remains synchronous and local
3312
3549
  forwardInVault(wb.connections, (m, a) => conn.account('connections', m, ...a))
3550
+ wb.connections.recover = async id => { checkConnectionId(id); return (await wb.connections.list()).find(c => c.id === id && c.grantable) || null }
3313
3551
  Object.defineProperty(wb.connections, 'lock', { value: () => Promise.reject(vaultRefusal('connections.lock (the vault locks what it holds itself)')), configurable: true, writable: true }) // move 3: no key leaves a vault
3314
3552
  // the sign-in comes back to THIS page (sweep 10-24 #6): forwarded bare, the vault's SDK named its own origin's /mcp-callback,
3315
3553
  // where no page waits — the default is the page's, as outside a vault
@@ -3318,6 +3556,7 @@ function refuseInVault(wb) {
3318
3556
  // gets the id alone, and each Space is unlinked through its own handle, as outside a vault
3319
3557
  wb.connections.detach = async (id, { spaces = [] } = {}) => {
3320
3558
  const cid = String(id || ''), out = await conn.account('connections', 'detach', cid)
3559
+ if (out?.removed?.length) { wb.a2a._dropMoved(out.removed); refreshVaultA2AViews(conn, out) }
3321
3560
  let removedFrom = 0
3322
3561
  for (const sp of Array.isArray(spaces) ? spaces : []) { try { if (sp && sp.connections) { await sp.connections.revoke(cid); removedFrom++ } } catch { /* one Space's refusal does not undo the detach */ } }
3323
3562
  return { ...(out || {}), removedFrom }
@@ -3325,12 +3564,17 @@ function refuseInVault(wb) {
3325
3564
  forwardInVault(wb.usernames, (m, a) => conn.account('usernames', m, ...a))
3326
3565
  // the Shortcut KEY stays in the vault: `shortcut.key` is null here, rotateKey resolves null, and wb.vault.showSiriKey()
3327
3566
  // shows it in the vault's own screen
3328
- forwardInVault(wb.siri, (m, a) => conn.account('siri', m, ...a).then((r) => { if (m === 'rotateKey') { wb._vaultSiri = r || wb._vaultSiri; return null } if (m === 'revoke') wb._vaultSiri = { key: null, hasKey: false, endpoint: wb._vaultSiri && wb._vaultSiri.endpoint }; return r }), ['status', 'rotateKey', 'revoke'])
3567
+ forwardInVault(wb.siri, (m, a) => conn.account('siri', m, ...a).then((r) => { if (m === 'rotateKey') { wb._vaultSiri = r || wb._vaultSiri; return null } if (m === 'revoke') wb._vaultSiri = { key: null, hasKey: false, endpoint: wb._vaultSiri && wb._vaultSiri.endpoint }; return r }), ['status', 'sync', 'rotateKey', 'revoke'])
3329
3568
  wb._vaultSiri = (conn.info && conn.info.siri) || { key: null, endpoint: null }
3330
3569
  Object.defineProperty(wb.siri, 'shortcut', { get() { return { ...wb._vaultSiri } }, configurable: true }) // as the vault last said
3331
3570
  Object.defineProperty(wb.siri, 'state', { get() { return null }, configurable: true }) // the vault keeps it: its inbox private keys never come here
3332
3571
  wb.siri.restore = () => { throw vaultRefusal('restoring the Siri state (the vault keeps it)') }
3333
- forwardInVault(wb.a2a, (m, a) => conn.account('a2a', m, ...a), ['status', 'revoke'])
3572
+ forwardInVault(wb.a2a, async (m, a) => {
3573
+ const result = await conn.account('a2a', m, ...a)
3574
+ if (m === 'revoke') { conn.a2aEpoch = (conn.a2aEpoch || 0) + 1; wb.a2a._dropAllDrafts() }
3575
+ if (m === 'stopJobAgent') { wb.a2a._dropMoved(result.removed); refreshVaultA2AViews(conn, result) }
3576
+ return result
3577
+ }, ['status', 'revoke', 'stopJobAgent'])
3334
3578
  Object.defineProperty(wb.a2a, 'state', { get() { return null }, configurable: true }) // the vault keeps it: the lanes' inbox private keys never come here
3335
3579
  wb.a2a.restore = () => { throw vaultRefusal('restoring the A2A state (the vault keeps it)') }
3336
3580
  Object.defineProperty(wb.invite, 'state', { get() { return null }, configurable: true }) // the vault keeps the account's invite key
@@ -3348,16 +3592,28 @@ function refuseInVault(wb) {
3348
3592
  function refuseSpaceInVault(sp) {
3349
3593
  const vc = () => sp._wb && sp._wb.vault && sp._wb.vault._c // read at each call: the vault this Space asks through now
3350
3594
  if (!vc()) { blockInVault(sp.connections, 'connections'); blockInVault(sp.siri, 'the Siri inbox'); return sp }
3351
- const call = (ns) => (m, a) => vc().roomAccount(sp.room, ns, m, ...a)
3595
+ const call = ns => (m, a) => {
3596
+ if (ns === 'connections' && m === 'revoke' && a[1]?.includeAssistant && !vc().info?.scopedConnectionRevoke)
3597
+ throw sdkError('Update the vault kit to revoke private assistant grants', 'vault_unsupported')
3598
+ return vc().roomAccount(sp.room, ns, m, ...a)
3599
+ }
3352
3600
  // grant by id: the callKey is the vault's (wb.connections.attach in a vault returns { id, label, host, account })
3353
3601
  forwardInVault(sp.connections, (m, a) => call('connections')(m, m === 'grant' ? [a[0] && typeof a[0] === 'object' ? a[0].id : a[0], a[1] && { from: a[1].from, tools: a[1].tools, auto: a[1].auto, reads: a[1].reads }] : a))
3354
3602
  forwardInVault(sp.siri, async (m, a) => {
3355
3603
  if (m !== 'collect') { const r = await call('siri')(m, a); if (m === 'enable' && r) sp._wb._vaultSiri = { key: null, hasKey: !!r.hasKey, endpoint: r.endpoint }; return r }
3356
3604
  const deliver = a[0] && a[0].deliver
3357
3605
  if (deliver !== undefined && typeof deliver !== 'function') throw sdkError('witbitz: collect({ deliver }) takes a function — deliver(text, meta)', 'invalid_argument')
3358
- if (!deliver) return call('siri')('collect', [{}])
3359
- const off = vc().onAsk('siriDeliver', sp.room, ({ text, meta }) => deliver(text, meta)) // the vault hands each drop here; a throw leaves it un-acked
3360
- try { return await call('siri')('collect', [{ deliver: true }]) } finally { off() }
3606
+ const transport = vc()
3607
+ const queue = transport.siriCollections ||= new Map()
3608
+ const collect = async () => {
3609
+ if (!deliver) return call('siri')('collect', [{}])
3610
+ const off = transport.onAsk('siriDeliver', sp.room, ({ text, meta }) => deliver(text, meta))
3611
+ try { return await call('siri')('collect', [{ deliver: true }]) } finally { off() }
3612
+ }
3613
+ const previous = queue.get(sp.room) || Promise.resolve()
3614
+ const run = previous.catch(() => {}).then(collect)
3615
+ queue.set(sp.room, run)
3616
+ try { return await run } finally { if (queue.get(sp.room) === run) queue.delete(sp.room) }
3361
3617
  })
3362
3618
  return sp
3363
3619
  }
@@ -3386,7 +3642,7 @@ export class VaultSession {
3386
3642
  }
3387
3643
  /** What the vault said when the page connected — { tenant, signedIn, email, rooms, siri, account } — with the sign-in and the
3388
3644
  * account kept current from the vault's events since (sync sweep 10-26 #10: it was the welcome, frozen). */
3389
- get info() { return { ...this._c.info, ...this._live } }
3645
+ get info() { return { ...this._c.info, ...this._live, ...(this._wb._vaultSiri ? { siri: { ...this._wb._vaultSiri } } : {}) } }
3390
3646
  /** The Spaces this vault holds, newest first: [{ room, title, at, lane?, tier?, lanes? }] — never a link. */
3391
3647
  async rooms() { return this._c.rooms() }
3392
3648
  /** A live {@link Space} for a room the vault holds — its key stays in the vault. */
@@ -3400,12 +3656,16 @@ export class VaultSession {
3400
3656
  if (it.lane) {
3401
3657
  // its Space forgotten (forget / dropRoom keep the lane): said by name, about THIS room — it threw not_in_vault naming
3402
3658
  // the Space's id (sync sweep 2026-11-03 #4)
3659
+ if (all.some(r => r?.room === it.lane && r.lane)) throw sdkError('Conflicting private-room links must be synced before opening this lane.', 'association_changed')
3403
3660
  if (!all.some((r) => r && r.room === it.lane)) throw sdkError('witbitz: this private lane\'s Space is no longer in this vault, so the lane cannot be opened', 'lane_space_gone')
3404
3661
  const space = await this.openRoom(it.lane)
3405
3662
  // the Space opened here is the lane's own: lane.close() closes it too — it was left polling (sync sweep 2026-11-03 #5)
3406
3663
  try { const lane = await this._openLane(room, { space, resume }); lane._ownsSharedSpace = true; return lane } catch (e) { space.close(); throw e }
3407
3664
  }
3408
- return refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, resume, wb, lanes: it.lanes === true }))
3665
+ const sp = new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, resume, wb, lanes: it.lanes === true })
3666
+ if (it.tier === 'enclave') wb._enc.rooms.set(room, true)
3667
+ if (it.detachedLane) sp._detachedLane = true
3668
+ return refuseSpaceInVault(sp)
3409
3669
  }
3410
3670
  /** @private wb.openLane in a vault: the lane's ROOM ID (from rooms(), where `lane` names its Space) — a link is the
3411
3671
  * vault's to open. */
@@ -3423,6 +3683,7 @@ export class VaultSession {
3423
3683
  if (tier !== undefined && tier !== null && tierIsEnclave(tier) !== (it.tier === 'enclave')) throw tierMismatch('this lane is ' + (it.tier === 'enclave' ? 'confidential' : 'standard') + ' — its Space\'s tier')
3424
3684
  // a lane of the OTHER tier (the app links one): mirrored by this device, no bridge — as outside a vault (Witbitz.openLane)
3425
3685
  const crossTier = (it.tier === 'enclave') !== ((held.find((r) => r.room === space.room) || {}).tier === 'enclave')
3686
+ if (it.tier === 'enclave') wb._enc.rooms.set(room, true)
3426
3687
  return refuseSpaceInVault(new Lane(wb._client, { room, mk: null, link: null, viewer: wb._viewer, sharedRoom: space.room, sharedMk: null, actions, resume, wb, shared: space, mirror: crossTier ? (mirror || true) : mirror, crossTier }))
3427
3688
  }
3428
3689
  /** Show the Siri Shortcut's key in the VAULT's own screen (it posts words into the person's Spaces, so it never comes
@@ -3447,9 +3708,9 @@ export class VaultSession {
3447
3708
  return r
3448
3709
  }
3449
3710
  /** Share a Space: the VAULT shows its share screen with the link (the link carries the key, so it never comes here). */
3450
- async share(space, opts = {}) { return this._c.share(space && space.room ? space.room : String(space || ''), opts) }
3711
+ async share(space, opts = {}) { if (opts.hostInviteTemplate !== undefined && !this._c.info?.hostInvites) throw sdkError('Update the vault kit to use host invites', 'vault_unsupported'); return this._c.share(space && space.room ? space.room : String(space || ''), opts) }
3451
3712
  /** Sign in — the vault shows its sign-in screen; resolves { email } once signed in. */
3452
- async signIn(opts = {}) { return this._c.signIn(opts) }
3713
+ async signIn() { return this._c.signIn() }
3453
3714
  async signOut() { return this._c.signOut() }
3454
3715
  /** { signedIn, email, keyId } — who the vault has signed in (keyId: its session key's public id, what space.isMine compares). */
3455
3716
  async whoami() { return this._c.whoami() }
@@ -3461,20 +3722,25 @@ export class VaultSession {
3461
3722
  on(event, cb) { if (!this._fns.has(event)) this._fns.set(event, new Set()); this._fns.get(event).add(cb); return () => this._fns.get(event).delete(cb) }
3462
3723
  _event(d) {
3463
3724
  if (d?.ev === 'rooms' && Array.isArray(d.rooms)) {
3725
+ this._live = { ...this._live, rooms: d.rooms.map(r => ({ ...r })) }
3726
+ const held = new Set(d.rooms.map(r => r.room))
3727
+ const memory = this._wb._assistantMemory?.group
3728
+ if (memory) for (const room of memory.keys()) if (!held.has(room)) memory.delete(room)
3729
+ for (const r of d.rooms) if (r.tier === 'enclave') this._wb._enc.rooms.set(r.room, true)
3464
3730
  for (const lane of this._wb._openLanes || []) {
3465
3731
  const saved = d.rooms.find(r => r.room === lane.room)
3466
3732
  if (lane._sharedRoom && saved?.lane !== lane._sharedRoom) lane._detachShared()
3467
3733
  }
3468
3734
  }
3469
3735
  if (d && d.ev === 'signedIn') this._live = { ...this._live, signedIn: true, email: String(d.email || ''), keyId: String(d.keyId || '') }
3470
- else if (d && (d.ev === 'signedOut' || d.ev === 'accountSignedOut')) this._live = { ...this._live, signedIn: false, email: '', keyId: '' } // accountSignedOut: the vault forgot the account AND its sign-in — info said signed in, with the old email (sync sweep 11-22 #5)
3736
+ else if (d && (d.ev === 'signedOut' || d.ev === 'accountSignedOut')) this._live = { ...this._live, signedIn: false, email: '', keyId: '', ...(d.reason === 'expired' ? {} : { rooms: [] }) } // accountSignedOut: the vault forgot the account AND its sign-in — info said signed in, with the old email (sync sweep 11-22 #5)
3471
3737
  else if (d && d.ev === 'session') this._live = { ...this._live, keyId: String(d.keyId || '') } // a renewed session: its new key's public id (space.isMine)
3472
3738
  else if (d && d.ev === 'account' && d.view) this._live = { ...this._live, account: d.view }
3473
3739
  else if (d && d.ev === 'lock' && d.lock && typeof d.lock === 'object') this._live = { ...this._live, lock: { available: !!d.lock.available, on: !!d.lock.on, protect: !!d.lock.protect } } // a vault started with `lock: true`
3474
3740
  else if (d && d.ev === 'push' && d.push && typeof d.push === 'object') this._live = { ...this._live, push: { available: !!d.push.available, on: !!d.push.on } } // `push: true`
3475
3741
  const set = this._fns.get(d.ev); if (set) for (const fn of set) { try { fn(d) } catch { /* the listener's own */ } }
3476
3742
  }
3477
- async _create({ agent, tools, immediateTools, clientTools, agentReplies, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, safeMedia, lanes }) {
3743
+ async _create({ agent, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, usernames, safeMedia, lanes }) {
3478
3744
  const enc = tierIsEnclave(tier) // the vault attests the enclave and keeps the key; the page only asks
3479
3745
  const split = splitKeyChoice(key) // the vault makes it through its app-half function (startVault({ appShare: true }))
3480
3746
  const wb = this._wb
@@ -3490,13 +3756,16 @@ export class VaultSession {
3490
3756
  await wb._checkModel(model || (agent && agent.model))
3491
3757
  const gate = normAdmission(admission)
3492
3758
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
3759
+ applySkills(cfg, skills)
3493
3760
  if (Array.isArray(clientTools)) cfg.clientTools = clientTools
3494
3761
  if (agentReplies !== undefined) cfg.agentReplies = agentReplies
3495
3762
  cfg.region = region || wb._region
3496
3763
  if (direct !== undefined) cfg.direct = true
3764
+ if (usernames === false && gate?.admission === 'email') cfg.usernames = false
3497
3765
  if (safeMedia === true) cfg.safeMedia = true // as outside a vault (sync sweep 2026-10-28: it was refused here while configure turned it on)
3498
3766
  if (lanes === true) cfg.lanes = true
3499
3767
  const { room } = await this._c.create(cfg, enc || split ? { ...(enc ? { enclave: true } : {}), ...(split ? { split: true } : {}) } : undefined)
3768
+ if (enc) wb._enc.rooms.set(room, true)
3500
3769
  const made = refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, wb, gated: !!gate, lanes: lanes === true }))
3501
3770
  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)
3502
3771
  if (direct !== undefined) await made.setReplyMode('ondemand').catch(() => {}) // as outside a vault: the assistant answers when @mentioned
@@ -3507,8 +3776,41 @@ export class VaultSession {
3507
3776
  /** `wb.connections` — the ACCOUNT's connections: credentials the standing Sentinel holds and spends on your behalf.
3508
3777
  * Attaching seals the secret to the attested Sentinel; the page keeps only an id, a label, a host and a `callKey`.
3509
3778
  * Nothing here touches a Space: grant one to a Space with `space.connections.grant(conn)`. */
3779
+ function checkConnectionId(id) {
3780
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(id)) throw sdkError('witbitz: invalid connection ID', 'invalid_argument')
3781
+ }
3510
3782
  class Connections {
3511
- constructor(wb) { this._wb = wb }
3783
+ constructor(wb) { this._wb = wb; this._pendingMemory = new Map() }
3784
+ _pendingFor(account) {
3785
+ if (this._vaultPending) return this._vaultPending
3786
+ const protect = this._wb.protect
3787
+ const name = id => 'witbitz:conn-pending:' + encodeURIComponent(account) + ':' + id
3788
+ const memory = this._pendingMemory
3789
+ const persistent = !!protect && (!('_storage' in protect) || !!protect._storage)
3790
+ const load = id => persistent ? protect.load(name(id)) : memory.get(name(id))
3791
+ const drop = async id => { if (persistent) await protect.remove?.(name(id)); memory.delete(name(id)) }
3792
+ return {
3793
+ durable: true, load, drop,
3794
+ keep: async (id, rec) => {
3795
+ const value = { ...rec, account, at: Date.now() }
3796
+ if (persistent) {
3797
+ await protect.save(name(id), value)
3798
+ if ((await load(id))?.callKey !== rec.callKey) throw sdkError('witbitz: the connection key could not be saved', 'storage_unavailable')
3799
+ } else memory.set(name(id), value)
3800
+ },
3801
+ }
3802
+ }
3803
+ async recover(id) {
3804
+ const wb = this._wb
3805
+ wb._auth()
3806
+ checkConnectionId(id)
3807
+ const account = await wb._account(), pending = this._pendingFor(account)
3808
+ const record = await pending.load(id)
3809
+ if (!record?.callKey || record.account !== account) return null
3810
+ const listed = (await this.list()).find(c => c.id === id)
3811
+ if (!listed || account !== await wb._account()) return null
3812
+ return { ...listed, id, label: listed.label || record.label || '', host: listed.host || record.host || '', account, callKey: record.callKey }
3813
+ }
3512
3814
  /** The app's service/outside-agent picker data, without credentials. A builder draws its own picker. */
3513
3815
  catalog({ category } = {}) {
3514
3816
  if (category !== undefined && typeof category !== 'string') throw sdkError('witbitz: catalog category must be a string', 'invalid_argument')
@@ -3523,7 +3825,7 @@ class Connections {
3523
3825
  }
3524
3826
  const result = await spacesUsingConnection(id, [...byId.values()], async room => {
3525
3827
  const link = await wb._openLink(byId.get(room).link)
3526
- if (link.room !== room) throw new Error('room link mismatch')
3828
+ if (link.room !== room) throw sdkError('room link mismatch', 'invalid_link')
3527
3829
  return wb._client.getConfig(room, link.mk, { plainMark: true })
3528
3830
  })
3529
3831
  if (wb._archiveGeneration !== generation || (wb.backup._s?.master || null) !== master) throw sdkError('the account changed', 'account_changed')
@@ -3558,7 +3860,7 @@ class Connections {
3558
3860
  const wb = this._wb, auth = wb._auth()
3559
3861
  const account = await wb._account()
3560
3862
  if (job && webhook !== true && !/^whsec_/.test(String(secret || '').trim())) throw sdkError('witbitz: a job agent is a webhook — pass webhook: true and its whole https address as host', 'invalid_argument')
3561
- const out = await attachConnection({ post: wb._sentinelPost(), auth, account, label, host, secret, rules, limits, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow, tenant: wb._tenant || undefined, ...(webhook === true ? { bearerWebhook: true } : {}) })
3863
+ const out = await attachConnection({ post: wb._sentinelPost(), pendingStore: this._pendingFor(account), auth, account, label, host, secret, rules, limits, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow, tenant: wb._tenant || undefined, ...(webhook === true ? { bearerWebhook: true } : {}) })
3562
3864
  const j = out.webhook && job ? roomJob(job) : null
3563
3865
  return { ...out, account, ...(j ? { job: j } : {}) }
3564
3866
  }
@@ -3581,10 +3883,14 @@ class Connections {
3581
3883
  * keep offering a connection that answers 404 (sync sweep, 10-16 #9). → the Sentinel's answer + `removedFrom` (a count). */
3582
3884
  async detach(id, { spaces = [] } = {}) {
3583
3885
  const wb = this._wb, cid = String(id || '')
3886
+ const account = await wb._account()
3887
+ const removed = await wb.a2a._disconnectConnection(cid, this._bindingFor?.(cid, account))
3888
+ if (account !== await wb._account()) throw sdkError('Account changed during disconnect', 'account_changed')
3584
3889
  const out = await detachConnection({ post: wb._sentinelPost(), auth: wb._auth(), id: cid })
3890
+ await this._pendingFor(account).drop(cid)
3585
3891
  let removedFrom = 0
3586
3892
  for (const sp of Array.isArray(spaces) ? spaces : []) { try { if (sp && sp.connections) { await sp.connections.revoke(cid); removedFrom++ } } catch { /* one Space's refusal does not undo the detach */ } }
3587
- return { ...(out || {}), removedFrom }
3893
+ return { ...(out || {}), ...(removed.length ? { removed } : {}), removedFrom }
3588
3894
  }
3589
3895
 
3590
3896
  // ── CONNECT TO A BUILDER'S OAUTH APP (https://witbitz.chat/docs/connections.md). Two calls around the consent screen. The PKCE
@@ -3612,7 +3918,8 @@ class Connections {
3612
3918
  const dk = await this._dispKey()
3613
3919
  const disp = dk && label ? await sealDisp(dk, id, { label: String(label).trim().slice(0, 80) }).catch(() => '') : ''
3614
3920
  const sealed = await sealToEnclave(key, nonce, { state: String(state), code: String(code), callKey, id, ...(label ? { label: String(label) } : {}), ...(host ? { host: String(host) } : {}), ...(disp ? { disp } : {}) })
3615
- const r = await post({ op: 'sentinel', sentinel: { mode: 'oauthfinish', sealed }, ...auth })
3921
+ const account = await wb._account()
3922
+ const r = await postWithPendingKey(post, { op: 'sentinel', sentinel: { mode: 'oauthfinish', sealed }, ...auth }, id, { label, host, callKey, account, at: Date.now() }, this._pendingFor(account))
3616
3923
  if (!r || r.error || !r.ok) throw Object.assign(new Error(`witbitz: the sign-in was not completed (${(r && (r.error || r.reason)) || 'no answer'})`), { code: (r && r.error) || 'no_answer', ...(r && r.reason ? { reason: r.reason } : {}) })
3617
3924
  return { id: r.id, label: String(r.label || label || ''), host: r.host, provider: 'oauth2', callKey, account: r.account || await wb._account() } // `label`: the Connection type promises one (sync sweep, 2026-10-10)
3618
3925
  }
@@ -3637,15 +3944,16 @@ class Connections {
3637
3944
  * its host needs no declaration (connections.js attachMcp; it was filed under the tenant and refused — docs sync, 2026-11-22). */
3638
3945
  async attachMcp ({ url, label, token = '' } = {}) {
3639
3946
  const wb = this._wb, auth = wb._auth(), account = await wb._account()
3640
- const out = await attachMcpServer({ post: wb._sentinelPost(), auth, account, label, url, token, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3947
+ const out = await attachMcpServer({ post: wb._sentinelPost(), pendingStore: this._pendingFor(account), auth, account, label, url, token, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3641
3948
  return { ...out, account, mcp: true }
3642
3949
  }
3643
3950
  /** Finish a server's sign-in with the `state` and `code` your callback received. → a connection, as `attachMcp`. */
3644
3951
  async finishMcp ({ state, code, label, host } = {}) {
3645
3952
  const wb = this._wb, auth = wb._auth()
3646
3953
  if (!state || !code) throw sdkError('witbitz: finishMcp needs the state and code from your callback', 'invalid_argument')
3647
- const out = await finishMcpSignIn({ post: wb._sentinelPost(), auth, state: String(state), code: String(code), label, host, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3648
- return { ...out, account: await wb._account(), mcp: true }
3954
+ const account = await wb._account()
3955
+ const out = await finishMcpSignIn({ post: wb._sentinelPost(), pendingStore: this._pendingFor(account), auth, state: String(state), code: String(code), label, host, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3956
+ return { ...out, account, mcp: true }
3649
3957
  }
3650
3958
  /** The tools an MCP connection offers, as the server describes them (asked through the Sentinel). → `{ tools, server, truncated }`. */
3651
3959
  async mcpTools (id) { const wb = this._wb; return listMcpTools({ post: wb._sentinelPost(), auth: wb._auth(), id: String(id || '') }) }
@@ -3659,7 +3967,7 @@ class SpaceConnections {
3659
3967
  async grants() {
3660
3968
  const sp = this._space
3661
3969
  if (sp._wb?.vault?._c) return sp._wb.vault._c.roomAccount(sp.room, 'connections', 'grants')
3662
- const cfg = await sp._gateConfig({ plainMark: true })
3970
+ const cfg = await sp._gateConfig({ fresh: true, plainMark: true })
3663
3971
  const wb = sp._wb
3664
3972
  const [account, list] = await Promise.all([wb._account().catch(() => ''), wb.connections.list().catch(() => null)])
3665
3973
  const known = Array.isArray(list) ? new Set(list.map(c => c.id)) : null
@@ -3685,7 +3993,7 @@ class SpaceConnections {
3685
3993
  let mcp
3686
3994
  if (c.mcp && !sp._wb) throw sdkError('witbitz: granting an MCP connection needs the signed-in account (open the Space through wb)', 'invalid_argument')
3687
3995
  if (c.mcp) { // an MCP server: its tools, as the app's "Add" does (mcpToolsSheet addWithRecommended)
3688
- const listed = await listMcpTools({ post: sp._wb._sentinelPost(), auth: sp._wb._auth(), id: String(c.id) })
3996
+ const listed = await listGrantTools(c.host, () => listMcpTools({ post: sp._wb._sentinelPost(), auth: sp._wb._auth(), id: String(c.id) }))
3689
3997
  const all = listed.tools.map(roomTool).filter(Boolean)
3690
3998
  const rec = recommendedChoice(all)
3691
3999
  const chosen = new Set(Array.isArray(tools) ? tools.map(String) : rec.chosen)
@@ -3702,14 +4010,44 @@ class SpaceConnections {
3702
4010
  const { mcp: _flag, ...entry } = c
3703
4011
  const r = await sp._client.setConfig(sp.room, sp._mk, { connections: { add: roomEntry({ ...entry, account, reads: reads === 'auto' || reads === undefined && readsAutoFor(c) ? 'auto' : undefined, ...(mcp ? { mcp } : {}) }) } }, from)
3704
4012
  if (!r || r.status !== 200) throw refused('recording the connection in this Space', r)
4013
+ sp._gateCfg = null
3705
4014
  return { granted: String(c.id), ...(mcp ? { tools: mcp.tools.map((t) => t.name), auto: mcp.auto } : {}) }
3706
4015
  }
3707
4016
  /** Drop a connection from THIS Space only; it stays attached to the account. */
3708
- async revoke(id, { from } = {}) {
4017
+ async revoke(id, { from, includeAssistant = false } = {}) {
4018
+ const parent = this._space, wb = parent._wb
4019
+ if (includeAssistant) {
4020
+ const generation = wb?._archiveGeneration
4021
+ if (!wb || parent._memoryOwner !== generation) throw sdkError('Reopen this Space in the current account', 'account_changed')
4022
+ let complete = !!wb._heldLaneRooms
4023
+ if (wb.account.enabled) {
4024
+ try { complete = !!(await wb.account.sync())?.ok } catch { complete = false }
4025
+ if (generation !== wb._archiveGeneration) throw sdkError('The account changed', 'account_changed')
4026
+ }
4027
+ const saved = new Map((wb.account.rooms || []).filter(r => !r.detachedLane && r.shared === parent.room).map(r => [r.room, r]))
4028
+ const live = new Map([...(wb._archiveHandles || []), ...(wb._openLanes || [])].filter(sp => sp._sharedRoom === parent.room &&
4029
+ !sp._stopped && !sp._detachedLane && sp._memoryOwner === parent._memoryOwner).map(sp => [sp.room, sp]))
4030
+ const ids = new Set([parent.room, ...saved.keys(), ...live.keys(), ...(wb._heldLaneRooms?.(parent.room) || [])])
4031
+ const unchecked = [], removedFrom = []
4032
+ for (const room of ids) {
4033
+ if (wb._archiveGeneration !== generation) throw sdkError('The account changed', 'account_changed')
4034
+ let sp
4035
+ try {
4036
+ sp = room === parent.room ? parent : live.get(room) || (wb._scopedRoom ? wb._scopedRoom(room) : await wb.openSpace(saved.get(room).link))
4037
+ if (sp.room !== room || wb._archiveGeneration !== generation) throw sdkError('Room or account changed', 'account_changed')
4038
+ await sp.connections.revoke(id, { from })
4039
+ removedFrom.push(room)
4040
+ } catch { unchecked.push(room) }
4041
+ finally { if (sp && sp !== parent && !live.has(room)) sp.close() }
4042
+ }
4043
+ if (unchecked.length) throw Object.assign(sdkError('Some Space grants could not be revoked', 'partial_revoke'), { unchecked, removedFrom })
4044
+ return { revoked: String(id), removedFrom, incomplete: !complete }
4045
+ }
3709
4046
  from = this._space._who(from)
3710
4047
  const sp = this._space
3711
4048
  const r = await sp._client.setConfig(sp.room, sp._mk, { connections: { remove: String(id || '') } }, from)
3712
4049
  if (!r || r.status !== 200) throw refused('dropping the connection', r) // as grant: the server's code, status and reason (sync sweep, 2026-10-10)
4050
+ sp._gateCfg = null
3713
4051
  return { revoked: String(id) }
3714
4052
  }
3715
4053
  }
@@ -3718,13 +4056,14 @@ class SpaceConnections {
3718
4056
  * STATE (`wb.siri.state`) holds the inbox private keys — without it a drop can never be opened — so persist it as
3719
4057
  * you persist the session, and hand it back as `new Witbitz({ siri: state })`. */
3720
4058
  class SiriAccount {
3721
- constructor(wb) { this._wb = wb }
4059
+ constructor(wb) { this._wb = wb; this.onState = null }
4060
+ _changed() { this.onState?.(this.state) }
3722
4061
  /** JSON-safe state to persist. */
3723
4062
  get state() { return JSON.parse(JSON.stringify(this._wb._siri)) }
3724
4063
  /** Adopt persisted state. */
3725
4064
  restore(state) { this._wb._siri = siriStateOf(state); return this }
3726
4065
  /** The Shortcut's key and endpoint (null key until a Space enables Siri). */
3727
- get shortcut() { return { key: this._wb._siri.token || null, endpoint: SIRI_ENDPOINT } }
4066
+ get shortcut() { return { key: this._wb._siri.pendingRotation ? null : this._wb._siri.token || null, endpoint: SIRI_ENDPOINT } }
3728
4067
  /** What the Sentinel holds for this account (aliases, counts) — as it reports it. */
3729
4068
  async status() {
3730
4069
  const wb = this._wb, auth = wb._auth()
@@ -3733,16 +4072,29 @@ class SiriAccount {
3733
4072
  return r
3734
4073
  }
3735
4074
  /** A new Shortcut key: the old one stops working the moment the record is pushed. → the new key. */
3736
- async rotateKey() { return this._change((st) => { st.token = newSiriKey(); return st.token }) }
4075
+ async sync() {
4076
+ const result = await this._change(async st => {
4077
+ if (!st.token) return NO_SIRI_CHANGE
4078
+ const remote = await this.status()
4079
+ if (remote.configured && !siriAliasesDiffer(st.rooms, remote)) return NO_SIRI_CHANGE
4080
+ return true
4081
+ })
4082
+ return { synced: result === true }
4083
+ }
4084
+ async rotateKey() { return this._change((st, rotation) => { if (!rotation) st.token = newSiriKey(); return st.token }) }
3737
4085
  /** Turn Siri off everywhere for this account: the Sentinel forgets the record; the local state is cleared. */
3738
4086
  // IN THE SAME QUEUE AS EVERY CHANGE (sync sweep 2026-11-14 P7, owner: yes): a change still being pushed when revoke() ran finished after
3739
4087
  // it and put Siri back at the Sentinel and here. Now revoke waits for it, and a change asked after it runs on the cleared state.
3740
4088
  async revoke() {
4089
+ const wb = this._wb, generation = wb._archiveGeneration, auth = wb._auth()
4090
+ const check = () => { if (generation !== wb._archiveGeneration) throw sdkError('Account changed during Siri deletion', 'account_changed') }
3741
4091
  const run = async () => {
3742
- const wb = this._wb, auth = wb._auth()
4092
+ check()
3743
4093
  const r = await wb._sentinelPost()({ op: 'sentinel', sentinel: { mode: 'sirirevoke' }, ...auth })
3744
4094
  if (!r || r.error) throw Object.assign(new Error(`witbitz: the Sentinel could not be reached (${(r && r.error) || 'no answer'})`), { code: (r && r.error) || 'no_answer' })
3745
- wb._siri = siriStateOf(null)
4095
+ check()
4096
+ wb._siri = siriStateOf({ rev: Math.max(Date.now(), (wb._siri.rev || 0) + 1) })
4097
+ this._changed()
3746
4098
  return r
3747
4099
  }
3748
4100
  const p = (this._q || Promise.resolve()).then(run, run)
@@ -3757,15 +4109,62 @@ class SiriAccount {
3757
4109
  // overwritten (sync sweep 2026-11-13 #2: the next keep pass then stamped the other devices' Spaces `gone` everywhere): the
3758
4110
  // change is made again on top of what landed and that is pushed — at most a few times, then the latest state stands.
3759
4111
  _change(fn) {
4112
+ const generation = this._wb._archiveGeneration
3760
4113
  const run = async () => {
4114
+ if (generation !== this._wb._archiveGeneration) throw sdkError('Account changed before Siri setup', 'account_changed')
3761
4115
  let out
3762
4116
  for (let i = 0; i < 4; i++) {
3763
- const base = this._wb._siri
4117
+ const account = await this._wb._account(), base = this._wb._siri
3764
4118
  const next = siriStateOf(JSON.parse(JSON.stringify(base)))
3765
- out = await fn(next)
3766
- if (out === NO_SIRI_CHANGE) return out
3767
- await this._push(next)
3768
- if (this._wb._siri === base) { this._wb._siri = next; return out }
4119
+ const pending = next.pendingRemovals || []
4120
+ const priorSetup = next.pendingSetup, rotation = next.pendingRotation
4121
+ delete next.pendingRotation
4122
+ delete next.pendingSetup
4123
+ if (priorSetup) {
4124
+ if (!next.token) next.token = priorSetup.token
4125
+ if (next.token === priorSetup.token) {
4126
+ for (const [id, inbox] of Object.entries(priorSetup.rooms)) if (!next.rooms[id]) next.rooms[id] = inbox
4127
+ if (!next.defaultRoom && priorSetup.defaultRoom) next.defaultRoom = priorSetup.defaultRoom
4128
+ }
4129
+ }
4130
+ delete next.pendingRemovals
4131
+ for (const room of pending) {
4132
+ delete next.rooms[room]
4133
+ if (next.defaultRoom === room) next.defaultRoom = ''
4134
+ }
4135
+ if (rotation) next.token = rotation.to
4136
+ out = await fn(next, rotation)
4137
+ if (out === NO_SIRI_CHANGE && !pending.length && !priorSetup && !rotation) return out
4138
+ if (generation !== this._wb._archiveGeneration || account !== await this._wb._account()) throw sdkError('Account changed during Siri setup', 'account_changed')
4139
+ const removed = Object.keys(base.rooms).filter(room => !next.rooms[room])
4140
+ const added = Object.entries(next.rooms).filter(([id]) => !base.rooms[id])
4141
+ const stageLocal = !this._stageInbox && (removed.length || added.length || priorSetup || next.token !== base.token) && this._wb._siri === base
4142
+ if (stageLocal) {
4143
+ if (next.token !== base.token && (base.token || !added.length)) base.pendingRotation = { from: base.token, to: next.token }
4144
+ if (removed.length) base.pendingRemovals = removed
4145
+ if (added.length) base.pendingSetup = siriStateOf({ token: next.token, rooms: Object.fromEntries(added), defaultRoom: next.defaultRoom })
4146
+ else delete base.pendingSetup
4147
+ this._changed()
4148
+ }
4149
+ const finish = await this._stageInbox?.(next)
4150
+ try { await this._push(next) } catch (e) {
4151
+ if (e.definiteRefusal || (e.status >= 400 && e.status < 500)) {
4152
+ finish?.(false)
4153
+ if (stageLocal && this._wb._siri === base) {
4154
+ if (rotation) base.pendingRotation = rotation
4155
+ else delete base.pendingRotation
4156
+ if (priorSetup) base.pendingSetup = priorSetup
4157
+ else delete base.pendingSetup
4158
+ if (pending.length) base.pendingRemovals = pending
4159
+ else delete base.pendingRemovals
4160
+ this._changed()
4161
+ }
4162
+ }
4163
+ throw e
4164
+ }
4165
+ if (generation !== this._wb._archiveGeneration || account !== await this._wb._account()) throw sdkError('Account changed during Siri setup', 'account_changed')
4166
+ finish?.(true)
4167
+ if (this._wb._siri === base) { this._wb._siri = next; this._changed(); return out === NO_SIRI_CHANGE ? true : out }
3769
4168
  }
3770
4169
  throw sdkError('witbitz: the Siri state kept changing while it was being saved — try again', 'siri_busy')
3771
4170
  }
@@ -3783,7 +4182,7 @@ class SiriAccount {
3783
4182
  const { nonce, key } = await attestStandingSentinel({ post, auth, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3784
4183
  const sealed = await sealToEnclave(key, nonce, rec)
3785
4184
  const r = await post({ op: 'sentinel', sentinel: { mode: 'sirigrant', sealed }, ...auth })
3786
- if (!r || r.error || !r.ok) throw (r ? Object.assign(new Error(`witbitz: the Sentinel refused the Siri record (${r.error || r.reason || 'refused'})`), { code: r.error || 'refused', ...(r.reason ? { reason: r.reason } : {}) }) : Object.assign(new Error('witbitz: the Sentinel did not answer'), { code: 'no_answer' }))
4185
+ if (!r || r.error || !r.ok) throw (r ? Object.assign(new Error(`witbitz: the Sentinel refused the Siri record (${r.error || r.reason || 'refused'})`), { code: r.error || 'refused', definiteRefusal: (r.ok === false || !!r.error) && !(r.status >= 500) && !['timeout', 'busy', 'unreachable'].includes(r.error) /* not 'sentinel_unavailable': the server says nothing was sent (sentinelRelay.mjs: no endpoint) — staged as unknown, a failed rotate hid the key and the next Siri change completed it (34304d584) */, ...(r.reason ? { reason: r.reason } : {}) }) : Object.assign(new Error('witbitz: the Sentinel did not answer'), { code: 'no_answer' }))
3787
4186
  return r
3788
4187
  }
3789
4188
  }
@@ -3796,25 +4195,49 @@ class SpaceSiri {
3796
4195
  /** Enable Siri for this Space: the word you will say ("groceries"), optionally the default for anything said
3797
4196
  * without an alias. Mints the Shortcut key on the first enable and an inbox keypair for this Space, pushes the
3798
4197
  * account's record to the Sentinel. → `{ key, endpoint, alias }` — the key is what the Shortcut sends. */
3799
- async enable({ alias, label = '', makeDefault = false } = {}) {
4198
+ _assistantRoom() {
4199
+ const sp = this._space, wb = this._wb()
4200
+ if (wb._siriLane) return wb._siriLane(sp.room)
4201
+ if (sp._memoryOwner !== wb._archiveGeneration) throw sdkError('Reopen this Space in the current account', 'account_changed')
4202
+ const open = [...(wb._archiveHandles || [])].find(x => !x._stopped && !x._detachedLane && x._sharedRoom === sp.room && x._archiveGeneration === wb._archiveGeneration && x._archiveEmail === (wb._session?.email || '') && x._archiveMaster === (wb.backup._s?.master || null))
4203
+ if (open) return open.room
4204
+ const backupOwner = wb._siriBackupOwners?.get(wb.backup._s) || wb.backup._s?.email
4205
+ if (backupOwner && backupOwner !== wb._session?.email) return null
4206
+ return wb.account.rooms.find(r => !r.detachedLane && r.shared === sp.room)?.room
4207
+ }
4208
+ async enable({ alias, label = '', makeDefault = false, includeAssistant = false } = {}) {
3800
4209
  const wb = this._wb(), sp = this._space
3801
- const a = normSiriAlias(alias)
3802
- if (!a) throw sdkError('witbitz: an alias is needed — the word you will say to Siri', 'invalid_argument')
3803
- if (/[,:;]/.test(a)) throw sdkError('witbitz: an alias cannot contain , : or ;', 'invalid_argument')
4210
+ if (sp.temporary) throw sdkError('Temporary Spaces cannot receive Siri captures', 'temporary_room')
4211
+ const requested = normSiriAlias(alias)
4212
+ if (alias !== undefined && !requested) throw sdkError('witbitz: an alias is needed — the word you will say to Siri', 'invalid_argument')
4213
+ if (/[,:;]/.test(requested)) throw sdkError('witbitz: an alias cannot contain , : or ;', 'invalid_argument')
3804
4214
  return wb.siri._change(async (st) => { // kept only once the Sentinel took it (pass 9, K#5)
4215
+ const a = requested || st.rooms[sp.room]?.alias || uniqueAlias(label || sp.title || 'Space', new Set(Object.values(st.rooms).map(r => r.alias)))
3805
4216
  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')
3806
4217
  if (!st.token) st.token = newSiriKey()
3807
4218
  const cur = st.rooms[sp.room]
3808
4219
  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)
3809
4220
  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() } }
4221
+ const lane = includeAssistant && this._assistantRoom()
4222
+ if (lane && !st.rooms[lane]) {
4223
+ const taken = new Set(Object.values(st.rooms).map(r => r.alias))
4224
+ const assistantAlias = uniqueAlias(a.slice(0, 22) + ' assistant', taken), kp = await genRecipientKey()
4225
+ st.rooms[lane] = { alias: assistantAlias, label: (label || a) + ' · assistant', pub: { x: kp.publicJwk.x, y: kp.publicJwk.y }, priv: kp.privateJwk, at: Date.now() }
4226
+ }
3810
4227
  if (makeDefault) st.defaultRoom = sp.room; else if (st.defaultRoom === sp.room) st.defaultRoom = ''
3811
4228
  return { key: st.token, endpoint: SIRI_ENDPOINT, alias: a }
3812
4229
  })
3813
4230
  }
3814
4231
  /** Disable Siri for this Space (other Spaces keep theirs). A push that fails rejects and keeps it on, here as at the Sentinel. */
3815
- async disable() {
4232
+ async disable({ includeAssistant = false } = {}) {
3816
4233
  const wb = this._wb(), room = this._space.room
3817
- const r = await wb.siri._change((st) => { if (!st.rooms[room]) return NO_SIRI_CHANGE; delete st.rooms[room]; if (st.defaultRoom === room) st.defaultRoom = ''; return true })
4234
+ const targets = [room, includeAssistant && this._assistantRoom()].filter(Boolean)
4235
+ const r = await wb.siri._change(st => {
4236
+ if (!targets.some(id => st.rooms[id])) return NO_SIRI_CHANGE
4237
+ for (const id of targets) delete st.rooms[id]
4238
+ if (targets.includes(st.defaultRoom)) st.defaultRoom = ''
4239
+ return true
4240
+ })
3818
4241
  return { disabled: r === true }
3819
4242
  }
3820
4243
  /** Collect: pull the account's drops, open the ones for THIS Space with its inbox key, post each as you (🎙-marked),