@witbitz/sdk 4.4.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 (79) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +15 -0
  3. package/accountErase.js +9 -3
  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/awsKey.js +3 -1
  11. package/backupRecord.js +3 -0
  12. package/codeAttachments.js +1 -0
  13. package/codeCache.js +27 -3
  14. package/codeCloud.js +2 -0
  15. package/codeComputers.js +8 -0
  16. package/codeSent.js +43 -2
  17. package/codeTransport.js +24 -5
  18. package/connections.js +21 -3
  19. package/decrypt.html +69 -9
  20. package/eraseFile.js +15 -0
  21. package/idbSeal.js +5 -2
  22. package/inviteReceive.js +44 -0
  23. package/inviteSend.js +8 -2
  24. package/l1-worker-src.js +1 -1
  25. package/l1-worker.js +30 -14
  26. package/laneAssociation.js +11 -1
  27. package/laneLinkCore.js +9 -0
  28. package/ledgerView.js +30 -4
  29. package/manifest.json +78 -72
  30. package/offlineBundle.js +21 -0
  31. package/package.json +8 -2
  32. package/protectedLocal.js +34 -11
  33. package/reactionHolders.js +86 -0
  34. package/roomIntake.js +324 -0
  35. package/roomRoster.js +9 -2
  36. package/scheduleNext.js +60 -0
  37. package/sdkA2A.js +46 -8
  38. package/sdkAccount.js +71 -14
  39. package/sdkAccountDoc.js +3 -3
  40. package/sdkAccountSections.js +58 -18
  41. package/sdkAgui.js +33 -6
  42. package/sdkBackup.js +21 -6
  43. package/sdkBackupV2.js +15 -3
  44. package/sdkCloudDevice.js +12 -3
  45. package/sdkComputers.js +118 -17
  46. package/sdkDictation.js +1 -1
  47. package/sdkErase.js +3 -1
  48. package/sdkExports.js +15 -6
  49. package/sdkInvitations.js +4 -2
  50. package/sdkKeptAgent.js +19 -3
  51. package/sdkKeptIntake.js +100 -0
  52. package/sdkLaneLink.js +5 -6
  53. package/sdkRekey.js +72 -5
  54. package/sdkSchedules.js +8 -1
  55. package/sdkSpeech.js +14 -1
  56. package/sdkTemporaryRooms.js +2 -1
  57. package/sdkTurn.js +12 -4
  58. package/sharedViews.js +17 -1
  59. package/siri.js +29 -5
  60. package/spaceClient.js +96 -12
  61. package/spaceExport.js +50 -5
  62. package/spaceFork.js +15 -7
  63. package/spaceTemplates.js +2 -2
  64. package/speechOut.js +17 -3
  65. package/store.js +51 -13
  66. package/sw-notif-core.js +2 -1
  67. package/tapTrail.js +58 -0
  68. package/usageReceipts.js +12 -5
  69. package/vault-core.js +90 -16
  70. package/vault-kit.mjs +2 -2
  71. package/vault-screens.js +25 -11
  72. package/vaultAtRest.js +3 -2
  73. package/vaultCoreLock.js +3 -1
  74. package/vaultCorePush.js +58 -7
  75. package/vaultWorkerHost.js +9 -3
  76. package/witbitz-admin.d.ts +3 -0
  77. package/witbitz-admin.mjs +10 -10
  78. package/witbitz-sdk.d.ts +59 -23
  79. package/witbitz-sdk.js +271 -64
package/witbitz-sdk.js CHANGED
@@ -46,7 +46,7 @@ import { receiptFor } from './usageReceipts.js' // a turn's usage receipt addres
46
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)
47
47
  export { aguiRun, aguiHistory, aguiAgent }
48
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)
49
- 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)
50
50
  import { Dictation, voiceForDictation } from './sdkDictation.js' // wb.dictation(): press-to-talk, the mic straight to Tinfoil's realtime enclave
51
51
  import { Protect } from './sdkProtect.js' // wb.protect: what the app keeps on the device, sealed under a passkey-derived key
52
52
  import { boxesHash, bareEC, jkey } from './spaceFork.js' // the membership fork's notice format, shared with the app
@@ -87,10 +87,11 @@ import { openRoomStream } from './roomStreamClient.js'
87
87
  import { makeEmailPost, emailStart, emailVerify, emailRefresh } from './emailSignIn.js' // the email-code protocol the vault and the Spaces app use
88
88
  import { answerDeviceCall } from './deviceCall.js' // one way to answer a device call, shared with the Spaces app
