@witbitz/sdk 4.3.0 → 4.5.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 (112) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +41 -5
  3. package/accountErase.js +15 -4
  4. package/accountIndexDoc.js +24 -7
  5. package/accountRecord.js +6 -2
  6. package/accountStores.js +21 -5
  7. package/acctV2App.js +111 -12
  8. package/acctV2Client.js +11 -1
  9. package/acctV2UiCore.js +27 -7
  10. package/agentDoorTools.js +28 -0
  11. package/awsKey.js +3 -1
  12. package/backupRecord.js +3 -0
  13. package/chatLock.js +16 -0
  14. package/cloudDevicePins.js +2 -2
  15. package/codeAttachments.js +101 -0
  16. package/codeCache.js +173 -0
  17. package/codeCloud.js +2 -2
  18. package/codeComputers.js +9 -0
  19. package/codeFolders.js +116 -0
  20. package/codeHistory.js +76 -0
  21. package/codeLanguage.js +54 -0
  22. package/codeModes.js +2 -0
  23. package/codeProgress.js +54 -0
  24. package/codeSent.js +109 -0
  25. package/codeSubagents.js +107 -0
  26. package/codeTransport.js +46 -5
  27. package/connections.js +37 -20
  28. package/decrypt.html +69 -9
  29. package/deviceAttest.js +9 -3
  30. package/eraseFile.js +15 -0
  31. package/idb.js +19 -3
  32. package/idbSeal.js +5 -2
  33. package/inviteReceive.js +44 -0
  34. package/inviteSend.js +8 -2
  35. package/jobAgents.js +2 -2
  36. package/keptMerge.js +9 -2
  37. package/l1-worker-src.js +1 -1
  38. package/l1-worker.js +122 -43
  39. package/laneAssociation.js +78 -0
  40. package/laneConfig.js +4 -3
  41. package/laneLinkCore.js +9 -0
  42. package/ledgerView.js +30 -4
  43. package/manifest.json +112 -87
  44. package/memberChange.js +4 -2
  45. package/mirrorBatch.js +47 -0
  46. package/offlineBundle.js +21 -0
  47. package/opRouting.js +10 -0
  48. package/package.json +27 -2
  49. package/pdfOptions.js +13 -0
  50. package/pdfText.js +107 -0
  51. package/pdfjs.mjs +28 -0
  52. package/pdfjs.worker.mjs +28 -0
  53. package/protectedLocal.js +52 -13
  54. package/reactionHolders.js +86 -0
  55. package/removedMessage.js +1 -1
  56. package/roomEmbed.js +111 -0
  57. package/roomIntake.js +324 -0
  58. package/roomName.js +1 -1
  59. package/roomRoster.js +30 -7
  60. package/rosterCount.js +6 -3
  61. package/scheduleNext.js +60 -0
  62. package/sdkA2A.js +200 -42
  63. package/sdkAccount.js +88 -18
  64. package/sdkAccountDoc.js +13 -5
  65. package/sdkAccountSections.js +172 -23
  66. package/sdkAgui.js +33 -6
  67. package/sdkBackup.js +53 -11
  68. package/sdkBackupV2.js +15 -3
  69. package/sdkCloudDevice.js +20 -5
  70. package/sdkComputers.js +695 -65
  71. package/sdkDictation.js +115 -25
  72. package/sdkErase.js +12 -5
  73. package/sdkExports.js +19 -8
  74. package/sdkInvitations.js +4 -2
  75. package/sdkKeptAgent.js +19 -3
  76. package/sdkKeptIntake.js +100 -0
  77. package/sdkLaneLink.js +8 -9
  78. package/sdkPlan.js +4 -2
  79. package/sdkRekey.js +122 -22
  80. package/sdkReport.js +1 -1
  81. package/sdkSafeMedia.js +1 -1
  82. package/sdkSchedules.js +8 -1
  83. package/sdkSpeech.js +32 -2
  84. package/sdkTemporaryRooms.js +124 -0
  85. package/sdkTurn.js +12 -4
  86. package/sdkVault.js +66 -10
  87. package/sentinelRelease.js +1 -0
  88. package/sharedViews.js +34 -4
  89. package/siri.js +140 -9
  90. package/spaceClient.js +112 -17
  91. package/spaceEmailGate.js +2 -2
  92. package/spaceExport.js +50 -5
  93. package/spaceFork.js +15 -7
  94. package/spaceTemplates.js +99 -0
  95. package/speechOut.js +21 -5
  96. package/store.js +134 -27
  97. package/sw-notif-core.js +11 -8
  98. package/tapTrail.js +58 -0
  99. package/turnVerdict.js +1 -0
  100. package/usageReceipts.js +12 -5
  101. package/vault-core.js +568 -126
  102. package/vault-kit.mjs +3 -3
  103. package/vault-screens.js +30 -18
  104. package/vaultAtRest.js +38 -6
  105. package/vaultCoreLock.js +3 -1
  106. package/vaultCorePush.js +58 -7
  107. package/vaultKeep.js +9 -3
  108. package/vaultWorkerHost.js +32 -7
  109. package/witbitz-admin.d.ts +3 -0
  110. package/witbitz-admin.mjs +12 -11
  111. package/witbitz-sdk.d.ts +170 -43
  112. package/witbitz-sdk.js +833 -203
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)
@@ -44,28 +46,29 @@ import { receiptFor } from './usageReceipts.js' // a turn's usage receipt addres
44
46
  import { aguiRun, aguiHistory, aguiAgent } from './sdkAgui.js' // a Space as an AG-UI 1.0 agent, in the builder's page (https://witbitz.chat/docs/sdk-agents.md#ag-ui)
45
47
  export { aguiRun, aguiHistory, aguiAgent }
46
48
  export { verifyEat, fetchAndVerifyEat, EAT_PROFILE } from './eat.js' // RATS/EAT: check a Witbitz enclave with a standard token (https://witbitz.chat/docs/sdk-keys.md#eat)
47
- import { Speech } from './sdkSpeech.js' // wb.speak(): text read aloud, the Spaces app's "Play aloud" player (speechOut.js)
49
+ import { Speech, tokenPayer } 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'
@@ -84,11 +87,13 @@ import { openRoomStream } from './roomStreamClient.js'
84
87
  import { makeEmailPost, emailStart, emailVerify, emailRefresh } from './emailSignIn.js' // the email-code protocol the vault and the Spaces app use
85
88
  import { answerDeviceCall } from './deviceCall.js' // one way to answer a device call, shared with the Spaces app
86
89
  import { LANE_PERSONA, LANE_AGENT_NAME, inheritToolsFrom, laneInherits, gatedStub } from './laneConfig.js'
87
- import { renderSharedViews, viewsNamedIn, SHARED_VIEWS_DOC } from './sharedViews.js'
90
+ import { renderSharedViews, viewsNamedIn, viewFromRead, isMapView, SHARED_VIEWS_DOC } from './sharedViews.js'
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
- 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
93
+ import { allReactors, rowIsMine } from './reactionHolders.js' // who holds a reaction (space.reactionsOf) — one rule with the app and the server
94
+ import { makeLedgerView, needsTailResync, mayHideEdit, TAIL_RESYNC_WITH_NEW_MS, REACTION_RESYNC_TAIL, entryKeyOf, readAllPages } from './ledgerView.js' // how the Spaces app merges a room's entries
95
+ import { roomInviteFlags, applySkills, roomEmbed } from './roomEmbed.js'
96
+ import { turnVerdict, QUEUE_RETRY_MS, QUEUE_MAX_TRIES, CONTINUATION_WINDOW_MS } from './turnVerdict.js' // the send hold + answer reading the Spaces app uses
92
97
  /** A turn's answer with `ok` always a boolean: posted / silent / pending → true; anything with an error, or busy, refused,
93
98
  * failed, no answer → false (Space#_turnHeld). */
94
99
  const withTurnOk = (r) => { const k = turnVerdict(r).kind; return withUsage({ ...(r || {}), ok: !(r && r.error) && (k === 'ok' || k === 'silent' || k === 'pending') }) }
@@ -102,17 +107,19 @@ import { WitbitzAdmin } from './witbitz-admin.js'
102
107
  import { Turn, turnUsage } from './sdkTurn.js' // space.turn(): a turn you can hold (sdk-roadmap item 6)
103
108
  import { planChange } from './sdkPlan.js'
104
109
  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
110
+ export { assistantTemplates } from './spaceTemplates.js'
111
+ 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
112
  import { connectVault } from './sdkVault.js' // a builder-hosted vault holds the keys; this page never does (docs/sdk-vault-mode.md)
107
113
  import { makeTurnFeed } from './turnFeed.js' // one reading of a running turn, shared with the Spaces app
108
114
  import { roomRegion, regionCode, DEFAULT_REGION, newRoomId } from './regions.js' // a room's home region is in its id (docs/multi-region.md)
109
115
 
110
116
  // The room's reply mode and model pick: ONE module with the Spaces app (roomSettings.js — the same names, the same sealed
111
117
  // `agentmode` and `model` docs), so the SDK and the app are one setting, not two that drift.
112
- import { REPLY_MODES, REPLY_MODE_LABEL, modeFromDoc, modelPickFromDoc, turnModelOf, roomDefaultReplyMode } from './roomSettings.js'
118
+ import { REPLY_MODES, REPLY_MODE_LABEL, modeFromDoc, modelPickFromDoc, modelDocOf, turnModelOf, roomDefaultReplyMode } from './roomSettings.js'
113
119
  import { TOOLRULES_DOC, RULE_VALUES, toolRulesDocOf, rulesFromDoc } from './toolRules.js' // which tools run on their own (space.toolRules)
114
120
  import { rosterParticipants } from './rosterCount.js' // the server's count (agent/rosterCount.mjs) — replyMode()'s default
115
121
  const NAME_RECHECK_EVERY = 20 // = roomTitle.js RETITLE_EVERY / agent/spaceService.mjs RETITLE_AFTER
122
+ const ATTACH_KEEP_B64 = 4 * 1024 * 1024 // an opened attachment kept on its message for snapshot() up to this much base64 (~3 MB a file)
116
123
  const SETTINGS_FRESH_MS = 20_000 // a member may change either from another client; a long-lived handle re-reads them before a turn after this long
117
124
  const DEFAULT_ENDPOINT = 'https://api.witbitz.chat/v1/space' // the public, self-authenticating Space endpoint (a Space authenticates by its key-commitment, not a tenant account)
118
125
  const DEFAULT_VIEWER = 'https://witbitz-spaces.pages.dev' // shareLink base — the reference Spaces app ORIGIN (the client appends `/space?room=…#…`). Override to point links at your own viewer origin.
