@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
@@ -0,0 +1,332 @@
1
+ // sdkAccountSections.js — THE SPACES APP'S OPTIONAL ACCOUNT SECTIONS FOR A BUILDER (docs/sdk-account-format-plan.md phase 5,
2
+ // decision 7; the owner, 2026-11-13: "yes. Do 1-5" — no section named, so the plan's examples). `wb.account.contacts`, `.name`
3
+ // and `.roomDefaults`: each is read and written in the SAME doc, field and shape the Spaces app uses, in the account's index room
4
+ // (sdkAccount.js indexRoomOf), sealed under the app's account-store key (loc.app, as phase 3's `xindex`), and merged by the app's
5
+ // OWN rules — imported, never copied:
6
+ // contacts `xindex2.contacts` store.js mergeContactLists (a row by its email / @username / agent id; a newer `at` wins;
7
+ // a removal is a `deleted` row) + dedupePeople, at most 1000 — as saveContacts keeps them
8
+ // name `xindex.name` the app's rule: one name for the account, trimmed to 24; an empty name never replaces one
9
+ // roomDefaults `xroom-defaults` roomDefaultPrefs.js: writeRoomDefaults stamps each changed option, mergeRoomDefaults keeps
10
+ // the later edit per option (temporary and private assistants never both on)
11
+ // OPT-IN: a section reads nothing until the app first uses it (get, a change, on('change')); a builder that never does sees no
12
+ // request and no change. Once used, every account sync (the stream, the minute poll — sdkAccount.js _sync) reads it again and
13
+ // fires 'change' when another device moved it. A write lands only over the version read (409 → read, merge, again), never after
14
+ // a read that was not definitive (the clobber rule), and keeps every other field of the doc as it was: the index sync (xindex)
15
+ // and the vault keep (xindex2) write these docs too, each carrying what it does not own (sdkAccountDoc.js toAppIndex, vaultKeep.js
16
+ // keepToApp). No SDK release before 3.24.0 reads or writes any of the three docs.
17
+ import { mergeContactLists, normContact, dedupePeople, contactKey } from './store.js'
18
+ import { cleanRoomDefaults, writeRoomDefaults, ROOM_DEFAULTS_DOC } from './roomDefaultPrefs.js'
19
+ import { sealDoc } from './accountSeal.js'
20
+ import { BLOCKS_DOC, cleanBlocks, mergeBlocks, isBlocked } from './blocks.js' // blocks: the app's list and its rules
21
+ import { CHAT_LOCKS_DOC, cleanChatLocks, mergeChatLocks, validPin, newSalt, saltsOf, newLockId, stretchPin, pinIdFor, addLock, dropLock, lockOfTarget, liveLocks, accountTries, wrongTryIn, deleteLockedTargets } from './chatLock.js'
22
+
23
+ const fail = (code, msg, extra = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...extra })
24
+ const canon = (x) => JSON.stringify(x === undefined ? null : x)
25
+ const copy = (x) => (x === null || x === undefined ? null : JSON.parse(JSON.stringify(x)))
26
+ const obj = (x) => (x && typeof x === 'object' && !Array.isArray(x) ? x : null)
27
+
28
+ class Section {
29
+ /** @param {object} spec { doc, of(doc) → value, apply(doc, change) → the doc to write, or null when nothing moves, calls } */
30
+ constructor (ix, spec) { this._ix = ix; this._spec = spec; this._calls = spec.calls; this._val = null; this._master = null; this._used = false; this._fns = new Set(); this._remote = false }
31
+ /** What this device last read (null before the first read, and for another account). */
32
+ get value () { if (this._remote) return copy(this._val); const s = this._ix._backup._s; return s && s.master === this._master ? copy(this._val) : null }
33
+ /** Read it now. */
34
+ async get () { return this._pass(null) }
35
+ /** 'change': fn(value) when a read finds that another device changed it. */
36
+ on (ev, fn) { if (ev === 'change' && typeof fn === 'function') { this._fns.add(fn); if (!this._used && this._ix.enabled) this._pass(null).catch(() => null) } return this }
37
+ off (ev, fn) { this._fns.delete(fn); return this }
38
+ _seen (v, fire = false) { const was = this._val; this._remote = true; this._val = v; if (fire && canon(was) !== canon(v)) this._fire(v) } // in a vault: what the vault read
39
+ _fire (v) { for (const fn of this._fns) { try { fn(copy(v)) } catch { /* the app's callback */ } } }
40
+ async _pass (change) {
41
+ const ix = this._ix, d = this._spec.doc
42
+ if (!ix.enabled) throw fail('not_enabled', 'turn the account on first (wb.backup.enable or restore)')
43
+ this._used = true
44
+ const s0 = ix._backup._s, moved = () => { if (ix._backup._s !== s0) throw fail('account_changed', 'the account changed on this device during the call') }
45
+ for (let i = 0; i < 5; i++) {
46
+ const loc = await ix._where(); moved()
47
+ if (this._master !== loc.master) { this._master = loc.master; this._val = null }
48
+ if (!loc.made && !(s0.device && s0.device.made)) { await ix._ensureRoom(loc); moved() } // the index room, made once (as the sync does)
49
+ const got = await ix._read(loc, d, loc.app); moved()
50
+ if (!got.ok) throw fail(got.unopenable ? 'unopenable' : 'unreadable', `the account's ${d} could not be ${got.unopenable ? 'opened' : 'read'}`, { status: got.status })
51
+ const next = change === null ? null : this._spec.apply(got.doc, change)
52
+ if (next) {
53
+ const w = await ix._client().state(loc.room, loc.mk, d, await sealDoc(loc.app, next), 'account ' + d, 'device', got.v); moved()
54
+ if (w && w.status === 409) { await new Promise((r) => setTimeout(r, 10 + Math.floor(Math.random() * 40) * (i + 1))); continue } // another device wrote: merge over it
55
+ if (!w || w.status !== 200) throw fail('save_failed', `the account's ${d} could not be saved`, { status: w && w.status })
56
+ this._val = this._spec.of(next); return copy(this._val)
57
+ }
58
+ const was = this._val, now = this._spec.of(got.doc)
59
+ this._val = now
60
+ if (was !== null && canon(was) !== canon(now)) this._fire(now)
61
+ return copy(now)
62
+ }
63
+ throw fail('save_failed', `the account's ${d} kept changing under this device — try again`, { status: 409 })
64
+ }
65
+ }
66
+
67
+ export function codeAgentPreference(ix, agent) {
68
+ const pref = new Section(ix, {
69
+ doc: 'xindex2',
70
+ of: doc => String(doc?.code?.agent || ''),
71
+ apply(doc, name) {
72
+ const code = doc?.code || {}
73
+ if ((code.agent || '') === name) return null
74
+ return { ...doc, code: { ...code, agent: name, mod: Math.max(Date.now(), (Number(code.mod) || 0) + 1) } }
75
+ },
76
+ })
77
+ return pref._pass(agent === undefined ? null : agent)
78
+ }
79
+
80
+ export function computerModelPreference(ix, computer, model) {
81
+ const pref = new Section(ix, {
82
+ doc: 'xindex2',
83
+ of: doc => String(doc?.code?.models?.[computer] || ''),
84
+ apply(doc, ref) {
85
+ const code = doc?.code || {}, models = { ...code.models }
86
+ if ((models[computer] || '') === ref) return null
87
+ if (ref) {
88
+ if (!(computer in models) && Object.keys(models).length >= 32) throw fail('too_many_models', 'the account already keeps 32 computer model choices')
89
+ models[computer] = ref
90
+ } else delete models[computer]
91
+ return { ...doc, code: { ...code, models, mod: Math.max(Date.now(), (Number(code.mod) || 0) + 1) } }
92
+ },
93
+ })
94
+ return pref._pass(model === undefined ? null : model)
95
+ }
96
+
97
+ // ── contacts: xindex2.contacts ──
98
+ const contactsOf = (doc) => dedupePeople(((obj(doc) && Array.isArray(doc.contacts)) ? doc.contacts : []).map(normContact).filter(Boolean))
99
+ const withContacts = (doc, rows) => {
100
+ const cur = contactsOf(doc), next = dedupePeople(mergeContactLists(cur, rows).list).slice(0, 1000)
101
+ return canon(next) === canon(cur) ? null : { v: 2, ...(obj(doc) || {}), contacts: next, at: Date.now() }
102
+ }
103
+ const live = (list) => list && list.filter((c) => !c.deleted).map(({ deleted: _d, ...c }) => c)
104
+ // one row, stamped against the list each try read: newer than any copy of it (the app's LWW), a removal its tombstone
105
+ const stamped = (c, gone) => (cur) => {
106
+ const ex = cur.find((x) => contactKey(x) === contactKey(c))
107
+ if (gone && !ex) return []
108
+ return [{ ...(gone ? ex : c), ...(gone ? { deleted: true } : {}), at: Math.max(Date.now(), ((ex && ex.at) || 0) + 1) }]
109
+ }
110
+ const oneContact = (contact) => { const c = normContact(contact); if (!c) throw fail('invalid_argument', 'a contact needs an email or an @username (a saved assistant: an id and a name)'); return c }
111
+ class Contacts extends Section {
112
+ constructor (ix) { super(ix, { doc: 'xindex2', of: contactsOf, calls: ['get', 'set', 'remove', 'merge'], apply: (doc, rows) => withContacts(doc, typeof rows === 'function' ? rows(contactsOf(doc)) : rows) }) }
113
+ get value () { return live(super.value) }
114
+ async get () { return live(await super.get()) }
115
+ _fire (v) { super._fire(live(v)) } // the app keeps a removal as a row; the builder sees the people
116
+ /** Add or edit one contact ({ email | username, fn?, tel? } or a saved assistant { kind: 'agent', id, fn, persona? }); it wins over older copies. */
117
+ async set (contact) { return live(await this._pass(stamped(oneContact(contact), false))) }
118
+ /** Remove one (by its email, @username or assistant id) on every device — the app's tombstone row. */
119
+ async remove (contact) { return live(await this._pass(stamped(oneContact(contact), true))) }
120
+ /** Fold in a list as the app does on a sync or a restore: each row by its own `at`. */
121
+ async merge (list) { if (!Array.isArray(list)) throw fail('invalid_argument', 'contacts.merge takes a list'); return live(await this._pass(list)) }
122
+ }
123
+
124
+ // ── name: xindex.name ──
125
+ class Name extends Section {
126
+ constructor (ix) { super(ix, { doc: 'xindex', of: (doc) => (obj(doc) && typeof doc.name === 'string' ? doc.name : ''), calls: ['get', 'set'],
127
+ apply: (doc, name) => (obj(doc) && doc.name === name ? null : { v: 2, rooms: {}, devices: {}, signouts: {}, ...(obj(doc) || {}), name, at: Date.now() }) }) }
128
+ /** The person's name, for every device of the account (the app keeps 24 characters). An empty name is refused, as the app never writes one over a name. */
129
+ async set (name) { const n = String(typeof name === 'string' ? name : '').trim().slice(0, 24); if (!n) throw fail('invalid_argument', 'a name is needed'); return this._pass(n) }
130
+ }
131
+
132
+ // ── roomDefaults: xroom-defaults ──
133
+ const memStore = (v) => { const m = new Map(v ? [['space:default-room', JSON.stringify(v)]] : []); return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, x) => { m.set(k, String(x)) }, removeItem: (k) => { m.delete(k) } } }
134
+ const optionsOf = (doc) => { const c = cleanRoomDefaults(doc); if (!c) return null; const { v: _v, mods: _m, ...o } = c; return o }
135
+ class RoomDefaults extends Section {
136
+ constructor (ix) { super(ix, { doc: 'x' + ROOM_DEFAULTS_DOC, of: optionsOf, calls: ['get', 'set'],
137
+ apply: (doc, patch) => { const cur = cleanRoomDefaults(doc), next = writeRoomDefaults(patch, {}, memStore(cur), Date.now()); return next && canon(optionsOf(next)) !== canon(optionsOf(cur)) ? next : null } }) }
138
+ /** Change some of the New-Space defaults ({ quick, enclave, verified, lanes, temporary }: booleans; { assistant, model }: strings).
139
+ * `verified` is kept for older apps: today's app makes every new Space verified and ignores it (sync sweep 11-21 #11). */
140
+ async set (patch) {
141
+ const p = obj(patch), c = p && cleanRoomDefaults({ v: 1, ...p })
142
+ if (!p || !Object.keys(p).length || Object.keys(p).some((k) => k === 'v' || k === 'mods' || !c || !(k in c))) throw fail('invalid_argument', 'roomDefaults.set takes { quick, enclave, verified, lanes, temporary } (booleans) and { assistant, model } (strings)')
143
+ return this._pass(p)
144
+ }
145
+ }
146
+
147
+ // ── blocks: xblocks { v: 1, list } — the app's Block (blocks.js; docs/report-and-block.md §4; sync sweep 2026-11-13) ──
148
+ // One entry per person, keyed on what proves who they are (a verified email, an @username, the key that signed in one Space —
149
+ // space.blockIdentity); a newer `at` wins; an unblock is a `gone` tombstone that retires every older block it shares a proof with.
150
+ const blocksOf = (doc) => cleanBlocks(obj(doc) && Array.isArray(doc.list) ? doc.list : [])
151
+ const withBlocks = (doc, add) => { const cur = blocksOf(doc), next = mergeBlocks(cur, add); return canon(next) === canon(cur) ? null : { ...(obj(doc) || {}), v: 1, list: next } }
152
+ const liveBlocks = (list) => list && list.filter((b) => !b.gone)
153
+ const oneWho = (who) => { const w = obj(who), c = w && cleanBlocks([{ ...w, at: 1 }]); if (!c || !c.length) throw fail('invalid_argument', 'a block names a person by { email }, { user } or { room, sid } — space.blockIdentity(message)'); return { ...c[0], at: 0 } }
154
+ const nextAt = (cur) => Math.max(Date.now(), ...cur.map((b) => (b.at || 0) + 1))
155
+ class Blocks extends Section {
156
+ constructor (ix) { super(ix, { doc: 'x' + BLOCKS_DOC, of: blocksOf, calls: ['get', 'block', 'unblock', 'merge'], apply: (doc, add) => withBlocks(doc, typeof add === 'function' ? add(blocksOf(doc)) : add) }) }
157
+ get value () { return liveBlocks(super.value) }
158
+ async get () { return liveBlocks(await super.get()) }
159
+ _fire (v) { super._fire(liveBlocks(v)) } // the app keeps an unblock as a row; the builder sees who is blocked
160
+ /** Block a person on every device of the account ({ email?, user?, room?, sid?, name? } — space.blockIdentity(message), plus the name to show). */
161
+ async block (who) { const w = oneWho(who); return liveBlocks(await this._pass((cur) => [{ ...w, at: nextAt(cur) }])) }
162
+ /** Unblock: every live entry that names them by any proof goes, kept as a tombstone so another device does not bring them back. */
163
+ async unblock (who) {
164
+ const w = oneWho(who)
165
+ return liveBlocks(await this._pass((cur) => { const at = nextAt(cur), gone = cur.filter((b) => isBlocked(w, [b])); return (gone.length ? gone : [w]).map((b) => ({ ...b, name: '', at, gone: true })) }))
166
+ }
167
+ /** Fold in a list (another store's, a restore) as the app does: per person the newer entry wins. */
168
+ async merge (list) { if (!Array.isArray(list)) throw fail('invalid_argument', 'blocks.merge takes a list'); return liveBlocks(await this._pass(list)) }
169
+ /** Is this writer blocked? Any one proof they share counts. From what this device last read — or from `list`, one of your own. */
170
+ has (who, list) { return isBlocked(obj(who), list ? cleanBlocks(list) : (super.value || [])) }
171
+ }
172
+
173
+ /** Puts the sections on the account index (`ix.contacts`, `ix.name`, `ix.roomDefaults`, `ix.blocks`) and keeps them in `ix._sections`. */
174
+ class ChatLocks extends Section {
175
+ constructor(ix) { super(ix, { doc: 'x' + CHAT_LOCKS_DOC, of: cleanChatLocks, calls: ['get', 'merge', 'set', 'remove', 'check', 'match', 'changePin', 'previewDeleteAll', 'deleteAll'], apply: (doc, incoming) => { const next = typeof incoming === 'function' ? incoming(cleanChatLocks(doc)) : mergeChatLocks(doc, incoming); return canon(next) === canon(cleanChatLocks(doc)) ? null : next } }) }
176
+ async merge(doc) {
177
+ const clean = cleanChatLocks(doc); if (!clean) throw fail('invalid_argument', 'chatLocks.merge needs a chat-locks document')
178
+ return this._write(clean)
179
+ }
180
+ async set({ kind, target, pin, title } = {}) {
181
+ if (!['room', 'code'].includes(kind) || typeof target !== 'string' || !target || target.length > 300 || !validPin(pin)) throw fail('invalid_argument', 'chatLocks.set needs kind, target and a PIN of 4–12 digits')
182
+ const s0 = this._ix._backup._s, salt = saltsOf(await this.get())[0] || newSalt(), fingerprint = await pinIdFor(await stretchPin(pin, salt)), id = newLockId()
183
+ if (this._ix._backup._s !== s0) throw fail('account_changed', 'the account changed during PIN setup')
184
+ return this._write((doc) => { if (lockOfTarget(doc, kind, target)) throw fail('locked', 'this chat is already locked'); return addLock(doc, id, { kind, target, salt, pin: fingerprint, title }) })
185
+ }
186
+ async remove({ lockId } = {}) {
187
+ if (typeof lockId !== 'string' || !/^lk_[A-Za-z0-9_-]{22}$/.test(lockId)) throw fail('invalid_argument', 'chatLocks.remove needs a lockId')
188
+ return this._write((doc) => dropLock(doc, lockId))
189
+ }
190
+ async changePin({ lockId, pin, newPin } = {}) {
191
+ if (!validPin(newPin)) throw fail('invalid_argument', 'a PIN is 4–12 digits')
192
+ const s0 = this._ix._backup._s, doc = await this.get(), lock = liveLocks(doc).find((l) => l.lockId === lockId)
193
+ if (!lock) throw fail('not_found', 'that display lock does not exist')
194
+ const checked = await this.check({ lockId, pin })
195
+ if (!checked.ok) throw fail('wrong_pin', 'the current PIN was not accepted', { next: checked.next })
196
+ const fingerprint = await pinIdFor(await stretchPin(newPin, lock.salt))
197
+ if (this._ix._backup._s !== s0) throw fail('account_changed', 'the account changed during PIN setup')
198
+ return this._write((cur) => {
199
+ const current = liveLocks(cur).find((l) => l.lockId === lockId)
200
+ if (!current || current.pin !== lock.pin || current.salt !== lock.salt) throw fail('changed_meanwhile', 'the display lock changed; try again')
201
+ return addLock(cur, lockId, { kind: current.kind, target: current.target, salt: current.salt, title: current.title, pin: fingerprint })
202
+ })
203
+ }
204
+ _mintedAssistants(targets) {
205
+ const parents = new Set(targets.filter(t => t.kind === 'room').map(t => t.target))
206
+ return (this._ix._backup.rooms || []).filter(r => r.shared && parents.has(r.shared) && !r.detachedLane && r.laneOrigin === 'minted')
207
+ }
208
+ async previewDeleteAll() {
209
+ const owner = this._ix._backup._s
210
+ if (!(await this._ix.sync())?.ok || this._ix._backup._s !== owner) throw fail('index_unavailable', 'the account could not be synced')
211
+ const targets = liveLocks(await this.get()).map(({ kind, target, lockId }) => ({ kind, target, lockId }))
212
+ if (this._ix._backup._s !== owner) throw fail('account_changed', 'the account changed')
213
+ const locked = new Set(targets.filter(t => t.kind === 'room').map(t => t.target))
214
+ const privateAssistants = this._mintedAssistants(targets).filter(r => !locked.has(r.room))
215
+ .map(r => ({ room: r.room, parent: r.shared, title: r.label || '' }))
216
+ return { targets, privateAssistants }
217
+ }
218
+ async deleteAll({ includePrivateAssistants = false, privateAssistantRooms } = {}) {
219
+ if (privateAssistantRooms !== undefined && (!Array.isArray(privateAssistantRooms) || !privateAssistantRooms.every(r => typeof r === 'string'))) throw fail('invalid_argument', 'privateAssistantRooms must contain room IDs')
220
+ const owner = this._ix._backup._s, { targets, privateAssistants } = await this.previewDeleteAll()
221
+ const approved = privateAssistants.filter(r => privateAssistantRooms ? privateAssistantRooms.includes(r.room) : includePrivateAssistants === true).map(r => r.room)
222
+ return this._deleteTargets(targets, owner, undefined, approved)
223
+ }
224
+ async _deleteTargets(targets, owner, afterRemoval, assistants = []) {
225
+ const ix = this._ix
226
+ const current = () => !!owner && ix._backup._s === owner
227
+ const approved = new Set([...assistants, ...targets.filter(t => t.kind === 'room').map(t => t.target)])
228
+ return deleteLockedTargets(targets, {
229
+ stillLocked: async (id, kind, target) => {
230
+ if (!current()) return false
231
+ const lock = lockOfTarget(await this.get(), kind, target)
232
+ return current() && lock?.lockId === id
233
+ },
234
+ removeTarget: async (kind, target) => {
235
+ if (!current() || !await ix._deleteLockTarget(kind, target, current, approved, afterRemoval) || !current()) return false
236
+ if (afterRemoval) await afterRemoval(kind, target)
237
+ return current()
238
+ },
239
+ removeLock: async (id, kind, target) => {
240
+ if (!current()) throw fail('account_changed', 'the account changed')
241
+ await this._write(doc => lockOfTarget(doc, kind, target)?.lockId === id ? dropLock(doc, id) : doc, { retryMarker: true })
242
+ },
243
+ })
244
+ }
245
+ async match({ pin } = {}) {
246
+ if (!validPin(pin)) throw fail('invalid_argument', 'a PIN is 4–12 digits')
247
+ const owner = this._ix._backup._s, doc = await this.get(), dev = this._ix.deviceId
248
+ if (!dev) throw fail('not_enabled', 'this account has no device id for synced PIN attempts')
249
+ const before = accountTries(doc), salts = saltsOf(doc)
250
+ if (before.next > Date.now() || !salts.length) return { ok: false, matches: [], next: before.next }
251
+ const fingerprints = new Map()
252
+ for (const salt of salts) fingerprints.set(salt, await pinIdFor(await stretchPin(pin, salt)))
253
+ if (this._ix._backup._s !== owner) throw fail('account_changed', 'the account changed during PIN checking')
254
+ let matches = [], next = 0
255
+ await this._write(cur => {
256
+ const now = Date.now(), tries = accountTries(cur), locks = liveLocks(cur)
257
+ matches = []; next = tries.next
258
+ if (next > now || !locks.length) return cur
259
+ if (locks.some(l => !fingerprints.has(l.salt))) throw fail('changed_meanwhile', 'display locks changed; try again')
260
+ matches = locks.filter(l => fingerprints.get(l.salt) === l.pin)
261
+ .map(({ lockId, kind, target, title }) => ({ lockId, kind, target, title: title || '' }))
262
+ const result = matches.length ? cur : wrongTryIn(cur, dev, now)
263
+ next = accountTries(result, now).next
264
+ return result
265
+ })
266
+ return { ok: !!matches.length, matches, next }
267
+ }
268
+ async check({ lockId, pin } = {}) {
269
+ if (!validPin(pin)) throw fail('invalid_argument', 'a PIN is 4–12 digits')
270
+ const s0 = this._ix._backup._s, doc = await this.get(), lock = liveLocks(doc).find((l) => l.lockId === lockId)
271
+ if (!lock) throw fail('not_found', 'that display lock does not exist')
272
+ const before = accountTries(doc)
273
+ if (before.next > Date.now()) return { ok: false, next: before.next }
274
+ const fingerprint = await pinIdFor(await stretchPin(pin, lock.salt))
275
+ if (this._ix._backup._s !== s0) throw fail('account_changed', 'the account changed during PIN checking')
276
+ let ok = false, next = 0
277
+ const dev = this._ix.deviceId
278
+ if (!dev) throw fail('not_enabled', 'this account has no device id for synced PIN attempts')
279
+ await this._write((cur) => {
280
+ ok = false
281
+ const now = Date.now(), current = liveLocks(cur).find((l) => l.lockId === lockId), tries = accountTries(cur)
282
+ if (!current || current.pin !== lock.pin || current.salt !== lock.salt) throw fail('changed_meanwhile', 'the display lock changed; try again')
283
+ if (tries.next > now) { next = tries.next; return cur }
284
+ ok = fingerprint === current.pin
285
+ const result = ok ? cur : wrongTryIn(cur, dev, now)
286
+ next = accountTries(result, now).next
287
+ return result
288
+ })
289
+ return { ok, next }
290
+ }
291
+ async _write(change, { retryMarker = false } = {}) {
292
+ const ix = this._ix, owner = ix._backup._s, merged = await this._pass(change)
293
+ if (retryMarker && owner === ix._backup._s) {
294
+ owner.chatLockMarkPending = Math.max(Date.now(), (owner.chatLockMarkPending || 0) + 1)
295
+ ix._backup._changed?.()
296
+ }
297
+ try { await this._mark(owner) } catch (error) {
298
+ if (!retryMarker || owner !== ix._backup._s) throw error
299
+ }
300
+ return merged
301
+ }
302
+ async _mark(s0) {
303
+ const ix = this._ix, pending = s0.chatLockMarkPending
304
+ for (let i = 0; i < 5; i++) {
305
+ const loc = await ix._where(), got = await ix._read(loc, 'xindex', loc.app)
306
+ if (ix._backup._s !== s0) throw fail('account_changed', 'the account changed during chatLocks.merge')
307
+ if (!got.ok) throw fail('unreadable', 'the account index could not be read')
308
+ const marks = ((got.doc || {}).signouts || {})
309
+ const next = { ...(got.doc || {}), signouts: { ...marks, '@chatlocks': Math.max(Date.now(), (Number(marks['@chatlocks']) || 0) + 1) } }
310
+ const r = await ix._client().state(loc.room, loc.mk, 'xindex', await sealDoc(loc.app, next), 'chat locks present', 'device', got.v)
311
+ if (r && r.status === 409) continue
312
+ if (!r || r.status !== 200) throw fail('save_failed', 'the chat-lock presence mark could not be saved')
313
+ if (pending && ix._backup._s === s0 && s0.chatLockMarkPending === pending) { delete s0.chatLockMarkPending; ix._backup._changed?.() }
314
+ return
315
+ }
316
+ throw fail('save_failed', 'the account index kept changing; retry chatLocks.merge')
317
+ }
318
+ }
319
+
320
+ export function attachSections (ix) {
321
+ const all = { contacts: new Contacts(ix), name: new Name(ix), roomDefaults: new RoomDefaults(ix), blocks: new Blocks(ix), chatLocks: new ChatLocks(ix) }
322
+ Object.defineProperty(ix, '_sections', { value: all, enumerable: false })
323
+ for (const [k, s] of Object.entries(all)) Object.defineProperty(ix, k, { value: s, enumerable: true, configurable: true })
324
+ }
325
+ /** After an account sync: the sections the app uses are read again (a change another device made fires 'change'). */
326
+ export async function refreshSections (ix) {
327
+ for (const s of Object.values(ix._sections || {})) if (s._used && !s._remote) {
328
+ await s._pass(null).catch(() => null)
329
+ }
330
+ const owner = ix._backup._s
331
+ if (owner?.chatLockMarkPending && ix.chatLocks && !ix.chatLocks._remote) await ix.chatLocks._mark(owner).catch(() => {})
332
+ }
package/sdkAgui.js ADDED
@@ -0,0 +1,141 @@
1
+ // spaces/public/sdkAgui.js — a Witbitz Space as an AG-UI agent (the Agent–User Interaction protocol, 1.0; docs:
2
+ // https://witbitz.chat/docs/sdk-agents.md#ag-ui). It runs IN THE BUILDER'S PAGE, on the Space the SDK already decrypts there, so an AG-UI
3
+ // front end (CopilotKit's components, or any client of @ag-ui/client) shows a Witbitz room without the room leaving the
4
+ // device: the adapter turns what the Space already emits into AG-UI events, and AG-UI's input back into the Space.
5
+ //
6
+ // partial (the reply so far) → TEXT_MESSAGE_START / TEXT_MESSAGE_CONTENT (deltas) / TEXT_MESSAGE_END
7
+ // message (self: the reply) → closes the message (or carries it whole, when nothing streamed)
8
+ // proposal (waits for a human) → TOOL_CALL_START / ARGS / END, and the run ends with an INTERRUPT outcome
9
+ // input.resume (resolved/cancelled) → space.approve / space.deny → TOOL_CALL_RESULT
10
+ // input.context → this turn's `instructions` (never stored in the room)
11
+ // space.messages → MESSAGES_SNAPSHOT (aguiHistory) — the agent's initial messages
12
+ //
13
+ // No dependency: AG-UI's client is rxjs-based, so aguiAgent() takes the builder's OWN AbstractAgent and Observable and
14
+ // returns a subclass. aguiRun() is the plain async iterator under it.
15
+ // Not mapped (yet): AG-UI front-end tools (input.tools) — a Space's own tools and approvals cover the room; STATE events.
16
+
17
+ const now = () => Date.now()
18
+ const textOf = (content) => (typeof content === 'string' ? content : Array.isArray(content) ? content.filter((p) => p && p.type === 'text' && typeof p.text === 'string').map((p) => p.text).join('\n') : '')
19
+ const sentIds = new WeakMap() // per Space: the user-message ids already sent — AG-UI clients resend the whole history every run
20
+ const contextText = (ctx) => (Array.isArray(ctx) && ctx.length ? 'Context from the app:\n' + ctx.map((c) => `- ${c.description}: ${c.value}`).join('\n') : '')
21
+
22
+ /**
23
+ * Run one AG-UI run against a Space. → an async iterator of AG-UI 1.0 events, ending with RUN_FINISHED or RUN_ERROR.
24
+ * @param space a Space (or Lane) from the SDK
25
+ * @param input an AG-UI RunAgentInput ({ threadId, runId, messages, context?, resume? })
26
+ * @param opts { from, mode = 'always', timeoutMs = TURN_TIMEOUT_MS (~16 min, as space.turn()), graceMs = 1500, signal }
27
+ */
28
+ import { isLaneCopy } from './roomName.js'
29
+ import { TURN_TIMEOUT_MS } from './sdkTurn.js' // the same wait as space.turn() and the app (~16 min) // the one test for a lane's copy of its shared room's line
30
+ export function aguiRun(space, input, { from, mode = 'always', timeoutMs = TURN_TIMEOUT_MS, graceMs = 1500, signal } = {}) {
31
+ const queue = [], waiters = []
32
+ let done = false
33
+ const push = (e) => { if (done) return; const ev = { ...e, timestamp: now() }; const w = waiters.shift(); if (w) w({ value: ev, done: false }); else queue.push(ev) }
34
+ const end = () => { done = true; for (const w of waiters.splice(0)) w({ value: undefined, done: true }) }
35
+ const { threadId, runId } = input
36
+ const subs = []
37
+ const listen = (ev, cb) => { space.on(ev, cb); subs.push([ev, cb]) }
38
+ const unlisten = () => { for (const [ev, cb] of subs.splice(0)) { try { space.off(ev, cb) } catch { /* an older Space without off() */ } } }
39
+ let timer = null
40
+ const finish = (e) => { if (done) return; clearTimeout(timer); unlisten(); push(e); end() }
41
+ const fail = (message, code) => finish({ type: 'RUN_ERROR', message, code })
42
+
43
+ ;(async () => {
44
+ push({ type: 'RUN_STARTED', threadId, runId })
45
+ if (signal) { if (signal.aborted) return finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'cancelled' } }); signal.addEventListener('abort', () => finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'cancelled' } }), { once: true }) }
46
+
47
+ // 1. Resume: the person answered an interrupt — approve or deny the proposal in the room.
48
+ const resume = Array.isArray(input.resume) ? input.resume : []
49
+ for (const r of resume) {
50
+ const id = String(r.interruptId)
51
+ try {
52
+ if (r.status === 'resolved') { const out = await space.approve(id, r.payload && typeof r.payload === 'object' && r.payload.from ? { from: r.payload.from } : undefined); push({ type: 'TOOL_CALL_RESULT', messageId: 'wb-res-' + id, toolCallId: id, role: 'tool', content: JSON.stringify({ approved: true, result: out && out.result !== undefined ? out.result : null }) }) }
53
+ else { await space.deny(id); push({ type: 'TOOL_CALL_RESULT', messageId: 'wb-res-' + id, toolCallId: id, role: 'tool', content: JSON.stringify({ approved: false }) }) }
54
+ } catch (e) { return fail(`the room refused ${r.status === 'resolved' ? 'the approval' : 'the denial'}: ${(e && e.message) || e}`, (e && e.code) || 'refused') }
55
+ }
56
+
57
+ // 2. The new user message, if there is one this Space has not been sent yet.
58
+ const msgs = Array.isArray(input.messages) ? input.messages : []
59
+ const last = msgs[msgs.length - 1]
60
+ const sent = sentIds.get(space) || new Set(); sentIds.set(space, sent)
61
+ const fresh = last && last.role === 'user' && !sent.has(last.id) && textOf(last.content).trim() ? last : null
62
+ if (!fresh) { if (resume.length) return finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'success' } }); return fail('nothing to send: the last message is not a new user message, and nothing to resume', 'no_input') }
63
+
64
+ const mid = 'wb-' + runId
65
+ let started = false, streamed = '', proposals = []
66
+ const start = () => { if (!started) { started = true; push({ type: 'TEXT_MESSAGE_START', messageId: mid, role: 'assistant' }) } }
67
+ const content = (delta) => { if (delta) push({ type: 'TEXT_MESSAGE_CONTENT', messageId: mid, delta }) }
68
+ listen('partial', (p) => {
69
+ if (!p || typeof p.text !== 'string' || !p.text) return
70
+ start()
71
+ if (p.text.startsWith(streamed)) { content(p.text.slice(streamed.length)); streamed = p.text }
72
+ })
73
+ listen('proposal', (p) => { if (p && p.id && !proposals.some((x) => x.id === p.id)) proposals.push(p) })
74
+ listen('message', (m) => {
75
+ if (!m || m.self !== true || done) return
76
+ const final = String(m.text || '')
77
+ start()
78
+ content(final.startsWith(streamed) ? final.slice(streamed.length) : streamed ? '' : final)
79
+ push({ type: 'TEXT_MESSAGE_END', messageId: mid })
80
+ try { if (typeof space._pollPending === 'function') space._pollPending() } catch { /* the proposals poll still runs */ } // ask NOW: a card made during the turn sits on its own channel
81
+ // A proposal made during the turn can reach the device just after the reply (its own channel): wait a beat for it.
82
+ setTimeout(() => {
83
+ if (done) return
84
+ if (!proposals.length) return finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'success' } })
85
+ for (const p of proposals) {
86
+ push({ type: 'TOOL_CALL_START', toolCallId: p.id, toolCallName: p.action || 'proposal', parentMessageId: mid })
87
+ push({ type: 'TOOL_CALL_ARGS', toolCallId: p.id, delta: JSON.stringify(p.args || {}) })
88
+ push({ type: 'TOOL_CALL_END', toolCallId: p.id })
89
+ }
90
+ finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'interrupt', interrupts: proposals.map((p) => ({ id: p.id, reason: 'approval_required', toolCallId: p.id, ...(p.text ? { message: String(p.text) } : {}) })) } })
91
+ }, proposals.length ? 0 : graceMs)
92
+ })
93
+ timer = setTimeout(() => fail(`no reply from the room within ${Math.round(timeoutMs / 1000)} s`, 'timeout'), timeoutMs)
94
+ sent.add(fresh.id)
95
+ let r
96
+ try {
97
+ const instructions = contextText(input.context)
98
+ r = await space.send(textOf(fresh.content), { from: from || fresh.name || 'You', mode, ...(instructions ? { instructions } : {}) })
99
+ } catch (e) { sent.delete(fresh.id); return fail(String((e && e.message) || e), (e && e.code) || 'send_failed') }
100
+ if (r && r.ok === false) { sent.delete(fresh.id); return fail(r.error === 'busy' ? 'the room is busy answering an earlier message' : `the room did not take the message (${r.error || 'refused'})`, r.error || 'refused') }
101
+ })().catch((e) => fail(String((e && e.message) || e), 'adapter'))
102
+
103
+ return {
104
+ [Symbol.asyncIterator]() { return this },
105
+ next() { if (queue.length) return Promise.resolve({ value: queue.shift(), done: false }); if (done) return Promise.resolve({ value: undefined, done: true }); return new Promise((res) => waiters.push(res)) },
106
+ return() { finish({ type: 'RUN_FINISHED', threadId, runId, outcome: { type: 'cancelled' } }); queue.length = 0; return Promise.resolve({ value: undefined, done: true }) },
107
+ }
108
+ }
109
+
110
+ /** The room so far, as AG-UI messages: the assistant's replies as `assistant`, everyone else's as `user` with their name.
111
+ * → a MESSAGES_SNAPSHOT event (its `.messages` are an agent's initial messages). */
112
+ export function aguiHistory(space) {
113
+ const messages = (space.messages || [])
114
+ .filter((m) => m && typeof m.text === 'string' && m.text && !m.sys && m.kind !== 'data' && m.kind !== 'fork')
115
+ // A LANE COPY (a line mirrored from the shared room) is never this agent's turn, even when the shared room's own
116
+ // assistant wrote it: a `user` message, named as from the shared room (sync sweep, 2026-10-10).
117
+ .map((m, i) => { const copy = isLaneCopy(m), who = m.from || m.name; return { id: String(m.id || 'wb-' + i), role: m.self === true && !copy ? 'assistant' : 'user', content: m.text, ...(who || copy ? { name: String(who || 'someone') + (copy ? ' (from the shared room)' : '') } : {}) } })
118
+ return { type: 'MESSAGES_SNAPSHOT', timestamp: now(), messages }
119
+ }
120
+
121
+ /**
122
+ * An AG-UI agent for a Space, built from the BUILDER's own `AbstractAgent` (@ag-ui/client) and `Observable` (rxjs):
123
+ * import { AbstractAgent } from '@ag-ui/client'; import { Observable } from 'rxjs'
124
+ * const agent = aguiAgent({ AbstractAgent, Observable }, space, { threadId: space.room })
125
+ * `opts` passes to aguiRun (from, mode, timeoutMs, graceMs) and `agentConfig` to the AbstractAgent constructor.
126
+ */
127
+ export function aguiAgent({ AbstractAgent, Observable }, space, { threadId, agentConfig = {}, ...runOpts } = {}) {
128
+ if (typeof AbstractAgent !== 'function' || typeof Observable !== 'function') throw new TypeError('aguiAgent needs { AbstractAgent, Observable } — from @ag-ui/client and rxjs')
129
+ class WitbitzAgent extends AbstractAgent {
130
+ run(input) {
131
+ return new Observable((sub) => {
132
+ const ac = new AbortController()
133
+ ;(async () => {
134
+ try { for await (const e of aguiRun(space, input, { ...runOpts, signal: ac.signal })) sub.next(e); sub.complete() } catch (e) { sub.error(e) }
135
+ })()
136
+ return () => ac.abort()
137
+ })
138
+ }
139
+ }
140
+ return new WitbitzAgent({ threadId: threadId || space.room, initialMessages: aguiHistory(space).messages, ...agentConfig })
141
+ }
package/sdkAttest.js ADDED
@@ -0,0 +1,34 @@
1
+ // sdkAttest.js — A DEVICE THAT PROVES ITSELF, through the SDK: new Witbitz({ attest: { bridge } }). Witbitz's own cloud device in its
2
+ // enclave (cloud-device/attestBridge.mjs; the owner, 2026-11-21) uses it to read and post in the person's attested Spaces. It is the
3
+ // app's own machinery, reused: the device half that binds a proof to the room's fresh challenge and the member's signing key
4
+ // (deviceAttest.js), and the read provider spaceClient asks before a read of an attested room.
5
+ //
6
+ // RETIRED in 4.0.0 (the owner, 2026-11-22: "We dont need any emulation rooms"): `attest: { app }` — a builder's page proving it was
7
+ // SERVED as its app with the browser emulation's public platform key. A web page vouching for itself is no client check.
8
+ import { makeDeviceAttest, noteChallenge } from './deviceAttest.js'
9
+ import { setReadAttestProvider } from './spaceClient.js'
10
+
11
+ /** makeSdkAttest({ bridge, app?, client: () => spaceClient, storage?, installRead? }) →
12
+ * { turnFields(room, spk) → { chal, attestation } | {}, notePoll(room, r), noteAnswer(r), lastWhy() }
13
+ * `bridge`: the device (deviceAttest.js's contract). `app`: a label only — it names where the SDK keeps this device's signing key. */
14
+ export function makeSdkAttest ({ app = 'device', bridge, client, storage, installRead = true, log = () => {} } = {}) {
15
+ if (!bridge || typeof bridge.platform !== 'function') throw Object.assign(new Error('witbitz: attest is { bridge } — a device that proves itself'), { code: 'invalid_argument' })
16
+ const da = makeDeviceAttest({ bridge: () => bridge, client: { attestEnroll: (a) => client().attestEnroll(a) }, ...(storage ? { storage } : {}), log })
17
+ if (installRead) {
18
+ // a read of an attested room (spaceClient asks): the proof bound to the room's newest challenge and to THIS room
19
+ setReadAttestProvider(async (room, o) => {
20
+ if (o && o.challenge) noteChallenge(room, { challenge: o.challenge })
21
+ const a = await da.attestFor({ room, spk: { readRoom: String(room) } }).catch(() => null)
22
+ return a && a.attestation ? { read: { chal: a.chal, attestation: a.attestation } } : null
23
+ })
24
+ }
25
+ return {
26
+ app,
27
+ /** The fields a turn adds: { chal, attestation } — {} when there is no challenge from the room yet. */
28
+ async turnFields (room, spk) { const a = await da.attestFor({ room, spk }).catch(() => null); return a && a.attestation ? a : {} },
29
+ /** A poll answer carries the room's fresh challenge (an attested room). */
30
+ notePoll (room, r) { if (r && typeof r.challenge === 'string' && r.challenge) noteChallenge(room, r) },
31
+ noteAnswer: (r) => da.noteAnswer(r),
32
+ lastWhy: () => da.lastWhy(),
33
+ }
34
+ }