89
89
  import { LANE_PERSONA, LANE_AGENT_NAME, inheritToolsFrom, laneInherits, gatedStub } from './laneConfig.js'
90
- import { renderSharedViews, viewsNamedIn, SHARED_VIEWS_DOC } from './sharedViews.js'
90
+ import { renderSharedViews, viewsNamedIn, viewFromRead, isMapView, SHARED_VIEWS_DOC } from './sharedViews.js'
91
91
  import { receiptOf } from './sealedReceipt.js' // a verified room's sealedProof, computed by the member
92
92
  import { replyQuote } from './replyQuote.js' // the reply quote — one rule with the app's reply strip
93
- import { makeLedgerView, needsTailResync, REACTION_RESYNC_TAIL, entryKeyOf, readAllPages } from './ledgerView.js' // how the Spaces app merges a room's entries
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
94
95
  import { roomInviteFlags, applySkills, roomEmbed } from './roomEmbed.js'
95
96
  import { turnVerdict, QUEUE_RETRY_MS, QUEUE_MAX_TRIES, CONTINUATION_WINDOW_MS } from './turnVerdict.js' // the send hold + answer reading the Spaces app uses
96
97
  /** A turn's answer with `ok` always a boolean: posted / silent / pending → true; anything with an error, or busy, refused,
@@ -114,10 +115,11 @@ import { roomRegion, regionCode, DEFAULT_REGION, newRoomId } from './regions.js'
114
115
 
115
116
  // The room's reply mode and model pick: ONE module with the Spaces app (roomSettings.js — the same names, the same sealed
116
117
  // `agentmode` and `model` docs), so the SDK and the app are one setting, not two that drift.
117
- 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'
118
119
  import { TOOLRULES_DOC, RULE_VALUES, toolRulesDocOf, rulesFromDoc } from './toolRules.js' // which tools run on their own (space.toolRules)
119
120
  import { rosterParticipants } from './rosterCount.js' // the server's count (agent/rosterCount.mjs) — replyMode()'s default
120
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)
121
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
122
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)
123
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.
@@ -179,7 +181,10 @@ function healingClient(c, heal, keys = null) {
179
181
  // A poll refusal no retry cures (pollVerdict 'gated' with these reasons): the poll slows to HELD_POLL_MS (sync sweep, 2026-10-10).
180
182
  const PERMANENT_REFUSALS = new Set(['not_on_list'])
181
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')))
182
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
183
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
184
189
  // A quote: replyQuote.js, the app's reply strip's own rule; no `excerpt` when there is nothing to show.
185
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
@@ -194,7 +199,7 @@ const perTurn = (instructions) => (typeof instructions === 'string' && instructi
194
199
  /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
195
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)
196
201
  export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
197
- export const SDK_VERSION = '4.4.0'
202
+ export const SDK_VERSION = '4.5.0'
198
203
  // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
199
204
  const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
200
205
  /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
@@ -261,9 +266,11 @@ function mirrorBy(room, e) {
261
266
  async function withBytes(from, list) {
262
267
  if (!Array.isArray(list) || !list.length) return undefined
263
268
  return Promise.all(list.map(async (a) => {
264
- if (!a || typeof a !== 'object' || (typeof a.b64 === 'string' && a.b64)) return a
269
+ if (!a || typeof a !== 'object') return a
265
270
  const { ref, parts, size, ...rest } = a
266
- if (!ref && !parts) return rest
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
267
274
  const key = ref || (Array.isArray(parts) ? parts.join(',') : '')
268
275
  const misses = _copyMisses.get(from) || new Map()
269
276
  let o = null
@@ -279,8 +286,15 @@ async function withBytes(from, list) {
279
286
  }
280
287
  const COPY_TRIES = 3
281
288
  const _copyMisses = new WeakMap() // per source Space, this page's memory only
282
- const withMedia = (msg, images, files) => {
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 } = {}) => {
283
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`)
284
298
  return { ...msg, ...(im ? { images: im } : {}), ...(fl ? { files: fl } : {}) }
285
299
  }
286
300
  /** Throws `limit_exceeded` for a list of actions OFFERED TO ONE TURN that the server would cut or drop. */
@@ -659,7 +673,14 @@ export class Witbitz {
659
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
660
674
  * is REFUSED (code user_token_invalid / user_key_unavailable), never billed to you. */
661
675
  _forgetVoice() { this._dictation?._resetPayer(); this._speech?._resetPayer() }
662
- useUserToken(token) { if (this._userToken !== (token || null)) this._forgetVoice(); this._userToken = token || null; return this }
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
+ }
663
684
 