@@ -174,7 +181,10 @@ function healingClient(c, heal, keys = null) {
174
181
  // A poll refusal no retry cures (pollVerdict 'gated' with these reasons): the poll slows to HELD_POLL_MS (sync sweep, 2026-10-10).
175
182
  const PERMANENT_REFUSALS = new Set(['not_on_list'])
176
183
  const isPurged = (e) => !!(e && e.kind === 'purged') // a deleted mail's place in the history (agent/mailPurge.mjs) — never a message
184
+ // a mail row's entry — what op `mailpurge` replaces in its slot (agent/mailPurge.mjs isPurgeableMail; messageRender.js draws none)
185
+ const isMailEntry = (e) => !!(e && e.kind === 'data' && Array.isArray(e.ops) && e.ops.length && e.ops.every((o) => o && (o.collection === 'mail' || o.collection === 'mailfile')))
177
186
  const HELD_POLL_MS = 60000
187
+ const LANES_CHECK_WAIT_MS = 4000 // how long a poll waits for its periodic settings read before handing on what it read
178
188
  const KEY_WAIT_POLL_MS = 15000 // on the list of a re-keyed room but holding no key it can open (sdkRekey.js 'pending'): a fresh link or a restored invite key may come
179
189
  // A quote: replyQuote.js, the app's reply strip's own rule; no `excerpt` when there is nothing to show.
180
190
  const replyRef = (m) => { const q = m && m.id != null ? replyQuote(m) : null; return q && (q.excerpt ? q : { key: q.key, name: q.name }) } // the SDK quotes only a message with an id
@@ -189,7 +199,7 @@ const perTurn = (instructions) => (typeof instructions === 'string' && instructi
189
199
  /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
190
200
  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
201
  export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
192
- export const SDK_VERSION = '4.3.0'
202
+ export const SDK_VERSION = '4.5.0'
193
203
  // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
194
204
  const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
195
205
  /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
@@ -252,20 +262,39 @@ function mirrorBy(room, e) {
252
262
  return Object.keys(by).length ? { by } : {}
253
263
  }
254
264
  /** 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. */
265
+ * 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
266
  async function withBytes(from, list) {
257
267
  if (!Array.isArray(list) || !list.length) return undefined
258
268
  return Promise.all(list.map(async (a) => {
259
- if (!a || typeof a !== 'object' || (typeof a.b64 === 'string' && a.b64)) return a
269
+ if (!a || typeof a !== 'object') return a
260
270
  const { ref, parts, size, ...rest } = a
261
- 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 }
271
+ // bytes already on the entry (one opened before is kept on its message, _keepOpened): the copy carries them, never the SOURCE
272
+ // room's reference — that blob is sealed to the source room's key and would not open where the copy lands
273
+ if ((typeof a.b64 === 'string' && a.b64) || (!ref && !parts)) return rest
274
+ const key = ref || (Array.isArray(parts) ? parts.join(',') : '')
275
+ const misses = _copyMisses.get(from) || new Map()
276
+ let o = null
277
+ try { o = await from.attachment(a) } catch { o = null }
278
+ if (o?.b64) { misses.delete(key); return { ...rest, b64: o.b64, mime: a.mime || o.mime } }
279
+ // A few passes, then without the bytes (second review, 2026-11-27; the app's rule, mirrorLoop.js inlineForMirror): a blob that is
280
+ // gone failed every pass, the batch never landed, and no later message reached the lane — with no `error` event either.
281
+ const n = (misses.get(key) || 0) + 1
282
+ misses.set(key, n); _copyMisses.set(from, misses)
283
+ if (n < COPY_TRIES) throw sdkError('attachment bytes could not be copied', 'attachment_unavailable')
284
+ return rest
265
285
  }))
266
286
  }
267
- const withMedia = (msg, images, files) => {
287
+ const COPY_TRIES = 3
288
+ const _copyMisses = new WeakMap() // per source Space, this page's memory only
289
+ // …AND TOGETHER (side sweep 2026-11-28): a turn is one request to the Space API (~6 MB), so two files each under their cap could not
290
+ // be sent at once. The app's composer budget (attachments.js SEND_BUDGET), in base64 characters; a confidential room seals the
291
+ // request once more (4/3).
292
+ const SEND_B64_MAX = 5_000_000
293
+ const encRoomOf = (sp) => { try { return !!(sp && sp._wb && sp._wb._enc && sp._wb._enc.rooms && sp._wb._enc.rooms.has(sp.room)) } catch { return false } }
294
+ const withMedia = (msg, images, files, { enclave = false } = {}) => {
268
295
  const im = mediaList(images, 'images'), fl = mediaList(files, 'files')
296
+ const chars = [...(im || []), ...(fl || [])].reduce((t, a) => t + a.b64.length, 0)
297
+ if ((enclave ? chars * 4 / 3 : chars) > SEND_B64_MAX) throw limitError(`these attachments are ${n(Math.floor(chars * 3 / 4))} bytes together; one message takes about ${n(Math.floor(SEND_B64_MAX * 3 / 4 / (enclave ? 4 / 3 : 1)))}${enclave ? ' in a confidential Space' : ''} — send them in separate messages`)
269
298
  return { ...msg, ...(im ? { images: im } : {}), ...(fl ? { files: fl } : {}) }
270
299
  }
271
300
  /** Throws `limit_exceeded` for a list of actions OFFERED TO ONE TURN that the server would cut or drop. */
@@ -365,7 +394,7 @@ export class Witbitz {
365
394
  * enclaveClaim?, fetchImpl?, WebSocketImpl? } —
366
395
  * `tenant` is your tenant's PUBLIC id (never a key): Spaces this page creates are attributed to it when the page's origin
367
396
  * 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 } = {}) {
397
+ 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
398
  // THE DEV SERVER'S ATTESTATION ROOT (devserver/, the Witbitz dev server with a confidential tier): base64 DER. It REPLACES the
370
399
  // pinned AWS root for this client's confidential tier — so a client given it trusts only that local server's enclave, never
371
400
  // Witbitz's (shipped by mistake, it fails closed). Never set by default; nothing else reads it.
@@ -449,6 +478,7 @@ export class Witbitz {
449
478
  // names. So the SDK signs in the same way the Spaces app's "Email me a code" does — an emailed six-digit code,
450
479
  // any address, any origin (the endpoints answer cross-origin) — and keeps the SESSION the app may persist and hand
451
480
  // back (`new Witbitz({ session })`). `loginBase` is where the code endpoints live (the reference app's origin).
481
+ this.temporaryRooms = new TemporaryRooms(this, keepTemporaryRooms)
452
482
  this._endpoint = endpoint
453
483
  this._tenant = tenant || ''
454
484
  this._tenantKey = tenantKey || '' // SERVER-SIDE ONLY (https://witbitz.chat/docs/connections.md) — a wsk_ key in a page is a leak
@@ -528,6 +558,30 @@ export class Witbitz {
528
558
  /** The account's LIVE index (sdkAccount.js): the rooms, archived/forgotten marks and devices, kept in step between every
529
559
  * device that holds the backup. In a browser it syncs on its own once the backup is on; `sync()` any time. */
530
560
  this.account = new AccountIndex({ backup: this.backup, client: () => this._client, deviceName: deviceName || '', viewer: this._viewer, live: () => this._live, version: SDK_VERSION })
561
+ this.account._deleteLockTarget = async (kind, target, current, approved, afterRemoval) => {
562
+ if (kind === 'code') return this.computers._deleteLockedSession(target, current)
563
+ if (kind !== 'room' || !current()) return false
564
+ const fresh = await this.account.sync()
565
+ if (!current() || !fresh?.ok) return false
566
+ const children = this.backup.rooms.filter(r => r.shared === target && !r.detachedLane)
567
+ if (children.some(r => r.laneOrigin === 'minted' && !approved.has(r.room))) return false
568
+ for (const child of children) {
569
+ if (child.laneOrigin === 'minted') this.account.forget(child.room)
570
+ else this.backup._detachLane(child.room, target)
571
+ }
572
+ this.account.forget(target)
573
+ const synced = await this.account.sync()
574
+ if (!current() || !synced?.ok) return false
575
+ await this.backup.save()
576
+ if (!current() || this.backup.rooms.some(r => r.room === target || r.shared === target)) return false
577
+ if (afterRemoval) for (const child of children) {
578
+ if (!current()) return false
579
+ if (child.laneOrigin === 'minted') await afterRemoval('room', child.room)
580
+ }
581
+ return current()
582
+ }
583
+ this.account._pruneAgents = () => this.a2a._pruneForgotten()
584
+
531
585
  this.account._emptyHooks = () => this._emptySpaceHooks()
532
586
  this.account._readName = async row => {
533
587
  const { mk } = await this._openLink(row.link)
@@ -567,6 +621,8 @@ export class Witbitz {
567
621
  // work in a vault — the keyless client has no enrolment, the vault answers no read proof, and a proof would bind the
568
622
  // page's key, not the vault's (hosting.md § Rooms only your app may use)
569
623
  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')
624
+ for (const name of ['devRoot', 'enclaveClaim']) if (opts?.[name] !== undefined) throw sdkError('witbitz: the vault supplies ' + name, 'vault_unsupported')
625
+ if (opts && opts.sentinel !== undefined) throw sdkError('witbitz: the vault supplies the Sentinel trust settings', 'vault_unsupported')
570
626
  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
627
  // THE ACCOUNT'S STATE IS THE VAULT'S (sync sweep 11-13 P7): a persisted `backup` / `siri` / `a2a` / `invite` state was taken
572
628
  // 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 +632,11 @@ export class Witbitz {
576
632
  // 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
633
  // spend, and the vault had none to give — billing was silently off, and requireUserToken refused every vault turn. The
578
634
  // 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
635
+ const vc = conn.client && { ...conn.client }
580
636
  if (vc && typeof conn.userToken === 'function') {
581
- let legacyBilling = Promise.resolve()
637
+ const queueKey = Symbol.for('witbitz.vault.legacyBilling')
638
+ const queues = globalThis[queueKey] ||= new Map()
639
+ const scope = conn.origin || conn
582
640
  const tokenSlot = { turn: 5, title: 4, decide: 6, importChat: 3, importWhatsApp: 3 }
583
641
  for (const op of Object.keys(tokenSlot)) {
584
642
  const orig = vc[op]; if (typeof orig !== 'function') continue
@@ -591,17 +649,19 @@ export class Witbitz {
591
649
  } catch { /* a missing billing token follows this operation's normal authorization rules */ }
592
650
  args[tokenSlot[op]] = token
593
651
  if (conn.info?.billingPerCall) return orig(...args)
594
- const run = legacyBilling.then(async () => {
652
+ const run = (queues.get(scope) || Promise.resolve()).then(async () => {
595
653
  try { await conn.userToken(token) }
596
654
  catch (error) { if (token || error?.code !== 'vault_refused') throw error }
597
655
  return orig(...args)
598
656
  })
599
- legacyBilling = run.catch(() => {})
657
+ const settled = run.catch(() => {})
658
+ queues.set(scope, settled)
659
+ settled.then(() => { if (queues.get(scope) === settled) queues.delete(scope) })
600
660
  return run
601
661
  }
602
662
  }
603
663
  }
604
- const wb = new Witbitz({ ...opts, ...(conn.info && conn.info.endpoint ? { endpoint: conn.info.endpoint } : {}), live: false, client: conn.client })
664
+ 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
665
  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
666
  wb.vault = new VaultSession(wb, conn)
607
667
  refuseInVault(wb)
@@ -612,13 +672,49 @@ export class Witbitz {
612
672
  * `wb.users.token(userId)` — a string, or a function (sync or async) returning a fresh one; null stops sending it.
613
673
  * 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
674
  * is REFUSED (code user_token_invalid / user_key_unavailable), never billed to you. */
615
- useUserToken(token) { this._userToken = token || null; return this }
675
+ _forgetVoice() { this._dictation?._resetPayer(); this._speech?._resetPayer() }
676
+ // the same PAYER keeps its voice keys (side sweep: sdk-speech-token-refresh-exhausts-key-allowance): a refreshed token string for the
677
+ // same tenant user is not a new user — each new key spends one of the user's hourly issuances. A function or another form: compared whole.
678
+ useUserToken(token) {
679
+ const was = this._userToken, next = token || null
680
+ const same = was === next || (typeof was === 'string' && typeof next === 'string' && tokenPayer(was) === tokenPayer(next))
681
+ if (!same) this._forgetVoice()
682
+ this._userToken = next; return this
683
+ }
616
684
 
617
685
  /** The signed-in session `{ email, idToken, exp, sign }`, or null. JSON-safe: persist it and pass it back as
618
686
  * `new Witbitz({ session })`. It carries a private signing key — keep it where you keep secrets. */
619
687
  get session() { return this._session }
620
688
  /** 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 }
689
+ useSession(session) {
690
+ const next = sessionOf(session)
691
+ const scope = s => { const c = tokenClaims(s?.idToken); return firstPartyAppOf(c) === 'vaulted' ? VAULTED_APP : tokenApp(c) }
692
+ const switched = !!this._session && (this._session.email !== next?.email || scope(this._session) !== scope(next))
693
+ if (this._session?.email !== next?.email || scope(this._session) !== scope(next)) {
694
+ // The generation marks handles of the account that is LEAVING, so nothing of it runs on into the next one. A first sign-in
695
+ // (nobody → an account) leaves no account: bumped all the same, every Space opened before signing in — the usual order on a
696
+ // page that opens by link — had its handle closed for embed, assistant memory, linkPrivateRoom and the offline export
697
+ // (second review, 2026-11-27).
698
+ if (this._session) this._archiveGeneration++
699
+ this._forgetVoice()
700
+ if (this._session) { this._forgetSiriAccount(); this.a2a?._resetAccount() }
701
+ }
702
+ const prev = this._session
703
+ this._session = next
704
+ if (switched) { try { this.invite?._accountChanged() } catch { /* */ } } // the previous account's invite key is not this one's (side sweep: sdk-invite-collection-keeps-previous-account)
705
+ // …and through a sign-out (useSession(null) / signOut(), then the next sign-in): the account that left is compared at the next one
706
+ try { if (prev && !next) this.invite?._signedOut(prev); else if (!prev && next) this.invite?._signedIn(next) } catch { /* */ }
707
+ if (next?.idToken) this._prefetchIdentity()
708
+ return this
709
+ }
710
+ _forgetSiriAccount() {
711
+ const backup = this.backup?._s
712
+ if (backup && this._session?.email) {
713
+ this._siriBackupOwners ||= new WeakMap()
714
+ if (!this._siriBackupOwners.has(backup)) this._siriBackupOwners.set(backup, this._session.email)
715
+ }
716
+ this._siri = siriStateOf(null)
717
+ }
622
718
  /** 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
719
  * 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
720
  * own Witbitz account is not reachable from your page. '' when nobody is signed in. */
@@ -635,7 +731,7 @@ export class Witbitz {
635
731
  async signIn({ email, code, ticket, room = '' } = {}) {
636
732
  const result = await this._signInResult({ email, code, ticket, room })
637
733
  if (!code) return result
638
- this._session = result
734
+ this.useSession(result)
639
735
  this._enrollInvite()
640
736
  return result
641
737
  }
@@ -699,7 +795,7 @@ export class Witbitz {
699
795
  }
700
796
  _emailPost() { return makeEmailPost(this._loginBase, { fetchImpl: (...a) => this._fetch(...a) }) }
701
797
  /** Forget the session on this client (the token simply expires server-side). */
702
- signOut() { this._archiveGeneration++; this._session = null; return this }
798
+ signOut() { this.a2a?._resetAccount(); this._forgetSiriAccount(); this._forgetVoice(); this._archiveGeneration++; try { if (this._session) this.invite?._signedOut(this._session) } catch { /* */ } this._session = null; return this }
703
799
 
704
800
  /** Press-to-talk: `const mic = wb.dictation(); await mic.start({ onPartial }); const text = await mic.stop()`. The
705
801
  * microphone streams straight from the page to Tinfoil's confidential realtime enclave — never through Witbitz — on a
@@ -895,8 +991,9 @@ export class Witbitz {
895
991
  * → { sdk, endpoint, features, limits, tiers: { standard, enclave }, models: { regular, confidential } | null } */
896
992
  async capabilities() {
897
993
  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 */ }
994
+ let enclave = this.vault ? null : false
995
+ if (this.vault?._c?.info?.tierQuery) enclave = await this.vault._c.enclaveAvailable().catch(() => null)
996
+ if (!this.vault) try { await this._encClaimDoc(); enclave = true } catch { /* no published claim: no confidential tier here */ }
900
997
  const ids = (l) => (Array.isArray(l) ? l.map((m) => m && m.id).filter(Boolean) : [])
901
998
  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
999
  }
@@ -933,11 +1030,12 @@ export class Witbitz {
933
1030
  const { saveOfflineReader } = await import('./sdkExports.js')
934
1031
  return saveOfflineReader()
935
1032
  }
936
- async exportOfflineArchive({ recoveryKeys = false, rooms } = {}) {
1033
+ async exportOfflineArchive({ recoveryKeys = false, rooms, destination = 'download' } = {}) {
1034
+ if (!['download', 'clipboard'].includes(destination) || (destination === 'clipboard' && recoveryKeys !== true)) throw sdkError('Clipboard export requires recoveryKeys', 'invalid_argument')
937
1035
  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))
1036
+ if (this.vault) return this.vault._c.account('backup', 'exportArchive', recoveryKeys === true, rooms?.map(sp => sp.room), ...(destination === 'clipboard' ? [destination] : []))
939
1037
  const { saveAccountArchive } = await import('./sdkExports.js')
940
- const session = this._session, backup = this.backup._s
1038
+ const session = this._session, generation = this._archiveGeneration, backup = this.backup._s
941
1039
  const selected = new Map((rooms === undefined ? this.backup.rooms : []).map(r => [r.room, r]))
942
1040
  const opened = [...(this._archiveHandles || [])].filter(sp => sp._archiveGeneration === this._archiveGeneration && sp._archiveEmail === (session?.email || '') && sp._archiveMaster === (backup?.master || null))
943
1041
  if (rooms?.some(sp => !opened.includes(sp))) throw sdkError('select Spaces opened for this account', 'invalid_argument')
@@ -945,19 +1043,20 @@ export class Witbitz {
945
1043
  if (!sp || sp._wb !== this || sp._stopped || !sp.shareLink) throw sdkError('select open Spaces from this SDK client', 'invalid_argument')
946
1044
  selected.set(sp.room, { room: sp.room, link: sp.shareLink, title: sp.title, held: sp })
947
1045
  }
948
- return saveAccountArchive([...selected.values()], async (r, keysOnly) => {
1046
+ return saveAccountArchive([...selected.values()], async (r, keysOnly, attachments) => {
949
1047
  const { room, mk } = r.held?._mk ? { room: r.room, mk: r.held._mk } : await this._openLink(r.link)
950
1048
  if (room !== r.room) throw sdkError('witbitz: a saved link opens another Space', 'wrong_room')
951
1049
  if (keysOnly) return { key: mk }
952
- const saved = await this._client.exportSealed(room, mk)
1050
+ const saved = await this._client.exportSealed(room, mk, { attachments }) // + the stored attachments, sealed (sdkExports.js)
953
1051
  if (saved?.status !== 200) throw sdkError('witbitz: this Space\u2019s history could not be read just now', 'unavailable')
954
- return { key: mk, ledger: saved.sealed, count: saved.count }
955
- }, recoveryKeys === true, () => this._session === session && this.backup._s === backup)
1052
+ return { key: mk, ledger: saved.sealed, count: saved.count, attachments: saved.attachments }
1053
+ }, recoveryKeys === true, () => this._archiveGeneration === generation && (this.backup._s?.master || null) === (backup?.master || null), destination)
956
1054
  }
957
- async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, safeMedia, lanes, owner } = {}) {
1055
+ async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, usernames, safeMedia, lanes, owner } = {}) {
958
1056
  // A TEMPORARY ROOM (docs/visitor-limits.md): a `tmp-` room the deployment wipes when it is idle — `true`: after about half
959
1057
  // an hour, as the app's temporary Spaces; `{ days }` (1–7): that many days after its last question (a help desk on a
960
1058
  // public page, kept while the visitor comes back). Refused rather than faked where it cannot be wiped.
1059
+ const temporaryScope = this.vault ? null : this.temporaryRooms._scope()
961
1060
  let lapseDays = 0
962
1061
  if (temporary !== undefined && temporary !== false) {
963
1062
  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 +1073,7 @@ export class Witbitz {
974
1073
  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
1074
  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
1075
  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
1076
+ 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
1077
  // A DIRECT CHAT (the Spaces app's, directChat.js): a verified Space with exactly you and one other person, you its owner,
979
1078
  // `direct: true` sealed in — the server refuses its rename and each side calls it by the other person (space.directPeer).
980
1079
  if (direct !== undefined) admission = directAdmission(direct, admission, this._session)
@@ -989,11 +1088,16 @@ export class Witbitz {
989
1088
  const enc = tierIsEnclave(tier)
990
1089
  const split = splitKeyChoice(key)
991
1090
  if (split && !this._appShareUrl && !this._clientOpts.tenant) throw Object.assign(new Error("witbitz: a split-key room needs your app-half function — new Witbitz({ appShare: '/api/appshare' }) — or, with the Witbitz-held key, your tenant — new Witbitz({ tenant: 't_…' })"), { code: 'tenant_required' })
1091
+ // The account this create began under: a restore or sign-in that lands while the room is being made must not have the new
1092
+ // room's link recorded in ITS backup (side sweep: sdk-pending-create-follows-account-switch).
1093
+ const began = { generation: this._archiveGeneration, email: this._session?.email || '', master: this.backup._s?.master || null }
992
1094
  await this._checkModel(model || agent.model)
993
1095
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
1096
+ applySkills(cfg, skills)
994
1097
  if (Array.isArray(clientTools)) cfg.clientTools = clientTools
995
1098
  if (agentReplies !== undefined) cfg.agentReplies = agentReplies
996
1099
  if (direct !== undefined) cfg.direct = true
1100
+ if (usernames === false && gate?.admission === 'email') cfg.usernames = false
997
1101
  if (safeMedia === true) cfg.safeMedia = true // sealed with the rest (spaceClient.js create); a room without it is sealed exactly as before
998
1102
  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
1103
  cfg.region = region || this._region // the room's home region is in its id (regions.js, docs/multi-region.md)
@@ -1018,12 +1122,32 @@ export class Witbitz {
1018
1122
  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
1123
  const sp = new Space(this._client, { room, mk, link: enc ? markEncLink(link) : link, viewer: this._viewer, wb: this, gated: !!gate, split })
1020
1124
  sp.safeMedia._learn(safeMedia === true, 0) // a new room's setting is what it was made with
1021
- 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
1125
+ if (sp.temporary) await this.temporaryRooms._remember(sp, temporaryScope, { days: lapseDays, title: temporary?.title })
1126
+ const sameAccount = this._archiveGeneration === began.generation && (this._session?.email || '') === began.email && (began.master === null || (this.backup._s?.master || null) === began.master) // a backup first enabled meanwhile is this account's (as _onEnabled)
1127
+ const made = String(room).startsWith('tmp-') || !sameAccount ? sp : this._backedUp(sp) // another account now: the handle is returned, nothing recorded; a temporary room is never in the account backup (it is wiped), as the app's
1022
1128
  if (direct !== undefined) await made.setReplyMode('ondemand').catch(() => {}) // the assistant is in the chat and answers when @mentioned, as in the app
1023
1129
  return made // an enclave room's link says so, or a fresh client cannot know (see ENC_MARK)
1024
1130
  }
1025
1131
 
1026
1132
  /** @private how a split room is created: through the builder's function when there is one (`via`), else here. */
1133
+ setAssistantMemory(spaces = []) {
1134
+ if (!Array.isArray(spaces) || spaces.length > LIMITS.links + 1) throw sdkError('witbitz: choose a bounded list of Spaces for assistant memory', 'invalid_argument')
1135
+ const group = new Map()
1136
+ for (const sp of spaces) {
1137
+ 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')
1138
+ group.set(sp.room, sp)
1139
+ }
1140
+ this._assistantMemory = { group, generation: this._archiveGeneration, vaultGeneration: this._memoryGeneration }
1141
+ }
1142
+
1143
+ _memoryFor(sp) {
1144
+ const m = this._assistantMemory
1145
+ 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 []
1146
+ return [...m.group.values()].filter(other => other.room !== sp.room && other._isEnclave() === sp._isEnclave() && !other._detachedLane && (this.vault || other._mk)).map(other => ({
1147
+ room: other.room, ...(this.vault ? {} : { mk: other._mk }), label: other.title || 'Space',
1148
+ }))
1149
+ }
1150
+
1027
1151
  _splitOpts() { return { split: true, ...(this._appShareUrl ? { via: (body) => this._appShareCall(body) } : {}) } }
1028
1152
 
1029
1153
  /** @private one call to the builder's app-half function → { status, ...answer }. Same-origin by design: the function
@@ -1053,8 +1177,11 @@ export class Witbitz {
1053
1177
  * have instead of replaying the whole ledger (see `resume` on the {@link Space} constructor). → a live {@link Space}. */
1054
1178
  async openSpace(link, { resume, tier } = {}) {
1055
1179
  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')
1180
+ const temporaryScope = this.temporaryRooms._scope()
1056
1181
  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 }))
1182
+ const sp = new Space(this._client, { room, mk, link: s, viewer: this._viewer, resume, wb: this, split })
1183
+ if (sp.temporary) await this.temporaryRooms._remember(sp, temporaryScope)
1184
+ return this._backedUp(sp)
1058
1185
  }
1059
1186
 
1060
1187
  /** Reopen a member's existing private lane — the link {@link Space#privateLane} returned (`lane.shareLink`) — on
@@ -1066,7 +1193,7 @@ export class Witbitz {
1066
1193
  async openLane(laneLink, { space, actions, resume, tier, mirror = false } = {}) {
1067
1194
  if (space && !this.vault) await assertNotKept(space)
1068
1195
  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)
1196
+ 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
1197
  if (this.vault) return this.vault._openLane(laneLink, { space, actions, resume, tier, mirror })
1071
1198
  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
1199
  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 +1212,10 @@ export class Witbitz {
1085
1212
  const laneIsEnclave = !!(this._enc && this._enc.rooms.has(room))
1086
1213
  const crossTier = laneIsEnclave !== sharedIsEnclave
1087
1214
  await refuseAttestedIntoPlain(this._client, space.room, space._mk, room, mk) // sync sweep 2026-11-15 #5: as the app's mirrorLoop.js
1215
+ const known = this.backup.rooms.find(r => r.room === room)
1216
+ if (space._wb !== this || known?.detachedLane || (known?.shared && known.shared !== space.room)) {
1217
+ throw sdkError('Open this private room with its recorded parent Space.', 'lane_space_mismatch')
1218
+ }
1088
1219
  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
1220
  }
1090
1221
 
@@ -1184,10 +1315,13 @@ export class Space {
1184
1315
  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
1316
  this.epoch = null // latest key rotation observed by this handle
1186
1317
  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
1318
+ this._a2aReceipts = Array.isArray(resume?.a2aReceipts) ? resume.a2aReceipts.filter(key => typeof key === 'string' && key.length < 512).slice(-512) : []
1319
+ if ((this._a2aResume?.length || this._a2aReceipts.length) && wb) (wb._agentHandles ||= new Set()).add(this)
1320
+ this._gated = !!gated || roomInviteFlags(link).gated // an email-gated room (see markGateLink) — no config fetch to know it
1188
1321
  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
1322
  this._liveOpts = live !== undefined ? live : (wb && wb._live) || null // room streams (null → polling only)
1190
1323
  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
1324
+ this._memoryOwner = wb?.vault ? wb._memoryGeneration : wb?._archiveGeneration
1191
1325
  this._wb = wb // the Witbitz client that opened this Space — its session and Siri state (null for a bare handle)
1192
1326
  /** This Space's connections: what ITS assistant may spend. `grant` needs a connection from `wb.connections`. */
1193
1327
  this.connections = new SpaceConnections(this)
@@ -1297,7 +1431,7 @@ export class Space {
1297
1431
  this._view.apply([m]) // a live poll's overlap with what you already had is never re-pushed or re-emitted
1298
1432
  }
1299
1433
  }
