@witbitz/sdk 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/siri.js ADDED
@@ -0,0 +1,278 @@
1
+ // siri.js — the page's half of the CONFIDENTIAL VOICE INBOX (docs/siri-inbox.md). A Shortcut posts what you said to
2
+ // siri.witbitz.chat; TLS ends inside the standing Sentinel, which seals the words to the Space's INBOX PUBLIC KEY and
3
+ // keeps the box until one of your devices collects it. This module:
4
+ // · mints the Shortcut's KEY (kept in store.js, riding the account; the Sentinel holds only its hash),
5
+ // · mints a Space's INBOX KEYPAIR when you enable Siri there (the private half never leaves your devices),
6
+ // · sends the account's RECORD to the Sentinel — every alias, every inbox public key, the key hash, the default —
7
+ // sealed to the Sentinel's attested share key exactly as a connection grant is (attest → sealTo → sirigrant),
8
+ // · COLLECTS: pulls the drops, opens this Space's with its private key, posts each as you (🎙 marks the voice), acks.
9
+ // Nothing here reaches the Sentinel except through the Lambda's op:'sentinel' door, which relays ciphertext both ways.
10
+ import { sealTo } from './sealShare.js'
11
+ import { genRecipientKey, openBox } from './e2ee.js'
12
+ import { loadSiri, saveSiri, normSiriAlias } from './store.js'
13
+
14
+ export const SIRI_ENDPOINT = 'https://siri.witbitz.chat/in'
15
+ export class SiriError extends Error { constructor(m, code = '') { super(m); this.code = code } }
16
+ // connections.js (the Sentinel attestation) pulls the Nitro verifier in; loaded only when a record is pushed, so this
17
+ // module — and the collector — stay loadable where there is no verifier (the tests, and one day a lighter surface).
18
+ // ⛑ STAMPED, like every other lazy import here (spaceClient.js, enclave.js, drawer.js). A BARE './connections.js' is a
19
+ // URL that never changes across builds, so a phone's 4-hour HTTP cache hands back the previous build's bytes under this
20
+ // build's signed manifest and the loader refuses the module: "Cannot load script due to integrity mismatch" — which is
21
+ // exactly what the owner's iPhone showed on the first Siri deploy (2026-09-26). spaces/test/stampedImports.test.mjs.
22
+ const attest = async (o) => (await import('./connections.js')).attestStandingSentinel(o)
23
+ export const SIRI_MARK = '🎙 ' // what a collected drop opens with, so everyone (and the assistant) sees it was said, not typed
24
+ const b64url = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
25
+ const b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
26
+
27
+ /** A fresh Shortcut key: 32 random bytes, base64url, prefixed so it is recognisable in the Shortcuts app. */
28
+ export const newSiriKey = () => 'wsk_' + b64url(crypto.getRandomValues(new Uint8Array(32)))
29
+ /** What the Sentinel keeps of the key: sha256, standard base64. */
30
+ export async function siriKeyHash(key) { return b64(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(key)))) }
31
+
32
+ /** The account's record as the Sentinel wants it (siri.mjs normSiriRecord), from the store's copy. */
33
+ export async function siriRecordFor(account, s = loadSiri()) {
34
+ const rooms = Object.entries(s.rooms || {})
35
+ return {
36
+ // a key the hosted app's vault holds is here only as its hash (`tokenHash`; vaultAcctSecrets.js, review § 7.6) — the same value
37
+ account, tokenHash: s.token ? await siriKeyHash(s.token) : String(s.tokenHash || ''),
38
+ 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 : '',
40
+ created: Date.now(),
41
+ }
42
+ }
43
+
44
+ /** Send the whole record, sealed to the attested Sentinel. Idempotent: the Sentinel REPLACES what it held. `s`: the record to
45
+ * send — the store's, or a COPY with a change the caller keeps only once the Sentinel took it (pass 9, K#5). */
46
+ const EDIT_KEY = 'space:siri-pending-edit'
47
+ let publishing = Promise.resolve()
48
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
49
+ function applyEdit(base, next, latest) {
50
+ if ((base.rev || 0) !== (latest.rev || 0) || ((base.token || base.tokenHash) && (base.token || base.tokenHash) !== (latest.token || latest.tokenHash))) return latest
51
+ const result = structuredClone(latest)
52
+ 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]
53
+ for (const room of new Set([...Object.keys(base.rooms), ...Object.keys(next.rooms)])) {
54
+ if (same(base.rooms[room], next.rooms[room]) || !same(base.rooms[room], latest.rooms[room])) continue
55
+ if (next.rooms[room] && (latest.gone?.[room] || 0) < next.rooms[room].at) result.rooms[room] = next.rooms[room]
56
+ else if (!next.rooms[room]) {
57
+ delete result.rooms[room]
58
+ result.gone = { ...(result.gone || {}), [room]: Math.max(Date.now(), (base.rooms[room]?.at || 0) + 1) }
59
+ if (result.defaultRoom === room) result.defaultRoom = ''
60
+ }
61
+ }
62
+ const aliases = Object.values(result.rooms).map(row => row.alias)
63
+ if (new Set(aliases).size !== aliases.length) throw new SiriError('This Siri name is already in use.', 'alias')
64
+ if (Object.keys(result.rooms).length > 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
65
+ return result
66
+ }
67
+ export function pushSiriRecord(options = {}) {
68
+ const { account, s, base = loadSiri() } = options
69
+ const run = async () => {
70
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
71
+ const read = () => JSON.parse(localStorage.getItem(EDIT_KEY) || '{}')
72
+ 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) } }
73
+ // ★ A REPLAYED ENTRY THAT IS DROPPED MAY ALREADY BE AT THE SENTINEL (its answer was lost — that is why it was pending). Dropping it
74
+ // alone left the Sentinel aliasing a Space to an inbox key whose private half existed only in the dropped entry: captures
75
+ // accepted that nobody could open (second review, 2026-11-27). So the record this device DOES hold is sent at once; if that
76
+ // fails too, the next Siri change sends it.
77
+ const converge = async () => { try { await publishSiri({ ...options, s: loadSiri() }) } catch { /* the next Siri change sends the record */ } }
78
+ const transmit = async (entry, replayed = false) => {
79
+ for (let attempt = 0; attempt < 4; attempt++) {
80
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
81
+ if (!same(read()[account], entry)) throw new SiriError('The Siri setup changed.', 'siri_busy')
82
+ // An edit that can no longer apply (its name now taken, the 64 limit) is dropped, not kept: it was replayed before every
83
+ // later Siri save and failed each of them, for good (review of the sweep fixes, 2026-11-27; 2ccbc1bff)
84
+ const current = loadSiri()
85
+ let candidate
86
+ try { candidate = applyEdit(entry.base, entry.next, current) } catch (error) { drop(entry); if (replayed) await converge(); throw error }
87
+ if (!attempt && same(candidate, current)) { drop(entry); return { ok: true } }
88
+ const value = localStorage.getItem(EDIT_KEY)
89
+ const saved = options.confirmStored ? await options.confirmStored(EDIT_KEY, value) : localStorage.getItem(EDIT_KEY) === value
90
+ 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
91
+ if (!same(read()[account], entry) || (options.current && !options.current())) throw new SiriError('The Siri setup changed.', 'siri_busy')
92
+ let result
93
+ try { result = await publishSiri({ ...options, s: candidate }) }
94
+ catch (error) { if (error.definiteRefusal) { drop(entry); if (replayed) await converge() } throw error }
95
+ if (!same(read()[account], entry) || (options.current && !options.current())) throw new SiriError('The Siri setup changed.', 'siri_busy')
96
+ if (!same(current, loadSiri())) continue
97
+ saveSiri(candidate)
98
+ drop(entry)
99
+ return result
100
+ }
101
+ throw new SiriError('The Siri setup is changing. Try again.', 'siri_busy')
102
+ }
103
+ const pending = read()[account]
104
+ if (pending) {
105
+ await transmit(pending, true)
106
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
107
+ }
108
+ if (!s || same(base, s)) return publishSiri({ ...options, s: loadSiri() })
109
+ const entry = { base, next: s }
110
+ localStorage.setItem(EDIT_KEY, JSON.stringify({ ...read(), [account]: entry }))
111
+ return transmit(entry)
112
+ }
113
+ const operation = publishing.then(run)
114
+ publishing = operation.catch(() => {})
115
+ return operation
116
+ }
117
+ async function publishSiri({ post, auth = {}, account, pins, verify, intake = null, s = loadSiri() } = {}) {
118
+ if (!s.token && !s.tokenHash) throw new SiriError('no Siri key on this device yet', 'no_key')
119
+ const rec = await siriRecordFor(account, s)
120
+ // THE INTAKE (docs/message-intake.md): { room, pub, drop } — the Sentinel then drops what was said into the account's
121
+ // message room, and any device of the account posts it (the app: intakeProducers.js). Without it: kept for a pull, as before.
122
+ if (intake && intake.room && intake.pub && intake.drop) rec.intake = { room: intake.room, pub: { x: intake.pub.x, y: intake.pub.y }, drop: intake.drop }
123
+ const { nonce, key } = await attest({ post, auth, pins, verify })
124
+ const sealed = await sealTo(key, nonce, rec)
125
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'sirigrant', sealed }, ...auth })
126
+ 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) })
127
+ return r
128
+ }
129
+ export async function siriStatus({ post, auth = {} }) {
130
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'siristatus' }, ...auth })
131
+ if (!r || r.error) throw new SiriError(`the Sentinel could not be reached (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
132
+ return r
133
+ }
134
+ export function siriRevoke({ post, auth = {}, account, current = () => true, expectedRev }) {
135
+ const run = async () => {
136
+ if (!current()) throw new SiriError('The account changed.', 'account_changed')
137
+ if (expectedRev !== undefined) {
138
+ const s = loadSiri()
139
+ if (s.rev !== expectedRev || s.token || s.tokenHash) throw new SiriError('The Siri setup changed.', 'siri_busy')
140
+ }
141
+ const r = await revokeRecord(post, auth, current, expectedRev === undefined)
142
+ if (account) {
143
+ const pending = JSON.parse(localStorage.getItem(EDIT_KEY) || '{}')
144
+ delete pending[account]
145
+ if (Object.keys(pending).length) localStorage.setItem(EDIT_KEY, JSON.stringify(pending))
146
+ else localStorage.removeItem(EDIT_KEY)
147
+ }
148
+ return r
149
+ }
150
+ const operation = publishing.then(run)
151
+ publishing = operation.catch(() => {})
152
+ return operation
153
+ }
154
+ async function revokeRecord(post, auth, current, save) {
155
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'sirirevoke' }, ...auth })
156
+ if (!r || r.error) throw new SiriError(`the Sentinel could not be reached (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
157
+ // the setup is DELETED on every device of the account (pass 9, K#3): `rev` outranks any copy that still holds the old key,
158
+ // and each Space is marked taken off, so no other device's copy brings an alias or the key back
159
+ if (!current()) throw new SiriError('The account changed.', 'account_changed')
160
+ if (!save) return r
161
+ const was = loadSiri(), now = Date.now()
162
+ saveSiri({ token: '', defaultRoom: '', rooms: {}, rev: (was.rev || 0) + 1, gone: { ...(was.gone || {}), ...Object.fromEntries(Object.keys(was.rooms).map((rm) => [rm, now])) } })
163
+ return r
164
+ }
165
+
166
+ /** Enable Siri for a Space on this account: an alias, an inbox keypair (once), optionally the default. Local only —
167
+ * the caller pushes the record. Returns the store's copy. */
168
+ // `mint` / `mintToken` (the hosted app, siriSheet.js — only where the vault holds Siri keys, acctHeld.js): the inbox keypair and
169
+ // the Shortcut key are minted IN THE VAULT (vaultAcctSecrets.js, review § 7.6) → a public half / the key's hash; the room is a
170
+ // held stub ({ alias, label, pub, at, held: 1 }) and the key is kept here as `tokenHash` only.
171
+ export async function enableSiriHere({ room, label = '', alias, makeDefault = false, mint = null, mintToken = null, draft = null } = {}) {
172
+ const a = normSiriAlias(alias)
173
+ if (!a) throw new SiriError('an alias is needed — the word you will say to Siri', 'alias')
174
+ if (/[,:;]/.test(a)) throw new SiriError('an alias cannot contain , : or ;', 'alias')
175
+ const taken = (st) => { for (const [rm, r] of Object.entries(st.rooms)) if (rm !== room && r.alias === a) throw new SiriError(`"${a}" already names another Space`, 'alias') }
176
+ // 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
177
+ // (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
178
+ // meanwhile — and the record pushed to the Sentinel lacked it.
179
+ const s0 = draft || loadSiri(); taken(s0)
180
+ if (!s0.rooms[room] && Object.keys(s0.rooms).length >= 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
181
+ const tokenHash = (!s0.token && !s0.tokenHash && mintToken) ? await mintToken() : ''
182
+ const fresh = s0.rooms[room] ? null : mint ? { held: 1, pub: await mint() } : { kp: await genRecipientKey() }
183
+ const s = draft || loadSiri(); taken(s)
184
+ if (!s.rooms[room] && Object.keys(s.rooms).length >= 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
185
+ if (!s.token && !s.tokenHash) { if (tokenHash) s.tokenHash = tokenHash; else if (mintToken) s.tokenHash = await mintToken(); else s.token = newSiriKey() }
186
+ const cur = s.rooms[room]
187
+ 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
188
+ else {
189
+ const f = fresh || (mint ? { held: 1, pub: await mint() } : { kp: await genRecipientKey() }) // removed elsewhere since the first read: made now
190
+ s.rooms[room] = f.held ? { alias: a, label, pub: { x: f.pub.x, y: f.pub.y }, held: 1, at: Date.now() } : { alias: a, label, pub: { x: f.kp.publicJwk.x, y: f.kp.publicJwk.y }, priv: f.kp.privateJwk, at: Date.now() }
191
+ }
192
+ if (makeDefault) s.defaultRoom = room
193
+ else if (s.defaultRoom === room) s.defaultRoom = ''
194
+ return draft ? s : saveSiri(s)
195
+ }
196
+ export function disableSiriHere(room) {
197
+ const s = loadSiri()
198
+ if (!s.rooms[room]) return s
199
+ s.gone = { ...(s.gone || {}), [room]: Math.max(Date.now(), (s.rooms[room].at || 0) + 1) } // recorded: off on the account's other devices too (pass 9, K#3)
200
+ delete s.rooms[room]
201
+ if (s.defaultRoom === room) s.defaultRoom = ''
202
+ return saveSiri(s)
203
+ }
204
+ /** A new key: the old Shortcut stops working the moment the record is pushed. */
205
+ export function rotateSiriKey() { const s = loadSiri(); s.token = newSiriKey(); delete s.tokenHash; return saveSiri(s) }
206
+
207
+ /**
208
+ * COLLECT: pull the account's drops; open and post the ones for THIS Space (in the order they were said); ack what
209
+ * was posted (and what can no longer be opened — a drop for a key this account no longer has is unrecoverable);
210
+ * report the Spaces that hold the rest, so the caller can say "Siri left a message for Family".
211
+ * `send(text)` posts as the member (composer.js sendNow); a send that throws leaves the drop UNacked, to be collected next time.
212
+ */
213
+ /**
214
+ * `deliver` — hand each drop to the CALLER instead of posting it (a builder, 2026-09-27: their app files captures into
215
+ * its own inbox verbatim, and posting starts an assistant turn they do not want). Posting was already this collector's
216
+ * one injected step, so `deliver` replaces that call and nothing else moves: same pull, same ack rules, same
217
+ * `elsewhere`. Two deliberate differences from the posting path:
218
+ * • the caller gets the words AS SPOKEN. `SIRI_MARK` exists to tell a ROOM that something was said rather than
219
+ * typed; an inbox has no audience to tell, and a caller that wants the mark can add it.
220
+ * • it gets `{ id, room, alias, at }` — which drop, which Space, the word that was actually said (how an app
221
+ * routes), and when Siri took it, not when we collected it.
222
+ * ★ AT-LEAST-ONCE, and the asymmetry is the point. A `deliver` that throws or rejects is NOT acked, so a failed inbox
223
+ * write never eats a capture — the next collect sees it again. The converse is the cost the caller must design for: a
224
+ * write that SUCCEEDS and whose ack then fails is redelivered, so dedupe on `id`.
225
+ */
226
+ // ⛔ ONE SPACE'S PULL, AND EACH DROP ACKED AS IT IS POSTED (state machines pass 9, K#6 K#9):
227
+ // · the pull named no Space, so the Sentinel leased EVERY Space's drops to a collector that posts one Space's: for a minute
228
+ // nobody could collect the others — the toast "open Family to deliver it" led to an empty pull, and a collector going Space
229
+ // after Space never reached the later ones. The pull now names the Space; the others come back named, not leased
230
+ // (`elsewhere` — a Sentinel before that names them only by handing them out, as before, and they are still listed);
231
+ // · the lease is fixed at the pull (60 s) and the ack came after the whole loop, each drop a full turn: past a minute
232
+ // another device (or a second collect) pulled the rest — those already posted too — and posted them again. Each drop is
233
+ // now acked as it is posted, and nothing more is posted COLLECT_WINDOW_MS after the pull: the rest wait, unacked, for
234
+ // the next pull (`more: true`).
235
+ export const COLLECT_WINDOW_MS = 45_000
236
+ // `open(drop, rec)` → the plaintext of a drop for a Space whose private key this copy does not hold (a held stub — the hosted
237
+ // app's vault opens it, siriCollect.js; review § 7.6). Without it such a drop is left, unopened, for a device that can.
238
+ export async function collectSiriDrops({ post, auth = {}, room, send, deliver = null, s = loadSiri(), now = Date.now, open = null } = {}) {
239
+ const t0 = now()
240
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'siripull', ...(room ? { room } : {}) }, ...auth })
241
+ if (!r || r.error || !Array.isArray(r.drops)) return { delivered: 0, elsewhere: [], error: (r && r.error) || 'no answer' }
242
+ const elsewhere = new Map()
243
+ const nameElsewhere = (rm) => { const rec = s.rooms[rm]; if (rec && rm !== room) elsewhere.set(rm, { room: rm, label: rec.label || rec.alias, alias: rec.alias }) }
244
+ let delivered = 0, unopened = 0, more = false
245
+ for (const d of r.drops) {
246
+ if (!d || typeof d.id !== 'string') continue
247
+ const rec = s.rooms[d.room]
248
+ if (!rec) continue // enabled on another device and not synced here yet: leave it for that device
249
+ if (d.room !== room) { nameElsewhere(d.room); continue }
250
+ if (now() - t0 > COLLECT_WINDOW_MS) { more = true; continue } // its lease runs out before it could be posted and acked: the next pull takes it
251
+ const text = rec.priv ? await openBox(d.box, rec.priv) : open ? await Promise.resolve().then(() => open(d, rec)).catch(() => null) : null
252
+ // ⛔ NOT OPENED HERE IS NOT UNOPENABLE (2026-11-07, the implicit-state-machine review): this acked — deleted — a drop this
253
+ // device's key could not open, as "sealed to a key this Space no longer has". A device that has not synced a rotated Siri key
254
+ // yet holds the OLD one, and destroyed for good what another of the person's devices could open. Left for that device; the
255
+ // Sentinel drops what nobody collects after DROP_TTL_MS (30 days, infra/cloud-computer/sentinel/siri.mjs).
256
+ if (text == null) { unopened++; continue }
257
+ try {
258
+ if (deliver) await deliver(text, { id: d.id, room: d.room, alias: d.alias, at: d.at })
259
+ else await send(SIRI_MARK + text)
260
+ } catch { continue /* not delivered: not acked; collected next time. A failed write must never cost the member the capture. */ }
261
+ delivered++
262
+ try { await post({ op: 'sentinel', sentinel: { mode: 'siriack', ids: [d.id] }, ...auth }) } catch { /* the next pull sees it again; the room dedupes nothing, so say so in the doc */ }
263
+ }
264
+ for (const e of Array.isArray(r.elsewhere) ? r.elsewhere : []) if (e && typeof e.room === 'string') nameElsewhere(e.room)
265
+ return { delivered, elsewhere: [...elsewhere.values()], ...(unopened ? { unopened } : {}), ...(more ? { more } : {}) }
266
+ }
267
+
268
+ export const aliasFor = (title) => String(title || '').replace(/[,:;]/g, ' ').replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 32)
269
+ export function uniqueAlias(base, taken) {
270
+ const b = aliasFor(base) || 'space'
271
+ if (!taken.has(b)) return b
272
+ for (let n = 2; ; n++) { const c = `${b.slice(0, 32 - String(n).length - 1)} ${n}`; if (!taken.has(c)) return c }
273
+ }
274
+
275
+ export function siriAliasesDiffer(rooms, status) {
276
+ const aliases = Array.isArray(status.aliases) ? status.aliases : []
277
+ return aliases.length !== Object.keys(rooms).length || aliases.some(a => !rooms[a.room] || rooms[a.room].alias !== a.alias)
278
+ }