664
685
  /** The signed-in session `{ email, idToken, exp, sign }`, or null. JSON-safe: persist it and pass it back as
665
686
  * `new Witbitz({ session })`. It carries a private signing key — keep it where you keep secrets. */
@@ -668,6 +689,7 @@ export class Witbitz {
668
689
  useSession(session) {
669
690
  const next = sessionOf(session)
670
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))
671
693
  if (this._session?.email !== next?.email || scope(this._session) !== scope(next)) {
672
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
673
695
  // (nobody → an account) leaves no account: bumped all the same, every Space opened before signing in — the usual order on a
@@ -677,7 +699,11 @@ export class Witbitz {
677
699
  this._forgetVoice()
678
700
  if (this._session) { this._forgetSiriAccount(); this.a2a?._resetAccount() }
679
701
  }
702
+ const prev = this._session
680
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 { /* */ }
681
707
  if (next?.idToken) this._prefetchIdentity()
682
708
  return this
683
709
  }
@@ -769,7 +795,7 @@ export class Witbitz {
769
795
  }
770
796
  _emailPost() { return makeEmailPost(this._loginBase, { fetchImpl: (...a) => this._fetch(...a) }) }
771
797
  /** Forget the session on this client (the token simply expires server-side). */
772
- signOut() { this.a2a?._resetAccount(); this._forgetSiriAccount(); this._forgetVoice(); 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 }
773
799
 
774
800
  /** Press-to-talk: `const mic = wb.dictation(); await mic.start({ onPartial }); const text = await mic.stop()`. The
775
801
  * microphone streams straight from the page to Tinfoil's confidential realtime enclave — never through Witbitz — on a
@@ -1017,13 +1043,13 @@ export class Witbitz {
1017
1043
  if (!sp || sp._wb !== this || sp._stopped || !sp.shareLink) throw sdkError('select open Spaces from this SDK client', 'invalid_argument')
1018
1044
  selected.set(sp.room, { room: sp.room, link: sp.shareLink, title: sp.title, held: sp })
1019
1045
  }
1020
- return saveAccountArchive([...selected.values()], async (r, keysOnly) => {
1046
+ return saveAccountArchive([...selected.values()], async (r, keysOnly, attachments) => {
1021
1047
  const { room, mk } = r.held?._mk ? { room: r.room, mk: r.held._mk } : await this._openLink(r.link)
1022
1048
  if (room !== r.room) throw sdkError('witbitz: a saved link opens another Space', 'wrong_room')
1023
1049
  if (keysOnly) return { key: mk }
1024
- const saved = await this._client.exportSealed(room, mk)
1050
+ const saved = await this._client.exportSealed(room, mk, { attachments }) // + the stored attachments, sealed (sdkExports.js)
1025
1051
  if (saved?.status !== 200) throw sdkError('witbitz: this Space\u2019s history could not be read just now', 'unavailable')
1026
- return { key: mk, ledger: saved.sealed, count: saved.count }
1052
+ return { key: mk, ledger: saved.sealed, count: saved.count, attachments: saved.attachments }
1027
1053
  }, recoveryKeys === true, () => this._archiveGeneration === generation && (this.backup._s?.master || null) === (backup?.master || null), destination)
1028
1054
  }
1029
1055
  async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, usernames, safeMedia, lanes, owner } = {}) {
@@ -1062,6 +1088,9 @@ export class Witbitz {
1062
1088
  const enc = tierIsEnclave(tier)
1063
1089
  const split = splitKeyChoice(key)
1064
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 }
1065
1094
  await this._checkModel(model || agent.model)
1066
1095
  const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
1067
1096
  applySkills(cfg, skills)
@@ -1094,7 +1123,8 @@ export class Witbitz {
1094
1123
  const sp = new Space(this._client, { room, mk, link: enc ? markEncLink(link) : link, viewer: this._viewer, wb: this, gated: !!gate, split })
1095
1124
  sp.safeMedia._learn(safeMedia === true, 0) // a new room's setting is what it was made with
1096
1125
  if (sp.temporary) await this.temporaryRooms._remember(sp, temporaryScope, { days: lapseDays, title: temporary?.title })
1097
- const made = String(room).startsWith('tmp-') ? sp : this._backedUp(sp) // a temporary room is never in the account backup (it is wiped), as the app's
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
1098
1128
  if (direct !== undefined) await made.setReplyMode('ondemand').catch(() => {}) // the assistant is in the chat and answers when @mentioned, as in the app
1099
1129
  return made // an enclave room's link says so, or a fresh client cannot know (see ENC_MARK)
1100
1130
  }
@@ -1401,7 +1431,7 @@ export class Space {
1401
1431
  this._view.apply([m]) // a live poll's overlap with what you already had is never re-pushed or re-emitted
1402
1432
  }
1403
1433
  }
1404
- 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) }
1405
1435
  // the SAFE COPIES the poll kept beside their photos (never messages): a resumed Space polls only what is new, so without them
1406
1436
  // every older photo had no copy (sync sweep backlog P7)
1407
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) }
@@ -1548,12 +1578,15 @@ export class Space {
1548
1578
  on(event, cb, { replay = true } = {}) {
1549
1579
  // `{ replay: false }` on 'message': only what arrives AFTER the room's history was read (sdk-roadmap item 6) — for
1550
1580
  // notifications, analytics and side effects, which must not fire once per old message on every open.
1551
- 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 })
1552
1584
  ;(this._subs[event] ||= []).push(fn)
1553
1585
  if (event === 'a2a') { const agents = this.a2a; Promise.resolve().then(() => agents._flushHeld()) }
1554
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
1555
1587
  // Returns an UNSUBSCRIBE function. It still chains (`.on(…).on(…)`), because on() returned the space until 2026-10-05.
1556
- 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 }
1557
1590
  return Object.assign(off, { on: (...a) => this.on(...a), off: (...a) => this.off(...a) })
1558
1591
  }
1559
1592
  /** Remove a listener added with on(). The last 'proposal' listener stops the proposals poll that on() started. */