1300
- if (s.title && typeof s.title === 'object' && cleanTitle(s.title.title)) { const ts = Number(s.title.ts); this._title = { title: cleanTitle(s.title.title), manual: !!s.title.manual, by: String(s.title.by || ''), ts: Number.isFinite(ts) ? ts : -Infinity }; if (Number.isFinite(ts)) this._titleTs = Math.max(this._titleTs, ts) }
1434
+ if (s.title && typeof s.title === 'object' && cleanTitle(s.title.title)) { const ts = s.title.ts == null ? NaN : Number(s.title.ts); /* a name-doc title's -Infinity was saved as null — Number(null) is 0, which stopped the doc refresh (side sweep) */ this._title = { title: cleanTitle(s.title.title), manual: !!s.title.manual, by: String(s.title.by || ''), ts: Number.isFinite(ts) ? ts : -Infinity }; if (Number.isFinite(ts)) this._titleTs = Math.max(this._titleTs, ts) }
1301
1435
  // the SAFE COPIES the poll kept beside their photos (never messages): a resumed Space polls only what is new, so without them
1302
1436
  // every older photo had no copy (sync sweep backlog P7)
1303
1437
  if (Array.isArray(s.safeCopies) && this.safeMedia) for (const e of s.safeCopies.slice(0, 2000)) { if (e && typeof e === 'object' && e.kind === 'safe') this.safeMedia._note(e) }
@@ -1351,7 +1485,8 @@ export class Space {
1351
1485
  snapshot() {
1352
1486
  return {
1353
1487
  room: this.room,
1354
- ...(pendingOf(this._a2a ? this._a2a._pending : this._a2aResume).length ? { a2a: pendingOf(this._a2a ? this._a2a._pending : this._a2aResume) } : {}),
1488
+ ...((!this._wb?.a2a?._draftsSuspended && (this._a2a?._posted.size || this._a2aReceipts?.length)) ? { a2aReceipts: [...(this._a2a?._posted || this._a2aReceipts)].slice(-512) } : {}),
1489
+ ...(!this._wb?.a2a?._draftsSuspended && pendingOf(this._a2a ? this._a2a._pending : this._a2aResume).length ? { a2a: pendingOf(this._a2a ? this._a2a._pending : this._a2aResume) } : {}),
1355
1490
  count: this._count,
1356
1491
  etag: this._etag,
1357
1492
  messages: this.messages,
@@ -1398,6 +1533,7 @@ export class Space {
1398
1533
  _setTitle(t) {
1399
1534
  const same = this._title && this._title.title === t.title && this._title.manual === !!t.manual
1400
1535
  this._title = { title: t.title, manual: !!t.manual, by: t.by || '', ts: t.ts }
1536
+ if (!same && this.temporary && this._temporaryScope) this._wb.temporaryRooms._title(this)
1401
1537
  if (!same) this._emit('title', { title: t.title, manual: !!t.manual, by: t.by || '' })
1402
1538
  }
1403
1539
 
@@ -1433,7 +1569,7 @@ export class Space {
1433
1569
  get temporary() { return String(this.room || '').startsWith('tmp-') }
1434
1570
  /** True when this room gives every member a private assistant (`createSpace({ lanes: true })`, or a link that says so): the
1435
1571
  * 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 }
1572
+ get lanes() { return this._lanesSetting === undefined ? this._lanesHint || roomInviteFlags(this.shareLink).lanes : this._lanesSetting }
1437
1573
  /** Outside-agent door for a solo verified Space; group and open Spaces refuse on enable/collect. */
1438
1574
  get a2a() { return this._a2a || (this._a2a = this._wb && this._wb.vault ? new VaultLaneA2A(this, this._wb.vault._c) : new LaneA2A(this)) }
1439
1575
 
@@ -1442,12 +1578,15 @@ export class Space {
1442
1578
  on(event, cb, { replay = true } = {}) {
1443
1579
  // `{ replay: false }` on 'message': only what arrives AFTER the room's history was read (sdk-roadmap item 6) — for
1444
1580
  // notifications, analytics and side effects, which must not fire once per old message on every open.
1445
- const fn = event === 'message' && replay === false ? Object.assign((m) => { if (this._historyRead) cb(m) }, { _orig: cb }) : cb
1581
+ // EVERY registration is its own function (side sweep round 2): stored as the callback itself, an old unsubscribe called after its
1582
+ // registration was gone found a later on() of the same callback and silenced it. `_orig` is the callback (off(event, cb) matches it).
1583
+ const fn = Object.assign(event === 'message' && replay === false ? (m) => { if (this._historyRead) cb(m) } : (...a) => cb(...a), { _orig: cb })
1446
1584
  ;(this._subs[event] ||= []).push(fn)
1447
1585
  if (event === 'a2a') { const agents = this.a2a; Promise.resolve().then(() => agents._flushHeld()) }
1448
1586
  if ((event === 'proposal' || event === 'proposals') && !this._hostDriven && !this._pendingTimer && !this._stopped) this._pendingTimer = setInterval(() => this._pollPending(), 1500) // proposals arrive on their own channel (pending), not the ledger — polled once someone listens
1449
1587
  // Returns an UNSUBSCRIBE function. It still chains (`.on(…).on(…)`), because on() returned the space until 2026-10-05.
1450
- const off = () => { this.off(event, cb); return this }
1588
+ // it removes THIS registration only — off(event, cb) would also drop a later on() of the same callback (side sweep)
1589
+ const off = () => { const l = this._subs[event] || []; const i = l.indexOf(fn); if (i >= 0) this._subs[event] = l.filter((_, j) => j !== i); this._proposalsIdle(event); return this }
1451
1590
  return Object.assign(off, { on: (...a) => this.on(...a), off: (...a) => this.off(...a) })
1452
1591
  }
1453
1592
  /** Remove a listener added with on(). The last 'proposal' listener stops the proposals poll that on() started. */
@@ -1456,9 +1595,12 @@ export class Space {
1456
1595
  this._subs[event] = cb === undefined ? [] : l.filter((x) => x !== cb && x._orig !== cb) // no cb: every listener for the event
1457
1596
  // the proposals poll runs while anyone listens for 'proposal' OR 'proposals' — and on a Lane always (pass 5, V#14: the last
1458
1597
  // 'proposal' listener stopped a Lane's always-on poll, and the last 'proposals' listener never stopped a Space's)
1459
- if ((event === 'proposal' || event === 'proposals') && !this._keepsProposals && !(this._subs.proposal || []).length && !(this._subs.proposals || []).length && this._pendingTimer) { clearInterval(this._pendingTimer); this._pendingTimer = null }
1598
+ this._proposalsIdle(event)
1460
1599
  return this
1461
1600
  }
1601
+ _proposalsIdle(event) {
1602
+ if ((event === 'proposal' || event === 'proposals') && !this._keepsProposals && !(this._subs.proposal || []).length && !(this._subs.proposals || []).length && this._pendingTimer) { clearInterval(this._pendingTimer); this._pendingTimer = null }
1603
+ }
1462
1604
  _emit(event, arg) { if (this._stopped) return; for (const cb of (this._subs[event] || [])) { try { cb(arg) } catch { /* a listener throwing must not break the loop */ } } }
1463
1605
 
1464
1606
  /** Post a message from a member. The agent decides whether to answer and does so on its OWN turn — the reply (and
@@ -1471,7 +1613,61 @@ export class Space {
1471
1613
  * date, what is waiting, "answer in Hebrew" — and is NEVER stored, so it is not re-read from old messages every turn.
1472
1614
  * @param {string} text @param {object} [opts] { from, mode, instructions, images, files } — `from`: the display name to sign this
1473
1615
  * 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 } = {}) {
1616
+ linkPrivateRoom(target, { allowStandardDestination = false } = {}) {
1617
+ return this._privateRoomChange(target, false, allowStandardDestination === true)
1618
+ }
1619
+ unlinkPrivateRoom(target) { return this._privateRoomChange(target, true, false) }
1620
+ async _privateRoomChange(target, unlink, allowStandardDestination) {
1621
+ const wb = this._wb, room = target?.room
1622
+ const generation = () => wb?.vault ? wb._memoryGeneration : wb?._archiveGeneration
1623
+ const check = () => {
1624
+ if (!wb || target?._wb !== wb || target._memoryOwner !== generation() || this._memoryOwner !== generation())
1625
+ throw sdkError('Open both Spaces in the same account', 'account_changed')
1626
+ }
1627
+ check()
1628
+ if (!room || room === this.room || this.temporary || target.temporary || this._sharedRoom || this._detachedLane || wasLaneRoom(wb, this.room))
1629
+ throw sdkError('Choose a parent Space and a different durable private room.', 'invalid_argument')
1630
+ const method = unlink ? 'unlink' : 'link'
1631
+ if (wb.vault) return wb.vault._c.roomAccount(this.room, 'privateRoom', method, room, { allowStandardDestination })
1632
+ if (!wb.account.enabled) throw sdkError('Enable account backup to sync this room link.', 'backup_required')
1633
+ const sync = async () => {
1634
+ const r = await wb.account.sync()
1635
+ check()
1636
+ if (!r?.ok) throw sdkError('The room link could not be synced. Try again.', 'index_unavailable')
1637
+ }
1638
+ await sync()
1639
+ const record = wb.backup.rooms.find(r => r.room === room)
1640
+ if (!record || !wb.backup.rooms.some(r => r.room === this.room)) throw sdkError('Add both Spaces to this account first.', 'not_in_account')
1641
+ if (record.shared && record.shared !== this.room) throw sdkError('This private room is linked to a different Space.', 'already_linked')
1642
+ if (unlink) {
1643
+ if (!record.shared && !record.detachedLane) throw sdkError('This room is not linked to this Space.', 'not_linked')
1644
+ wb.backup._detachLane(room, this.room)
1645
+ for (const lane of wb._openLanes || []) if (lane.room === room && lane._sharedRoom === this.room) lane._detachShared()
1646
+ } else {
1647
+ 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')
1648
+ const cfg = await this._client.getConfig(this.room, this._mk, { plainMark: true })
1649
+ if (!cfg || gatedStub(cfg)) throw sdkError('Could not read the parent Space settings.', 'lane_wait')
1650
+ if (cfg.lanes === false) throw sdkError('Private assistants are disabled in this Space.', 'lanes_disabled')
1651
+ await assertNotKept(this); await assertNotKept(target)
1652
+ const confidential = sp => wb._enc.rooms.has(sp.room) || ENC_MARK.test(sp.shareLink || '')
1653
+ if (confidential(this) && !confidential(target) && !allowStandardDestination) throw sdkError('The private room uses the standard tier. Confirm before linking it.', 'tier_mismatch')
1654
+ await refuseAttestedIntoPlain(this._client, this.room, this._mk, room, target._mk)
1655
+ check()
1656
+ wb.backup._attachLane(room, this.room)
1657
+ }
1658
+ await sync()
1659
+ const accepted = wb.backup.rooms.find(r => r.room === room)
1660
+ if (!accepted || (unlink ? accepted.shared === this.room : accepted.detachedLane || accepted.shared !== this.room))
1661
+ throw sdkError('A different room link won the account sync. Reopen the room and try again.', 'association_changed')
1662
+ return { room, parent: this.room, linked: !unlink }
1663
+ }
1664
+ get embed() { return (this._embed ||= roomEmbed(this, () => wasLaneRoom(this._wb, this.room))).api }
1665
+ async invokeSkill(name, args = {}) {
1666
+ 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')
1667
+ return this.send('', { _skill: { name: name.trim(), args } })
1668
+ }
1669
+
1670
+ async send(text, { from = 'You', mode, instructions, dictation, images, files, stopKey, showPrompt, replyTo, tools, _onAttempt, _aborted, _skill } = {}) {
1475
1671
  { const f = arguments[1] && arguments[1].from; if (typeof f === 'string' && !arguments[1]._peerPost) this._who(f) } // remember the name this member uses
1476
1672
  // PER-QUESTION TOOLS on a plain room (docs/visitor-limits.md: a help desk's "search the guide", "which screen am I on"):
1477
1673
  // the same action shape a Lane takes, offered for THIS question only; an `await` action is answered by this page while
@@ -1484,7 +1680,7 @@ export class Space {
1484
1680
  if (extra.defs.length) toolOpts = { clientTools: extra.defs, clientGuidance: extra.guidance }
1485
1681
  }
1486
1682
  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
1683
+ const msg = withMedia({ from, ...(_skill ? { mcp: _skill } : { text: String(text) }), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files, { enclave: encRoomOf(this) }) // `images` ≤ 4, `files` ≤ 2 — see LIMITS
1488
1684
  const rt = replyRef(replyTo); if (rt) msg.replyTo = rt // a reply quotes the message it answers, as the app's do
1489
1685
  await this.safeMedia._prepare(msg) // a Safe media room: its photos' and PDFs' safe copies start now, and go beside it once stored
1490
1686
  const opts = { ...(await this._turnOpts(mode)), ...toolOpts, ...perTurn(instructions), ...stopOpt(stopKey), ...promptOpt(showPrompt) }
@@ -1529,6 +1725,8 @@ export class Space {
1529
1725
  try { r = await send() } catch { r = null }
1530
1726
  if (!r || !r.status) { await new Promise((ok) => setTimeout(ok, 400)); try { r = await send() } catch (e) { r = { status: 0, error: (e && e.code) || 'unavailable' } } }
1531
1727
  this._kick()
1728
+ // `capped`: the server stored the map WITHOUT this reaction (a bound: 50 names on one emoji, 12 emoji on one message)
1729
+ if (r && r.status === 200 && r.capped === true) return { ok: false, error: 'reaction_limit', reactions: r.reactions || {} }
1532
1730
  return r && r.status === 200 ? { ok: true, reactions: r.reactions || {} } : { ok: false, error: String((r && r.error) || (r && r.status === 404 ? 'not_found' : 'failed')) }
1533
1731
  }
1534
1732
 
@@ -1577,7 +1775,7 @@ export class Space {
1577
1775
  // from the server is { status, error, message } with NO ok, while a success usually carries the server's own ok:true —
1578
1776
  // so `r.ok !== false` read every refusal as a success. Now ok is always a boolean, read as turnVerdict reads the turn:
1579
1777
  // 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
1778
+ 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
1779
  const run = doTurn
1582
1780
  // A transport failure (no network, an enclave that cannot be reached or verified) is an ANSWER too: `send()` does not
1583
1781
  // throw (sdk.md) — it resolves { ok: false, status: 0, error } (sync sweep, 2026-10-10). Bad arguments still throw
@@ -1586,11 +1784,15 @@ export class Space {
1586
1784
  if (onAttempt) { try { onAttempt() } catch { /* */ } } // space.turn() marks where ITS reply can start
1587
1785
  try { return await run() } catch (e) { return { status: 0, error: String((e && e.code) || 'unavailable'), detail: String((e && e.message) || e).replace(/^witbitz: /, '').slice(0, 200) } }
1588
1786
  }
1787
+ // A turn that settled (aborted, timed out) while send() was still reading the room's settings posts nothing — the server
1788
+ // disregards a stop older than the turn, so a late first send ran in full (side sweep 2026-11-28)
1789
+ if (aborted && aborted()) return { status: 0, ok: false, error: 'aborted', detail: 'aborted before it was sent — the message was not stored' }
1589
1790
  let r = await doTurn()
1590
1791
  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' }
1792
+ 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
1793
  this._kick()
1593
- await new Promise((res) => setTimeout(res, this._queueRetryMs ?? QUEUE_RETRY_MS))
1794
+ await new Promise((res) => setTimeout(res, Math.min(this._queueRetryMs ?? QUEUE_RETRY_MS, deadline ? deadline - Date.now() : Infinity)))
1795
+ if (deadline && Date.now() >= deadline) return { ...r, ok: false, error: 'busy' }
1594
1796
  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
1797
  if (aborted && aborted()) return { ...r, ok: false, error: 'aborted', detail: 'aborted while the assistant was busy — the message was not stored' }
1596
1798
  r = await doTurn()
@@ -1613,13 +1815,39 @@ export class Space {
1613
1815
  if (!REPLY_MODES.includes(mode)) throw sdkError(`unknown reply mode ${JSON.stringify(mode)} — one of ${REPLY_MODES.join(', ')}`, 'invalid_argument')
1614
1816
  // A PRIVATE LANE ALWAYS REPLIES (the server: spaceService respondMode — a bridged lane is 'always'; the app hides the chip there):
1615
1817
  // 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')
1818
+ 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')
1819
+ this._modeGen = (this._modeGen || 0) + 1 // a settings read already on the wire does not put the old mode back
1617
1820
  const r = await this._client.state(this.room, this._mk, 'agentmode', { mode }, REPLY_MODE_LABEL[mode])
1618
1821
  if (!r || r.status !== 200) throw refused('setReplyMode', r) // every error carries a code (sync sweep, 2026-10-10)
1619
1822
  this._mode = mode
1620
1823
  return { mode }
1621
1824
  }
1622
1825
 
1826
+ /** THE ROOM'S MODEL PICK — the same setting as the Witbitz app's model chip, for every member: sealed to the room in its
1827
+ * `model` doc, and over the model `configure()` / `createSpace` set, on every turn whoever sends it. `id` is a model of
1828
+ * `wb.models()` for this Space's tier (else `unknown_model`, nothing written). `clearModel()` goes back to the room's own
1829
+ * model, as the chip's Default does (side sweep: sdk-missing-room-model-override-control). */
1830
+ async setModel(id) {
1831
+ if (typeof id !== 'string' || !id) throw sdkError('witbitz: setModel needs a model id from wb.models()', 'invalid_argument')
1832
+ if (!this._wb || typeof this._wb.models !== 'function') throw sdkError('witbitz: setModel needs the Witbitz instance that opened this Space', 'unavailable')
1833
+ const rows = await this._wb.models({ tier: this._isEnclave() ? 'enclave' : 'standard' })
1834
+ const row = (rows || []).find((m) => m && m.id === id)
1835
+ if (!row) throw sdkError(`witbitz: ${JSON.stringify(id)} is not a model offered for this Space — see wb.models()`, 'unknown_model')
1836
+ const pick = { catalog: String(row.id), wire: String(row.wire || ''), label: String(row.label || '') }
1837
+ this._modelGen = (this._modelGen || 0) + 1
1838
+ const r = await this._client.state(this.room, this._mk, 'model', modelDocOf(pick), pick.label || pick.catalog)
1839
+ if (!r || r.status !== 200) throw refused('setModel', r)
1840
+ this._modelPick = pick
1841
+ return { model: pick.catalog }
1842
+ }
1843
+ async clearModel() {
1844
+ this._modelGen = (this._modelGen || 0) + 1
1845
+ const r = await this._client.state(this.room, this._mk, 'model', modelDocOf(null), 'Default model')
1846
+ if (!r || r.status !== 200) throw refused('clearModel', r)
1847
+ this._modelPick = null
1848
+ return { model: null }
1849
+ }
1850
+
1623
1851
  /** The room's reply mode as it stands now: the stored one, else the room's default — the server's rule (roomSettings.js
1624
1852
  * roomDefaultReplyMode, sync sweep 2026-11-13 #1), counted with the room's sign-in record as the server counts. */
1625
1853
  /** WHICH TOOLS RUN ON THEIR OWN HERE (docs/approvals-model.md; the same setting as the Witbitz app's ⋯ → Tools). Each tool of the
@@ -1658,8 +1886,8 @@ export class Space {
1658
1886
  }
1659
1887
 
1660
1888
  async replyMode() {
1661
- if (this._sharedRoom) return 'always' // a private lane: the server always replies there
1662
- await this._modeReady
1889
+ if (this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)) return 'always' // a private lane: the server always replies there
1890
+ await this._freshSettings() // re-read once it is old, as a turn does (side sweep 2026-11-28: an idle handle kept another member's old choice)
1663
1891
  if (this._mode) return this._mode
1664
1892
  let cfg = null
1665
1893
  try { cfg = typeof this._client.getConfig === 'function' ? await this._client.getConfig(this.room, this._mk, { plainMark: true }) : null } catch { cfg = null }
@@ -1685,6 +1913,8 @@ export class Space {
1685
1913
  // every turn there carries it). The proof binds the member's signing key and the room's fresh challenge; a member with no
1686
1914
  // 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
1915
  async _provenTurn(msg, opts) {
1916
+ const live = this._embed?.context()
1917
+ if (live) opts = { ...opts, context: [opts.context, live].filter(Boolean).join('\n\n').slice(0, 4000) }
1688
1918
  const att = this._wb && this._wb._attest
1689
1919
  const send = async () => {
1690
1920
  if (!this._needsProof || !att) return this._client.turn(this.room, this._mk, msg, this._identity(), opts)
@@ -1725,9 +1955,11 @@ export class Space {
1725
1955
  // cannot be read keeps the last value; a room with no docs sends no mode (⇒ 'auto') and no model (⇒ its own).
1726
1956
  async _readSettings() {
1727
1957
  try {
1958
+ const gen = this._modelGen || 0 // a setModel / clearModel made while this read was on the wire stands
1959
+ const modeGen = this._modeGen || 0 // …and a setReplyMode (side sweep cycle 166, sdk-pending-settings-read-reverts-confirmed-reply-mode)
1728
1960
  const [a, b] = await Promise.all([this._client.state(this.room, this._mk, 'agentmode').catch(() => null), this._client.state(this.room, this._mk, 'model').catch(() => null)])
1729
- const m = modeFromDoc(a); if (m) this._mode = m
1730
- const p = modelPickFromDoc(b); if (p !== undefined) this._modelPick = p
1961
+ const m = modeFromDoc(a); if (m && (this._modeGen || 0) === modeGen) this._mode = m
1962
+ const p = modelPickFromDoc(b); if (p !== undefined && (this._modelGen || 0) === gen) this._modelPick = p
1731
1963
  } catch { /* a convenience; never let it break sending */ }
1732
1964
  this._settingsAt = Date.now()
1733
1965
  }
@@ -1740,7 +1972,8 @@ export class Space {
1740
1972
  await this._freshSettings()
1741
1973
  const m = mode !== undefined ? mode : this._mode
1742
1974
  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()) }
