@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/protectedLocal.js CHANGED
@@ -36,7 +36,7 @@ export const PROTECTED_PREFIXES = Object.freeze([
36
36
  'space:awshandle', // THIS device's own AWS key (a handle on the person's AWS budget — acctV2Wiring.js awsHandleStore): its PRIVATE half
37
37
  'space:invitekey', 'space:acctkey', // the invite key, the account-store key
38
38
  'space:attestedBox:', // an attested kind's invite box — its PRIVATE half (attestedBox.js), like the invite key above
39
- 'space:connectionKeys', 'space:siri', 'space:a2a', 'space:code', 'space:clouddevice', // Connections call keys, the Siri inbox key, outside-agent keys, the Code pairing
39
+ 'space:connectionKeys', 'space:siri', 'space:siri-pending-edit', 'space:a2a', 'space:a2a-pending-edit', 'space:a2a-pending-removals', 'space:a2a-delivered', 'space:code', 'space:clouddevice', // Connections call keys, the Siri inbox key, outside-agent keys, the Code pairing
40
40
  'space:connPending', 'space:androidConsent', // pending grants and the short-lived key for an Android connector return
41
41
  'space:contacts', 'space:agentlinks', 'space:recents', // content: people, agent links, the room list with its titles
42
42
  'space:blocks', // the people you blocked (blocks.js) — names and @usernames
@@ -45,6 +45,7 @@ export const PROTECTED_PREFIXES = Object.freeze([
45
45
  'space:share-in', 'space:share-last', // shareIn.js: words shared from another app (sessionStorage), the Space last shared into
46
46
  'space:moved-unsent:', // space.js keepUnsentForMove: words you wrote that a moved room refused, carried to the new room's box (sessionStorage)
47
47
  'space:away-unsent:', // space.js keepUnsentAway: words a Space refused after you had left it, kept for your return (sessionStorage; sync sweep 11-21 #7)
48
+ 'space:update-draft', // drafts.js parkDraftForUpdate: the open room's draft across "Update now"'s one reload (sessionStorage)
48
49
  'space:crossed:', // content: the lines you authored that crossed into a shared room
49
50
  'space:inviteowed:', // rekeyMembers.js: the people a member change added whose invites are still to go (their emails)
50
51
  // The 2026-10-10 audit (the owner: "Make sure that everything is encrypted when the lock is on") — every remaining store
@@ -80,15 +81,20 @@ export const cfgSaysProtected = (c) => !!(c && c.on && c.protect && c.protect.on
80
81
  // And a reviewed handful of SETTINGS that name no room, no person and no activity, which modules read ONCE at load — before
81
82
  // the unlock — so sealing them would reset them on every launch: feature flags, the side panel's width, the map language,
82
83
  // the diagnostics switches, the boot counter and the PUBLIC app catalog. Anything naming a room or a person is sealed.
83
- export const STAYS_CLEAR = Object.freeze(['witbitz-builder-reset-pending', 'space:lock', 'vault:lock', FRAMED_MARK,
84
- 'space:maplang', 'space:maplang.eff', 'space:mapsapp', 'space:settings:open', 'space:side', 'space:side-hidden', 'space:side-w', 'space:assistw',
84
+ // ⚑ THE SIGN-OUT MARKERS STAY CLEAR (second review, 2026-11-27): "a wipe is still to finish" must outlive the wipe itself. Sealed, the
85
+ // marker went with forgetProtectedLocal() in the same wipe (and read as absent while locked, and to the loader, which reads before
86
+ // this wrapper exists) — so on a protected device a wipe whose key clean-up failed was reported clean and never retried, and the
87
+ // previous account's keys could meet the next one. They name no room and no person ('1', 'reset', or the database names to drop).
88
+ export const STAYS_CLEAR = Object.freeze(['witbitz-builder-reset-pending', 'witbitz-spaces-signout-pending', 'witbitz-device-signout-pending', 'witbitz-device-reset-confirmed', 'space:lock', 'vault:lock', FRAMED_MARK,
89
+ 'space:maplang', 'space:maplang.eff', 'space:mapsapp', 'space:mapsapp:chosen' /* its mark: '1' or 'probe:<time>' — read with it by the map widgets (side sweep 2026-11-28) */, 'space:settings:open', 'space:side', 'space:side-hidden', 'space:side-w', 'space:assistw',
85
90
  'space:ohttp', 'space:caretdbg', 'space:rotlab', 'space:diag', 'space:notifPreview', 'space:boots', 'space:apps',
86
91
  'space:channel', 'space:runAt', // Official / Beta / Pinned + the newest build time run (channelChoice.js): read before the unlock, or a locked device would fall back to Official
87
92
  'space:strictfiles', // Strict file viewing (strictFiles.js): sealed, a locked device would read it as off and draw others' files behind the lock screen
88
93
  'space:autoupdate', // "Update automatically" (updateState.js): sealed, a locked device read it as On and updated behind the lock screen (sync sweep, 10-16)
89
94
  'space:atrest', // the regular app's storage is sealed by its DEVICE key (spaceAtRest.js SPACE_AT_REST_MARK): read at load, so its reads wait for the boot's unlock
90
95
  'vault:atrest', // the hosted vault's storage is sealed by its DEVICE key (vaultDeviceKey.js AT_REST_MARK): read at load, so its reads wait for the boot's unlock
91
- 'vault:repairAt']) // a time only: when the vault's boot guard last repaired (vault-boot-guard.js) — read before any unlock (sync sweep 10-21 #9)
96
+ 'vault:repairAt', // a time only: when the vault's boot guard last repaired (vault-boot-guard.js) — read before any unlock (sync sweep 10-21 #9)
97
+ 'space:appearance', 'space:appearance:options', 'vault:appearance']) // the Appearance choice (a theme name, a mode, colours, a font — nothing private): read at load to paint the lock screen (side sweep: protected-cold-lock-misses-appearance)
92
98
  // + the sign-in callbacks' hand-back: written by a page that holds no key (github-callback.html, mcp-callback.html) and
93
99
  // removed once read (connections.js) — sealed, a protected device never finished that path (sync sweep 10-20 #8)
94
100
  export const STAYS_CLEAR_PREFIXES = Object.freeze(['space:flag:', 'space:ghcb:', 'space:mcpcb:'])
@@ -139,7 +145,11 @@ const rawLength = () => (lengthDesc ? lengthDesc.get.call(localStorage) : localS
139
145
  // Disk writes are async (WebCrypto) and must land in the order they were made: one chain.
140
146
  let chain = Promise.resolve()
141
147
  const onDisk = (fn) => { chain = chain.then(fn).catch(() => {}); return chain }
142
- const writeSealed = (name, v) => { const k = key, nm = namer, g = sealGen; if (!k || !nm) return; onDisk(async () => { const o = await nm.opaque(name); const blob = await seal(k, v); if (sealGen !== g) return; try { raw.setItem.call(localStorage, o, JSON.stringify(blob)) } catch { /* private mode / full */ } try { raw.removeItem.call(localStorage, name) } catch { /* */ } }) }
148
+ // A sealed write the store refused (full, private mode) leaves the CLEAR original where it was (side sweep:
149
+ // device-storage-migration-drops-unsaved-copy): removed only once its sealed copy is on disk — never a value on neither. `unsaved`
150
+ // names the entries whose last sealed write failed (a re-key keeps their old names).
151
+ const unsaved = new Set()
152
+ const writeSealed = (name, v) => { const k = key, nm = namer, g = sealGen; if (!k || !nm) return; onDisk(async () => { const o = await nm.opaque(name); const blob = await seal(k, v); if (sealGen !== g) return; try { raw.setItem.call(localStorage, o, JSON.stringify(blob)) } catch { unsaved.add(name); return } /* private mode / full */ unsaved.delete(name); try { raw.removeItem.call(localStorage, name) } catch { /* */ } }) }
143
153
  const removeSealed = (name) => { const nm = namer; if (!nm) return; onDisk(async () => { try { raw.removeItem.call(localStorage, await nm.opaque(name)) } catch { /* */ } }) }
144
154
  /** Resolves once every queued disk write has landed (tests, and the switch-off). */
145
155
  export const protectedLocalFlushed = () => chain
@@ -160,6 +170,18 @@ export async function durableRead (name) {
160
170
 
161
171
  // LOCKED or MEMORY-ONLY, an entry still CLEAR on disk (never migrated: an unsecured computer, or a flag an older build wrote)
162
172
  // reads through — unless it is a secret: those are only ever answered by the overlay.
173
+ /** Return the exact disk entry that still opens to the pending operation. Hosted storage mirrors this entry. */
174
+ export async function durableEntry(name, value) {
175
+ await chain
176
+ if (!active || !raw) return rawGet(name) === value ? [name, value] : null
177
+ if (memoryOnly || !key || !namer) return null
178
+ try {
179
+ const opaque = await namer.opaque(name), stored = raw.getItem.call(localStorage, opaque)
180
+ const blob = stored && parseSealed(stored)
181
+ return blob && String(await open(key, blob)) === value ? [opaque, stored] : null
182
+ } catch { return null }
183
+ }
184
+
163
185
  const readThrough = (n) => { if (isProtectedKey(n)) return null; const v = raw.getItem.call(localStorage, n); return v != null && !parseSealed(v) ? v : null }
164
186
  const enumerate = () => {
165
187
  if (names) return names
@@ -250,21 +272,31 @@ export async function unlockProtectedLocal (rawKey, { switchOn = false, also = [
250
272
  return { stale: true }
251
273
  }
252
274
  const blob = parseSealed(v); if (!blob) return { name, skip: true }
253
- return { name, clear: String(await open(k, blob)) }
275
+ // side sweep (device-storage-unreadable-entry-clears-copy): one entry that will not open no longer throws out of the whole unlock
276
+ // (the at-rest boot read that as "the key opens nothing" and cleared every entry) — it is skipped and KEPT on disk
277
+ try { return { name, clear: String(await open(k, blob)) } } catch { return { name, unreadable: true } }
254
278
  }
255
279
  const blob = parseSealed(v)
256
280
  if (blob && isProtectedKey(stored)) { // phase 1: sealed under its own name
257
- try { return { clear: String(await open(k, blob)) } } catch (e) { if (!switchOn) throw e; return { stale: true } }
281
+ try { return { clear: String(await open(k, blob)), p1: true } } catch (e) { if (!switchOn) return { unreadable: true, p1: true }; return { stale: true } }
258
282
  }
259
283
  return { clear: v } // clear: never protected before, or written by an older build
260
284
  }))
261
285
  const logCopies = new Map() // an APPEND LOG's every copy, merged below — never one copy replacing another
262
286
  const carried = [], carriedNames = new Set() // 10·V#1: entries another known key opened — re-sealed under this one, then their old names go
287
+ const unreadable = new Set() // names under this key whose entry would not open: kept on disk, never written over by a locked default
288
+ const toClear = [] // [opaque name, real name, value]: sealed by an older build under a name that stays clear now
289
+ let p1 = 0, p1Opened = 0
263
290
  entries.forEach(([stored], i) => {
264
291
  const r = opened[i]
292
+ if (r.p1) { p1++; if (!r.unreadable) p1Opened++ }
293
+ if (r.unreadable) { if (isOpaqueName(stored)) opaque++; unreadable.add(r.name || stored); return }
265
294
  if (isOpaqueName(stored)) {
266
295
  opaque++
267
296
  if (r.stale) { stale.push(stored); return }
297
+ // A name that STAYS CLEAR now but an older build sealed (side sweep: map-widget-misses-protected-apple-choice): every read of
298
+ // it goes to the disk under its real name, so the sealed copy is written back there (unless a clear one exists) and goes.
299
+ if (staysClear(r.name)) { ours++; if (!r.skip) toClear.push([stored, r.name, r.clear]); return }
268
300
  if (r.carried) { ours++; carried.push(stored); if (!next.has(r.name)) { next.set(r.name, r.clear); carriedNames.add(r.name) } return } // this key's own copy, where there is one, is the newer
269
301
  ours++
270
302
  if (!r.skip) { next.set(r.name, r.clear); if (APPEND_LOGS.includes(r.name)) logCopies.set(r.name, [r.clear, ...(logCopies.get(r.name) || [])]) } // the sealed copy is the older history: first
@@ -288,12 +320,16 @@ export async function unlockProtectedLocal (rawKey, { switchOn = false, also = [
288
320
  while (lines.length > LOG_CAP) lines.shift()
289
321
  next.set(n, JSON.stringify(lines)); lockedWrites.delete(n); logWritten.push(n)
290
322
  }
291
- if (opaque && !ours && !switchOn) throw new Error('this key opens nothing here') // a wrong key: every name fails to open, change nothing
323
+ // a wrong key: every name fails to open, change nothing. A phase-1 entry that OPENED proves the key too (a partly migrated device whose
324
+ // only opaque entry is damaged — side sweep: device-storage-unreadable-entry-clears-copy, round 3)
325
+ if (opaque && !ours && !p1Opened && !switchOn) throw new Error('this key opens nothing here')
326
+ if (p1 && !p1Opened && !ours && !switchOn) throw new Error('this key opens nothing here') // phase 1 only, and not one entry opens: a wrong key
292
327
  if (switchOn) for (const n of stale) { try { raw.removeItem.call(localStorage, n) } catch { /* */ } }
328
+ for (const [o, n, v] of toClear) { try { if (raw.getItem.call(localStorage, n) == null) raw.setItem.call(localStorage, n, v); raw.removeItem.call(localStorage, o) } catch { /* the next unlock tries again */ } }
293
329
  // A write made while locked is kept only where the disk has NOTHING under that name: a module that found a value "missing"
294
330
  // at load (it was sealed) and wrote a default — a fresh device id, an empty list — must never replace the real one.
295
331
  const written = []
296
- for (const [n, v] of lockedWrites) if (v != null && !next.has(n)) { next.set(n, v); written.push(n) }
332
+ for (const [n, v] of lockedWrites) if (v != null && !next.has(n) && !unreadable.has(n)) { next.set(n, v); written.push(n) }
297
333
  const removed = []
298
334
  if (switchOn) sealGen++ // a new protection: writes made under another one are not this one's
299
335
  key = k; namer = nm; active = true; memoryOnly = false; names = null
@@ -315,11 +351,11 @@ export async function rekeyProtectedLocal (newRaw) {
315
351
  await chain
316
352
  const oldNm = namer, k = await importRaw(newRaw), nm = await makeNamer(newRaw)
317
353
  const old = []
318
- for (const stored of rawKeys()) if (isOpaqueName(stored) && (await oldNm.real(stored)) != null) old.push(stored)
354
+ for (const stored of rawKeys()) { if (!isOpaqueName(stored)) continue; const n = await oldNm.real(stored); if (n != null) old.push([stored, n]) }
319
355
  sealGen++; key = k; namer = nm; names = null
320
356
  for (const [n, v] of overlay) writeSealed(n, v)
321
357
  await chain
322
- for (const o of old) { try { raw.removeItem.call(localStorage, o) } catch { /* */ } }
358
+ for (const [o, n] of old) { if (unsaved.has(n)) continue; try { raw.removeItem.call(localStorage, o) } catch { /* */ } } // a copy the new key could not write keeps its old one (unlockProtectedLocal's `also` carries it)
323
359
  return { entries: overlay.size, moved: old.length }
324
360
  }
325
361
  /** Relock: nothing readable stays in memory; the sealed blobs stay on disk. */
@@ -361,8 +397,11 @@ try {
361
397
  nm.real(e.key).then((name) => {
362
398
  if (name == null || key !== k) return
363
399
  names = null
364
- if (e.newValue == null) { overlay.delete(name); return }
365
- const blob = parseSealed(e.newValue); if (blob) open(k, blob).then((v) => { if (key === k) overlay.set(name, String(v)) }).catch(() => {})
400
+ // …and say WHICH setting changed, under its real name: a listener for the plain `storage` event saw only the opaque name (side
401
+ // sweep: protected-lane-misses-appearance-change — an open assistant kept the old Appearance)
402
+ const told = () => { try { dispatchEvent(new CustomEvent('wb-protected-storage', { detail: { key: name } })) } catch { /* no window */ } }
403
+ if (e.newValue == null) { overlay.delete(name); told(); return }
404
+ const blob = parseSealed(e.newValue); if (blob) open(k, blob).then((v) => { if (key === k) { overlay.set(name, String(v)); told() } }).catch(() => {})
366
405
  }).catch(() => {})
367
406
  })
368
407
  } catch { /* no window */ }
@@ -0,0 +1,86 @@
1
+ // WHO HOLDS A REACTION — one rule for the server (agent/spaceService.mjs op 'react'), the app (messageActions.js) and the SDK
2
+ // (space.reactionsOf). Pure: no imports, no DOM (the server imports this file as it is).
3
+ //
4
+ // A message's reactions are stored as
5
+ // reactions { emoji: [names] } — what every client has always read; one entry PER REACTOR. In a verified
6
+ // room two members may share a display name, so a name can appear twice.
7
+ // reactBy { emoji: { keyId: name } } — verified rooms (side sweep: reaction-ownership-by-display-name, 2026-11-28):
8
+ // which verified key holds each reaction, under which name. One key holds an
9
+ // emoji once; a rename replaces its name.
10
+ // reactKeys { emoji: { name: keyId } } — the older verified-room record (2026-10-10), kept for older clients and an
11
+ // older server: each name with ONE key that holds it.
12
+ // `reactions` is what is present: a key whose name is no longer in the list holds nothing (an older server took the name
13
+ // out). A message written before `reactBy` existed is read through `reactKeys`; a key it shows under two names (a member
14
+ // who reacted, was renamed, and reacted again) counts once, under the later name.
15
+ // keyId = `${x}.${y}` of the member's signing key (agent/spaceService.mjs keyIdOfJwk).
16
+
17
+ const obj = (o) => (o && typeof o === 'object' && !Array.isArray(o) ? o : {})
18
+ const strs = (a) => (Array.isArray(a) ? a.filter((n) => typeof n === 'string') : [])
19
+
20
+ /** The keys holding `emoji` on `e` as [[keyId, name]] (insertion order), and the names a key no longer holds (legacy). */
21
+ function keyedOf(e, emoji) {
22
+ const by = Object.entries(obj(obj(e && e.reactBy)[emoji])).filter(([k, n]) => k && typeof n === 'string')
23
+ if (by.length) return { keyed: by, stale: [] }
24
+ const byKey = new Map(), stale = []
25
+ for (const [name, key] of Object.entries(obj(obj(e && e.reactKeys)[emoji]))) {
26
+ if (typeof key !== 'string' || !key) continue
27
+ if (byKey.has(key)) stale.push(byKey.get(key))
28
+ byKey.set(key, name)
29
+ }
30
+ return { keyed: [...byKey], stale }
31
+ }
32
+
33
+ /** One emoji's reactors on entry `e`, in the stored order: [{ name, key }] — `key` null for a name no verified key holds
34
+ * (an open room, or a reaction from before keys were recorded). */
35
+ export function reactorsOf(e, emoji) {
36
+ const names = strs(obj(e && e.reactions)[emoji])
37
+ const { keyed, stale } = keyedOf(e, emoji)
38
+ const queue = new Map() // name → the keys still to place on it
39
+ for (const [key, name] of keyed) { if (!queue.has(name)) queue.set(name, []); queue.get(name).push(key) }
40
+ const skip = new Map() // name → how many legacy duplicates of a renamed key to leave out
41
+ for (const n of stale) skip.set(n, (skip.get(n) || 0) + 1)
42
+ const out = []
43
+ for (const name of names) {
44
+ const q = queue.get(name)
45
+ if (q && q.length) { out.push({ name, key: q.shift() }); continue }
46
+ if (skip.get(name)) { skip.set(name, skip.get(name) - 1); continue }
47
+ out.push({ name, key: null })
48
+ }
49
+ return out
50
+ }
51
+
52
+ /** Every emoji's reactors: [[emoji, [{ name, key }]]], emoji nobody holds left out. */
53
+ export function allReactors(e) {
54
+ const out = []
55
+ for (const emoji of Object.keys(obj(e && e.reactions))) { const rows = reactorsOf(e, emoji); if (rows.length) out.push([emoji, rows]) }
56
+ return out
57
+ }
58
+
59
+ /** The three stored fields for one emoji's rows: { names, by, keys } — `by`/`keys` empty when no row has a key. */
60
+ export function storedOf(rows) {
61
+ const names = [], by = {}, keys = {}
62
+ for (const r of rows) {
63
+ names.push(r.name)
64
+ if (r.key) { by[r.key] = r.name; if (keys[r.name] === undefined) keys[r.name] = r.key }
65
+ }
66
+ return { names, by, keys }
67
+ }
68
+
69
+ /** This device's key in the stored keyId form: accepts the app's / SDK's `kty:crv:x:y` (agentIdentity.keyIdOf), a JWK, or
70
+ * `x.y` as is. '' when none. */
71
+ export function reactKeyOf(k) {
72
+ if (!k) return ''
73
+ if (typeof k === 'object') return k.x && k.y ? `${k.x}.${k.y}` : ''
74
+ const s = String(k)
75
+ const p = s.split(':')
76
+ if (p.length === 4 && p[2] && p[3]) return `${p[2]}.${p[3]}`
77
+ return /^[^:]+\.[^:]+$/.test(s) ? s : ''
78
+ }
79
+
80
+ /** Is this row mine? A row a verified key holds is mine only when that key is this device's (`myKey`, when it is known);
81
+ * a row with no key — every row of an open room — is mine by name, as it always was. */
82
+ export function rowIsMine(row, me, myKey) {
83
+ const mk = reactKeyOf(myKey)
84
+ if (row && row.key && mk) return row.key === mk
85
+ return !!(me && row && row.name === me)
86
+ }
package/removedMessage.js CHANGED
@@ -3,7 +3,7 @@ export const SHARED_REMOVED_TEXT = 'Removed in the shared Space'
3
3
  /** Replacement, never a merge: no body, media, tool output or attachment references survive. */
4
4
  export function removedCopy(e) {
5
5
  const { id, ts, name, from, self, verified, user, spk, vspk, sid } = e || {}
6
- return { id, ts, name, from, self, verified, user, spk, vspk, sid, kind: 'text', text: REMOVED_TEXT, removedByWitbitz: true }
6
+ return { id, ts, name, from, self, verified, user, spk, vspk, sid, ...(e?.keyOnly ? { keyOnly: true } : {}), kind: 'text', text: REMOVED_TEXT, removedByWitbitz: true }
7
7
  }
8
8
  export function sharedRemovedCopy(e) {
9
9
  const { id, ts, name, from, self } = e || {}
package/roomEmbed.js ADDED
@@ -0,0 +1,111 @@
1
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
2
+ const types = new Set(['string', 'number', 'boolean', 'array', 'object'])
3
+ const validName = name => /^[a-zA-Z0-9_]{1,64}$/.test(name) && !Object.hasOwn(Object.prototype, name)
4
+ export function applySkills(config, skills) {
5
+ if (skills === undefined) return
6
+ if (!object(skills) || Object.keys(skills).length > 16 || !Object.entries(skills).every(([name, spec]) => validName(name) && object(spec) &&
7
+ [spec.in, ...(spec.out === undefined ? [] : [spec.out])].every(schema => object(schema) && Object.keys(schema).length <= 16 &&
8
+ Object.entries(schema).every(([key, type]) => validName(key) && types.has(type)))))
9
+ throw Object.assign(new Error('Each skill needs a name and a typed input schema.'), { code: 'invalid_argument' })
10
+ config.skills = Object.fromEntries(Object.entries(skills).map(([name, spec]) => [name, { in: { ...spec.in } }]))
11
+ const protocol = skillProtocol(skills)
12
+ if (protocol) config.persona = (config.persona || '') + '\n' + protocol
13
+ }
14
+
15
+ export function skillProtocol(skills) {
16
+ const names = Object.keys(skills || {})
17
+ if (!names.length) return ''
18
+ const rows = names.map((n) => ' • ' + n + '(' + JSON.stringify((skills[n] || {}).in || {}) + ')')
19
+ return [
20
+ '',
21
+ '--- YOUR MCP SKILLS (the app invokes these on you as TYPED tool calls over the bridge, NOT chat messages) ---',
22
+ ...rows,
23
+ 'When one is invoked you are told exactly which skill and with what arguments. Handle it FULLY — use your platform',
24
+ 'tools (read_url, web_search, the map/photo tools, …) whenever they make the answer better — then reply with the',
25
+ 'finished answer for the reader. Do not just echo the raw arguments back.',
26
+ ].join('\n')
27
+ }
28
+
29
+ export function embeddedInvite(template, link, origin) {
30
+ if (typeof template !== 'string' || template.length > 2000 || template.split('{link}').length !== 2 || !link)
31
+ throw Object.assign(new Error('An invite template needs a single {link} placeholder.'), { code: 'invalid_argument' })
32
+ const base = new URL(origin)
33
+ const url = new URL(template.replace('{link}', encodeURIComponent(link)), base.origin)
34
+ if (!['http:', 'https:'].includes(base.protocol) || url.origin !== base.origin || url.username || url.password)
35
+ throw Object.assign(new Error('The invite must open the embedding application.'), { code: 'invalid_argument' })
36
+ return url.href
37
+ }
38
+
39
+ export function setLiveDoc(docs, name, text) {
40
+ const key = String(name || 'document').slice(0, 80)
41
+ if (typeof text === 'string' && text) docs[key] = text.slice(0, 4000)
42
+ else delete docs[key]
43
+ }
44
+ export function formatLiveDocs(embedLiveDocs, meet = '') {
45
+ const names = Object.keys(embedLiveDocs).filter((n) => embedLiveDocs[n])
46
+ if (!names.length) return meet || undefined
47
+ let body = ''
48
+ for (const n of names) body += '[' + String(n).slice(0, 80) + ']\n' + String(embedLiveDocs[n]) + '\n\n'
49
+ return (meet + '=== LIVE CONTEXT (the CURRENT text of what the user has open right now — e.g. a draft, a call transcript. It updates live; reason over THIS and quote it exactly. It is not a saved file.) ===\n\n' + body + '=== end live context ===').slice(0, 4000) // matches the server's 4KB context cap; large sources get windowed/summarized later
50
+ }
51
+
52
+ export function roomEmbed(space, knownLane = () => false) {
53
+ const docs = Object.create(null), watches = new Set()
54
+ const owner = () => space._wb?.vault ? space._wb._memoryGeneration : space._wb?._archiveGeneration
55
+ const generation = space._memoryOwner ?? owner()
56
+ const active = () => !space._stopped && generation === owner()
57
+ function check() {
58
+ if (!active()) throw Object.assign(new Error('The Space closed or the account changed.'), { code: 'closed' })
59
+ }
60
+ async function state(patch) {
61
+ check()
62
+ const r = patch === undefined ? await space._client.state(space.room, space._mk, 'embed')
63
+ : await space._client.state(space.room, space._mk, 'embed', patch, '', 'embed')
64
+ check()
65
+ if (r?.status !== 200) throw Object.assign(new Error('The embedded state could not be synchronized.'), { code: r?.error || 'unavailable' })
66
+ return r
67
+ }
68
+ return {
69
+ context: () => active() ? formatLiveDocs(docs) : undefined,
70
+ close() { for (const stop of [...watches]) stop(); for (const name of Object.keys(docs)) delete docs[name] },
71
+ api: {
72
+ async invite(template) {
73
+ check()
74
+ if (space._sharedRoom || space._detachedLane || knownLane()) throw Object.assign(new Error('A private lane cannot be shared'), { code: 'private_lane' })
75
+ if (space._wb?.vault) return space._wb.vault.share(space, { hostInviteTemplate: template })
76
+ return embeddedInvite(template, space.shareLink, globalThis.location?.origin)
77
+ },
78
+ async read() { return (await state()).state ?? null },
79
+ async update(patch) {
80
+ if (!object(patch)) throw Object.assign(new Error('A state update needs an object.'), { code: 'invalid_argument' })
81
+ await state(patch)
82
+ },
83
+ watch(fn) {
84
+ check()
85
+ if (typeof fn !== 'function') throw new TypeError('A state listener is required.')
86
+ let timer, stopped = false, version = -1
87
+ const stop = () => { stopped = true; clearTimeout(timer); watches.delete(stop) }
88
+ async function poll() {
89
+ try {
90
+ const r = await state(), v = r.v || 0
91
+ if (!stopped && v > version) { version = v; fn(r.state ?? null) }
92
+ } catch { /* retry when the room becomes available */ }
93
+ if (!stopped && active()) timer = setTimeout(poll, 2500)
94
+ else stop()
95
+ }
96
+ watches.add(stop); void poll()
97
+ return stop
98
+ },
99
+ setLiveDocument(name, text) { check(); setLiveDoc(docs, name, text) },
100
+ },
101
+ }
102
+ }
103
+
104
+ export function roomInviteFlags(link) {
105
+ try {
106
+ const url = new URL(link, 'https://example.invalid/')
107
+ const fragment = new URLSearchParams(url.hash.slice(1))
108
+ const has = (key, value) => url.searchParams.getAll(key).includes(value) || fragment.getAll(key).includes(value)
109
+ return { gated: has('gate', 'email'), lanes: has('lanes', '1') }
110
+ } catch { return { gated: false, lanes: false } }
111
+ }