@@ -1562,9 +1595,12 @@ export class Space {
1562
1595
  this._subs[event] = cb === undefined ? [] : l.filter((x) => x !== cb && x._orig !== cb) // no cb: every listener for the event
1563
1596
  // the proposals poll runs while anyone listens for 'proposal' OR 'proposals' — and on a Lane always (pass 5, V#14: the last
1564
1597
  // 'proposal' listener stopped a Lane's always-on poll, and the last 'proposals' listener never stopped a Space's)
1565
- 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)
1566
1599
  return this
1567
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
+ }
1568
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 */ } } }
1569
1605
 
1570
1606
  /** Post a message from a member. The agent decides whether to answer and does so on its OWN turn — the reply (and
@@ -1644,7 +1680,7 @@ export class Space {
1644
1680
  if (extra.defs.length) toolOpts = { clientTools: extra.defs, clientGuidance: extra.guidance }
1645
1681
  }
1646
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)
1647
- const msg = withMedia({ from, ...(_skill ? { mcp: _skill } : { text: String(text) }), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files) // `images` ≤ 4, `files` ≤ 2 — see LIMITS
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
1648
1684
  const rt = replyRef(replyTo); if (rt) msg.replyTo = rt // a reply quotes the message it answers, as the app's do
1649
1685
  await this.safeMedia._prepare(msg) // a Safe media room: its photos' and PDFs' safe copies start now, and go beside it once stored
1650
1686
  const opts = { ...(await this._turnOpts(mode)), ...toolOpts, ...perTurn(instructions), ...stopOpt(stopKey), ...promptOpt(showPrompt) }
@@ -1689,6 +1725,8 @@ export class Space {
1689
1725
  try { r = await send() } catch { r = null }
1690
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' } } }
1691
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 || {} }
1692
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')) }
1693
1731
  }
1694
1732
 
@@ -1746,6 +1784,9 @@ export class Space {
1746
1784
  if (onAttempt) { try { onAttempt() } catch { /* */ } } // space.turn() marks where ITS reply can start
1747
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) } }
1748
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' }
1749
1790
  let r = await doTurn()