1975
+ const memory = extra.links ? [] : this._wb?._memoryFor?.(this) || []
1976
+ return { ...(memory.length ? { links: memory } : {}), ...extra, ...(m ? { mode: m } : {}), ...(model ? { model } : {}), ...(await this._receipt()) }
1744
1977
  }
1745
1978
  /** @private THE ACCOUNT'S USAGE RECEIPT for a turn here (docs/usage-receipts.md; the owner, 2026-10-23: a builder's app
1746
1979
  * records the account's usage too): the address the server seals this turn's cost to, from the account's usage key
@@ -1770,8 +2003,8 @@ export class Space {
1770
2003
  async exportFile() {
1771
2004
  if (this._wb?.vault) return this._wb.vault._c.roomAccount(this.room, 'portable', 'export')
1772
2005
  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)
2006
+ const generation = this._wb?._archiveGeneration
2007
+ return saveRoomExport(this, this._wb?._enc?.rooms.has(this.room) || ENC_MARK.test(this.shareLink || '') ? 'enclave' : 'standard', () => this._wb?._archiveGeneration === generation)
1775
2008
  }
1776
2009
  async sealedProof() {
1777
2010
  if (!(this._client && this._client.vault)) this._needKey('sealedProof') // a vault reads the stored boxes for the page (ciphertext only)
@@ -1850,11 +2083,14 @@ export class Space {
1850
2083
  // `at` than its tombstone — it came back on every device. Closed, the backup only follows a room it still holds.
1851
2084
  const keep = !this._stopped || (() => { try { return this._wb.backup.rooms.some((r) => r.room === this.room) } catch { return false } })()
1852
2085
  try { if (keep && this._wb && this._wb.backup) this._wb.backup.add(this) } catch { /* the backup must never cost the room */ }
2086
+ // a temporary room is never in the backup: its own list keeps the link temporaryRooms.open() reopens with (side sweep)
2087
+ // …closed too: a rotation that completes after close() still moves the list's link — only of a room still ON the list (round 2)
2088
+ try { if (this.temporary && this._temporaryScope) this._wb.temporaryRooms._remember(this, this._temporaryScope, keep ? {} : { onlyIfListed: true }).catch(() => {}) } catch { /* */ }
1853
2089
  this._emit('rekeyed', { room: this.room, epoch: this.epoch, link: this.shareLink })
1854
2090
  }
1855
2091
 
1856
2092
  async _reattest() {
1857
- if (!this._isEnclave()) return false
2093
+ if (this._client?.keyless || this._client?.vault || !this._isEnclave()) return false
1858
2094
  if (this._reattestP) return this._reattestP
1859
2095
  if (Date.now() - (this._reattestAt || 0) < 10000) return !!this._reattestLast
1860
2096
  this._reattestAt = Date.now()
@@ -1872,6 +2108,7 @@ export class Space {
1872
2108
  /** @private announce this device in the room's guest book under its signing key, once per open: the email gate then
1873
2109
  * vouches for the address behind it (the server's `seen`), which is how a fork finds the remaining members' devices. */
1874
2110
  async _announce() {
2111
+ if (!this._gated && !this._client?.vault) return
1875
2112
  this._announced = true
1876
2113
  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
2114
  const sess = this._wb && this._wb._session
@@ -1891,7 +2128,10 @@ export class Space {
1891
2128
  const { roster, changed } = ensureSelf(r.state, self)
1892
2129
  if (!changed && !unseenIn(r.seen, self.id) && !entriesMissing(r.seen, self.id, this.room)) return // entries: one more announce per page, never retried
1893
2130
  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)
2131
+ // 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.
2132
+ // 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
2133
+ // 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.
2134
+ const written = await this._client.state(this.room, this._mk, ROSTER_DOC, Array.isArray(r.state) ? roster : { people: roster }, '', 'member', r.v || 0)
1895
2135
  if (written?.status === 409) continue
1896
2136
  if (written?.status !== 200) return
1897
2137
  announcedIn(this.room, self.id)
@@ -1988,7 +2228,7 @@ export class Space {
1988
2228
  const claims = (Array.isArray(book.state) ? book.state : book.state?.people || []).some(row => row?.verified)
1989
2229
  const history = claims || cfg.admission === 'email' ? await this._roomHistory() : { entries: [] }
1990
2230
  const entries = history.entries || []
1991
- const attested = new Set(deriveRoster(entries, null).map(p => jkey(p.spk)))
2231
+ const attested = verifiedSigningIds(entries)
1992
2232
  const posters = verifiedPosters(entries, book.seen || {})
1993
2233
  const rows = listRoster(book.state, { attested: row => !!seen[row.id] || attested.has(row.id) })
1994
2234
  if (cfg.admission !== 'email') return {
@@ -2015,7 +2255,7 @@ export class Space {
2015
2255
  }
2016
2256
  const cfg = await this._gateConfig({ plainMark: true })
2017
2257
  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 }
2258
+ if (cfg.admission !== 'email') return { gated: false, ...(cfg.lane === true || cfg.bridge ? { lane: true } : {}), ...lanesOn }
2019
2259
  const a = cfg.allow || {}
2020
2260
  const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [])
2021
2261
  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 +2301,7 @@ export class Space {
2061
2301
  * hidden (hashed) one, or the address's domain. An open room admits everyone. ⚑ A member admitted by @username alone
2062
2302
  * cannot be checked here — that match needs the server's key — so it reads `false` for them. */
2063
2303
  async admits(email) {
2064
- const e = String(email || '').normalize('NFKC').trim().toLowerCase()
2304
+ const e = String(email || '').trim().toLowerCase()
2065
2305
  const at = e.indexOf('@')
2066
2306
  if (at < 1 || at === e.length - 1) throw sdkError(`witbitz: "${email}" is not an email address`, 'invalid_argument')
2067
2307
  const cfg = await this._gateConfig({ plainMark: true })
@@ -2121,14 +2361,33 @@ export class Space {
2121
2361
  isMine(message) {
2122
2362
  const m = message
2123
2363
  if (!m || m.verified !== true) return false
2364
+ const id = (k) => (k && k.kty && k.crv && k.x != null && k.y != null ? `${k.kty}:${k.crv}:${k.x}:${k.y}` : null) // = agentIdentity.keyIdOf
2365
+ const mine = this._ownKeyId()
2366
+ return !!mine && id(m.vspk || m.spk) === mine
2367
+ }
2368
+
2369
+ /** This session's signing key id (`kty:crv:x:y`, agentIdentity.keyIdOf), or null. */
2370
+ _ownKeyId() {
2124
2371
  const id = (k) => (k && k.kty && k.crv && k.x != null && k.y != null ? `${k.kty}:${k.crv}:${k.x}:${k.y}` : null) // = agentIdentity.keyIdOf
2125
2372
  // IN A VAULT the session is the vault's: it hands the page its key's PUBLIC id (welcome, whoami, its events) — this read
2126
2373
  // false there for every message (sweep 11-07 #9)
2127
2374
  const v = this._wb && this._wb.vault
2128
- let mine = null
2129
- if (v) { const i = v.info || {}; mine = i.signedIn !== false && typeof i.keyId === 'string' && i.keyId ? i.keyId : null }
2130
- else { const sess = this._wb && this._wb._session; mine = sess && sess.sign ? id(sess.sign.pub) : null }
2131
- return !!mine && id(m.vspk || m.spk) === mine
2375
+ if (v) { const i = v.info || {}; return i.signedIn !== false && typeof i.keyId === 'string' && i.keyId ? i.keyId : null }
2376
+ const sess = this._wb && this._wb._session
2377
+ return sess && sess.sign ? id(sess.sign.pub) : null
2378
+ }
2379
+
2380
+ /** WHO REACTED, as the Spaces app shows it → `{ [emoji]: { count, names, mine } }`. In a verified room each signed-in member
2381
+ * is one reactor and `mine` is decided by THIS session's key, not by a name (two members may share a name; a renamed member
2382
+ * counts once — `reactBy` on the message). In an open room names are all there is: `mine` = your `from` name. `from`: the
2383
+ * name to match where no key holds a reaction (default: the name this Space last sent as). Side sweep:
2384
+ * reaction-ownership-by-display-name. */
2385
+ reactionsOf(message, { from } = {}) {
2386
+ const me = typeof from === 'string' && from.trim() ? from.trim() : (this._memberName || '')
2387
+ const myKey = this._ownKeyId()
2388
+ const out = {}
2389
+ for (const [emoji, rows] of allReactors(message)) out[emoji] = { count: rows.length, names: rows.map((r) => r.name), mine: rows.some((r) => rowIsMine(r, me, myKey)) }
2390
+ return out
2132
2391
  }
2133
2392
 
2134
2393
  /** WHO WROTE `message`, as Block knows a person (the Spaces app's blocks.js; docs/report-and-block.md §4) → `{ email?, user?,
@@ -2170,15 +2429,22 @@ export class Space {
2170
2429
  const r = await this._client.importChat(this.room, this._mk, url.trim())
2171
2430
  if (!r || r.status !== 200) throw refused('importChat', r)
2172
2431
  this._kick()
2173
- return { imported: r.imported, title: r.title, entries: r.entries }
2432
+ return { imported: r.imported, title: r.title, entries: r.entries, ...(r.shortened > 0 ? { shortened: r.shortened } : {}) } // shortened: messages cut to fit (side sweep: whatsapp-long-message-silently-truncated)
2174
2433
  }
2175
2434
 
2176
2435
  async importWhatsApp(text) {
2177
2436
  if (typeof text !== 'string' || !text.trim()) throw sdkError('witbitz: importWhatsApp() needs the exported chat text', 'invalid_argument')
2178
- const r = await this._client.importWhatsApp(this.room, this._mk, text)
2437
+ // the export's times are this device's local ones: its time zone (and date order, for a chat whose dates read either way) let the
2438
+ // server keep each message's own time, as the app's import does (side sweep: sdk-whatsapp-import-restamps-message-times)
2439
+ let locale = ''; try { locale = (globalThis.navigator && navigator.language) || Intl.DateTimeFormat().resolvedOptions().locale || '' } catch { /* */ }
2440
+ // …and the time zone's NAME, so a summer message imported in winter is read at its own date's offset, not today's (side sweep:
2441
+ // sdk-whatsapp-import-uses-current-offset-for-historical-dates); a server that does not know the name uses `tz`
2442
+ let zone = ''; try { zone = Intl.DateTimeFormat().resolvedOptions().timeZone || '' } catch { /* */ }
2443
+ const hints = { tz: new Date().getTimezoneOffset(), order: /^en-US\b|^en$/i.test(locale) ? 'mdy' : 'dmy', ...(zone ? { zone } : {}) }
2444
+ const r = await this._client.importWhatsApp(this.room, this._mk, text, undefined, hints)
2179
2445
  if (!r || r.status !== 200) throw refused('importWhatsApp', r)
2180
2446
  this._kick()
2181
- return { imported: r.imported, title: r.title, entries: r.entries }
2447
+ return { imported: r.imported, title: r.title, entries: r.entries, ...(r.shortened > 0 ? { shortened: r.shortened } : {}) } // shortened: messages cut to 8,000 characters
2182
2448
  }
2183
2449
 
2184
2450
  async attachment(att) {
@@ -2188,7 +2454,26 @@ export class Space {
2188
2454
  if (!refs.length) throw sdkError('witbitz: that attachment has neither bytes nor a reference', 'invalid_argument')
2189
2455
  const got = await Promise.all(refs.map((ref) => this._client.blob(this.room, this._mk, ref)))
2190
2456
  if (got.some((r) => !r || r.status !== 200 || typeof r.b64 !== 'string')) { const err = new Error('witbitz: the attachment could not be fetched or opened'); err.code = 'attachment_unavailable'; throw err }
2191
- return { b64: got.map((r) => r.b64).join(''), mime: att.mime || got[0].mime || 'application/octet-stream', ...(att.name ? { name: att.name } : {}) }
2457
+ const b64 = got.map((r) => r.b64).join(''), mime = att.mime || got[0].mime || 'application/octet-stream'
2458
+ this._keepOpened(refs, b64, mime)
2459
+ return { b64, mime, ...(att.name ? { name: att.name } : {}) }
2460
+ }
2461
+ /** @private an attachment opened once is kept on its message, so snapshot() carries it and a Space resumed from that snapshot opens
2462
+ * it with no fetch — as an inline one (side sweep: sdk-offline-previously-opened-attachments). Only up to ATTACH_KEEP_B64 a file:
2463
+ * a snapshot an app stores must not fill its storage; a larger one is fetched again, as before. */
2464
+ _keepOpened(refs, b64, mime) {
2465
+ if (b64.length > ATTACH_KEEP_B64) return
2466
+ const key = JSON.stringify(refs)
2467
+ for (const m of this.messages || []) {
2468
+ for (const list of [m && m.images, m && m.files]) {
2469
+ if (!Array.isArray(list)) continue
2470
+ for (const e of list) {
2471
+ if (!e || typeof e !== 'object' || e.b64) continue
2472
+ const own = Array.isArray(e.parts) && e.parts.length ? e.parts : (e.ref ? [e.ref] : [])
2473
+ if (own.length && JSON.stringify(own) === key) { e.b64 = b64; if (!e.mime) e.mime = mime }
2474
+ }
2475
+ }
2476
+ }
2192
2477
  }
2193
2478
 
2194
2479
  /** Attach a PRIVATE assistant lane to this shared Space, for the current member. The lane is the member's OWN room:
@@ -2201,7 +2486,7 @@ export class Space {
2201
2486
  // 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
2487
  // which nothing in the app makes and nothing reads back
2203
2488
  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)
2489
+ 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
2490
  await assertNotKept(this)
2206
2491
  this._needKey('privateLane')
2207
2492
  let gate = normAdmission(admission) // a lane can be gated too — it is the member's OWN room
@@ -2258,7 +2543,8 @@ export class Space {
2258
2543
  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
2544
  const inh = laneInherits(sharedCfg, { email: me, attested })
2260
2545
  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 }
2546
+ if (tools === undefined && immediateTools === undefined && agent?.tools === undefined) { tools = inh.config.tools; immediateTools = inh.config.immediateTools }
2547
+ if (platformTools === undefined) platformTools = inh.config.platformTools
2262
2548
  if (sharedCfg && sharedCfg.admission === 'email') {
2263
2549
  if (admission === undefined) {
2264
2550
  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 +2564,7 @@ export class Space {
2278
2564
  // 2026-10-24 — it sent the standard room as a bridge the enclave could not find, and its assistant never saw the room).
2279
2565
  const crossTier = enc !== sharedIsEnclave
2280
2566
  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 })
2567
+ lane._laneOrigin = 'minted'
2281
2568
  return wb ? wb._backedUp(lane) : lane
2282
2569
  }
2283
2570
 
@@ -2292,14 +2579,22 @@ export class Space {
2292
2579
  }
2293
2580
  if (wb) await wb._checkModel(model || agent.model)
2294
2581
  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 */ }
2582
+ const inheritCustom = tools === undefined && immediateTools === undefined && agent?.tools === undefined
2583
+ const inheritPlatform = platformTools === undefined
2584
+ if (inheritCustom || inheritPlatform) {
2585
+ try {
2586
+ const inherited = inheritToolsFrom(await this._client.getConfig(this.room, null))
2587
+ if (inheritCustom) { tools = inherited.tools; immediateTools = inherited.immediateTools }
2588
+ if (inheritPlatform) platformTools = inherited.platformTools
2589
+ } catch { /* the vault reads the settings before creating the lane */ }
2297
2590
  }
2298
2591
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: LANE_AGENT_NAME, persona: framingOpt(framing) ? '' : DEFAULT_ASSIST })
2299
2592
  cfg.region = roomRegion(this.room)
2300
2593
  // an `admission` that opens the lane reaches the vault as `{ open }` (an open room's config names no admission, so the vault
2301
2594
  // 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)
2595
+ const options = { ...(admission !== undefined && !(gate && gate.admission === 'email') ? { open: true } : {}), inheritCustom, inheritPlatform }
2596
+ const { room } = await wb.vault._c.createLane(this.room, cfg, options)
2597
+ if (wb._enc.rooms.has(this.room)) wb._enc.rooms.set(room, true)
2303
2598
  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
2599
  }
2305
2600
 
@@ -2332,7 +2627,7 @@ export class Space {
2332
2627
  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
2628
  // 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
2629
  // 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 }
2630
+ 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
2631
  if ('name' in agent) patch.agentName = agent.name
2337
2632
  if ('instructions' in agent) patch.persona = agent.instructions
2338
2633
  if ('model' in agent) { if (this._wb) await this._wb._checkModel(agent.model); patch.model = agent.model }
@@ -2356,11 +2651,11 @@ export class Space {
2356
2651
  async plan(change = {}) {
2357
2652
  let cfg = null, gatedUnread = false
2358
2653
  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)
2654
+ 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
2655
  const sess = this._wb && this._wb._session
2361
2656
  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
2657
  : 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) })
2658
+ 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
2659
  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
2660
  return out
2366
2661
  }
