@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/sdkVault.js CHANGED
@@ -12,6 +12,7 @@
12
12
  // the page replies with the call `answer(id, { result } | { error })`
13
13
  // The page posts ONLY to the pinned vault origin (never '*') and accepts ONLY messages from that origin AND from the
14
14
  // window that frames it — a page we did not write must not broadcast, and nothing else on the page may answer for the vault.
15
+ import { TURN_TIMEOUT_MS } from './sdkTurn.js'
15
16
  import { WORKER_OPS } from './workerClient.js'
16
17
 
17
18
  export const VAULT_PROTOCOL = 1
@@ -34,23 +35,34 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
34
35
  const origin = String(vault || '').replace(/\/+$/, '')
35
36
  if (!isOrigin(origin)) return Promise.reject(Object.assign(new Error('witbitz: `vault` must be the vault\'s origin, e.g. https://vault.example.com'), { code: 'invalid_argument' }))
36
37
  if (!win || win.top === win) return Promise.reject(Object.assign(new Error('witbitz: this page is not framed by a vault — open the vault (' + origin + '), which opens this page inside it'), { code: 'not_in_vault' }))
38
+ const cacheKey = Symbol.for('witbitz.vault.transports.v1')
39
+ const transports = win[cacheKey] ||= new Map()
40
+ if (transports.has(origin)) return transports.get(origin)
41
+ const connection = openTransport(win, origin, helloMs)
42
+ transports.set(origin, connection)
43
+ connection.catch(() => { if (transports.get(origin) === connection) transports.delete(origin) })
44
+ return connection
45
+ }
46
+
47
+ function openTransport(win, origin, helloMs) {
37
48
  const top = win.top
38
49
  const waiting = new Map()
39
50
  const listeners = new Set()
40
51
  const askers = new Map() // kind → room → the page's handler for the vault's question
41
52
  const streams = new Map() // room → the handlers of every Space on this page showing it (the vault holds one socket per room)
42
- let seq = 0
53
+ const sequenceKey = Symbol.for('witbitz.vault.requestSequence')
54
+ if (!Number.isSafeInteger(win[sequenceKey])) win[sequenceKey] = 0
43
55
  let welcome = null
44
56
  let onWelcome = null
45
- win.addEventListener('message', (e) => {
57
+ const receive = (e) => {
46
58
  if (e.origin !== origin || e.source !== top) return // only the vault that frames us
47
59
  const d = e.data
48
60
  if (!d || d.ch !== 'wbvault') return
49
- if (d.t === 'welcome') { welcome = d; if (onWelcome) onWelcome(d); return }
61
+ if (d.t === 'welcome') { welcome = Object.assign(welcome || {}, d); if (onWelcome) onWelcome(welcome); return }
50
62
  if (d.t === 'res') {
51
63
  const w = waiting.get(d.id); if (!w) return
52
64
  waiting.delete(d.id); clearTimeout(w.timer)
53
- if (d.error) w.rej(Object.assign(new Error(String(d.error)), { code: d.code || 'vault_refused', status: d.status, ...(d.code === 'wrong_pin' && Number.isSafeInteger(d.next) && d.next >= 0 ? { next: d.next } : {}), ...(Array.isArray(d.unavailable) ? { unavailable: d.unavailable } : {}), ...(typeof d.reason === 'string' ? { reason: d.reason } : {}), ...(d.verdict && typeof d.verdict === 'object' ? { verdict: d.verdict } : {}) })); else w.res(d.result)
65
+ if (d.error) w.rej(Object.assign(new Error(String(d.error)), { code: d.code || 'vault_refused', status: d.status, ...(d.code === 'wrong_pin' && Number.isSafeInteger(d.next) && d.next >= 0 ? { next: d.next } : {}), ...(d.code === 'partial_revoke' ? { removedFrom: d.removedFrom || [], unchecked: d.unchecked || [] } : {}), ...(Array.isArray(d.unavailable) ? { unavailable: d.unavailable } : {}), ...(typeof d.reason === 'string' ? { reason: d.reason } : {}), ...(d.verdict && typeof d.verdict === 'object' ? { verdict: d.verdict } : {}) })); else w.res(d.result)
54
66
  return
55
67
  }
56
68
  if (d.t === 'ask' && typeof d.id === 'number') {
@@ -59,13 +71,42 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
59
71
  .then((result) => call('answer', d.id, { result: result === undefined ? null : result }), (err) => call('answer', d.id, { error: String((err && err.message) || err || 'refused').slice(0, 200) })).catch(() => {})
60
72
  return
61
73
  }
74
+ if (d.t === 'event' && welcome) {
75
+ if (d.ev === 'signedOut' || d.ev === 'accountSignedOut') {
76
+ Object.assign(welcome, { signedIn: false, email: '', keyId: '', siri: null })
77
+ if (d.reason !== 'expired') {
78
+ streams.clear(); welcome.rooms = []; welcome.keyStates = []; welcome.account = null
79
+ }
80
+ delete welcome.notifOpen
81
+ }
82
+ if (d.ev === 'signedIn') {
83
+ Object.assign(welcome, { signedIn: true, email: d.email || '', keyId: d.keyId || '' })
84
+ post({ t: 'hello', v: VAULT_PROTOCOL })
85
+ }
86
+ if (d.ev === 'siri' && d.siri) welcome.siri = d.siri
87
+ if (d.ev === 'rooms' && Array.isArray(d.rooms)) {
88
+ welcome.rooms = d.rooms
89
+ const held = new Set(d.rooms.map(r => r.room))
90
+ for (const room of streams.keys()) if (!held.has(room)) streams.delete(room)
91
+ }
92
+ if (d.ev === 'session' || d.ev === 'signedIn') welcome.keyId = d.keyId || ''
93
+ if (d.ev === 'account') welcome.account = d.view
94
+ if (d.ev === 'lock') welcome.lock = d.lock
95
+ if (d.ev === 'push') welcome.push = d.push
96
+ if (d.ev === 'key' && d.room) {
97
+ const prior = (Array.isArray(welcome.keyStates) ? welcome.keyStates : []).filter(k => k.room !== d.room)
98
+ if (d.kind === 'pending' || d.kind === 'removed') prior.push({ room: d.room, kind: d.kind, reason: d.reason || '' })
99
+ welcome.keyStates = prior.slice(-200)
100
+ }
101
+ }
62
102
  if (d.t === 'event' && d.ev === 'stream') { for (const fn of streams.get(d.room) || []) { try { fn(d) } catch { /* */ } } return }
63
103
  if (d.t === 'event') { for (const fn of listeners) { try { fn(d) } catch { /* a listener's error is its own */ } } }
64
- })
104
+ }
105
+ win.addEventListener('message', receive)
65
106
  const post = (msg) => top.postMessage({ ch: 'wbvault', ...msg }, origin)
66
107
  const call = (op, ...args) => new Promise((res, rej) => {
67
- const id = ++seq
68
- const timer = setTimeout(() => { if (waiting.delete(id)) rej(Object.assign(new Error('witbitz: the vault did not answer (' + op + ')'), { code: 'vault_timeout' })) }, PERSON_OPS.has(op) ? PERSON_MS : WAKE_OPS.has(op) ? WAKE_MS : CALL_MS)
108
+ const id = ++win[sequenceKey]
109
+ const timer = setTimeout(() => { if (waiting.delete(id)) rej(Object.assign(new Error('witbitz: the vault did not answer (' + op + ')'), { code: 'vault_timeout' })) }, PERSON_OPS.has(op) ? PERSON_MS : WAKE_OPS.has(op) ? WAKE_MS : op === 'op' && args[0] === 'turn' ? TURN_TIMEOUT_MS : CALL_MS)
69
110
  waiting.set(id, { res, rej, timer })
70
111
  try { post({ t: 'call', id, op, args }) } catch (err) { waiting.delete(id); clearTimeout(timer); rej(err) }
71
112
  })
@@ -84,7 +125,21 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
84
125
  client.streamOpen = (room, onEvent, onState) => {
85
126
  const fn = (d) => { if (d.event) onEvent(d.event); else if ('up' in d && onState) onState(!!d.up) }
86
127
  let set = streams.get(room)
87
- if (!set) { set = new Set(); streams.set(room, set); call('stream', room, true).catch(() => { streams.delete(room) }) } // refused or not held: the Space keeps polling
128
+ if (!set) {
129
+ set = new Set(); streams.set(room, set)
130
+ let delay = 1000
131
+ const subscribe = () => {
132
+ if (streams.get(room) !== set) return
133
+ call('stream', room, true).catch(err => {
134
+ if (streams.get(room) !== set) return
135
+ for (const notify of set) { try { notify({ up: false }) } catch {} }
136
+ if (['not_in_vault', 'bad_room', 'vault_refused'].includes(err?.code)) return
137
+ setTimeout(subscribe, delay)
138
+ delay = Math.min(30000, delay * 2)
139
+ })
140
+ }
141
+ subscribe()
142
+ }
88
143
  set.add(fn)
89
144
  return { stop: () => { if (set.delete(fn) && !set.size && streams.get(room) === set) { streams.delete(room); call('stream', room, false).catch(() => {}) } }, setGrants: () => {}, sync: () => {} }
90
145
  }
@@ -93,9 +148,10 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
93
148
  create: (cfg, opts) => call('create', cfg, ...(opts ? [opts] : [])), // opts { enclave }: dropping it would make a STANDARD Space where a confidential one was asked
94
149
  rooms: () => call('rooms'),
95
150
  share: (room, opts) => call('share', room, opts || {}),
96
- signIn: (opts) => call('signIn', opts || {}),
151
+ signIn: () => call('signIn'),
97
152
  signOut: () => call('signOut'),
98
153
  userToken: (t) => call('userToken', t), // per-user billing: the page's current token, handed over before an op that can spend
154
+ enclaveAvailable: () => call('enclaveAvailable'),
99
155
  whoami: () => call('whoami'),
100
156
  lockSettings: () => call('lockSettings'), // the vault's lock sheet (a vault started with `lock: true`): the person decides there; the page learns { available, on, protect }
101
157
  notifications: () => call('notifications'), // the vault's notifications card (`push: true`): the person decides; the page learns { available, on }
@@ -114,7 +170,7 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
114
170
  resolve(v)
115
171
  }