1750
1791
  for (let i = 0; turnVerdict(r).kind === 'busy' && !noHold; i++) {
1751
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' }
@@ -1775,12 +1816,38 @@ export class Space {
1775
1816
  // A PRIVATE LANE ALWAYS REPLIES (the server: spaceService respondMode — a bridged lane is 'always'; the app hides the chip there):
1776
1817
  // a mode stored on it changed nothing and was reported back as if it did (sync sweep 2026-11-14 P1, owner: yes)
1777
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
1778
1820
  const r = await this._client.state(this.room, this._mk, 'agentmode', { mode }, REPLY_MODE_LABEL[mode])
1779
1821
  if (!r || r.status !== 200) throw refused('setReplyMode', r) // every error carries a code (sync sweep, 2026-10-10)
1780
1822
  this._mode = mode
1781
1823
  return { mode }
1782
1824
  }
1783
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
+
1784
1851
  /** The room's reply mode as it stands now: the stored one, else the room's default — the server's rule (roomSettings.js
1785
1852
  * roomDefaultReplyMode, sync sweep 2026-11-13 #1), counted with the room's sign-in record as the server counts. */
1786
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
@@ -1820,7 +1887,7 @@ export class Space {
1820
1887
 
1821
1888
  async replyMode() {
1822
1889
  if (this._sharedRoom || this._detachedLane || wasLaneRoom(this._wb, this.room)) return 'always' // a private lane: the server always replies there
1823
- await this._modeReady
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)
1824
1891
  if (this._mode) return this._mode
1825
1892
  let cfg = null
1826
1893
  try { cfg = typeof this._client.getConfig === 'function' ? await this._client.getConfig(this.room, this._mk, { plainMark: true }) : null } catch { cfg = null }
@@ -1888,9 +1955,11 @@ export class Space {
1888
1955
  // cannot be read keeps the last value; a room with no docs sends no mode (⇒ 'auto') and no model (⇒ its own).
1889
1956
  async _readSettings() {
1890
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)
1891
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)])
1892
- const m = modeFromDoc(a); if (m) this._mode = m
1893
- 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
1894
1963
  } catch { /* a convenience; never let it break sending */ }
1895
1964
  this._settingsAt = Date.now()
1896
1965
  }
@@ -2014,6 +2083,9 @@ export class Space {
2014
2083
  // `at` than its tombstone — it came back on every device. Closed, the backup only follows a room it still holds.
2015
2084
  const keep = !this._stopped || (() => { try { return this._wb.backup.rooms.some((r) => r.room === this.room) } catch { return false } })()
2016
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 { /* */ }
2017
2089
  this._emit('rekeyed', { room: this.room, epoch: this.epoch, link: this.shareLink })
2018
2090
  }
2019
2091
 