@@ -2378,7 +2673,7 @@ export class Space {
2378
2673
  _runExtra() { return {} } // a Lane adds its bridge fields — a lane's run sees its shared room, as its turns do
2379
2674
 
2380
2675
  /** 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' })) }
2676
+ 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
2677
  _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
2678
 
2384
2679
  async _decide(id, approve, { recordResult, from = 'You' } = {}) {
@@ -2397,7 +2692,9 @@ export class Space {
2397
2692
  if (!r || r.status !== 200 || !r.decided) throw refused(approve ? 'approve' : 'deny', r)
2398
2693
  let result
2399
2694
  if (isClientWrite && r && r.deviceExec) {
2400
- try { result = await this._writes[act.type](act) } catch (e) { result = { error: String((e && e.message) || e) } }
2695
+ // the server's run said no (it expired between the approval and the run): nothing is applied here (side sweep: device-approval-applies-after-execution-expiry)
2696
+ if (r.execution && r.execution.ok === false) result = { error: String(r.execution.error || 'not_run') }
2697
+ else try { result = await this._writes[act.type](act) } catch (e) { result = { error: String((e && e.message) || e) } }
2401
2698
  } else if (approve && r && r.execution) {
2402
2699
  result = r.execution // a server-executed proposal (an approved crossing, a data write)
2403
2700
  }
@@ -2418,8 +2715,9 @@ export class Space {
2418
2715
  }
2419
2716
  /** @private the continuation turn after an approved call ran (see _decide) — the same proofs and options as a send. */
2420
2717
  async _continueAfter(id, from) {
2718
+ const deadline = Date.now() + CONTINUATION_WINDOW_MS
2421
2719
  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))
2720
+ const r = await this._turnHeld(() => this._provenTurn({ from: String(from || 'You'), text: '', cont: id }, opts), undefined, undefined, false, deadline)
2423
2721
  this._kick()
2424
2722
  return r
2425
2723
  }