116
172
  let stopped = false
117
- const timer = setTimeout(() => { stopped = true; reject(Object.assign(new Error('witbitz: the vault at ' + origin + ' did not answer — is this page framed by it?'), { code: 'not_in_vault' })) }, helloMs)
173
+ const timer = setTimeout(() => { stopped = true; win.removeEventListener?.('message', receive); reject(Object.assign(new Error('witbitz: the vault at ' + origin + ' did not answer — is this page framed by it?'), { code: 'not_in_vault' })) }, helloMs)
118
174
  if (welcome) return done(welcome)
119
175
  onWelcome = (w) => { onWelcome = null; done(w) }
120
176
  // the vault may still be starting its worker: say hello until it answers (or the wait ends)
@@ -10,6 +10,7 @@ import { derSigToRaw } from './x509.js'
10
10
 
11
11
  /** The build-enclave images whose verdicts count — infra/build-enclave/pins.json `buildEnclave` (held equal by a test). */
12
12
  export const BUILD_ENCLAVE_PCR0 = Object.freeze([
13
+ "c6a8cbd0c05d8e003e75b266f1dde2a6426b7cd61f845e4b128e59063e40968b44f30d934bbe1925582fe33bbdd0b1d7",
13
14
  "f490096d57e4287146e8b8d7bf4c75f423984ca52199efab0ee8684fbee6cfe6ab82c72d54f05a38f24a0d4ad6e2f557",
14
15
  "41ec7e0e54beac5759fba7efa06c48081dbd96c7299c29c92a9c619036ce057cec357ad4ad71a165d7f881df120b043b",
15
16
  "9f0801335a952bdbac70b6793150738d7ce30bc3a0d520fec6f573de22a822aa5ef762f78648bc8608ca0b2eeccda556",
package/sharedViews.js CHANGED
@@ -9,7 +9,7 @@ export const SHARED_VIEWS_DOC = 'sharedviews'
9
9
  export const SHARED_VIEWS_MAX = 12000 // the state allows 32 KB; a long multi-week plan must arrive whole
10
10
 
11
11
  /** `views` = [{ label, state }] (a widget's label and its doc's state) → the text, or '' when there is nothing to say. */
12
- export function renderSharedViews(views) {
12
+ export function renderSharedViews(views, source = '') {
13
13
  const parts = []
14
14
  for (const v of Array.isArray(views) ? views : []) {
15
15
  const st = v && v.state
@@ -18,20 +18,50 @@ export function renderSharedViews(views) {
18
18
  parts.push('ITINERARY' + (st.title ? ' — ' + st.title : '') + '\n' + st.days.map((d) => `${(d && d.name) || 'Day'}: ${((d && d.items) || []).map((i) => `${i && i.when ? i.when + ' — ' : ''}${(i && i.text) || ''}`).filter(Boolean).join('; ')}`).join('\n'))
19
19
  } else if (Array.isArray(st.places) && st.places.length) {
20
20
  parts.push('MAP (' + String((v && v.label) || 'map').replace(/^\W+\s*/, '') + '): ' + st.places.map((pl) => `${(pl && pl.name) || 'place'}${pl && Number.isFinite(pl.rating) ? ` ★${pl.rating}` : ''}${pl && pl.chosen ? ' (shortlisted)' : ''}`).join(', '))
21
+ } else if (Array.isArray(st.places)) {
22
+ parts.push('MAP (' + String((v && v.label) || 'map').replace(/^\W+\s*/, '') + '): no stops') // an empty map is "no stops" (owner decision 14)
21
23
  }
22
24
  }
23
- return parts.join('\n\n').slice(0, SHARED_VIEWS_MAX)
25
+ const chars = Array.from(parts.join('\n\n').slice(0, SHARED_VIEWS_MAX))
26
+ const size = text => new TextEncoder().encode(JSON.stringify({ source, text })).length
27
+ const text = chars.join('')
28
+ if (size(text) <= 32000) return text
29
+ let low = 0, high = chars.length
30
+ while (low < high) {
31
+ const mid = Math.ceil((low + high) / 2)
32
+ if (size(chars.slice(0, mid).join('')) <= 32000) low = mid
33
+ else high = mid - 1
34
+ }
35
+ return chars.slice(0, low).join('')
36
+ }
37
+
38
+ /** ONE VIEW'S READ → what the lane is told (side sweep: empty-map-card-blocks-lane-view-refresh; owner decision 14: an empty map means
39
+ * "no stops", not "unchanged"). A map whose places all failed to resolve has a card and no doc, so an ANSWERED read with no state is
40
+ * that map with no stops — it used to stop the whole `sharedviews` write, and the lane's assistant kept the previous plan. A FAILED
41
+ * read (none, or a non-200) is unknown → null: the caller writes nothing. Not a map: a missing doc says nothing. */
42
+ export function viewFromRead({ label, map } = {}, r) {
43
+ if (!r || (r.status && r.status !== 200)) return null
44
+ if (r.state) return { label, state: r.state }
45
+ if (r.status !== 200) return null // no state and no answer that says so: unknown
46
+ return { label, state: map ? { places: [] } : null }
24
47
  }
48
+ /** Is a view a MAP? The log names its kind ('places' when the agent drew a map); an older entry with none is a map unless it is the
49
+ * itinerary — the app's widget card makes the same default (widgetCard.js). */
50
+ export const isMapView = (v) => (v && v.kind ? v.kind === 'places' : !(v && v.name === 'itinerary'))
25
51
 
26
52
  /** The views a room's log names: each widget's doc name and label, newest first, at most `max`. */
27
53
  export function viewsNamedIn(entries, max = 12) {
28
54
  const out = [], seen = new Set()
29
55
  const list = Array.isArray(entries) ? entries : []
30
- for (let i = list.length - 1; i >= 0 && out.length < max; i--) {
56
+ for (let i = list.length - 1; i >= 0; i--) {
31
57
  const ws = list[i] && Array.isArray(list[i].widgets) ? list[i].widgets : []
32
58
  for (const w of ws) {
33
59
  if (!w || typeof w.name !== 'string' || !w.name || seen.has(w.name)) continue
34
- seen.add(w.name); out.push({ name: w.name, label: typeof w.title === 'string' && w.title ? w.title : w.name })
60
+ if (out.length >= max) {
61
+ if (w.name !== 'itinerary' || !out.length) continue
62
+ out.pop()
63
+ }
64
+ seen.add(w.name); out.push({ name: w.name, label: typeof w.title === 'string' && w.title ? w.title : w.name, ...(typeof w.kind === 'string' && w.kind ? { kind: w.kind } : {}) })
35
65
  }
36
66
  }
37
67
  return out
package/siri.js CHANGED
@@ -31,19 +31,110 @@ export async function siriKeyHash(key) { return b64(await crypto.subtle.digest('
31
31
 
32
32
  /** The account's record as the Sentinel wants it (siri.mjs normSiriRecord), from the store's copy. */
33
33
  export async function siriRecordFor(account, s = loadSiri()) {
34
- const rooms = Object.entries(s.rooms || {})
34
+ // ONE SPOKEN NAME, ONE SPACE (side sweep siri-merge-keeps-duplicate-spoken-names): renames made on two devices merge per Space, so a
35
+ // name can end up on two — and the Sentinel refuses the whole record, keeping every Space on its old names. The Space renamed LAST
36
+ // (`at`) keeps the name; the other is left out of what is sent until it is given another.
37
+ const owner = new Map()
38
+ for (const [room, r] of Object.entries(s.rooms || {})) { const was = owner.get(r.alias); if (!was || (Number(r.at) || 0) > (Number(s.rooms[was].at) || 0)) owner.set(r.alias, room) }
39
+ const rooms = Object.entries(s.rooms || {}).filter(([room, r]) => owner.get(r.alias) === room)
35
40
  return {
36
41
  // a key the hosted app's vault holds is here only as its hash (`tokenHash`; vaultAcctSecrets.js, review § 7.6) — the same value
37
42
  account, tokenHash: s.token ? await siriKeyHash(s.token) : String(s.tokenHash || ''),
38
43
  aliases: rooms.map(([room, r]) => ({ alias: r.alias, room, label: r.label || '', inboxPub: { x: r.pub.x, y: r.pub.y } })),
39
- defaultAlias: s.defaultRoom && s.rooms[s.defaultRoom] ? s.rooms[s.defaultRoom].alias : '',
44
+ defaultAlias: s.defaultRoom && s.rooms[s.defaultRoom] && owner.get(s.rooms[s.defaultRoom].alias) === s.defaultRoom ? s.rooms[s.defaultRoom].alias : '',
40
45
  created: Date.now(),
41
46
  }
42
47
  }
43
48
 
44
49
  /** Send the whole record, sealed to the attested Sentinel. Idempotent: the Sentinel REPLACES what it held. `s`: the record to
45
50
  * send — the store's, or a COPY with a change the caller keeps only once the Sentinel took it (pass 9, K#5). */
46
- export async function pushSiriRecord({ post, auth = {}, account, pins, verify, intake = null, s = loadSiri() } = {}) {
51
+ const EDIT_KEY = 'space:siri-pending-edit'
52
+ let publishing = Promise.resolve()
53
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
54
+ function applyEdit(base, next, latest) {
55
+ if ((base.rev || 0) !== (latest.rev || 0) || ((base.token || base.tokenHash) && (base.token || base.tokenHash) !== (latest.token || latest.tokenHash))) return latest
56
+ const result = structuredClone(latest)
57
+ for (const field of ['token', 'tokenHash', 'defaultRoom']) if ((field === 'defaultRoom' || !(latest.token || latest.tokenHash) || (base.token || base.tokenHash)) && !same(base[field], next[field]) && same(base[field], latest[field])) result[field] = next[field]
58
+ for (const room of new Set([...Object.keys(base.rooms), ...Object.keys(next.rooms)])) {
59
+ if (same(base.rooms[room], next.rooms[room]) || !same(base.rooms[room], latest.rooms[room])) continue
60
+ if (next.rooms[room] && (latest.gone?.[room] || 0) < next.rooms[room].at) result.rooms[room] = next.rooms[room]
61
+ else if (!next.rooms[room]) {
62
+ delete result.rooms[room]
63
+ result.gone = { ...(result.gone || {}), [room]: Math.max(Date.now(), (base.rooms[room]?.at || 0) + 1) }
64
+ if (result.defaultRoom === room) result.defaultRoom = ''
65
+ }
66
+ }
67
+ const aliases = Object.values(result.rooms).map(row => row.alias)
68
+ if (new Set(aliases).size !== aliases.length) throw new SiriError('This Siri name is already in use.', 'alias')
69
+ if (Object.keys(result.rooms).length > 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
70
+ return result
71
+ }
72
+ /** Does `cur` show every change the edit (base → next) made? */
73
+ function editShows(base, next, cur) {
74
+ // a FIRST setup's own new key yields to one another device made meanwhile (applyEdit): that is the merge, not a conflict
75
+ const minted = !(base.token || base.tokenHash)
76
+ for (const f of ['token', 'tokenHash', 'defaultRoom']) if (!(minted && f !== 'defaultRoom') && !same(base[f], next[f]) && !same(cur[f], next[f])) return false
77
+ const b = base.rooms || {}, n = next.rooms || {}, c = cur.rooms || {}
78
+ for (const room of new Set([...Object.keys(b), ...Object.keys(n)])) if (!same(b[room], n[room]) && !same(c[room], n[room])) return false
79
+ return true
80
+ }
81
+ export function pushSiriRecord(options = {}) {
82
+ const { account, s, base = loadSiri() } = options
83
+ const run = async () => {
84
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
85
+ const read = () => JSON.parse(localStorage.getItem(EDIT_KEY) || '{}')
86
+ const drop = entry => { const all = read(); if (same(all[account], entry)) { delete all[account]; if (Object.keys(all).length) localStorage.setItem(EDIT_KEY, JSON.stringify(all)); else localStorage.removeItem(EDIT_KEY) } }
87
+ // ★ A REPLAYED ENTRY THAT IS DROPPED MAY ALREADY BE AT THE SENTINEL (its answer was lost — that is why it was pending). Dropping it
88
+ // alone left the Sentinel aliasing a Space to an inbox key whose private half existed only in the dropped entry: captures
89
+ // accepted that nobody could open (second review, 2026-11-27). So the record this device DOES hold is sent at once; if that
90
+ // fails too, the next Siri change sends it.
91
+ const converge = async () => { try { await publishSiri({ ...options, s: loadSiri() }) } catch { /* the next Siri change sends the record */ } }
92
+ const transmit = async (entry, replayed = false) => {
93
+ for (let attempt = 0; attempt < 4; attempt++) {
94
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
95
+ if (!same(read()[account], entry)) throw new SiriError('The Siri setup changed.', 'siri_busy')
96
+ // An edit that can no longer apply (its name now taken, the 64 limit) is dropped, not kept: it was replayed before every
97
+ // later Siri save and failed each of them, for good (review of the sweep fixes, 2026-11-27; 2ccbc1bff)
98
+ const current = loadSiri()
99
+ let candidate
100
+ try { candidate = applyEdit(entry.base, entry.next, current) } catch (error) { drop(entry); if (replayed) await converge(); throw error }
101
+ // nothing to send: the edit is already in place — or another device changed the same Space or setting meanwhile and its change
102
+ // stands, which is no save to report (side sweep: siri-conflicting-edit-reported-as-saved: "Renamed" / "Off" was shown)
103
+ if (!attempt && same(candidate, current)) { drop(entry); if (!replayed && !editShows(entry.base, entry.next, current)) throw new SiriError('Another device changed this Siri setting first — check it and try again.', 'siri_conflict'); return { ok: true } }
104
+ const value = localStorage.getItem(EDIT_KEY)
105
+ const saved = options.confirmStored ? await options.confirmStored(EDIT_KEY, value) : localStorage.getItem(EDIT_KEY) === value
106
+ if (!saved) { drop(entry); if (replayed) await converge(); throw new SiriError('Could not save the pending Siri change on this device.', 'storage_failed') } // not kept either: a device that cannot store it would replay it for ever
107
+ if (!same(read()[account], entry) || (options.current && !options.current())) throw new SiriError('The Siri setup changed.', 'siri_busy')
108
+ let result
109
+ try { result = await publishSiri({ ...options, s: candidate }) }
110
+ catch (error) { if (error.definiteRefusal) { drop(entry); if (replayed) await converge() } throw error }
111
+ if (!same(read()[account], entry) || (options.current && !options.current())) throw new SiriError('The Siri setup changed.', 'siri_busy')
112
+ if (!same(current, loadSiri())) continue
113
+ saveSiri(candidate)
114
+ drop(entry)
115
+ // SENT, BUT NOT THIS EDIT (side sweep: siri-conflicting-edit-reported-as-saved — the rest): another device changed the same Space
116
+ // or setting while this edit was being published; the retry sent the record as it now stands (the Sentinel must hold what the
117
+ // device holds), without this edit's change — said as a conflict, never "Renamed" / "Off"
118
+ if (!replayed && !editShows(entry.base, entry.next, candidate)) throw new SiriError('Another device changed this Siri setting first — check it and try again.', 'siri_conflict')
119
+ return result
120
+ }
121
+ throw new SiriError('The Siri setup is changing. Try again.', 'siri_busy')
122
+ }
123
+ const pending = read()[account]
124
+ if (pending) {
125
+ await transmit(pending, true)
126
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
127
+ }
128
+ if (!s || same(base, s)) return publishSiri({ ...options, s: loadSiri() })
129
+ const entry = { base, next: s }
130
+ localStorage.setItem(EDIT_KEY, JSON.stringify({ ...read(), [account]: entry }))
131
+ return transmit(entry)
132
+ }
133
+ const operation = publishing.then(run)
134
+ publishing = operation.catch(() => {})
135
+ return operation
136
+ }
137
+ async function publishSiri({ post, auth = {}, account, pins, verify, intake = null, s = loadSiri() } = {}) {
47
138
  if (!s.token && !s.tokenHash) throw new SiriError('no Siri key on this device yet', 'no_key')
48
139
  const rec = await siriRecordFor(account, s)
49
140
  // THE INTAKE (docs/message-intake.md): { room, pub, drop } — the Sentinel then drops what was said into the account's
@@ -52,7 +143,7 @@ export async function pushSiriRecord({ post, auth = {}, account, pins, verify, i
52
143
  const { nonce, key } = await attest({ post, auth, pins, verify })
53
144
  const sealed = await sealTo(key, nonce, rec)
54
145
  const r = await post({ op: 'sentinel', sentinel: { mode: 'sirigrant', sealed }, ...auth })
55
- if (!r || r.error || !r.ok) throw new SiriError(`the Sentinel refused the record (${(r && (r.error || r.reason)) || 'no answer'})`, (r && r.error) || 'refused')
146
+ if (!r || r.error || !r.ok) throw Object.assign(new SiriError(`the Sentinel refused the record (${(r && (r.error || r.reason)) || 'no answer'})`, (r && r.error) || 'refused'), { definiteRefusal: !!r && !!(r.error || r.ok === false) && !(r.status >= 500) && !['busy', 'unreachable', 'sentinel_unavailable', 'timeout'].includes(r.error) })
56
147
  return r
57
148
  }
58
149
  export async function siriStatus({ post, auth = {} }) {
@@ -60,11 +151,33 @@ export async function siriStatus({ post, auth = {} }) {
60
151
  if (!r || r.error) throw new SiriError(`the Sentinel could not be reached (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
61
152
  return r
62
153
  }
63
- export async function siriRevoke({ post, auth = {} }) {
154
+ export function siriRevoke({ post, auth = {}, account, current = () => true, expectedRev }) {
155
+ const run = async () => {
156
+ if (!current()) throw new SiriError('The account changed.', 'account_changed')
157
+ if (expectedRev !== undefined) {
158
+ const s = loadSiri()
159
+ if (s.rev !== expectedRev || s.token || s.tokenHash) throw new SiriError('The Siri setup changed.', 'siri_busy')
160
+ }
161
+ const r = await revokeRecord(post, auth, current, expectedRev === undefined)
162
+ if (account) {
163
+ const pending = JSON.parse(localStorage.getItem(EDIT_KEY) || '{}')
164
+ delete pending[account]
165
+ if (Object.keys(pending).length) localStorage.setItem(EDIT_KEY, JSON.stringify(pending))
166
+ else localStorage.removeItem(EDIT_KEY)
167
+ }
168
+ return r
169
+ }
170
+ const operation = publishing.then(run)
171
+ publishing = operation.catch(() => {})
172
+ return operation
173
+ }
174
+ async function revokeRecord(post, auth, current, save) {
64
175
  const r = await post({ op: 'sentinel', sentinel: { mode: 'sirirevoke' }, ...auth })
65
176
  if (!r || r.error) throw new SiriError(`the Sentinel could not be reached (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
66
177
  // the setup is DELETED on every device of the account (pass 9, K#3): `rev` outranks any copy that still holds the old key,
67
178
  // and each Space is marked taken off, so no other device's copy brings an alias or the key back
179
+ if (!current()) throw new SiriError('The account changed.', 'account_changed')
180
+ if (!save) return r
68
181
  const was = loadSiri(), now = Date.now()
69
182
  saveSiri({ token: '', defaultRoom: '', rooms: {}, rev: (was.rev || 0) + 1, gone: { ...(was.gone || {}), ...Object.fromEntries(Object.keys(was.rooms).map((rm) => [rm, now])) } })
70
183
  return r
@@ -75,7 +188,7 @@ export async function siriRevoke({ post, auth = {} }) {
75
188
  // `mint` / `mintToken` (the hosted app, siriSheet.js — only where the vault holds Siri keys, acctHeld.js): the inbox keypair and
76
189
  // the Shortcut key are minted IN THE VAULT (vaultAcctSecrets.js, review § 7.6) → a public half / the key's hash; the room is a
77
190
  // held stub ({ alias, label, pub, at, held: 1 }) and the key is kept here as `tokenHash` only.
78
- export async function enableSiriHere({ room, label = '', alias, makeDefault = false, mint = null, mintToken = null } = {}) {
191
+ export async function enableSiriHere({ room, label = '', alias, makeDefault = false, mint = null, mintToken = null, draft = null } = {}) {
79
192
  const a = normSiriAlias(alias)
80
193
  if (!a) throw new SiriError('an alias is needed — the word you will say to Siri', 'alias')
81
194
  if (/[,:;]/.test(a)) throw new SiriError('an alias cannot contain , : or ;', 'alias')
@@ -83,10 +196,12 @@ export async function enableSiriHere({ room, label = '', alias, makeDefault = fa
83
196
  // THE SLOW PART FIRST, THEN THE CHANGE ON WHAT IS THERE NOW (sync sweep 2026-11-14 #2, as the SDK since 48ddb8733): the vault's mints
84
197
  // (up to 8 s each) or the keypair ran on a copy read BEFORE them, and saving that copy dropped another device's merge that landed
85
198
  // meanwhile — and the record pushed to the Sentinel lacked it.
86
- const s0 = loadSiri(); taken(s0)
199
+ const s0 = draft || loadSiri(); taken(s0)
200
+ if (!s0.rooms[room] && Object.keys(s0.rooms).length >= 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
87
201
  const tokenHash = (!s0.token && !s0.tokenHash && mintToken) ? await mintToken() : ''
88
202
  const fresh = s0.rooms[room] ? null : mint ? { held: 1, pub: await mint() } : { kp: await genRecipientKey() }
89
- const s = loadSiri(); taken(s)
203
+ const s = draft || loadSiri(); taken(s)
204
+ if (!s.rooms[room] && Object.keys(s.rooms).length >= 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
90
205
  if (!s.token && !s.tokenHash) { if (tokenHash) s.tokenHash = tokenHash; else if (mintToken) s.tokenHash = await mintToken(); else s.token = newSiriKey() }
91
206
  const cur = s.rooms[room]
92
207
  if (cur) s.rooms[room] = { ...cur, alias: a, label: label || cur.label, at: Date.now() } // `at` moves on a rename: the newer copy leads a merge
@@ -96,7 +211,7 @@ export async function enableSiriHere({ room, label = '', alias, makeDefault = fa
96
211
  }
97
212
  if (makeDefault) s.defaultRoom = room
98
213
  else if (s.defaultRoom === room) s.defaultRoom = ''
99
- return saveSiri(s)
214
+ return draft ? s : saveSiri(s)
100
215
  }
101
216
  export function disableSiriHere(room) {
102
217
  const s = loadSiri()
@@ -169,3 +284,19 @@ export async function collectSiriDrops({ post, auth = {}, room, send, deliver =
169
284
  for (const e of Array.isArray(r.elsewhere) ? r.elsewhere : []) if (e && typeof e.room === 'string') nameElsewhere(e.room)
170
285
  return { delivered, elsewhere: [...elsewhere.values()], ...(unopened ? { unopened } : {}), ...(more ? { more } : {}) }
171
286
  }
287
+
288
+ export const aliasFor = (title) => String(title || '').replace(/[,:;]/g, ' ').replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 32)
289
+ export function uniqueAlias(base, taken) {
290
+ const b = aliasFor(base) || 'space'
291
+ if (!taken.has(b)) return b
292
+ for (let n = 2; ; n++) { const c = `${b.slice(0, 32 - String(n).length - 1)} ${n}`; if (!taken.has(c)) return c }
293
+ }
294
+
295
+ /** The service's record differs from this list. `defaultRoom` (this device's default Space, '' for none): a changed default is
296
+ * a difference too — an unnamed phrase follows the service's default (side sweep). Not passed: aliases only, as before. */
297
+ export function siriAliasesDiffer(rooms, status, defaultRoom) {
298
+ const aliases = Array.isArray(status.aliases) ? status.aliases : []
299
+ if (aliases.length !== Object.keys(rooms).length || aliases.some(a => !rooms[a.room] || rooms[a.room].alias !== a.alias)) return true
300
+ if (defaultRoom === undefined) return false
301
+ return ((defaultRoom && rooms[defaultRoom] && rooms[defaultRoom].alias) || '') !== (status.defaultAlias || '')
302
+ }