@@ -2289,14 +2361,33 @@ export class Space {
2289
2361
  isMine(message) {
2290
2362
  const m = message
2291
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() {
2292
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
2293
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
2294
2373
  // false there for every message (sweep 11-07 #9)
2295
2374
  const v = this._wb && this._wb.vault
2296
- let mine = null
2297
- if (v) { const i = v.info || {}; mine = i.signedIn !== false && typeof i.keyId === 'string' && i.keyId ? i.keyId : null }
2298
- else { const sess = this._wb && this._wb._session; mine = sess && sess.sign ? id(sess.sign.pub) : null }
2299
- 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
2300
2391
  }
2301
2392
 
2302
2393
  /** WHO WROTE `message`, as Block knows a person (the Spaces app's blocks.js; docs/report-and-block.md §4) → `{ email?, user?,
@@ -2338,15 +2429,22 @@ export class Space {
2338
2429
  const r = await this._client.importChat(this.room, this._mk, url.trim())
2339
2430
  if (!r || r.status !== 200) throw refused('importChat', r)
2340
2431
  this._kick()
2341
- 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)
2342
2433
  }
2343
2434
 
2344
2435
  async importWhatsApp(text) {
2345
2436
  if (typeof text !== 'string' || !text.trim()) throw sdkError('witbitz: importWhatsApp() needs the exported chat text', 'invalid_argument')
2346
- 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)
2347
2445
  if (!r || r.status !== 200) throw refused('importWhatsApp', r)
2348
2446
  this._kick()
2349
- 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
2350
2448
  }
2351
2449
 
2352
2450
  async attachment(att) {
@@ -2356,7 +2454,26 @@ export class Space {
2356
2454
  if (!refs.length) throw sdkError('witbitz: that attachment has neither bytes nor a reference', 'invalid_argument')
2357
2455
  const got = await Promise.all(refs.map((ref) => this._client.blob(this.room, this._mk, ref)))
2358
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 }
2359
- 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
+ }
2360
2477
  }
2361
2478
 
2362
2479
  /** Attach a PRIVATE assistant lane to this shared Space, for the current member. The lane is the member's OWN room:
@@ -2575,7 +2692,9 @@ export class Space {
2575
2692
  if (!r || r.status !== 200 || !r.decided) throw refused(approve ? 'approve' : 'deny', r)
2576
2693
  let result
2577
2694
  if (isClientWrite && r && r.deviceExec) {
2578
- 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) } }
2579
2698
  } else if (approve && r && r.execution) {
2580
2699
  result = r.execution // a server-executed proposal (an approved crossing, a data write)
2581
2700
  }
@@ -2658,20 +2777,30 @@ export class Space {
2658
2777
  if (this._inflight) { this._pollAgain = true; return }
2659
2778
  this._inflight = true
2660
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)
2661
2781
  try {
2662
- 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 })
2663
2784
  if (this._stopped) return // V#7: answered after close(): nothing of it is applied, announced, or run (a device call included)
2664
2785
  if (!this._sharedRoom && r && r.status === 200 && Date.now() - (this._lanesCheckedAt || 0) > 30000 && typeof this._client.getConfig === 'function') {
2665
2786
  this._lanesCheckedAt = Date.now()
2666
- try {
2667
- const cfg = await this._client.getConfig(this.room, this._mk, { plainMark: true })
2668
- if (this._stopped) return
2669
- if (cfg?.admission === 'email' || cfg?.gated === true) this._gated = true
2670
- if (cfg && !gatedStub(cfg) && (typeof cfg.lanes === 'boolean' || cfg.plain === true)) {
2671
- this._lanesSetting = cfg.lanes === true
2672
- if (this._gateCfg && typeof cfg.lanes === 'boolean') this._gateCfg.lanes = cfg.lanes
2673
- }
2674
- } 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
2675
2804
  }
2676
2805
  if (this._wb && this._wb._attest) this._wb._attest.notePoll(this.room, r) // a room that requires your app: its fresh challenge
2677
2806
  // ⛔ A REFUSED POLL LOOKED LIKE AN EMPTY ROOM (a builder, 2026-09-29). A poll carrying an error code — in a 200 (the
@@ -2724,7 +2853,7 @@ export class Space {
2724
2853
  this._removedSourceMessages?.delete(removedEntryKey(e))
2725
2854
  if (e.id?.startsWith('sh:')) this._removalsMirrored?.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
2726
2855
  }
2727
- else if (this._removedSourceMessages && this._removedSourceMessages.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
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)
2728
2857
  // `from` IS THE DOCUMENTED FIELD (see the header and `on()` below) — the ledger calls it `name`, and this
2729
2858
  // emitted the raw entry, so an author test written from the docs (`m.from === me`) silently matched
2730
2859
  // NOTHING and every delivered message read as "not mine". Reported by the first outside builder after it
@@ -2733,7 +2862,7 @@ export class Space {
2733
2862
  // an entry that already carries `from` is left alone. `messages` gets the SAME object as the event — two
2734
2863
  // shapes for one thing is how this happened.
2735
2864
  if (isTitleEntry(e)) { this._noteTitle(e); continue } // the room's NAME, not a message (roomName.js)
2736
- 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)
2737
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
2738
2867
  const m = e && e.from === undefined && e.name !== undefined ? { ...e, from: e.name } : e
2739
2868
  const { added, updated } = this._view.apply([m])
@@ -2741,7 +2870,7 @@ export class Space {
2741
2870
  if (!added.length) continue // the same entry again
2742
2871
  this._emit('message', m)
2743
2872
  this.safeMedia._arrived(m) // a message this handle sent: its safe copies go beside it
2744
- 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)
2745
2874
  if (e && e.kind === 'fork') this._maybeMoved(e) // a membership fork: is this device one of the keepers?
2746
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 }) }
2747
2876
  }
@@ -2749,10 +2878,27 @@ export class Space {
2749
2878
  // `more`: another page follows (a long room loads in pages) — read it at once, and until it has, the history is
2750
2879
  // not whole: a lane mirror must not take a short list for another history (sync sweep, 2026-10-10)
2751
2880
  }
2752
- if (clearedRemoval) { this._count = 0; this._etag = null }
2753
- 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
2754
2894
  this._maybeTitleDoc()
2755
- 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
+ }
2756
2902
  if (r.deviceCall) this._runDeviceCall(r.deviceCall) // an `await` action the turn is waiting on — answer from this device
2757
2903
  this._partialFromPoll(r)
2758
2904
  this._liveFeed(r)
@@ -2790,19 +2936,32 @@ export class Space {
2790
2936
 
2791
2937
  // THE IN-PLACE CHANGE (ledgerView.js): the ledger moved and brought no entry — a reaction or a caption rewrote one you
2792
2938
  // hold. Re-read a short tail and announce what changed; its etag is NOT adopted (a reply landing in between would be lost).
2793
- async _tailResync() {
2794
- 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))
2795
2942
  if (!(r && r.status === 200 && Array.isArray(r.entries))) return
2796
- 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) {
2797
2953
  if (this._removedMessages && this._removedMessages.has(removedEntryKey(e))) e = removedCopy(e)
2798
2954
  else if (e.sourceRestored === true) {
2799
2955
  this._removedSourceMessages?.delete(removedEntryKey(e))
2800
2956
  if (e.id?.startsWith('sh:')) this._removalsMirrored?.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
2801
2957
  }
2802
- else if (this._removedSourceMessages && this._removedSourceMessages.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2958
+ else if (this._removedSourceMessages?.has(removedEntryKey(e)) || this._pendingSourceHides?.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2803
2959
  if (isTitleEntry(e)) { this._noteTitle(e); continue }
2804
- 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)
2805
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
2806
2965
  const { updated } = this._view.apply([m])
2807
2966
  for (const u of updated) this._emit('update', { id: u.id, message: u.entry, fields: u.fields })
2808
2967
  }
@@ -2972,7 +3131,7 @@ export class Lane extends Space {
2972
3131
  ...stopOpt(stopKey),
2973
3132
  ...promptOpt(showPrompt),
2974
3133
  })
2975
- const msg = withMedia({ from, ...(_skill ? { mcp: _skill } : { 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) })
2976
3135
  { const rt = replyRef(replyTo); if (rt) msg.replyTo = rt }
2977
3136
  await this.safeMedia._prepare(msg)
2978
3137
  const r = await this._turnHeld(() => {
@@ -3012,7 +3171,7 @@ export class Lane extends Space {
3012
3171
  if (!(other instanceof Lane)) throw sdkError('witbitz: link takes another private Lane, not a shared Space', 'not_a_lane')
3013
3172
  const l = linkLanes(this, other, { to, as, cap, resume }, { tierMismatch })
3014
3173
  const acct = this._wb && this._wb.account
3015
- 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)
3016
3175
  return l
3017
3176
  }
3018
3177
 
@@ -3086,6 +3245,24 @@ export class Lane extends Space {
3086
3245
  if (!this._stopped && !from._stopped) {
3087
3246
  this._removalsMirrored = this._removalsMirrored || new Set()
3088
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
+ }
3089
3266
  for (let i = 0; i < removed.length && !from._stopped && !this._stopped; i += 25) {
3090
3267
  const batch = removed.slice(i, i + 25), patches = batch.map((e) => ({ id: 'sh:' + e.id, ts: e.ts, sourceRoom: from.room, sourceRemoved: true }))
3091
3268
  if (!attached()) return { mirrored: sent }
@@ -3101,6 +3278,7 @@ export class Lane extends Space {
3101
3278
  this._removedSourceMessages = this._removedSourceMessages || new Map()
3102
3279
  const target = { id: 'sh:' + e.id, ts: e.ts }, key = removedEntryKey(target)
3103
3280
  this._removedSourceMessages.set(key, target)
3281
+ this._pendingSourceHides.delete(key)
3104
3282
  const cur = this.messages.find((m) => removedEntryKey(m) === key)
3105
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 })
3106
3284
  }
@@ -3181,7 +3359,9 @@ export class Lane extends Space {
3181
3359
  this._viewsAt = Date.now()
3182
3360
  try {
3183
3361
  const views = []
3184
- for (const v of viewsNamedIn(from.messages)) { const d = await this._client.state(from.room, from._mk, v.name).catch(() => null); if (!d?.state || (d.status && d.status !== 200)) { this._viewsAt = 0; throw sdkError('shared view unavailable', 'state_unavailable') } views.push({ label: v.label, state: d.state }) }
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) }
3185
3365
  const text = renderSharedViews(views, from.room)
3186
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 } }
3187
3367
  } catch { /* never break the mirror */ }
@@ -3203,7 +3383,7 @@ export class Lane extends Space {
3203
3383
  for (const off of this._sharedOffs || []) { try { off() } catch { /* */ } }
3204
3384
  this._sharedOffs = []
3205
3385
  for (const l of [...(this._laneLinks || [])]) l._stop() // stops here; the link itself (in wb.account) stays
3206
- 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) } }
3207
3387
  clearTimeout(this._mirrorTimer); clearInterval(this._viewsTick)