@@ -2479,19 +2777,30 @@ export class Space {
2479
2777
  if (this._inflight) { this._pollAgain = true; return }
2480
2778
  this._inflight = true
2481
2779
  let read = false // this poll was a 200: only then may `_more` ask for the next page at once
2780
+ const heldBefore = this._count // what this handle held before the poll (mayHideEdit: the first read refreshes nothing)
2482
2781
  try {
2483
- const r = await this._client.pollSealed(this.room, this._mk, this._etag, this._count)
2782
+ const sentEdit = this._editTag || '0' // the edit record this handle last saw: the answer names the entries changed in place since (agent/ledgerEdits.mjs)
2783
+ const r = await this._client.pollSealed(this.room, this._mk, this._etag, this._count, { sinceEdit: sentEdit })
2484
2784
  if (this._stopped) return // V#7: answered after close(): nothing of it is applied, announced, or run (a device call included)
2485
2785
  if (!this._sharedRoom && r && r.status === 200 && Date.now() - (this._lanesCheckedAt || 0) > 30000 && typeof this._client.getConfig === 'function') {
2486
2786
  this._lanesCheckedAt = Date.now()
2487
- try {
2488
- const cfg = await this._client.getConfig(this.room, this._mk, { plainMark: true })
2489
- if (this._stopped) return
2490
- if (cfg && !gatedStub(cfg) && (typeof cfg.lanes === 'boolean' || cfg.plain === true)) {
2491
- this._lanesSetting = cfg.lanes === true
2492
- if (this._gateCfg && typeof cfg.lanes === 'boolean') this._gateCfg.lanes = cfg.lanes
2493
- }
2494
- } catch { /* retain the last confirmed setting */ }
2787
+ const check = (async () => {
2788
+ try {
2789
+ const cfg = await this._client.getConfig(this.room, this._mk, { plainMark: true })
2790
+ if (this._stopped) return
2791
+ if (cfg?.admission === 'email' || cfg?.gated === true) this._gated = true
2792
+ if (cfg && !gatedStub(cfg) && (typeof cfg.lanes === 'boolean' || cfg.plain === true)) {
2793
+ this._lanesSetting = cfg.lanes === true
2794
+ if (this._gateCfg && typeof cfg.lanes === 'boolean') this._gateCfg.lanes = cfg.lanes
2795
+ }
2796
+ } catch { /* retain the last confirmed setting */ }
2797
+ })()
2798
+ // A STALLED SETTINGS READ MUST NOT HOLD THE MESSAGES THIS POLL READ (side sweep: sdk-room-settings-stall-holds-read-messages):
2799
+ // the fetch has no deadline of its own, so wait for it a moment only; a late answer still applies when it lands.
2800
+ let waited
2801
+ await Promise.race([check, new Promise((res) => { waited = setTimeout(res, LANES_CHECK_WAIT_MS) })])
2802
+ clearTimeout(waited)
2803
+ if (this._stopped) return
2495
2804
  }
2496
2805
  if (this._wb && this._wb._attest) this._wb._attest.notePoll(this.room, r) // a room that requires your app: its fresh challenge
2497
2806
  // ⛔ A REFUSED POLL LOOKED LIKE AN EMPTY ROOM (a builder, 2026-09-29). A poll carrying an error code — in a 200 (the
@@ -2540,8 +2849,11 @@ export class Space {
2540
2849
  if (r.changed && Array.isArray(r.entries)) {
2541
2850
  for (let e of r.entries) {
2542
2851
  if (this._removedMessages && this._removedMessages.has(removedEntryKey(e))) e = removedCopy(e)
2543
- else if (e.sourceRestored === true) this._removedSourceMessages?.delete(removedEntryKey(e))
2544
- else if (this._removedSourceMessages && this._removedSourceMessages.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2852
+ else if (e.sourceRestored === true) {
2853
+ this._removedSourceMessages?.delete(removedEntryKey(e))
2854
+ if (e.id?.startsWith('sh:')) this._removalsMirrored?.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
2855
+ }
2856
+ else if (this._removedSourceMessages?.has(removedEntryKey(e)) || this._pendingSourceHides?.has(removedEntryKey(e))) e = sharedRemovedCopy(e) // a removal still being written is hidden too (side sweep: sdk-lane-copy-retains-body-until-removal-ack)
2545
2857
  // `from` IS THE DOCUMENTED FIELD (see the header and `on()` below) — the ledger calls it `name`, and this
2546
2858
  // emitted the raw entry, so an author test written from the docs (`m.from === me`) silently matched
2547
2859
  // NOTHING and every delivered message read as "not mine". Reported by the first outside builder after it
@@ -2550,7 +2862,7 @@ export class Space {
2550
2862
  // an entry that already carries `from` is left alone. `messages` gets the SAME object as the event — two
2551
2863
  // shapes for one thing is how this happened.
2552
2864
  if (isTitleEntry(e)) { this._noteTitle(e); continue } // the room's NAME, not a message (roomName.js)
2553
- if (isPurged(e)) continue // a DELETED MAIL's place (agent/mailPurge.mjs): nothing is left of it — the app draws nothing either (sync sweep 11-22 #9)
2865
+ if (isPurged(e)) { this._view.remove(e.id, e.ts); continue } // a DELETED MAIL's place (agent/mailPurge.mjs): nothing is left of it — the app draws nothing either (sync sweep 11-22 #9)
2554
2866
  if (this.safeMedia._note(e)) continue // a photo's SAFE COPY, kept beside it — never a message (sdkSafeMedia.js); the line that moved the setting is read and stays a message
2555
2867
  const m = e && e.from === undefined && e.name !== undefined ? { ...e, from: e.name } : e
2556
2868
  const { added, updated } = this._view.apply([m])
@@ -2558,7 +2870,7 @@ export class Space {
2558
2870
  if (!added.length) continue // the same entry again
2559
2871
  this._emit('message', m)
2560
2872
  this.safeMedia._arrived(m) // a message this handle sent: its safe copies go beside it
2561
- if (m && !m.self && typeof m.text === 'string') this._feed.landed(m.text) // a stored answer: its own late stream frames are not a partial (turnFeed.js; sync sweep 10-15 #16)
2873
+ if (m && m.self && typeof m.text === 'string') this._feed.landed(m.text) // `self` = the assistant's (side sweep 2026-11-28: it read !m.self) — a stored answer: its own late stream frames are not a partial (turnFeed.js; sync sweep 10-15 #16)
2562
2874
  if (e && e.kind === 'fork') this._maybeMoved(e) // a membership fork: is this device one of the keepers?
2563
2875
  if (e && e.kind === 'data' && Array.isArray(e.ops)) { applyDataEntry(this._rows, e); this._emit('data', { ops: e.ops, from: e.name || '', self: !!e.self, text: e.text || '', ts: e.ts }) }
2564
2876
  }
@@ -2566,10 +2878,27 @@ export class Space {
2566
2878
  // `more`: another page follows (a long room loads in pages) — read it at once, and until it has, the history is
2567
2879
  // not whole: a lane mirror must not take a short list for another history (sync sweep, 2026-10-10)
2568
2880
  }
2569
- if (clearedRemoval) { this._count = 0; this._etag = null }
2570
- this._more = !!(clearedRemoval || (r.changed && r.more)); read = true // the NEXT poll (in `finally`, at once) reads the next page
2881
+ // THE ENTRIES THE SERVER SAYS WERE CHANGED IN PLACE (round 8, side sweep: reaction-refresh-misses-edited-history): the tail re-read
2882
+ // sees only the last 50, so a held message further back kept an old reaction and no `update` said otherwise. Applied as a re-read
2883
+ // is; one the answer could not carry is read from its place (a few); a record that cannot say leaves it to the tail re-read.
2884
+ // Only an answer for the record this handle sent.
2885
+ if (r.edits && typeof r.edits.tag === 'string' && r.edits.since === sentEdit) {
2886
+ this._applyHeld(Array.isArray(r.edits.entries) ? r.edits.entries : [])
2887
+ for (const i of (Array.isArray(r.edits.missing) ? r.edits.missing : []).slice(0, 3)) this._tailResync(i).catch(() => {})
2888
+ if (r.edits.lost && Date.now() - (this._resyncAt || 0) > 1500) { this._resyncAt = Date.now(); this._tailResync().catch(() => {}) }
2889
+ this._editTag = r.edits.tag
2890
+ }
2891
+ const rereadAll = !!this._rereadAll; this._rereadAll = false // a mail held from before the tail re-read (_tailResync)
2892
+ if (clearedRemoval || rereadAll) { this._count = 0; this._etag = null }
2893
+ this._more = !!(clearedRemoval || rereadAll || (r.changed && r.more)); read = true // the NEXT poll (in `finally`, at once) reads the next page
2571
2894
  this._maybeTitleDoc()
2572
- if (needsTailResync(r, this._count) && Date.now() - (this._resyncAt || 0) > 1500) { this._resyncAt = Date.now(); this._tailResync().catch(() => {}) } // an in-place change pages as nothing
2895
+ if ((needsTailResync(r, this._count) && Date.now() - (this._resyncAt || 0) > 1500) || (mayHideEdit(r, heldBefore) && !r.more && Date.now() - (this._resyncAt || 0) > TAIL_RESYNC_WITH_NEW_MS)) { this._resyncAt = Date.now(); this._tailResync().catch(() => {}) } // an in-place change pages as nothing — or rides in with a new message (side sweep: reaction-refresh-misses-edited-history)
2896
+ // …and one INSIDE the floor is not skipped for good: it runs once the floor ends (side sweep round 5)
2897
+ else if (mayHideEdit(r, heldBefore) && !r.more && !this._resyncOwed) {
2898
+ this._resyncOwed = true
2899
+ const t = setTimeout(() => { this._resyncOwed = false; if (this._stopped) return; this._resyncAt = Date.now(); this._tailResync().catch(() => {}) }, Math.max(0, TAIL_RESYNC_WITH_NEW_MS - (Date.now() - (this._resyncAt || 0))))
2900
+ if (t && typeof t.unref === 'function') t.unref() // never keeps a Node process alive
2901
+ }
2573
2902
  if (r.deviceCall) this._runDeviceCall(r.deviceCall) // an `await` action the turn is waiting on — answer from this device
2574
2903
  this._partialFromPoll(r)
2575
2904
  this._liveFeed(r)
@@ -2607,16 +2936,32 @@ export class Space {
2607
2936
 
2608
2937
  // THE IN-PLACE CHANGE (ledgerView.js): the ledger moved and brought no entry — a reaction or a caption rewrote one you
2609
2938
  // hold. Re-read a short tail and announce what changed; its etag is NOT adopted (a reply landing in between would be lost).
2610
- async _tailResync() {
2611
- const r = await this._client.pollSealed(this.room, this._mk, null, Math.max(0, this._count - REACTION_RESYNC_TAIL))
2939
+ // `at`: read from that index instead of the tail — an entry the server named as edited but could not carry (round 8, _poll)
2940
+ async _tailResync(at) {
2941
+ const r = await this._client.pollSealed(this.room, this._mk, null, Number.isInteger(at) ? at : Math.max(0, this._count - REACTION_RESYNC_TAIL))
2612
2942
  if (!(r && r.status === 200 && Array.isArray(r.entries))) return
2613
- for (let e of r.entries) {
2943
+ this._applyHeld(r.entries)
2944
+ if (Number.isInteger(at)) return
2945
+ // A MAIL HELD FROM FURTHER BACK than this tail (side sweep round 2): a mail is deleted IN ITS SLOT (agent/mailPurge.mjs), which this
2946
+ // tail cannot see — the next poll reads the whole history again (as a cleared removal does), and its purged places drop it.
2947
+ const tailIds = new Set(r.entries.map((e) => e && e.id))
2948
+ if (this.messages.some((m) => isMailEntry(m) && !tailIds.has(m.id))) this._rereadAll = true
2949
+ }
2950
+ /** Entries this handle ALREADY holds, as they are now (a re-read, or the poll's `edits`) → an `update` for each that changed. */
2951
+ _applyHeld(entries) {
2952
+ for (let e of entries) {
2614
2953
  if (this._removedMessages && this._removedMessages.has(removedEntryKey(e))) e = removedCopy(e)
2615
- else if (e.sourceRestored === true) this._removedSourceMessages?.delete(removedEntryKey(e))
2616
- else if (this._removedSourceMessages && this._removedSourceMessages.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2954
+ else if (e.sourceRestored === true) {
2955
+ this._removedSourceMessages?.delete(removedEntryKey(e))
2956
+ if (e.id?.startsWith('sh:')) this._removalsMirrored?.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
2957
+ }
2958
+ else if (this._removedSourceMessages?.has(removedEntryKey(e)) || this._pendingSourceHides?.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2617
2959
  if (isTitleEntry(e)) { this._noteTitle(e); continue }
2618
- if (isPurged(e)) continue // a deleted mail's place, written over its entry in that slot: no `update` (sync sweep 11-22 #9)
2960
+ if (isPurged(e)) { this._view.remove(e.id, e.ts); continue } // a deleted mail's place, written over its entry in that slot: no `update` (sync sweep 11-22 #9)
2619
2961
  const m = e && e.from === undefined && e.name !== undefined ? { ...e, from: e.name } : e
2962
+ // only entries this handle ALREADY holds: one that landed meanwhile is the ordinary poll's to add and announce as a
2963
+ // `message` — inserting it here made that poll skip it as known (side sweep: sdk-reaction-refresh-swallows-new-message-event)
2964
+ if (m == null || m.id == null || !this._view.has(m.id)) continue
2620
2965
  const { updated } = this._view.apply([m])
2621
2966
  for (const u of updated) this._emit('update', { id: u.id, message: u.entry, fields: u.fields })
2622
2967
  }
@@ -2708,6 +3053,7 @@ export class Lane extends Space {
2708
3053
  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
3054
  // THE MIRROR (2026-10-02) — see _runMirror. The cursor is how many of the shared room's messages this lane already
2710
3055
  // holds; it rides snapshot()/resume as `mirrored`, and the server dedups by id, so a cursor that is off only resends.
3056
+ this._mirrorAnchor = resume?.mirrorAnchor || null
2711
3057
  this._mirrorCursor = resume && Number.isFinite(Number(resume.mirrored)) ? Math.max(0, Number(resume.mirrored)) : 0
2712
3058
  if (mirror && shared instanceof Space) {
2713
3059
  this._mirrorFrom = shared
@@ -2750,7 +3096,7 @@ export class Lane extends Space {
2750
3096
 
2751
3097
  /** Post a private message to your assistant. Its reply is private; anything it wants the shared room to see, or any
2752
3098
  * 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 } = {}) {
3099
+ async send(text, { from = 'You', mode, tools, dictation, replace = false, instructions, images, files, links, stopKey, showPrompt, replyTo, _onAttempt, _aborted, _linkPost, _peerPost, _noHold, _skill } = {}) {
2754
3100
  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
3101
  { 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
3102
  // PER-TURN TOOLS (2026-09-25): `tools` takes the same action shape the constructor takes, offered for THIS turn only
@@ -2759,6 +3105,7 @@ export class Lane extends Space {
2759
3105
  // name wins for the turn); the handlers are registered so a proposal or an in-turn read for them can run.
2760
3106
  // `replace: true` (2026-09-26): the turn is offered ONLY `tools` — a skill runs with its own set — while every
2761
3107
  // standing handler stays registered, so a proposal approved later still runs. `replace` with no tools ⇒ no tools.
3108
+ let additions
2762
3109
  let defs = this._clientTools, guidance = this._guidance
2763
3110
  if (replace) { defs = []; guidance = '' }
2764
3111
  // LINKED LANES (sdkLaneLink.js): while this lane is linked, every turn is offered tell_lane — `replace` included, since
@@ -2770,11 +3117,12 @@ export class Lane extends Space {
2770
3117
  if (extra.defs.length) {
2771
3118
  const names = new Set(extra.defs.map((d) => d.name))
2772
3119
  defs = [...defs.filter((d) => !names.has(d.name)), ...extra.defs]
2773
- Object.assign(this._writes, extra.handlers); Object.assign(this._reads, extra.reads)
3120
+ additions = extra
2774
3121
  guidance = [guidance, extra.guidance].filter(Boolean).join(' ')
2775
3122
  }
2776
3123
  }
2777
3124
  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 })`)
3125
+ if (additions) { Object.assign(this._writes, additions.handlers); Object.assign(this._reads, additions.reads) }
2778
3126
  const opts = await this._turnOpts(mode, {
2779
3127
  ...this._bridgeOpts(), // the lane observes the shared room + can cross into it (keyless: the worker holds the shared room's key)
2780
3128
  ...this._linksOpt(links),
@@ -2783,10 +3131,13 @@ export class Lane extends Space {
2783
3131
  ...stopOpt(stopKey),
2784
3132
  ...promptOpt(showPrompt),
2785
3133
  })
2786
- const msg = withMedia({ from, text: String(text), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files)
3134
+ const msg = withMedia({ from, ...(_skill ? { mcp: _skill } : { text: String(text) }), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files, { enclave: encRoomOf(this) })
2787
3135
  { const rt = replyRef(replyTo); if (rt) msg.replyTo = rt }
2788
3136
  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)
3137
+ const r = await this._turnHeld(() => {
3138
+ const { bridgeRoom, bridgeMk, viewSource, links: oldLinks, ...rest } = opts
3139
+ return this._provenTurn(msg, { ...rest, ...this._bridgeOpts(), ...this._linksOpt(links) })
3140
+ }, _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
3141
  this._kick()
2791
3142
  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
3143
  return r
@@ -2820,7 +3171,7 @@ export class Lane extends Space {
2820
3171
  if (!(other instanceof Lane)) throw sdkError('witbitz: link takes another private Lane, not a shared Space', 'not_a_lane')
2821
3172
  const l = linkLanes(this, other, { to, as, cap, resume }, { tierMismatch })
2822
3173
  const acct = this._wb && this._wb.account
2823
- if (acct && acct.enabled && typeof acct._noteLink === 'function') { acct._noteLink(this.room, other.room, l.cap); l._onUnlink = () => acct._dropLink(this.room, other.room) }
3174
+ if (acct && acct.enabled && typeof acct._noteLink === 'function') { acct._noteLink(this.room, other.room, l.cap, l); l._onUnlink = () => acct._dropLink(this.room, other.room, l) } // l: stopped here when another device's unlink arrives (sdkAccount.js)
2824
3175
  return l
2825
3176
  }
2826
3177
 
@@ -2871,43 +3222,47 @@ export class Lane extends Space {
2871
3222
  const cfg = canReadConfig ? await from._client.getConfig(from.room, from._mk, { plainMark: true }) : {}
2872
3223
  if (!cfg || gatedStub(cfg)) return { mirrored: 0 }
2873
3224
  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)))
3225
+ 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
3226
  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
3227
+ const anchorOf = e => e ? removedEntryKey(e) : null
3228
+ if (this._mirrorCursor && (this._mirrorCursor > all.length || this._mirrorAnchor !== anchorOf(all[this._mirrorCursor - 1]))) {
3229
+ const anchor = this._mirrorAnchor ? all.findIndex(e => anchorOf(e) === this._mirrorAnchor) : -1
3230
+ this._mirrorCursor = anchor + 1
3231
+ } // a cursor from another history: start over; the server's id-dedup makes it a resend, never a double
2877
3232
  const copyEntry = async e => ({
2878
3233
  sourceRoom: from.room,
2879
3234
  id: 'sh:' + (e.id || ('t' + e.ts)), // the entry id alone, no room prefix — stable across a fork (the app's rule)
2880
3235
  from: e.name || e.from || 'party', ...(e.self === true ? { self: true } : {}), ...(e.md === true ? { md: true } : {}),
2881
3236
  ...(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)
3237
+ ...(e.self && Array.isArray(e.sources) ? { sources: e.sources.slice(0, 12) } : {}),
2882
3238
  ...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
3239
  ...(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
3240
  text: e.text, files: await withBytes(from, e.files), images: await withBytes(from, e.images),
2885
3241
  ...(e.removedByWitbitz ? { sourceRemoved: true } : {}),
2886
3242
  })
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).
3243
+
3244
+ // Apply removals before fresh attachments, which can fail to load.
2908
3245
  if (!this._stopped && !from._stopped) {
2909
3246
  this._removalsMirrored = this._removalsMirrored || new Set()
2910
3247
  const removed = all.filter((e) => e.removedByWitbitz && (!from._removedMessages || from._removedMessages.has(removedEntryKey(e))) && !this._removalsMirrored.has(removedEntryKey(e)))
3248
+ // HIDDEN AT ONCE, written after (side sweep: sdk-lane-copy-retains-body-until-removal-ack): the copy this handle holds
3249
+ // shows the notice while the write is pending — a failed write or an older server must not leave the removed words
3250
+ // and attachment references in `messages` / `snapshot()`. The original is kept in memory only, to lift a hide whose
3251
+ // removal the Space reversed before any write landed.
3252
+ this._pendingSourceHides = this._pendingSourceHides || new Map()
3253
+ for (const [key, original] of this._pendingSourceHides) {
3254
+ if (all.some((e) => e.removedByWitbitz && removedEntryKey({ id: 'sh:' + e.id, ts: e.ts }) === key)) continue
3255
+ this._pendingSourceHides.delete(key)
3256
+ if (this._removedSourceMessages?.has(key)) continue
3257
+ for (const u of this._view.apply([original]).updated) this._emit('update', { id: u.id, message: u.entry, fields: u.fields })
3258
+ }
3259
+ for (const e of removed) {
3260
+ const key = removedEntryKey({ id: 'sh:' + e.id, ts: e.ts })
3261
+ const cur = this.messages.find((m) => removedEntryKey(m) === key)
3262
+ if (!cur || cur.sourceRemoved || this._pendingSourceHides.has(key)) continue
3263
+ this._pendingSourceHides.set(key, cur)
3264
+ for (const u of this._view.apply([sharedRemovedCopy(cur)]).updated) this._emit('update', { id: u.id, message: u.entry, fields: u.fields })
3265
+ }
2911
3266
  for (let i = 0; i < removed.length && !from._stopped && !this._stopped; i += 25) {
2912
3267
  const batch = removed.slice(i, i + 25), patches = batch.map((e) => ({ id: 'sh:' + e.id, ts: e.ts, sourceRoom: from.room, sourceRemoved: true }))
2913
3268
  if (!attached()) return { mirrored: sent }
@@ -2923,11 +3278,41 @@ export class Lane extends Space {
2923
3278
  this._removedSourceMessages = this._removedSourceMessages || new Map()
2924
3279
  const target = { id: 'sh:' + e.id, ts: e.ts }, key = removedEntryKey(target)
2925
3280
  this._removedSourceMessages.set(key, target)
3281
+ this._pendingSourceHides.delete(key)
2926
3282
  const cur = this.messages.find((m) => removedEntryKey(m) === key)
2927
3283
  if (cur) for (const u of this._view.apply([sharedRemovedCopy(cur)]).updated) this._emit('update', { id: u.id, message: u.entry, fields: u.fields })
2928
3284
  }
2929
3285
  this._kick()
2930
3286
  }
3287
+ }
3288
+ while (this._mirrorCursor < all.length && !from._stopped && !this._stopped) {
3289
+ const slice = all.slice(this._mirrorCursor, this._mirrorCursor + 25)
3290
+ const batch = this._mirrorData ? slice : slice.filter((e) => e.kind !== 'data')
3291
+ if (!batch.length) { this._mirrorCursor += slice.length; this._mirrorAnchor = anchorOf(slice.at(-1)); continue }
3292
+ const entries = await Promise.all(batch.map(copyEntry))
3293
+ // A REFUSAL THAT THROWS is still a refusal (sync sweep 11-16 #16): a vault refuses an attested Space's copy into an ordinary
3294
+ // lane by throwing, and the timer's catch swallowed it — every message tried again, silently. Said once, like the others.
3295
+ const start = this._mirrorCursor
3296
+ let accepted = 0
3297
+ for (const part of mirrorBatches(entries)) {
3298
+ if (!attached() || from._stopped || this._stopped) return { mirrored: sent }
3299
+ let r
3300
+ try { r = await this._client.mirror(this.room, this._mk, part) }
3301
+ catch (error) { r = { status: 0, error: error?.code || 'mirror_failed', reason: String(error?.message || '').slice(0, 300) } }
3302
+ if (r?.status !== 200) {
3303
+ const key = String(r?.error || r?.status || 'no_answer')
3304
+ if (this._mirrorRefusal !== key) { this._mirrorRefusal = key; this._emit('error', refused('mirror', r)) }
3305
+ return { mirrored: sent }
3306
+ }
3307
+ this._mirrorRefusal = null
3308
+ accepted += part.length; sent += part.length
3309
+ this._mirrorCursor = start + slice.indexOf(batch[accepted - 1]) + 1
3310
+ this._mirrorAnchor = anchorOf(all[this._mirrorCursor - 1])
3311
+ }
3312
+ this._mirrorCursor = start + slice.length
3313
+ this._mirrorAnchor = anchorOf(slice.at(-1))
3314
+ }
3315
+ if (!this._stopped && !from._stopped) {
2931
3316
  // A cleared moderation list triggers a fresh source read. Cached message text is never a restoration.
2932
3317
  const hiddenCopies = new Set(this.messages.filter(e => e.sourceRemoved).map(removedEntryKey))
2933
3318
  const candidates = all.filter(e => hiddenCopies.has(removedEntryKey({ id: 'sh:' + e.id, ts: e.ts })) && !from._removedMessages?.has(removedEntryKey(e)))
@@ -2938,18 +3323,26 @@ export class Lane extends Space {
2938
3323
  const wanted = new Set(candidates.map(removedEntryKey))
2939
3324
  const originals = history.entries.filter(e => wanted.has(removedEntryKey(e)) && !hidden.has(removedEntryKey(e)) && !e.removedByWitbitz && e.kind !== 'fork')
2940
3325
  for (let i = 0; i < originals.length; i += 25) {
2941
- const entries = await Promise.all(originals.slice(i, i + 25).map(copyEntry))
3326
+ const attempts = await Promise.allSettled(originals.slice(i, i + 25).map(copyEntry))
3327
+ const entries = attempts.filter(result => result.status === 'fulfilled').map(result => result.value)
3328
+ if (!entries.length) continue
2942
3329
  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 }))
3330
+ for (const part of mirrorBatches(entries.map(e => ({ ...e, restoreSource: true })))) {
3331
+ if (!attached()) return { mirrored: sent }
3332
+ const r = await this._client.mirror(this.room, this._mk, part)
3333
+ if (r?.status !== 200) return { mirrored: sent }
3334
+ for (const e of r.sourceRestorations || []) {
3335
+ this._removedSourceMessages?.delete(removedEntryKey(e))
3336
+ this._removalsMirrored.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
3337
+ }
3338
+ if (r.sourceRestorations?.length) { this._count = 0; this._etag = null; this._kick() }
2948
3339
  }
2949
- if (r.sourceRestorations?.length) { this._count = 0; this._etag = null; this._kick() }
2950
3340
  }
2951
3341
  }
2952
3342
  }
3343
+ // CAPTION CATCH-UP (the app's rule, mirrorLoop.js): a shared photo is described by the shared room's assistant AFTER
3344
+ // it first crossed. Once the description lands, re-send it as a description-only patch so the lane's assistant gets
3345
+ // what the shared room has. Recent entries, once per id (sync sweep, 2026-10-10 — the SDK never sent it).
2953
3346
  this._descMirrored = this._descMirrored || new Set()
2954
3347
  const patches = []
2955
3348
  for (const e of all.slice(-40)) {
@@ -2966,8 +3359,10 @@ export class Lane extends Space {
2966
3359
  this._viewsAt = Date.now()
2967
3360
  try {
2968
3361
  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)
3362
+ // an ANSWERED read with no doc is an empty map ("no stops"), not a reason to leave the lane's views as they were; only a FAILED
3363
+ // read stops the write (side sweep: empty-map-card-blocks-lane-view-refresh)
3364
+ for (const v of viewsNamedIn(from.messages)) { const d = await this._client.state(from.room, from._mk, v.name).catch(() => null); const view = viewFromRead({ label: v.label, map: isMapView(v) }, d); if (!view) { this._viewsAt = 0; throw sdkError('shared view unavailable', 'state_unavailable') } views.push(view) }
3365
+ const text = renderSharedViews(views, from.room)
2971
3366
  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
3367
  } catch { /* never break the mirror */ }
2973
3368
  }
@@ -2980,8 +3375,7 @@ export class Lane extends Space {
2980
3375
  }
2981
3376
 
2982
3377
  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 } : {}) }
3378
+ return { ...super.snapshot(), ...(this._mirrorFrom ? { mirrored: this._mirrorCursor, mirrorAnchor: this._mirrorAnchor } : {}) }
2985
3379
  }
2986
3380
 
2987
3381
  close() {
@@ -2989,7 +3383,7 @@ export class Lane extends Space {
2989
3383
  for (const off of this._sharedOffs || []) { try { off() } catch { /* */ } }
2990
3384
  this._sharedOffs = []
2991
3385
  for (const l of [...(this._laneLinks || [])]) l._stop() // stops here; the link itself (in wb.account) stays
2992
- if (this._mirrorFrom && this._mirrorSub) for (const ev of ['message', 'update']) { const l = this._mirrorFrom._subs[ev]; if (l) { const i = l.indexOf(this._mirrorSub); if (i >= 0) l.splice(i, 1) } }
3386
+ if (this._mirrorFrom && this._mirrorSub) for (const ev of ['message', 'update']) { const l = this._mirrorFrom._subs[ev]; if (l) { const i = l.findIndex((x) => x === this._mirrorSub || x._orig === this._mirrorSub); if (i >= 0) l.splice(i, 1) } }
2993
3387
  clearTimeout(this._mirrorTimer); clearInterval(this._viewsTick)
2994
3388
  if (this._ownsSharedSpace && this._sharedSpace) { try { this._sharedSpace.close() } catch { /* */ } } // a Space vault.openRoom(laneId) opened for it
2995
3389
  return super.close()
@@ -3001,10 +3395,11 @@ export class Lane extends Space {
3001
3395
  for (const off of this._sharedOffs || []) { try { off() } catch {} }
3002
3396
  this._sharedOffs = []
3003
3397
  if (this._mirrorFrom && this._mirrorSub) for (const ev of ['message', 'update']) {
3004
- const listeners = this._mirrorFrom._subs?.[ev], index = listeners?.indexOf(this._mirrorSub) ?? -1
3398
+ const listeners = this._mirrorFrom._subs?.[ev], index = listeners?.findIndex((x) => x === this._mirrorSub || x._orig === this._mirrorSub) ?? -1
3005
3399
  if (index >= 0) listeners.splice(index, 1)
3006
3400
  }
3007
3401
  if (this._ownsSharedSpace) this._sharedSpace?.close()
3402
+ this._detachedLane = true
3008
3403
  this._sharedRoom = null; this._sharedMk = null; this._mirrorFrom = null; this._sharedSpace = null
3009
3404
  clearTimeout(this._mirrorTimer); clearInterval(this._viewsTick)
3010
3405
  this._emit('disconnected', { reason: 'lanes_disabled' })
@@ -3012,7 +3407,7 @@ export class Lane extends Space {
3012
3407
  _checkShared() {
3013
3408
  if (!this._sharedRoom) return
3014
3409
  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()
3410
+ if (rec && (rec.detachedLane || rec.kind !== 'lane' || (rec.shared && rec.shared !== this._sharedRoom))) this._detachShared()
3016
3411
  }
3017
3412
  _bridgeOpts() { this._checkShared(); if (!this._sharedRoom) return {}; return this._crossTier ? { viewSource: this._sharedRoom } : { ...(this._sharedMk ? { bridgeMk: this._sharedMk } : {}), bridgeRoom: this._sharedRoom } }
3018
3413
  _runExtra() { return { ...this._bridgeOpts(), ...this._linksOpt() } } // sync sweep, 2026-10-10: Lane.run had no bridge, then no linked rooms
@@ -3080,11 +3475,9 @@ const ENC_MARK = /[?#&]enc=1(?:[&#]|$)/ // in the fragment (markEncLink) OR the
3080
3475
  const markEncLink = (l) => (ENC_MARK.test(String(l)) ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'enc=1')
3081
3476
  /** An email-gated room's link says so too (the app's own convention, inviteLinks.js): a client opening it knows to sign
3082
3477
  * 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')
3478
+ const markGateLink = (l) => (roomInviteFlags(l).gated ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'gate=email')
3085
3479
  /** 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')
3480
+ const markLanesLink = (l) => (roomInviteFlags(l).lanes ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'lanes=1')
3088
3481
  /** 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
3482
  * 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
3483
  const SPLIT_MARK = /[#&]us=/
@@ -3165,16 +3558,19 @@ const sessionOf = (x) => (x && typeof x === 'object' && typeof x.idToken === 'st
3165
3558
  /** 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
3559
  * `wasLane`) — the SDK's record, as the app's is `space:lane-rooms`. Without the backup the SDK knows only the Lane handle. */
3167
3560
  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 }
3561
+ 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
3562
  }
3170
- const siriStateOf = (x) => {
3563
+ const siriStateOf = (x, allowPending = true) => {
3171
3564
  const o = x && typeof x === 'object' ? x : {}
3172
3565
  const rooms = {}
3173
3566
  for (const [room, r] of Object.entries(o.rooms && typeof o.rooms === 'object' ? o.rooms : {})) {
3174
3567
  if (!r || typeof r !== 'object' || !r.alias || !r.pub || !r.priv) continue
3175
3568
  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
3569
  }
3177
- return { token: typeof o.token === 'string' ? o.token : '', defaultRoom: typeof o.defaultRoom === 'string' && rooms[o.defaultRoom] ? o.defaultRoom : '', rooms }
3570
+ const pending = Array.isArray(o.pendingRemovals) ? [...new Set(o.pendingRemovals.filter(id => typeof id === 'string' && Object.hasOwn(rooms, id)))] : []
3571
+ const setup = allowPending && o.pendingSetup ? siriStateOf(o.pendingSetup, false) : null
3572
+ const rotation = allowPending && o.pendingRotation
3573
+ 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
3574
  }
3179
3575
 
3180
3576
  /** `wb.usernames` — the member's @username. One name means one person across ALL of Witbitz (not per app): it is
@@ -3250,12 +3646,35 @@ function refuseInVault(wb) {
3250
3646
  // read the vault's last VIEW of them (no link, no key, no master secret); `onChange` fires when it changes.
3251
3647
  wb._vaultAccount = (conn.info && conn.info.account) || { enabled: false, format: null, deviceId: '', rooms: [], devices: [], links: [], lastError: null, erasure: false }
3252
3648
  let accountGeneration = 0
3649
+ let memoryEmail = String(conn.info?.email || '').toLowerCase()
3650
+ wb._memoryGeneration = 0
3253
3651
  const view = () => wb._vaultAccount
3652
+ const vaultLiveLinks = new Set() // the lane links open in THIS page (Lane#link → _noteLink)
3653
+ const pairKey = (a, b) => [String(a), String(b)].sort().join('|')
3254
3654
  conn.on((ev) => {
3655
+ if (ev?.ev === 'a2aChanged') refreshVaultA2AViews(conn, ev)
3656
+ if (ev?.ev === 'siri' && ev.siri) wb._vaultSiri = { ...ev.siri, key: null }
3657
+ const expired = ev?.ev === 'signedOut' && ev.reason === 'expired'
3658
+ if (expired) wb.a2a._draftsSuspended = true
3659
+ if (ev?.ev === 'signedOut' || ev?.ev === 'accountSignedOut' || ev?.ev === 'signedIn') {
3660
+ const email = ev.ev === 'signedIn' ? String(ev.email || '').toLowerCase() : ''
3661
+ const resumed = wb.a2a._draftsSuspended && email && email === memoryEmail
3662
+ if (!email || email !== memoryEmail) {
3663
+ if (!expired) wb.a2a._dropAllDrafts()
3664
+ wb._forgetVoice(); wb._memoryGeneration++; wb._assistantMemory = null
3665
+ }
3666
+ if (!expired) {
3667
+ memoryEmail = email; wb.a2a._draftsSuspended = false
3668
+ if (resumed) for (const handle of wb._agentHandles || []) handle._a2a?._flushHeld()
3669
+ }
3670
+ }
3255
3671
  if (['signedOut', 'accountSignedOut', 'signedIn'].includes(ev?.ev) || (ev?.ev === 'account' && ev.view?.enabled !== view().enabled)) {
3672
+ if (ev.view?.enabled === false && !expired) wb.a2a._dropAllDrafts()
3256
3673
  wb._vaultGeneration = ++accountGeneration
3674
+ conn.a2aEpoch = (conn.a2aEpoch || 0) + 1
3257
3675
  wb._vaultSiri = { key: null, hasKey: false, endpoint: wb._vaultSiri?.endpoint }
3258
3676
  if (ev.ev !== 'signedOut' && ev.ev !== 'accountSignedOut' && ev.view?.enabled !== false) {
3677
+ refreshVaultA2AViews(conn, ev)
3259
3678
  const generation = accountGeneration
3260
3679
  conn.account('siri', 'shortcut').then(value => { if (generation === accountGeneration) wb._vaultSiri = value }).catch(() => {})
3261
3680
  }
@@ -3267,6 +3686,16 @@ function refuseInVault(wb) {
3267
3686
  if (ev && ev.ev === 'accountSection' && Object.prototype.hasOwnProperty.call(wb.account._sections || {}, ev.section)) { wb.account._sections[ev.section]._seen(ev.value, true); return }
3268
3687
  if (!ev || ev.ev !== 'account' || !ev.view) return
3269
3688
  const was = wb._vaultAccount; wb._vaultAccount = ev.view
3689
+ // ANOTHER DEVICE'S UNLINK STOPS THE LINK OPEN IN THIS PAGE (side sweep: sdk-live-lane-link-after-remote-unlink) — as the direct SDK's
3690
+ // account sync does (sdkAccount.js _stopDroppedLinks): a pair the vault's view held and no longer holds was unlinked elsewhere.
3691
+ if (vaultLiveLinks.size) {
3692
+ const had = new Set(((was && was.links) || []).map((l) => pairKey(l.a, l.b))), has = new Set((ev.view.links || []).map((l) => pairKey(l.a, l.b)))
3693
+ for (const live of [...vaultLiveLinks]) {
3694
+ if (live._dead) { vaultLiveLinks.delete(live); continue }
3695
+ const k = pairKey(live.a.room, live.b.room)
3696
+ if (had.has(k) && !has.has(k)) { live._remoteGone = true; vaultLiveLinks.delete(live); try { live._stop() } catch { /* */ } }
3697
+ }
3698
+ }
3270
3699
  if (typeof wb.account.onChange === 'function' && JSON.stringify([was.rooms, was.devices, was.links]) !== JSON.stringify([ev.view.rooms, ev.view.devices, ev.view.links])) { try { wb.account.onChange({ rooms: ev.view.rooms, devices: ev.view.devices }) } catch { /* the app's callback */ } }
3271
3700
  if (typeof wb.backup.onState === 'function' && was.enabled !== ev.view.enabled) { try { wb.backup.onState(null) } catch { /* */ } }
3272
3701
  })
@@ -3281,8 +3710,13 @@ function refuseInVault(wb) {
3281
3710
  getters(wb.backup, { enabled: () => view().enabled, format: () => view().format, service: () => view().service || null, gated: () => !!view().gated, state: () => null, invite: () => null, rooms: () => view().rooms.map((r) => ({ ...r })) }) // gated: as the vault says (it read false for ever — sync sweep 11-09 #24)
3282
3711
  forwardInVault(wb.account, (m, a) => conn.account('account', m, ...(m === 'signOutDevice' ? [a[0]] : a)), ['sync', 'start', 'stop', 'archive', 'pin', 'rename', 'forget', 'signOut', 'listDevices', 'signOutDevice', 'repairNames', 'previewEmptySpaces', 'removeEmptySpaces', 'usage'])
3283
3712
  // lane.link() records the link on the account (Lane#link → _noteLink): in a vault the index is the vault's (sync sweep, 10-17 #6)
3284
- wb.account._noteLink = (a, b, cap) => { conn.account('account', 'noteLink', a, b, cap).catch(() => {}) }
3285
- wb.account._dropLink = (a, b) => { conn.account('account', 'dropLink', a, b).catch(() => {}) }
3713
+ wb.account._noteLink = (a, b, cap, live = null) => { if (live) vaultLiveLinks.add(live); conn.account('account', 'noteLink', a, b, cap).catch(() => {}) }
3714
+ wb.account._dropLink = (a, b, handle = null) => {
3715
+ // a handle stopped by another device's unlink, or one a live link of the same pair replaced, does not unlink that replacement
3716
+ // (side sweep: retired-sdk-link-unlinks-replacement)
3717
+ if (handle && (handle._remoteGone || [...vaultLiveLinks].some((l) => l !== handle && !l._dead && pairKey(l.a.room, l.b.room) === pairKey(a, b)))) return
3718
+ conn.account('account', 'dropLink', a, b).catch(() => {})
3719
+ }
3286
3720
  // THE OPTIONAL SECTIONS (wb.account.contacts / .name / .roomDefaults — sdkAccountSections.js, plan phase 5): the account's docs
3287
3721
  // need its master secret, which is the vault's — each call goes to the vault (ACCOUNT_CALLS account.section), which runs the
3288
3722
  // same section on its own SDK and sends 'accountSection' when another device changed one. They carry no key and no link.
@@ -3291,7 +3725,7 @@ function refuseInVault(wb) {
3291
3725
  const generation = accountGeneration
3292
3726
  const v = await conn.account('account', 'section', name, m, ...a)
3293
3727
  if (generation !== accountGeneration) throw sdkError('the account changed during the call', 'account_changed')
3294
- if (!(name === 'chatLocks' && m === 'check')) sec._seen(v)
3728
+ if (!(name === 'chatLocks' && (m === 'check' || m === 'match' || m === 'previewDeleteAll' || m === 'deleteAll'))) sec._seen(v)
3295
3729
  return v
3296
3730
  }
3297
3731
  const on = sec.on.bind(sec)
@@ -3310,6 +3744,7 @@ function refuseInVault(wb) {
3310
3744
  getters(wb.erasure, { available: () => !!view().erasure })
3311
3745
  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
3746
  forwardInVault(wb.connections, (m, a) => conn.account('connections', m, ...a))
3747
+ wb.connections.recover = async id => { checkConnectionId(id); return (await wb.connections.list()).find(c => c.id === id && c.grantable) || null }
3313
3748
  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
3749
  // 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
3750
  // where no page waits — the default is the page's, as outside a vault
@@ -3318,6 +3753,7 @@ function refuseInVault(wb) {
3318
3753
  // gets the id alone, and each Space is unlinked through its own handle, as outside a vault
3319
3754
  wb.connections.detach = async (id, { spaces = [] } = {}) => {
3320
3755
  const cid = String(id || ''), out = await conn.account('connections', 'detach', cid)
3756
+ if (out?.removed?.length) { wb.a2a._dropMoved(out.removed); refreshVaultA2AViews(conn, out) }
3321
3757
  let removedFrom = 0
3322
3758
  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
3759
  return { ...(out || {}), removedFrom }
@@ -3325,19 +3761,28 @@ function refuseInVault(wb) {
3325
3761
  forwardInVault(wb.usernames, (m, a) => conn.account('usernames', m, ...a))
3326
3762
  // the Shortcut KEY stays in the vault: `shortcut.key` is null here, rotateKey resolves null, and wb.vault.showSiriKey()
3327
3763
  // 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'])
3764
+ 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
3765
  wb._vaultSiri = (conn.info && conn.info.siri) || { key: null, endpoint: null }
3330
3766
  Object.defineProperty(wb.siri, 'shortcut', { get() { return { ...wb._vaultSiri } }, configurable: true }) // as the vault last said
3331
3767
  Object.defineProperty(wb.siri, 'state', { get() { return null }, configurable: true }) // the vault keeps it: its inbox private keys never come here
3332
3768
  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'])
3769
+ forwardInVault(wb.a2a, async (m, a) => {
3770
+ const result = await conn.account('a2a', m, ...a)
3771
+ if (m === 'revoke') { conn.a2aEpoch = (conn.a2aEpoch || 0) + 1; wb.a2a._dropAllDrafts() }
3772
+ if (m === 'stopJobAgent') { wb.a2a._dropMoved(result.removed); refreshVaultA2AViews(conn, result) }
3773
+ return result
3774
+ }, ['status', 'revoke', 'stopJobAgent'])
3334
3775
  Object.defineProperty(wb.a2a, 'state', { get() { return null }, configurable: true }) // the vault keeps it: the lanes' inbox private keys never come here
3335
3776
  wb.a2a.restore = () => { throw vaultRefusal('restoring the A2A state (the vault keeps it)') }
3336
3777
  Object.defineProperty(wb.invite, 'state', { get() { return null }, configurable: true }) // the vault keeps the account's invite key
3337
3778
  Object.defineProperty(wb.invite, 'status', { get() { return 'vault' }, configurable: true }) // …and publishes it: there is nothing for the page to enroll or restore (sweep 10-23 #20 — it read 'none' for ever)
3338
3779
  wb.invite.enroll = async () => 'vault' // the status, a string, as outside a vault and in the d.ts (sweep 10-24 #9)
3339
3780
  wb.invite.restore = () => { throw vaultRefusal('restoring the invite key (the vault keeps it)') }
3340
- wb.signIn = () => Promise.reject(sdkError('witbitz: in a vault, sign in with wb.vault.signIn() — the vault keeps the session', 'vault_signs_in'))
3781
+ // the invitations delivered to this account: the VAULT opens its inbox, asks the person before joining, and answers rooms only —
3782
+ // `link` is '' (it would carry the key); open one with wb.vault.openRoom(room). An older vault refuses it by name (side sweep:
3783
+ // sdk-missing-inbox-invite-acceptance)
3784
+ wb.invite.collect = () => conn.account('invite', 'collect').catch((e) => { throw e?.code === 'vault_refused' ? vaultRefusal('collecting invitations (update the vault kit)') : e })
3785
+ wb.signIn =() => Promise.reject(sdkError('witbitz: in a vault, sign in with wb.vault.signIn() — the vault keeps the session', 'vault_signs_in'))
3341
3786
  wb.refreshSession = wb.signIn
3342
3787
  wb.useSession = () => { throw sdkError('witbitz: in a vault, the vault keeps the session — wb.vault.signIn() / wb.vault.info.email', 'vault_signs_in') } // it answered and adopted nothing, as signOut did (sync sweep 11-08 #29)
3343
3788
  wb.signOut = () => { throw sdkError('witbitz: in a vault, sign out with wb.vault.signOut() — the vault keeps the session', 'vault_signs_in') } // it reported success and signed nothing out (sync sweep 10-19)
@@ -3348,16 +3793,28 @@ function refuseInVault(wb) {
3348
3793
  function refuseSpaceInVault(sp) {
3349
3794
  const vc = () => sp._wb && sp._wb.vault && sp._wb.vault._c // read at each call: the vault this Space asks through now
3350
3795
  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)
3796
+ const call = ns => (m, a) => {
3797
+ if (ns === 'connections' && m === 'revoke' && a[1]?.includeAssistant && !vc().info?.scopedConnectionRevoke)
3798
+ throw sdkError('Update the vault kit to revoke private assistant grants', 'vault_unsupported')
3799
+ return vc().roomAccount(sp.room, ns, m, ...a)
3800
+ }
3352
3801
  // grant by id: the callKey is the vault's (wb.connections.attach in a vault returns { id, label, host, account })
3353
3802
  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
3803
  forwardInVault(sp.siri, async (m, a) => {
3355
3804
  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
3805
  const deliver = a[0] && a[0].deliver
3357
3806
  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() }
3807
+ const transport = vc()
3808
+ const queue = transport.siriCollections ||= new Map()
3809
+ const collect = async () => {
3810
+ if (!deliver) return call('siri')('collect', [{}])
3811
+ const off = transport.onAsk('siriDeliver', sp.room, ({ text, meta }) => deliver(text, meta))
3812
+ try { return await call('siri')('collect', [{ deliver: true }]) } finally { off() }
3813
+ }
3814
+ const previous = queue.get(sp.room) || Promise.resolve()
3815
+ const run = previous.catch(() => {}).then(collect)
3816
+ queue.set(sp.room, run)
3817
+ try { return await run } finally { if (queue.get(sp.room) === run) queue.delete(sp.room) }
3361
3818
  })
3362
3819
  return sp
3363
3820
  }
@@ -3386,7 +3843,7 @@ export class VaultSession {
3386
3843
  }
3387
3844
  /** What the vault said when the page connected — { tenant, signedIn, email, rooms, siri, account } — with the sign-in and the
3388
3845
  * 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 } }
3846
+ get info() { return { ...this._c.info, ...this._live, ...(this._wb._vaultSiri ? { siri: { ...this._wb._vaultSiri } } : {}) } }
3390
3847
  /** The Spaces this vault holds, newest first: [{ room, title, at, lane?, tier?, lanes? }] — never a link. */
3391
3848
  async rooms() { return this._c.rooms() }
3392
3849
  /** A live {@link Space} for a room the vault holds — its key stays in the vault. */
@@ -3400,12 +3857,16 @@ export class VaultSession {
3400
3857
  if (it.lane) {
3401
3858
  // its Space forgotten (forget / dropRoom keep the lane): said by name, about THIS room — it threw not_in_vault naming
3402
3859
  // the Space's id (sync sweep 2026-11-03 #4)
3860
+ 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
3861
  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
3862
  const space = await this.openRoom(it.lane)
3405
3863
  // 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
3864
  try { const lane = await this._openLane(room, { space, resume }); lane._ownsSharedSpace = true; return lane } catch (e) { space.close(); throw e }
3407
3865
  }
3408
- return refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, resume, wb, lanes: it.lanes === true }))
3866
+ const sp = new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, resume, wb, lanes: it.lanes === true })
3867
+ if (it.tier === 'enclave') wb._enc.rooms.set(room, true)
3868
+ if (it.detachedLane) sp._detachedLane = true
3869
+ return refuseSpaceInVault(sp)
3409
3870
  }
3410
3871
  /** @private wb.openLane in a vault: the lane's ROOM ID (from rooms(), where `lane` names its Space) — a link is the
3411
3872
  * vault's to open. */
@@ -3423,6 +3884,7 @@ export class VaultSession {
3423
3884
  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
3885
  // a lane of the OTHER tier (the app links one): mirrored by this device, no bridge — as outside a vault (Witbitz.openLane)
3425
3886
  const crossTier = (it.tier === 'enclave') !== ((held.find((r) => r.room === space.room) || {}).tier === 'enclave')
3887
+ if (it.tier === 'enclave') wb._enc.rooms.set(room, true)
3426
3888
  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
3889
  }
3428
3890
  /** 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 +3909,9 @@ export class VaultSession {
3447
3909
  return r
3448
3910
  }
3449
3911
  /** 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) }
3912
+ 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
3913
  /** Sign in — the vault shows its sign-in screen; resolves { email } once signed in. */
3452
- async signIn(opts = {}) { return this._c.signIn(opts) }
3914
+ async signIn() { return this._c.signIn() }
3453
3915
  async signOut() { return this._c.signOut() }
3454
3916
  /** { signedIn, email, keyId } — who the vault has signed in (keyId: its session key's public id, what space.isMine compares). */
3455
3917
  async whoami() { return this._c.whoami() }
@@ -3461,20 +3923,25 @@ export class VaultSession {
3461
3923
  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
3924
  _event(d) {
3463
3925
  if (d?.ev === 'rooms' && Array.isArray(d.rooms)) {
3926
+ this._live = { ...this._live, rooms: d.rooms.map(r => ({ ...r })) }
3927
+ const held = new Set(d.rooms.map(r => r.room))
3928
+ const memory = this._wb._assistantMemory?.group
3929
+ if (memory) for (const room of memory.keys()) if (!held.has(room)) memory.delete(room)
3930
+ for (const r of d.rooms) if (r.tier === 'enclave') this._wb._enc.rooms.set(r.room, true)
3464
3931
  for (const lane of this._wb._openLanes || []) {
3465
3932
  const saved = d.rooms.find(r => r.room === lane.room)
3466
3933
  if (lane._sharedRoom && saved?.lane !== lane._sharedRoom) lane._detachShared()
3467
3934
  }
3468
3935
  }
3469
3936
  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)
3937
+ 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
3938
  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
3939
  else if (d && d.ev === 'account' && d.view) this._live = { ...this._live, account: d.view }
3473
3940
  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
3941
  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
- const set = this._fns.get(d.ev); if (set) for (const fn of set) { try { fn(d) } catch { /* the listener's own */ } }
3942
+ const set = this._fns.get(d.ev); if (set) for (const fn of [...set]) { try { fn(d) } catch { /* the listener's own */ } }
3476
3943
  }
3477
- async _create({ agent, tools, immediateTools, clientTools, agentReplies, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, safeMedia, lanes }) {
3944
+ async _create({ agent, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, usernames, safeMedia, lanes }) {
3478
3945
  const enc = tierIsEnclave(tier) // the vault attests the enclave and keeps the key; the page only asks
3479
3946
  const split = splitKeyChoice(key) // the vault makes it through its app-half function (startVault({ appShare: true }))
3480
3947
  const wb = this._wb
@@ -3490,13 +3957,16 @@ export class VaultSession {
3490
3957
  await wb._checkModel(model || (agent && agent.model))
3491
3958
  const gate = normAdmission(admission)
3492
3959
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
3960
+ applySkills(cfg, skills)
3493
3961
  if (Array.isArray(clientTools)) cfg.clientTools = clientTools
3494
3962
  if (agentReplies !== undefined) cfg.agentReplies = agentReplies
3495
3963
  cfg.region = region || wb._region
3496
3964
  if (direct !== undefined) cfg.direct = true
3965
+ if (usernames === false && gate?.admission === 'email') cfg.usernames = false
3497
3966
  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
3967
  if (lanes === true) cfg.lanes = true
3499
3968
  const { room } = await this._c.create(cfg, enc || split ? { ...(enc ? { enclave: true } : {}), ...(split ? { split: true } : {}) } : undefined)
3969
+ if (enc) wb._enc.rooms.set(room, true)
3500
3970
  const made = refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, wb, gated: !!gate, lanes: lanes === true }))
3501
3971
  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
3972
  if (direct !== undefined) await made.setReplyMode('ondemand').catch(() => {}) // as outside a vault: the assistant answers when @mentioned
@@ -3507,8 +3977,44 @@ export class VaultSession {
3507
3977
  /** `wb.connections` — the ACCOUNT's connections: credentials the standing Sentinel holds and spends on your behalf.
3508
3978
  * Attaching seals the secret to the attested Sentinel; the page keeps only an id, a label, a host and a `callKey`.
3509
3979
  * Nothing here touches a Space: grant one to a Space with `space.connections.grant(conn)`. */
3980
+ function checkConnectionId(id) {
3981
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(id)) throw sdkError('witbitz: invalid connection ID', 'invalid_argument')
3982
+ }
3510
3983
  class Connections {
3511
- constructor(wb) { this._wb = wb }
3984
+ constructor(wb) { this._wb = wb; this._pendingMemory = new Map() }
3985
+ _pendingFor(account) {
3986
+ if (this._vaultPending) return this._vaultPending
3987
+ const protect = this._wb.protect
3988
+ const name = id => 'witbitz:conn-pending:' + encodeURIComponent(account) + ':' + id
3989
+ const memory = this._pendingMemory
3990
+ const persistent = !!protect && (!('_storage' in protect) || !!protect._storage)
3991
+ const load = id => persistent ? protect.load(name(id)) : memory.get(name(id))
3992
+ const drop = async id => { if (persistent) await protect.remove?.(name(id)); memory.delete(name(id)) }
3993
+ return {
3994
+ durable: true, load, drop,
3995
+ keep: async (id, rec) => {
3996
+ const value = { ...rec, account, at: Date.now() }
3997
+ if (persistent) {
3998
+ await protect.save(name(id), value)
3999
+ if ((await load(id))?.callKey !== rec.callKey) throw sdkError('witbitz: the connection key could not be saved', 'storage_unavailable')
4000
+ } else memory.set(name(id), value)
4001
+ },
4002
+ }
4003
+ }
4004
+ async recover(id) {
4005
+ const wb = this._wb
4006
+ wb._auth()
4007
+ checkConnectionId(id)
4008
+ const account = await wb._account(), pending = this._pendingFor(account)
4009
+ const record = await pending.load(id)
4010
+ if (!record?.callKey || record.account !== account) return null
4011
+ const listed = (await this.list()).find(c => c.id === id)
4012
+ if (!listed || account !== await wb._account()) return null
4013
+ // A JOB AGENT'S TRIGGER comes back as `attach` gave it (side sweep 2026-11-28: the listing names the path under `rules` and holds no
4014
+ // job settings, so a recovered webhook granted to a Space could neither format a job nor ask the agent to report back)
4015
+ const path = listed.sign && Array.isArray(listed.rules?.paths) && listed.rules.paths.length === 1 ? listed.rules.paths[0] : ''
4016
+ return { ...listed, id, label: listed.label || record.label || '', host: listed.host || record.host || '', account, callKey: record.callKey, ...(path ? { webhook: path } : {}), ...(path && record.job ? { job: record.job } : {}) }
4017
+ }
3512
4018
  /** The app's service/outside-agent picker data, without credentials. A builder draws its own picker. */
3513
4019
  catalog({ category } = {}) {
3514
4020
  if (category !== undefined && typeof category !== 'string') throw sdkError('witbitz: catalog category must be a string', 'invalid_argument')
@@ -3523,7 +4029,7 @@ class Connections {
3523
4029
  }
3524
4030
  const result = await spacesUsingConnection(id, [...byId.values()], async room => {
3525
4031
  const link = await wb._openLink(byId.get(room).link)
3526
- if (link.room !== room) throw new Error('room link mismatch')
4032
+ if (link.room !== room) throw sdkError('room link mismatch', 'invalid_link')
3527
4033
  return wb._client.getConfig(room, link.mk, { plainMark: true })
3528
4034
  })
3529
4035
  if (wb._archiveGeneration !== generation || (wb.backup._s?.master || null) !== master) throw sdkError('the account changed', 'account_changed')
@@ -3558,7 +4064,10 @@ class Connections {
3558
4064
  const wb = this._wb, auth = wb._auth()
3559
4065
  const account = await wb._account()
3560
4066
  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 } : {}) })
4067
+ // the job's settings are kept with the pending key, so `recover` after a lost reply gives them back (side sweep 2026-11-28)
4068
+ const jobKept = job ? roomJob(job) : null, pend = this._pendingFor(account)
4069
+ const pendingStore = jobKept ? { ...pend, keep: (id, rec) => pend.keep(id, { ...rec, job: jobKept }) } : pend
4070
+ const out = await attachConnection({ post: wb._sentinelPost(), pendingStore, 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
4071
  const j = out.webhook && job ? roomJob(job) : null
3563
4072
  return { ...out, account, ...(j ? { job: j } : {}) }
3564
4073
  }
@@ -3581,10 +4090,14 @@ class Connections {
3581
4090
  * keep offering a connection that answers 404 (sync sweep, 10-16 #9). → the Sentinel's answer + `removedFrom` (a count). */
3582
4091
  async detach(id, { spaces = [] } = {}) {
3583
4092
  const wb = this._wb, cid = String(id || '')
4093
+ const account = await wb._account()
4094
+ const removed = await wb.a2a._disconnectConnection(cid, this._bindingFor?.(cid, account))
4095
+ if (account !== await wb._account()) throw sdkError('Account changed during disconnect', 'account_changed')
3584
4096
  const out = await detachConnection({ post: wb._sentinelPost(), auth: wb._auth(), id: cid })
4097
+ await this._pendingFor(account).drop(cid)
3585
4098
  let removedFrom = 0
3586
4099
  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 }
4100
+ return { ...(out || {}), ...(removed.length ? { removed } : {}), removedFrom }
3588
4101
  }
3589
4102
 
3590
4103
  // ── CONNECT TO A BUILDER'S OAUTH APP (https://witbitz.chat/docs/connections.md). Two calls around the consent screen. The PKCE
@@ -3612,7 +4125,8 @@ class Connections {
3612
4125
  const dk = await this._dispKey()
3613
4126
  const disp = dk && label ? await sealDisp(dk, id, { label: String(label).trim().slice(0, 80) }).catch(() => '') : ''
3614
4127
  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 })
4128
+ const account = await wb._account()
4129
+ const r = await postWithPendingKey(post, { op: 'sentinel', sentinel: { mode: 'oauthfinish', sealed }, ...auth }, id, { label, host, callKey, account, at: Date.now() }, this._pendingFor(account))
3616
4130
  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
4131
  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
4132
  }
@@ -3637,15 +4151,16 @@ class Connections {
3637
4151
  * its host needs no declaration (connections.js attachMcp; it was filed under the tenant and refused — docs sync, 2026-11-22). */
3638
4152
  async attachMcp ({ url, label, token = '' } = {}) {
3639
4153
  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 })
4154
+ 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
4155
  return { ...out, account, mcp: true }
3642
4156
  }
3643
4157
  /** Finish a server's sign-in with the `state` and `code` your callback received. → a connection, as `attachMcp`. */
3644
4158
  async finishMcp ({ state, code, label, host } = {}) {
3645
4159
  const wb = this._wb, auth = wb._auth()
3646
4160
  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 }
4161
+ const account = await wb._account()
4162
+ 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 })
4163
+ return { ...out, account, mcp: true }
3649
4164
  }
3650
4165
  /** The tools an MCP connection offers, as the server describes them (asked through the Sentinel). → `{ tools, server, truncated }`. */
3651
4166
  async mcpTools (id) { const wb = this._wb; return listMcpTools({ post: wb._sentinelPost(), auth: wb._auth(), id: String(id || '') }) }
@@ -3659,7 +4174,7 @@ class SpaceConnections {
3659
4174
  async grants() {
3660
4175
  const sp = this._space
3661
4176
  if (sp._wb?.vault?._c) return sp._wb.vault._c.roomAccount(sp.room, 'connections', 'grants')
3662
- const cfg = await sp._gateConfig({ plainMark: true })
4177
+ const cfg = await sp._gateConfig({ fresh: true, plainMark: true })
3663
4178
  const wb = sp._wb
3664
4179
  const [account, list] = await Promise.all([wb._account().catch(() => ''), wb.connections.list().catch(() => null)])
3665
4180
  const known = Array.isArray(list) ? new Set(list.map(c => c.id)) : null
@@ -3685,7 +4200,7 @@ class SpaceConnections {
3685
4200
  let mcp
3686
4201
  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
4202
  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) })
4203
+ const listed = await listGrantTools(c.host, () => listMcpTools({ post: sp._wb._sentinelPost(), auth: sp._wb._auth(), id: String(c.id) }))
3689
4204
  const all = listed.tools.map(roomTool).filter(Boolean)
3690
4205
  const rec = recommendedChoice(all)
3691
4206
  const chosen = new Set(Array.isArray(tools) ? tools.map(String) : rec.chosen)
@@ -3702,14 +4217,44 @@ class SpaceConnections {
3702
4217
  const { mcp: _flag, ...entry } = c
3703
4218
  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
4219
  if (!r || r.status !== 200) throw refused('recording the connection in this Space', r)
4220
+ sp._gateCfg = null
3705
4221
  return { granted: String(c.id), ...(mcp ? { tools: mcp.tools.map((t) => t.name), auto: mcp.auto } : {}) }
3706
4222
  }
3707
4223
  /** Drop a connection from THIS Space only; it stays attached to the account. */
3708
- async revoke(id, { from } = {}) {
4224
+ async revoke(id, { from, includeAssistant = false } = {}) {
4225
+ const parent = this._space, wb = parent._wb
4226
+ if (includeAssistant) {
4227
+ const generation = wb?._archiveGeneration
4228
+ if (!wb || parent._memoryOwner !== generation) throw sdkError('Reopen this Space in the current account', 'account_changed')
4229
+ let complete = !!wb._heldLaneRooms
4230
+ if (wb.account.enabled) {
4231
+ try { complete = !!(await wb.account.sync())?.ok } catch { complete = false }
4232
+ if (generation !== wb._archiveGeneration) throw sdkError('The account changed', 'account_changed')
4233
+ }
4234
+ const saved = new Map((wb.account.rooms || []).filter(r => !r.detachedLane && r.shared === parent.room).map(r => [r.room, r]))
4235
+ const live = new Map([...(wb._archiveHandles || []), ...(wb._openLanes || [])].filter(sp => sp._sharedRoom === parent.room &&
4236
+ !sp._stopped && !sp._detachedLane && sp._memoryOwner === parent._memoryOwner).map(sp => [sp.room, sp]))
4237
+ const ids = new Set([parent.room, ...saved.keys(), ...live.keys(), ...(wb._heldLaneRooms?.(parent.room) || [])])
4238
+ const unchecked = [], removedFrom = []
4239
+ for (const room of ids) {
4240
+ if (wb._archiveGeneration !== generation) throw sdkError('The account changed', 'account_changed')
4241
+ let sp
4242
+ try {
4243
+ sp = room === parent.room ? parent : live.get(room) || (wb._scopedRoom ? wb._scopedRoom(room) : await wb.openSpace(saved.get(room).link))
4244
+ if (sp.room !== room || wb._archiveGeneration !== generation) throw sdkError('Room or account changed', 'account_changed')
4245
+ await sp.connections.revoke(id, { from })
4246
+ removedFrom.push(room)
4247
+ } catch { unchecked.push(room) }
4248
+ finally { if (sp && sp !== parent && !live.has(room)) sp.close() }
4249
+ }
4250
+ if (unchecked.length) throw Object.assign(sdkError('Some Space grants could not be revoked', 'partial_revoke'), { unchecked, removedFrom })
4251
+ return { revoked: String(id), removedFrom, incomplete: !complete }
4252
+ }
3709
4253
  from = this._space._who(from)
3710
4254
  const sp = this._space
3711
4255
  const r = await sp._client.setConfig(sp.room, sp._mk, { connections: { remove: String(id || '') } }, from)
3712
4256
  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)
4257
+ sp._gateCfg = null
3713
4258
  return { revoked: String(id) }
3714
4259
  }
3715
4260
  }
@@ -3718,13 +4263,14 @@ class SpaceConnections {
3718
4263
  * STATE (`wb.siri.state`) holds the inbox private keys — without it a drop can never be opened — so persist it as
3719
4264
  * you persist the session, and hand it back as `new Witbitz({ siri: state })`. */
3720
4265
  class SiriAccount {
3721
- constructor(wb) { this._wb = wb }
4266
+ constructor(wb) { this._wb = wb; this.onState = null }
4267
+ _changed() { this.onState?.(this.state) }
3722
4268
  /** JSON-safe state to persist. */
3723
4269
  get state() { return JSON.parse(JSON.stringify(this._wb._siri)) }
3724
4270
  /** Adopt persisted state. */
3725
4271
  restore(state) { this._wb._siri = siriStateOf(state); return this }
3726
4272
  /** 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 } }
4273
+ get shortcut() { return { key: this._wb._siri.pendingRotation ? null : this._wb._siri.token || null, endpoint: SIRI_ENDPOINT } }
3728
4274
  /** What the Sentinel holds for this account (aliases, counts) — as it reports it. */
3729
4275
  async status() {
3730
4276
  const wb = this._wb, auth = wb._auth()
@@ -3733,16 +4279,29 @@ class SiriAccount {
3733
4279
  return r
3734
4280
  }
3735
4281
  /** 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 }) }
4282
+ async sync() {
4283
+ const result = await this._change(async st => {
4284
+ if (!st.token) return NO_SIRI_CHANGE
4285
+ const remote = await this.status()
4286
+ if (remote.configured && !siriAliasesDiffer(st.rooms, remote, st.defaultRoom || '')) return NO_SIRI_CHANGE
4287
+ return true
4288
+ })
4289
+ return { synced: result === true }
4290
+ }
4291
+ async rotateKey() { return this._change((st, rotation) => { if (!rotation) st.token = newSiriKey(); return st.token }) }
3737
4292
  /** Turn Siri off everywhere for this account: the Sentinel forgets the record; the local state is cleared. */
3738
4293
  // 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
4294
  // 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
4295
  async revoke() {
4296
+ const wb = this._wb, generation = wb._archiveGeneration, auth = wb._auth()
4297
+ const check = () => { if (generation !== wb._archiveGeneration) throw sdkError('Account changed during Siri deletion', 'account_changed') }
3741
4298
  const run = async () => {
3742
- const wb = this._wb, auth = wb._auth()
4299
+ check()
3743
4300
  const r = await wb._sentinelPost()({ op: 'sentinel', sentinel: { mode: 'sirirevoke' }, ...auth })
3744
4301
  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)
4302
+ check()
4303
+ wb._siri = siriStateOf({ rev: Math.max(Date.now(), (wb._siri.rev || 0) + 1) })
4304
+ this._changed()
3746
4305
  return r
3747
4306
  }
3748
4307
  const p = (this._q || Promise.resolve()).then(run, run)
@@ -3757,15 +4316,62 @@ class SiriAccount {
3757
4316
  // overwritten (sync sweep 2026-11-13 #2: the next keep pass then stamped the other devices' Spaces `gone` everywhere): the
3758
4317
  // change is made again on top of what landed and that is pushed — at most a few times, then the latest state stands.
3759
4318
  _change(fn) {
4319
+ const generation = this._wb._archiveGeneration
3760
4320
  const run = async () => {
4321
+ if (generation !== this._wb._archiveGeneration) throw sdkError('Account changed before Siri setup', 'account_changed')
3761
4322
  let out
3762
4323
  for (let i = 0; i < 4; i++) {
3763
- const base = this._wb._siri
4324
+ const account = await this._wb._account(), base = this._wb._siri
3764
4325
  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 }
4326
+ const pending = next.pendingRemovals || []
4327
+ const priorSetup = next.pendingSetup, rotation = next.pendingRotation
4328
+ delete next.pendingRotation
4329
+ delete next.pendingSetup
4330
+ if (priorSetup) {
4331
+ if (!next.token) next.token = priorSetup.token
4332
+ if (next.token === priorSetup.token) {
4333
+ for (const [id, inbox] of Object.entries(priorSetup.rooms)) if (!next.rooms[id]) next.rooms[id] = inbox
4334
+ if (!next.defaultRoom && priorSetup.defaultRoom) next.defaultRoom = priorSetup.defaultRoom
4335
+ }
4336
+ }
4337
+ delete next.pendingRemovals
4338
+ for (const room of pending) {
4339
+ delete next.rooms[room]
4340
+ if (next.defaultRoom === room) next.defaultRoom = ''
4341
+ }
4342
+ if (rotation) next.token = rotation.to
4343
+ out = await fn(next, rotation)
4344
+ if (out === NO_SIRI_CHANGE && !pending.length && !priorSetup && !rotation) return out
4345
+ if (generation !== this._wb._archiveGeneration || account !== await this._wb._account()) throw sdkError('Account changed during Siri setup', 'account_changed')
4346
+ const removed = Object.keys(base.rooms).filter(room => !next.rooms[room])
4347
+ const added = Object.entries(next.rooms).filter(([id]) => !base.rooms[id])
4348
+ const stageLocal = !this._stageInbox && (removed.length || added.length || priorSetup || next.token !== base.token) && this._wb._siri === base
4349
+ if (stageLocal) {
4350
+ if (next.token !== base.token && (base.token || !added.length)) base.pendingRotation = { from: base.token, to: next.token }
4351
+ if (removed.length) base.pendingRemovals = removed
4352
+ if (added.length) base.pendingSetup = siriStateOf({ token: next.token, rooms: Object.fromEntries(added), defaultRoom: next.defaultRoom })
4353
+ else delete base.pendingSetup
4354
+ this._changed()
4355
+ }
4356
+ const finish = await this._stageInbox?.(next)
4357
+ try { await this._push(next) } catch (e) {
4358
+ if (e.definiteRefusal || (e.status >= 400 && e.status < 500)) {
4359
+ finish?.(false)
4360
+ if (stageLocal && this._wb._siri === base) {
4361
+ if (rotation) base.pendingRotation = rotation
4362
+ else delete base.pendingRotation
4363
+ if (priorSetup) base.pendingSetup = priorSetup
4364
+ else delete base.pendingSetup
4365
+ if (pending.length) base.pendingRemovals = pending
4366
+ else delete base.pendingRemovals
4367
+ this._changed()
4368
+ }
4369
+ }
4370
+ throw e
4371
+ }
4372
+ if (generation !== this._wb._archiveGeneration || account !== await this._wb._account()) throw sdkError('Account changed during Siri setup', 'account_changed')
4373
+ finish?.(true)
4374
+ if (this._wb._siri === base) { this._wb._siri = next; this._changed(); return out === NO_SIRI_CHANGE ? true : out }
3769
4375
  }
3770
4376
  throw sdkError('witbitz: the Siri state kept changing while it was being saved — try again', 'siri_busy')
3771
4377
  }
@@ -3783,7 +4389,7 @@ class SiriAccount {
3783
4389
  const { nonce, key } = await attestStandingSentinel({ post, auth, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3784
4390
  const sealed = await sealToEnclave(key, nonce, rec)
3785
4391
  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' }))
4392
+ 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
4393
  return r
3788
4394
  }
3789
4395
  }
@@ -3796,25 +4402,49 @@ class SpaceSiri {
3796
4402
  /** Enable Siri for this Space: the word you will say ("groceries"), optionally the default for anything said
3797
4403
  * without an alias. Mints the Shortcut key on the first enable and an inbox keypair for this Space, pushes the
3798
4404
  * account's record to the Sentinel. → `{ key, endpoint, alias }` — the key is what the Shortcut sends. */
3799
- async enable({ alias, label = '', makeDefault = false } = {}) {
4405
+ _assistantRoom() {
4406
+ const sp = this._space, wb = this._wb()
4407
+ if (wb._siriLane) return wb._siriLane(sp.room)
4408
+ if (sp._memoryOwner !== wb._archiveGeneration) throw sdkError('Reopen this Space in the current account', 'account_changed')
4409
+ 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))
4410
+ if (open) return open.room
4411
+ const backupOwner = wb._siriBackupOwners?.get(wb.backup._s) || wb.backup._s?.email
4412
+ if (backupOwner && backupOwner !== wb._session?.email) return null
4413
+ return wb.account.rooms.find(r => !r.detachedLane && r.shared === sp.room)?.room
4414
+ }
4415
+ async enable({ alias, label = '', makeDefault = false, includeAssistant = false } = {}) {
3800
4416
  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')
4417
+ if (sp.temporary) throw sdkError('Temporary Spaces cannot receive Siri captures', 'temporary_room')
4418
+ const requested = normSiriAlias(alias)
4419
+ if (alias !== undefined && !requested) throw sdkError('witbitz: an alias is needed — the word you will say to Siri', 'invalid_argument')
4420
+ if (/[,:;]/.test(requested)) throw sdkError('witbitz: an alias cannot contain , : or ;', 'invalid_argument')
3804
4421
  return wb.siri._change(async (st) => { // kept only once the Sentinel took it (pass 9, K#5)
4422
+ const a = requested || st.rooms[sp.room]?.alias || uniqueAlias(label || sp.title || 'Space', new Set(Object.values(st.rooms).map(r => r.alias)))
3805
4423
  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
4424
  if (!st.token) st.token = newSiriKey()
3807
4425
  const cur = st.rooms[sp.room]
3808
4426
  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
4427
  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() } }
4428
+ const lane = includeAssistant && this._assistantRoom()
4429
+ if (lane && !st.rooms[lane]) {
4430
+ const taken = new Set(Object.values(st.rooms).map(r => r.alias))
4431
+ const assistantAlias = uniqueAlias(a.slice(0, 22) + ' assistant', taken), kp = await genRecipientKey()
4432
+ st.rooms[lane] = { alias: assistantAlias, label: (label || a) + ' · assistant', pub: { x: kp.publicJwk.x, y: kp.publicJwk.y }, priv: kp.privateJwk, at: Date.now() }
4433
+ }
3810
4434
  if (makeDefault) st.defaultRoom = sp.room; else if (st.defaultRoom === sp.room) st.defaultRoom = ''
3811
4435
  return { key: st.token, endpoint: SIRI_ENDPOINT, alias: a }
3812
4436
  })
3813
4437
  }
3814
4438
  /** 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() {
4439
+ async disable({ includeAssistant = false } = {}) {
3816
4440
  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 })
4441
+ const targets = [room, includeAssistant && this._assistantRoom()].filter(Boolean)
4442
+ const r = await wb.siri._change(st => {
4443
+ if (!targets.some(id => st.rooms[id])) return NO_SIRI_CHANGE
4444
+ for (const id of targets) delete st.rooms[id]
4445
+ if (targets.includes(st.defaultRoom)) st.defaultRoom = ''
4446
+ return true
4447
+ })
3818
4448
  return { disabled: r === true }
3819
4449
  }
3820
4450
  /** Collect: pull the account's drops, open the ones for THIS Space with its inbox key, post each as you (🎙-marked),