3208
3388
  if (this._ownsSharedSpace && this._sharedSpace) { try { this._sharedSpace.close() } catch { /* */ } } // a Space vault.openRoom(laneId) opened for it
3209
3389
  return super.close()
@@ -3215,7 +3395,7 @@ export class Lane extends Space {
3215
3395
  for (const off of this._sharedOffs || []) { try { off() } catch {} }
3216
3396
  this._sharedOffs = []
3217
3397
  if (this._mirrorFrom && this._mirrorSub) for (const ev of ['message', 'update']) {
3218
- 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
3219
3399
  if (index >= 0) listeners.splice(index, 1)
3220
3400
  }
3221
3401
  if (this._ownsSharedSpace) this._sharedSpace?.close()
@@ -3469,6 +3649,8 @@ function refuseInVault(wb) {
3469
3649
  let memoryEmail = String(conn.info?.email || '').toLowerCase()
3470
3650
  wb._memoryGeneration = 0
3471
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('|')
3472
3654
  conn.on((ev) => {
3473
3655
  if (ev?.ev === 'a2aChanged') refreshVaultA2AViews(conn, ev)
3474
3656
  if (ev?.ev === 'siri' && ev.siri) wb._vaultSiri = { ...ev.siri, key: null }
@@ -3504,6 +3686,16 @@ function refuseInVault(wb) {
3504
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 }
3505
3687
  if (!ev || ev.ev !== 'account' || !ev.view) return
3506
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
+ }
3507
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 */ } }
3508
3700
  if (typeof wb.backup.onState === 'function' && was.enabled !== ev.view.enabled) { try { wb.backup.onState(null) } catch { /* */ } }
3509
3701
  })
@@ -3518,8 +3710,13 @@ function refuseInVault(wb) {
3518
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)
3519
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'])
3520
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)
3521
- wb.account._noteLink = (a, b, cap) => { conn.account('account', 'noteLink', a, b, cap).catch(() => {}) }
3522
- 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
+ }
3523
3720
  // THE OPTIONAL SECTIONS (wb.account.contacts / .name / .roomDefaults — sdkAccountSections.js, plan phase 5): the account's docs
3524
3721
  // need its master secret, which is the vault's — each call goes to the vault (ACCOUNT_CALLS account.section), which runs the
3525
3722
  // same section on its own SDK and sends 'accountSection' when another device changed one. They carry no key and no link.
@@ -3581,7 +3778,11 @@ function refuseInVault(wb) {
3581
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)
3582
3779
  wb.invite.enroll = async () => 'vault' // the status, a string, as outside a vault and in the d.ts (sweep 10-24 #9)
3583
3780
  wb.invite.restore = () => { throw vaultRefusal('restoring the invite key (the vault keeps it)') }
3584
- 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'))
3585
3786
  wb.refreshSession = wb.signIn
3586
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)
3587
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)
@@ -3738,7 +3939,7 @@ export class VaultSession {
3738
3939
  else if (d && d.ev === 'account' && d.view) this._live = { ...this._live, account: d.view }
3739
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`
3740
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`
3741
- 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 */ } }
3742
3943
  }
3743
3944
  async _create({ agent, tools, immediateTools, clientTools, agentReplies, skills, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, usernames, safeMedia, lanes }) {
3744
3945
  const enc = tierIsEnclave(tier) // the vault attests the enclave and keeps the key; the page only asks
@@ -3809,7 +4010,10 @@ class Connections {
3809
4010
  if (!record?.callKey || record.account !== account) return null
3810
4011
  const listed = (await this.list()).find(c => c.id === id)
3811
4012
  if (!listed || account !== await wb._account()) return null
3812
- return { ...listed, id, label: listed.label || record.label || '', host: listed.host || record.host || '', account, callKey: record.callKey }
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 } : {}) }
3813
4017
  }
3814
4018
  /** The app's service/outside-agent picker data, without credentials. A builder draws its own picker. */
3815
4019
  catalog({ category } = {}) {
@@ -3860,7 +4064,10 @@ class Connections {
3860
4064
  const wb = this._wb, auth = wb._auth()
3861
4065
  const account = await wb._account()
3862
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')
3863
- const out = await attachConnection({ post: wb._sentinelPost(), pendingStore: this._pendingFor(account), auth, account, label, host, secret, rules, limits, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow, tenant: wb._tenant || undefined, ...(webhook === true ? { bearerWebhook: true } : {}) })
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 } : {}) })
3864
4071
  const j = out.webhook && job ? roomJob(job) : null
3865
4072
  return { ...out, account, ...(j ? { job: j } : {}) }
3866
4073
  }
@@ -4076,7 +4283,7 @@ class SiriAccount {
4076
4283
  const result = await this._change(async st => {
4077
4284
  if (!st.token) return NO_SIRI_CHANGE
4078
4285
  const remote = await this.status()
4079
- if (remote.configured && !siriAliasesDiffer(st.rooms, remote)) return NO_SIRI_CHANGE
4286
+ if (remote.configured && !siriAliasesDiffer(st.rooms, remote, st.defaultRoom || '')) return NO_SIRI_CHANGE
4080
4287
  return true
4081
4288
  })
4082
4289
  return { synced: result === true }