@witbitz/sdk 0.0.0-stage → 4.3.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -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/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
package/witbitz-sdk.js ADDED
@@ -0,0 +1,3835 @@
1
+ // witbitz-sdk.js — the small, stable Witbitz application SDK.
2
+ //
3
+ // Witbitz is a runtime: a shared room with humans, an AI agent, sealed persistent state, identity and authority. This
4
+ // SDK is the thin surface over it — the sealing, the room key, the op-dispatch and the poll loop all disappear, so a
5
+ // static page can stand up a private, agent-backed, link-shared room in a few lines:
6
+ //
7
+ // import { Witbitz } from 'https://witbitz-spaces.pages.dev/witbitz-sdk.js'
8
+ // const wb = new Witbitz()
9
+ // const space = await wb.createSpace({ agent: { name: 'Helper', instructions: 'You help plan trips.' } })
10
+ // space.on('message', (m) => render(m)) // m = { from, text, self, id, ts }
11
+ // await space.send('Plan me a weekend in Kyoto') // the agent answers on its own turn → arrives via on('message')
12
+ // console.log(space.shareLink) // the link IS the auth — hand it to someone to let them in
13
+ //
14
+ // It re-exports the SAME reference client the production Spaces app runs on (nothing forked, nothing reimplemented): a
15
+ // cross-origin import of this one URL pulls the transitive crypto from this origin automatically. The room key never
16
+ // reaches the server — only its commitment — and reads are content-blind (the client opens the sealed ledger locally).
17
+ // `space.sealedProof()` returns the exact opaque bytes the server stores, so an app can PROVE that at rest.
18
+ import { makeSpaceClient } from './spaceClient.js'
19
+ import { ownAdmissionEntries } from './emptySpaces.js'
20
+ import { memberHash } from './rosterHash.js'
21
+ import { verifyAttestation } from './nitroVerify.js' // devRoot: the dev server's Sentinel, checked under its root
22
+ import { AccountBackup } from './sdkBackup.js'
23
+ import { linkLanes, laneLinkTool } from './sdkLaneLink.js' // lane.link(other): two of a member's assistants ask each other
24
+ import { InviteAccount, adoptGrant as adoptRoomGrant, changeMembers as changeMembersInPlace, rotateKey as rotateKeyInPlace, relink } from './sdkRekey.js' // a verified room changes its members in place (https://witbitz.chat/docs/sdk-people.md#members)
25
+ import { Computers } from './sdkComputers.js' // wb.computers: the person's cloud computers (docs/sdk-cloud-computers.md)
26
+ import { opensEnvelopes, sealsIdentity } from './reqEnvelope.js' // the sealed request envelope: does a live enclave open it
27
+ import { SpaceSafeMedia } from './sdkSafeMedia.js' // space.safeMedia: photos and PDFs shown from copies an attested enclave made safe (docs/safe-media.md)
28
+ import { SpaceSchedules } from './sdkSchedules.js'
29
+ import { CloudDevice, SpaceAlwaysOn, assertNotKept, disconnectRoomLanes } from './sdkCloudDevice.js'
30
+ import { linkKeptAgent, unlinkKeptAgent } from './sdkKeptAgent.js'
31
+ import { otherWaysRows, typedMcpUrl, spacesUsingConnection, grantStatus } from './connOtherWays.js'
32
+ import { CATALOG as CONNECTION_CATALOG } from './connCatalog.js'
33
+ import { resendInvitation } from './sdkInvitations.js'
34
+ import { removedCopy, sharedRemovedCopy } from './removedMessage.js'
35
+ import { entryKeyOf as removedEntryKey } from './ledgerView.js'
36
+ import { fileReport, REPORT_REASONS } from './sdkReport.js' // space.report(): the Spaces app's Report (App Store rule 1.2; docs/report-and-block.md §3)
37
+ import { safeMediaReady } from './safeMedia.js'
38
+ import { A2AAccount, LaneA2A, VaultLaneA2A, pendingOf } from './sdkA2A.js' // wb.a2a + lane.a2a: outside agents into a private lane (https://witbitz.chat/docs/sdk-agents.md#a2a)
39
+ import { makeSdkAttest } from './sdkAttest.js' // attest: { bridge } — a device that proves itself (the cloud device)
40
+ import { Builds } from './sdkBuilds.js' // wb.builds: which enclave build THIS PERSON accepts ('mine'), or any Witbitz publishes (default)
41
+ import { Erasure } from './sdkErase.js' // wb.erasure: the deletion commitment, the membership mark, the filed erase list (https://witbitz.chat/docs/sdk-builder.md#user-erasure)
42
+ import { AccountIndex } from './sdkAccount.js'
43
+ import { receiptFor } from './usageReceipts.js' // a turn's usage receipt address (docs/usage-receipts.md) // wb.account: the live index between the account's devices
44
+ import { aguiRun, aguiHistory, aguiAgent } from './sdkAgui.js' // a Space as an AG-UI 1.0 agent, in the builder's page (https://witbitz.chat/docs/sdk-agents.md#ag-ui)
45
+ export { aguiRun, aguiHistory, aguiAgent }
46
+ export { verifyEat, fetchAndVerifyEat, EAT_PROFILE } from './eat.js' // RATS/EAT: check a Witbitz enclave with a standard token (https://witbitz.chat/docs/sdk-keys.md#eat)
47
+ import { Speech } from './sdkSpeech.js' // wb.speak(): text read aloud, the Spaces app's "Play aloud" player (speechOut.js)
48
+ import { Dictation, voiceForDictation } from './sdkDictation.js' // wb.dictation(): press-to-talk, the mic straight to Tinfoil's realtime enclave
49
+ import { Protect } from './sdkProtect.js' // wb.protect: what the app keeps on the device, sealed under a passkey-derived key
50
+ import { boxesHash, bareEC, jkey, deriveRoster } from './spaceFork.js' // the membership fork's notice format, shared with the app
51
+ import { normAdmission, checkAdminCollections, judgeMove, newRoomKeepsGov } from './emailFork.js' // the gate's rules with the app; following a move an OLDER client made (a Space no longer moves: #members)
52
+ import { deleteOwnRoom } from './roomDelete.js'
53
+ import { sealTo, openBox, commit as keyCommit } from './e2ee.js'
54
+ import { roomUsageRecords, summarizeUsage, usageCsv } from './usageSummary.js'
55
+ import { stillOnList } from './memberChange.js'
56
+ import { ROSTER_DOC, selfRow, ensureSelf, unseenIn, entriesMissing, announcedIn, privateInvitationMatches, listRoster, verifiedPosters, membersView } from './roomRoster.js'
57
+ import { reconstructMk } from './splitKeyClient.js' // the split-key combine + the mandatory commitment check
58
+ // The account half — sign-in, connections, the Siri inbox — reuses the SAME modules the Spaces app runs (nothing
59
+ // forked): the Sentinel attestation + grant sealing (connections.js), the Siri record and collector (siri.js), and the
60
+ // sealing primitives. The SDK adds only the session and the state the app used to keep in its own store.
61
+ import { attachConnection, listConnections, detachConnection, attestStandingSentinel, roomEntry, CONNECTION_HOST, STANDING_SENTINEL_PCR0, startMcpSignIn, finishMcpSignIn, attachMcp as attachMcpServer, listMcpTools, isCurated } from './connections.js'
62
+ import { readsAutoFor } from './connCatalog.js'
63
+ import { lockConnections, wrapProof } from './connWrap.js' // move 3: the old-form connections locked under their key
64
+ import { dispKeyOf, sealDisp } from './connDisp.js' // step 2: a connection's name sealed to the account's devices (docs/standing-sentinel.md)
65
+ import { recommendedChoice } from './mcpRecommended.js' // an MCP server's recommended tools: reads run on their own, changes ask (as the app)
66
+ import { roomTool, roomJob } from './connectionEntry.js' // one MCP tool's bounded room form
67
+ import { withBook, bookTheRest } from './toolBooks.js' // an MCP connection's tools as a sealed tool book, as the app
68
+ import { siriRecordFor, collectSiriDrops, newSiriKey, SIRI_ENDPOINT } from './siri.js'
69
+ import { sealTo as sealToEnclave } from './sealShare.js'
70
+ import { genRecipientKey } from './e2ee.js'
71
+ import { genKeypair, spkNonce } from './entrySig.js'
72
+ import { normSiriAlias } from './store.js'
73
+ // ── THE CONFIDENTIAL TIER (2026-09-27, a builder: "enclave tier in createSpace and privateLane, so the room key never
74
+ // reaches the relay"). Every piece below is the SAME module the Spaces app runs — the attestation (enclaveRoute), the
75
+ // room's acceptance block and its ENFORCEMENT (enclaveAccept gatedKey), the claim parser. Nothing about the security of
76
+ // this tier is reimplemented here; the SDK supplies the session and the choreography the app kept inline in its page.
77
+ import { attestEnclave } from './enclaveRoute.js'
78
+ import { publishedKey } from './enclaveAccept.js'
79
+ import { enclaveClaim } from './enclaveClaim.js'
80
+ // ROOM STREAMS (https://witbitz.chat/docs/sdk-rooms.md#live): the reply as it is written, and "the ledger grew", pushed down a
81
+ // socket on the relay instead of found by polling. The SAME reader the Spaces app runs; the SDK connects on /s/ — the
82
+ // relay's path for pages on any origin (a builder's app is not a Witbitz origin).
83
+ import { openRoomStream } from './roomStreamClient.js'
84
+ import { makeEmailPost, emailStart, emailVerify, emailRefresh } from './emailSignIn.js' // the email-code protocol the vault and the Spaces app use
85
+ import { answerDeviceCall } from './deviceCall.js' // one way to answer a device call, shared with the Spaces app
86
+ import { LANE_PERSONA, LANE_AGENT_NAME, inheritToolsFrom, laneInherits, gatedStub } from './laneConfig.js'
87
+ import { renderSharedViews, viewsNamedIn, SHARED_VIEWS_DOC } from './sharedViews.js'
88
+ import { receiptOf } from './sealedReceipt.js' // a verified room's sealedProof, computed by the member
89
+ import { replyQuote } from './replyQuote.js' // the reply quote — one rule with the app's reply strip
90
+ import { makeLedgerView, needsTailResync, REACTION_RESYNC_TAIL, entryKeyOf, readAllPages } from './ledgerView.js' // how the Spaces app merges a room's entries
91
+ import { turnVerdict, QUEUE_RETRY_MS, QUEUE_MAX_TRIES } from './turnVerdict.js' // the send hold + answer reading the Spaces app uses
92
+ /** A turn's answer with `ok` always a boolean: posted / silent / pending → true; anything with an error, or busy, refused,
93
+ * failed, no answer → false (Space#_turnHeld). */
94
+ const withTurnOk = (r) => { const k = turnVerdict(r).kind; return withUsage({ ...(r || {}), ok: !(r && r.error) && (k === 'ok' || k === 'silent' || k === 'pending') }) }
95
+ /** The server's usage record → { tokensIn, tokensOut, tokensCached, costMicros, costUsd, calls, models, source } (sdkTurn turnUsage). */
96
+ const withUsage = (r) => { if (r && r.usage) { const u = turnUsage(r.usage); if (u) r.usage = u; else delete r.usage } return r }
97
+ import { renameRefusalText } from './renameRefusal.js' // why a rename was refused — the app's words
98
+ import { isTitleEntry, latestTitle, titleFromDoc, sendRename as sendRoomRename, cleanTitle, isDirect, directPeer, isLaneCopy as laneCopy } from './roomName.js' // a room's NAME — the same rule the Spaces app reads it by
99
+ import { pollVerdict } from './pollVerdict.js' // one verdict on a poll answer, shared with the Spaces app
100
+ import { hide, redacted, REDACTED } from './sdkRedact.js'
101
+ import { WitbitzAdmin } from './witbitz-admin.js'
102
+ import { Turn, turnUsage } from './sdkTurn.js' // space.turn(): a turn you can hold (sdk-roadmap item 6)
103
+ import { planChange } from './sdkPlan.js'
104
+ import { schemaProblem } from './rowSchema.js' // a collection's row schema — the same verdict as the server
105
+ import { scopedAccount, tokenClaims, firstPartyAppOf, sentinelAccount, VAULTED_APP } from './accountScope.js' // the account a sign-in may act on — the same derivation as the Lambda
106
+ import { connectVault } from './sdkVault.js' // a builder-hosted vault holds the keys; this page never does (docs/sdk-vault-mode.md)
107
+ import { makeTurnFeed } from './turnFeed.js' // one reading of a running turn, shared with the Spaces app
108
+ import { roomRegion, regionCode, DEFAULT_REGION, newRoomId } from './regions.js' // a room's home region is in its id (docs/multi-region.md)
109
+
110
+ // The room's reply mode and model pick: ONE module with the Spaces app (roomSettings.js — the same names, the same sealed
111
+ // `agentmode` and `model` docs), so the SDK and the app are one setting, not two that drift.
112
+ import { REPLY_MODES, REPLY_MODE_LABEL, modeFromDoc, modelPickFromDoc, turnModelOf, roomDefaultReplyMode } from './roomSettings.js'
113
+ import { TOOLRULES_DOC, RULE_VALUES, toolRulesDocOf, rulesFromDoc } from './toolRules.js' // which tools run on their own (space.toolRules)
114
+ import { rosterParticipants } from './rosterCount.js' // the server's count (agent/rosterCount.mjs) — replyMode()'s default
115
+ const NAME_RECHECK_EVERY = 20 // = roomTitle.js RETITLE_EVERY / agent/spaceService.mjs RETITLE_AFTER
116
+ const SETTINGS_FRESH_MS = 20_000 // a member may change either from another client; a long-lived handle re-reads them before a turn after this long
117
+ const DEFAULT_ENDPOINT = 'https://api.witbitz.chat/v1/space' // the public, self-authenticating Space endpoint (a Space authenticates by its key-commitment, not a tenant account)
118
+ const DEFAULT_VIEWER = 'https://witbitz-spaces.pages.dev' // shareLink base — the reference Spaces app ORIGIN (the client appends `/space?room=…#…`). Override to point links at your own viewer origin.
119
+
120
+ const DEFAULT_ASSIST = LANE_PERSONA // laneConfig.js — the Spaces app's lane persona; one definition for both
121
+
122
+ // Turn friendly `actions` into the client-tool wire shape + a handler map. Each action = { name, description, input?, run }.
123
+ // A write is `mode: 'propose'` → the agent can only PROPOSE it; a human approves before `run` executes on the device.
124
+ // Honored only on a private LANE (client-executed tools are lane-only server-side).
125
+ // An action may also be a READ — `mode: 'await'` — which the agent calls DURING a turn for something only the device
126
+ // knows; the SDK runs `run` and hands the result back to the turn. Anything else stays a proposal a human approves.
127
+ // PER-TURN INSTRUCTIONS (a builder, 2026-09-29): prepending the app's context block to every message stored ~30 copies of
128
+ // it in the window the assistant re-reads each turn (~30k tokens), and moving it into a tool description made the facts
129
+ // usable but the INSTRUCTIONS unheeded. `instructions` rides the turn, reaches the model as its own labelled section for
130
+ // this reply, and is never stored. Bounded by the server too (8,000 characters).
131
+ const stopOpt = (k) => (typeof k === 'string' && /^[A-Za-z0-9]{8,64}$/.test(k) ? { stopKey: k } : {}) // the turn's cancel nonce (https://witbitz.chat/docs/sdk-assistant.md#turn); only space.turn() mints one
132
+ // A REPLY quotes the message it answers (agent/asyncTurn.mjs keeps { key, name, excerpt }, bounded) — the app's shape.
133
+ // `replyTo`: a Message from 'message' / snapshot(). The key is ledgerView.js entryKeyOf, the app's rule.
134
+ // A ROOM CLIENT THAT HEALS ITS ENCLAVE KEY (sync sweep, 2026-10-10). In a confidential room every keyed call (a send, a
135
+ // reaction, a row, an approval, a rename, a run, a gated poll) can meet a key the enclave no longer holds — `401
136
+ // bad_mkseal` after the enclave was replaced — or none at all ("enclave key unavailable": the room was opened while its
137
+ // enclave slept). The app re-attests and retries in both cases (space.js); here every call does, once: `heal()` attests
138
+ // (shared, throttled) and says whether a fresh key is in hand. Non-functions and open rooms pass through unchanged.
139
+ const RAW_CLIENT = Symbol('witbitz.rawClient')
140
+ // A ROOM RE-KEYED IN PLACE (https://witbitz.chat/docs/sdk-people.md#members): a call with the room's old key is answered `stale_key`;
141
+ // `keys.adopt()` takes this account's grant (sdkRekey.js) and the call runs once more with the new key in place of the old one.
142
+ function healingClient(c, heal, keys = null) {
143
+ if (!c || typeof c !== 'object') return c
144
+ c = c[RAW_CLIENT] || c // a fork's or a lane's Space is handed its parent's client: wrap the RAW one, or the parent's heal (its own room) ran first
145
+ return new Proxy(c, {
146
+ get(t, k) {
147
+ if (k === RAW_CLIENT) return t
148
+ const v = t[k]
149
+ if (typeof v !== 'function') return v
150
+ return async (...a) => {
151
+ let r
152
+ try { r = await v.apply(t, a) } catch (e) {
153
+ if (/enclave key unavailable/i.test(String(e && e.message))) {
154
+ if (await heal()) return v.apply(t, a)
155
+ if (e && typeof e === 'object' && !e.code) e.code = 'enclave_unavailable' // its enclave is asleep or could not be verified: try again shortly
156
+ }
157
+ throw e
158
+ }
159
+ if (r && (r.status === 401 || r.status === 200) && r.error === 'bad_mkseal' && await heal()) return v.apply(t, a) // 200: the confidential host front once flattened every status
160
+ // A CONFIDENTIAL ROOM THIS CLIENT DID NOT KNOW (an old unmarked link): the standard tier refuses it `confidential_room`.
161
+ // Learn the tier, as the app does (l1.js learnTier), and send it once more to the enclave — sealed from then on
162
+ // (sweep 11-06, unclear #3: until then every call sent the room key readable to the Lambda).
163
+ if (r && r.error === 'confidential_room' && keys && typeof keys.learnTier === 'function' && typeof a[0] === 'string' && await keys.learnTier(a[0]).catch(() => false)) return v.apply(t, a)
164
+ if (r && (r.status === 401 || r.status === 200) && r.error === 'stale_key' && keys && k !== 'grant') {
165
+ const got = await keys.adopt(a)
166
+ if (got) return v.apply(t, a.map((x) => (typeof x === 'string' && got.old.has(x) ? got.mk : x)))
167
+ }
168
+ return r
169
+ }
170
+ },
171
+ })
172
+ }
173
+
174
+ // A poll refusal no retry cures (pollVerdict 'gated' with these reasons): the poll slows to HELD_POLL_MS (sync sweep, 2026-10-10).
175
+ const PERMANENT_REFUSALS = new Set(['not_on_list'])
176
+ const isPurged = (e) => !!(e && e.kind === 'purged') // a deleted mail's place in the history (agent/mailPurge.mjs) — never a message
177
+ const HELD_POLL_MS = 60000
178
+ const KEY_WAIT_POLL_MS = 15000 // on the list of a re-keyed room but holding no key it can open (sdkRekey.js 'pending'): a fresh link or a restored invite key may come
179
+ // A quote: replyQuote.js, the app's reply strip's own rule; no `excerpt` when there is nothing to show.
180
+ const replyRef = (m) => { const q = m && m.id != null ? replyQuote(m) : null; return q && (q.excerpt ? q : { key: q.key, name: q.name }) } // the SDK quotes only a message with an id
181
+ const promptOpt = (on) => (on === true ? { showPrompt: true } : {}) // send(…, { showPrompt: true }) → the answer's `prompt`: exactly what the model was sent (sdk-assistant.md#builder-mode)
182
+ const perTurn = (instructions) => (typeof instructions === 'string' && instructions.trim() ? { instructions: instructions.trim().slice(0, 8000) } : {})
183
+
184
+ // ⛔ SILENT CUTS COST A BUILDER A DAY (2026-09-29): "the model read two calendars of four because the list at the end of
185
+ // a description was gone." The server bounds what an app declares and CUTS or DROPS the excess without a word
186
+ // (agent/spaceHandlerCommon.mjs sanitizeClientTools, agent/dataTools.mjs sanitizeDataSchema). The SDK now refuses at
187
+ // DECLARATION time, naming the limit, so it surfaces while the app is being built. It checks nothing stricter than the
188
+ // server — sdkLimits.test.mjs holds these numbers equal to the server's.
189
+ /** This SDK's version: 'dev' on the live build, the release number in /sdk/<version>/ (tools/sdk-release.mjs sets it). */
190
+ export { isLaneCopy } from './roomName.js' // is this message a lane's copy of its shared room's line? (the app's own test, sdk-agents.md#lanes)
191
+ export { Protect } // device storage protection, usable before a client exists (sdkProtect.js, #protect)
192
+ export const SDK_VERSION = '4.3.0'
193
+ // Every error the SDK throws carries a `code` (sdk-reference.md#errors): an argument it cannot use is `invalid_argument`.
194
+ const sdkError = (message, code = 'invalid_argument') => Object.assign(new Error(message), { code })
195
+ /** What this SDK build can do — for feature detection (wb.capabilities()). Names only grow; a removed one is a major version. */
196
+ const FEATURES = Object.freeze(['spaces', 'turn', 'replay-option', 'store', 'proposals', 'lanes', 'lane-links', 'a2a', 'admission', 'admins', 'owners', 'plan', 'enclave', 'split-key', 'certificates', 'connections', 'siri', 'dictation', 'speech', 'backup', 'protect', 'erasure', 'builds', 'account-index', 'usernames', 'agui', 'eat', 'admin-sdk', 'rekey', 'tool-rules', 'lanes-configure', 'chat-locks', 'session-browser', 'schedules', 'invite-resend', 'connection-catalog', 'chat-lock-pin', 'session-browser-private', 'email-move', 'mirror-removals'])
197
+ export const LIMITS = Object.freeze({
198
+ actions: 32, actionName: 64, actionDescription: 2000, actionInputSchema: 8000,
199
+ collections: 16, fieldsPerCollection: 32, name: 40, collectionDescription: 300, fieldDescription: 200,
200
+ // What one turn may carry — the server's own caps (agent/spaceHandlerCommon.mjs parseMedia / sanitizeLinks), which it
201
+ // applies by DROPPING the excess silently. The SDK refuses instead, so a file never vanishes without a word.
202
+ images: 4, imageBytes: 1_100_000, files: 2, fileBytes: 3_700_000, links: 16,
203
+ })
204
+ const n = (x) => x.toLocaleString('en-US')
205
+ const limitError = (msg) => { const e = new Error('witbitz: ' + msg); e.code = 'limit_exceeded'; return e }
206
+ /** A refusal from the room, with the server's own error as `code` — `not_admin`, `not_authorized`, … — so an app can
207
+ * tell "you may not" from "it failed". `status` and `reason` ride along. */
208
+ const refused = (what, r) => { const e = new Error(`witbitz: ${what} refused: ${r ? r.status : '?'} ${(r && (r.reason || r.error)) || ''}`.trim()); e.code = (r && r.error) || 'failed'; if (r) { e.status = r.status; if (r.reason) e.reason = r.reason } return e }
209
+ // ATTACHMENTS on a turn (2026-10-02). Each is `{ b64, mime, name? }` or `{ bytes, mime, name? }` (a Uint8Array or an
210
+ // ArrayBuffer). Base64 is what travels; the server stores it out of line, sealed under the room key. Sizes are checked
211
+ // against the server's caps in BYTES (base64 is 4/3 of that) and refused here rather than dropped there.
212
+ const B64_MAX = { images: 1_500_000, files: 5_000_000 }
213
+ function toB64(bytes) {
214
+ const u = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
215
+ let bin = ''
216
+ for (let i = 0; i < u.length; i += 0x8000) bin += String.fromCharCode(...u.subarray(i, i + 0x8000))
217
+ return btoa(bin)
218
+ }
219
+ function mediaList(list, kind) {
220
+ if (list === undefined || list === null) return undefined
221
+ if (!Array.isArray(list)) throw sdkError(`witbitz: \`${kind}\` takes an array of { b64 | bytes, mime, name? }`, 'invalid_argument')
222
+ const max = LIMITS[kind]
223
+ if (list.length > max) throw limitError(`${list.length} ${kind} on one message; the limit is ${max}`)
224
+ const out = list.map((a, i) => {
225
+ if (!a || typeof a !== 'object') throw sdkError(`witbitz: ${kind}[${i}] is not an attachment`, 'invalid_argument')
226
+ const b64 = typeof a.b64 === 'string' && a.b64 ? a.b64 : (a.bytes instanceof Uint8Array || a.bytes instanceof ArrayBuffer ? toB64(a.bytes) : '')
227
+ if (!b64) throw sdkError(`witbitz: ${kind}[${i}] needs \`b64\` or \`bytes\``, 'invalid_argument')
228
+ if (typeof a.mime !== 'string' || !/^[\w.+-]+\/[\w.+-]+$/.test(a.mime)) throw sdkError(`witbitz: ${kind}[${i}] needs a \`mime\` type, like ${kind === 'images' ? 'image/jpeg' : 'application/pdf'}`, 'invalid_argument')
229
+ if (b64.length > B64_MAX[kind]) throw limitError(`${kind}[${i}] is ${n(Math.floor(b64.length * 3 / 4))} bytes; the limit is ${n(kind === 'images' ? LIMITS.imageBytes : LIMITS.fileBytes)} per ${kind === 'images' ? 'image' : 'file'}`)
230
+ return { b64, mime: a.mime, ...(a.name ? { name: String(a.name).slice(0, 120) } : {}) }
231
+ })
232
+ return out.length ? out : undefined
233
+ }
234
+ // WHO WROTE A MIRRORED LINE, as its Space knew them (the app's mirrorLoop.js byOf, rule for rule; the lane's Block reads it,
235
+ // blockView markMirrored): a person's message only — never the agent's, nor an outside agent's line relayed under a member's
236
+ // key (a SIGNED relay only: an unverified poster who types those words is still blockable) — and only what the server
237
+ // stamped. The signing key in that Space for ANY poster; for a verified one also the @username and the email the room
238
+ // verified (senderNames.js attestedIdentity: not on a `keyOnly` entry). The app also reads the room's roster record for the
239
+ // key; the SDK keeps none, so an entry without a stamped email carries the key alone (sync sweep 11-13 P1: the SDK stamped
240
+ // nothing for an unverified poster and never the email). mirrorLoop.js is not imported: it pulls the app's shell with it.
241
+ const RELAYED_AGENT_LINE = /^🤖 (.{1,80}?) \(via A2A\): /
242
+ const MIRROR_EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
243
+ function mirrorBy(room, e) {
244
+ if (!e || e.self === true || e.kind === 'agent') return {}
245
+ const verified = e.verified === true
246
+ if (verified && RELAYED_AGENT_LINE.test(String(e.text || ''))) return {}
247
+ const k = e.vspk || e.spk
248
+ const sid = k && k.x && k.y ? `${k.x}.${k.y}` : '' // profilePhoto.js rowIdOfKey
249
+ const user = verified && typeof e.user === 'string' && /^@?[a-z0-9_.-]{1,40}$/i.test(e.user) ? e.user.replace(/^@/, '') : ''
250
+ const email = verified && e.keyOnly !== true && MIRROR_EMAIL.test(String(e.email || '').trim()) ? String(e.email).trim().toLowerCase() : ''
251
+ const by = { ...(email ? { email } : {}), ...(user ? { user } : {}), ...(sid && room ? { room, sid } : {}) }
252
+ return Object.keys(by).length ? { by } : {}
253
+ }
254
+ /** Attachments a COPY must carry as bytes: a stored one points at a blob sealed to the SOURCE room's key, which would
255
+ * never open in the room it is copied to. A failed source read leaves the batch pending for the next mirror. */
256
+ async function withBytes(from, list) {
257
+ if (!Array.isArray(list) || !list.length) return undefined
258
+ return Promise.all(list.map(async (a) => {
259
+ if (!a || typeof a !== 'object' || (typeof a.b64 === 'string' && a.b64)) return a
260
+ const { ref, parts, size, ...rest } = a
261
+ if (!ref && !parts) return rest
262
+ const o = await from.attachment(a)
263
+ if (!o?.b64) throw sdkError('attachment bytes could not be copied', 'attachment_unavailable')
264
+ return { ...rest, b64: o.b64, mime: a.mime || o.mime }
265
+ }))
266
+ }
267
+ const withMedia = (msg, images, files) => {
268
+ const im = mediaList(images, 'images'), fl = mediaList(files, 'files')
269
+ return { ...msg, ...(im ? { images: im } : {}), ...(fl ? { files: fl } : {}) }
270
+ }
271
+ /** Throws `limit_exceeded` for a list of actions OFFERED TO ONE TURN that the server would cut or drop. */
272
+ export function checkActions(actions) {
273
+ const list = Array.isArray(actions) ? actions.filter((a) => a && a.name && typeof a.run === 'function') : []
274
+ if (list.length > LIMITS.actions) throw limitError(`${list.length} actions offered to one turn; the limit is ${LIMITS.actions} per turn — the rest would be dropped`)
275
+ checkActionItems(list)
276
+ }
277
+ // ★ THE COUNT IS PER TURN, NOT PER REGISTRATION (a builder, 2026-09-29: "We build the Lane with all 30 of our actions, so
278
+ // an approved card still finds its handler after a reload, but a turn is offered only 19–24"). The server caps the
279
+ // clientTools a TURN carries; a lane may register more, so an approved proposal finds its handler after a reload. So a
280
+ // registration checks each action; the count is checked in send(), on what that turn actually offers.
281
+ function checkActionItems(list) {
282
+ for (const a of list) {
283
+ if (typeof a.name !== 'string' || !new RegExp(`^[a-zA-Z0-9_]{1,${LIMITS.actionName}}$`).test(a.name)) throw limitError(`action name ${JSON.stringify(a.name)} must be letters, digits and _ (up to ${LIMITS.actionName}) — otherwise the tool is dropped`)
284
+ const d = String(a.description || a.name)
285
+ if (d.length > LIMITS.actionDescription) throw limitError(`the description of action "${a.name}" is ${n(d.length)} characters; the limit is ${n(LIMITS.actionDescription)} — the rest would be cut before the assistant sees it`)
286
+ const schemaLen = JSON.stringify(a.input || { type: 'object', properties: {} }).length
287
+ if (schemaLen > LIMITS.actionInputSchema) throw limitError(`the input schema of action "${a.name}" is ${n(schemaLen)} characters of JSON; the limit is ${n(LIMITS.actionInputSchema)} — over it the whole tool would be dropped`)
288
+ }
289
+ }
290
+ // REASONING EFFORT is per MODEL, and per route: DeepSeek V4.1 takes `medium` on the standard tier and refuses it on the
291
+ // confidential one; Mistral Large takes no effort at all. The platform measures each (tools/effort-probe.mjs) and
292
+ // publishes the list on `wb.models()`; the server fits a value the model does not take back to its default rather than
293
+ // fail a turn, so without this check a builder's `medium` would silently run as `low`. Refused here, naming the list.
294
+ export const EFFORTS = Object.freeze(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'])
295
+ const effortError = (msg) => { const e = new Error('witbitz: ' + msg); e.code = 'invalid_effort'; return e }
296
+ /** Throws `invalid_effort` when `model` names a reasoning_effort that the model it names does not take. `catalog` is
297
+ * `wb.models()`' rows; a model it does not list (BYO, a new wire name) is checked only against the ladder. */
298
+ export function checkModelEffort(model, catalog = []) {
299
+ const effort = model && typeof model === 'object' && model.params && typeof model.params === 'object' ? model.params.reasoning_effort : undefined
300
+ if (effort === undefined || effort === null) return
301
+ if (!EFFORTS.includes(effort)) throw effortError(`reasoning_effort ${JSON.stringify(effort)} is not an effort level; the levels are ${EFFORTS.join(', ')}, and each model takes some of them — see wb.models()`)
302
+ const key = model.catalog || model.wire
303
+ const row = (catalog || []).find((m) => m && (m.id === key || m.wire === key))
304
+ if (!row || !Array.isArray(row.efforts)) return
305
+ if (!row.efforts.length) throw effortError(`${row.id} takes no reasoning_effort — drop the field`)
306
+ if (!row.efforts.includes(effort)) throw effortError(`${row.id} does not take reasoning_effort "${effort}"; it takes ${row.efforts.join(', ')}`)
307
+ }
308
+ /** Throws `limit_exceeded` for a `data` schema the server would cut, drop or rename. */
309
+ export function checkDataSchema(data) {
310
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return
311
+ const cols = Object.entries(data)
312
+ if (cols.length > LIMITS.collections) throw limitError(`${cols.length} collections; the limit is ${LIMITS.collections} — the rest would be dropped`)
313
+ const okName = (k) => new RegExp(`^[A-Za-z0-9_.\\-]{1,${LIMITS.name}}$`).test(k)
314
+ for (const [col, v] of cols) {
315
+ if (!okName(col)) throw limitError(`collection name ${JSON.stringify(col)} must be letters, digits, _ . - (up to ${LIMITS.name}) — otherwise it is renamed`)
316
+ if (v && typeof v === 'object' && typeof v.description === 'string' && v.description.length > LIMITS.collectionDescription) throw limitError(`the description of collection "${col}" is ${n(v.description.length)} characters; the limit is ${LIMITS.collectionDescription} — the rest would be cut`)
317
+ if (v && typeof v === 'object' && 'write' in v) {
318
+ if (v.write !== 'admins' && v.write !== 'members') throw sdkError(`witbitz: collection "${col}" write is 'admins' or 'members'`, 'invalid_argument')
319
+ if (!v.fields && !v.schema) throw sdkError(`witbitz: collection "${col}" declares write — give its fields as { fields: {…}, write } (or a schema), or "write" would be read as a field`, 'invalid_argument')
320
+ }
321
+ if (v && typeof v === 'object' && 'schema' in v) { // a ROW SCHEMA (rowSchema.js): refused here exactly as the server would refuse it
322
+ const why = schemaProblem(v.schema)
323
+ if (why) throw Object.assign(new Error(`witbitz: the schema of collection "${col}" cannot be enforced — ${why}`), { code: 'invalid_schema' })
324
+ }
325
+ const fields = v && typeof v === 'object' && v.fields && typeof v.fields === 'object' ? v.fields : (v && typeof v === 'object' && !('fields' in v) && !('description' in v) && !('schema' in v) ? v : {})
326
+ const fe = Object.entries(fields)
327
+ if (fe.length > LIMITS.fieldsPerCollection) throw limitError(`collection "${col}" has ${fe.length} fields; the limit is ${LIMITS.fieldsPerCollection} — the rest would be dropped`)
328
+ for (const [f, d] of fe) {
329
+ if (!okName(f)) throw limitError(`field name ${JSON.stringify(f)} in "${col}" must be letters, digits, _ . - (up to ${LIMITS.name}) — otherwise it is renamed`)
330
+ const dl = String(d == null ? '' : d).length
331
+ if (dl > LIMITS.fieldDescription) throw limitError(`the description of field "${f}" in "${col}" is ${n(dl)} characters; the limit is ${LIMITS.fieldDescription} — the rest would be cut`)
332
+ }
333
+ }
334
+ }
335
+
336
+ function buildActions(actions = []) {
337
+ checkActionItems((Array.isArray(actions) ? actions : []).filter((a) => a && a.name && typeof a.run === 'function')) // each action; the per-turn COUNT is checked in send()
338
+ const defs = []; const handlers = {}; const reads = {}; const names = []; const readNames = []
339
+ for (const a of (Array.isArray(actions) ? actions : [])) {
340
+ if (!a || !a.name || typeof a.run !== 'function') continue
341
+ const mode = a.mode === 'await' ? 'await' : 'propose'
342
+ defs.push({ name: a.name, description: String(a.description || a.name), inputSchema: a.input || { type: 'object', properties: {} }, mode })
343
+ if (mode === 'await') { reads[a.name] = a.run; readNames.push(a.name) } else { handlers[a.name] = a.run; names.push(a.name) }
344
+ }
345
+ const readGuidance = readNames.length ? ` You can also READ from the member's device with: ${readNames.join(', ')} — call them when you need that information; they answer within the turn.` : ''
346
+ const guidance = names.length
347
+ ? `You also have effectful actions you can PROPOSE (never run directly): ${names.join(', ')}. When the member asks for something these cover, propose the action(s) with concrete arguments; a human approves before anything runs. Do not claim an action is done — say it is proposed and awaiting approval.`
348
+ : ''
349
+ return { defs, handlers, reads, guidance: guidance + readGuidance }
350
+ }
351
+
352
+ // AN ATTESTED SPACE IS COPIED ONLY INTO AN ATTESTED LANE (sync sweep 2026-11-15 #5; the app's mirrorLoop.js since 9b3853a35): a lane
353
+ // mirrors its Space's messages, so an ordinary lane of an attested Space would hand them to any device holding the lane's key — the
354
+ // app's proof every read of the Space needs would no longer protect them. A read that fails refuses (never "not attested").
355
+ async function refuseAttestedIntoPlain(client, sharedRoom, sharedMk, laneRoom, laneMk) {
356
+ if (!client || typeof client.attestedRoom !== 'function') return
357
+ const ask = async (room, mk) => { try { return !!(await client.attestedRoom(room, mk)) } catch (e) { throw sdkError('witbitz: whether this Space requires an attested app could not be read, so its lane waits — try again (' + ((e && e.message) || e) + ')', 'policy_unreadable') } }
358
+ if (!(await ask(sharedRoom, sharedMk))) return
359
+ if (!(await ask(laneRoom, laneMk))) throw sdkError('witbitz: this Space requires an attested app, so it is copied only into a lane that requires one too — this lane does not', 'attested')
360
+ }
361
+ /** A Witbitz client bound to an endpoint. Stateless besides the transport; make one and reuse it. */
362
+ export class Witbitz {
363
+ /** @param {object} [opts] { endpoint?, tenantEndpoint?, viewer?, app?, tenant?, tenantKey?, session?, userToken?, live?, loginBase?,
364
+ * sentinel?, siri?, backup?, vaultApi?, deviceName?, appShare?, a2a?, a2aEndpoint?, invite?, protect?, region?, builds?, attest?,
365
+ * enclaveClaim?, fetchImpl?, WebSocketImpl? } —
366
+ * `tenant` is your tenant's PUBLIC id (never a key): Spaces this page creates are attributed to it when the page's origin
367
+ * is one the tenant declared. The full list, with defaults: https://witbitz.chat/docs/sdk-reference.md#configuration. */
368
+ constructor({ endpoint = DEFAULT_ENDPOINT, tenantEndpoint, viewer = DEFAULT_VIEWER, app, tenant, tenantKey, session, loginBase, sentinel, fetchImpl, siri, live, WebSocketImpl, userToken, backup, enclaveClaim: encClaimUrl, vaultApi, appShare, deviceName, a2a, a2aEndpoint, invite, protect, region, builds, attest, client: pluggedClient, _roomPass, _renewSignIn, _appShareMember, devRoot } = {}) {
369
+ // THE DEV SERVER'S ATTESTATION ROOT (devserver/, the Witbitz dev server with a confidential tier): base64 DER. It REPLACES the
370
+ // pinned AWS root for this client's confidential tier — so a client given it trusts only that local server's enclave, never
371
+ // Witbitz's (shipped by mistake, it fails closed). Never set by default; nothing else reads it.
372
+ this._devRoot = null
373
+ if (devRoot) {
374
+ try { this._devRoot = Uint8Array.from(atob(String(devRoot).replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0)) } catch { throw sdkError('witbitz: devRoot is not base64 — pass the root the dev server printed', 'invalid_argument') }
375
+ }
376
+ this._region = regionCode({ region }) // where createSpace homes a new room (regions.js); an unknown code → the default region
377
+ // `attest: { bridge }` — a device that proves itself with its own hardware or enclave (the cloud device, cloud-device/worker.mjs).
378
+ // `attest: { app }` (a page proving it was served as your app) is RETIRED in 4.0.0 (the owner, 2026-11-22: "We dont need any
379
+ // emulation rooms"): a web page vouching for itself is no client check.
380
+ if (attest !== undefined && attest && typeof attest === 'object' && typeof attest.app === 'string' && !attest.bridge) throw sdkError('witbitz: attest: { app } is retired — a web page cannot prove which app it is (sdk-changes.md, 4.0.0)', 'attest_app_retired')
381
+ if (attest !== undefined) { if (!attest || typeof attest !== 'object' || !(attest.bridge && typeof attest.bridge.platform === 'function')) throw sdkError('witbitz: attest is { bridge } — a device that proves itself', 'invalid_argument'); this._attest = makeSdkAttest({ bridge: attest.bridge, app: 'device', client: () => this._client }) } // attest.bridge: a device that proves itself (Witbitz's cloud device; not for builders)
382
+ // LIVE (room streams): on by default in a browser; `live: false` turns it off (polling only). Needs your page's CSP
383
+ // to allow connect-src wss://code-relay.witbitz.chat — if the socket cannot open, the SDK simply keeps polling.
384
+ const wsImpl = WebSocketImpl || (typeof window !== 'undefined' && typeof WebSocket === 'function' ? WebSocket : null)
385
+ this._live = live === false || !wsImpl ? null : { WebSocketImpl: wsImpl }
386
+ this._viewer = viewer.replace(/\/+$/, '')
387
+ // `enclaveClaim`: where the enclave's PUBLISHED measurement is served when your links point at a `viewer` of your own that
388
+ // does not serve /enclave-claim.json itself (the error below named this option for a week before it existed, 2026-10-03). https only.
389
+ this._encClaimUrl = typeof encClaimUrl === 'string' && /^https:\/\//.test(encClaimUrl) ? encClaimUrl : ''
390
+ // ★ THE `auth` HOOK IS WHAT MAKES AN EMAIL-GATED ROOM USABLE (2026-09-27, a builder: "every room a secure room").
391
+ // For a gated Space the server gates EVERY op, reads included — so identity that reaches only `turn` yields a room
392
+ // you can write to and cannot poll. makeSpaceClient asks per room; this answers from the session, and answers
393
+ // EMPTILY when there is none or it has expired, so an open room still works with no sign-in at all.
394
+ // PER-USER BILLING: the token YOUR backend minted for the signed-in user (wb.users.token on your server). A string or a
395
+ // function the SDK calls before each op that can spend, so you can refresh it there. Set later with useUserToken().
396
+ this._userToken = userToken || null
397
+ this._clientOpts = {
398
+ endpoint,
399
+ ...(app ? { app } : {}),
400
+ ...(tenant ? { tenant } : {}),
401
+ userToken: () => (typeof this._userToken === 'function' ? this._userToken() : this._userToken),
402
+ delCommit: (room) => (this.erasure ? this.erasure._commitFor(room) : null), // only this account can later delete a room it created (sdkErase.js)
403
+ // INTERNAL — a builder's VAULT (vault-core.js) only: the room pass of its account on the Witbitz account service (roomPass.js,
404
+ // docs/device-gate-design.md) on this client's verified-Space requests. Not an option for pages.
405
+ ...(_roomPass && typeof _roomPass.fieldsFor === 'function' ? { roomPass: _roomPass } : {}),
406
+ ...(typeof _renewSignIn === 'function' ? { renewSignIn: _renewSignIn } : {}), // INTERNAL (the vault): renew the session once on `pass: app_unnamed`
407
+ auth: async () => {
408
+ const sess = this._session
409
+ if (!sess || !sess.idToken || !sess.sign || !sess.sign.pub) return {}
410
+ if (sess.exp && sess.exp <= Date.now()) return {}
411
+ return { idToken: sess.idToken, spk: sess.sign.pub }
412
+ },
413
+ // ── THE CONFIDENTIAL TIER, per room. `enclave` marks a room's ops for the relay; `mkPub` is the ATTESTED key the
414
+ // room key is sealed to, so the relay only ever carries opaque bytes. Both are per-room because a tier is fixed at
415
+ // creation and one client may hold rooms of both kinds.
416
+ // ★ mkPub goes through enclaveAccept.publishedKey: the room key is sealed only to a build Witbitz publishes (the
417
+ // claim's pins, a rollover's set included). Rooms carry no acceptance block any more — in the Spaces app which build
418
+ // is accepted is each PERSON's choice (trustedBuilds.js); the SDK's is wb.builds (sdkBuilds.js — 'mine' = theirs, 'published' = any published).
419
+ enclave: (room) => this._enc.rooms.has(room),
420
+ mkPub: (room) => {
421
+ // the key of THIS room's region's enclave (docs/multi-region.md); the last-attested key stands in only for a
422
+ // default-region room — a room elsewhere never borrows another region's key (its enclave could not open the seal)
423
+ const k = this._enc.byRegion.get(roomRegion(room)) || (roomRegion(room) === DEFAULT_REGION && this._enc.key ? { key: this._enc.key, attested: this._enc.attested, platform: this._enc.platform } : null)
424
+ if (!this._enc.rooms.has(room) || !k) return null
425
+ return this.builds ? this.builds._key({ key: k.key, attested: k.attested, platform: k.platform, room }) : publishedKey({ key: k.key, attested: k.attested, platform: k.platform, room }) // wb.builds: the person's own list in 'mine' mode
426
+ },
427
+ // THE SEALED REQUEST ENVELOPE (reqEnvelope.js): this room's live enclave says, in its MEASURED policy, that it opens them
428
+ envelope: (room) => {
429
+ const k = this._enc.byRegion.get(roomRegion(room)) || (roomRegion(room) === DEFAULT_REGION ? { attested: this._enc.attested } : null)
430
+ if (!this._enc.rooms.has(room)) return false
431
+ return k ? opensEnvelopes(k.attested) : null // no attested facts here = UNKNOWN, never plaintext
432
+ },
433
+ // option B: the live enclave takes the sign-in from inside the envelope (its measured policy, SEALED_IDENTITY)
434
+ identity: (room) => {
435
+ const k = this._enc.byRegion.get(roomRegion(room)) || (roomRegion(room) === DEFAULT_REGION ? { attested: this._enc.attested } : null)
436
+ return !!(this._enc.rooms.has(room) && k && sealsIdentity(k.attested))
437
+ },
438
+ }
439
+ /** The confidential tier's session: the published claim, what the live enclave attested, and the key mk seals to. */
440
+ this._enc = { claim: null, attested: null, platform: null, key: null, rooms: new Map(), byRegion: new Map() } // byRegion: region → { key, attested, platform }
441
+ // A PLUGGED-IN CLIENT (docs/sdk-vault-mode.md, phase 1): a page that does not hold its rooms' keys hands the SDK a
442
+ // client whose ops take no key — the keys live where that client sends the ops (a vault's worker). `keyless: true`
443
+ // on it tells every Space so; the default is the direct client, which holds them here.
444
+ this._client = pluggedClient && typeof pluggedClient === 'object' ? pluggedClient : makeSpaceClient(this._clientOpts)
445
+ /** @type {VaultSession|null} set by {@link Witbitz.inVault}: the vault that holds this page's keys */
446
+ this.vault = null
447
+ // ── THE ACCOUNT HALF (2026-09-27, a builder: "our app has no Witbitz accounts — what is the intended path?").
448
+ // A connection and a Siri key belong to an ACCOUNT: the verified email on a sign-in token, never a field a page
449
+ // names. So the SDK signs in the same way the Spaces app's "Email me a code" does — an emailed six-digit code,
450
+ // any address, any origin (the endpoints answer cross-origin) — and keeps the SESSION the app may persist and hand
451
+ // back (`new Witbitz({ session })`). `loginBase` is where the code endpoints live (the reference app's origin).
452
+ this._endpoint = endpoint
453
+ this._tenant = tenant || ''
454
+ this._tenantKey = tenantKey || '' // SERVER-SIDE ONLY (https://witbitz.chat/docs/connections.md) — a wsk_ key in a page is a leak
455
+ this._tenantEndpointOverride = tenantEndpoint ? String(tenantEndpoint) : '' // builder ops; derived from `endpoint` when absent
456
+ this._loginBase = String(loginBase || viewer).replace(/\/+$/, '')
457
+ this._fetch = typeof fetchImpl === 'function' ? fetchImpl : ((...a) => fetch(...a))
458
+ // SPLIT-KEY ROOMS, BUILDER-HOSTED (the main path, https://witbitz.chat/docs/sdk-keys.md#split-key): the URL of YOUR function that holds
459
+ // the app half (spaces/templates/appshare). Absent ⇒ the Witbitz-held key, for a builder who cannot host one.
460
+ this._appShareUrl = appShare ? String(appShare) : ''
461
+ // @private A MEMBER'S OWN DEVICE (the cloud device, which keeps only a split Space's user share): (room) → { status, appShare, commit }
462
+ // — the app half asked with the member's proof (spaces/functions/api/appshare.js op 'member'), per open, never kept.
463
+ this._appShareMember = typeof _appShareMember === 'function' ? _appShareMember : null
464
+ this._session = sessionOf(session)
465
+ if (this._session && this._session.idToken) queueMicrotask(() => this._prefetchIdentity()) // a restored session (option B: sweep 11-06 #9)
466
+ // Advanced: a tenant running its OWN standing Sentinel pins its image here (and its Lambda's SENTINEL_HOP_PCRS);
467
+ // `verify` is the attestation verifier (tests inject one; production uses nitroVerify through connections.js).
468
+ // A NEW WITBITZ SENTINEL BUILD IS FOLLOWED (2.2.3; sync sweep 10-16 #4: every earlier release could only fail once its
469
+ // pinned build was retired): `follow` 'published' (default — the app's "Accept new Witbitz builds automatically") takes
470
+ // a build Witbitz publishes at /sentinel-claim.json; 'ask' calls `onNewBuild(pcr0)` → true to accept; 'off' keeps the
471
+ // pins as they are. Your own `pins` are never followed.
472
+ const fmode = sentinel && ['published', 'ask', 'off'].includes(sentinel.follow) ? sentinel.follow : 'published'
473
+ const ownPins = !!(sentinel && Array.isArray(sentinel.pins))
474
+ // With `devRoot` (the dev server's root): its Sentinel is checked under that root, and its builds are followed from ITS claim
475
+ // (`viewer`/sentinel-claim.json) — never Witbitz's. Without it, as before.
476
+ const devVerify = this._devRoot && !(sentinel && typeof sentinel.verify === 'function') ? { verify: (doc, o) => verifyAttestation(doc, { ...o, root: this._devRoot }) } : {}
477
+ const claimDefault = this._devRoot ? String(viewer).replace(/\/+$/, '') + '/sentinel-claim.json' : DEFAULT_VIEWER + '/sentinel-claim.json'
478
+ this._sentinel = { pins: ownPins ? sentinel.pins : STANDING_SENTINEL_PCR0, ...(sentinel && typeof sentinel.verify === 'function' ? { verify: sentinel.verify } : devVerify),
479
+ follow: ownPins || fmode === 'off' ? null : { auto: () => fmode === 'published', ask: async (p) => !!(sentinel && typeof sentinel.onNewBuild === 'function' && await sentinel.onNewBuild(p)), claimUrl: String((sentinel && sentinel.claimUrl) || claimDefault), fetch: (u, o) => this._fetch(u, o) } }
480
+ this._siri = siriStateOf(siri) // { token, defaultRoom, rooms: { [room]: { alias, label, pub, priv, at } } } — the app persists it (wb.siri.state)
481
+ this.connections = new Connections(this)
482
+ /** The person's cloud computers: list, create, open (sessions, approvals, questions, files, events), remove — sdkComputers.js. */
483
+ this.computers = new Computers(this)
484
+ // BUILDER OPS (tenant secret key) live in witbitz-admin.js now (sdk-roadmap item 5). These names delegate there and
485
+ // keep working; on your server prefer `new WitbitzAdmin({ tenant, tenantKey })`, where `users` is `customers`.
486
+ this._admin = new WitbitzAdmin({ tenant, tenantKey, endpoint, tenantEndpoint, fetchImpl: (...a) => this._fetch(...a), sentinel })
487
+ this.providers = this._admin.providers
488
+ this.hosts = this._admin.hosts
489
+ this.origins = this._admin.origins
490
+ this.rooms = this._admin.rooms
491
+ this.users = this._admin.customers
492
+ this.billing = this._admin.billing
493
+ if (tenantKey && typeof window !== 'undefined' && typeof document !== 'undefined') {
494
+ // A wsk_ key in a page is readable by every visitor. Not refused (a local tool may do this on purpose), but said.
495
+ try { console.warn('witbitz: a tenant SECRET key was passed to new Witbitz() in a browser page — anyone who opens the page can read it. Use WitbitzAdmin on your server (witbitz-admin.js).') } catch { /* */ }
496
+ }
497
+ this.siri = new SiriAccount(this)
498
+ /** The signed-in member's @username (global across Witbitz): claim / release / mine / resolve. */
499
+ this.usernames = new Usernames(this)
500
+ /** The ACCOUNT BACKUP (sdkBackup.js): `enable()` → a recovery code; rooms are recorded as this client creates and
501
+ * opens them; `restore({ code })` on a new device hands them back. `backup` is a prior `wb.backup.state`. */
502
+ this.backup = new AccountBackup({ fetch: this._fetch, tenant: this._tenant, ...(vaultApi ? { base: vaultApi } : {}), state: backup || null, email: () => (this._session && this._session.email) || '' })
503
+ this._archiveGeneration = 0
504
+ this.backup._onEnabled = master => {
505
+ for (const sp of this._archiveHandles || []) if (!sp._archiveMaster && sp._archiveEmail === (this._session?.email || '') && sp._archiveGeneration === this._archiveGeneration) sp._archiveMaster = master
506
+ }
507
+ /** @type {Erasure} the tenant's erase of a user reaches the rooms this account created (sdkErase.js) */
508
+ this.erasure = new Erasure(this)
509
+ /** Which enclave build this person accepts (sdkBuilds.js): `new Witbitz({ builds: 'mine' })` = their own list, the app's rules. */
510
+ this.builds = new Builds(this, typeof builds === 'string' ? { mode: builds } : (builds && typeof builds === 'object' ? builds : {}))
511
+ /** DEVICE STORAGE PROTECTION (sdkProtect.js): what the app keeps on the device — the session, room snapshots, the Siri /
512
+ * A2A / backup state — sealed under a key a platform passkey derives, nowhere on disk. `protect`: { storage, storeKey,
513
+ * rpId, rpName } (localStorage and this page's host by default). Off until `wb.protect.enable()`. */
514
+ // An app opens its protected storage BEFORE it builds the client (the session and the backup state are constructor
515
+ // options): `new Protect()` → unlock → load → `new Witbitz({ protect, session, backup })` adopts that same object.
516
+ // Recognised by what it does, not instanceof: a page that loaded sdkProtect.js under another URL has another class object.
517
+ const isProtect = (x) => x instanceof Protect || !!(x && typeof x === 'object' && ['unlock', 'lock', 'seal', 'open', 'save', 'load'].every((m) => typeof x[m] === 'function'))
518
+ this.protect = isProtect(protect) ? protect : new Protect({ ...(protect && typeof protect === 'object' ? protect : {}), backup: this.backup })
519
+ if (!this.protect._backup) this.protect._backup = this.backup
520
+ /** A2A into private lanes (sdkA2A.js): the account's record — which lanes outside agents may reach. Persist
521
+ * `wb.a2a.state` (it holds the lanes' inbox private keys) and hand it back as `new Witbitz({ a2a })`. */
522
+ this.a2a = new A2AAccount(this, { state: a2a || null, ...(a2aEndpoint ? { endpoint: a2aEndpoint } : {}) })
523
+ /** This account's INVITE KEY for this app (sdkRekey.js, https://witbitz.chat/docs/sdk-people.md#members): published at sign-in, it is
524
+ * what a member change in place seals a Space's new key to. Persist `wb.invite.state` (a private key) as you persist the
525
+ * session and hand it back as `new Witbitz({ invite })`; with a backup on, it rides the backup too. */
526
+ this.invite = new InviteAccount(this, { state: invite || null })
527
+ this.cloudDevice = new CloudDevice(this)
528
+ /** The account's LIVE index (sdkAccount.js): the rooms, archived/forgotten marks and devices, kept in step between every
529
+ * device that holds the backup. In a browser it syncs on its own once the backup is on; `sync()` any time. */
530
+ this.account = new AccountIndex({ backup: this.backup, client: () => this._client, deviceName: deviceName || '', viewer: this._viewer, live: () => this._live, version: SDK_VERSION })
531
+ this.account._emptyHooks = () => this._emptySpaceHooks()
532
+ this.account._readName = async row => {
533
+ const { mk } = await this._openLink(row.link)
534
+ const [history, doc] = await Promise.all([
535
+ readAllPages(since => this._client.poll(row.room, mk, undefined, since)),
536
+ this._client.state(row.room, mk, 'title').catch(() => null),
537
+ ])
538
+ if (history.incomplete) return null
539
+ return { entries: history.entries, doc }
540
+ }
541
+ this.backup._afterMigration = async ({ signed = false } = {}) => {
542
+ const state = this.backup._s, current = () => { if (this.backup._s !== state) throw sdkError('witbitz: the account changed during migration', 'account_changed') }
543
+ this.account._spk = await this.backup._v2.deviceSpk(this.backup); current()
544
+ const read = await this.account.sync(); current()
545
+ if (!read || !read.ok) throw sdkError('witbitz: the account index could not be read; retry migration', 'index_unavailable')
546
+ if (signed) return
547
+ for (const d of this.account.devices) if (d.id !== this.account.deviceId) this.account.signOut(d.id, { reason: 'moved' })
548
+ const saved = await this.account.sync(); current()
549
+ if (!saved || !saved.ok) throw sdkError('witbitz: other devices could not be signed out; retry migration', 'index_unavailable')
550
+ }
551
+ if (typeof window !== 'undefined' && this.backup.enabled) this.account.start()
552
+ // Credentials stay readable by name and out of Object.keys / JSON / error-reporter walks (sdkRedact.js).
553
+ hide(this, ['_session', '_tenantKey', '_userToken', '_siri', '_clientOpts', '_client', '_enc', '_admin', 'backup', 'account', 'a2a', 'invite', 'protect', 'erasure'])
554
+ }
555
+
556
+ /** IN A VAULT (docs/sdk-vault-mode.md): this page is framed by a vault YOU host on another origin, which keeps every room
557
+ * key in its own worker — the page never holds one (no `space.key`, no key in a link, nothing in its storage). Sign-in,
558
+ * creating a Space and sharing it happen in the vault; reading and sending work here as everywhere else.
559
+ * @param {object} opts { vault, ...the usual options } — `vault`: the vault's origin, e.g. 'https://vault.example.com'.
560
+ * @returns {Promise<Witbitz>} a client whose `vault` is the {@link VaultSession}; rejects `not_in_vault` when the page is
561
+ * not framed by that origin. */
562
+ static async inVault({ vault, ...opts } = {}) { return Witbitz._withVault(await connectVault({ vault }), opts) }
563
+ /** @private a client over an open vault connection (connectVault's) — tests hand in their own. */
564
+ static _withVault(conn, opts = {}) {
565
+ // REFUSED BY NAME, BEFORE ANYTHING IS MADE (sync sweep 11-09 #17, #24): a session handed to inVault would be adopted
566
+ // although the vault keeps the session (useSession is refused here, so this was the way round it); and `attest` cannot
567
+ // work in a vault — the keyless client has no enrolment, the vault answers no read proof, and a proof would bind the
568
+ // page's key, not the vault's (hosting.md § Rooms only your app may use)
569
+ if (opts && opts.session !== undefined && opts.session !== null) throw sdkError('witbitz: in a vault, the vault keeps the session — do not pass one to Witbitz.inVault (wb.vault.signIn() / wb.vault.info.email)', 'vault_signs_in')
570
+ if (opts && opts.attest !== undefined) throw sdkError("witbitz: attest is not available in a vault — attest is { bridge }, for a device that proves itself with its own hardware or enclave (a page's own proof, attest: { app }, was retired in 4.0.0)", 'vault_unsupported') // sync sweep 2026-11-23 #19: it pointed to the retired feature
571
+ // THE ACCOUNT'S STATE IS THE VAULT'S (sync sweep 11-13 P7): a persisted `backup` / `siri` / `a2a` / `invite` state was taken
572
+ // into the page — the backup's master secret, the Siri and A2A inboxes' private keys, the invite key — and a backup that was
573
+ // on started the page's own account loop beside the vault's. The vault keeps them (its getters read null here, `restore`
574
+ // refuses): refused by name, before anything is made. null = none, as for `session`.
575
+ for (const k of ['backup', 'siri', 'a2a', 'invite']) if (opts && opts[k] !== undefined && opts[k] !== null) throw sdkError(`witbitz: in a vault, the vault keeps the account's ${k} state — do not pass \`${k}\` to Witbitz.inVault`, 'vault_unsupported')
576
+ // PER-USER BILLING REACHES THE VAULT (sync sweep, 10-17 #5): the vault's worker asks for the token on each op that can
577
+ // spend, and the vault had none to give — billing was silently off, and requireUserToken refused every vault turn. The
578
+ // page hands its current token to the vault right before each such op; the vault keeps it in memory only.
579
+ const vc = conn.client
580
+ if (vc && typeof conn.userToken === 'function') {
581
+ let legacyBilling = Promise.resolve()
582
+ const tokenSlot = { turn: 5, title: 4, decide: 6, importChat: 3, importWhatsApp: 3 }
583
+ for (const op of Object.keys(tokenSlot)) {
584
+ const orig = vc[op]; if (typeof orig !== 'function') continue
585
+ vc[op] = async (...args) => {
586
+ const source = wb._userToken
587
+ let token = ''
588
+ try {
589
+ const value = typeof source === 'function' ? await source() : source
590
+ if (typeof value === 'string' && value.length <= 4096) token = value
591
+ } catch { /* a missing billing token follows this operation's normal authorization rules */ }
592
+ args[tokenSlot[op]] = token
593
+ if (conn.info?.billingPerCall) return orig(...args)
594
+ const run = legacyBilling.then(async () => {
595
+ try { await conn.userToken(token) }
596
+ catch (error) { if (token || error?.code !== 'vault_refused') throw error }
597
+ return orig(...args)
598
+ })
599
+ legacyBilling = run.catch(() => {})
600
+ return run
601
+ }
602
+ }
603
+ }
604
+ const wb = new Witbitz({ ...opts, ...(conn.info && conn.info.endpoint ? { endpoint: conn.info.endpoint } : {}), live: false, client: conn.client })
605
+ wb._vaultLive = opts.live !== false // the page's own socket stays off (live: false); the vault streams for it unless the page said live: false
606
+ wb.vault = new VaultSession(wb, conn)
607
+ refuseInVault(wb)
608
+ return wb
609
+ }
610
+
611
+ /** PER-USER BILLING, in the PAGE: bill this user's turns to their own key. `token` is what your backend got from
612
+ * `wb.users.token(userId)` — a string, or a function (sync or async) returning a fresh one; null stops sending it.
613
+ * It is sent only on ops that can spend (a turn, a title, approving an action, an import). A token that does not hold
614
+ * is REFUSED (code user_token_invalid / user_key_unavailable), never billed to you. */
615
+ useUserToken(token) { this._userToken = token || null; return this }
616
+
617
+ /** The signed-in session `{ email, idToken, exp, sign }`, or null. JSON-safe: persist it and pass it back as
618
+ * `new Witbitz({ session })`. It carries a private signing key — keep it where you keep secrets. */
619
+ get session() { return this._session }
620
+ /** Adopt a session persisted earlier (or drop it with null). */
621
+ useSession(session) { const next = sessionOf(session); if (this._session?.email !== next?.email) this._archiveGeneration++; this._session = next; if (this._session && this._session.idToken) this._prefetchIdentity(); return this }
622
+ /** The ACCOUNT this sign-in acts on (accountScope.js): the email for a sign-in made on Witbitz's own pages; an account of
623
+ * this app's own (`dana@x.com.app-…`) for one made on yours — connections, Siri and A2A here are this app's, and the user's
624
+ * own Witbitz account is not reachable from your page. '' when nobody is signed in. */
625
+ // ⛔ A SIGN-IN MADE IN THE HOSTED APP acts on the hosted app's own account (`…app-<hash of app.witbitz.chat>`), as the Lambda
626
+ // derives it (sentinelAccount by origin; SENTINEL_APP_BY_TOKEN holds the token's app to it). The plain email here made the
627
+ // cloud device's a2areply for a hosted account refused (sentinel_refused) — the job ran, its answer never got back
628
+ // (the owner's iPhone, 2026-11-25).
629
+ async _account() { const s = this._session; if (!s || !s.email) return ''; const c = tokenClaims(s.idToken); return firstPartyAppOf(c) === 'vaulted' ? sentinelAccount(s.email, c, { origin: VAULTED_APP }) : scopedAccount(s.email, c) }
630
+
631
+ /** Sign in with an emailed code, in two calls. `signIn({ email })` sends a six-digit code and returns a pending
632
+ * `{ ticket, email }`; `signIn({ email, ticket, code })` verifies it and returns the session (also kept on this
633
+ * client). The token is issued by Witbitz's own email provider and verifies like a Google token; any address works.
634
+ * @returns {Promise<{ ticket:string, email:string } | { email:string, idToken:string, exp:number, sign:object }>} */
635
+ async signIn({ email, code, ticket, room = '' } = {}) {
636
+ const result = await this._signInResult({ email, code, ticket, room })
637
+ if (!code) return result
638
+ this._session = result
639
+ this._enrollInvite()
640
+ return result
641
+ }
642
+
643
+ async _signInResult({ email, code, ticket, room = '' } = {}) {
644
+ const addr = String(email || '').trim().toLowerCase()
645
+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(addr)) throw sdkError('witbitz: signIn needs a valid email address', 'invalid_argument')
646
+ const post = this._emailPost() // emailSignIn.js — the protocol the vault and the Spaces app sign in with
647
+ if (!code) {
648
+ // A fresh signing key per session, bound into the token through the nonce (the same binding the app uses), so a
649
+ // later slice can sign with it; nothing else reads it today.
650
+ const g = await genKeypair(); const sign = { priv: g.priv, pub: g.pub }
651
+ const nonce = await spkNonce(sign.pub)
652
+ let ticket
653
+ try { ({ ticket } = await emailStart(post, { email: addr, room, nonce, tenant: this._tenant })) } catch (e) {
654
+ throw Object.assign(new Error(e.code === 'not_configured' ? 'witbitz: email codes are not available on this deployment' : 'witbitz: could not send a code' + (e.reason ? ` (${e.reason})` : '')), { code: e.code, reason: e.reason, hint: e.message })
655
+ }
656
+ this._pendingSignIn = { ticket, email: addr, sign }
657
+ return { ticket, email: addr }
658
+ }
659
+ const pend = this._pendingSignIn && (!ticket || this._pendingSignIn.ticket === ticket) ? this._pendingSignIn : null
660
+ const tk = ticket || (pend && pend.ticket)
661
+ if (!tk) throw sdkError('witbitz: signIn({ email }) first — the code needs the ticket it was sent for', 'invalid_argument')
662
+ let v
663
+ try { v = await emailVerify(post, { ticket: tk, code }) } catch (e) {
664
+ throw Object.assign(new Error('witbitz: the code was not accepted' + (e.reason ? ` (${e.reason})` : '')), { code: e.code, reason: e.reason, hint: e.message })
665
+ }
666
+ if ((v.email && v.email !== addr) || (pend && pend.email !== addr)) throw sdkError('The code belongs to a different address', 'account_changed')
667
+ this._pendingSignIn = null
668
+ return { email: v.email || addr, idToken: v.jwt, exp: v.exp, ...(pend && pend.sign ? { sign: pend.sign } : {}) }
669
+ }
670
+ /** Renew the session WITHOUT a new code — before it expires (`wb.session.exp`): a fresh signing key, and the old one
671
+ * proves this is the device that verified (the same renewal the Spaces app runs). Throws code 'refresh_failed' when
672
+ * the server will not renew it (expired, revoked) → sign in again. Persist the result like the session itself. */
673
+ async refreshSession() {
674
+ const s = this._session
675
+ if (!s || !s.idToken || !s.sign) throw Object.assign(new Error('witbitz: refreshSession needs a session from signIn() on this client'), { code: 'no_session' })
676
+ const g = await genKeypair(); const sign = { priv: g.priv, pub: g.pub }
677
+ const r = await emailRefresh(this._emailPost(), { throwOnRefusal: true, token: s.idToken, kpOld: s.sign, newNonce: await spkNonce(sign.pub), ...(this._tenant ? { tenant: this._tenant } : {}) }) // tenant: the renewed token names this app (§ 12.1)
678
+ if (!r) throw Object.assign(new Error('witbitz: the session could not be renewed — sign in again'), { code: 'refresh_failed' })
679
+ if (this._session !== s) throw sdkError('witbitz: the session changed during renewal', 'account_changed')
680
+ this._session = { email: r.email || s.email, idToken: r.jwt, exp: r.exp, sign }
681
+ this._enrollInvite()
682
+ return this._session
683
+ }
684
+ // the invite key is published in the background: a sign-in never waits on it, a failure costs only a later member change
685
+ _enrollInvite() { try { this._inviteP = this.invite.enroll().catch(() => null) } catch { /* */ } this._prefetchIdentity() }
686
+ // OPTION B: this sign-in's hints are fetched IN THE BACKGROUND — a few seconds after sign-in (and on a restored session), then
687
+ // hourly — never right before a room request, so the fetch's timing does not tie it to a room (docs/confidential-identity-
688
+ // option-b.md; sweep 11-06 #9: nothing ever called it, so the first fetch went just before the first room request).
689
+ _prefetchIdentity(delayMs = 2000 + Math.floor(Math.random() * 8000)) {
690
+ try {
691
+ clearTimeout(this._idPrefetchT)
692
+ this._idPrefetchT = setTimeout(() => {
693
+ const s = this._session, c = this._client
694
+ if (s && s.idToken && c && typeof c.prefetchIdentity === 'function') c.prefetchIdentity(s.idToken).catch(() => {})
695
+ if (s && s.idToken) this._prefetchIdentity(50 * 60_000 + Math.floor(Math.random() * 10 * 60_000))
696
+ }, delayMs)
697
+ if (this._idPrefetchT && typeof this._idPrefetchT.unref === 'function') this._idPrefetchT.unref() // never keeps a Node process alive
698
+ } catch { /* the next sealed request fetches them */ }
699
+ }
700
+ _emailPost() { return makeEmailPost(this._loginBase, { fetchImpl: (...a) => this._fetch(...a) }) }
701
+ /** Forget the session on this client (the token simply expires server-side). */
702
+ signOut() { this._archiveGeneration++; this._session = null; return this }
703
+
704
+ /** Press-to-talk: `const mic = wb.dictation(); await mic.start({ onPartial }); const text = await mic.stop()`. The
705
+ * microphone streams straight from the page to Tinfoil's confidential realtime enclave — never through Witbitz — on a
706
+ * short-lived key Witbitz mints for the signed-in user (wb.signIn) or the user your backend vouched for
707
+ * (wb.useUserToken). One per client; 13 languages, not Hebrew. Your page's CSP must allow
708
+ * `connect-src wss://inference.tinfoil.sh`. https://witbitz.chat/docs/sdk-assistant.md#dictation.
709
+ * @returns {Dictation} */
710
+ dictation() {
711
+ return (this._dictation = this._dictation || new Dictation(this, this._live ? { WebSocketImpl: this._live.WebSocketImpl } : {}))
712
+ }
713
+
714
+ /** Text read aloud: `await wb.speak('Your table is booked.')`; `wb.speech.stop()`, `wb.speech.playing`. The same player as
715
+ * the Spaces app's "Play aloud": the text goes straight from the page to Tinfoil's attested speech model on a short-lived
716
+ * key Witbitz mints for the signed-in user (wb.signIn) or the user your backend vouched for (wb.useUserToken). Not
717
+ * Hebrew. Your page's CSP must allow `connect-src https://inference.tinfoil.sh` and `media-src blob:`.
718
+ * https://witbitz.chat/docs/sdk-assistant.md#speak. @returns {Speech} */
719
+ get speech() {
720
+ return (this._speech = this._speech || new Speech(this))
721
+ }
722
+ /** Read `text` aloud → resolves when it has played (wb.speech.play). */
723
+ speak(text) { return this.speech.play(text) }
724
+
725
+ /** @private the sentinel door: `{ idToken }` for a live session, or a clear error. */
726
+ _auth(what = 'connections and the Siri inbox belong') {
727
+ const sess = this._session
728
+ if (!sess || !sess.idToken) throw Object.assign(new Error(`witbitz: sign in first (${signInHow(this)}) — ${what} to an account`), { code: 'sign_in_required' })
729
+ if (sess.exp && sess.exp <= Date.now()) throw Object.assign(new Error(`witbitz: the sign-in has expired — ${signInHow(this)} again`), { code: 'sign_in_required' })
730
+ return { idToken: sess.idToken }
731
+ }
732
+ _sentinelPost() { return (body) => this._client.sentinel(body.sentinel, body.idToken) }
733
+ /** With `devRoot` (the dev server): the cloud device is the dev server's — its attestation checked under that root, against the
734
+ * measurement the dev server publishes at <viewer>/cloud-device-claim.json; never Witbitz's pins or followed images. Else
735
+ * undefined: Witbitz's own pins, unchanged. */
736
+ async _cloudDeviceOpts() {
737
+ if (!this._devRoot) return undefined
738
+ if (!this._cdDev) {
739
+ const url = this._viewer.replace(/\/+$/, '') + '/cloud-device-claim.json'
740
+ const r = await this._fetch(url)
741
+ if (!r.ok) throw sdkError(`witbitz: the dev server's cloud device could not be found (${url} answered ${r.status})`, r.status === 404 ? 'not_in_dev_server' : 'offline')
742
+ const claim = await r.json()
743
+ const pins = Array.isArray(claim && claim.pcr0) ? claim.pcr0.filter((p) => /^[0-9a-f]{96}$/.test(p)) : []
744
+ if (!claim || claim.dev !== true || !pins.length) throw sdkError(`witbitz: ${url} is not a dev server's cloud-device claim`, 'attestation')
745
+ this._cdDev = { pins, verify: (doc, o) => verifyAttestation(doc, { ...o, root: this._devRoot }), follow: null }
746
+ }
747
+ return this._cdDev
748
+ }
749
+ /** The models this deployment offers on a tier, each with the reasoning efforts it takes:
750
+ * `[{ id, label, wire, efforts, defaultEffort, default }]`. `efforts: []` = the model takes none; `null` = not measured.
751
+ * Pass `model: { catalog: id, params: { reasoning_effort } }` to `createSpace` / `configure` to choose one.
752
+ * @param {object} [opts] { tier?: 'standard' | 'enclave' } */
753
+ async models({ tier } = {}) {
754
+ const all = await this._modelCatalog()
755
+ if (!all) { const e = new Error('witbitz: the model catalog could not be fetched'); e.code = 'unavailable'; throw e }
756
+ return tierIsEnclave(tier) ? all.confidential : all.regular
757
+ }
758
+
759
+ /** Both tiers' rows, fetched once; null (and not remembered) when the endpoint does not answer. */
760
+ async _modelCatalog() {
761
+ if (this._models) return this._models
762
+ const r = await this._encPost({ op: 'models' }).catch(() => null)
763
+ if (!r || !Array.isArray(r.regular)) return null
764
+ this._models = { regular: r.regular, confidential: Array.isArray(r.confidential) ? r.confidential : [], tempRooms: r.tempRooms === true } // tempRooms: this deployment wipes temporary rooms (createSpace({ temporary }))
765
+ return this._models
766
+ }
767
+
768
+ /** checkModelEffort against the live catalog. A catalog that cannot be fetched checks the ladder only — the server
769
+ * fits the value either way, so an unreachable list must not block creating a room. */
770
+ async _checkModel(model) {
771
+ const effort = model && typeof model === 'object' && model.params ? model.params.reasoning_effort : undefined
772
+ if (effort === undefined || effort === null) return
773
+ const all = await this._modelCatalog()
774
+ checkModelEffort(model, all ? [...all.regular, ...all.confidential] : [])
775
+ }
776
+
777
+ // ── THE CONFIDENTIAL TIER ────────────────────────────────────────────────────────────────────────────────────────
778
+ /** One POST straight at the Space endpoint, for the enclave ops the room client does not model (attest, wake, and
779
+ * handing the enclave its own copy of the config). */
780
+ async _encPost(body) {
781
+ const r = await this._fetch(this._endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
782
+ try { return await r.json() } catch { return null }
783
+ }
784
+
785
+ /** Fetch the platform's PUBLISHED claim — what it says it currently runs — and verify the LIVE enclave against it.
786
+ * Refreshes the key mk seals to, which changes on every wake, so this runs again after one. */
787
+ /** The platform's PUBLISHED claim document. ★ FAILS LOUDLY, BY CODE. `viewer` is documented as the share-link base
788
+ * and doubles as this URL's origin, so a builder who points links at their own origin — the documented thing to do —
789
+ * used to get a failed fetch that `createSpace` swallowed, and a room minted with NOTHING pinned, reported as
790
+ * success. That is the tier's whole promise turned off by a cosmetic setting. The derivation stays (a staging viewer
791
+ * needs a staging claim); what changes is that anything other than a claim document now refuses and says which URL
792
+ * it tried. Distinct from a LIVE attestation failure, which is a legitimate cold start and stays soft. */
793
+ async _encClaimDoc() {
794
+ if (this._enc.claim) return this._enc.claim
795
+ const url = (this._encClaimUrl || (this._viewer.replace(/\/+$/, '') + '/enclave-claim.json'))
796
+ const bad = (why) => {
797
+ const e = new Error(`witbitz: the enclave's published measurement could not be read from ${url} — ${why}. That URL comes from \`viewer\`; if your links point at your own origin, pass the claim's real URL as \`new Witbitz({ enclaveClaim })\`. Refusing rather than minting a confidential room that pins nothing.`)
798
+ e.code = 'enclave_claim_unavailable'
799
+ return e
800
+ }
801
+ let r
802
+ try { r = await this._fetch(url, { cache: 'no-store' }) } catch { throw bad('it could not be fetched') } // never a cached copy: a stale measurement rejects a legitimately rebuilt enclave
803
+ if (r && r.ok === false && r.status === 404) { // the Witbitz dev server (devserver/) has no confidential tier, and says so
804
+ const j = await r.json().catch(() => null)
805
+ if (j && j.error === 'not_in_dev_server') throw sdkError('witbitz: confidential Spaces are not available on the Witbitz dev server — create a standard Space there, or use Witbitz itself for this tier', 'not_in_dev_server')
806
+ }
807
+ if (!r || r.ok === false) throw bad(`it answered ${(r && r.status) || 'nothing'}`)
808
+ let claim
809
+ try { claim = await r.json() } catch { throw bad('it did not answer JSON — an app shell or a 404 page, most likely') }
810
+ if (!claim || typeof claim !== 'object' || !claim.enclave) throw bad('it answered JSON that is not a claim document')
811
+ this._enc.claim = claim
812
+ this._enc.claimUrl = url // the policy text it names is fetched from HERE, not from the page — see _policyFetcher
813
+ return claim
814
+ }
815
+
816
+ /** ⛔ THE POLICY TEXT COMES FROM THE CLAIM'S ORIGIN, BOUNDED (a builder, 2026-09-29: openSpace on a confidential room
817
+ * hung for ever in headless Firefox after "enclave-claim.json, one /v1/space request, then nothing"). The claim names
818
+ * its policy by a RELATIVE url; attestEnclave's default fetch() resolves that against the PAGE, so on a builder's site
819
+ * it went to the builder's server — never the right bytes, and on a server that holds the request open, a hang with
820
+ * no timeout. Node and the Witbitz app never showed it: there the page origin is the viewer, or there is no page. */
821
+ _policyFetcher(claimUrl) {
822
+ return async (u) => {
823
+ const url = new URL(String(u), claimUrl).href
824
+ const ac = typeof AbortController === 'function' ? new AbortController() : null
825
+ const timer = ac ? setTimeout(() => ac.abort(), this._policyTimeoutMs ?? 10000) : null
826
+ try {
827
+ const r = await this._fetch(url, { cache: 'no-store', ...(ac ? { signal: ac.signal } : {}) }) // network-only: a cached policy text is a stale one
828
+ if (!r || r.ok === false) throw sdkError(`enclave: policy text ${(r && r.status) || 'unreachable'} at ${url}`, 'enclave_claim_unavailable')
829
+ return new Uint8Array(await r.arrayBuffer())
830
+ } finally { if (timer) clearTimeout(timer) }
831
+ }
832
+ }
833
+
834
+ /** Attest the enclave that serves `room` (its region's — the request names the room, so the front forwards it), and keep
835
+ * its key under that region. No room (a room not minted yet): the facts of whichever enclave answers — every region
836
+ * runs the same measured build — and the key is kept under the default region only when no room says otherwise. */
837
+ async _encAttest(room) {
838
+ await this._encClaimDoc()
839
+ const { recipientJwk, attested } = await attestEnclave({ room, send: (b) => this._encPost(b), claim: this._enc.claim, ...(this._devRoot ? { root: this._devRoot } : {}), fetchPolicy: this._policyFetcher(this._enc.claimUrl || (this._viewer.replace(/\/+$/, '') + '/enclave-claim.json')) })
840
+ let platform = null
841
+ try { const c = enclaveClaim(this._enc.claim); platform = c ? { pcrs: c.pcrs } : null } catch { platform = null }
842
+ this._enc = { ...this._enc, attested, platform, key: recipientJwk }
843
+ if (room) this._enc.byRegion.set(roomRegion(room), { key: recipientJwk, attested, platform })
844
+ else if (!this._enc.byRegion.has(DEFAULT_REGION)) this._enc.byRegion.set(DEFAULT_REGION, { key: recipientJwk, attested, platform })
845
+ try { if (this.builds) this.builds._attested(room ? roomRegion(room) : DEFAULT_REGION, attested, platform) } catch { /* first use / automatic is best-effort; the gate decides */ }
846
+ return attested
847
+ }
848
+
849
+ /** Route an EXISTING room's ops to the enclave, before anything is asked of it. Provisional on purpose: it is what
850
+ * makes the very next call — the open — an enclave call rather than the 404 against the standard relay. */
851
+ async _encAdopt(room) {
852
+ if (!room || this._enc.rooms.has(room)) return
853
+ await this._encAttestSoft(room)
854
+ this._enc.rooms.set(room, true)
855
+ }
856
+
857
+ /** Attest before a NEW confidential room is made. Two failures look alike from the outside and must not be treated alike:
858
+ * a LIVE attestation failure is the documented cold start (mint in follow mode, pin nothing, wake it next), while a
859
+ * CONFIGURATION failure means we never saw a measurement at all — and swallowing that mints a confidential room
860
+ * whose acceptance pins nothing, which is the one outcome this tier exists to prevent. Soft for the first, loud for
861
+ * the second. */
862
+ async _encAttestSoft(room) {
863
+ try { return await this._encAttest(room) } catch (e) {
864
+ if (e && (e.code === 'enclave_claim_unavailable' || e.code === 'not_in_dev_server')) throw e // a configuration answer, never a cold start
865
+ // A document that ARRIVED but does not chain to the trusted root (or is not signed by its own certificate) is never a cold
866
+ // start: no enclave of ours can produce one. A measurement mismatch stays soft — a rebuilt enclave meets a claim that lags.
867
+ if (e && typeof e.message === 'string' && /^(chain: |attestation: COSE signature does not verify)/.test(e.message)) {
868
+ throw sdkError(`witbitz: the enclave's attestation does not chain to the trusted root (${e.message}) — refusing to trust it`, 'attestation_untrusted')
869
+ }
870
+ return null
871
+ }
872
+ }
873
+
874
+ /** Wait until the enclave is up AND attested. Returns the attestation, or throws when it never came. */
875
+ async _encWake(room, { tries = 45, waitMs = 8000 } = {}) {
876
+ for (let i = 0; i < tries; i++) {
877
+ try { await this._encPost({ op: 'wake', enclave: true, room }) } catch { /* keep trying */ }
878
+ try { return await this._encAttest(room) } catch { /* not up yet */ }
879
+ await new Promise((res) => setTimeout(res, waitMs))
880
+ }
881
+ throw Object.assign(new Error('witbitz: the enclave did not come up — the Space exists, but nothing has been sent to it'), { code: 'enclave_unavailable' })
882
+ }
883
+
884
+ /** ★ Hand the enclave its OWN copy of the sealed config, BEFORE the first turn. The enclave reads the room record
885
+ * from its own store, which holds only the mk-commitment — without this the turn runs a DEFAULT agent instead of the
886
+ * one that was asked for, and it is too late once a turn has run. */
887
+ async _encSealConfig(room, commit, configSealed) {
888
+ if (!configSealed) return false
889
+ const r = await this._encPost({ op: 'create', enclave: true, room, ...(commit ? { commit } : {}), configSealed })
890
+ return !!(r && (r.ok || r.status === 200 || r.created || r.exists || r.error === 'exists')) // 409 { error: 'exists' }: the create already carried it there (spaceRoom.mjs)
891
+ }
892
+
893
+ /** Feature detection, mostly for on-prem deployments: this SDK's version and features, the declaration limits, which
894
+ * tiers this deployment serves (the confidential tier = its published measurement can be read) and its models.
895
+ * → { sdk, endpoint, features, limits, tiers: { standard, enclave }, models: { regular, confidential } | null } */
896
+ async capabilities() {
897
+ const models = await this._modelCatalog().catch(() => null)
898
+ let enclave = false
899
+ try { await this._encClaimDoc(); enclave = true } catch { /* no published claim: no confidential tier here */ }
900
+ const ids = (l) => (Array.isArray(l) ? l.map((m) => m && m.id).filter(Boolean) : [])
901
+ return { sdk: SDK_VERSION, endpoint: this._endpoint, features: [...FEATURES], limits: { ...LIMITS }, tiers: { standard: true, enclave }, models: models ? { regular: ids(models.regular), confidential: ids(models.confidential) } : null }
902
+ }
903
+
904
+ /** Is this tenant key good, and whose is it? → `{ ok: true, tenant }` or `{ ok: false, reason }`. See WitbitzAdmin. */
905
+ async verifyTenantKey() { return this._admin.verifyTenantKey() }
906
+ _roomDeleteEndpoint() {
907
+ const endpoint = this._tenantEndpoint()
908
+ if (!/\/tenant-space(?=$|[?#])/.test(endpoint)) throw sdkError('witbitz: room deletion requires a tenant-space endpoint', 'invalid_endpoint')
909
+ return endpoint.replace(/\/tenant-space(?=$|[?#])/, '/spaces/rooms/delete')
910
+ }
911
+ _tenantEndpoint() { return this._admin._tenantEndpoint() }
912
+ _tenantRest(...a) { return this._admin._tenantRest(...a) }
913
+ _tenantPost() { return this._admin._tenantPost() }
914
+
915
+ /** Create a shared, private, agent-backed Space. → a live {@link Space}.
916
+ * @param {object} [opts]
917
+ * @param {object} [opts.agent] { name, instructions, tools?, model? }
918
+ * @param {object[]} [opts.tools] your app's tool definitions { name, description?, inputSchema?, readOnly?, autoRun? } (the platform's own tools: opts.platformTools)
919
+ * @param {string[]} [opts.immediateTools] the subset it may call WITHOUT human approval (others become proposals)
920
+ * @param {string|object} [opts.model] a model id, or { catalog, params: { reasoning_effort } } (checkModelEffort)
921
+ * @param {object} [opts.data] the store's collections { col: { description?, fields: { f: 'what it is' }, write?: 'admins' } }
922
+ * @param {object} [opts.admission] { emails, domains, advertise?, admins?, owners? } — the email gate, create-time only
923
+ * @param {string} [opts.tier] 'standard' (default) | 'enclave' — the confidential tier, create-time only
924
+ * @param {string} [opts.key] 'standard' (default) | 'split' — a split-key room (needs `appShare` or `tenant`)
925
+ * @param {string} [opts.region] the room's home region, a code from regions.js (e.g. 'us'); default: `new Witbitz({ region })`, else the default region
926
+ * @param {boolean} [opts.safeMedia] SAFE MEDIA: others' photos and PDFs are shown only from copies an attested enclave made safe (space.safeMedia)
927
+ * @param {boolean} [opts.lanes] A PRIVATE ASSISTANT FOR EVERYONE, as the app's New Space option: sealed in the room, and the link says so (space.lanes) */
928
+ async recreateSpace(bundle, opts = {}) {
929
+ const { recreateExport } = await import('./sdkExports.js')
930
+ return recreateExport(this, bundle, opts)
931
+ }
932
+ async saveOfflineReader() {
933
+ const { saveOfflineReader } = await import('./sdkExports.js')
934
+ return saveOfflineReader()
935
+ }
936
+ async exportOfflineArchive({ recoveryKeys = false, rooms } = {}) {
937
+ if (rooms !== undefined && (!Array.isArray(rooms) || rooms.some(sp => !sp || sp._wb !== this || sp._stopped || !sp.room))) throw sdkError('select open Spaces from this SDK client', 'invalid_argument')
938
+ if (this.vault) return this.vault._c.account('backup', 'exportArchive', recoveryKeys === true, rooms?.map(sp => sp.room))
939
+ const { saveAccountArchive } = await import('./sdkExports.js')
940
+ const session = this._session, backup = this.backup._s
941
+ const selected = new Map((rooms === undefined ? this.backup.rooms : []).map(r => [r.room, r]))
942
+ const opened = [...(this._archiveHandles || [])].filter(sp => sp._archiveGeneration === this._archiveGeneration && sp._archiveEmail === (session?.email || '') && sp._archiveMaster === (backup?.master || null))
943
+ if (rooms?.some(sp => !opened.includes(sp))) throw sdkError('select Spaces opened for this account', 'invalid_argument')
944
+ for (const sp of rooms ?? opened) {
945
+ if (!sp || sp._wb !== this || sp._stopped || !sp.shareLink) throw sdkError('select open Spaces from this SDK client', 'invalid_argument')
946
+ selected.set(sp.room, { room: sp.room, link: sp.shareLink, title: sp.title, held: sp })
947
+ }
948
+ return saveAccountArchive([...selected.values()], async (r, keysOnly) => {
949
+ const { room, mk } = r.held?._mk ? { room: r.room, mk: r.held._mk } : await this._openLink(r.link)
950
+ if (room !== r.room) throw sdkError('witbitz: a saved link opens another Space', 'wrong_room')
951
+ if (keysOnly) return { key: mk }
952
+ const saved = await this._client.exportSealed(room, mk)
953
+ if (saved?.status !== 200) throw sdkError('witbitz: this Space\u2019s history could not be read just now', 'unavailable')
954
+ return { key: mk, ledger: saved.sealed, count: saved.count }
955
+ }, recoveryKeys === true, () => this._session === session && this.backup._s === backup)
956
+ }
957
+ async createSpace({ agent = {}, tools, immediateTools, clientTools, agentReplies, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, temporary, safeMedia, lanes, owner } = {}) {
958
+ // A TEMPORARY ROOM (docs/visitor-limits.md): a `tmp-` room the deployment wipes when it is idle — `true`: after about half
959
+ // an hour, as the app's temporary Spaces; `{ days }` (1–7): that many days after its last question (a help desk on a
960
+ // public page, kept while the visitor comes back). Refused rather than faked where it cannot be wiped.
961
+ let lapseDays = 0
962
+ if (temporary !== undefined && temporary !== false) {
963
+ if (temporary !== true && !(temporary && typeof temporary === 'object' && Number.isInteger(temporary.days) && temporary.days >= 1 && temporary.days <= 7)) throw sdkError('witbitz: temporary takes true or { days } — a whole number of days from 1 to 7', 'invalid_temporary')
964
+ if (this.vault) throw sdkError('witbitz: a temporary room is not available in a vault yet', 'vault_unsupported')
965
+ lapseDays = temporary === true ? 0 : temporary.days
966
+ }
967
+ if (safeMedia !== undefined && typeof safeMedia !== 'boolean') throw sdkError('witbitz: safeMedia takes true or false', 'invalid_argument')
968
+ // RETIRED in 4.0.0 (the owner, 2026-11-22: "We dont need any emulation rooms"): `owner` made a room only a page SERVED as your app
969
+ // could use — a web page vouching for itself, which anyone can copy. Client verification is the Witbitz apps' hardware proof.
970
+ if (owner !== undefined) throw sdkError('witbitz: createSpace({ owner }) is retired — a web page cannot prove which app it is (sdk-changes.md, 4.0.0)', 'owner_rule_retired')
971
+ if (clientTools !== undefined && !Array.isArray(clientTools)) throw sdkError('clientTools must be an array', 'invalid_argument')
972
+ if (agentReplies !== undefined && typeof agentReplies !== 'boolean') throw sdkError('agentReplies must be a boolean', 'invalid_argument')
973
+ if (lanes !== undefined && typeof lanes !== 'boolean') throw sdkError('witbitz: lanes takes true or false', 'invalid_argument')
974
+ if (lanes === true && temporary !== undefined && temporary !== false) throw sdkError('witbitz: a temporary room has no private lanes — a lane is a durable room, and its copies would outlive the wipe', 'temporary_room') // as the app (space.js)
975
+ if (safeMedia === true && temporary !== undefined && temporary !== false) throw sdkError('witbitz: a temporary room has no Safe media — the Spaces app never offers it there (New Space, ⋯ → This Space)', 'temporary_room') // newSpaceAssistants.js paintSafeOpt (sync sweep 2026-11-13)
976
+ if (safeMedia === true && !safeMediaReady()) throw sdkError('witbitz: no safe-media enclave is accepted in this release yet', 'safe_media_unavailable')
977
+ if (this.vault) return this.vault._create({ agent, tools, immediateTools, clientTools, agentReplies, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, safeMedia, lanes }) // vault-core CREATE_FIELDS takes safeMedia and lanes
978
+ // A DIRECT CHAT (the Spaces app's, directChat.js): a verified Space with exactly you and one other person, you its owner,
979
+ // `direct: true` sealed in — the server refuses its rename and each side calls it by the other person (space.directPeer).
980
+ if (direct !== undefined) admission = directAdmission(direct, admission, this._session)
981
+ // ★ THE CREATOR IS THE OWNER, as in the app (space.js gatedBase; docs/verified-room-members.md): a verified room names its
982
+ // signed-in creator as its first owner when they are on its list and no owners were given — authority then follows that
983
+ // email onto every device (sync sweep, 10-12). Not on the list, or not signed in: unchanged (an owner who cannot open it
984
+ // would be no owner).
985
+ { const me = this._session && this._session.email && !(this._session.exp && this._session.exp <= Date.now()) ? String(this._session.email).trim().toLowerCase() : ''
986
+ const listed = admission && typeof admission === 'object' && Array.isArray(admission.emails) ? admission.emails.map((e) => String(e).trim().toLowerCase()) : []
987
+ if (me && listed.includes(me) && !(Array.isArray(admission.owners) && admission.owners.length)) admission = { ...admission, owners: [me] } }
988
+ const gate = normAdmission(admission)
989
+ const enc = tierIsEnclave(tier)
990
+ const split = splitKeyChoice(key)
991
+ if (split && !this._appShareUrl && !this._clientOpts.tenant) throw Object.assign(new Error("witbitz: a split-key room needs your app-half function — new Witbitz({ appShare: '/api/appshare' }) — or, with the Witbitz-held key, your tenant — new Witbitz({ tenant: 't_…' })"), { code: 'tenant_required' })
992
+ await this._checkModel(model || agent.model)
993
+ const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
994
+ if (Array.isArray(clientTools)) cfg.clientTools = clientTools
995
+ if (agentReplies !== undefined) cfg.agentReplies = agentReplies
996
+ if (direct !== undefined) cfg.direct = true
997
+ if (safeMedia === true) cfg.safeMedia = true // sealed with the rest (spaceClient.js create); a room without it is sealed exactly as before
998
+ if (lanes === true) cfg.lanes = true // every member's app makes them a private lane (roomSync.js ensureOwnLane reads it from the sealed config)
999
+ cfg.region = region || this._region // the room's home region is in its id (regions.js, docs/multi-region.md)
1000
+ if (temporary !== undefined && temporary !== false) {
1001
+ const all = await this._modelCatalog().catch(() => null)
1002
+ if (!(all && all.tempRooms)) throw sdkError('witbitz: temporary rooms are not available on this deployment', 'temporary_unavailable')
1003
+ cfg.room = newRoomId(cfg.region, { prefix: 'tmp' }) // the whole stack keys off the prefix (the app's tempRooms.js mints the same shape)
1004
+ }
1005
+ // Attest FIRST (a configuration failure is loud, a cold enclave is not — _encAttestSoft); mint; only then wake and hand
1006
+ // the enclave its config.
1007
+ if (enc) await this._encAttestSoft()
1008
+ const { room, mk, links, commit, configSealed, userShare, enclaveCreated } = await this._client.create(cfg, { base: this._viewer, ...(enc && !split ? { enclave: true } : {}), ...(split ? this._splitOpts() : {}), ...(lapseDays ? { lapseDays } : {}) })
1009
+ if (enc) {
1010
+ this._enc.rooms.set(room, true) // from here the client marks this room's ops enclave:true and seals mk to the attested key
1011
+ await this._encWake(room)
1012
+ // The create went to the enclave carrying the sealed config, and the enclave answered that it made the room — so its record
1013
+ // already holds the config (agent/spaceRoom.mjs). Handing it over again was a second round trip answered `409 exists` on every
1014
+ // confidential create (~0.4 s; the HN demo's timeline, 2026-11-06). Without that answer (an older server), as before.
1015
+ if (!enclaveCreated && !(await this._encSealConfig(room, commit, configSealed))) throw sdkError('the new confidential Space could not receive its configuration', 'enclave_seal_failed')
1016
+ }
1017
+ const base = split ? splitLinkOf(links[0], userShare, commit) : links[0]
1018
+ const link = lanes === true ? markLanesLink(gate ? markGateLink(base) : base) : gate ? markGateLink(base) : base // lanes=1: the app's hint — an invitee's app makes their lane without first reading the room's settings
1019
+ const sp = new Space(this._client, { room, mk, link: enc ? markEncLink(link) : link, viewer: this._viewer, wb: this, gated: !!gate, split })
1020
+ sp.safeMedia._learn(safeMedia === true, 0) // a new room's setting is what it was made with
1021
+ const made = String(room).startsWith('tmp-') ? sp : this._backedUp(sp) // a temporary room is never in the account backup (it is wiped), as the app's
1022
+ if (direct !== undefined) await made.setReplyMode('ondemand').catch(() => {}) // the assistant is in the chat and answers when @mentioned, as in the app
1023
+ return made // an enclave room's link says so, or a fresh client cannot know (see ENC_MARK)
1024
+ }
1025
+
1026
+ /** @private how a split room is created: through the builder's function when there is one (`via`), else here. */
1027
+ _splitOpts() { return { split: true, ...(this._appShareUrl ? { via: (body) => this._appShareCall(body) } : {}) } }
1028
+
1029
+ /** @private one call to the builder's app-half function → { status, ...answer }. Same-origin by design: the function
1030
+ * answers its own origin only. */
1031
+ async _appShareCall(body) {
1032
+ let r
1033
+ try { r = await this._fetch(this._appShareUrl, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }) } catch { return { status: 0, error: 'appshare_unreachable' } }
1034
+ const j = await r.json().catch(() => ({}))
1035
+ return { ...(j && typeof j === 'object' ? j : {}), status: r.status }
1036
+ }
1037
+
1038
+ /** @private every room this client creates or opens is recorded in the account backup (a no-op until enabled). */
1039
+ _backedUp(sp) {
1040
+ if (!this.vault && sp.shareLink && !sp.room.startsWith('tmp-')) {
1041
+ (this._archiveHandles ||= new Set()).add(sp)
1042
+ sp._archiveGeneration = this._archiveGeneration
1043
+ sp._archiveEmail = this._session?.email || ''; sp._archiveMaster = this.backup._s?.master || null
1044
+ }
1045
+ try { this.backup.add(sp) } catch { /* the backup must never cost the room */ }
1046
+ try { this.erasure._seen(sp) } catch { /* nor the erase list */ }
1047
+ return sp
1048
+ }
1049
+
1050
+ /** Open a Space you (or a member) hold a link to. The link's fragment carries the key; it never touches the server.
1051
+ * @param {string} link a Space share link (or the current page URL, if it is one).
1052
+ * @param {object} [opts] { resume? } — a prior {@link Space#snapshot}, so this open resumes past what you already
1053
+ * have instead of replaying the whole ledger (see `resume` on the {@link Space} constructor). → a live {@link Space}. */
1054
+ async openSpace(link, { resume, tier } = {}) {
1055
+ if (this.vault) throw sdkError('witbitz: in a vault, a link is opened by the vault (the link points at it) — then wb.vault.openRoom(room)', 'vault_opens_links')
1056
+ const { room, mk, link: s, split } = await this._openLink(link, { tier })
1057
+ return this._backedUp(new Space(this._client, { room, mk, link: s, viewer: this._viewer, resume, wb: this, split }))
1058
+ }
1059
+
1060
+ /** Reopen a member's existing private lane — the link {@link Space#privateLane} returned (`lane.shareLink`) — on
1061
+ * its shared Space, with its actions. One call: it opens the lane's link once and returns a live {@link Lane}.
1062
+ * A lane of a confidential Space is confidential, exactly as privateLane made it, even from an older unmarked link.
1063
+ * @param {string} laneLink the lane's link
1064
+ * @param {object} opts { space, actions?, resume?, tier? } — `space`: the shared {@link Space} this lane belongs to
1065
+ * (its crossings are posted there, so it is required); `resume`: a prior {@link Space#snapshot} of the lane. */
1066
+ async openLane(laneLink, { space, actions, resume, tier, mirror = false } = {}) {
1067
+ if (space && !this.vault) await assertNotKept(space)
1068
+ if (space && space.temporary) throw sdkError('witbitz: a temporary room has no private lane — the lane is a durable room, and its copies of the room would outlive the wipe', 'temporary_room') // as the app (roomSync.js ensureOwnLane; sync sweep 2026-10-27 #3)
1069
+ if (space && (space._sharedRoom || wasLaneRoom(this, space.room))) throw sdkError('witbitz: a private lane has no lane of its own — open the lane on its Space', 'lane_of_lane') // as privateLane (sync sweep 11-08: openLane took a lane as the Space)
1070
+ if (this.vault) return this.vault._openLane(laneLink, { space, actions, resume, tier, mirror })
1071
+ if (!(space instanceof Space) || !space.room || !space._mk) throw sdkError('witbitz: openLane needs `space`, the shared Space the lane belongs to (from createSpace or openSpace) — a lane posts its crossings there', 'invalid_argument')
1072
+ if (roomFromLink(String(laneLink)) === space.room) throw sdkError('witbitz: that is the Space\'s own link, not a lane of it — open it with openSpace', 'invalid_argument') // a Space recorded as its own lane (sweep P1)
1073
+ const sharedIsEnclave = !!(this._enc && this._enc.rooms.has(space.room))
1074
+ // THE LANE'S OWN TIER (sweep 11-06 #6): a lane of a confidential Space was always taken as confidential — right for an old
1075
+ // unmarked privateLane link, wrong for a regular room the app LINKED to it (drawer.js), whose ops then went to an enclave
1076
+ // that does not hold it. The link's mark or `tier` decide; an unmarked link is asked of the standard tier (keyless: op
1077
+ // policy is public) — it answers for its own rooms and refuses a confidential one.
1078
+ let laneEnclave = sharedIsEnclave
1079
+ if (sharedIsEnclave && !tier && !ENC_MARK.test(String(laneLink))) { const has = await this._standardHas(roomFromLink(String(laneLink))); if (has === true) laneEnclave = false }
1080
+ const { room, mk, link: s, split } = await this._openLink(laneLink, { tier, enclave: laneEnclave })
1081
+ await assertNotKept({ room, _mk: mk, _wb: this, _client: this._client })
1082
+ // ACROSS TIERS (the owner: 2026-10-11 for the app, 2026-10-23 "make it also in the sdk"). The two tiers keep separate
1083
+ // stores and a confidential room's key never rides the standard tier, so a lane of the other tier gets NO bridge: this
1084
+ // device copies the Space into it (the mirror, on whatever was asked), as the Spaces app does (roomSync.laneBridge).
1085
+ const laneIsEnclave = !!(this._enc && this._enc.rooms.has(room))
1086
+ const crossTier = laneIsEnclave !== sharedIsEnclave
1087
+ await refuseAttestedIntoPlain(this._client, space.room, space._mk, room, mk) // sync sweep 2026-11-15 #5: as the app's mirrorLoop.js
1088
+ return this._backedUp(new Lane(this._client, { room, mk, link: s, viewer: this._viewer, sharedRoom: space.room, sharedMk: space._mk, actions, resume, wb: this, shared: space, mirror: crossTier ? (mirror || true) : mirror, split, crossTier }))
1089
+ }
1090
+
1091
+ /** Does the STANDARD tier hold `room`? → true · false (it refused it as confidential) · null (cannot tell). Keyless. */
1092
+ async _standardHas(room) {
1093
+ if (!room) return null
1094
+ try {
1095
+ const r = await this._client.policyOf(room, null)
1096
+ if (!r) return null
1097
+ if (r.error === 'confidential_room' || r.confidential === true || r.tier === 'enclave') return false // tier: the tier guard's word on a keyless policy (agent/tierGuard.mjs)
1098
+ // ONLY A DEFINITIVE YES (sweep 11-07 #3): a confidential room's mirror row and a missing room both answer an EMPTY 200 here
1099
+ // (agent/spaceRoom.mjs), and taking that for "standard" sent the lane's first keyed op — its key readable — to the Lambda
1100
+ if (r.status === 200) return r.configSealed || r.gated === true || r.lanes === true || r.policy ? true : null
1101
+ if (r.status === 401 || r.status === 403) return true
1102
+ return null
1103
+ } catch { return null }
1104
+ }
1105
+
1106
+ /** Open a link to { room, mk, link }. An enclave room is adopted BEFORE the open (on one, the open is itself an
1107
+ * enclave op), and the room the open answered after. ★ A link minted before the marker existed can still be adopted with
1108
+ * `{ tier: 'enclave' }` — rooms created by an earlier build have unmarked links and would otherwise be unopenable. */
1109
+ _emptySpaceHooks() {
1110
+ const b = this.backup, state = b._s, session = this._session
1111
+ const current = () => !!state && b._s === state && this._session === session
1112
+ const records = () => current() ? state.rooms || [] : []
1113
+ const remove = async (room, options) => {
1114
+ const key = await this.erasure._key()
1115
+ return key && current() ? deleteOwnRoom(room, { ...options, url: this._roomDeleteEndpoint(), keys: [key], dropKeys: this.erasure._dropKeys(), fetchImpl: (...a) => this._fetch(...a) }) : { status: 0, body: { error: 'no_account_key' } }
1116
+ }
1117
+ return {
1118
+ rooms: () => records().map(r => ({ room: r.room, title: r.label || 'Space', pinned: !!r.pinned })),
1119
+ me: () => this.erasure._account(),
1120
+ keep: room => records().some(r => r.room === room && (r.kind === 'lane' || r.help) || r.shared === room),
1121
+ read: async room => {
1122
+ const row = records().find(r => r.room === room)
1123
+ if (!row) return null
1124
+ const { mk } = await this._openLink(row.link)
1125
+ const config = await this._client.getConfig(room, mk, { plainMark: true })
1126
+ if (current() && (config?.help || config?.lane || config?.bridge)) return { excluded: true }
1127
+ const v = await readAllPages(since => this._client.poll(room, mk, undefined, since))
1128
+ return current() && config && !config.help && !config.lane && !config.bridge && v.status === 200 && !v.incomplete ? { config, entries: v.entries, etag: v.etag, selfEntries: await ownAdmissionEntries(config, this.erasure._account(), () => this._client.state(room, mk, 'roster')), selfHash: this.erasure._account() ? await memberHash(this.erasure._account(), room) : null } : null
1129
+ },
1130
+ prepare: room => remove(room, { check: true, reviewPolicy: true }),
1131
+ deleteOnServer: (room, reviewedEtag, reviewedPolicy) => remove(room, { reviewedEtag, reviewedPolicy }),
1132
+ checkDeletion: room => remove(room, { check: true }),
1133
+ forget: async room => { if (current()) this.account.forget(room) },
1134
+ gone: async room => (await remove(room, { check: true })).body?.deleted === true,
1135
+ }
1136
+ }
1137
+
1138
+ async _openLink(link, { tier, enclave = false } = {}) {
1139
+ const s = String(link)
1140
+ const enc = tierIsEnclave(tier) || ENC_MARK.test(s) || enclave
1141
+ if (SPLIT_MARK.test(s)) {
1142
+ // A SPLIT link is half a key. The account backup may hold the whole key (§3.4 — never hostage to the app half);
1143
+ // otherwise the room's tenant serves the app half to THIS page only if its origin is declared. Either way the
1144
+ // combine must match the room's commitment before it is used (§6.4).
1145
+ const room = roomFromLink(s), userShare = fragParam(s, 'us'), want = fragParam(s, 'spc')
1146
+ if (!room || !userShare) throw sdkError('witbitz: that link is not a Space link (or its key is incomplete)', 'invalid_link')
1147
+ const kept = this.backup.keyFor(room)
1148
+ // ⚑ A SPLIT ENCLAVE SPACE (the hosted app makes them: a backend create, then the enclave seal — the owner, 2026-11-25: "Keep this
1149
+ // Space always on" on a hosted Enclave Space ended "could not read this Space's gate"). The app half is the standard tier's to serve,
1150
+ // as for any split room; once the key is whole, the room's ops go to its enclave. It used to be refused here outright.
1151
+ if (kept && want && await keyCommit(kept) === want) { if (enc) await this._encAdopt(room); return { room, mk: kept, link: s, split: true } }
1152
+ const r = this._appShareMember ? await this._appShareMember(room).catch(() => ({ status: 0, error: 'appshare_unreachable' })) : this._appShareUrl ? await this._appShareCall({ op: 'get', room }) : await this._client.appSharePage(room)
1153
+ if (!r || r.status !== 200 || !r.appShare) {
1154
+ const code = (r && r.error) || 'split_unopenable'
1155
+ throw Object.assign(new Error(code === 'origin_not_declared'
1156
+ ? "witbitz: this room's other key half is served only to its tenant's declared origins (wb.origins), and this page is not on one"
1157
+ : `witbitz: the room's other key half could not be fetched (${code})`), { code, status: r && r.status })
1158
+ }
1159
+ const mk = await reconstructMk({ userShare, appShare: r.appShare, expectedCommit: want || r.commit })
1160
+ if (!mk) throw Object.assign(new Error('witbitz: the two key halves do not make this room’s key — refused'), { code: 'split_mismatch' })
1161
+ if (enc) await this._encAdopt(room) // after the halves are whole: its ops route to the enclave
1162
+ return { room, mk, link: s, split: true }
1163
+ }
1164
+ if (enc) await this._encAdopt(roomFromLink(s))
1165
+ const { room, mk } = await this._client.open(s)
1166
+ if (!room || !mk) throw sdkError('witbitz: that link is not a Space link (or its key is incomplete)', 'invalid_link')
1167
+ if (enc) await this._encAdopt(room) // the room the open answered (a link need not name it) — its ops route to the enclave
1168
+ return { room, mk, link: s }
1169
+ }
1170
+ }
1171
+
1172
+ /** A live handle to one Space. Emits `message` as entries arrive (yours, other members', and the agent's), and
1173
+ * `error` on a transient poll failure. Backed by a content-blind poll loop that opens the sealed ledger locally. */
1174
+ export class Space {
1175
+ /** @param {object} opts { room, mk, link, viewer?, resume? } — `resume` is a prior {@link Space#snapshot} (or the
1176
+ * same shape you built yourself: `{ count, etag, messages, rows }`, all optional). Passing it seeds this Space
1177
+ * from what you already have instead of replaying the ledger from entry 0: `pollSealed`'s `sinceCount` already
1178
+ * slices server-side, so the first live poll asks for only what is new. Malformed input never throws — a bad or
1179
+ * partial `resume` just resumes as much of it as parses, exactly as if the missing parts had not been passed. */
1180
+ constructor(client, { room, mk, link, viewer = DEFAULT_VIEWER, resume, wb = null, live, gated = false, split = false, poll = true, handlers, lanes = false }) {
1181
+ /** @type {string} the server-visible room id */
1182
+ if (typeof resume?.room === 'string' && resume.room !== room) resume = null
1183
+ this.room = room
1184
+ this._lanesHint = lanes === true // in a vault the page holds no link: the vault's room list says it (sync sweep 2026-10-29 #3)
1185
+ this.epoch = null // latest key rotation observed by this handle
1186
+ this._a2aResume = resume && Array.isArray(resume.a2a) ? resume.a2a : null
1187
+ this._gated = !!gated || GATE_MARK.test(String(link || '')) // an email-gated room (see markGateLink) — no config fetch to know it
1188
+ this._split = !!split || SPLIT_MARK.test(String(link || '')) // a split-key room: its link is half a key (https://witbitz.chat/docs/sdk-keys.md#split-key)
1189
+ this._liveOpts = live !== undefined ? live : (wb && wb._live) || null // room streams (null → polling only)
1190
+ this._stream = null; this._streamFrameAt = 0; this._partial = { text: null }; this._feed = makeTurnFeed() // turnFeed.js: the room's word on a running turn, read the same way the Spaces app reads it
1191
+ this._wb = wb // the Witbitz client that opened this Space — its session and Siri state (null for a bare handle)
1192
+ /** This Space's connections: what ITS assistant may spend. `grant` needs a connection from `wb.connections`. */
1193
+ this.connections = new SpaceConnections(this)
1194
+ /** The Siri inbox for THIS Space: enable an alias, collect what was said, disable. Needs a signed-in `wb`. */
1195
+ this.siri = new SpaceSiri(this)
1196
+ /** SAFE MEDIA in this Space: the setting, verified safe copies of photos and PDFs, making one (sdkSafeMedia.js). */
1197
+ this.safeMedia = new SpaceSafeMedia(this)
1198
+ this.schedules = new SpaceSchedules(this)
1199
+ this.alwaysOn = new SpaceAlwaysOn(this)
1200
+ /** @type {string} the share link — hand it to someone to let them in (the link IS the auth) */
1201
+ this.shareLink = link
1202
+ /** @type {Array} every message seen so far, oldest first */
1203
+ // ledgerView.js — how the Spaces app merges a room's entries: a new id is added, a known one REWRITTEN in place (a
1204
+ // reaction, a caption, a reply's widgets) is updated where it stands and announced on 'update'.
1205
+ this._view = makeLedgerView()
1206
+ this.messages = this._view.list
1207
+ this._oldKeys = new Set() // this room's keys before a change in place (sdkRekey.js): a call still carrying one runs again with the new
1208
+ this._client = healingClient(client, () => this._reattest(), { adopt: (args) => this._adoptKey(args), learnTier: async (room) => { const wb = this._wb; if (!room || !wb || !wb._enc || wb._enc.rooms.has(room) || typeof wb._encAdopt !== 'function') return false; await wb._encAdopt(room); return wb._enc.rooms.has(room) && !!wb._enc.key } }) // a stale / missing enclave key heals on ANY keyed call (below); a re-keyed room's old key too
1209
+ this._mk = mk
1210
+ this._viewer = viewer
1211
+ this._subs = {}
1212
+ this._etag = null
1213
+ this._count = 0
1214
+ this._timer = null
1215
+ this._inflight = false
1216
+ this._stopped = false
1217
+ this._lastActive = 0
1218
+ /** Resolves once the WHOLE history has been read (every page of a long room) — by then `messages` (and `data.rows()`) hold what the room had. A refused
1219
+ * poll (a warming enclave, a gated read before sign-in) does not count; those keep retrying and raise `error`.
1220
+ * Rejects only when this key can never open the room (`code: 'cannot_open'`), the room requires a room pass this client cannot
1221
+ * get (`code: 'pass_required'`), or the handle is closed first (`code: 'closed'`). A builder waited on `_inflight`/`_timer` for this and drew an empty room on a refused poll. */
1222
+ this.ready = new Promise((resolve, reject) => { this._readyResolve = resolve; this._readyReject = reject })
1223
+ this.ready.catch(() => {}) // an unawaited ready that rejects must not become an unhandled rejection
1224
+ // REPLY MODE (spaces/test/sdkReplyMode.test.mjs) — 'auto' | 'always' | 'ondemand', carried on each turn. The room's
1225
+ // setting lives in the sealed, content-blind `agentmode` doc that the Spaces app already writes
1226
+ // (spaces/public/agentMode.js), so a builder and our own UI mean the SAME thing by "Always" rather than running two
1227
+ // parallel mechanisms. Read ONCE here, at construction, because a rebuilt handle from a saved link must already
1228
+ // carry it on its FIRST send — a remedy that only takes effect on the second message is not a remedy. Best-effort:
1229
+ // `_modeReady` never rejects, and a room with no doc simply sends no mode (⇒ the room's default, roomSettings.js roomDefaultReplyMode).
1230
+ // THE ROOM'S NAME (https://witbitz.chat/docs/sdk-rooms.md#room-name) — roomName.js, the module the Spaces app reads it with:
1231
+ // the newest { kind:'title' } entry in the log (a rename, a generated name), else the room's shared title doc. Title
1232
+ // entries are not messages: they never enter `messages` and never fire 'message'; they set `title` and fire 'title'.
1233
+ this._title = null; this._titleTs = -Infinity; this._titleDocAt = Date.now(); this._titleDocEvery = SETTINGS_FRESH_MS // the doc is read again on the settings' cadence (_maybeTitleDoc)
1234
+ if (!this._hostDriven && poll !== false) Promise.resolve().then(async () => { // the doc: for a room with no title entry yet
1235
+ try { const t = titleFromDoc(await client.state(room, mk, 'title')); if (t && this._titleTs === -Infinity && !this._title) this._setTitle({ title: t.title, manual: t.manual, by: '', ts: -Infinity }) } catch { /* the name is a convenience */ }
1236
+ })
1237
+ this._mode = null; this._modelPick = undefined; this._settingsAt = 0
1238
+ this._modeReady = Promise.resolve().then(() => this._readSettings())
1239
+ // Proposals (the agent's data writes, a lane's crossings and actions) + device-side reads, on every Space:
1240
+ this._writes = {}; this._reads = {}; this._pendingActions = {}; this._inflightPending = false; this._pendingTimer = null; this._devDone = new Set()
1241
+ // HOST-DRIVEN: `poll: false` — the page that holds this handle runs its own poll loop (the
1242
+ // Spaces app does) and asks for proposals with pending(); the Space starts no timer of its own. `handlers`: device
1243
+ // actions by type, run here when a member approves one (the same as a lane's propose-mode actions).
1244
+ this._hostDriven = poll === false
1245
+ if (handlers && typeof handlers === 'object') for (const [k, fn] of Object.entries(handlers)) if (typeof fn === 'function') this._writes[k] = fn
1246
+ this._pendingList = []; this._pendingSig = null
1247
+ // THE ROOM AS A STORE — the replayed rows: Map<collection, Map<id, { row, updated, by }>>. Built from the ledger's
1248
+ // `data` entries as they stream in (the same replay the agent's data_query runs server-side), so `rows()` is exactly
1249
+ // what the Space holds — no second copy, nothing to sync.
1250
+ this._rows = new Map()
1251
+ const self = this
1252
+ /** `space.data`: rows(collection) · get(collection, id) · put(collection, row, { id? }) · delete(collection, id) */
1253
+ this.data = {
1254
+ // `_v`: the row's VERSION — the id of the ledger entry that last wrote it. Hand it back as `ifVersion` on a put or
1255
+ // delete and the write is refused (error.code 'row_changed', with the row's current version) if the row changed
1256
+ // since you read it — across devices, since the check runs on the server inside the ledger's own conditional
1257
+ // write. `ifVersion: null` means "only if the row does not exist". (2026-09-26, a builder's move-a-task race.)
1258
+ rows(collection) { const m = self._rows.get(String(collection)); return m ? [...m].map(([id, v]) => ({ id, ...v.row, _updated: v.updated, _by: v.by, _v: v.v || null, ...rowMarks(v) })) : [] },
1259
+ get(collection, id) { const v = self._rows.get(String(collection))?.get(String(id)); return v ? { id: String(id), ...v.row, _updated: v.updated, _by: v.by, _v: v.v || null, ...rowMarks(v) } : null },
1260
+ async put(collection, row, { id, from, ifVersion } = {}) { from = self._who(from); return self._write([{ op: 'put', collection, ...(id ? { id } : {}), row, ...(ifVersion !== undefined ? { ifVersion } : {}) }], from) },
1261
+ async delete(collection, id, { from, ifVersion } = {}) { from = self._who(from); return self._write([{ op: 'del', collection, id, ...(ifVersion !== undefined ? { ifVersion } : {}) }], from) },
1262
+ /** several rows in ONE entry (one line in the room, one ordering point) */
1263
+ async batch(ops, { from } = {}) { return self._write(ops, self._who(from)) },
1264
+ }
1265
+ // The key and the link ARE the admission: readable as space.key / space.shareLink, never enumerable (sdkRedact.js).
1266
+ hide(this, ['_mk', 'shareLink', '_client', '_wb', '_oldKeys'])
1267
+ // IN A VAULT the vault follows a re-keyed room (vault-core.js followKey) and says so: the same events as here
1268
+ try { const v = wb && wb.vault && wb.vault._c; if (v && typeof v.on === 'function') {
1269
+ // removed / pending HOLD the poll as a direct Space's _keyWait does (the vault's own retries stay its own); rekeyed lets go
1270
+ // (sync sweep 11-08 #27: the event was passed on and the page kept polling at full speed)
1271
+ const held = (kind, reason) => { this._keyWait = kind === 'removed' ? 'removed' : (reason || 'pending'); this._pollHeld = true }
1272
+ const known = wb.vault._keyState && wb.vault._keyState.get(this.room)
1273
+ if (known) held(known.kind, known.reason) // said before this Space was opened
1274
+ this._vaultKeyOff = v.on((d) => { if (d && d.ev === 'key' && d.room === this.room && ['rekeyed', 'removed', 'pending'].includes(d.kind)) { this._gateCfg = null; if (d.kind === 'rekeyed') { this.epoch = Number(d.epoch) || 0; this._keyWait = null; this._pollHeld = false; this._etag = null; if (!this._stopped) Promise.resolve().then(() => this._kick()) } else held(d.kind, d.reason); this._emit(d.kind, { room: this.room, ...(d.kind === 'rekeyed' ? { epoch: this.epoch } : {}), ...(d.reason ? { reason: d.reason } : {}) }) } })
1275
+ } } catch { /* */ }
1276
+ if (resume) this._resume(resume) // seed count/etag/messages/rows BEFORE the first poll, so it asks for only what is new
1277
+ if (new.target === Space && this._a2aResume?.length) void this.a2a
1278
+ if (this._hostDriven) this._settleReady(); else this._poll() // start streaming immediately; a fresh Space is empty, a resumed one continues, an opened-with-no-resume one replays its history here
1279
+ }
1280
+
1281
+ // Seed from a prior snapshot() (or the same shape built by hand). Best-effort and defensive on every field
1282
+ // independently — a malformed/partial resume must never throw or block opening, it just resumes whatever parsed
1283
+ // and starts the rest fresh, exactly as if `resume` had not been passed at all.
1284
+ _resume(s) {
1285
+ if (!s || typeof s !== 'object') return
1286
+ if (typeof s.room === 'string' && s.room !== this.room) return // V#8: another room's snapshot (a wrong cache key): its messages, and its count — which skips this room's first entries — are not this room's. A snapshot from before the field has none and is taken as before.
1287
+ try {
1288
+ if (Array.isArray(s.messages)) {
1289
+ this._removedMessages = new Map((Array.isArray(s.removed) ? s.removed : s.messages.filter((e) => e && e.removedByWitbitz)).map((e) => [removedEntryKey(e), { id: e.id, ts: e.ts }]))
1290
+ this._removedSourceMessages = new Map((Array.isArray(s.sourceRemovals) ? s.sourceRemovals : s.messages.filter((e) => e && e.sourceRemoved)).map((e) => [removedEntryKey(e), { id: e.id, ts: e.ts }]))
1291
+ for (let m of s.messages) {
1292
+ if (!m || typeof m !== 'object') continue
1293
+ if (this._removedMessages.has(removedEntryKey(m))) m = removedCopy(m)
1294
+ else if (this._removedSourceMessages.has(removedEntryKey(m))) m = sharedRemovedCopy(m)
1295
+ if (isTitleEntry(m)) { this._noteTitle(m); continue }
1296
+ if (this.safeMedia && this.safeMedia._note(m)) continue // the line that moved Safe media is read (and stays a message: _note → false)
1297
+ this._view.apply([m]) // a live poll's overlap with what you already had is never re-pushed or re-emitted
1298
+ }
1299
+ }
1300
+ if (s.title && typeof s.title === 'object' && cleanTitle(s.title.title)) { const ts = Number(s.title.ts); this._title = { title: cleanTitle(s.title.title), manual: !!s.title.manual, by: String(s.title.by || ''), ts: Number.isFinite(ts) ? ts : -Infinity }; if (Number.isFinite(ts)) this._titleTs = Math.max(this._titleTs, ts) }
1301
+ // the SAFE COPIES the poll kept beside their photos (never messages): a resumed Space polls only what is new, so without them
1302
+ // every older photo had no copy (sync sweep backlog P7)
1303
+ if (Array.isArray(s.safeCopies) && this.safeMedia) for (const e of s.safeCopies.slice(0, 2000)) { if (e && typeof e === 'object' && e.kind === 'safe') this.safeMedia._note(e) }
1304
+ if (Number.isInteger(s.count) && s.count >= 0) this._count = s.count
1305
+ if (typeof s.etag === 'string' && s.etag) this._etag = s.etag
1306
+ if (Array.isArray(s.rows)) {
1307
+ for (const entry of s.rows) {
1308
+ if (!Array.isArray(entry) || entry.length !== 2) continue
1309
+ const [collection, rows] = entry
1310
+ if (typeof collection !== 'string' || !Array.isArray(rows)) continue
1311
+ const m = new Map()
1312
+ for (const r of rows) {
1313
+ if (!Array.isArray(r) || r.length !== 2) continue
1314
+ const [id, v] = r
1315
+ if (typeof id !== 'string' || !v || typeof v !== 'object') continue
1316
+ m.set(id, { row: ownFields(v.row), updated: Number(v.updated) || 0, by: v.by || '', v: typeof v.v === 'string' ? v.v : '', ...stampsOf(v) })
1317
+ }
1318
+ this._rows.set(collection, m)
1319
+ }
1320
+ }
1321
+ } catch { /* resume is a convenience — a bad shape resumes as much as it parsed, never blocks opening */ }
1322
+ }
1323
+
1324
+ /** A resumable, JSON-safe snapshot of everything this Space holds: `{ count, etag, messages, rows }`. Persist it
1325
+ * (e.g. `localStorage.setItem(key, JSON.stringify(space.snapshot()))`) and hand it back as `resume` next time —
1326
+ * to {@link Witbitz#openSpace} or the {@link Space} constructor directly — so reopening this Space continues from
1327
+ * here instead of replaying the whole ledger. Call it whenever suits your app (on `message`/`data`, or on close);
1328
+ * it is a plain read of current state, not a network call. */
1329
+ /** TURN CERTIFICATES (https://witbitz.chat/docs/sdk-keys.md#eat): in a confidential (enclave) room every assistant reply is signed inside
1330
+ * the enclave by an attested key, with the build's measurement, each model call's verified receipt and each tool call.
1331
+ * This checks the whole loaded history on the device (the Nitro attestation, the published audit verdict, every
1332
+ * signature, every reply's text) → { verified, failed: [{ id, reason }], unchecked, before, copies, builds, calls, tools }.
1333
+ * `copies`: a private lane's copies of its Space's replies — the lane's enclave never signed them, so they are counted, not failed.
1334
+ * A regular room has none: { verified: 0, failed: [], before: <its replies> }. */
1335
+ async certificates() {
1336
+ const { verifyRoom } = await import('./turnCerts.js')
1337
+ const r = await verifyRoom(this.messages, { room: this.room })
1338
+ // "REBUILT FROM SOURCE" (the app's row, encSource.js; the owner, 2026-11-06: SDK too): each build the replies came from, looked
1339
+ // up in the build enclave's published releases — the commit it was rebuilt from and its public Rekor entry, or null
1340
+ const builds = [...r.builds.values()]
1341
+ try {
1342
+ const { releaseFor, rekorUrl, RELEASES_LOG } = await import('./encSource.js')
1343
+ const url = new URL(RELEASES_LOG, String(import.meta.url).startsWith('blob:') ? location.href : import.meta.url).href // root-absolute: Witbitz's own log, also from a versioned copy
1344
+ const res = await fetch(url, { cache: 'no-cache' })
1345
+ const text = res && res.ok ? await res.text() : null
1346
+ for (const b of builds) { const rel = text == null ? undefined : releaseFor(text, b && b.pcr16); b.source = rel ? { commit: rel.commit, logIndex: rel.logIndex, rekor: rekorUrl(rel.logIndex) } : (rel === null ? null : undefined) }
1347
+ } catch { /* the log could not be read: `source` stays absent — not "not rebuilt" */ }
1348
+ return { verified: r.verified, failed: r.failed, unchecked: r.unchecked, before: r.before, copies: r.copies, builds, calls: Object.fromEntries(r.calls), tools: Object.fromEntries(r.tools) } // unchecked: the proof is in history this instance has not read — not a failure; copies: a lane's copies of its Space's replies (turnCerts.js)
1349
+ }
1350
+
1351
+ snapshot() {
1352
+ return {
1353
+ room: this.room,
1354
+ ...(pendingOf(this._a2a ? this._a2a._pending : this._a2aResume).length ? { a2a: pendingOf(this._a2a ? this._a2a._pending : this._a2aResume) } : {}),
1355
+ count: this._count,
1356
+ etag: this._etag,
1357
+ messages: this.messages,
1358
+ removed: this._removedMessages ? [...this._removedMessages.values()] : [],
1359
+ sourceRemovals: this._removedSourceMessages ? [...this._removedSourceMessages.values()] : [],
1360
+ safeCopies: this.safeMedia && this.safeMedia._copies ? [...this.safeMedia._copies.values()].flat() : [],
1361
+ rows: [...this._rows].map(([collection, rows]) => [collection, [...rows]]),
1362
+ title: this._title ? { title: this._title.title, manual: this._title.manual, by: this._title.by, ts: Number.isFinite(this._titleTs) ? this._titleTs : null } : null,
1363
+ }
1364
+ }
1365
+
1366
+ /** The room's name, the same on every device and in the Spaces app: the newest rename or generated name in the room's
1367
+ * log, else its shared title doc; null while it has none. 'title' fires when it changes. */
1368
+ get title() { return this._title ? this._title.title : null }
1369
+
1370
+ /** Rename the room for every member and device: appended to the room's log (a rename line in the Spaces app). →
1371
+ * { ok, title } — `ok` false: an older server took it into the room's shared doc only (members see it when they open). */
1372
+ async rename(name, { by } = {}) {
1373
+ by = this._who(by)
1374
+ const title = cleanTitle(name)
1375
+ if (!title) { const e = new Error('witbitz: a room name is 1–80 characters'); e.code = 'bad_request'; throw e }
1376
+ const r = await sendRoomRename({ title: (t, b) => this._client.title(this.room, this._mk, false, { title: t, by: b }), writeDoc: (st, summary) => this._client.state(this.room, this._mk, 'title', st, summary) }, title, by)
1377
+ if (r.refused) { const e = new Error('witbitz: ' + renameRefusalText(r)); e.code = r.refused; if (r.reason) e.reason = r.reason; throw e } // the app's words, its reason kept (renameRefusal.js; sync sweep, 2026-10-11)
1378
+ if (r.unavailable) { const e = new Error('witbitz: the room could not take the new name right now — try again'); e.code = 'unavailable'; if (r.reason) e.reason = r.reason; throw e } // nothing stored (0 / 5xx): never shown as taken
1379
+ this._setTitle({ title, manual: true, by, ts: this._titleTs }) // shown now; its entry arrives with the next poll
1380
+ return { ok: r.took, title }
1381
+ }
1382
+
1383
+ _noteTitle(e) {
1384
+ const t = latestTitle([e]); if (!t || t.ts < this._titleTs) return // an older name read later never wins
1385
+ this._titleTs = t.ts
1386
+ this._setTitle(t)
1387
+ }
1388
+ /** @private THE NAME DOC, AGAIN (sync sweep 10-26 #4; the app's eccc6b28): it was read once, at open — a member who opened the
1389
+ * room before it was named (a joiner still signing in) never got the name. Re-read on the settings' cadence while no title
1390
+ * ENTRY has named the room; never once one has. */
1391
+ _maybeTitleDoc() {
1392
+ if (this._titleTs !== -Infinity || this._titleDocBusy || this._hostDriven || Date.now() - this._titleDocAt < this._titleDocEvery) return
1393
+ this._titleDocBusy = true; this._titleDocAt = Date.now()
1394
+ Promise.resolve(this._client.state(this.room, this._mk, 'title'))
1395
+ .then((d) => { const t = titleFromDoc(d); if (t && this._titleTs === -Infinity) this._setTitle({ title: t.title, manual: t.manual, by: '', ts: -Infinity }) }, () => {})
1396
+ .finally(() => { this._titleDocBusy = false })
1397
+ }
1398
+ _setTitle(t) {
1399
+ const same = this._title && this._title.title === t.title && this._title.manual === !!t.manual
1400
+ this._title = { title: t.title, manual: !!t.manual, by: t.by || '', ts: t.ts }
1401
+ if (!same) this._emit('title', { title: t.title, manual: !!t.manual, by: t.by || '' })
1402
+ }
1403
+
1404
+ async _write(ops, from) {
1405
+ const bad = [...new Set((Array.isArray(ops) ? ops : []).flatMap((o) => (o && o.row && typeof o.row === 'object' ? Object.keys(o.row).filter(isReserved) : [])))]
1406
+ if (bad.length) throw Object.assign(new Error(`witbitz: a row may not set ${bad.join(', ')} — \`id\` is the row's key (pass it as { id }) and \`_\` names are the room's marks`), { code: 'reserved_field' })
1407
+ const r = await this._client.data(this.room, this._mk, ops, from)
1408
+ if (r && r.status === 409 && r.error === 'row_changed') { // a conditional write lost: the caller re-reads and decides
1409
+ const e = new Error('row_changed: ' + (r.conflicts || []).map((c) => `${c.collection}/${c.id} is now ${c.version === null ? 'absent' : c.version}`).join(', '))
1410
+ e.code = 'row_changed'; e.conflicts = r.conflicts || []
1411
+ throw e
1412
+ }
1413
+ if (!r || r.status !== 200) throw refused('data write', r)
1414
+ this._kick() // the entry comes back through the poll → the reducer + the 'data' event, same as every other member
1415
+ return { ok: true, id: r.id, ops: r.ops || [] }
1416
+ }
1417
+
1418
+ // The device half of an `await` action: the turn parked a call for THIS device; run the handler, return the result.
1419
+ async _runDeviceCall(dc) { // deviceCall.js — answered the way the Spaces app answers it
1420
+ return answerDeviceCall(dc, { done: this._devDone, find: (name) => this._reads[name], send: (result) => this._client.toolResult(this.room, this._mk, dc.callId, result) })
1421
+ }
1422
+
1423
+ /** The room master key (base64url). You rarely need it — use {@link shareLink} — but it lets you build custom links. */
1424
+ // KEYLESS: what still needs the room key in the page refuses clearly over a worker-held key,
1425
+ // until its phase moves it behind the client.
1426
+ _needKey(what) {
1427
+ if (!(this._client && this._client.keyless)) return
1428
+ if (this._client.vault) throw sdkError(`witbitz: ${what} is not available in a vault yet`, 'vault_unsupported')
1429
+ throw Object.assign(new Error(`witbitz: ${what} is not available yet over a worker-held key`), { code: 'keyless' })
1430
+ }
1431
+ get key() { return this._client && this._client.keyless ? null : this._mk } // KEYLESS: the key lives in the app's worker, never here
1432
+ /** True for a temporary room (`createSpace({ temporary })`): wiped when idle, never in the account backup. */
1433
+ get temporary() { return String(this.room || '').startsWith('tmp-') }
1434
+ /** True when this room gives every member a private assistant (`createSpace({ lanes: true })`, or a link that says so): the
1435
+ * Spaces app makes its users theirs; in your app, `privateLane()`. */
1436
+ get lanes() { return this._lanesSetting === undefined ? this._lanesHint || LANES_MARK.test(String(this.shareLink || '')) : this._lanesSetting }
1437
+ /** Outside-agent door for a solo verified Space; group and open Spaces refuse on enable/collect. */
1438
+ get a2a() { return this._a2a || (this._a2a = this._wb && this._wb.vault ? new VaultLaneA2A(this, this._wb.vault._c) : new LaneA2A(this)) }
1439
+
1440
+ /** Subscribe to `message` ({ from, text, self, id, ts, widgets? } — `name` carries the same value as `from`, it is
1441
+ * what the sealed ledger calls the field) or `error` (Error). Chainable. */
1442
+ on(event, cb, { replay = true } = {}) {
1443
+ // `{ replay: false }` on 'message': only what arrives AFTER the room's history was read (sdk-roadmap item 6) — for
1444
+ // notifications, analytics and side effects, which must not fire once per old message on every open.
1445
+ const fn = event === 'message' && replay === false ? Object.assign((m) => { if (this._historyRead) cb(m) }, { _orig: cb }) : cb
1446
+ ;(this._subs[event] ||= []).push(fn)
1447
+ if (event === 'a2a') { const agents = this.a2a; Promise.resolve().then(() => agents._flushHeld()) }
1448
+ if ((event === 'proposal' || event === 'proposals') && !this._hostDriven && !this._pendingTimer && !this._stopped) this._pendingTimer = setInterval(() => this._pollPending(), 1500) // proposals arrive on their own channel (pending), not the ledger — polled once someone listens
1449
+ // Returns an UNSUBSCRIBE function. It still chains (`.on(…).on(…)`), because on() returned the space until 2026-10-05.
1450
+ const off = () => { this.off(event, cb); return this }
1451
+ return Object.assign(off, { on: (...a) => this.on(...a), off: (...a) => this.off(...a) })
1452
+ }
1453
+ /** Remove a listener added with on(). The last 'proposal' listener stops the proposals poll that on() started. */
1454
+ off(event, cb) {
1455
+ const l = this._subs[event]; if (!l) return this
1456
+ this._subs[event] = cb === undefined ? [] : l.filter((x) => x !== cb && x._orig !== cb) // no cb: every listener for the event
1457
+ // the proposals poll runs while anyone listens for 'proposal' OR 'proposals' — and on a Lane always (pass 5, V#14: the last
1458
+ // 'proposal' listener stopped a Lane's always-on poll, and the last 'proposals' listener never stopped a Space's)
1459
+ if ((event === 'proposal' || event === 'proposals') && !this._keepsProposals && !(this._subs.proposal || []).length && !(this._subs.proposals || []).length && this._pendingTimer) { clearInterval(this._pendingTimer); this._pendingTimer = null }
1460
+ return this
1461
+ }
1462
+ _emit(event, arg) { if (this._stopped) return; for (const cb of (this._subs[event] || [])) { try { cb(arg) } catch { /* a listener throwing must not break the loop */ } } }
1463
+
1464
+ /** Post a message from a member. The agent decides whether to answer and does so on its OWN turn — the reply (and
1465
+ * any others) arrive via `on('message')`, not as a return value.
1466
+ * While the assistant is still replying to an earlier message, this one is HELD and resent until the room takes it
1467
+ * (up to ~3 min); if it never gets in, the result is `{ ok: false, error: 'busy' }`. A turn longer than ~30 s is cut
1468
+ * at the API front door while the server finishes it: the result then carries `pending: true` and the reply still
1469
+ * arrives on 'message' — do not resend it.
1470
+ * `instructions` (a string, up to 8,000 characters) reaches the assistant as instructions for THIS reply only — today's
1471
+ * date, what is waiting, "answer in Hebrew" — and is NEVER stored, so it is not re-read from old messages every turn.
1472
+ * @param {string} text @param {object} [opts] { from, mode, instructions, images, files } — `from`: the display name to sign this
1473
+ * message as (default 'You'); `images` (≤ 4) / `files` (≤ 2) are { b64 | bytes, mime, name? }, refused over LIMITS at the call */
1474
+ async send(text, { from = 'You', mode, instructions, dictation, images, files, stopKey, showPrompt, replyTo, tools, _onAttempt, _aborted } = {}) {
1475
+ { const f = arguments[1] && arguments[1].from; if (typeof f === 'string' && !arguments[1]._peerPost) this._who(f) } // remember the name this member uses
1476
+ // PER-QUESTION TOOLS on a plain room (docs/visitor-limits.md: a help desk's "search the guide", "which screen am I on"):
1477
+ // the same action shape a Lane takes, offered for THIS question only; an `await` action is answered by this page while
1478
+ // the turn waits (the device call), a `propose` one after the member approves.
1479
+ let toolOpts = {}
1480
+ if (Array.isArray(tools) && tools.length) {
1481
+ const extra = buildActions(tools)
1482
+ if (extra.defs.length > LIMITS.actions) throw limitError(`${extra.defs.length} actions offered to this turn; the limit is ${LIMITS.actions} per turn`)
1483
+ Object.assign(this._writes, extra.handlers); Object.assign(this._reads, extra.reads)
1484
+ if (extra.defs.length) toolOpts = { clientTools: extra.defs, clientGuidance: extra.guidance }
1485
+ }
1486
+ if (this._feed) this._feed.sent() // a new turn: its own words are never held back by the previous answer (turnFeed.js; the app does the same — sync sweep 10-16 #10)
1487
+ const msg = withMedia({ from, text: String(text), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files) // `images` ≤ 4, `files` ≤ 2 — see LIMITS
1488
+ const rt = replyRef(replyTo); if (rt) msg.replyTo = rt // a reply quotes the message it answers, as the app's do
1489
+ await this.safeMedia._prepare(msg) // a Safe media room: its photos' and PDFs' safe copies start now, and go beside it once stored
1490
+ const opts = { ...(await this._turnOpts(mode)), ...toolOpts, ...perTurn(instructions), ...stopOpt(stopKey), ...promptOpt(showPrompt) }
1491
+ const r = await this._turnHeld(() => this._provenTurn(msg, opts), _onAttempt, _aborted)
1492
+ this._kick() // poll faster so the reply lands quickly
1493
+ if (r && r.ok) this._askName()
1494
+ return r
1495
+ }
1496
+
1497
+ // THE ROOM'S NAME FOLLOWS THE CONVERSATION (sdk-rooms.md#room-name: "one is generated after the first exchange"), the way the
1498
+ // Spaces app asks for it (roomTitle.js maybeGenerateTitle): after the first exchange on this handle, and again every
1499
+ // NAME_RECHECK_EVERY sends. The SERVER decides whether a name may be generated (roomName.js mayAutoName — one person in
1500
+ // the room, no name set by hand) and appends it to the log, where it arrives as the 'title' event. It was never asked
1501
+ // from the SDK, so a room used only through it stayed unnamed (sync sweep, 2026-10-10). Fire-and-forget.
1502
+ _askName() {
1503
+ if (this._title && this._title.manual) return
1504
+ // COUNTED IN THE ROOM'S ENTRIES, as the app's roomTitle.js and the server's RETITLE_AFTER count them — not this handle's
1505
+ // own sends: a room others write in was re-asked too rarely (or a busy handle too often) (sync sweep, 10-12)
1506
+ const at = Math.max(Number(this._count) || 0, (this.messages || []).length)
1507
+ if (this._naming || (this._namedAt !== undefined && at - this._namedAt < NAME_RECHECK_EVERY)) return
1508
+ // The recheck window starts on any ANSWER — the server's "not yet / not here" (a 200 with no title: a group, a
1509
+ // direct chat, too few entries) included, as the app's roomTitle.js does. Only a failed ask (thrown, non-200: asleep,
1510
+ // offline) is asked again at the next send.
1511
+ this._naming = true
1512
+ Promise.resolve(this._client.title && this._client.title(this.room, this._mk, !!this._title))
1513
+ .then((r) => { if (r && (r.status === 200 || r.title)) this._namedAt = at })
1514
+ .catch(() => {}).finally(() => { this._naming = false })
1515
+ }
1516
+
1517
+ /** React to a message with an emoji (or take your reaction off): `await space.react(message, '👍')`,
1518
+ * `react(message, '👍', { off: true })`. The reaction is written ON the message — no new entry, no assistant turn —
1519
+ * and arrives on every device as an 'update'. In a verified room it belongs to your signed-in key: nobody else can
1520
+ * take it off. → { ok, reactions } (reactions = { emoji: [names] }), or { ok: false, error }. */
1521
+ async react(message, emoji, { off = false, from } = {}) {
1522
+ from = this._who(from)
1523
+ if (!message || typeof message !== 'object' || message.id == null) throw sdkError('witbitz: react(message, emoji) takes a Message (from "message" or snapshot())', 'invalid_argument')
1524
+ if (typeof emoji !== 'string' || !emoji.trim() || emoji.length > 16) throw sdkError('witbitz: react needs one emoji', 'invalid_argument')
1525
+ // One retry on a transport failure (a throw, or no status), as the app's reaction does (space.js); a refusal is an
1526
+ // answer, never thrown — the result is `{ ok: false, error }` as typed (sync sweep, 2026-10-10).
1527
+ const send = () => this._client.react(this.room, this._mk, { target: entryKeyOf(message), emoji: emoji.trim(), ...(off ? { off: true } : {}) }, from)
1528
+ let r
1529
+ try { r = await send() } catch { r = null }
1530
+ if (!r || !r.status) { await new Promise((ok) => setTimeout(ok, 400)); try { r = await send() } catch (e) { r = { status: 0, error: (e && e.code) || 'unavailable' } } }
1531
+ this._kick()
1532
+ return r && r.status === 200 ? { ok: true, reactions: r.reactions || {} } : { ok: false, error: String((r && r.error) || (r && r.status === 404 ? 'not_found' : 'failed')) }
1533
+ }
1534
+
1535
+ /** Send, and hold THIS turn: `{ status, text, result, on('partial'|'done'), finished, abort() }` (sdkTurn.js).
1536
+ * `finished` resolves `{ status: 'done'|'silent'|'failed'|'aborted'|'timeout', reply, text, proposed, error? }` and
1537
+ * never rejects. Takes send()'s options plus `timeoutMs` (default ~16 min, the app's wait — sdkTurn.js TURN_TIMEOUT_MS; on timeout the turn is stopped). */
1538
+ turn(text, opts = {}) {
1539
+ const t = new Turn(this, text, opts)
1540
+ // close() settles a turn still running (pass 5, V#17: its listeners went silent and `finished` waited for its timeout)
1541
+ if (t.status === 'running') { (this._turns ||= new Set()).add(t); t.finished.then(() => { this._turns.delete(t) }) }
1542
+ return t
1543
+ }
1544
+
1545
+ /** THE ASSISTANT AS A FUNCTION (sdk-assistant.md#run): run this room's assistant once on `input` and get the answer back —
1546
+ * nothing is written to the room (no message, no reply, no card, no notification). The room is the container that
1547
+ * admits and bills it, and its store is readable to the assistant (data_query). The assistant sees `input`, not the
1548
+ * room's conversation, and only the tools that need no approval.
1549
+ * `schema` asks for structured output: `{ field: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' }`
1550
+ * (all required) or a JSON Schema object; the result's `output` then fits it, or the run fails `no_structured_output`.
1551
+ * ⚑ A run must finish within ~30 s on the hosted endpoint: past that the answer cannot be returned and nothing was
1552
+ * kept, so the result is `{ ok: false, error: 'too_slow' }` — shorten the task or lower the effort.
1553
+ * → { ok, text, output?, usage?, prompt?, error?, detail? } — never throws for a refusal. */
1554
+ async run(input, { instructions, schema, images, from = 'app', showPrompt } = {}) {
1555
+ const msg = withMedia({ from, text: String(input) }, images, undefined)
1556
+ await this._freshSettings(); const model = turnModelOf(this._modelPick) // a run answers with the room's model, like its turns
1557
+ let r
1558
+ // a transport failure is an ANSWER, as send()'s is (sync sweep, 2026-10-10: run() threw): { ok: false, error, detail }
1559
+ try { r = await this._provenTurn(msg, { ...(await this._receipt()), ...perTurn(instructions), ...promptOpt(showPrompt), run: true, ...(schema ? { schema } : {}), ...(model ? { model } : {}), ...this._runExtra() }) } catch (e) { return { ok: false, error: String((e && e.code) || 'unavailable'), detail: String((e && e.message) || e).replace(/^witbitz: /, '').slice(0, 200) } }
1560
+ const extra = { ...(r && r.usage ? { usage: r.usage } : {}), ...(r && r.prompt ? { prompt: r.prompt } : {}) }
1561
+ if (r && r.status === 200 && r.run) return { ok: true, text: String(r.reply || ''), ...(r.output !== undefined ? { output: r.output } : {}), ...extra }
1562
+ if (r && r.status === 503 && !r.error) return { ok: false, error: 'too_slow', detail: 'the run did not finish within the endpoint\'s ~30 s; nothing was kept — shorten the task or lower the effort', ...extra }
1563
+ if (r && r.status === 200) return { ok: false, error: 'run_unsupported', detail: 'this server answered a turn, not a run (an older deployment)' }
1564
+ return { ok: false, error: String((r && r.error) || 'failed'), ...(r && r.reason ? { detail: String(r.reason) } : {}), ...(r && r.reply ? { text: String(r.reply) } : {}), ...(r && Number.isFinite(r.retryAfter) ? { retryAfter: r.retryAfter } : {}), ...extra } // rate_limited: retryAfter (s)
1565
+ }
1566
+
1567
+ // ⛔ A MESSAGE SENT WHILE THE ASSISTANT WAS REPLYING WAS LOST, AND send() SAID ok (a builder, 2026-09-29). The server
1568
+ // QUEUES by design (agent/spaceTransport.mjs §QUEUE): while a reply runs it stores nothing new and answers `busy`, and
1569
+ // the CLIENT holds the message and resends when the room frees. The app has done that since the queue shipped
1570
+ // (space.js: 1.5 s × 120 ≈ 180 s — longer than a 150 s turn); the SDK returned the busy answer as the result, a builder
1571
+ // read `ok: true`, and the message was gone. Now: held and resent the same way, and one that could not get in comes
1572
+ // back `ok: false, error: 'busy'` — never ok:true.
1573
+ // ★ And the 30 s cut: the API front door ends a request at ~30 s while the server finishes the turn (150 s) and the
1574
+ // reply arrives on 'message'. That 503 carries none of OUR error codes; it is marked `pending: true` so it does not
1575
+ // read as a failure — and it is NOT resent, because the first message is still being answered.
1576
+ // ⛔ AND EVERY RESULT SAYS ok (2026-10-07; a builder: "user_token_required comes back as { ok: true, error }"). A refusal
1577
+ // from the server is { status, error, message } with NO ok, while a success usually carries the server's own ok:true —
1578
+ // so `r.ok !== false` read every refusal as a success. Now ok is always a boolean, read as turnVerdict reads the turn:
1579
+ // posted, silent and pending are ok; busy, refused, failed and no answer are not; an error field is never ok.
1580
+ async _turnHeld(doTurn, onAttempt, aborted, noHold) { // noHold: a link's ask — the first busy answer comes back (the app's tell_lane says "busy"); sync sweep, 2026-10-10 // aborted(): space.turn()'s abort() — a held message is never resent after it (sync sweep, 2026-10-10) // turnVerdict.js — the hold policy and the reading the Spaces app's send uses
1581
+ const run = doTurn
1582
+ // A transport failure (no network, an enclave that cannot be reached or verified) is an ANSWER too: `send()` does not
1583
+ // throw (sdk.md) — it resolves { ok: false, status: 0, error } (sync sweep, 2026-10-10). Bad arguments still throw
1584
+ // before this point (limit_exceeded and the like), as documented.
1585
+ doTurn = async () => {
1586
+ if (onAttempt) { try { onAttempt() } catch { /* */ } } // space.turn() marks where ITS reply can start
1587
+ try { return await run() } catch (e) { return { status: 0, error: String((e && e.code) || 'unavailable'), detail: String((e && e.message) || e).replace(/^witbitz: /, '').slice(0, 200) } }
1588
+ }
1589
+ let r = await doTurn()
1590
+ for (let i = 0; turnVerdict(r).kind === 'busy' && !noHold; i++) {
1591
+ if (i >= (this._queueMaxTries ?? QUEUE_MAX_TRIES)) return { ...r, ok: false, error: 'busy', detail: 'the assistant was still replying; the message was not stored — send it again' }
1592
+ this._kick()
1593
+ await new Promise((res) => setTimeout(res, this._queueRetryMs ?? QUEUE_RETRY_MS))
1594
+ if (this._stopped) return { ...r, ok: false, error: 'closed', detail: 'the Space was closed while the assistant was busy — the message was not stored' } // V#17: a closed handle does not keep resending for ~3 min
1595
+ if (aborted && aborted()) return { ...r, ok: false, error: 'aborted', detail: 'aborted while the assistant was busy — the message was not stored' }
1596
+ r = await doTurn()
1597
+ }
1598
+ if (turnVerdict(r).kind === 'pending') return { ...r, pending: true, ok: true }
1599
+ return withTurnOk(r)
1600
+ }
1601
+
1602
+ /** How the assistant decides whether to reply, for THIS room and every member of it:
1603
+ * 'auto' — it answers when you are alone with it or address it, and uses a judgement call in a group so it does
1604
+ * not interject while people are talking to each other. Only a builder sets it; the Witbitz app shows it
1605
+ * as Auto but offers only the two below.
1606
+ * 'always' — it answers every message. In a 1:1 room this is usually what you want.
1607
+ * 'ondemand' — it answers only when you @-mention it (`@ai`, or `@` + its name); talking ABOUT it does not count.
1608
+ * A room with no stored mode uses the Witbitz app's default, for every sender: 'ondemand' in a verified room with more
1609
+ * than one person (or one whose people cannot be counted, such as a domain), 'always' otherwise.
1610
+ * Sealed to the room like everything else, so it survives a reload, converges across members, and matches the
1611
+ * setting in the Witbitz app. Pass `mode` to `send()` instead to override it for a single message in a room with no stored mode. */
1612
+ async setReplyMode(mode) {
1613
+ if (!REPLY_MODES.includes(mode)) throw sdkError(`unknown reply mode ${JSON.stringify(mode)} — one of ${REPLY_MODES.join(', ')}`, 'invalid_argument')
1614
+ // A PRIVATE LANE ALWAYS REPLIES (the server: spaceService respondMode — a bridged lane is 'always'; the app hides the chip there):
1615
+ // a mode stored on it changed nothing and was reported back as if it did (sync sweep 2026-11-14 P1, owner: yes)
1616
+ if (this._sharedRoom) throw sdkError('witbitz: a private lane always replies — its reply mode cannot be set', 'lane')
1617
+ const r = await this._client.state(this.room, this._mk, 'agentmode', { mode }, REPLY_MODE_LABEL[mode])
1618
+ if (!r || r.status !== 200) throw refused('setReplyMode', r) // every error carries a code (sync sweep, 2026-10-10)
1619
+ this._mode = mode
1620
+ return { mode }
1621
+ }
1622
+
1623
+ /** The room's reply mode as it stands now: the stored one, else the room's default — the server's rule (roomSettings.js
1624
+ * roomDefaultReplyMode, sync sweep 2026-11-13 #1), counted with the room's sign-in record as the server counts. */
1625
+ /** WHICH TOOLS RUN ON THEIR OWN HERE (docs/approvals-model.md; the same setting as the Witbitz app's ⋯ → Tools). Each tool of the
1626
+ * room's assistant either runs on its own or asks first (a card a person approves); the server enforces it on every turn,
1627
+ * whoever sends the message.
1628
+ * await space.toolRules.get() → { tools: [{ name, about, default, now, rule? }], rules: { name: 'auto'|'ask' } }
1629
+ * await space.toolRules.set(name, 'auto') → runs on its own; 'ask' → asks first; null → back to its default
1630
+ * In a room with admins only an admin may set them (error code `not_admin`). */
1631
+ get toolRules () {
1632
+ const sp = this
1633
+ return {
1634
+ get: async () => {
1635
+ const r = await sp._client.toolRules(sp.room, sp._mk, typeof sp._bridgeOpts === 'function' ? sp._bridgeOpts() : {})
1636
+ if (!r || r.status !== 200) throw refused('toolRules.get', r)
1637
+ return { tools: Array.isArray(r.tools) ? r.tools : [], rules: r.rules || {} }
1638
+ },
1639
+ // ⛔ 10·S#2 / S#4 (pass 10): built on the version it read (`ifV`; a conflict reads again), never on a failed read taken as
1640
+ // "no rules" (that erased every other rule), and it answers the rules it wrote (the write's answer carries none).
1641
+ set: async (name, mode) => {
1642
+ let cur = await sp._client.state(sp.room, sp._mk, TOOLRULES_DOC).catch((e) => ({ status: 0, error: String((e && e.message) || e) }))
1643
+ if (typeof name !== 'string' || !name) throw sdkError('witbitz: toolRules.set needs a tool name', 'invalid_argument')
1644
+ if (mode !== null && !RULE_VALUES.includes(mode)) throw sdkError(`witbitz: a tool rule is 'auto', 'ask' or null (its default) — not ${JSON.stringify(mode)}`, 'invalid_argument')
1645
+ for (let i = 0; i < 4; i++) {
1646
+ if (i) cur = await sp._client.state(sp.room, sp._mk, TOOLRULES_DOC).catch((e) => ({ status: 0, error: String((e && e.message) || e) }))
1647
+ if (!cur || (cur.status && cur.status !== 200)) throw refused('toolRules.set', cur)
1648
+ const rules = { ...rulesFromDoc(cur) }
1649
+ if (mode === null) delete rules[name]; else rules[name] = mode
1650
+ const r = await sp._client.state(sp.room, sp._mk, TOOLRULES_DOC, toolRulesDocOf(rules), 'Tool settings changed', undefined, Number(cur.v) || 0)
1651
+ if (r && r.status === 409) continue
1652
+ if (!r || r.status !== 200) throw refused('toolRules.set', r)
1653
+ return { rules }
1654
+ }
1655
+ throw sdkError('witbitz: toolRules.set — the rules kept changing elsewhere; try again', 'conflict')
1656
+ },
1657
+ }
1658
+ }
1659
+
1660
+ async replyMode() {
1661
+ if (this._sharedRoom) return 'always' // a private lane: the server always replies there
1662
+ await this._modeReady
1663
+ if (this._mode) return this._mode
1664
+ let cfg = null
1665
+ try { cfg = typeof this._client.getConfig === 'function' ? await this._client.getConfig(this.room, this._mk, { plainMark: true }) : null } catch { cfg = null }
1666
+ // a room whose settings could not be read is NOT an unverified room (sync sweep 2026-11-14 #7: it answered 'always'; a verified
1667
+ // group is 'ondemand') — refuse, as the server's answer is unknown. A PLAIN room (no settings at all) reads `{ plain: true }`.
1668
+ if (cfg && cfg.plain === true) cfg = null
1669
+ else if (!cfg || typeof cfg !== 'object' || gatedStub(cfg)) throw sdkError('witbitz: this Space\u2019s settings could not be read just now, so its reply mode is not known — try again', 'config_unavailable')
1670
+ let members = null
1671
+ if (cfg && cfg.admission === 'email') {
1672
+ const seen = await Promise.resolve(this._client.state(this.room, this._mk, 'roster')).then((d) => (d && d.seen) || null).catch(() => null)
1673
+ members = await rosterParticipants(cfg, this.room, { seen }).catch(() => null)
1674
+ }
1675
+ return roomDefaultReplyMode(cfg, members)
1676
+ }
1677
+
1678
+ // The turn options every send builds on. A per-turn mode rides along but does NOT overwrite the room's setting — and the server
1679
+ // lets a STORED mode win over it (roomSettings.js turnReplyMode); otherwise the room's own mode rides along. REFUSES an unknown mode rather than dropping it — this whole feature
1680
+ // exists because an option that is silently discarded reads exactly like one that does not work.
1681
+ /** The signed-in member, in the shape `spaceClient.turn` expects — or null when nobody is signed in.
1682
+ * A GATED room needs this on every turn: without it the server cannot tell who is writing and refuses. An OPEN room
1683
+ * is unaffected, which is why this returns null rather than throwing. */
1684
+ // A TURN WITH YOUR APP'S PROOF (B8): only in a room the server said needs one ('attestation: missing' — learned once, then
1685
+ // every turn there carries it). The proof binds the member's signing key and the room's fresh challenge; a member with no
1686
+ // sign-in signs with a key of this page's own (as the app's attested rooms do). Every other room: exactly as before.
1687
+ async _provenTurn(msg, opts) {
1688
+ const att = this._wb && this._wb._attest
1689
+ const send = async () => {
1690
+ if (!this._needsProof || !att) return this._client.turn(this.room, this._mk, msg, this._identity(), opts)
1691
+ const id = this._identity() || await this._deviceIdentity(msg.from)
1692
+ let f = await att.turnFields(this.room, id.sign.pub)
1693
+ if (!f.attestation) { att.notePoll(this.room, await this._client.pollSealed(this.room, this._mk, null, 0).catch(() => null)); f = await att.turnFields(this.room, id.sign.pub) }
1694
+ const r = await this._client.turn(this.room, this._mk, { ...msg, ...f }, id, opts)
1695
+ att.noteAnswer(r)
1696
+ return r
1697
+ }
1698
+ let r = await send()
1699
+ if (att && !this._needsProof && r && r.status === 403 && /^attestation: missing/.test(String(r.reason || ''))) { this._needsProof = true; r = await send() }
1700
+ return r
1701
+ }
1702
+ async _deviceIdentity(name) {
1703
+ // ONE KEY PER APP on this origin (the review: one key linked a person's attested rooms across apps); a failed generation is
1704
+ // not kept, so the next turn tries again
1705
+ const slot = 'witbitz:attest-sign:' + String((this._wb._attest && this._wb._attest.app) || '')
1706
+ if (!this._wb._attestSign) {
1707
+ let kept = null
1708
+ try { kept = JSON.parse(globalThis.localStorage.getItem(slot) || 'null') } catch { /* none */ }
1709
+ this._wb._attestSign = kept && kept.priv && kept.pub ? Promise.resolve(kept)
1710
+ : genKeypair().then((k) => { const v = { priv: k.priv, pub: k.pub }; try { globalThis.localStorage.setItem(slot, JSON.stringify(v)) } catch { /* memory only */ } return v })
1711
+ .catch((e) => { this._wb._attestSign = null; throw e })
1712
+ }
1713
+ return { attestKey: true, name: String(name || 'You'), sign: await this._wb._attestSign }
1714
+ }
1715
+
1716
+ _identity() {
1717
+ const sess = this._wb && this._wb._session
1718
+ if (!sess || !sess.idToken || !sess.email || !sess.sign || !sess.sign.priv || !sess.sign.pub) return null
1719
+ if (sess.exp && sess.exp <= Date.now()) return null
1720
+ return { email: sess.email, googleIdToken: sess.idToken, sign: sess.sign }
1721
+ }
1722
+
1723
+ // THE ROOM'S SETTINGS (roomSettings.js): read on open, and again before a turn once they are SETTINGS_FRESH_MS old — the
1724
+ // app re-reads them on its poll tick, so a member's change from any client converges here too. Best-effort: a doc that
1725
+ // cannot be read keeps the last value; a room with no docs sends no mode (⇒ 'auto') and no model (⇒ its own).
1726
+ async _readSettings() {
1727
+ try {
1728
+ const [a, b] = await Promise.all([this._client.state(this.room, this._mk, 'agentmode').catch(() => null), this._client.state(this.room, this._mk, 'model').catch(() => null)])
1729
+ const m = modeFromDoc(a); if (m) this._mode = m
1730
+ const p = modelPickFromDoc(b); if (p !== undefined) this._modelPick = p
1731
+ } catch { /* a convenience; never let it break sending */ }
1732
+ this._settingsAt = Date.now()
1733
+ }
1734
+ async _freshSettings() {
1735
+ await this._modeReady
1736
+ if (Date.now() - this._settingsAt > SETTINGS_FRESH_MS) { this._modeReady = this._readSettings(); await Promise.race([this._modeReady, new Promise((r) => setTimeout(r, 1500))]) }
1737
+ }
1738
+ async _turnOpts(mode, extra = {}) {
1739
+ if (mode !== undefined && !REPLY_MODES.includes(mode)) throw sdkError(`unknown reply mode ${JSON.stringify(mode)} — one of ${REPLY_MODES.join(', ')}`, 'invalid_argument')
1740
+ await this._freshSettings()
1741
+ const m = mode !== undefined ? mode : this._mode
1742
+ const model = turnModelOf(this._modelPick) // the room's model pick (the app's model chip) — over its create-time model, as every app turn does
1743
+ return { ...extra, ...(m ? { mode: m } : {}), ...(model ? { model } : {}), ...(await this._receipt()) }
1744
+ }
1745
+ /** @private THE ACCOUNT'S USAGE RECEIPT for a turn here (docs/usage-receipts.md; the owner, 2026-10-23: a builder's app
1746
+ * records the account's usage too): the address the server seals this turn's cost to, from the account's usage key
1747
+ * (wb.account) — none until the account is on. In a vault the vault adds it (it holds the key). */
1748
+ async _receipt() {
1749
+ try {
1750
+ if (this._client && this._client.vault) return {}
1751
+ const k = this._wb && this._wb.account && typeof this._wb.account._usageKey === 'function' ? this._wb.account._usageKey() : null
1752
+ return k ? { receipt: await receiptFor(k, this.room) } : {}
1753
+ } catch { return {} }
1754
+ }
1755
+
1756
+ // ★ WHO DID IT, on the lines other members read (sync sweep, 2026-10-10). approve, deny, rename, react, configure, row
1757
+ // writes and connection grants defaulted to "You" — so the other members read "You renamed…", "You approved…". The
1758
+ // app passes the member's name. Here: the name passed, else the name this member last sent or acted under, else
1759
+ // "A member". (send()'s documented default stays "You".)
1760
+ _who(from) {
1761
+ // 'you' in any case is nobody's name — other members would read it (sync sweep, 2026-10-10)
1762
+ if (typeof from === 'string' && from.trim() && from.trim().toLowerCase() !== 'you') { this._memberName = from.trim().slice(0, 80); return this._memberName }
1763
+ return this._memberName || 'A member'
1764
+ }
1765
+
1766
+ /** What the server ACTUALLY stores for this room — the opaque, sealed ledger. Content-blind at rest, provable: the
1767
+ * server holds ciphertext and is NOT a recipient. Fetch it with no key (reading ciphertext reveals nothing) and show
1768
+ * a user exactly what leaves their device. → { bytes, recipients, sha256, alg, sealed } | null (null before the first
1769
+ * message). `recipients` names who can decrypt — in a normal Space it is `['room']`; the operator is never in it. */
1770
+ async exportFile() {
1771
+ if (this._wb?.vault) return this._wb.vault._c.roomAccount(this.room, 'portable', 'export')
1772
+ const { saveRoomExport } = await import('./sdkExports.js')
1773
+ const session = this._wb?._session
1774
+ return saveRoomExport(this, this._wb?._enc?.rooms.has(this.room) || ENC_MARK.test(this.shareLink || '') ? 'enclave' : 'standard', () => this._wb?._session === session)
1775
+ }
1776
+ async sealedProof() {
1777
+ if (!(this._client && this._client.vault)) this._needKey('sealedProof') // a vault reads the stored boxes for the page (ciphertext only)
1778
+ // A VERIFIED room refuses the keyless read to everyone (a non-member must not get its ciphertext): a member reads the
1779
+ // same stored bytes with the key and computes the proof here (sealedReceipt.js; sync sweep, 2026-10-10).
1780
+ if (this._gated && typeof this._client.exportSealed === 'function') {
1781
+ const x = await this._client.exportSealed(this.room, this._mk).catch(() => null)
1782
+ return x && x.status === 200 ? receiptOf(x.sealed) : null
1783
+ }
1784
+ const r = await this._client.sealed(this.room)
1785
+ // A 404 may be a GATED room opened from a link with no gate marker (its config not read yet): the refusal looks like
1786
+ // "nothing stored" on purpose. Ask as a member before saying there is nothing (sync sweep, 2026-10-10).
1787
+ if (r && r.status === 404 && typeof this._client.exportSealed === 'function') { const x = await this._client.exportSealed(this.room, this._mk).catch(() => null); if (x && x.status === 200 && x.sealed != null) return receiptOf(x.sealed) }
1788
+ if (!r || r.status !== 200) return null
1789
+ return { bytes: r.bytes, recipients: Array.isArray(r.recipients) ? r.recipients : [], sha256: r.sha256, alg: r.alg, sealed: r.sealed }
1790
+ }
1791
+
1792
+ _isEnclave() { return !!(this._wb && this._wb._enc && this._wb._enc.rooms.has(this.room)) }
1793
+ // A STALE ENCLAVE KEY (`bad_mkseal`: the enclave was replaced, so what this page sealed to the old one cannot be opened)
1794
+ // is healed by attesting the new enclave — the app does the same on a read and on a send (space.js). Throttled to once
1795
+ // per 10 s; true when a fresh key is in hand (sync sweep, 2026-10-10: the SDK stayed on the dead key until a reload).
1796
+ // ONE attest at a time, shared by every caller: a send that meets a stale key while the poll is already re-attesting
1797
+ // waits for that attest and is resent, instead of losing its retry to the throttle (sync sweep, 2026-10-10). Within
1798
+ // 10 s of the last attest its answer stands (the key is as fresh as it gets) — never a second attest.
1799
+ /** A VERIFIED ROOM'S MEMBERS, CHANGED IN PLACE (https://witbitz.chat/docs/sdk-people.md#members): the same room, link, history and
1800
+ * lanes, and from now on a NEW key that only the people still on the list receive — each member's device takes it on its next
1801
+ * request ('rekeyed'); a removed member's sees 'removed'. `admission`: { emails, domains?, admins?, owners?, advertise? }, the
1802
+ * list stated in FULL, as fork() takes it. Needs a signed-in owner or admin of an email-gated Space, and each member's invite
1803
+ * key for THIS app (wb.invite, published at their sign-in) — anyone without one is listed in `unreachable` and their device is
1804
+ * told to ask for a fresh link ('pending'): send them `link`. → { inPlace:true, epoch, link, removed, added, unreachable } */
1805
+ async changeMembers(admission = {}) {
1806
+ if (this._sharedRoom) throw Object.assign(new Error("witbitz: a lane is one member's own room — change its Space's members instead"), { code: 'lane' })
1807
+ if (this._wb && this._wb.vault) return this._wb.vault._c.changeMembers(this.room, admission) // the vault holds the key: it asks the person, makes the new key, keeps it
1808
+ return changeMembersInPlace(this, admission)
1809
+ }
1810
+ async resendInvite(recipient) {
1811
+ if (this._wb && this._wb.vault) return this._wb.vault._c.roomAccount(this.room, 'invitations', 'resend', recipient)
1812
+ return resendInvitation(this, recipient)
1813
+ }
1814
+ /** Rotate the key now: the same members, a new key (a lost phone, a link sent to the wrong place) — whoever holds only a copy
1815
+ * of the old key reads nothing written after. → { inPlace:true, rotated:true, epoch, link, unreachable } */
1816
+ async rotateKey() {
1817
+ if (this._sharedRoom) throw Object.assign(new Error("witbitz: a lane is one member's own room — rotate its Space's key instead"), { code: 'lane' })
1818
+ if (this._wb && this._wb.vault) return this._wb.vault._c.rotateKey(this.room)
1819
+ return rotateKeyInPlace(this)
1820
+ }
1821
+ /** @private a call met `stale_key`: take this account's grant once (shared), never more than every 15 s while it waits. */
1822
+ async _adoptKey(args) {
1823
+ if ((args || []).some((x) => typeof x === 'string' && this._oldKeys.has(x)) && this._mk && !this._oldKeys.has(this._mk)) return { mk: this._mk, old: this._oldKeys } // the key was already taken
1824
+ if (this._keyP) return this._keyP
1825
+ if (this._keyWait && Date.now() - (this._keyAt || 0) < 15000) return null
1826
+ // a grant that did not come (grant_unavailable sets no _keyWait) is asked again after 2 s, 4, 8 … up to a minute — not on
1827
+ // every op the room answers stale, ~1/s (the app's l1.js STALE_BACKOFF_MS; sync sweep 11-08 #31)
1828
+ if (this._keyMiss && Date.now() < this._keyMiss.until) return null
1829
+ this._keyAt = Date.now()
1830
+ this._keyP = adoptRoomGrant(this).then((got) => {
1831
+ if (got) { this._keyMiss = null; return { mk: this._mk, old: this._oldKeys } }
1832
+ const n = ((this._keyMiss && this._keyMiss.n) || 0) + 1
1833
+ this._keyMiss = { n, until: Date.now() + GRANT_BACKOFF_MS[Math.min(n, GRANT_BACKOFF_MS.length) - 1] }
1834
+ return null
1835
+ }, () => null).finally(() => { this._keyP = null })
1836
+ return this._keyP
1837
+ }
1838
+ /** @private this room's key changed (a member change or a rotation, here or on another device) */
1839
+ _setKey(mk, epoch, split = null) {
1840
+ this._gateCfg = null
1841
+ if (this._mk && this._mk !== mk) this._oldKeys.add(this._mk)
1842
+ this._mk = mk
1843
+ this.epoch = Number(epoch) || 0
1844
+ this.shareLink = relink(this.shareLink, split || { mk })
1845
+ this._etag = null // a read with the old key can have raced the change and answered the NEW etag: read again from here
1846
+ this._keyWait = null; this._keyMiss = null; this._pollHeld = false
1847
+ try { if (this._wb && this._wb.invite) this._wb.invite._waiting.delete(this) } catch { /* */ }
1848
+ if (this._stream) { try { this._stream.stop() } catch { /* */ } this._stream = null } // the stream opens with the room key
1849
+ // ★ A CLOSED HANDLE (pass 6, K#6): a grant adopted after close() re-added a room the person had just forgotten, with a newer
1850
+ // `at` than its tombstone — it came back on every device. Closed, the backup only follows a room it still holds.
1851
+ const keep = !this._stopped || (() => { try { return this._wb.backup.rooms.some((r) => r.room === this.room) } catch { return false } })()
1852
+ try { if (keep && this._wb && this._wb.backup) this._wb.backup.add(this) } catch { /* the backup must never cost the room */ }
1853
+ this._emit('rekeyed', { room: this.room, epoch: this.epoch, link: this.shareLink })
1854
+ }
1855
+
1856
+ async _reattest() {
1857
+ if (!this._isEnclave()) return false
1858
+ if (this._reattestP) return this._reattestP
1859
+ if (Date.now() - (this._reattestAt || 0) < 10000) return !!this._reattestLast
1860
+ this._reattestAt = Date.now()
1861
+ this._reattestP = Promise.resolve().then(() => this._wb._encAttest(this.room)).then(() => true, () => false)
1862
+ .then((ok) => { this._reattestLast = ok; this._reattestP = null; return ok })
1863
+ return this._reattestP
1864
+ }
1865
+
1866
+ /** RETIRED in 3.0.0 — MEMBERS CHANGE ONLY IN PLACE (the owner, 2026-10-23: "only in place"). A Space never moves to a new
1867
+ * room any more: `space.changeMembers(admission)` changes who is in, in the same room, with a new key only the remaining
1868
+ * members receive (#members). A move an OLDER client made is still followed (`_maybeMoved`). Throws `use_change_members`. */
1869
+ async fork() {
1870
+ throw sdkError('witbitz: a Space no longer moves to a new room — members change in place: space.changeMembers(admission) (https://witbitz.chat/docs/sdk-people.md#members)', 'use_change_members')
1871
+ }
1872
+ /** @private announce this device in the room's guest book under its signing key, once per open: the email gate then
1873
+ * vouches for the address behind it (the server's `seen`), which is how a fork finds the remaining members' devices. */
1874
+ async _announce() {
1875
+ this._announced = true
1876
+ if (this._client && this._client.vault && this._wb && this._wb.vault) { if (!this._sharedRoom) this._wb.vault._c.announce(this.room).catch(() => {}); return } // the vault's device, by its own rule
1877
+ const sess = this._wb && this._wb._session
1878
+ if (this._sharedRoom || !sess || !sess.sign || !sess.sign.pub || typeof this._client.state !== 'function') return
1879
+ try {
1880
+ // Only in an EMAIL-GATED room — the only kind that forks, and where this key already rides the member's own posts.
1881
+ // The SDK signs with ONE key per session, so announcing it in open rooms would let them be linked to each other.
1882
+ // Known without a fetch (the creation, the link's marker, or a gate already read) — every open is not a config read.
1883
+ if (!this._gated) return
1884
+ if (this._wb && !this._wb._inviteP && this._wb.invite.status !== 'enrolled') this._wb._enrollInvite() // a member of a verified room on a restored session: its invite key is published once per client, so a change in place reaches it
1885
+ // TWO MEMBERS ANNOUNCING AT ONCE: each writes the book it read, and the last write wins — read it back, and announce again
1886
+ // while this row (or the gate's record of it, roomRoster.unseenIn) is missing; a member change in place names members by it
1887
+ const self = selfRow({ signPub: sess.sign.pub })
1888
+ for (let i = 0; i < 3; i++) {
1889
+ const r = await this._client.state(this.room, this._mk, ROSTER_DOC)
1890
+ if (!r || r.status !== 200) return
1891
+ const { roster, changed } = ensureSelf(r.state, self)
1892
+ if (!changed && !unseenIn(r.seen, self.id) && !entriesMissing(r.seen, self.id, this.room)) return // entries: one more announce per page, never retried
1893
+ if (this._stopped || this._wb._session !== sess) return
1894
+ const written = await this._client.state(this.room, this._mk, ROSTER_DOC, { people: roster }, '', 'member', r.v || 0)
1895
+ if (written?.status === 409) continue
1896
+ if (written?.status !== 200) return
1897
+ announcedIn(this.room, self.id)
1898
+ await new Promise((res) => setTimeout(res, 200 + Math.floor(Math.random() * 600)))
1899
+ }
1900
+ } catch { /* the guest book is best-effort; it never costs the room */ }
1901
+ }
1902
+
1903
+ /** @private a fork notice arrived: follow it only if the gate stamped it (and, in a room with admins, an admin posted
1904
+ * it), its boxes match its signed hash, and one box opens with THIS device's key → emit `moved`. */
1905
+ async _maybeMoved(e) {
1906
+ try {
1907
+ if (this._client && this._client.vault && this._wb && this._wb.vault) { // the vault reads the notice from the room and judges it
1908
+ const r = await this._wb.vault._c.follow(this.room, e.id)
1909
+ if (r && r.refused) this._emit('moveRefused', { from: this.room, at: e.ts, reason: r.refused, ...(r.code ? { code: r.code } : {}) }) // code: vault_unsupported for a confidential move in a vault (sdk.md)
1910
+ else if (r && r.room) this._emit('moved', { room: r.room, link: null, from: this.room, at: e.ts }) // open it with wb.vault.openRoom(room)
1911
+ return
1912
+ }
1913
+ const sess = this._wb && this._wb._session
1914
+ if (!sess || !sess.sign || !sess.sign.priv) return
1915
+ const cfg = await this._gateConfig()
1916
+ const v = await judgeMove(e, { cfg, signPriv: sess.sign.priv, room: this.room, forkAuthority: (cfg && cfg.forkAuthority) || null }) // emailFork.js — the app's rule, its forkAuthority included (a room with no admins follows only a move its creator key signed)
1917
+ if (!v) return
1918
+ if (v.refuse) { this._emit('moveRefused', { from: this.room, at: e.ts, reason: v.refuse }); return }
1919
+ const o = v.follow
1920
+ // A CONFIDENTIAL move: the new room's ops (its config read included) go to the enclave — adopt it first, under the
1921
+ // acceptance block its own sealed config carries.
1922
+ if (this._wb && (this._isEnclave() || ENC_MARK.test(String(o.link || '')))) { await this._wb._encAdopt(o.room) }
1923
+ if (v.needsGovCheck && !(await this._newRoomKeepsGov(o.room, o.mk, e.gov))) { this._emit('moveRefused', { from: this.room, room: o.room, at: e.ts, reason: 'the new room\'s owners or admins are not what the move declared' }); return }
1924
+ this._emit('moved', { room: o.room, link: o.link, from: this.room, at: e.ts })
1925
+ } catch { /* a notice that cannot be checked is not followed */ }
1926
+ }
1927
+
1928
+ /** @private OWNERS: does the NEW room's sealed config name exactly the owners and admins the move declared, and admit
1929
+ * each of them? Read with the new room's key on this device. Anything unreadable is a no. */
1930
+ async _newRoomKeepsGov(room, mk, gov) {
1931
+ try { return await newRoomKeepsGov(await this._client.getConfig(room, mk), gov, room) } catch { return false }
1932
+ }
1933
+
1934
+ /** READ THE GATE (2026-10-02). Who this Space admits, from its own sealed config — the list the server enforces, read
1935
+ * with this Space's key on this device. → `{ gated: false }` for an open room, else `{ gated: true, emails, domains,
1936
+ * usernames, hidden }`: `emails`/`usernames` are the ADVERTISED entries (see `admission.advertise` on createSpace),
1937
+ * `hidden` counts the entries stored only as a room-salted hash, which no member can read back — check one with
1938
+ * {@link Space#admits}. Throws `config_unavailable` when the config cannot be read, never a guess. */
1939
+ /** A direct chat's OTHER person, read from its sealed allow-list (only the two of you can post — the gate checks it):
1940
+ * `{ email }` (or `{ username }` for an older room), or null when this is not a direct chat you are in. Call the chat by
1941
+ * them, as the Spaces app does; nobody renames a direct chat (`rename()` → `direct_chat`). Needs a signed-in session. */
1942
+ async directPeer() {
1943
+ const sess = this._wb && this._wb._session
1944
+ let cfg
1945
+ try { cfg = await this._gateConfig() } catch (e) { if (e && e.code === 'sign_in_required') throw e; return null }
1946
+ const me = this._wb && this._wb.vault ? ((await this._wb.vault.whoami()) || {}).email : sess && sess.email // in a vault, its signed-in member
1947
+ return isDirect(cfg) && cfg.admission === 'email' ? directPeer(cfg, me) : null
1948
+ }
1949
+
1950
+ _invitationMatches(cfg, seen) {
1951
+ return privateInvitationMatches(cfg, this.room, seen, {
1952
+ resolveUsers: async users => ({ resolved: await Promise.all(users.map(async username => {
1953
+ const found = await this._client.userResolve?.(username).catch(() => null)
1954
+ return { username, ...(found?.handle ? { handle: found.handle } : {}) }
1955
+ })) }),
1956
+ userTag: (name, room) => this._client.userTag(name, room),
1957
+ })
1958
+ }
1959
+
1960
+ async _roomHistory() {
1961
+ const poll = this._client.pollSealed || this._client.poll
1962
+ if (!poll) return { entries: [], incomplete: true }
1963
+ return readAllPages(since => poll.call(this._client, this.room, this._mk, undefined, since))
1964
+ }
1965
+
1966
+ async usage() {
1967
+ const [history, title] = await Promise.all([
1968
+ this._roomHistory(), this._client.state(this.room, this._mk, 'title').catch(() => null),
1969
+ ])
1970
+ const entries = history.entries || [], titles = title?.state?.usage || []
1971
+ const records = roomUsageRecords(entries, titles)
1972
+ return {
1973
+ records: records.map(e => ({ at: e.ts, kind: e.title ? 'title' : 'reply', usage: e.usage })),
1974
+ summary: summarizeUsage(entries, { titles }), csv: usageCsv(records),
1975
+ incomplete: !!history.incomplete || title?.status !== 200,
1976
+ }
1977
+ }
1978
+
1979
+ async roster() {
1980
+ if (this._wb?.vault?._c?.roomAccount) {
1981
+ try { return await this._wb.vault._c.roomAccount(this.room, 'roster', 'list') }
1982
+ catch (err) { if (err?.code !== 'vault_refused') throw err }
1983
+ }
1984
+ const cfg = await this._gateConfig({ plainMark: true })
1985
+ const book = await this._client.state(this.room, this._mk, ROSTER_DOC)
1986
+ if (book?.status !== 200) throw sdkError('witbitz: the room roster could not be read', 'roster_unavailable')
1987
+ const seen = Object.fromEntries(Object.entries(book.seen || {}).filter(([, p]) => p && !p.left))
1988
+ const claims = (Array.isArray(book.state) ? book.state : book.state?.people || []).some(row => row?.verified)
1989
+ const history = claims || cfg.admission === 'email' ? await this._roomHistory() : { entries: [] }
1990
+ const entries = history.entries || []
1991
+ const attested = new Set(deriveRoster(entries, null).map(p => jkey(p.spk)))
1992
+ const posters = verifiedPosters(entries, book.seen || {})
1993
+ const rows = listRoster(book.state, { attested: row => !!seen[row.id] || attested.has(row.id) })
1994
+ if (cfg.admission !== 'email') return {
1995
+ gated: false, incomplete: !!history.incomplete, members: rows.map(row => ({ label: row.label, verified: row.verified })), pending: [], domains: [], unopenedPrivateInvites: 0,
1996
+ }
1997
+ const onList = await stillOnList(cfg, this.room, [...Object.values(seen), ...posters])
1998
+ const { hiddenUnseen, seenHandles } = await this._invitationMatches(cfg, [...Object.values(seen), ...posters])
1999
+ const { items, hidden } = membersView({
2000
+ allow: cfg.allow, rows: rows.filter(row => seen[row.id]), seenPerson: id => seen[id],
2001
+ posters: [...Object.values(seen), ...posters], hiddenUnseen, seenHandles, onList,
2002
+ })
2003
+ const person = ({ label, address, user }) => ({ label, ...(address ? { address } : {}), ...(user ? { username: user } : {}) })
2004
+ return {
2005
+ gated: true, incomplete: !!history.incomplete, members: items.filter(i => i.tag === 'signed in').map(i => ({ ...person(i), verified: true })),
2006
+ pending: items.filter(i => i.tag === 'not yet opened').map(person),
2007
+ domains: (cfg.allow?.domains || []).filter(d => typeof d === 'string'), unopenedPrivateInvites: hidden,
2008
+ }
2009
+ }
2010
+
2011
+ async admission() {
2012
+ if (this._wb?.vault?._c?.roomAccount) {
2013
+ try { return await this._wb.vault._c.roomAccount(this.room, 'roster', 'admission') }
2014
+ catch (err) { if (err?.code !== 'vault_refused') throw err }
2015
+ }
2016
+ const cfg = await this._gateConfig({ plainMark: true })
2017
+ const lanesOn = cfg.lanes === true ? { lanes: true } : {} // a Space whose members get private lanes (createSpace({ lanes }), the app's option) — sealed
2018
+ if (cfg.admission !== 'email') return { gated: false, ...(cfg.lane === true ? { lane: true } : {}), ...lanesOn }
2019
+ const a = cfg.allow || {}
2020
+ const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [])
2021
+ const legacy = Array.isArray(a.users) ? a.users.length : 0 // a legacy room's @username entries: counted as hidden — no username is read back (2026-10-11)
2022
+ const admins = cfg.admins && Array.isArray(cfg.admins.emails) ? cfg.admins.emails.filter((x) => typeof x === 'string') : []
2023
+ const owners = cfg.owners && Array.isArray(cfg.owners.emails) ? cfg.owners.emails.filter((x) => typeof x === 'string') : []
2024
+ let unopenedPrivateInvites = 0
2025
+ if (list(a.mh).length) {
2026
+ const book = await Promise.resolve().then(() => this._client.state(this.room, this._mk, ROSTER_DOC)).catch(() => null)
2027
+ unopenedPrivateInvites = undefined
2028
+ if (book?.status === 200) {
2029
+ const history = await this._roomHistory()
2030
+ if (!history.incomplete) {
2031
+ const seen = book.seen || {}
2032
+ const people = [...Object.values(seen).filter(p => p && !p.left), ...verifiedPosters(history.entries, seen)]
2033
+ const matches = await this._invitationMatches(cfg, people)
2034
+ unopenedPrivateInvites = matches.hiddenUnseen ?? list(a.mh).length
2035
+ }
2036
+ }
2037
+ }
2038
+ return { ...(unopenedPrivateInvites !== undefined ? { unopenedPrivateInvites } : {}), gated: true, emails: list(a.emails), domains: list(a.domains), hidden: list(a.mh).length + legacy, admins, owners, ...(cfg.lane === true || cfg.bridge ? { lane: true } : {}), ...lanesOn } // lane: a private lane, not a Space (laneConfig.js)
2039
+ }
2040
+
2041
+ /** Is `email` one of this room's ADMINS? The room enforces it (2026-10-02): with admins, only they change the
2042
+ * assistant, write a collection declared `write: 'admins'`, or approve a card that does either or calls a
2043
+ * connection. A non-admin's attempt is refused
2044
+ * with `code: 'not_admin'`. A room without admins has none (every member may do all of it, as before). */
2045
+ async isAdmin(email) {
2046
+ const e = String(email || '').trim().toLowerCase()
2047
+ const cfg = await this._gateConfig({ plainMark: true })
2048
+ const has = (o) => !!(o && Array.isArray(o.emails) && o.emails.some((x) => String(x).trim().toLowerCase() === e))
2049
+ return has(cfg.admins) || has(cfg.owners) // an owner is an admin
2050
+ }
2051
+
2052
+ /** Is `email` one of this room's OWNERS (a level above admins, enforced by the room)? An owner can do all an admin can,
2053
+ * and only an owner can change the owners or lower or remove an admin when the room is moved ({@link Space#fork}). */
2054
+ async isOwner(email) {
2055
+ const e = String(email || '').trim().toLowerCase()
2056
+ const cfg = await this._gateConfig({ plainMark: true })
2057
+ return !!(cfg.owners && Array.isArray(cfg.owners.emails) && cfg.owners.emails.some((x) => String(x).trim().toLowerCase() === e))
2058
+ }
2059
+
2060
+ /** Does this Space's gate admit `email`? Checked on this device against the sealed list: an advertised address, a
2061
+ * hidden (hashed) one, or the address's domain. An open room admits everyone. ⚑ A member admitted by @username alone
2062
+ * cannot be checked here — that match needs the server's key — so it reads `false` for them. */
2063
+ async admits(email) {
2064
+ const e = String(email || '').normalize('NFKC').trim().toLowerCase()
2065
+ const at = e.indexOf('@')
2066
+ if (at < 1 || at === e.length - 1) throw sdkError(`witbitz: "${email}" is not an email address`, 'invalid_argument')
2067
+ const cfg = await this._gateConfig({ plainMark: true })
2068
+ if (cfg.admission !== 'email') return true
2069
+ const a = cfg.allow || {}
2070
+ if ((Array.isArray(a.emails) ? a.emails : []).some((x) => String(x).trim().toLowerCase() === e)) return true
2071
+ if (Array.isArray(a.mh) && a.mh.length && a.mh.includes(await memberHash(e, this.room))) return true
2072
+ const domain = e.slice(at + 1)
2073
+ return (Array.isArray(a.domains) ? a.domains : []).some((d) => String(d).trim().toLowerCase().replace(/^@/, '') === domain)
2074
+ }
2075
+
2076
+ /** Who is signed in here — the vault's member in a vault, else this page's session — or ''. Never throws. */
2077
+ async _signedInEmail() {
2078
+ try {
2079
+ if (this._wb && this._wb.vault) { const w = await this._wb.vault.whoami(); return w && w.email ? String(w.email) : '' }
2080
+ const s = this._wb && this._wb._session; return s && s.email ? String(s.email) : ''
2081
+ } catch { return '' }
2082
+ }
2083
+
2084
+ async _gateConfig({ fresh = false, plainMark = false } = {}) {
2085
+ const owner = this._wb?.vault ? this._wb._vaultGeneration : this._wb?._session
2086
+ const key = this._mk, epoch = this.epoch
2087
+ if (!fresh && this._gateCfg && this._gateOwner === owner) return this._gateCfg
2088
+ const cfg = typeof this._client.getConfig === 'function' ? await this._client.getConfig(this.room, this._mk, plainMark ? { plainMark: true } : undefined) : null
2089
+ if (key !== this._mk || epoch !== this.epoch || owner !== (this._wb?.vault ? this._wb._vaultGeneration : this._wb?._session)) throw sdkError('the room or account changed during the read', 'account_changed')
2090
+ if (cfg && typeof cfg.lanes === 'boolean') this._lanesSetting = cfg.lanes
2091
+ if (!cfg || typeof cfg !== 'object') { const err = new Error("witbitz: could not read this Space's gate (its sealed config did not load) — try again"); err.code = 'config_unavailable'; throw err }
2092
+ // A gated room answers a caller who has not signed in with only { admission: 'email', gated: true } — not the config.
2093
+ // That stub is never cached, so the read after sign-in gets the real one.
2094
+ if (cfg.gated === true && !cfg.allow) { if (!this._gated) { this._gated = true; if (this._announced) this._announce() } const me = await this._signedInEmail(); const e = new Error(me ? `witbitz: this Space is email-gated and ${me} is not on its list — only its members read its gate` : 'witbitz: this Space is email-gated — sign in (' + signInHow(this._wb) + ') to read its gate'); e.code = 'sign_in_required'; throw e } // signed in but not admitted: the server answers the same stub, and "sign in" was wrong there (sync sweep 11-14 P7: a signed-in vault)
2095
+ this._gateOwner = owner
2096
+ this._gateCfg = cfg // the gate is sealed at creation and never changes in place (membership change = a new room)
2097
+ if (cfg.admission === 'email' && !this._gated) { this._gated = true; if (this._announced) this._announce() } // a room that predates the link marker announces once its gate is read
2098
+ return cfg
2099
+ }
2100
+
2101
+ /** A FILE OF THIS SPACE BY ITS NAME (the app's file links, fileLinks.js; the owner, 2026-11-06: SDK too). The assistant names the
2102
+ * room's attachments by name — `[Plan.pdf](Plan.pdf)` — so a link in its reply can be opened: → `{ message, att }`, the newest
2103
+ * message carrying a file or image of that name (case-insensitive), or null. Read its bytes with `space.attachment(att)`.
2104
+ * In a lane, a copy of the Space's line is not one of the lane's files (as in the app). */
2105
+ fileNamed(name) {
2106
+ const want = String(name || '').trim().toLowerCase()
2107
+ if (!want) return null
2108
+ for (let i = this.messages.length - 1; i >= 0; i--) {
2109
+ const m = this.messages[i]
2110
+ if (laneCopy(m)) continue // a lane's COPY of its Space's line is not a file of this room: the app links none (its copy is rendered apart, fileLinks.js) — sync sweep 11-08
2111
+ for (const att of [...(Array.isArray(m && m.files) ? m.files : []), ...(Array.isArray(m && m.images) ? m.images : [])]) {
2112
+ if (att && typeof att.name === 'string' && att.name.trim().toLowerCase() === want) return { message: m, att }
2113
+ }
2114
+ }
2115
+ return null
2116
+ }
2117
+
2118
+ /** Did THIS signed-in session send `message`? (the app's own-message marking; the owner, 2026-11-06: SDK too). True for a
2119
+ * message the server verified as signed with this session's key — never by a typed name. A message from before a
2120
+ * `refreshSession()` (a new key) or from another device of yours reads false. */
2121
+ isMine(message) {
2122
+ const m = message
2123
+ if (!m || m.verified !== true) return false
2124
+ const id = (k) => (k && k.kty && k.crv && k.x != null && k.y != null ? `${k.kty}:${k.crv}:${k.x}:${k.y}` : null) // = agentIdentity.keyIdOf
2125
+ // IN A VAULT the session is the vault's: it hands the page its key's PUBLIC id (welcome, whoami, its events) — this read
2126
+ // false there for every message (sweep 11-07 #9)
2127
+ const v = this._wb && this._wb.vault
2128
+ let mine = null
2129
+ if (v) { const i = v.info || {}; mine = i.signedIn !== false && typeof i.keyId === 'string' && i.keyId ? i.keyId : null }
2130
+ else { const sess = this._wb && this._wb._session; mine = sess && sess.sign ? id(sess.sign.pub) : null }
2131
+ return !!mine && id(m.vspk || m.spk) === mine
2132
+ }
2133
+
2134
+ /** WHO WROTE `message`, as Block knows a person (the Spaces app's blocks.js; docs/report-and-block.md §4) → `{ email?, user?,
2135
+ * room?, sid? }`, or null when nothing proves it (a typed name, the assistant, an outside agent's relayed line): the verified
2136
+ * email and @username the server stamped, and the key that signed it in this Space. A lane's copy of its Space's line names
2137
+ * the Space's writer (`by`, the mirror's). Pass it to `wb.account.blocks.block()` / `.has()`. */
2138
+ blockIdentity(message) {
2139
+ const m = message
2140
+ if (!m || typeof m !== 'object') return null
2141
+ const b = /^sh:/.test(String(m.id || '')) && m.by && typeof m.by === 'object' ? m.by : (mirrorBy(this.room, m).by || null)
2142
+ if (!b) return null
2143
+ const out = { ...(b.email ? { email: String(b.email).toLowerCase() } : {}), ...(b.user ? { user: String(b.user).replace(/^@/, '').toLowerCase() } : {}), ...(b.room && b.sid ? { room: String(b.room), sid: String(b.sid) } : {}) }
2144
+ return Object.keys(out).length ? out : null
2145
+ }
2146
+
2147
+ /** REPORT a message, a person or the assistant's answer to Witbitz (App Store rule 1.2; sdk-people.md#report) — what the
2148
+ * Spaces app's Report sends: the message and, with `context: true`, the 5 before it. Needs a signed-in session; the room
2149
+ * checks membership first. `reason`: one of `Space.REPORT_REASONS`. → `{ ok: true, id }` | `{ ok: false, error, detail? }`
2150
+ * (`not_member`, `sign_in`, `budget` — 20 a day). Throws `invalid_argument`, `sign_in_required`; in a vault `vault_unsupported`. */
2151
+ async report(message, { reason, note, context = false } = {}) { return fileReport(this, message, { reason, note, context }) }
2152
+ static get REPORT_REASONS() { return REPORT_REASONS }
2153
+
2154
+ /** THIS SPACE'S ATTESTED LINE (the app's ⋯ → This Space): does it take only a page proved to be one named app (an attested
2155
+ * app, B8 — `createSpace({ owner })`, or the Witbitz apps' own rooms)? Read from the room's public policy. →
2156
+ * `{ required, confidential }`. A read that fails throws `policy_unreadable` — never "no". In a vault: `vault_unsupported`. */
2157
+ async attested() {
2158
+ if (this._client && this._client.vault) throw sdkError('witbitz: attested() is not available in a vault yet', 'vault_unsupported')
2159
+ if (!this._client || typeof this._client.attestedRoom !== 'function') throw sdkError('witbitz: this Space cannot read its policy here', 'policy_unreadable')
2160
+ let required
2161
+ try { required = !!(await this._client.attestedRoom(this.room, this._mk)) } catch (e) { throw sdkError('witbitz: whether this Space requires an attested app could not be read — try again (' + String((e && e.message) || e).slice(0, 80) + ')', 'policy_unreadable') }
2162
+ return { required, confidential: this._isEnclave() }
2163
+ }
2164
+
2165
+ /** The bytes of an attachment on a message (`message.images[i]` / `message.files[i]`) → `{ b64, mime, name? }`. The
2166
+ * room stores attachments OUT OF LINE, sealed under its key, so a message carries a reference; this fetches the
2167
+ * sealed parts and opens them here. Throws `attachment_unavailable` if a part is missing or will not open. */
2168
+ async importChat(url) {
2169
+ if (typeof url !== 'string' || !url.trim()) throw sdkError('witbitz: importChat() needs a shared chat URL', 'invalid_argument')
2170
+ const r = await this._client.importChat(this.room, this._mk, url.trim())
2171
+ if (!r || r.status !== 200) throw refused('importChat', r)
2172
+ this._kick()
2173
+ return { imported: r.imported, title: r.title, entries: r.entries }
2174
+ }
2175
+
2176
+ async importWhatsApp(text) {
2177
+ if (typeof text !== 'string' || !text.trim()) throw sdkError('witbitz: importWhatsApp() needs the exported chat text', 'invalid_argument')
2178
+ const r = await this._client.importWhatsApp(this.room, this._mk, text)
2179
+ if (!r || r.status !== 200) throw refused('importWhatsApp', r)
2180
+ this._kick()
2181
+ return { imported: r.imported, title: r.title, entries: r.entries }
2182
+ }
2183
+
2184
+ async attachment(att) {
2185
+ if (!att || typeof att !== 'object') throw sdkError('witbitz: attachment() takes an entry from message.images or message.files', 'invalid_argument')
2186
+ if (typeof att.b64 === 'string' && att.b64) return { b64: att.b64, mime: att.mime || 'application/octet-stream', ...(att.name ? { name: att.name } : {}) }
2187
+ const refs = Array.isArray(att.parts) && att.parts.length ? att.parts : (att.ref ? [att.ref] : [])
2188
+ if (!refs.length) throw sdkError('witbitz: that attachment has neither bytes nor a reference', 'invalid_argument')
2189
+ const got = await Promise.all(refs.map((ref) => this._client.blob(this.room, this._mk, ref)))
2190
+ if (got.some((r) => !r || r.status !== 200 || typeof r.b64 !== 'string')) { const err = new Error('witbitz: the attachment could not be fetched or opened'); err.code = 'attachment_unavailable'; throw err }
2191
+ return { b64: got.map((r) => r.b64).join(''), mime: att.mime || got[0].mime || 'application/octet-stream', ...(att.name ? { name: att.name } : {}) }
2192
+ }
2193
+
2194
+ /** Attach a PRIVATE assistant lane to this shared Space, for the current member. The lane is the member's OWN room:
2195
+ * its agent sees this shared room's messages (labeled) — and queries its rows, read-only, when it declares `data` — and thinks/drafts with the member privately, but can post
2196
+ * into the shared room only through a crossing the member APPROVES. Give it `actions` and it can also propose
2197
+ * effectful client-side actions the member approves before they run (the agent never runs anything unilaterally).
2198
+ * @param {object} [opts] { agent:{name,instructions,model?}, actions?:[{name,description,input?,run(args)}] } → a {@link Lane} */
2199
+ async privateLane({ agent = {}, actions = [], tools, immediateTools, model, data, admission, tier, mirror = false, platformTools, framing, dataWrites } = {}) {
2200
+ if (this.temporary) throw sdkError('witbitz: a temporary room has no private lane — the lane is a durable room, and its copies of the room would outlive the wipe', 'temporary_room') // as the app (roomSync.js ensureOwnLane; sync sweep 2026-10-27 #3)
2201
+ // A LANE HAS NO LANE (sweep P1): a lane of a lane was minted — a third room carrying the member's thinking one hop further,
2202
+ // which nothing in the app makes and nothing reads back
2203
+ if (this._client && this._client.vault) return this._vaultLane({ agent, actions, tools, immediateTools, model, data, admission, tier, mirror, platformTools, framing, dataWrites }) // the vault refuses a lane of a lane itself (vault-core createLane)
2204
+ if (this._sharedRoom || wasLaneRoom(this._wb, this.room)) throw sdkError('witbitz: a private lane has no lane of its own — ask from its Space', 'lane_of_lane') // …nor a room that WAS one, opened as a Space (openSpace(laneLink)) — as the app (roomSync.js isLaneRoom; sync sweep 11-11 #3)
2205
+ await assertNotKept(this)
2206
+ this._needKey('privateLane')
2207
+ let gate = normAdmission(admission) // a lane can be gated too — it is the member's OWN room
2208
+ const wb = this._wb
2209
+ if (wb) await wb._checkModel(model || agent.model)
2210
+ const asked = tierIsEnclave(tier) // FIRST, so an unknown tier still throws and can never be read as "inherit"
2211
+ // ★ A LANE OF A CONFIDENTIAL SPACE IS CONFIDENTIAL, without being asked. The tier used to come only from this
2212
+ // argument, so a lane attached to an enclave-tier Space was an ORDINARY room on the standard relay unless the tier
2213
+ // was passed again — and it failed silently, because the lane works either way. That is a DOWNGRADE, not a choice:
2214
+ // a lane holds the member's private thinking, drafts and research, often more sensitive than the shared room
2215
+ // everyone present can already read. ADMISSION inherits too, without the members (laneInherits, below): a verified
2216
+ // Space's lane admits its one member.
2217
+ // An explicit `tier:'standard'` here REFUSES rather than downgrading, for the same reason an unknown tier throws.
2218
+ const sharedIsEnclave = !!(wb && wb._enc && wb._enc.rooms.has(this.room))
2219
+ if (sharedIsEnclave && !asked && tier !== undefined && tier !== null) {
2220
+ throw Object.assign(new Error("witbitz: this Space is confidential, so its private lane is too — a lane holds the member's own drafts, and silently downgrading it would be worse than refusing. Omit `tier` to inherit, or attach the lane to a standard Space."), { code: 'tier_mismatch' })
2221
+ }
2222
+ const enc = asked || sharedIsEnclave
2223
+ if (enc && !wb) throw Object.assign(new Error('witbitz: an enclave-tier lane needs the Witbitz client that opened this Space'), { code: 'no_client' })
2224
+ // ★ WHAT A LANE TAKES FROM ITS SPACE: everything but the members (laneConfig.js laneInherits — the app's rule; the owner,
2225
+ // 10-15). The shared room's tools unless you name the lane's own, and a VERIFIED Space's gate narrowed to the signed-in
2226
+ // member — an SDK lane of a verified Space was an OPEN room (sync sweep, 10-16 #1). Never weaker than its Space: no
2227
+ // sign-in to admit, or an `admission` that would open it, is refused by name.
2228
+ let sharedCfg = null, cfgRead = typeof this._client.getConfig !== 'function' // a client that cannot read settings: as before
2229
+ // …except for a Space known to be verified or confidential: its lane must be as strict as it, and a client that cannot read
2230
+ // its settings cannot make it so — refused, never an open lane (sweep 11-04 P1)
2231
+ if (cfgRead && (this._gated || sharedIsEnclave)) throw sdkError("witbitz: this client cannot read the Space's settings, so a private lane of a verified or confidential Space cannot be made as strict as it", 'lane_wait')
2232
+ // A SLEEPING CONFIDENTIAL SPACE is woken first, as the vault does (vault-core createLane): asleep, its settings read fails, and
2233
+ // a failed read now waits — so privateLane() on one always ended in lane_wait (sync sweep 11-04 #4)
2234
+ if (!cfgRead && sharedIsEnclave && wb && typeof wb._encWake === 'function') { try { await wb._encWake(this.room, { tries: 8 }) } catch { /* the read below says what is wrong */ } }
2235
+ if (!cfgRead) { try { sharedCfg = await this._client.getConfig(this.room, this._mk, { plainMark: true }) } catch { sharedCfg = null } }
2236
+ if (sharedCfg && sharedCfg.lanes === false) throw sdkError('witbitz: private lanes are disabled for this Space', 'lanes_disabled')
2237
+ if (sharedCfg && sharedCfg.plain === true) { sharedCfg = null; cfgRead = true } // a plain room: read, and it has no settings
2238
+ // the placeholder a verified Space's settings read gives before the sign-in admits (gated, no allow) is not its settings:
2239
+ // read as such, the lane got none of its Space's tools (sync sweep 2026-10-29 #9; the app: roomSync gatedStub)
2240
+ // the member's words whether or not the link says gated (sync sweep 11-10 #10: a gated link got the generic "could not be read")
2241
+ if (gatedStub(sharedCfg)) { sharedCfg = null; { const sess = this._wb && this._wb._session; throw sdkError(sess && sess.email ? "witbitz: this Space's settings open only to an admitted member — you are signed in as " + sess.email + ", but its gate has not admitted you yet, so its private lane cannot be made — ask an admin of the Space, then try again" : "witbitz: this Space's settings need a sign-in that admits you before its private lane can be made — sign in (" + signInHow(this._wb) + "), then try again", 'lane_wait') } } // the words for who is asking (sync sweep 11-09)
2242
+ // a read that FAILED waits, whatever the link says — as the vault and the app do (sync sweep 2026-11-03: an old unmarked
2243
+ // link of a verified Space whose first read failed got an OPEN lane)
2244
+ // A REMOVED MEMBER is not "try again" (as the vault, sync sweep 11-10 #10): the settings read answers nothing for a key the room no
2245
+ // longer holds, and the room's grant tells removed from re-keyed — a new key taken is read once more; removed is said by name
2246
+ if (!sharedCfg && !cfgRead && this._mk) {
2247
+ const took = await this._adoptKey([this._mk]).catch(() => null)
2248
+ if (took) { try { sharedCfg = await this._client.getConfig(this.room, this._mk, { plainMark: true }) } catch { sharedCfg = null } if (sharedCfg && sharedCfg.plain === true) { sharedCfg = null; cfgRead = true } }
2249
+ if (this._keyWait === 'removed') throw sdkError('witbitz: you are no longer a member of this Space, so it has no private lane for you', 'removed')
2250
+ }
2251
+ if (!sharedCfg && (this._gated || !cfgRead)) throw sdkError("witbitz: this Space's settings could not be read, so its private lane cannot be made as strict as it yet — try again", 'lane_wait')
2252
+ const sess = wb && wb._session
2253
+ const me = sess && sess.email && !(sess.exp && sess.exp <= Date.now()) ? String(sess.email).trim().toLowerCase() : ''
2254
+ // An ATTESTED Space (its owner policy requires an attested app): its lane is made only by the attested app itself (the Witbitz app on
2255
+ // the device, since 10ed84f3), under the same rule — never by the SDK
2256
+ // (sync sweep 2026-10-19 #3: an SDK lane of one was an ordinary room bridged to it).
2257
+ let attested = false
2258
+ if (typeof this._client.attestedRoom === 'function') { try { attested = !!(await this._client.attestedRoom(this.room, this._mk)) } catch { throw sdkError("witbitz: whether this Space requires an attested app could not be read, so its private lane waits — try again", 'lane_wait') } } // a failed read is not 'not attested' (sync sweep 11-08)
2259
+ const inh = laneInherits(sharedCfg, { email: me, attested })
2260
+ if (inh.wait === 'attested') throw sdkError('witbitz: this Space requires an attested app, so its private lane is made only by that app (the Witbitz app on the device), under the same rule — not by the SDK', 'attested')
2261
+ if (tools === undefined && immediateTools === undefined) { tools = inh.config.tools; immediateTools = inh.config.immediateTools }
2262
+ if (sharedCfg && sharedCfg.admission === 'email') {
2263
+ if (admission === undefined) {
2264
+ if (inh.wait === 'email') throw sdkError("witbitz: this Space is verified, so its private lane is gated to you — sign in first (" + signInHow(wb) + ")", 'sign_in_required')
2265
+ gate = normAdmission({ emails: inh.gate.allow.emails })
2266
+ } else if (!(gate && gate.admission === 'email')) throw sdkError("witbitz: this Space is verified, so its private lane must be too — an open lane would let anyone with its link read the member's private assistant. Omit `admission` to gate it to the signed-in member.", 'lane_downgrade')
2267
+ }
2268
+ const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: LANE_AGENT_NAME, persona: framingOpt(framing) ? '' : DEFAULT_ASSIST }) // builder mode: no Spaces lane persona either
2269
+ cfg.lane = true // a lane says so in its own sealed settings, as the app's (laneConfig.js; sync sweep 11-19 P1)
2270
+ cfg.region = roomRegion(this.room) // a lane lives where its shared room does — the server refuses a bridge across regions
2271
+ if (enc) await wb._encAttestSoft()
2272
+ const split = this._split // a lane of a split Space is split too — its own userShare and app half
2273
+ const { room, mk, links, commit, configSealed, userShare, enclaveCreated } = await this._client.create(cfg, { base: this._viewer, ...(enc && !split ? { enclave: true } : {}), ...(split ? (wb ? wb._splitOpts() : { split: true }) : {}) })
2274
+ if (enc) { wb._enc.rooms.set(room, true); await wb._encWake(room); if (!enclaveCreated && !(await wb._encSealConfig(room, commit, configSealed))) throw sdkError('the new confidential lane could not receive its configuration', 'enclave_seal_failed') }
2275
+ const laneBase = split ? splitLinkOf(links[0], userShare, commit) : links[0]
2276
+ // A confidential lane of a STANDARD Space (`tier: 'enclave'` asked) is across tiers, as openLane's: the enclave does not
2277
+ // hold the standard room, so its turns carry no bridge and this device mirrors the Space into it (the docs audit,
2278
+ // 2026-10-24 — it sent the standard room as a bridge the enclave could not find, and its assistant never saw the room).
2279
+ const crossTier = enc !== sharedIsEnclave
2280
+ const lane = new Lane(this._client, { room, mk, link: enc ? markEncLink(laneBase) : laneBase, viewer: this._viewer, sharedRoom: this.room, sharedMk: this._mk, actions, wb: this._wb, shared: this, mirror: crossTier ? (mirror || true) : mirror, split, crossTier })
2281
+ return wb ? wb._backedUp(lane) : lane
2282
+ }
2283
+
2284
+ /** IN A VAULT the vault makes the lane (it keeps the key) and records it as this Space's lane; the page gets a keyless
2285
+ * Lane whose bridge key the vault's worker fills in by room. A confidential Space's lane is confidential too (the vault
2286
+ * makes it so — docs/sdk-vault-mode.md § As built, "Confidential Spaces in a vault"); asking for another tier is refused below. */
2287
+ async _vaultLane({ agent, actions, tools, immediateTools, model, data, admission, tier, mirror, platformTools, framing, dataWrites }) {
2288
+ const wb = this._wb
2289
+ if (tier !== undefined && tier !== null) { // a lane's tier is its Space's (the vault makes it so); a different one is refused, never a silent change
2290
+ const asked = tierIsEnclave(tier), it = (await wb.vault.rooms()).find((r) => r.room === this.room), isEnc = !!(it && it.tier === 'enclave')
2291
+ if (asked !== isEnc) throw tierMismatch(isEnc ? 'this Space is confidential, so its private lane is too — omit `tier` to inherit' : 'this Space is not confidential — a lane is on its Space\'s tier')
2292
+ }
2293
+ if (wb) await wb._checkModel(model || agent.model)
2294
+ const gate = normAdmission(admission)
2295
+ if (tools === undefined && immediateTools === undefined) {
2296
+ try { const inh = inheritToolsFrom(await this._client.getConfig(this.room, null)); tools = inh.tools; immediateTools = inh.immediateTools } catch { /* unreadable: the lane gets the defaults */ }
2297
+ }
2298
+ const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: LANE_AGENT_NAME, persona: framingOpt(framing) ? '' : DEFAULT_ASSIST })
2299
+ cfg.region = roomRegion(this.room)
2300
+ // an `admission` that opens the lane reaches the vault as `{ open }` (an open room's config names no admission, so the vault
2301
+ // could not tell it from none): in a verified Space it is refused by name, as outside a vault (lane_downgrade)
2302
+ const { room } = await wb.vault._c.createLane(this.room, cfg, admission !== undefined && !(gate && gate.admission === 'email') ? { open: true } : undefined)
2303
+ return refuseSpaceInVault(new Lane(this._client, { room, mk: null, link: null, viewer: this._viewer, sharedRoom: this.room, sharedMk: null, actions, wb, shared: this, mirror })) // its connections and Siri go through the vault, as a Space's
2304
+ }
2305
+
2306
+ /** Change the assistant IN PLACE — name, instructions, model, the store's collections, which platform tools it gets —
2307
+ * for every member, visibly: a system line lands in the Space ("⚙️ You changed the assistant's instructions") and the
2308
+ * next turn runs on the new settings. Your own tools, admission and governance stay as created (a move — fork() — or a new room).
2309
+ * @param {object} opts { agent: { name?, instructions?, model? }, data?, platformTools?, framing?, dataWrites?, safeMedia?, lanes?, from? } → { changed: string[] } */
2310
+ async configure({ agent = {}, data, platformTools, framing, dataWrites, safeMedia, lanes, from, ...rest } = {}) {
2311
+ from = this._who(from)
2312
+ if (lanes === true && this.room.startsWith('tmp-')) throw sdkError('witbitz: temporary Spaces cannot have private lanes', 'temporary_room')
2313
+ if (lanes === true && !this._client.vault) await assertNotKept(this)
2314
+ // what plan() judges, refused the same way (sync sweep, 2026-10-11: they were dropped without a word)
2315
+ for (const k of Object.keys(rest)) {
2316
+ if (['tools', 'immediateTools', 'tier', 'key'].includes(k)) throw Object.assign(new Error(`witbitz: ${k} is chosen when a room is made — make a new room (plan() says so)`), { code: 'create_time' })
2317
+ if (k === 'admission') throw this._sharedRoom ? Object.assign(new Error("witbitz: a lane is one member's own room — change its Space's members instead"), { code: 'lane' }) : Object.assign(new Error('witbitz: a new member list is changed with space.changeMembers(admission)'), { code: 'use_fork' })
2318
+ throw Object.assign(new Error(`witbitz: ${k} is not a setting configure() changes`), { code: 'unknown_field' })
2319
+ }
2320
+ // the keys plan() judges, refused the same way (sync sweep, 2026-10-10: configure ignored them, plan refused them)
2321
+ for (const k of Object.keys(agent || {})) {
2322
+ if (k === 'tools') throw Object.assign(new Error("witbitz: agent.tools are chosen when a room is made — make a new room (plan() says so)"), { code: 'create_time' })
2323
+ if (!['name', 'instructions', 'model'].includes(k)) throw Object.assign(new Error(`witbitz: agent.${k} is not a setting of the assistant`), { code: 'unknown_field' })
2324
+ }
2325
+ // a private lane follows its Space's Safe media — refused here as safeMedia.set refuses it (sync sweep 2026-10-31 #2)
2326
+ if (safeMedia !== undefined && this._sharedRoom) throw sdkError('witbitz: a private lane follows its Space’s Safe media — set it on the Space', 'lane_follows_space')
2327
+ if (safeMedia === true && this.temporary) throw sdkError('witbitz: a temporary room has no Safe media — the Spaces app never offers it there', 'temporary_room') // as createSpace (sync sweep 2026-11-13)
2328
+ const patch = {}
2329
+ if (platformTools !== undefined) patch.platformTools = platformToolsOpt(platformTools) ?? null // true/null → all again
2330
+ if (framing !== undefined) patch.framing = framingOpt(framing) ?? null // 'builder' → the app's prompt only; null → the Spaces framing again
2331
+ if (dataWrites !== undefined) patch.dataWrites = dataWrites === false ? false : null // false → data_query only
2332
+ if (safeMedia !== undefined) { if (typeof safeMedia !== 'boolean') throw sdkError('witbitz: safeMedia takes true or false', 'invalid_argument'); if (safeMedia && !safeMediaReady()) throw sdkError('witbitz: no safe-media enclave is accepted in this release yet', 'safe_media_unavailable'); patch.safeMedia = safeMedia ? true : null } // as createSpace (sync sweep 2026-10-28) // SAFE MEDIA on/off for everyone (docs/safe-media.md)
2333
+ // PRIVATE ASSISTANTS ON OR OFF IN PLACE (docs/always-on-agent-plan.md Phase 0b): a Space made with them can turn them off (and on);
2334
+ // members' existing private rooms stay as Spaces of their own. A lane has none of its own.
2335
+ if (lanes !== undefined) { if (typeof lanes !== 'boolean') throw sdkError('witbitz: lanes takes true or false', 'invalid_argument'); if (this._sharedRoom) throw sdkError("witbitz: a private lane has no private assistants of its own — set it on the Space", 'lane'); patch.lanes = lanes }
2336
+ if ('name' in agent) patch.agentName = agent.name
2337
+ if ('instructions' in agent) patch.persona = agent.instructions
2338
+ if ('model' in agent) { if (this._wb) await this._wb._checkModel(agent.model); patch.model = agent.model }
2339
+ if (data !== undefined) { checkDataSchema(data); patch.dataSchema = data } // declare or change the store's collections (null → none); refused if over LIMITS
2340
+ const r = await this._client.setConfig(this.room, this._mk, patch, from)
2341
+ if (!r || r.status !== 200) throw refused('configure', r)
2342
+ if (lanes !== undefined) this._lanesSetting = lanes
2343
+ if (lanes === false) {
2344
+ if (this._wb?.vault) {
2345
+ for (const lane of this._wb._openLanes || []) if (lane._sharedRoom === this.room) lane._detachShared()
2346
+ } else await disconnectRoomLanes(this._wb, this.room)
2347
+ }
2348
+ if (safeMedia !== undefined) this.safeMedia._learn(safeMedia, Date.now())
2349
+ return { changed: Array.isArray(r.changed) ? r.changed : [] }
2350
+ }
2351
+
2352
+ /** What a change would REQUIRE, before you make it — and nothing is changed (sdkPlan.js). `change` takes
2353
+ * configure()'s, fork()'s and createSpace()'s fields: { agent, data, admission, tier, key, tools, immediateTools }.
2354
+ * → { how: 'none'|'in_place'|'fork'|'new_room'|'refused', history: 'kept'|'carried'|'not_carried'|null, call, steps,
2355
+ * reason?, code? } */
2356
+ async plan(change = {}) {
2357
+ let cfg = null, gatedUnread = false
2358
+ if (change && change.admission !== undefined && !this._sharedRoom) { this._gateCfg = null; try { cfg = await this._gateConfig() } catch (e) { if (e && e.code === 'sign_in_required') gatedUnread = true; else if (e && e.code !== 'config_unavailable') throw e } } // signed out in a gated room: a refusal, not a throw (sdk-assistant.md#changing-the-assistant)
2359
+ else if (change && (change.agent || change.data !== undefined || change.platformTools !== undefined || change.framing !== undefined || change.dataWrites !== undefined || change.safeMedia !== undefined) && typeof this._client.getConfig === 'function') { try { const c = await this._client.getConfig(this.room, this._mk); gatedUnread = !!(c && c.gated === true && !c.allow); cfg = c && typeof c === 'object' && !gatedUnread ? c : null } catch { cfg = null } } // the in-place rules need the room's admins (sdkPlan.js)
2360
+ const sess = this._wb && this._wb._session
2361
+ const me = this._wb && this._wb.vault ? String(((await this._wb.vault.whoami()) || {}).email || '') // in a vault, its signed-in member (sync sweep 10-15 #2)
2362
+ : sess && (!sess.exp || sess.exp > Date.now()) ? String(sess.email || '') : ''
2363
+ const out = planChange(change, { cfg, me, lane: !!this._sharedRoom, checkData: checkDataSchema, gatedUnread, signIn: signInHow(this._wb) })
2364
+ if (out.how === 'in_place' && change.agent && change.agent.model && this._wb) { try { await this._wb._checkModel(change.agent.model) } catch (e) { return { how: 'refused', history: null, call: null, steps: out.steps, reason: String(e.message || e), code: e.code || 'invalid_model' } } }
2365
+ return out
2366
+ }
2367
+
2368
+ /** Approve a proposal → the runtime executes it (a data write lands in the Space; a lane's crossing posts to the shared
2369
+ * room), or, for one of your own `actions`, runs your handler on this device.
2370
+ * `{ recordResult: false }` — for a connection call whose answer you hand to the assistant yourself: the room records
2371
+ * the call (who approved, what was called, how it went) but not the answer body. */
2372
+ // `from`: the approver's name as it appears on what the approval DOES — a crossing lands in the shared room under it.
2373
+ // A name is a claim; in an email-gated room the server adds `verified` + the attested @username beside it.
2374
+ approve(id, { recordResult, from } = {}) { return this._decide(id, true, { recordResult, from: this._who(from) }) }
2375
+ /** Deny a proposal → drop it (the agent is told, so it won't re-propose the same thing). */
2376
+ deny(id, { from } = {}) { return this._decide(id, false, { from: this._who(from) }) }
2377
+ _decideExtra() { return {} } // a Lane adds its bridge fields
2378
+ _runExtra() { return {} } // a Lane adds its bridge fields — a lane's run sees its shared room, as its turns do
2379
+
2380
+ /** Stop the poll loop and release the handle. */
2381
+ close() { this._stopped = true; this._wb?._archiveHandles?.delete(this); try { if (this._wb && this._wb.invite) this._wb.invite._waiting.delete(this); if (this._vaultKeyOff) this._vaultKeyOff() } catch { /* */ } for (const t of [...(this._turns || [])]) { try { t._settle('failed', { error: 'closed' }) } catch { /* */ } } clearTimeout(this._timer); this._timer = null; if (this._stream) { this._stream.stop(); this._stream = null } if (this._pendingTimer) { clearInterval(this._pendingTimer); this._pendingTimer = null } this._settleReady(Object.assign(new Error('witbitz: the Space was closed before its first poll'), { code: 'closed' })) }
2382
+ _settleReady(err) { if (!this._readyResolve) return; const [ok, no] = [this._readyResolve, this._readyReject]; this._readyResolve = this._readyReject = null; if (err) no(err); else ok(this) }
2383
+
2384
+ async _decide(id, approve, { recordResult, from = 'You' } = {}) {
2385
+ const act = this._pendingActions[id]
2386
+ const isClientWrite = approve && act && typeof this._writes[act.type] === 'function'
2387
+ const r = await this._client.decide(this.room, this._mk, id, approve, String(from || 'You'), {
2388
+ ...this._decideExtra(),
2389
+ ...(isClientWrite ? { deviceExec: true } : {}), // a client action: the server approves but does NOT run it — we do, below
2390
+ ...(recordResult === false ? { recordResult: false } : {}),
2391
+ })
2392
+ // A REFUSED decision (2026-10-02 — `not_admin` in a room with admins) leaves the card pending, for someone who may
2393
+ // decide it. It used to fall through: the card was dropped here and `resolved` fired with approved:true.
2394
+ // …and so does NO answer: OHTTP's failure is { status: 0 }, which a truthy-status test waved through as approved (sync sweep, 2026-10-11)
2395
+ // …and a 200 that decided nothing (a proxy's error page, a body that lost its fields) is no decision either: every real
2396
+ // answer names the card's new status in `decided` (spaceService op decide; sync sweep, 2026-10-11)
2397
+ if (!r || r.status !== 200 || !r.decided) throw refused(approve ? 'approve' : 'deny', r)
2398
+ let result
2399
+ if (isClientWrite && r && r.deviceExec) {
2400
+ try { result = await this._writes[act.type](act) } catch (e) { result = { error: String((e && e.message) || e) } }
2401
+ } else if (approve && r && r.execution) {
2402
+ result = r.execution // a server-executed proposal (an approved crossing, a data write)
2403
+ }
2404
+ delete this._pendingActions[id]
2405
+ this._emit('resolved', { id, approved: !!approve, action: act && act.type, result })
2406
+ this._kick()
2407
+ // THE ASSISTANT CONTINUES (the Spaces app's pendingProposals.js → space.js continueAfterApproval; sync sweep 2026-11-13): a call
2408
+ // the SERVER ran left its result in the room, so the assistant is asked to go on from it — a turn with no message, `cont`: this
2409
+ // card (the server admits it only for a card approved and run in the last 10 minutes, once). Not for a crossing (it is the
2410
+ // message itself), a write this page applied, or a result you hand to the assistant yourself (`recordResult: false`). Its
2411
+ // reply arrives on 'message'; approve() does not wait for it.
2412
+ // ⚑ Not over the Spaces app's own worker client (keyless, no vault): its pendingProposals.js sends the continuation itself
2413
+ // (space.js continueAfterApproval, with the app's wake and proofs) — two would race for the one admission.
2414
+ const appWorker = !!(this._client && this._client.keyless && !this._client.vault)
2415
+ const ran = !appWorker && approve && !isClientWrite && recordResult !== false && act && act.type !== 'cross_to_shared' && r.execution && r.execution.ok === true
2416
+ if (ran) { this._continueAfter(id, from).catch(() => {}); return { ...r, result, continued: true } }
2417
+ return { ...r, result }
2418
+ }
2419
+ /** @private the continuation turn after an approved call ran (see _decide) — the same proofs and options as a send. */
2420
+ async _continueAfter(id, from) {
2421
+ const opts = await this._turnOpts(undefined, this._runExtra()) // a lane's bridge and links, as its turns
2422
+ const r = await this._turnHeld(() => this._provenTurn({ from: String(from || 'You'), text: '', cont: id }, opts))
2423
+ this._kick()
2424
+ return r
2425
+ }
2426
+
2427
+ _proposalOf(pid, act) {
2428
+ return {
2429
+ id: pid,
2430
+ kind: act.type === 'cross_to_shared' ? 'message' : 'action',
2431
+ action: act.type || '',
2432
+ args: act,
2433
+ text: act.text || act.why || '',
2434
+ approve: (opts) => this.approve(pid, opts),
2435
+ deny: (opts) => this.deny(pid, opts),
2436
+ }
2437
+ }
2438
+ /** Ask the room for its waiting proposals now → the current list (what `proposals` carries). */
2439
+ async pending() {
2440
+ if (this._inflightPending) { try { await this._inflightPending } catch { /* */ } }
2441
+ await this._pollPending()
2442
+ return this._pendingList.slice()
2443
+ }
2444
+ async _pollPending() {
2445
+ // A room that refused this reader for good (_pollHeld: not on the list, removed) refuses `pending` too — the proposals
2446
+ // poll follows the main poll's minute instead of asking every 1.5 s (sync sweep, 2026-10-10).
2447
+ if (this._pollHeld && Date.now() - (this._pendingHeldAt || 0) < HELD_POLL_MS) return
2448
+ if (this._pollHeld) this._pendingHeldAt = Date.now()
2449
+ if (this._stopped || this._inflightPending) return
2450
+ let done; this._inflightPending = new Promise((r) => { done = r })
2451
+ try {
2452
+ const r = await this._client.pending(this.room, this._mk)
2453
+ // A read that FAILED says nothing about the cards: keep the last list (sync sweep, 2026-10-10 — one 5xx emptied every
2454
+ // waiting card, here and in the app, which draws from this, and the next good read re-fired every 'proposal').
2455
+ if (!(r && r.status === 200 && Array.isArray(r.pending))) return
2456
+ const list = r.pending
2457
+ const live = new Set()
2458
+ for (const p of list) {
2459
+ const pid = p && p.id; if (!pid) continue
2460
+ live.add(pid)
2461
+ if (pid in this._pendingActions) continue // already surfaced
2462
+ const act = p.action || {}
2463
+ this._pendingActions[pid] = act
2464
+ this._emit('proposal', this._proposalOf(pid, act))
2465
+ }
2466
+ for (const pid of Object.keys(this._pendingActions)) if (!live.has(pid)) delete this._pendingActions[pid] // resolved elsewhere
2467
+ // THE WHOLE LIST, for a page that draws a card of everything waiting (the Spaces app's): `proposals` fires when the
2468
+ // set or a text changes — including a proposal resolved on another device, which `proposal` never tells.
2469
+ this._pendingList = list.filter((p) => p && p.id).map((p) => this._proposalOf(p.id, p.action || {}))
2470
+ const sig = this._pendingList.map((p) => p.id + ':' + (p.text || p.action)).join('\u241f')
2471
+ if (sig !== this._pendingSig) { this._pendingSig = sig; this._emit('proposals', this._pendingList.slice()) }
2472
+ } catch { /* transient */ } finally { this._inflightPending = false; done() }
2473
+ }
2474
+
2475
+ async _poll() {
2476
+ if (this._stopped) return
2477
+ // a kick while a poll is out (a send, the stream's "the ledger grew") is not dropped: one more poll at once when it settles
2478
+ // (pass 5, V#15 — a finished reply landed up to 3 s late)
2479
+ if (this._inflight) { this._pollAgain = true; return }
2480
+ this._inflight = true
2481
+ let read = false // this poll was a 200: only then may `_more` ask for the next page at once
2482
+ try {
2483
+ const r = await this._client.pollSealed(this.room, this._mk, this._etag, this._count)
2484
+ if (this._stopped) return // V#7: answered after close(): nothing of it is applied, announced, or run (a device call included)
2485
+ if (!this._sharedRoom && r && r.status === 200 && Date.now() - (this._lanesCheckedAt || 0) > 30000 && typeof this._client.getConfig === 'function') {
2486
+ this._lanesCheckedAt = Date.now()
2487
+ try {
2488
+ const cfg = await this._client.getConfig(this.room, this._mk, { plainMark: true })
2489
+ if (this._stopped) return
2490
+ if (cfg && !gatedStub(cfg) && (typeof cfg.lanes === 'boolean' || cfg.plain === true)) {
2491
+ this._lanesSetting = cfg.lanes === true
2492
+ if (this._gateCfg && typeof cfg.lanes === 'boolean') this._gateCfg.lanes = cfg.lanes
2493
+ }
2494
+ } catch { /* retain the last confirmed setting */ }
2495
+ }
2496
+ if (this._wb && this._wb._attest) this._wb._attest.notePoll(this.room, r) // a room that requires your app: its fresh challenge
2497
+ // ⛔ A REFUSED POLL LOOKED LIKE AN EMPTY ROOM (a builder, 2026-09-29). A poll carrying an error code — in a 200 (the
2498
+ // confidential tier's host front flattened every status to 200) or in a 4xx/5xx — used to take the success path,
2499
+ // find no entries and say nothing. Now it raises 'error' with the code, ONCE per distinct refusal (a poll runs every
2500
+ // ~600 ms), and a good poll clears it so the same refusal later is reported again. (422 keeps its own message.)
2501
+ const verdict = pollVerdict(r) // pollVerdict.js — the same verdict the Spaces app reaches on the same answer
2502
+ // a moment's wait is not a refusal (sync sweep 2026-11-14 P5, owner: yes — the app stays silent there too): an enclave starting
2503
+ // (`warming`) or a check that could not be made just now (`unavailable`: the verifier, the tier, the store, a delete finishing)
2504
+ // raises no 'error' — the poll asks again on its own.
2505
+ const transient = verdict.kind === 'warming' || verdict.kind === 'unavailable'
2506
+ const refusal = verdict.kind !== 'ok' && verdict.kind !== 'cannot_open' && verdict.kind !== 'no_answer' && !transient ? verdict.code : null
2507
+ if (refusal) {
2508
+ const key = refusal + '|' + (r.reason || '')
2509
+ if (this._pollRefusal !== key) {
2510
+ this._pollRefusal = key
2511
+ const e = new Error(`witbitz: the room could not be read (${refusal}${r.reason ? ': ' + r.reason : ''})`)
2512
+ e.code = refusal; if (r.reason) e.reason = r.reason; e.status = r.status
2513
+ this._emit('error', e)
2514
+ }
2515
+ // A refusal a retry cannot cure — not on the room's list, removed, the room's settings unreadable — slows the
2516
+ // poll to once a minute (the app stops it, sync sweep 2026-10-10): a re-admission is still noticed, nothing
2517
+ // hammers. `_kick()` (a send, the stream) polls at once as before.
2518
+ this._pollHeld = PERMANENT_REFUSALS.has(r.reason) || refusal === 'gate_unreadable' || !!this._keyWait // removed from a re-keyed room, or waiting for a fresh link
2519
+ // NO ROOM PASS where the room requires one (agent/roomPass.mjs, the cutoff: this address is on passes): the client already asked for
2520
+ // a fresh pass and tried again (spaceClient.js), so a retry here cannot cure it — this client is not on the account service, or
2521
+ // this device was signed out there. `ready` rejects by name instead of waiting for ever (devserver/test/roomPassCutoff.test.mjs,
2522
+ // 2026-11-26: a refused client was never told); the poll is held to once a minute, as for any refusal a retry cannot cure.
2523
+ if (!r.passRetryable && /^pass: (pass_required|app_unnamed)/.test(String(r.reason || ''))) {
2524
+ this._pollHeld = true
2525
+ this._settleReady(Object.assign(new Error('witbitz: this Space requires a room pass for this address, and this client has none — its account is not on the account service here, or this device was signed out'), { code: 'pass_required', reason: r.reason, status: r.status }))
2526
+ }
2527
+ return
2528
+ }
2529
+ this._pollRefusal = null; this._pollHeld = false
2530
+ if (r && r.status === 200) {
2531
+ if (r.etag) this._etag = r.etag
2532
+ const clearedRemoval = Array.isArray(r.removed) && this._removedMessages?.size && [...this._removedMessages.keys()].some(key => !r.removed.some(e => removedEntryKey(e) === key))
2533
+ if (Array.isArray(r.removed)) {
2534
+ this._removedMessages = new Map(r.removed.filter((e) => e && e.id != null && e.ts != null).map((e) => [removedEntryKey(e), e]))
2535
+ for (const e of [...this.messages]) if (this._removedMessages.has(removedEntryKey(e)) && !e.removedByWitbitz) {
2536
+ const m = removedCopy(e), { updated } = this._view.apply([m])
2537
+ for (const u of updated) this._emit('update', { id: u.id, message: u.entry, fields: u.fields })
2538
+ }
2539
+ }
2540
+ if (r.changed && Array.isArray(r.entries)) {
2541
+ for (let e of r.entries) {
2542
+ if (this._removedMessages && this._removedMessages.has(removedEntryKey(e))) e = removedCopy(e)
2543
+ else if (e.sourceRestored === true) this._removedSourceMessages?.delete(removedEntryKey(e))
2544
+ else if (this._removedSourceMessages && this._removedSourceMessages.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2545
+ // `from` IS THE DOCUMENTED FIELD (see the header and `on()` below) — the ledger calls it `name`, and this
2546
+ // emitted the raw entry, so an author test written from the docs (`m.from === me`) silently matched
2547
+ // NOTHING and every delivered message read as "not mine". Reported by the first outside builder after it
2548
+ // cost him an afternoon (2026-09-21). The `data` event one line down has always done this translation;
2549
+ // this is the one that forgot. `name` is kept for anyone who worked out the real shape by inspection, and
2550
+ // an entry that already carries `from` is left alone. `messages` gets the SAME object as the event — two
2551
+ // shapes for one thing is how this happened.
2552
+ if (isTitleEntry(e)) { this._noteTitle(e); continue } // the room's NAME, not a message (roomName.js)
2553
+ if (isPurged(e)) continue // a DELETED MAIL's place (agent/mailPurge.mjs): nothing is left of it — the app draws nothing either (sync sweep 11-22 #9)
2554
+ if (this.safeMedia._note(e)) continue // a photo's SAFE COPY, kept beside it — never a message (sdkSafeMedia.js); the line that moved the setting is read and stays a message
2555
+ const m = e && e.from === undefined && e.name !== undefined ? { ...e, from: e.name } : e
2556
+ const { added, updated } = this._view.apply([m])
2557
+ if (updated.length) { const u = updated[0]; this._emit('update', { id: u.id, message: u.entry, fields: u.fields }); continue } // a reaction / caption / widgets on a message you already have
2558
+ if (!added.length) continue // the same entry again
2559
+ this._emit('message', m)
2560
+ this.safeMedia._arrived(m) // a message this handle sent: its safe copies go beside it
2561
+ if (m && !m.self && typeof m.text === 'string') this._feed.landed(m.text) // a stored answer: its own late stream frames are not a partial (turnFeed.js; sync sweep 10-15 #16)
2562
+ if (e && e.kind === 'fork') this._maybeMoved(e) // a membership fork: is this device one of the keepers?
2563
+ if (e && e.kind === 'data' && Array.isArray(e.ops)) { applyDataEntry(this._rows, e); this._emit('data', { ops: e.ops, from: e.name || '', self: !!e.self, text: e.text || '', ts: e.ts }) }
2564
+ }
2565
+ if (typeof r.version === 'number') this._count = r.version
2566
+ // `more`: another page follows (a long room loads in pages) — read it at once, and until it has, the history is
2567
+ // not whole: a lane mirror must not take a short list for another history (sync sweep, 2026-10-10)
2568
+ }
2569
+ if (clearedRemoval) { this._count = 0; this._etag = null }
2570
+ this._more = !!(clearedRemoval || (r.changed && r.more)); read = true // the NEXT poll (in `finally`, at once) reads the next page
2571
+ this._maybeTitleDoc()
2572
+ if (needsTailResync(r, this._count) && Date.now() - (this._resyncAt || 0) > 1500) { this._resyncAt = Date.now(); this._tailResync().catch(() => {}) } // an in-place change pages as nothing
2573
+ if (r.deviceCall) this._runDeviceCall(r.deviceCall) // an `await` action the turn is waiting on — answer from this device
2574
+ this._partialFromPoll(r)
2575
+ this._liveFeed(r)
2576
+ // READY = the WHOLE history, every page (sync sweep, 2026-10-10: it fired after the first, and a `replay: false`
2577
+ // listener heard page two's old messages as new)
2578
+ if (!this._more) {
2579
+ this._settleReady() // after the entries are applied, so what the polls carried is already in `messages`
2580
+ this._historyRead = true // on('message', cb, { replay: false }) hears from here on
2581
+ }
2582
+ if (!this._announced) this._announce()
2583
+ } else if (r && r.status === 422) {
2584
+ this._emit('error', Object.assign(new Error('witbitz: this key cannot open the room history'), { code: 'cannot_open' }))
2585
+ this._settleReady(Object.assign(new Error('witbitz: this key cannot open the room history'), { code: 'cannot_open' }))
2586
+ }
2587
+ } catch (err) {
2588
+ // THE VAULT DROPPED THIS SPACE (forget, a sign-out): a refusal a retry cannot cure — said ONCE and the poll held to once a
2589
+ // minute, as a permanent refusal is (sync sweep 2026-11-23: every ~3 s tick raised `not_in_vault` again, for ever)
2590
+ if (err && err.code === 'not_in_vault') {
2591
+ if (this._pollRefusal !== 'not_in_vault|') { this._pollRefusal = 'not_in_vault|'; this._emit('error', err) }
2592
+ this._pollHeld = true
2593
+ return
2594
+ }
2595
+ // a failure with no code of its own (the network, a thrown read) is `unavailable`: a poll error is transient (sdk-reference.md#errors)
2596
+ this._emit('error', err instanceof Error ? (err.code ? err : Object.assign(err, { code: 'unavailable' })) : sdkError(String(err), 'unavailable'))
2597
+ } finally {
2598
+ this._inflight = false
2599
+ // ONE timer: the next page at once while the history is still loading, else the usual interval. A refusal, a 422, a
2600
+ // transport failure or a throw ends the paging (sync sweep, 2026-10-10: `_more` stayed true and it polled at 0 ms,
2601
+ // past the held one-a-minute poll of a permanent refusal) — the usual poll reads the next page when it can.
2602
+ if (!read) this._more = false
2603
+ const again = this._pollAgain && !this._hostDriven; this._pollAgain = false
2604
+ if (!this._stopped) { clearTimeout(this._timer); this._timer = setTimeout(() => this._poll(), (this._more || again) && !this._hostDriven ? 0 : this._interval()) }
2605
+ }
2606
+ }
2607
+
2608
+ // THE IN-PLACE CHANGE (ledgerView.js): the ledger moved and brought no entry — a reaction or a caption rewrote one you
2609
+ // hold. Re-read a short tail and announce what changed; its etag is NOT adopted (a reply landing in between would be lost).
2610
+ async _tailResync() {
2611
+ const r = await this._client.pollSealed(this.room, this._mk, null, Math.max(0, this._count - REACTION_RESYNC_TAIL))
2612
+ if (!(r && r.status === 200 && Array.isArray(r.entries))) return
2613
+ for (let e of r.entries) {
2614
+ if (this._removedMessages && this._removedMessages.has(removedEntryKey(e))) e = removedCopy(e)
2615
+ else if (e.sourceRestored === true) this._removedSourceMessages?.delete(removedEntryKey(e))
2616
+ else if (this._removedSourceMessages && this._removedSourceMessages.has(removedEntryKey(e))) e = sharedRemovedCopy(e)
2617
+ if (isTitleEntry(e)) { this._noteTitle(e); continue }
2618
+ if (isPurged(e)) continue // a deleted mail's place, written over its entry in that slot: no `update` (sync sweep 11-22 #9)
2619
+ const m = e && e.from === undefined && e.name !== undefined ? { ...e, from: e.name } : e
2620
+ const { updated } = this._view.apply([m])
2621
+ for (const u of updated) this._emit('update', { id: u.id, message: u.entry, fields: u.fields })
2622
+ }
2623
+ }
2624
+
2625
+ // Poll fast right after activity (a live exchange), then back off while idle so a quiet Space costs almost nothing.
2626
+ // While the room's stream is DELIVERING (a frame in the last 3 s), the frames carry the reply: poll only as a net.
2627
+ _interval() { if (this._pollHeld) return this._keyWait && this._keyWait !== 'removed' ? KEY_WAIT_POLL_MS : HELD_POLL_MS; return Date.now() - this._streamFrameAt < 3000 ? 3000 : Date.now() - this._lastActive < 8000 ? 900 : 3000 }
2628
+
2629
+ // ── the reply as it is written: `partial` ({ text, step }) — text is the reply so far ('' before the first words, with
2630
+ // `step` saying what the assistant is doing: { phase:'thinking'|'writing'|'deciding' } or { tool }); `text: null` once there is no
2631
+ // reply in progress (the finished one arrives as a `message`). From the room's stream when it is delivering, and from
2632
+ // every poll regardless — the two are ordered by sequence number, so an older one never rewinds a newer one.
2633
+ // `partial` carries { text, step }: the reply so far, or ('' + a step) what the turn is doing, or (null) none any more.
2634
+ // The ORDER and the sequence rules are turnFeed's; this only draws them as events.
2635
+ _emitPartial(text, step) {
2636
+ const p = this._partial
2637
+ if (text === p.text && !step) return
2638
+ p.text = text
2639
+ this._emit('partial', { text, step: step || null })
2640
+ }
2641
+ _clearPartial() { if (this._partial.text === null) return; this._partial = { text: null }; this._emit('partial', { text: null, step: null }) }
2642
+ _drawFeed(o) {
2643
+ if (o.text) this._emitPartial(o.text, null)
2644
+ else if (o.status) this._emitPartial('', o.status)
2645
+ }
2646
+ _partialFromPoll(r) {
2647
+ const o = this._feed.poll(r)
2648
+ if (o.text || o.status) return this._drawFeed(o)
2649
+ // No turn in progress — but a poll can lag a live stream, so clear only once the stream has been quiet a moment.
2650
+ if (o.text === null && !o.status && Date.now() - this._streamFrameAt > 1500) this._clearPartial()
2651
+ }
2652
+ // Open the room's stream after the first successful poll (a gated room's grants ride that poll), then keep it in step.
2653
+ _liveFeed(r) {
2654
+ // IN A VAULT the socket lives in the vault's worker, which keeps it in step from the polls it runs for this Space
2655
+ const raw = this._client && (this._client[RAW_CLIENT] || this._client) // the stream handle is not a room op: past the healing wrapper, which makes every function async
2656
+ if (raw && raw.vault && typeof raw.streamOpen === 'function') {
2657
+ if (!this._stream && !this._stopped && !(this._wb && this._wb._vaultLive === false)) this._stream = raw.streamOpen(this.room, (ev) => this._onStreamEvent(ev))
2658
+ return
2659
+ }
2660
+ if (!this._liveOpts || this._stopped || (this._client && this._client.keyless)) return // a keyless Space has no key to open the stream with — it polls
2661
+ if (!this._stream) {
2662
+ this._stream = openRoomStream({ mk: this._mk, grants: Array.isArray(r.streamGrants) ? r.streamGrants : null, path: 's', WebSocketImpl: this._liveOpts.WebSocketImpl, ...(this._liveOpts.relay ? { relay: this._liveOpts.relay } : {}), onEvent: (ev) => this._onStreamEvent(ev) })
2663
+ return
2664
+ }
2665
+ if (Array.isArray(r.streamGrants)) this._stream.setGrants(r.streamGrants)
2666
+ this._stream.sync(typeof r.partialText === 'string' ? r.partialText : '')
2667
+ }
2668
+ _onStreamEvent(ev) {
2669
+ if (this._stopped) return
2670
+ this._streamFrameAt = Date.now()
2671
+ // ★ AND THE CARDS (2026-09-30, the owner: "why doesn't it include the proposal cards"). A proposal is not a ledger
2672
+ // entry — it lives in the sealed authority doc — so a stream signal fetched the reply live and left the card to the
2673
+ // 1.5 s proposals poll. A card made during a turn exists before that turn's `end` and "the ledger grew", so both ask
2674
+ // for proposals too, whenever anyone listens for them (a lane always does).
2675
+ const o = this._feed.stream(ev)
2676
+ if (o.refetch) { clearTimeout(this._timer); this._timer = null; this._poll(); if (this._pendingTimer) this._pollPending(); return } // the ledger grew: fetch it now
2677
+ if (o.end) {
2678
+ // "No reply in progress." A status with no words yet (Auto deciding, and deciding not to) ends HERE — it used to stay
2679
+ // on screen; words already shown stay until the finished entry replaces them on the poll below.
2680
+ if (this._partial.text === '') this._clearPartial()
2681
+ if (!this._inflight) { clearTimeout(this._timer); this._timer = null; this._poll() } if (this._pendingTimer) this._pollPending(); return // the finished reply is in: pick it up
2682
+ }
2683
+ this._drawFeed(o)
2684
+ }
2685
+ _kick() { this._lastActive = Date.now(); clearTimeout(this._timer); this._timer = null; if (!this._hostDriven) this._poll(); if (this._pendingTimer) this._pollPending() }
2686
+ }
2687
+
2688
+ /** A PRIVATE assistant lane — a member's own room, bridged to a shared {@link Space}. It IS a Space (its private
2689
+ * thread streams on `message`), and adds human-in-the-loop authority:
2690
+ * • `proposal` ({ id, kind:'message'|'action', action, args, text, approve(), deny() }) — the agent proposed a
2691
+ * crossing to the shared room (`kind:'message'`) or an effectful client action (`kind:'action'`). NOTHING happens
2692
+ * until a human calls approve() (posts the crossing / runs your handler on this device) or deny().
2693
+ * • `resolved` ({ id, approved, action, result? }) — after a decision. */
2694
+ export class Lane extends Space {
2695
+ constructor(client, { room, mk, link, viewer, sharedRoom, sharedMk, actions, resume, wb = null, shared = null, mirror = false, split = false, poll, handlers, live, crossTier = false }) {
2696
+ if (typeof resume?.room === 'string' && resume.room !== room) resume = null
2697
+ super(client, { room, mk, link, viewer, resume, wb, split, poll, handlers, ...(live !== undefined ? { live } : {}) }) // `live`: as a Space's (a vault's own handle opens no stream) // `resume`: a prior snapshot() — see Space; was dropped here for a Lane (2026-09-25)
2698
+ this._sharedRoom = sharedRoom
2699
+ if (this._wb && sharedRoom) (this._wb._openLanes ||= new Set()).add(this)
2700
+ this._sharedMk = sharedMk
2701
+ this._sharedSpace = shared instanceof Space ? shared : null // lane.safeMedia follows its Space's setting (sdkSafeMedia.js; sync sweep 2026-10-27 #1)
2702
+ this._crossTier = !!crossTier // a lane of the other tier: mirrored by this device, no bridge on its turns (openLane)
2703
+ hide(this, ['_sharedMk'])
2704
+ this._sharedOffs = [] // its hooks on the Space, taken off by close() (sweep 11-07 #12: they outlived the lane)
2705
+ if (shared instanceof Space && sharedMk) this._sharedOffs.push(shared.on('rekeyed', () => { this._sharedMk = shared._mk })) // the shared room re-keyed in place: its crossings carry the new key
2706
+ // a lane's Safe media follows its Space's: when the Space's setting moves, the lane says so too (sweep P1: its 'safeMedia'
2707
+ // event never fired for the Space's changes, though lane.safeMedia.on had moved)
2708
+ if (shared instanceof Space) this._sharedOffs.push(shared.on('safeMedia', (e) => { try { this._emit('safeMedia', { ...(e || {}), on: this.safeMedia ? this.safeMedia.on : (e && e.on), via: 'space' }) } catch { /* */ } }))
2709
+ // THE MIRROR (2026-10-02) — see _runMirror. The cursor is how many of the shared room's messages this lane already
2710
+ // holds; it rides snapshot()/resume as `mirrored`, and the server dedups by id, so a cursor that is off only resends.
2711
+ this._mirrorCursor = resume && Number.isFinite(Number(resume.mirrored)) ? Math.max(0, Number(resume.mirrored)) : 0
2712
+ if (mirror && shared instanceof Space) {
2713
+ this._mirrorFrom = shared
2714
+ // Messages only by default (2026-10-02, a builder: every row write in a busy team room filled the lane as a "▦ …
2715
+ // saved …" line). `mirror: { data: true }` carries the data lines too. Filtered at SEND, so the cursor still counts
2716
+ // the same list and a saved `mirrored` cursor stays right.
2717
+ this._mirrorData = !!(mirror && typeof mirror === 'object' && mirror.data === true)
2718
+ this._mirrorSub = () => this._scheduleMirror()
2719
+ shared.on('message', this._mirrorSub)
2720
+ shared.on('update', this._mirrorSub) // a late image caption is an update: the catch-up below re-sends it
2721
+ shared.ready.then(() => this._scheduleMirror(), () => {})
2722
+ // A change to a VIEW (the plan, the map) is not a message: on a timer too, as the app's mirror loop (sync sweep,
2723
+ // 2026-10-10 — a lane learned of an edited itinerary only when someone next spoke). The pass reads views at most
2724
+ // every 15 s, so a quiet room costs one cheap pass per tick.
2725
+ this._viewsTick = setInterval(() => { if (!this._stopped && !this._mirrorFrom?._stopped) this._scheduleMirror(); else clearInterval(this._viewsTick) }, 15_000); try { this._viewsTick.unref?.() } catch { /* a browser timer has no unref */ }
2726
+ }
2727
+ const built = buildActions(actions)
2728
+ this._clientTools = built.defs
2729
+ this._writes = { ...this._writes, ...built.handlers } // propose-mode actions (+ any `handlers` given): run on this device after the member approves
2730
+ this._reads = built.reads // await-mode actions: run on this device DURING the turn, the result goes back to it
2731
+ this._guidance = built.guidance
2732
+ this._keepsProposals = true // off() never stops it (V#14)
2733
+ if (!this._pendingTimer && !this._hostDriven) this._pendingTimer = setInterval(() => this._pollPending(), 1500) // a lane always listens for proposals
2734
+ if (!this._hostDriven) setTimeout(() => this._pollPending(), 0) // and asks ONCE right away (2026-09-26): a proposal already waiting is on screen at open, not 1.5 s later. Next tick, not now: the caller attaches its `proposal` listener right after `new Lane(...)`, and an emit inside the constructor would fire before it
2735
+ // RESUMED WITH OUTSIDE-AGENT TASKS WAITING (sync sweep 10-26 #8): lane.a2a is built now — it watches for the drafts still
2736
+ // coming and sends an 'auto' peer's — not only once the page reads lane.a2a; a draft for the member waits for the 'a2a' listener
2737
+ if (this._a2aResume && this._a2aResume.length) void this.a2a
2738
+ }
2739
+
2740
+ /** Replace the STANDING actions (what every turn is offered) while keeping every handler ever registered — a card
2741
+ * approved after a reload still finds its handler. `setActions([])` leaves the lane offering nothing until a turn
2742
+ * brings its own `tools`. (2026-09-26: builders used to set lane._clientTools = [] for this.) */
2743
+ setActions(actions = []) {
2744
+ const built = buildActions(actions)
2745
+ this._clientTools = built.defs
2746
+ this._guidance = built.guidance
2747
+ Object.assign(this._writes, built.handlers); Object.assign(this._reads, built.reads)
2748
+ return this
2749
+ }
2750
+
2751
+ /** Post a private message to your assistant. Its reply is private; anything it wants the shared room to see, or any
2752
+ * effectful action, it must PROPOSE (→ the `proposal` event) — the member approves before it happens. */
2753
+ async send(text, { from = 'You', mode, tools, dictation, replace = false, instructions, images, files, links, stopKey, showPrompt, replyTo, _onAttempt, _aborted, _linkPost, _peerPost, _noHold } = {}) {
2754
+ if (this._feed) this._feed.sent() // a new turn: its own words are never held back by the previous answer (turnFeed.js; sync sweep 10-16 #10)
2755
+ { const f = arguments[1] && arguments[1].from; if (!_linkPost && !_peerPost && typeof f === 'string' && f.trim() && f.trim().toLowerCase() !== 'you') this._memberName = f.trim().slice(0, 80) } // the name this member uses — a crossing they approve lands under it (never a linked room's or an outside agent's post: _linkPost, _peerPost)
2756
+ // PER-TURN TOOLS (2026-09-25): `tools` takes the same action shape the constructor takes, offered for THIS turn only
2757
+ // — a builder whose actions depend on the subject of the conversation (views vs skills) no longer has to reach
2758
+ // into _client.turn. Defs and guidance ride beside the standing ones (a per-turn action with a standing action's
2759
+ // name wins for the turn); the handlers are registered so a proposal or an in-turn read for them can run.
2760
+ // `replace: true` (2026-09-26): the turn is offered ONLY `tools` — a skill runs with its own set — while every
2761
+ // standing handler stays registered, so a proposal approved later still runs. `replace` with no tools ⇒ no tools.
2762
+ let defs = this._clientTools, guidance = this._guidance
2763
+ if (replace) { defs = []; guidance = '' }
2764
+ // LINKED LANES (sdkLaneLink.js): while this lane is linked, every turn is offered tell_lane — `replace` included, since
2765
+ // an answer the other assistant sends back must still be able to reach the member through this one.
2766
+ const linkTool = laneLinkTool(this)
2767
+ if (linkTool && !defs.some((d) => d.name === 'tell_lane')) { defs = [...defs, linkTool.def]; guidance = [guidance, linkTool.guidance].filter(Boolean).join(' ') }
2768
+ if (Array.isArray(tools) && tools.length) {
2769
+ const extra = buildActions(tools)
2770
+ if (extra.defs.length) {
2771
+ const names = new Set(extra.defs.map((d) => d.name))
2772
+ defs = [...defs.filter((d) => !names.has(d.name)), ...extra.defs]
2773
+ Object.assign(this._writes, extra.handlers); Object.assign(this._reads, extra.reads)
2774
+ guidance = [guidance, extra.guidance].filter(Boolean).join(' ')
2775
+ }
2776
+ }
2777
+ if (defs.length > LIMITS.actions) throw limitError(`${defs.length} actions offered to this turn; the limit is ${LIMITS.actions} per turn — the rest would be dropped (register as many as you like; offer at most ${LIMITS.actions} with send's { tools, replace })`)
2778
+ const opts = await this._turnOpts(mode, {
2779
+ ...this._bridgeOpts(), // the lane observes the shared room + can cross into it (keyless: the worker holds the shared room's key)
2780
+ ...this._linksOpt(links),
2781
+ ...(defs.length ? { clientTools: defs, clientGuidance: guidance } : {}),
2782
+ ...perTurn(instructions), // this reply only, never stored — see Space.send
2783
+ ...stopOpt(stopKey),
2784
+ ...promptOpt(showPrompt),
2785
+ })
2786
+ const msg = withMedia({ from, text: String(text), ...(dictation ? { voice: voiceForDictation(dictation, this.room) } : {}) }, images, files)
2787
+ { const rt = replyRef(replyTo); if (rt) msg.replyTo = rt }
2788
+ await this.safeMedia._prepare(msg)
2789
+ const r = await this._turnHeld(() => this._provenTurn(msg, opts), _onAttempt, _aborted, _noHold) // held + resent while the assistant is busy — see Space._turnHeld; with your app's proof where the room requires it, as Space.send (sync sweep 11-09 #18)
2790
+ this._kick()
2791
+ if (r && r.ok) this._askName() // a lane is named like any room: the app's roomTitle.js does not skip lanes (sync sweep, 2026-10-10)
2792
+ return r
2793
+ }
2794
+
2795
+ /** ONE LANE, SEVERAL ROOMS (2026-10-02). Besides the shared Space it crosses into, a lane's assistant can READ other
2796
+ * rooms the member holds — a person in two teams has one lane that sees both. `setLinks([spaceB, { space: spaceC,
2797
+ * label: 'Design team' }])` sets them for every turn; `send(text, { links })` replaces them for one turn. The
2798
+ * assistant gets the last messages of each, read-only; it can cross only into the lane's own shared Space. Each
2799
+ * linked room applies ITS OWN gate: a gated room is read only when the signed-in member is on its list. Same tier
2800
+ * only — a confidential room cannot be read from a standard lane, or the reverse. */
2801
+ setLinks(links = []) { this._links = this._normLinks(links); return this }
2802
+
2803
+ async linkKept(space, opts = {}) {
2804
+ if (!(space instanceof Space) || space._sharedRoom) throw sdkError('witbitz: linkKept needs an always-on Space', 'invalid_argument')
2805
+ if (this._wb && this._wb.vault) return this._wb.vault._c.roomAccount(this.room, 'keptAgent', 'link', space.room, opts)
2806
+ return linkKeptAgent(this, space, opts)
2807
+ }
2808
+ async unlinkKept(space, link) {
2809
+ if (!(space instanceof Space) || space._sharedRoom) throw sdkError('witbitz: unlinkKept needs its kept Space', 'invalid_argument')
2810
+ if (this._wb && this._wb.vault) return this._wb.vault._c.roomAccount(this.room, 'keptAgent', 'unlink', space.room, link)
2811
+ return unlinkKeptAgent(this, space, link)
2812
+ }
2813
+
2814
+ /** LINK TWO OF THE MEMBER'S LANES (2026-10-03): each assistant can ask the other with `tell_lane`, asynchronously — the
2815
+ * question crosses framed, the other assistant is woken to answer, and the answer comes back and wakes this one. All
2816
+ * on this device, while both lanes are open here. `to` is what THIS assistant calls the other, `as` what the other
2817
+ * calls this one; `cap` bounds a chain of assistants asking each other (default 3, 0 = none). → a link with
2818
+ * `unlink()`, `run()` and `state` (pass it back as `resume` after a reload). Lanes of either tier. */
2819
+ link(other, { to, as, cap, resume } = {}) {
2820
+ if (!(other instanceof Lane)) throw sdkError('witbitz: link takes another private Lane, not a shared Space', 'not_a_lane')
2821
+ const l = linkLanes(this, other, { to, as, cap, resume }, { tierMismatch })
2822
+ const acct = this._wb && this._wb.account
2823
+ if (acct && acct.enabled && typeof acct._noteLink === 'function') { acct._noteLink(this.room, other.room, l.cap); l._onUnlink = () => acct._dropLink(this.room, other.room) }
2824
+ return l
2825
+ }
2826
+
2827
+ _normLinks(links) {
2828
+ if (!Array.isArray(links)) throw sdkError('witbitz: links takes an array of Spaces (or { space, label })', 'invalid_argument')
2829
+ if (links.length > LIMITS.links) throw limitError(`${links.length} linked rooms; the limit is ${LIMITS.links}`)
2830
+ const enc = this._isEnclave()
2831
+ return links.map((x, i) => {
2832
+ const sp = x instanceof Space ? x : (x && x.space)
2833
+ if (!(sp instanceof Space) || !sp.room || !(sp._mk || (this._client && this._client.vault))) throw sdkError(`witbitz: links[${i}] is not a Space (from openSpace or createSpace)`, 'invalid_argument')
2834
+ if (sp.room === this.room) throw sdkError(`witbitz: links[${i}] is this lane itself`, 'invalid_argument')
2835
+ if (sp._isEnclave() !== enc) throw tierMismatch(enc ? 'this lane is confidential and the linked room is not' : 'the linked room is confidential and this lane is not')
2836
+ const label = x instanceof Space ? undefined : (x.label ? String(x.label).slice(0, 80) : undefined)
2837
+ return { room: sp.room, ...(sp._mk ? { mk: sp._mk } : {}), ...(label ? { label } : {}) } // no key in a vault: its worker fills it by room
2838
+ })
2839
+ }
2840
+
2841
+ _linksOpt(perTurn) {
2842
+ const list = perTurn !== undefined ? this._normLinks(perTurn) : (this._links || [])
2843
+ return list.length ? { links: list } : {}
2844
+ }
2845
+
2846
+ /** THE MIRROR (2026-10-02) — the SDK twin of the app's mirrorLoop.js. With `mirror: true` (privateLane / openLane),
2847
+ * this device copies the shared Space's messages into the lane as they arrive, so the lane's OWN ledger holds the
2848
+ * whole shared history and its assistant reads it like any other history — not just the newest 20 the server shows a
2849
+ * lane turn. Each copy arrives on the lane as a message with `source: 'shared'` and an `sh:` id — `isLaneCopy(m)` (filter those out to keep a lane UI
2850
+ * private-only). Only this device can do it: it holds both keys, and the server never joins the two rooms. It runs
2851
+ * while both handles are open; a lane reopened later catches up from its cursor. Attachments cross as bytes, stored
2852
+ * again under the lane's key (a pointer sealed to the shared room would never open here). */
2853
+ async mirrorNow() { return this._runMirror() }
2854
+
2855
+ _scheduleMirror() {
2856
+ if (!this._mirrorFrom || this._mirrorFrom._stopped || this._stopped) return
2857
+ clearTimeout(this._mirrorTimer)
2858
+ this._mirrorTimer = setTimeout(() => { this._runMirror().catch(() => {}) }, 250) // a burst of messages → one pass
2859
+ }
2860
+
2861
+ async _runMirror() {
2862
+ this._checkShared()
2863
+ const from = this._mirrorFrom
2864
+ const attached = () => { this._checkShared(); return this._mirrorFrom === from && !from._stopped && !this._stopped }
2865
+ if (!from || from._stopped || this._stopped) return { mirrored: 0 }
2866
+ if (this._mirrorInFlight) { this._mirrorAgain = true; return { mirrored: 0 } }
2867
+ this._mirrorInFlight = true
2868
+ let sent = 0
2869
+ try {
2870
+ const canReadConfig = typeof from._client.getConfig === 'function'
2871
+ const cfg = canReadConfig ? await from._client.getConfig(from.room, from._mk, { plainMark: true }) : {}
2872
+ if (!cfg || gatedStub(cfg)) return { mirrored: 0 }
2873
+ if (cfg.lanes === false) { from._lanesSetting = false; this._detachShared(); return { mirrored: 0 } }
2874
+ const all = (from.messages || []).filter((e) => e && !e.sys && e.kind !== 'fork' && (e.text || (Array.isArray(e.files) && e.files.length) || (Array.isArray(e.images) && e.images.length)))
2875
+ if (from._more || !(from._historyRead || from._hostDriven)) return { mirrored: 0 } // not the whole shared history yet (a failed page leaves _more false) // the shared room is still loading its pages: a cursor past what has arrived is not another history
2876
+ if (this._mirrorCursor > all.length) this._mirrorCursor = 0 // a cursor from another history: start over; the server's id-dedup makes it a resend, never a double
2877
+ const copyEntry = async e => ({
2878
+ sourceRoom: from.room,
2879
+ id: 'sh:' + (e.id || ('t' + e.ts)), // the entry id alone, no room prefix — stable across a fork (the app's rule)
2880
+ from: e.name || e.from || 'party', ...(e.self === true ? { self: true } : {}), ...(e.md === true ? { md: true } : {}),
2881
+ ...(typeof e.fr === 'string' ? { fr: e.fr, frRoom: from.room } : {}), // the Space's franking record + which Space: a report of the copy names the ORIGINAL (the app's mirrorLoop.js; sync sweep 11-19 P1)
2882
+ ...mirrorBy(from.room, e), // WHO WROTE IT, as the Space verified them — Block collapses their copy in the lane too (the app's mirrorLoop.js byOf; sync sweep 11-08)
2883
+ ...(Number.isFinite(e.ts) ? { ts: e.ts } : {}), ...(e.replyTo && e.replyTo.key ? { replyTo: e.replyTo } : {}), // when it was said, and what it answers (sync sweep, 2026-10-10)
2884
+ text: e.text, files: await withBytes(from, e.files), images: await withBytes(from, e.images),
2885
+ ...(e.removedByWitbitz ? { sourceRemoved: true } : {}),
2886
+ })
2887
+ while (this._mirrorCursor < all.length && !from._stopped && !this._stopped) {
2888
+ const slice = all.slice(this._mirrorCursor, this._mirrorCursor + 25)
2889
+ const batch = this._mirrorData ? slice : slice.filter((e) => e.kind !== 'data')
2890
+ if (!batch.length) { this._mirrorCursor += slice.length; continue }
2891
+ const entries = await Promise.all(batch.map(copyEntry))
2892
+ // A REFUSAL THAT THROWS is still a refusal (sync sweep 11-16 #16): a vault refuses an attested Space's copy into an ordinary
2893
+ // lane by throwing, and the timer's catch swallowed it — every message tried again, silently. Said once, like the others.
2894
+ let r
2895
+ if (from._stopped || this._stopped) break
2896
+ if (!attached()) return { mirrored: sent }
2897
+ try { r = await this._client.mirror(this.room, this._mk, entries) } catch (e) { r = { status: 0, error: String((e && e.code) || 'mirror_failed'), reason: String((e && e.message) || '').replace(/^witbitz: /, '').slice(0, 300) } }
2898
+ if (!r || r.status !== 200) { // the cursor holds; the next pass retries — said ONCE per distinct refusal, as the poll does (sync sweep, 2026-10-10)
2899
+ const key = String((r && (r.error || r.status)) || 'no_answer'); if (this._mirrorRefusal !== key) { this._mirrorRefusal = key; this._emit('error', refused('mirror', r)) }
2900
+ break
2901
+ }
2902
+ this._mirrorRefusal = null
2903
+ this._mirrorCursor += slice.length; sent += batch.length
2904
+ }
2905
+ // CAPTION CATCH-UP (the app's rule, mirrorLoop.js): a shared photo is described by the shared room's assistant AFTER
2906
+ // it first crossed. Once the description lands, re-send it as a description-only patch so the lane's assistant gets
2907
+ // what the shared room has. Recent entries, once per id (sync sweep, 2026-10-10 — the SDK never sent it).
2908
+ if (!this._stopped && !from._stopped) {
2909
+ this._removalsMirrored = this._removalsMirrored || new Set()
2910
+ const removed = all.filter((e) => e.removedByWitbitz && (!from._removedMessages || from._removedMessages.has(removedEntryKey(e))) && !this._removalsMirrored.has(removedEntryKey(e)))
2911
+ for (let i = 0; i < removed.length && !from._stopped && !this._stopped; i += 25) {
2912
+ const batch = removed.slice(i, i + 25), patches = batch.map((e) => ({ id: 'sh:' + e.id, ts: e.ts, sourceRoom: from.room, sourceRemoved: true }))
2913
+ if (!attached()) return { mirrored: sent }
2914
+ const r = await this._client.mirror(this.room, this._mk, patches)
2915
+ if (!r || r.status !== 200) break
2916
+ if (!Array.isArray(r.sourceRemovals)) {
2917
+ if (!this._removalUnsupported) { this._removalUnsupported = true; this._emit('error', sdkError('witbitz: this server did not acknowledge source removals; the mirror will retry', 'mirror_removal_unsupported')) }
2918
+ break
2919
+ }
2920
+ this._removalUnsupported = false
2921
+ for (const e of batch) if (r.sourceRemovals.some((a) => a && a.id === 'sh:' + e.id && a.ts === e.ts)) {
2922
+ this._removalsMirrored.add(removedEntryKey(e))
2923
+ this._removedSourceMessages = this._removedSourceMessages || new Map()
2924
+ const target = { id: 'sh:' + e.id, ts: e.ts }, key = removedEntryKey(target)
2925
+ this._removedSourceMessages.set(key, target)
2926
+ const cur = this.messages.find((m) => removedEntryKey(m) === key)
2927
+ if (cur) for (const u of this._view.apply([sharedRemovedCopy(cur)]).updated) this._emit('update', { id: u.id, message: u.entry, fields: u.fields })
2928
+ }
2929
+ this._kick()
2930
+ }
2931
+ // A cleared moderation list triggers a fresh source read. Cached message text is never a restoration.
2932
+ const hiddenCopies = new Set(this.messages.filter(e => e.sourceRemoved).map(removedEntryKey))
2933
+ const candidates = all.filter(e => hiddenCopies.has(removedEntryKey({ id: 'sh:' + e.id, ts: e.ts })) && !from._removedMessages?.has(removedEntryKey(e)))
2934
+ if (candidates.length && attached()) {
2935
+ const history = await from._roomHistory()
2936
+ if (!history.incomplete && Array.isArray(history.removed)) {
2937
+ const hidden = new Set(history.removed.map(removedEntryKey))
2938
+ const wanted = new Set(candidates.map(removedEntryKey))
2939
+ const originals = history.entries.filter(e => wanted.has(removedEntryKey(e)) && !hidden.has(removedEntryKey(e)) && !e.removedByWitbitz && e.kind !== 'fork')
2940
+ for (let i = 0; i < originals.length; i += 25) {
2941
+ const entries = await Promise.all(originals.slice(i, i + 25).map(copyEntry))
2942
+ if (!attached()) break
2943
+ const r = await this._client.mirror(this.room, this._mk, entries.map(e => ({ ...e, restoreSource: true })))
2944
+ if (r?.status !== 200) break
2945
+ for (const e of r.sourceRestorations || []) {
2946
+ this._removedSourceMessages?.delete(removedEntryKey(e))
2947
+ this._removalsMirrored.delete(removedEntryKey({ id: e.id.slice(3), ts: e.ts }))
2948
+ }
2949
+ if (r.sourceRestorations?.length) { this._count = 0; this._etag = null; this._kick() }
2950
+ }
2951
+ }
2952
+ }
2953
+ this._descMirrored = this._descMirrored || new Set()
2954
+ const patches = []
2955
+ for (const e of all.slice(-40)) {
2956
+ if (!(e && Array.isArray(e.images) && e.images.some((i) => i && typeof i.desc === 'string' && i.desc.trim()))) continue
2957
+ const key = 'sh:' + (e.id || ('t' + e.ts))
2958
+ if (this._descMirrored.has(key)) continue
2959
+ patches.push({ id: key, from: e.name || e.from || 'party', images: e.images.map((i) => (i && typeof i.desc === 'string' && i.desc.trim() ? { desc: String(i.desc).slice(0, 2000) } : {})) })
2960
+ }
2961
+ if (patches.length && attached()) { const r = await this._client.mirror(this.room, this._mk, patches).catch(() => null); if (r && r.status === 200) for (const p of patches) this._descMirrored.add(p.id) }
2962
+ }
2963
+ // THE SHARED ROOM'S VIEWS (sharedViews.js): this handle holds both keys, so it reads the shared room's itinerary and
2964
+ // map docs and writes them, as text, into the lane's `sharedviews` doc — the lane's turn reads it. Only on a change.
2965
+ if (!from._stopped && !this._stopped && typeof this._client.state === 'function' && Date.now() - (this._viewsAt || 0) > 15_000) { // at most every 15 s: a busy room must not re-read every view on every message
2966
+ this._viewsAt = Date.now()
2967
+ try {
2968
+ const views = []
2969
+ for (const v of viewsNamedIn(from.messages)) { const d = await this._client.state(from.room, from._mk, v.name).catch(() => null); if (!d?.state || (d.status && d.status !== 200)) return; views.push({ label: v.label, state: d.state }) }
2970
+ const text = renderSharedViews(views)
2971
+ if (attached() && (text !== this._sharedViews || this._sharedViewsSource !== from.room)) { const r = await this._client.state(this.room, this._mk, SHARED_VIEWS_DOC, { source: from.room, text }, text.slice(0, 200), 'device'); if (r && r.status === 200) { this._sharedViews = text; this._sharedViewsSource = from.room } }
2972
+ } catch { /* never break the mirror */ }
2973
+ }
2974
+ } finally {
2975
+ this._mirrorInFlight = false
2976
+ if (this._mirrorAgain) { this._mirrorAgain = false; this._scheduleMirror() }
2977
+ }
2978
+ if (sent) this._kick()
2979
+ return { mirrored: sent }
2980
+ }
2981
+
2982
+ snapshot() {
2983
+ const a2a = pendingOf(this._a2a ? this._a2a._pending : this._a2aResume) // waiting outside-agent tasks ride along (sync sweep 10-24 #17)
2984
+ return { ...super.snapshot(), ...(this._mirrorFrom ? { mirrored: this._mirrorCursor } : {}), ...(a2a.length ? { a2a } : {}) }
2985
+ }
2986
+
2987
+ close() {
2988
+ this._wb?._openLanes?.delete(this)
2989
+ for (const off of this._sharedOffs || []) { try { off() } catch { /* */ } }
2990
+ this._sharedOffs = []
2991
+ for (const l of [...(this._laneLinks || [])]) l._stop() // stops here; the link itself (in wb.account) stays
2992
+ if (this._mirrorFrom && this._mirrorSub) for (const ev of ['message', 'update']) { const l = this._mirrorFrom._subs[ev]; if (l) { const i = l.indexOf(this._mirrorSub); if (i >= 0) l.splice(i, 1) } }
2993
+ clearTimeout(this._mirrorTimer); clearInterval(this._viewsTick)
2994
+ if (this._ownsSharedSpace && this._sharedSpace) { try { this._sharedSpace.close() } catch { /* */ } } // a Space vault.openRoom(laneId) opened for it
2995
+ return super.close()
2996
+ }
2997
+
2998
+ /** @private the bridge to its Space — none across tiers (a confidential room's key never rides the standard tier). */
2999
+ _detachShared() {
3000
+ if (!this._sharedRoom) return
3001
+ for (const off of this._sharedOffs || []) { try { off() } catch {} }
3002
+ this._sharedOffs = []
3003
+ if (this._mirrorFrom && this._mirrorSub) for (const ev of ['message', 'update']) {
3004
+ const listeners = this._mirrorFrom._subs?.[ev], index = listeners?.indexOf(this._mirrorSub) ?? -1
3005
+ if (index >= 0) listeners.splice(index, 1)
3006
+ }
3007
+ if (this._ownsSharedSpace) this._sharedSpace?.close()
3008
+ this._sharedRoom = null; this._sharedMk = null; this._mirrorFrom = null; this._sharedSpace = null
3009
+ clearTimeout(this._mirrorTimer); clearInterval(this._viewsTick)
3010
+ this._emit('disconnected', { reason: 'lanes_disabled' })
3011
+ }
3012
+ _checkShared() {
3013
+ if (!this._sharedRoom) return
3014
+ const rec = this._wb?.backup?.rooms?.find(r => r.room === this.room)
3015
+ if (rec && (rec.kind !== 'lane' || (rec.shared && rec.shared !== this._sharedRoom))) this._detachShared()
3016
+ }
3017
+ _bridgeOpts() { this._checkShared(); if (!this._sharedRoom) return {}; return this._crossTier ? { viewSource: this._sharedRoom } : { ...(this._sharedMk ? { bridgeMk: this._sharedMk } : {}), bridgeRoom: this._sharedRoom } }
3018
+ _runExtra() { return { ...this._bridgeOpts(), ...this._linksOpt() } } // sync sweep, 2026-10-10: Lane.run had no bridge, then no linked rooms
3019
+ _decideExtra() { return this._bridgeOpts() } // keyless: the worker holds the shared room's key // a crossing posts into the shared room on approve
3020
+ }
3021
+
3022
+ // THE ROOM AS A STORE — the device-side replay, the same reducer the agent's data_query runs server-side
3023
+ // (agent/dataTools.mjs rowsFromEntries): puts upsert, deletes remove, in ledger order.
3024
+ function applyDataEntry(rows, e) {
3025
+ for (const o of e.ops) {
3026
+ if (!o || !o.collection) continue
3027
+ const c = String(o.collection)
3028
+ let m = rows.get(c); if (!m) { m = new Map(); rows.set(c, m) }
3029
+ if (o.op === 'del') m.delete(String(o.id))
3030
+ else if (o.op === 'put' && o.row && typeof o.row === 'object') m.set(String(o.id), { row: ownFields(o.row), updated: Number(e.ts) || 0, by: e.name || '', v: typeof e.id === 'string' ? e.id : '', ...stampsOf(e) }) // v: the entry that last wrote the row (⇄ the server's rowsFromEntries)
3031
+ }
3032
+ }
3033
+
3034
+ // `_verified` / `_user` on a row: set only when the SERVER stamped the write — its author passed the room's email gate
3035
+ // (agent/spaceService.mjs data op). `_by` stays the name the writer chose, a claim; these two are not.
3036
+ // Absent, not false, on an unmarked row, so a row's shape is unchanged for rooms with no email gate.
3037
+ // `_email`: the writer's VERIFIED email, stamped beside `_verified` (most members have no @username). `_carriedBy`: the
3038
+ // verified email of the member who carried the row here (a fork). `_carried`: the room the row was written in and the marks
3039
+ // the server gave it THERE ({ from, verified?, user?, email? }) — set when the server carried the move (op 'carry'); a
3040
+ // device's carry keeps none. Every one of these comes from the server's stamp on the ledger entry, never from the row.
3041
+ function rowMarks(v) {
3042
+ return { ...(v.verified === true ? { _verified: true, ...(v.user ? { _user: v.user } : {}), ...(v.email ? { _email: v.email } : {}) } : {}), ...(v.carriedBy ? { _carriedBy: v.carriedBy } : {}), ...(v.carried ? { _carried: v.carried } : {}) }
3043
+ }
3044
+ /** The server's stamps on an entry (or a resumed row), each only in the shape the server writes it. */
3045
+ function stampsOf(e) {
3046
+ const ok = (x) => typeof x === 'string' && x
3047
+ const c = e.carried && typeof e.carried === 'object' && ok(e.carried.from) ? e.carried : null
3048
+ return { ...(e.verified === true ? { verified: true, ...(ok(e.user) ? { user: e.user } : {}), ...(ok(e.email) ? { email: e.email } : {}) } : {}), ...(ok(e.carriedBy) ? { carriedBy: e.carriedBy } : {}), ...(c ? { carried: { from: c.from, ...(c.verified === true ? { verified: true, ...(ok(c.user) ? { user: c.user } : {}), ...(ok(c.email) ? { email: c.email } : {}) } : {}) } } : {}) }
3049
+ }
3050
+ // RESERVED row fields (⇄ agent/dataTools.mjs reservedRowFields): `id` is the row's key and `_` names are the marks above.
3051
+ // A row is read WITHOUT them — a row stored before the server refused them must not pose as the server's stamp.
3052
+ const isReserved = (k) => k === 'id' || k.startsWith('_')
3053
+ function ownFields(row) { return Object.fromEntries(Object.entries(row || {}).filter(([k]) => !isReserved(k))) }
3054
+
3055
+ export default Witbitz
3056
+
3057
+ // ── The account half: session helpers, connections, the Siri inbox ──────────────────────────────────────────────
3058
+ /** `{ emails?, domains? }` → the sealed config's `admission` + `allow`, or null for an OPEN Space.
3059
+ *
3060
+ * The gate and the allow-list ride INSIDE the sealed config, so the platform can read that a room is gated and never
3061
+ * who is admitted. Validation is here rather than at the first refused read because an allow-list that admits nobody
3062
+ * locks the CREATOR out too, and a room cannot be converted afterwards — the cheapest place to catch that is the call. */
3063
+ /** `tier` → is this the confidential (enclave) tier? A typo must not silently mint a PLAIN room that a builder then
3064
+ * believes is confidential — so anything unrecognised throws. */
3065
+ const tierIsEnclave = (tier) => {
3066
+ if (tier === undefined || tier === null || tier === 'standard') return false
3067
+ if (tier === 'enclave' || tier === 'confidential') return true
3068
+ throw sdkError(`witbitz: unknown tier ${JSON.stringify(tier)} — 'enclave' or 'standard'`, 'invalid_argument')
3069
+ }
3070
+
3071
+ const tierMismatch = (why) => { const e = new Error(`witbitz: a lane and the rooms it reads must be on the same tier — ${why}. Open both from links of the same tier (an enclave link carries #enc=1).`); e.code = 'tier_mismatch'; return e }
3072
+
3073
+ /** ★ AN ENCLAVE ROOM'S LINK SAYS SO. Enclave-ness lived only in `_enc.rooms`, an in-memory Map on the client that
3074
+ * created the room, so a FRESH client — a builder's app on every launch — treated the room as standard, talked to the
3075
+ * standard relay and got `404 create_required` (reported 2026-09-27). The app has the same Map plus two things a
3076
+ * builder's client has not: a durable copy in the account's room list, and an open-time probe. A fresh client holds
3077
+ * only the link, so the link is where the marker belongs; the fragment already carries `gate=email` (and `lanes=1` for a room that gives every member a private lane, createSpace({ lanes })).
3078
+ * Unknown fragment keys are ignored by every existing reader, so an older client is unaffected. */
3079
+ const ENC_MARK = /[?#&]enc=1(?:[&#]|$)/ // in the fragment (markEncLink) OR the query: the hosted vault marks a link it hands the cloud device `…&enc=1#us=…` (vault-loader encLink) — read as standard until 2026-11-25
3080
+ const markEncLink = (l) => (ENC_MARK.test(String(l)) ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'enc=1')
3081
+ /** An email-gated room's link says so too (the app's own convention, inviteLinks.js): a client opening it knows to sign
3082
+ * in, and the SDK knows to announce its device in the room's guest book (see Space#fork). Never sent to the server. */
3083
+ const GATE_MARK = /[#&]gate=email(?:&|$)/
3084
+ const markGateLink = (l) => (GATE_MARK.test(String(l)) ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'gate=email')
3085
+ /** A room that gives every member a private assistant: its link says so (the app's grammar, inviteLinks.js `&lanes=1`). */
3086
+ const LANES_MARK = /[#&]lanes=1(?:&|$)/
3087
+ const markLanesLink = (l) => (LANES_MARK.test(String(l)) ? String(l) : String(l) + (String(l).includes('#') ? '&' : '#') + 'lanes=1')
3088
+ /** SPLIT-KEY links (https://witbitz.chat/docs/sdk-keys.md#split-key) — the app's own grammar (inviteLinks.js): `#us=<userShare>&spc=<commit>` in
3089
+ * place of `#mk=`. The link is HALF a key; the other half comes only to a page on an origin the room's tenant declared. */
3090
+ const SPLIT_MARK = /[#&]us=/
3091
+ const GRANT_BACKOFF_MS = [2000, 4000, 8000, 16000, 32000, 60000] // = l1.js STALE_BACKOFF_MS
3092
+ const splitLinkOf = (link, userShare, commit) => String(link).split('#')[0] + '#us=' + encodeURIComponent(userShare) + (commit ? '&spc=' + encodeURIComponent(commit) : '')
3093
+ const fragParam = (link, k) => { const m = new RegExp('[#&]' + k + '=([^&]*)').exec(String(link)); return m ? decodeURIComponent(m[1]) : '' }
3094
+ const splitKeyChoice = (key) => {
3095
+ if (key === undefined || key === null || key === 'standard') return false
3096
+ if (key === 'split') return true
3097
+ throw sdkError(`witbitz: unknown key ${JSON.stringify(key)} — 'split' or 'standard'`, 'invalid_argument')
3098
+ }
3099
+ /** The room id straight from the link's query — needed BEFORE `open()` is called, because on an enclave room the open
3100
+ * itself is the request that must already be routed to the enclave. */
3101
+ const roomFromLink = (l) => { const m = /[?&]room=([^&#]+)/.exec(String(l)); return m ? decodeURIComponent(m[1]) : '' }
3102
+
3103
+ /** ONE config builder for BOTH a shared Space and a private lane. They were built by two separate pieces of code and
3104
+ * drifted: a lane could not declare `data`, so its assistant truthfully reported having no data_query (a builder hit
3105
+ * this on the confidential tier, 2026-09-27). ★ A lane always HAD tools — `spaceService` gives every room the platform
3106
+ * set, plus cross_to_shared on a bridged lane, plus its `actions`; what a lane could not have was the two
3107
+ * CONFIG-BORNE sources, the builder's own `tools`/`immediateTools` and `dataSchema`. The owner's rule is that a lane
3108
+ * is exactly a room, so the shape is built here once and neither caller may grow a field the other lacks.
3109
+ * `gate` is passed in already normalised, so an invalid admission still throws before anything else is decided.
3110
+ * `defaults` carries the only two things that legitimately differ: the assistant's name and its fallback persona. */
3111
+ /** createSpace({ direct }): the gate a direct chat is made with — the signed-in member and one other address, both shown,
3112
+ * the member its owner (the app's New Space with one person and no name). */
3113
+ /** How a page signs in: in a vault the vault does it (wb.vault.signIn) — the error must name the call that works there (sync sweep, 10-16). */
3114
+ const signInHow = (wb) => (wb && wb.vault ? 'wb.vault.signIn' : 'wb.signIn') // the call that signs in HERE (sync sweep 10-20 #11: in a vault it is the vault's)
3115
+ function directAdmission(direct, admission, sess, signIn = 'wb.signIn') {
3116
+ if (admission !== undefined) throw sdkError('witbitz: a direct chat sets its own members — pass direct OR admission, not both')
3117
+ const me = sess && sess.email && !(sess.exp && sess.exp <= Date.now()) ? String(sess.email).trim().toLowerCase() : ''
3118
+ if (!me) throw sdkError('witbitz: a direct chat needs a signed-in member (' + signIn + ')', 'sign_in_required')
3119
+ const peer = String(direct || '').trim().toLowerCase()
3120
+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(peer)) throw sdkError('witbitz: direct takes the other person\'s email address')
3121
+ if (peer === me) throw sdkError('witbitz: a direct chat is with someone else — for a room of your own, use admission: { emails: [you] }')
3122
+ return { emails: [me, peer], advertise: true, owners: [me] }
3123
+ }
3124
+
3125
+ function roomConfig({ agent = {}, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, defaults) {
3126
+ checkDataSchema(data) // refuse what the server would cut, drop or rename — see LIMITS
3127
+ // `write: 'admins'` means nothing in a room with no admins or owners: the server enforces it only where there are some
3128
+ // (spaceService hasAdmins), so every member would write it. Refused here rather than accepted and ignored (sync sweep, 2026-10-10).
3129
+ checkAdminCollections(data, gate)
3130
+ const pt = platformToolsOpt(platformTools)
3131
+ const fr = framingOpt(framing)
3132
+ const t = tools || agent.tools
3133
+ return {
3134
+ agentName: (agent.name || defaults.agentName).slice(0, 80),
3135
+ persona: String(agent.instructions || agent.persona || defaults.persona).slice(0, 4000),
3136
+ ...(Array.isArray(t) && t.length ? { tools: t } : {}),
3137
+ ...(Array.isArray(immediateTools) && immediateTools.length ? { immediateTools } : {}),
3138
+ ...(model || agent.model ? { model: model || agent.model } : {}),
3139
+ ...(gate || {}), // email admission: the gate + the allow-list, sealed with the rest (undefined ⇒ an OPEN room, sealed exactly as before)
3140
+ ...(pt !== undefined ? { platformTools: pt } : {}), // which platform tools the assistant gets: absent = all, false = none, a list = only those
3141
+ ...(fr ? { framing: fr } : {}), // BUILDER MODE: the prompt is your instructions and tools only (sdk-assistant.md#builder-mode)
3142
+ ...(dataWrites === false ? { dataWrites: false } : {}), // the assistant reads the store (data_query) but proposes no writes
3143
+ ...(data && typeof data === 'object' ? { dataSchema: data } : {}), // THE ROOM AS A STORE: declared collections + field rules → the agent gets data_query / data_put / data_delete. On a LANE this is the LANE's OWN store, under the lane's own key — never the shared room's (deliberate, 2026-09-27: shared-collection reads are a separate feature).
3144
+ }
3145
+ }
3146
+
3147
+
3148
+ /** `framing` → 'builder' | undefined; anything else refused (a typo must not silently keep the Spaces framing). */
3149
+ function framingOpt(v) {
3150
+ if (v === undefined || v === null || v === 'spaces') return undefined
3151
+ if (v === 'builder') return 'builder'
3152
+ throw sdkError("witbitz: framing is 'builder' (your instructions and tools only) or omitted (the Spaces framing)", 'invalid_argument')
3153
+ }
3154
+
3155
+ /** `platformTools` → what the sealed config carries: undefined (all — the default), false (none) or a list of names. */
3156
+ function platformToolsOpt(v) {
3157
+ if (v === undefined || v === null || v === true) return undefined
3158
+ if (v === false) return false
3159
+ if (!Array.isArray(v) || v.some((n) => typeof n !== 'string' || !n || n.length > 64) || v.length > 64) throw Object.assign(new Error("witbitz: platformTools is true (all, the default), false (none) or a list of tool names, e.g. ['web_search', 'read_file']"), { code: 'bad_platform_tools' })
3160
+ return [...new Set(v)]
3161
+ }
3162
+
3163
+ const sessionOf = (x) => (x && typeof x === 'object' && typeof x.idToken === 'string' && x.idToken && typeof x.email === 'string')
3164
+ ? { email: String(x.email).toLowerCase(), idToken: x.idToken, exp: Number(x.exp) || 0, ...(x.sign && typeof x.sign === 'object' ? { sign: x.sign } : {}) } : null
3165
+ /** Was this room a private lane? The account's backup keeps a lane's kind even after it is re-added as a Space (sdkBackup.js
3166
+ * `wasLane`) — the SDK's record, as the app's is `space:lane-rooms`. Without the backup the SDK knows only the Lane handle. */
3167
+ function wasLaneRoom (wb, room) {
3168
+ try { const b = wb && wb.backup; if (!b || !b.enabled || !room) return false; const r = (b.rooms || []).find((x) => x && x.room === room); return !!(r && r.kind === 'lane') } catch { return false }
3169
+ }
3170
+ const siriStateOf = (x) => {
3171
+ const o = x && typeof x === 'object' ? x : {}
3172
+ const rooms = {}
3173
+ for (const [room, r] of Object.entries(o.rooms && typeof o.rooms === 'object' ? o.rooms : {})) {
3174
+ if (!r || typeof r !== 'object' || !r.alias || !r.pub || !r.priv) continue
3175
+ rooms[room] = { alias: String(r.alias), label: String(r.label || ''), pub: { x: r.pub.x, y: r.pub.y }, priv: r.priv, at: Number(r.at) || 0 }
3176
+ }
3177
+ return { token: typeof o.token === 'string' ? o.token : '', defaultRoom: typeof o.defaultRoom === 'string' && rooms[o.defaultRoom] ? o.defaultRoom : '', rooms }
3178
+ }
3179
+
3180
+ /** `wb.usernames` — the member's @username. One name means one person across ALL of Witbitz (not per app): it is
3181
+ * bound to the person's email-derived handle, and a room's email gate admits by it. Claim/release/mine act as the
3182
+ * signed-in member (the server derives who from the sign-in token, never from the page). `publish: true` also lists
3183
+ * the person in the public directory under that name; off by default. A released name is held for 30 days, and what
3184
+ * a member wrote keeps the `_user` it was stamped with. */
3185
+ // What console.log / JSON.stringify / util.inspect show (sdkRedact.js): the room, never its key or link. In a vault the
3186
+ // sign-in is the vault's (sweep 10-24 #10: it read signedIn: false there).
3187
+ redacted(Witbitz.prototype, (w) => ({ viewer: w._viewer, ...(w._tenant ? { tenant: w._tenant } : {}), signedIn: w.vault ? !!(w.vault.info && w.vault.info.signedIn) : !!(w._session && w._session.email), ...(w._tenantKey ? { tenantKey: REDACTED } : {}) }))
3188
+ redacted(Space.prototype, (sp) => ({ room: sp.room, shareLink: REDACTED, messages: Array.isArray(sp.messages) ? sp.messages.length : 0, ...(sp instanceof Lane ? { lane: true, sharedRoom: sp._sharedRoom || null } : {}) }))
3189
+
3190
+ class Usernames {
3191
+ constructor(wb) { this._wb = wb }
3192
+ async claim(name, { publish = false, name: display } = {}) {
3193
+ const { idToken } = this._wb._auth('a username belongs')
3194
+ const u = bareName(name)
3195
+ const r = await this._wb._client.userClaim(u, idToken, publish ? { publish: true, ...(display ? { name: display } : {}) } : {})
3196
+ if (!r || r.status !== 200) throw userError(r, `could not claim @${u}`)
3197
+ return { username: r.username || u }
3198
+ }
3199
+ async release() {
3200
+ const { idToken } = this._wb._auth('a username belongs')
3201
+ const r = await this._wb._client.userRelease(idToken)
3202
+ if (!r || r.status !== 200) throw userError(r, 'could not release the username')
3203
+ return { username: null }
3204
+ }
3205
+ /** → { username: string | null, published } */
3206
+ async mine() {
3207
+ const { idToken } = this._wb._auth('a username belongs')
3208
+ const r = await this._wb._client.userWhoami(idToken)
3209
+ if (!r || r.status !== 200) throw userError(r, 'could not read the username')
3210
+ return { username: r.username || null, published: r.published === true }
3211
+ }
3212
+ /** Is this @name taken? Public, rate-limited, no sign-in. → { username, exists } */
3213
+ async resolve(name) {
3214
+ const u = bareName(name)
3215
+ const r = await this._wb._client.userResolve(u)
3216
+ if (r && r.status === 404) return { username: u, exists: false }
3217
+ if (!r || r.status !== 200) throw userError(r, `could not look up @${u}`)
3218
+ return { username: r.username || u, exists: true }
3219
+ }
3220
+ }
3221
+ const bareName = (n) => String(n || '').trim().replace(/^@/, '').toLowerCase()
3222
+ const userError = (r, what) => Object.assign(new Error(`witbitz: ${what} (${(r && (r.message || r.error)) || (r && r.status) || 'no answer'})`), { code: (r && r.error) || 'user_failed', status: r && r.status })
3223
+
3224
+ /** In a vault the room keys and the account's session are the VAULT's. What needs either in the page is refused by name
3225
+ * (`vault_unsupported`) — it used to half-work: a backup that recorded nothing, "sign in first" while signed in, a crash,
3226
+ * a room list read as empty while the vault held Spaces. spaces/test/sdkVaultSurface.test.mjs holds every public member
3227
+ * to a decision. `keep`: the members that say something true about this page (a flag, a state to persist) and stay. */
3228
+ const vaultRefusal = (what) => sdkError(`witbitz: ${what} is not available in a vault yet`, 'vault_unsupported')
3229
+ function blockInVault(obj, what, keep = []) {
3230
+ if (!obj) return
3231
+ const names = new Set()
3232
+ for (let p = obj; p && p !== Object.prototype; p = Object.getPrototypeOf(p)) for (const k of Object.getOwnPropertyNames(p)) if (k !== 'constructor' && !k.startsWith('_') && !keep.includes(k)) names.add(k)
3233
+ for (const k of names) {
3234
+ let d = null
3235
+ for (let p = obj; p && !d; p = Object.getPrototypeOf(p)) d = Object.getOwnPropertyDescriptor(p, k)
3236
+ if (!d) continue
3237
+ if (d.get) { Object.defineProperty(obj, k, { get() { throw vaultRefusal(what) }, configurable: true }); continue }
3238
+ if (typeof d.value !== 'function') continue
3239
+ const isAsync = d.value.constructor && d.value.constructor.name === 'AsyncFunction'
3240
+ Object.defineProperty(obj, k, { value: isAsync ? () => Promise.reject(vaultRefusal(what)) : () => { throw vaultRefusal(what) }, configurable: true, writable: true })
3241
+ }
3242
+ }
3243
+ function refuseInVault(wb) {
3244
+ // THE ACCOUNT goes through the vault, which holds the sign-in (vault-core.js ACCOUNT_CALLS). The vault keeps what
3245
+ // must not reach the page — the session, the Siri inbox's private keys, each connection's callKey — and asks the person
3246
+ // before acting in their name.
3247
+ const conn = wb.vault._c
3248
+ // THE BACKUP, THE ACCOUNT INDEX AND THE ERASE LIST are the vault's (vault-core.js backupCall/accountCall): it records
3249
+ // every Space it holds, shows and takes the recovery code in its own screens, and keeps the index in step. The getters
3250
+ // read the vault's last VIEW of them (no link, no key, no master secret); `onChange` fires when it changes.
3251
+ wb._vaultAccount = (conn.info && conn.info.account) || { enabled: false, format: null, deviceId: '', rooms: [], devices: [], links: [], lastError: null, erasure: false }
3252
+ let accountGeneration = 0
3253
+ const view = () => wb._vaultAccount
3254
+ conn.on((ev) => {
3255
+ if (['signedOut', 'accountSignedOut', 'signedIn'].includes(ev?.ev) || (ev?.ev === 'account' && ev.view?.enabled !== view().enabled)) {
3256
+ wb._vaultGeneration = ++accountGeneration
3257
+ wb._vaultSiri = { key: null, hasKey: false, endpoint: wb._vaultSiri?.endpoint }
3258
+ if (ev.ev !== 'signedOut' && ev.ev !== 'accountSignedOut' && ev.view?.enabled !== false) {
3259
+ const generation = accountGeneration
3260
+ conn.account('siri', 'shortcut').then(value => { if (generation === accountGeneration) wb._vaultSiri = value }).catch(() => {})
3261
+ }
3262
+ for (const sec of Object.values(wb.account._sections || {})) sec._seen(null, true)
3263
+ }
3264
+ if (ev?.ev === 'accountSignedOut' && typeof wb.account.onSignedOut === 'function') {
3265
+ try { wb.account.onSignedOut(ev.reason ? { reason: ev.reason } : undefined) } catch { /* app callback */ }
3266
+ }
3267
+ if (ev && ev.ev === 'accountSection' && Object.prototype.hasOwnProperty.call(wb.account._sections || {}, ev.section)) { wb.account._sections[ev.section]._seen(ev.value, true); return }
3268
+ if (!ev || ev.ev !== 'account' || !ev.view) return
3269
+ const was = wb._vaultAccount; wb._vaultAccount = ev.view
3270
+ if (typeof wb.account.onChange === 'function' && JSON.stringify([was.rooms, was.devices, was.links]) !== JSON.stringify([ev.view.rooms, ev.view.devices, ev.view.links])) { try { wb.account.onChange({ rooms: ev.view.rooms, devices: ev.view.devices }) } catch { /* the app's callback */ } }
3271
+ if (typeof wb.backup.onState === 'function' && was.enabled !== ev.view.enabled) { try { wb.backup.onState(null) } catch { /* */ } }
3272
+ })
3273
+ const getters = (obj, map) => { for (const [k, f] of Object.entries(map)) Object.defineProperty(obj, k, { get: f, configurable: true }) }
3274
+ // signOutOthers / newRecoveryCode / deleteAccount: an account on the Witbitz account service (`service === 'account'`) — the vault
3275
+ // asks the person (its own confirm, the emailed code, the new code shown in its screens); the page gets only the outcome
3276
+ forwardInVault(wb.backup, (m, a) => conn.account('backup', m, ...(m === 'remove' ? [a[0]] : m === 'migrate' && a[0]?.silent === true ? [{ silent: true }] : m === 'deleteAccount' ? [{ names: (a[0] && Array.isArray(a[0].names) ? a[0].names : []) }] : [])), ['enable', 'restore', 'migrate', 'protectRecoveryEmail', 'manageSecurityKeys', 'save', 'upgrade', 'signOutOthers', 'newRecoveryCode', 'deleteAccount', 'beginEmailMove', 'pendingEmailMove', 'finishEmailMove', 'cancelPendingEmailMove', 'emailMove', 'requestMoveTime', 'cancelEmailMove'])
3277
+ wb.backup.remove = async (room) => { await conn.account('backup', 'remove', String(room || '')); return wb.backup } // a promise here: a refusal is said, not swallowed (sweep 10-24 #10)
3278
+ wb.backup.add = () => wb.backup // the vault records every Space it holds, on its own
3279
+ wb.backup.keyFor = () => { throw vaultRefusal('a key (the vault keeps them)') }
3280
+ wb.backup.setInvite = () => { throw vaultRefusal('writing the invite key into the backup (the vault keeps both)') } // the page writes no backup (sync sweep 11-13 P7)
3281
+ getters(wb.backup, { enabled: () => view().enabled, format: () => view().format, service: () => view().service || null, gated: () => !!view().gated, state: () => null, invite: () => null, rooms: () => view().rooms.map((r) => ({ ...r })) }) // gated: as the vault says (it read false for ever — sync sweep 11-09 #24)
3282
+ forwardInVault(wb.account, (m, a) => conn.account('account', m, ...(m === 'signOutDevice' ? [a[0]] : a)), ['sync', 'start', 'stop', 'archive', 'pin', 'rename', 'forget', 'signOut', 'listDevices', 'signOutDevice', 'repairNames', 'previewEmptySpaces', 'removeEmptySpaces', 'usage'])
3283
+ // lane.link() records the link on the account (Lane#link → _noteLink): in a vault the index is the vault's (sync sweep, 10-17 #6)
3284
+ wb.account._noteLink = (a, b, cap) => { conn.account('account', 'noteLink', a, b, cap).catch(() => {}) }
3285
+ wb.account._dropLink = (a, b) => { conn.account('account', 'dropLink', a, b).catch(() => {}) }
3286
+ // THE OPTIONAL SECTIONS (wb.account.contacts / .name / .roomDefaults — sdkAccountSections.js, plan phase 5): the account's docs
3287
+ // need its master secret, which is the vault's — each call goes to the vault (ACCOUNT_CALLS account.section), which runs the
3288
+ // same section on its own SDK and sends 'accountSection' when another device changed one. They carry no key and no link.
3289
+ for (const [name, sec] of Object.entries(wb.account._sections || {})) {
3290
+ for (const m of sec._calls) sec[m] = async (...a) => {
3291
+ const generation = accountGeneration
3292
+ const v = await conn.account('account', 'section', name, m, ...a)
3293
+ if (generation !== accountGeneration) throw sdkError('the account changed during the call', 'account_changed')
3294
+ if (!(name === 'chatLocks' && m === 'check')) sec._seen(v)
3295
+ return v
3296
+ }
3297
+ const on = sec.on.bind(sec)
3298
+ sec.on = (ev, fn) => { on(ev, fn); if (ev === 'change' && typeof fn === 'function') sec.get().catch(() => null); return sec } // the vault watches a section once asked
3299
+ sec._remote = true
3300
+ }
3301
+ getters(wb.account, { enabled: () => view().enabled, deviceId: () => view().deviceId, rooms: () => view().rooms.map((r) => ({ ...r })), devices: () => view().devices.map((d) => ({ ...d })), links: () => view().links.map((l) => ({ ...l })), lastError: () => { const e = view().lastError; return e ? (e instanceof Error ? e : typeof e === 'object' ? Object.assign(new Error(e.message), e) : new Error(String(e))) : null } }) // an Error, as outside a vault (the vault sends its message — sync sweep, 10-16)
3302
+ forwardInVault(wb.erasure, (m, a) => conn.account('erasure', m, ...a), ['file', 'status'])
3303
+ // WHICH BUILD THE PERSON ACCEPTS (sdkBuilds.js): in a vault the VAULT seals each room's key, with its own SDK — the page's list
3304
+ // decides nothing there, so its changes are refused by name (the vault kit takes them in a later phase)
3305
+ for (const m of ['accept', 'setAutomatic', 'sync']) wb.builds[m] = () => Promise.reject(vaultRefusal('wb.builds.' + m + ' (the vault seals the keys)'))
3306
+ // …and the verdict is the vault's too: the page never meets the enclave (the vault attests it), so it answered null for ever
3307
+ // while it read as "not attested yet" (sync sweep 11-13 P7). Synchronous, as outside a vault.
3308
+ wb.builds.verdict = () => { throw vaultRefusal('wb.builds.verdict (the vault meets the enclave and seals the keys)') }
3309
+ if (wb.builds.mode === 'mine') throw sdkError("witbitz: builds: 'mine' is not available in a vault yet — the vault seals each room's key with its own SDK, so the person's list would not be consulted", 'vault_unsupported') // never silently unenforced (review 2026-11-07)
3310
+ getters(wb.erasure, { available: () => !!view().erasure })
3311
+ for (const name of ['catalog', 'discover']) Object.defineProperty(wb.connections, name, { value: wb.connections[name].bind(wb.connections), configurable: true }) // public picker data remains synchronous and local
3312
+ forwardInVault(wb.connections, (m, a) => conn.account('connections', m, ...a))
3313
+ Object.defineProperty(wb.connections, 'lock', { value: () => Promise.reject(vaultRefusal('connections.lock (the vault locks what it holds itself)')), configurable: true, writable: true }) // move 3: no key leaves a vault
3314
+ // the sign-in comes back to THIS page (sweep 10-24 #6): forwarded bare, the vault's SDK named its own origin's /mcp-callback,
3315
+ // where no page waits — the default is the page's, as outside a vault
3316
+ wb.connections.startMcp = (opts = {}) => conn.account('connections', 'startMcp', { ...(opts || {}), ...(opts && opts.redirectUri ? {} : (typeof location !== 'undefined' && location.origin ? { redirectUri: location.origin + '/mcp-callback' } : {})) })
3317
+ // detach takes Space objects (`{ spaces }`), which do not cross to the vault (a DataCloneError — sync sweep 10-19 #7): the vault
3318
+ // gets the id alone, and each Space is unlinked through its own handle, as outside a vault
3319
+ wb.connections.detach = async (id, { spaces = [] } = {}) => {
3320
+ const cid = String(id || ''), out = await conn.account('connections', 'detach', cid)
3321
+ let removedFrom = 0
3322
+ for (const sp of Array.isArray(spaces) ? spaces : []) { try { if (sp && sp.connections) { await sp.connections.revoke(cid); removedFrom++ } } catch { /* one Space's refusal does not undo the detach */ } }
3323
+ return { ...(out || {}), removedFrom }
3324
+ }
3325
+ forwardInVault(wb.usernames, (m, a) => conn.account('usernames', m, ...a))
3326
+ // the Shortcut KEY stays in the vault: `shortcut.key` is null here, rotateKey resolves null, and wb.vault.showSiriKey()
3327
+ // shows it in the vault's own screen
3328
+ forwardInVault(wb.siri, (m, a) => conn.account('siri', m, ...a).then((r) => { if (m === 'rotateKey') { wb._vaultSiri = r || wb._vaultSiri; return null } if (m === 'revoke') wb._vaultSiri = { key: null, hasKey: false, endpoint: wb._vaultSiri && wb._vaultSiri.endpoint }; return r }), ['status', 'rotateKey', 'revoke'])
3329
+ wb._vaultSiri = (conn.info && conn.info.siri) || { key: null, endpoint: null }
3330
+ Object.defineProperty(wb.siri, 'shortcut', { get() { return { ...wb._vaultSiri } }, configurable: true }) // as the vault last said
3331
+ Object.defineProperty(wb.siri, 'state', { get() { return null }, configurable: true }) // the vault keeps it: its inbox private keys never come here
3332
+ wb.siri.restore = () => { throw vaultRefusal('restoring the Siri state (the vault keeps it)') }
3333
+ forwardInVault(wb.a2a, (m, a) => conn.account('a2a', m, ...a), ['status', 'revoke'])
3334
+ Object.defineProperty(wb.a2a, 'state', { get() { return null }, configurable: true }) // the vault keeps it: the lanes' inbox private keys never come here
3335
+ wb.a2a.restore = () => { throw vaultRefusal('restoring the A2A state (the vault keeps it)') }
3336
+ Object.defineProperty(wb.invite, 'state', { get() { return null }, configurable: true }) // the vault keeps the account's invite key
3337
+ Object.defineProperty(wb.invite, 'status', { get() { return 'vault' }, configurable: true }) // …and publishes it: there is nothing for the page to enroll or restore (sweep 10-23 #20 — it read 'none' for ever)
3338
+ wb.invite.enroll = async () => 'vault' // the status, a string, as outside a vault and in the d.ts (sweep 10-24 #9)
3339
+ wb.invite.restore = () => { throw vaultRefusal('restoring the invite key (the vault keeps it)') }
3340
+ wb.signIn = () => Promise.reject(sdkError('witbitz: in a vault, sign in with wb.vault.signIn() — the vault keeps the session', 'vault_signs_in'))
3341
+ wb.refreshSession = wb.signIn
3342
+ wb.useSession = () => { throw sdkError('witbitz: in a vault, the vault keeps the session — wb.vault.signIn() / wb.vault.info.email', 'vault_signs_in') } // it answered and adopted nothing, as signOut did (sync sweep 11-08 #29)
3343
+ wb.signOut = () => { throw sdkError('witbitz: in a vault, sign out with wb.vault.signOut() — the vault keeps the session', 'vault_signs_in') } // it reported success and signed nothing out (sync sweep 10-19)
3344
+ // dictation and reading aloud: the short-lived speech key is minted by the VAULT with its sign-in (or with your user
3345
+ // token, wb.useUserToken) — vault-core.js `speechKey`; the page streams to the speech model itself, as outside a vault
3346
+ }
3347
+ /** A Space in a vault: its connections and Siri need the account's session, which is the vault's. */
3348
+ function refuseSpaceInVault(sp) {
3349
+ const vc = () => sp._wb && sp._wb.vault && sp._wb.vault._c // read at each call: the vault this Space asks through now
3350
+ if (!vc()) { blockInVault(sp.connections, 'connections'); blockInVault(sp.siri, 'the Siri inbox'); return sp }
3351
+ const call = (ns) => (m, a) => vc().roomAccount(sp.room, ns, m, ...a)
3352
+ // grant by id: the callKey is the vault's (wb.connections.attach in a vault returns { id, label, host, account })
3353
+ forwardInVault(sp.connections, (m, a) => call('connections')(m, m === 'grant' ? [a[0] && typeof a[0] === 'object' ? a[0].id : a[0], a[1] && { from: a[1].from, tools: a[1].tools, auto: a[1].auto, reads: a[1].reads }] : a))
3354
+ forwardInVault(sp.siri, async (m, a) => {
3355
+ if (m !== 'collect') { const r = await call('siri')(m, a); if (m === 'enable' && r) sp._wb._vaultSiri = { key: null, hasKey: !!r.hasKey, endpoint: r.endpoint }; return r }
3356
+ const deliver = a[0] && a[0].deliver
3357
+ if (deliver !== undefined && typeof deliver !== 'function') throw sdkError('witbitz: collect({ deliver }) takes a function — deliver(text, meta)', 'invalid_argument')
3358
+ if (!deliver) return call('siri')('collect', [{}])
3359
+ const off = vc().onAsk('siriDeliver', sp.room, ({ text, meta }) => deliver(text, meta)) // the vault hands each drop here; a throw leaves it un-acked
3360
+ try { return await call('siri')('collect', [{ deliver: true }]) } finally { off() }
3361
+ })
3362
+ return sp
3363
+ }
3364
+ /** Replace each public method of `obj` with one that asks the vault: `send(method, args)`. Getters are left alone. */
3365
+ function forwardInVault(obj, send, only = null) {
3366
+ for (let p = obj; p && p !== Object.prototype; p = Object.getPrototypeOf(p)) {
3367
+ for (const k of Object.getOwnPropertyNames(p)) {
3368
+ if (k === 'constructor' || k.startsWith('_') || (only && !only.includes(k)) || Object.prototype.hasOwnProperty.call(obj, k)) continue
3369
+ const d = Object.getOwnPropertyDescriptor(p, k)
3370
+ if (!d || typeof d.value !== 'function') continue
3371
+ Object.defineProperty(obj, k, { value: (...a) => send(k, a), configurable: true, writable: true })
3372
+ }
3373
+ }
3374
+ }
3375
+
3376
+ /** The vault this page runs in ({@link Witbitz.inVault}). The keys are there; this is how the page asks for what needs them. */
3377
+ export class VaultSession {
3378
+ constructor(wb, conn) {
3379
+ this._wb = wb; this._c = conn; this.origin = conn.origin; this._fns = new Map(); this._live = {}
3380
+ // each room's last key state as the vault said it (once per vault window): a Space opened LATER on this page starts from it
3381
+ // (sync sweep 11-08 #27: it never heard it, and polled at full speed)
3382
+ this._keyState = new Map()
3383
+ for (const k of Array.isArray(conn.info && conn.info.keyStates) ? conn.info.keyStates : []) if (k && typeof k.room === 'string' && (k.kind === 'removed' || k.kind === 'pending')) this._keyState.set(k.room, { kind: k.kind, reason: String(k.reason || '') }) // what the vault holds now — a reloaded page hears it here, never again as an event (sync sweep 11-09)
3384
+ conn.on((d) => { if (d && d.ev === 'key' && typeof d.room === 'string') { if (d.kind === 'rekeyed') this._keyState.delete(d.room); else if (d.kind === 'removed' || d.kind === 'pending') this._keyState.set(d.room, { kind: d.kind, reason: d.reason || '' }) } })
3385
+ conn.on((ev) => this._event(ev))
3386
+ }
3387
+ /** What the vault said when the page connected — { tenant, signedIn, email, rooms, siri, account } — with the sign-in and the
3388
+ * account kept current from the vault's events since (sync sweep 10-26 #10: it was the welcome, frozen). */
3389
+ get info() { return { ...this._c.info, ...this._live } }
3390
+ /** The Spaces this vault holds, newest first: [{ room, title, at, lane?, tier?, lanes? }] — never a link. */
3391
+ async rooms() { return this._c.rooms() }
3392
+ /** A live {@link Space} for a room the vault holds — its key stays in the vault. */
3393
+ async openRoom(room, { resume } = {}) {
3394
+ if (typeof room !== 'string' || !room) throw sdkError('witbitz: openRoom takes a room id from wb.vault.rooms()', 'invalid_argument')
3395
+ const wb = this._wb
3396
+ // a room the vault does not hold is said here, as openLane says it — not as a Space whose every call fails (sweep 10-24 #10)
3397
+ const all = await this._c.rooms(), it = all.find((r) => r && r.room === room)
3398
+ if (!it) throw sdkError('witbitz: this vault holds no Space ' + room.slice(0, 40), 'not_in_vault')
3399
+ // a LANE's id opens it as its Space's lane — as a plain Space it skipped the lane rules (sync sweep 2026-11-02 #5)
3400
+ if (it.lane) {
3401
+ // its Space forgotten (forget / dropRoom keep the lane): said by name, about THIS room — it threw not_in_vault naming
3402
+ // the Space's id (sync sweep 2026-11-03 #4)
3403
+ if (!all.some((r) => r && r.room === it.lane)) throw sdkError('witbitz: this private lane\'s Space is no longer in this vault, so the lane cannot be opened', 'lane_space_gone')
3404
+ const space = await this.openRoom(it.lane)
3405
+ // the Space opened here is the lane's own: lane.close() closes it too — it was left polling (sync sweep 2026-11-03 #5)
3406
+ try { const lane = await this._openLane(room, { space, resume }); lane._ownsSharedSpace = true; return lane } catch (e) { space.close(); throw e }
3407
+ }
3408
+ return refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, resume, wb, lanes: it.lanes === true }))
3409
+ }
3410
+ /** @private wb.openLane in a vault: the lane's ROOM ID (from rooms(), where `lane` names its Space) — a link is the
3411
+ * vault's to open. */
3412
+ async _openLane(room, { space, actions, resume, tier, mirror }) {
3413
+ const wb = this._wb
3414
+ if (!(space instanceof Space) || !space.room) throw sdkError('witbitz: openLane needs `space`, the shared Space the lane belongs to', 'invalid_argument')
3415
+ if (typeof room !== 'string' || /[:#/]/.test(room)) throw sdkError('witbitz: in a vault, openLane takes the lane\'s room id from wb.vault.rooms() — the vault opens links', 'vault_opens_links')
3416
+ const held = await this._c.rooms(), it = held.find((r) => r.room === room)
3417
+ if (!it) throw sdkError('witbitz: this vault holds no Space ' + room.slice(0, 40), 'not_in_vault')
3418
+ await assertNotKept(space)
3419
+ if (it.lane !== space.room) throw sdkError('witbitz: that room is not a lane of this Space', 'invalid_argument')
3420
+ // its Space forgotten: said by name, as openRoom says it — the lane opened and every bridged turn then failed not_in_vault (sync sweep 11-04 #9)
3421
+ if (!held.some((r) => r && r.room === space.room)) throw sdkError('witbitz: this private lane\'s Space is no longer in this vault, so the lane cannot be opened', 'lane_space_gone')
3422
+ // a lane's tier is its Space's: a different one is refused, as privateLane does — never ignored (sync sweep, 10-15)
3423
+ if (tier !== undefined && tier !== null && tierIsEnclave(tier) !== (it.tier === 'enclave')) throw tierMismatch('this lane is ' + (it.tier === 'enclave' ? 'confidential' : 'standard') + ' — its Space\'s tier')
3424
+ // a lane of the OTHER tier (the app links one): mirrored by this device, no bridge — as outside a vault (Witbitz.openLane)
3425
+ const crossTier = (it.tier === 'enclave') !== ((held.find((r) => r.room === space.room) || {}).tier === 'enclave')
3426
+ return refuseSpaceInVault(new Lane(wb._client, { room, mk: null, link: null, viewer: wb._viewer, sharedRoom: space.room, sharedMk: null, actions, resume, wb, shared: space, mirror: crossTier ? (mirror || true) : mirror, crossTier }))
3427
+ }
3428
+ /** Show the Siri Shortcut's key in the VAULT's own screen (it posts words into the person's Spaces, so it never comes
3429
+ * to this page). Rejects `no_key` until a Space has Siri enabled. */
3430
+ async showSiriKey() { return this._c.account('siri', 'showKey') }
3431
+ /** The vault's LOCK SHEET, in the vault's own pixels: the person turns the lock (a passkey at every launch) and "Also protect
3432
+ * this device's storage" on or off there. Resolves { available, on, protect } when they close it; this page can turn neither
3433
+ * on nor off. Rejects `vault_unsupported` unless the vault was started with `lock: true` (`info.lock` says whether it was). */
3434
+ async showLock() {
3435
+ if (typeof this._c.lockSettings !== 'function') throw sdkError('witbitz: this vault offers no lock', 'vault_unsupported')
3436
+ const r = await this._c.lockSettings()
3437
+ this._live = { ...this._live, lock: r }
3438
+ return r
3439
+ }
3440
+ /** NOTIFICATIONS on this device, in the vault's own card: the person turns them on (the browser asks for its permission
3441
+ * there) or off. Resolves { available, on }. A tapped notification arrives as `on('notifOpen', ({ room }) => …)` — or, when
3442
+ * it opened the vault, as `info.notifOpen`. Rejects `vault_unsupported` unless the vault was started with `push: true`. */
3443
+ async showNotifications() {
3444
+ if (typeof this._c.notifications !== 'function') throw sdkError('witbitz: this vault sends no notifications', 'vault_unsupported')
3445
+ const r = await this._c.notifications()
3446
+ this._live = { ...this._live, push: r }
3447
+ return r
3448
+ }
3449
+ /** Share a Space: the VAULT shows its share screen with the link (the link carries the key, so it never comes here). */
3450
+ async share(space, opts = {}) { return this._c.share(space && space.room ? space.room : String(space || ''), opts) }
3451
+ /** Sign in — the vault shows its sign-in screen; resolves { email } once signed in. */
3452
+ async signIn(opts = {}) { return this._c.signIn(opts) }
3453
+ async signOut() { return this._c.signOut() }
3454
+ /** { signedIn, email, keyId } — who the vault has signed in (keyId: its session key's public id, what space.isMine compares). */
3455
+ async whoami() { return this._c.whoami() }
3456
+ /** Remove a Space from this vault (its key is forgotten on this device). */
3457
+ async forget(room) { return this._c.forget(room && room.room ? room.room : String(room || '')) }
3458
+ /** 'rooms' (the list changed: { rooms }), 'joined' ({ room } — the vault opened an invite), 'signedIn' ({ email }), 'signedOut',
3459
+ * 'accountSignedOut' (this device was signed out of the account, or the account was deleted, from another device: the vault forgot
3460
+ * the account, its sign-in and its Spaces here; `reason: 'erased'` — the account was deleted). */
3461
+ on(event, cb) { if (!this._fns.has(event)) this._fns.set(event, new Set()); this._fns.get(event).add(cb); return () => this._fns.get(event).delete(cb) }
3462
+ _event(d) {
3463
+ if (d?.ev === 'rooms' && Array.isArray(d.rooms)) {
3464
+ for (const lane of this._wb._openLanes || []) {
3465
+ const saved = d.rooms.find(r => r.room === lane.room)
3466
+ if (lane._sharedRoom && saved?.lane !== lane._sharedRoom) lane._detachShared()
3467
+ }
3468
+ }
3469
+ if (d && d.ev === 'signedIn') this._live = { ...this._live, signedIn: true, email: String(d.email || ''), keyId: String(d.keyId || '') }
3470
+ else if (d && (d.ev === 'signedOut' || d.ev === 'accountSignedOut')) this._live = { ...this._live, signedIn: false, email: '', keyId: '' } // accountSignedOut: the vault forgot the account AND its sign-in — info said signed in, with the old email (sync sweep 11-22 #5)
3471
+ else if (d && d.ev === 'session') this._live = { ...this._live, keyId: String(d.keyId || '') } // a renewed session: its new key's public id (space.isMine)
3472
+ else if (d && d.ev === 'account' && d.view) this._live = { ...this._live, account: d.view }
3473
+ else if (d && d.ev === 'lock' && d.lock && typeof d.lock === 'object') this._live = { ...this._live, lock: { available: !!d.lock.available, on: !!d.lock.on, protect: !!d.lock.protect } } // a vault started with `lock: true`
3474
+ else if (d && d.ev === 'push' && d.push && typeof d.push === 'object') this._live = { ...this._live, push: { available: !!d.push.available, on: !!d.push.on } } // `push: true`
3475
+ const set = this._fns.get(d.ev); if (set) for (const fn of set) { try { fn(d) } catch { /* the listener's own */ } }
3476
+ }
3477
+ async _create({ agent, tools, immediateTools, clientTools, agentReplies, model, data, admission, tier, key, platformTools, region, framing, dataWrites, direct, safeMedia, lanes }) {
3478
+ const enc = tierIsEnclave(tier) // the vault attests the enclave and keeps the key; the page only asks
3479
+ const split = splitKeyChoice(key) // the vault makes it through its app-half function (startVault({ appShare: true }))
3480
+ const wb = this._wb
3481
+ if (direct !== undefined) { const who = await this._c.whoami(); admission = directAdmission(direct, admission, who && who.signedIn ? { email: who.email } : null, 'wb.vault.signIn') } // the vault's signed-in member
3482
+ // THE CREATOR IS THE OWNER, as outside a vault (createSpace): the vault's signed-in member, when on the list and no owners given —
3483
+ // without it nobody could change the Space's members in place (changeMembers needs an owner or an admin)
3484
+ else if (admission && typeof admission === 'object' && Array.isArray(admission.emails) && !(Array.isArray(admission.owners) && admission.owners.length)) {
3485
+ const who = await this._c.whoami()
3486
+ if (!who || typeof who.signedIn !== 'boolean') throw sdkError('witbitz: the creating member could not be checked', 'identity_unavailable')
3487
+ const me = who && who.signedIn ? String(who.email || '').trim().toLowerCase() : ''
3488
+ if (me && admission.emails.map((e) => String(e).trim().toLowerCase()).includes(me)) admission = { ...admission, owners: [me] }
3489
+ }
3490
+ await wb._checkModel(model || (agent && agent.model))
3491
+ const gate = normAdmission(admission)
3492
+ const cfg = roomConfig({ agent, tools, immediateTools, model, data, gate, platformTools, framing, dataWrites }, { agentName: 'Assistant', persona: '' })
3493
+ if (Array.isArray(clientTools)) cfg.clientTools = clientTools
3494
+ if (agentReplies !== undefined) cfg.agentReplies = agentReplies
3495
+ cfg.region = region || wb._region
3496
+ if (direct !== undefined) cfg.direct = true
3497
+ if (safeMedia === true) cfg.safeMedia = true // as outside a vault (sync sweep 2026-10-28: it was refused here while configure turned it on)
3498
+ if (lanes === true) cfg.lanes = true
3499
+ const { room } = await this._c.create(cfg, enc || split ? { ...(enc ? { enclave: true } : {}), ...(split ? { split: true } : {}) } : undefined)
3500
+ const made = refuseSpaceInVault(new Space(wb._client, { room, mk: null, link: null, viewer: wb._viewer, wb, gated: !!gate, lanes: lanes === true }))
3501
+ made.safeMedia._learn(safeMedia === true, 0) // a new room's setting is what it was made with, as outside a vault (sync sweep 2026-10-28…11-02: it read null)
3502
+ if (direct !== undefined) await made.setReplyMode('ondemand').catch(() => {}) // as outside a vault: the assistant answers when @mentioned
3503
+ return made
3504
+ }
3505
+ }
3506
+
3507
+ /** `wb.connections` — the ACCOUNT's connections: credentials the standing Sentinel holds and spends on your behalf.
3508
+ * Attaching seals the secret to the attested Sentinel; the page keeps only an id, a label, a host and a `callKey`.
3509
+ * Nothing here touches a Space: grant one to a Space with `space.connections.grant(conn)`. */
3510
+ class Connections {
3511
+ constructor(wb) { this._wb = wb }
3512
+ /** The app's service/outside-agent picker data, without credentials. A builder draws its own picker. */
3513
+ catalog({ category } = {}) {
3514
+ if (category !== undefined && typeof category !== 'string') throw sdkError('witbitz: catalog category must be a string', 'invalid_argument')
3515
+ return CONNECTION_CATALOG.filter((c) => category === undefined || c.cat === category).map((c) => ({ ...c, kind: c.kind || 'mcp' }))
3516
+ }
3517
+ async spacesUsing(id) {
3518
+ const wb = this._wb, generation = wb._archiveGeneration, master = wb.backup._s?.master || null
3519
+ const byId = new Map(wb.account.rooms.map(r => [r.room, r]))
3520
+ for (const sp of wb._archiveHandles || []) {
3521
+ if (sp._archiveGeneration !== generation || sp._archiveEmail !== (wb._session?.email || '') || sp._archiveMaster !== master || byId.has(sp.room)) continue
3522
+ byId.set(sp.room, { room: sp.room, link: sp.shareLink, shared: sp._sharedRoom })
3523
+ }
3524
+ const result = await spacesUsingConnection(id, [...byId.values()], async room => {
3525
+ const link = await wb._openLink(byId.get(room).link)
3526
+ if (link.room !== room) throw new Error('room link mismatch')
3527
+ return wb._client.getConfig(room, link.mk, { plainMark: true })
3528
+ })
3529
+ if (wb._archiveGeneration !== generation || (wb.backup._s?.master || null) !== master) throw sdkError('the account changed', 'account_changed')
3530
+ if (!wb.backup.enabled) result.incomplete = true
3531
+ return result
3532
+ }
3533
+ discover(query = '', options = {}) {
3534
+ const text = String(query).trim().toLowerCase()
3535
+ const matches = c => [c.name, c.desc].some(s => String(s || '').toLowerCase().includes(text))
3536
+ const services = this.catalog(options).filter(matches)
3537
+ const address = options.category === undefined ? typedMcpUrl(query) || null : null
3538
+ const methods = [{ id: 'mcp', name: 'Other MCP server', desc: 'Any MCP server, by its address.' }, { id: 'apiKey', name: 'API key', desc: 'A service’s own key, for its API.' }]
3539
+ const alternatives = options.category === undefined
3540
+ ? otherWaysRows({ all: methods, matches, searching: !!text, anythingElse: !!(services.length || address) }).rows.map(m => m.id)
3541
+ : []
3542
+ return { services, address, alternatives }
3543
+ }
3544
+ /** The account's display key (connDisp.js), from the backup master this client holds; null without one (then names go as before). */
3545
+ async _dispKey () {
3546
+ const st = this._wb.backup && this._wb.backup.state, m = st && st.master
3547
+ if (!m) return null
3548
+ if (!this._disp || this._disp.master !== m) this._disp = { master: m, key: dispKeyOf(m).catch(() => null) }
3549
+ return this._disp.key
3550
+ }
3551
+ /** Attach a bearer token for one host. → `{ id, label, host, callKey }` — keep it (JSON-safe) to grant it to Spaces;
3552
+ * the secret is gone from this device the moment this returns.
3553
+ * AN AGENT THAT TAKES JOBS (portal/docs/outside-agents.md): `webhook: true` with `host` = the agent's whole https trigger
3554
+ * address makes a one-path, POST-only connection whose key goes as a Bearer header (a `whsec_…` secret is signed
3555
+ * instead, without the flag); `job: { field, headers }` says where the job goes in the request body and the fixed
3556
+ * headers every call carries. A Space granted it tells the agent, in every job, to report back with message_member. */
3557
+ async attach({ label, host, secret, rules, limits, webhook, job } = {}) {
3558
+ const wb = this._wb, auth = wb._auth()
3559
+ const account = await wb._account()
3560
+ if (job && webhook !== true && !/^whsec_/.test(String(secret || '').trim())) throw sdkError('witbitz: a job agent is a webhook — pass webhook: true and its whole https address as host', 'invalid_argument')
3561
+ const out = await attachConnection({ post: wb._sentinelPost(), auth, account, label, host, secret, rules, limits, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow, tenant: wb._tenant || undefined, ...(webhook === true ? { bearerWebhook: true } : {}) })
3562
+ const j = out.webhook && job ? roomJob(job) : null
3563
+ return { ...out, account, ...(j ? { job: j } : {}) }
3564
+ }
3565
+ /** What the Sentinel holds for this account — never a secret, never a callKey. In a vault the vault answers, and marks each
3566
+ * `grantable`: whether it holds that connection's callKey — `space.connections.grant` refuses the rest (`not_in_vault`). */
3567
+ async list() { const wb = this._wb; return listConnections({ post: wb._sentinelPost(), auth: wb._auth(), dispKey: await this._dispKey() }) } // a name sealed to the account's devices is opened here
3568
+ /** LOCK THE OLD ONES (docs/standing-sentinel.md § The two open pieces, move 3): a connection attached before 2026-11-16 that no
3569
+ * Space has spent since is still held in the Sentinel's old form — its callKey beside its secret. Pass the callKeys your app
3570
+ * keeps ({ id: callKey }, as `attach` returned them): each one the list marks `locked: false` is locked under its key, with no
3571
+ * call to the service. A vault does this itself on `list`. → { locked, failed, skipped } (skipped: no key passed for it). */
3572
+ async lock(keys = {}) {
3573
+ const wb = this._wb, post = wb._sentinelPost(), auth = wb._auth()
3574
+ const list = await this.list() // the same list `list` gives (names opened with the display key)
3575
+ return lockConnections({ post, auth, list,
3576
+ attest: () => attestStandingSentinel({ post, auth, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow }),
3577
+ proofOf: async (id, nonce, key) => (keys && typeof keys[id] === 'string' && keys[id] ? wrapProof({ callKey: keys[id], nonce, key }) : null) })
3578
+ }
3579
+ /** Detach everywhere: the Sentinel forgets it and every Space's grant for it is dead at once. Pass `spaces` (the Space handles
3580
+ * you granted it to) and it is also dropped from each one's settings, as the app's Disconnect does — else their assistants
3581
+ * keep offering a connection that answers 404 (sync sweep, 10-16 #9). → the Sentinel's answer + `removedFrom` (a count). */
3582
+ async detach(id, { spaces = [] } = {}) {
3583
+ const wb = this._wb, cid = String(id || '')
3584
+ const out = await detachConnection({ post: wb._sentinelPost(), auth: wb._auth(), id: cid })
3585
+ let removedFrom = 0
3586
+ for (const sp of Array.isArray(spaces) ? spaces : []) { try { if (sp && sp.connections) { await sp.connections.revoke(cid); removedFrom++ } } catch { /* one Space's refusal does not undo the detach */ } }
3587
+ return { ...(out || {}), removedFrom }
3588
+ }
3589
+
3590
+ // ── CONNECT TO A BUILDER'S OAUTH APP (https://witbitz.chat/docs/connections.md). Two calls around the consent screen. The PKCE
3591
+ // verifier lives in the enclave for the whole round trip, so the code this page ends up holding cannot be exchanged
3592
+ // by this page — only by the measured image that minted the challenge.
3593
+ /** Begin: → { authUrl, state }. Send the member to `authUrl`; your registered callback receives `?code=&state=`. */
3594
+ async startConnect ({ tenant, providerId } = {}) {
3595
+ const wb = this._wb, auth = wb._auth()
3596
+ if (!providerId) throw sdkError('witbitz: which provider? pass the id your builder gave you', 'invalid_argument')
3597
+ const r = await wb._sentinelPost()({ op: 'sentinel', sentinel: { mode: 'oauthstart', tenant: String(tenant || wb._tenant || ''), providerId: String(providerId) }, ...auth })
3598
+ if (!r || r.error || !r.authUrl) throw Object.assign(new Error(`witbitz: could not start the sign-in (${(r && (r.error || r.reason)) || 'no answer'})`), { code: (r && r.error) || 'no_answer', ...(r && r.reason ? { reason: r.reason } : {}) })
3599
+ return { authUrl: r.authUrl, state: r.state }
3600
+ }
3601
+ /** Finish with the `code` and `state` your callback received. The tokens never reach this page. → a connection you
3602
+ * grant to Spaces exactly as an attached one: { id, label, host, callKey, account }. */
3603
+ async finishConnect ({ state, code, label, host } = {}) {
3604
+ const wb = this._wb, auth = wb._auth()
3605
+ if (!state || !code) throw sdkError('witbitz: finishConnect needs the state and code from your callback', 'invalid_argument')
3606
+ const post = wb._sentinelPost()
3607
+ const { nonce, key } = await attestStandingSentinel({ post, auth, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3608
+ const callKey = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))))
3609
+ // the name sealed to the account's devices rides the finish, under the id it names (as attach / finishMcpSignIn do — sync sweep
3610
+ // 11-08: finishConnect sealed none). A Sentinel before the one that keeps it files the clear label, as before.
3611
+ const id = 'conn_' + btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(12)))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
3612
+ const dk = await this._dispKey()
3613
+ const disp = dk && label ? await sealDisp(dk, id, { label: String(label).trim().slice(0, 80) }).catch(() => '') : ''
3614
+ const sealed = await sealToEnclave(key, nonce, { state: String(state), code: String(code), callKey, id, ...(label ? { label: String(label) } : {}), ...(host ? { host: String(host) } : {}), ...(disp ? { disp } : {}) })
3615
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'oauthfinish', sealed }, ...auth })
3616
+ if (!r || r.error || !r.ok) throw Object.assign(new Error(`witbitz: the sign-in was not completed (${(r && (r.error || r.reason)) || 'no answer'})`), { code: (r && r.error) || 'no_answer', ...(r && r.reason ? { reason: r.reason } : {}) })
3617
+ return { id: r.id, label: String(r.label || label || ''), host: r.host, provider: 'oauth2', callKey, account: r.account || await wb._account() } // `label`: the Connection type promises one (sync sweep, 2026-10-10)
3618
+ }
3619
+
3620
+ // ── MCP SERVERS (the owner, 2026-10-23: "Are the connectors exposed in the sdk?" → "Yes"): as the app's ⋯ → Connections →
3621
+ // Other MCP server (https://witbitz.chat/docs/mcp-connections.md). The server's own sign-in runs INSIDE the Sentinel (it
3622
+ // registers an app there and holds the PKCE verifier); the member consents in a window; your callback page hands back
3623
+ // `code` + `state`; the code and a fresh callKey ride sealed to the Sentinel, which exchanges and files it. Your page never
3624
+ // holds the server's token. Grant it to a Space with `space.connections.grant(conn)` like any connection.
3625
+ /** Begin: does this server want a sign-in? → `{ needsSignIn: false, host }` (then `attachMcp({ url, label })`) or
3626
+ * `{ needsSignIn: true, authUrl, state, host }` (open `authUrl`; `redirectUri` — default `<your origin>/mcp-callback` — gets
3627
+ * `?code=&state=`; then `finishMcp`). Opens nothing. */
3628
+ async startMcp ({ url, label, redirectUri } = {}) {
3629
+ const wb = this._wb, auth = wb._auth()
3630
+ if (!url) throw sdkError('witbitz: startMcp needs the server\'s address, like https://mcp.example.com/mcp', 'invalid_argument')
3631
+ const cb = redirectUri ? String(redirectUri) : (typeof location !== 'undefined' && location.origin ? location.origin + '/mcp-callback' : '') // outside a page (a server, a test): name your callback
3632
+ const st = await startMcpSignIn({ post: wb._sentinelPost(), auth, url, label, redirectUri: cb })
3633
+ return st.needsAuth ? { needsSignIn: true, authUrl: st.authUrl, state: st.state, host: st.host } : { needsSignIn: false, host: st.host }
3634
+ }
3635
+ /** A server with no sign-in, or one you hold a token for (`token`, sealed to the Sentinel like any secret). → a connection
3636
+ * `{ id, label, host, callKey, account, mcp: true }`. The member's own, as a signed-in server is: never under your tenant, so
3637
+ * its host needs no declaration (connections.js attachMcp; it was filed under the tenant and refused — docs sync, 2026-11-22). */
3638
+ async attachMcp ({ url, label, token = '' } = {}) {
3639
+ const wb = this._wb, auth = wb._auth(), account = await wb._account()
3640
+ const out = await attachMcpServer({ post: wb._sentinelPost(), auth, account, label, url, token, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3641
+ return { ...out, account, mcp: true }
3642
+ }
3643
+ /** Finish a server's sign-in with the `state` and `code` your callback received. → a connection, as `attachMcp`. */
3644
+ async finishMcp ({ state, code, label, host } = {}) {
3645
+ const wb = this._wb, auth = wb._auth()
3646
+ if (!state || !code) throw sdkError('witbitz: finishMcp needs the state and code from your callback', 'invalid_argument')
3647
+ const out = await finishMcpSignIn({ post: wb._sentinelPost(), auth, state: String(state), code: String(code), label, host, dispKey: await this._dispKey(), pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3648
+ return { ...out, account: await wb._account(), mcp: true }
3649
+ }
3650
+ /** The tools an MCP connection offers, as the server describes them (asked through the Sentinel). → `{ tools, server, truncated }`. */
3651
+ async mcpTools (id) { const wb = this._wb; return listMcpTools({ post: wb._sentinelPost(), auth: wb._auth(), id: String(id || '') }) }
3652
+ }
3653
+
3654
+ /** `space.connections` — what THIS Space's assistant may spend. A grant is recorded in the Space's sealed
3655
+ * configuration (visibly — a system line lands); the assistant then gets `connection_call` for it, always proposed,
3656
+ * never auto-run, and never sees the secret. */
3657
+ class SpaceConnections {
3658
+ constructor(space) { this._space = space }
3659
+ async grants() {
3660
+ const sp = this._space
3661
+ if (sp._wb?.vault?._c) return sp._wb.vault._c.roomAccount(sp.room, 'connections', 'grants')
3662
+ const cfg = await sp._gateConfig({ plainMark: true })
3663
+ const wb = sp._wb
3664
+ const [account, list] = await Promise.all([wb._account().catch(() => ''), wb.connections.list().catch(() => null)])
3665
+ const known = Array.isArray(list) ? new Set(list.map(c => c.id)) : null
3666
+ return (Array.isArray(cfg.connections) ? cfg.connections : []).filter(c => typeof c?.id === 'string').map(c => ({
3667
+ id: c.id, label: String(c.label || ''), host: String(c.host || ''), status: grantStatus(c, account, known),
3668
+ }))
3669
+ }
3670
+ /** Grant a connection (the object `wb.connections.attach` returned, or `{ id, callKey, host, label, account }`). An MCP
3671
+ * connection (`mcp: true` — what attachMcp / finishMcp return) brings its tools: `tools` (names) to choose them, else the
3672
+ * recommended set — the app's (reads run on their own, changes ask); `auto` (names) for which run without asking. */
3673
+ async grant(conn, { from, tools, auto, reads } = {}) {
3674
+ from = this._space._who(from)
3675
+ const sp = this._space
3676
+ const c = conn && typeof conn === 'object' ? conn : {}
3677
+ if (reads !== undefined && !['auto', 'ask'].includes(reads)) throw sdkError('witbitz: reads takes auto or ask', 'invalid_argument')
3678
+ const account = String(c.account || (sp._wb ? await sp._wb._account() : '') || '').toLowerCase()
3679
+ if (!c.id || !c.callKey || !c.host || !account) throw sdkError('witbitz: grant needs { id, callKey, host, account } — the object wb.connections.attach returned', 'invalid_argument')
3680
+ // ONLY TO AN EMAIL-GATED ROOM (2026-10-02). In an open room — and a lane is open unless you gate it — the link is the
3681
+ // whole capability: whoever holds it can start a turn, and the assistant spends the connection. Gate the room (a
3682
+ // lane: privateLane({ admission: { emails: [me] } })) so every turn needs an allowed sign-in.
3683
+ const cfg = await sp._gateConfig()
3684
+ if (cfg.admission !== 'email') throw Object.assign(new Error("witbitz: a connection can be granted only to an email-gated Space — in an open one, anyone holding the link could have the assistant spend it. Gate it: createSpace / privateLane({ admission: { emails: [...] } })"), { code: 'gate_required' })
3685
+ let mcp
3686
+ if (c.mcp && !sp._wb) throw sdkError('witbitz: granting an MCP connection needs the signed-in account (open the Space through wb)', 'invalid_argument')
3687
+ if (c.mcp) { // an MCP server: its tools, as the app's "Add" does (mcpToolsSheet addWithRecommended)
3688
+ const listed = await listMcpTools({ post: sp._wb._sentinelPost(), auth: sp._wb._auth(), id: String(c.id) })
3689
+ const all = listed.tools.map(roomTool).filter(Boolean)
3690
+ const rec = recommendedChoice(all)
3691
+ const chosen = new Set(Array.isArray(tools) ? tools.map(String) : rec.chosen)
3692
+ const picked = all.filter((t) => chosen.has(t.name))
3693
+ if (!picked.length) throw sdkError('witbitz: none of those tools is offered by this server — mcpTools(id) lists them', 'invalid_argument')
3694
+ const names = new Set(picked.map((t) => t.name))
3695
+ mcp = { tools: picked, auto: (Array.isArray(auto) ? auto.map(String) : rec.auto).filter((n) => names.has(n)), ...(isCurated(c.host) ? {} : { own: true }), listedAt: Date.now() }
3696
+ // THE TOOL BOOK, as the app (toolBooks.js; sync sweep 2026-11-17 #3): the Space's other connections into books first, then this
3697
+ // one's tools — the config keeps names + the book's pin, so connections no longer fill its cap ("Too many tools")
3698
+ const io = { toolBook: (list) => sp._client.toolBook(sp.room, sp._mk, list), getConfig: () => sp._client.getConfig(sp.room, sp._mk), setConfig: (patch) => sp._client.setConfig(sp.room, sp._mk, patch, from) }
3699
+ await bookTheRest(io, String(c.id))
3700
+ mcp = await withBook(io, mcp)
3701
+ }
3702
+ const { mcp: _flag, ...entry } = c
3703
+ const r = await sp._client.setConfig(sp.room, sp._mk, { connections: { add: roomEntry({ ...entry, account, reads: reads === 'auto' || reads === undefined && readsAutoFor(c) ? 'auto' : undefined, ...(mcp ? { mcp } : {}) }) } }, from)
3704
+ if (!r || r.status !== 200) throw refused('recording the connection in this Space', r)
3705
+ return { granted: String(c.id), ...(mcp ? { tools: mcp.tools.map((t) => t.name), auto: mcp.auto } : {}) }
3706
+ }
3707
+ /** Drop a connection from THIS Space only; it stays attached to the account. */
3708
+ async revoke(id, { from } = {}) {
3709
+ from = this._space._who(from)
3710
+ const sp = this._space
3711
+ const r = await sp._client.setConfig(sp.room, sp._mk, { connections: { remove: String(id || '') } }, from)
3712
+ if (!r || r.status !== 200) throw refused('dropping the connection', r) // as grant: the server's code, status and reason (sync sweep, 2026-10-10)
3713
+ return { revoked: String(id) }
3714
+ }
3715
+ }
3716
+
3717
+ /** `wb.siri` — the account's Siri inbox: one Shortcut key for every Space, an inbox keypair per enabled Space. The
3718
+ * STATE (`wb.siri.state`) holds the inbox private keys — without it a drop can never be opened — so persist it as
3719
+ * you persist the session, and hand it back as `new Witbitz({ siri: state })`. */
3720
+ class SiriAccount {
3721
+ constructor(wb) { this._wb = wb }
3722
+ /** JSON-safe state to persist. */
3723
+ get state() { return JSON.parse(JSON.stringify(this._wb._siri)) }
3724
+ /** Adopt persisted state. */
3725
+ restore(state) { this._wb._siri = siriStateOf(state); return this }
3726
+ /** The Shortcut's key and endpoint (null key until a Space enables Siri). */
3727
+ get shortcut() { return { key: this._wb._siri.token || null, endpoint: SIRI_ENDPOINT } }
3728
+ /** What the Sentinel holds for this account (aliases, counts) — as it reports it. */
3729
+ async status() {
3730
+ const wb = this._wb, auth = wb._auth()
3731
+ const r = await wb._sentinelPost()({ op: 'sentinel', sentinel: { mode: 'siristatus' }, ...auth })
3732
+ if (!r || r.error) throw Object.assign(new Error(`witbitz: the Sentinel could not be reached (${(r && r.error) || 'no answer'})`), { code: (r && r.error) || 'no_answer' })
3733
+ return r
3734
+ }
3735
+ /** A new Shortcut key: the old one stops working the moment the record is pushed. → the new key. */
3736
+ async rotateKey() { return this._change((st) => { st.token = newSiriKey(); return st.token }) }
3737
+ /** Turn Siri off everywhere for this account: the Sentinel forgets the record; the local state is cleared. */
3738
+ // IN THE SAME QUEUE AS EVERY CHANGE (sync sweep 2026-11-14 P7, owner: yes): a change still being pushed when revoke() ran finished after
3739
+ // it and put Siri back at the Sentinel and here. Now revoke waits for it, and a change asked after it runs on the cleared state.
3740
+ async revoke() {
3741
+ const run = async () => {
3742
+ const wb = this._wb, auth = wb._auth()
3743
+ const r = await wb._sentinelPost()({ op: 'sentinel', sentinel: { mode: 'sirirevoke' }, ...auth })
3744
+ if (!r || r.error) throw Object.assign(new Error(`witbitz: the Sentinel could not be reached (${(r && r.error) || 'no answer'})`), { code: (r && r.error) || 'no_answer' })
3745
+ wb._siri = siriStateOf(null)
3746
+ return r
3747
+ }
3748
+ const p = (this._q || Promise.resolve()).then(run, run)
3749
+ this._q = p.catch(() => {})
3750
+ return p
3751
+ }
3752
+ // ⛔ A CHANGE IS KEPT ONLY ONCE THE SENTINEL TOOK IT (state machines pass 9, K#5): the state was changed in place and pushed
3753
+ // after — a failed push left a Space this device had taken off Siri still open at the Sentinel (and a retry found nothing to
3754
+ // take off), or a key this device had replaced still working there. `fn` changes a COPY; the copy is pushed; only then is it
3755
+ // the state. One change at a time. `fn` returns NO_SIRI_CHANGE when there is nothing to do (nothing pushed).
3756
+ // …and a restore() that landed while the push was out (a vault keep applying the account's merged Siri) is NOT
3757
+ // overwritten (sync sweep 2026-11-13 #2: the next keep pass then stamped the other devices' Spaces `gone` everywhere): the
3758
+ // change is made again on top of what landed and that is pushed — at most a few times, then the latest state stands.
3759
+ _change(fn) {
3760
+ const run = async () => {
3761
+ let out
3762
+ for (let i = 0; i < 4; i++) {
3763
+ const base = this._wb._siri
3764
+ const next = siriStateOf(JSON.parse(JSON.stringify(base)))
3765
+ out = await fn(next)
3766
+ if (out === NO_SIRI_CHANGE) return out
3767
+ await this._push(next)
3768
+ if (this._wb._siri === base) { this._wb._siri = next; return out }
3769
+ }
3770
+ throw sdkError('witbitz: the Siri state kept changing while it was being saved — try again', 'siri_busy')
3771
+ }
3772
+ const p = (this._q || Promise.resolve()).then(run, run)
3773
+ this._q = p.catch(() => {})
3774
+ return p
3775
+ }
3776
+ /** @private send the whole record — this account's, or `st`, a changed copy (_change) — sealed to the attested Sentinel
3777
+ * (idempotent: it REPLACES what it held). */
3778
+ async _push(st = this._wb._siri) {
3779
+ const wb = this._wb, auth = wb._auth()
3780
+ if (!st.token) st.token = newSiriKey()
3781
+ const rec = await siriRecordFor(await wb._account(), st)
3782
+ const post = wb._sentinelPost()
3783
+ const { nonce, key } = await attestStandingSentinel({ post, auth, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow })
3784
+ const sealed = await sealToEnclave(key, nonce, rec)
3785
+ const r = await post({ op: 'sentinel', sentinel: { mode: 'sirigrant', sealed }, ...auth })
3786
+ if (!r || r.error || !r.ok) throw (r ? Object.assign(new Error(`witbitz: the Sentinel refused the Siri record (${r.error || r.reason || 'refused'})`), { code: r.error || 'refused', ...(r.reason ? { reason: r.reason } : {}) }) : Object.assign(new Error('witbitz: the Sentinel did not answer'), { code: 'no_answer' }))
3787
+ return r
3788
+ }
3789
+ }
3790
+ const NO_SIRI_CHANGE = Symbol('no change')
3791
+
3792
+ /** `space.siri` — this Space's alias, and collecting what was said to it. */
3793
+ class SpaceSiri {
3794
+ constructor(space) { this._space = space }
3795
+ _wb() { const wb = this._space._wb; if (!wb) throw sdkError('witbitz: this Space has no client behind it — open it through a Witbitz instance', 'no_client'); return wb }
3796
+ /** Enable Siri for this Space: the word you will say ("groceries"), optionally the default for anything said
3797
+ * without an alias. Mints the Shortcut key on the first enable and an inbox keypair for this Space, pushes the
3798
+ * account's record to the Sentinel. → `{ key, endpoint, alias }` — the key is what the Shortcut sends. */
3799
+ async enable({ alias, label = '', makeDefault = false } = {}) {
3800
+ const wb = this._wb(), sp = this._space
3801
+ const a = normSiriAlias(alias)
3802
+ if (!a) throw sdkError('witbitz: an alias is needed — the word you will say to Siri', 'invalid_argument')
3803
+ if (/[,:;]/.test(a)) throw sdkError('witbitz: an alias cannot contain , : or ;', 'invalid_argument')
3804
+ return wb.siri._change(async (st) => { // kept only once the Sentinel took it (pass 9, K#5)
3805
+ for (const [rm, r] of Object.entries(st.rooms)) if (rm !== sp.room && r.alias === a) throw sdkError(`witbitz: "${a}" already names another Space`, 'invalid_argument')
3806
+ if (!st.token) st.token = newSiriKey()
3807
+ const cur = st.rooms[sp.room]
3808
+ if (cur) st.rooms[sp.room] = { ...cur, alias: a, label: label || cur.label, at: Date.now() } // the newer copy wins a merge (sync sweep 2026-11-15 #7)
3809
+ else { const kp = await genRecipientKey(); st.rooms[sp.room] = { alias: a, label: String(label || ''), pub: { x: kp.publicJwk.x, y: kp.publicJwk.y }, priv: kp.privateJwk, at: Date.now() } }
3810
+ if (makeDefault) st.defaultRoom = sp.room; else if (st.defaultRoom === sp.room) st.defaultRoom = ''
3811
+ return { key: st.token, endpoint: SIRI_ENDPOINT, alias: a }
3812
+ })
3813
+ }
3814
+ /** Disable Siri for this Space (other Spaces keep theirs). A push that fails rejects and keeps it on, here as at the Sentinel. */
3815
+ async disable() {
3816
+ const wb = this._wb(), room = this._space.room
3817
+ const r = await wb.siri._change((st) => { if (!st.rooms[room]) return NO_SIRI_CHANGE; delete st.rooms[room]; if (st.defaultRoom === room) st.defaultRoom = ''; return true })
3818
+ return { disabled: r === true }
3819
+ }
3820
+ /** Collect: pull the account's drops, open the ones for THIS Space with its inbox key, post each as you (🎙-marked),
3821
+ * ack them. → `{ delivered, elsewhere: [{ room, label, alias }] }` — `elsewhere` names other Spaces holding drops.
3822
+ *
3823
+ * `deliver(text, meta)` takes the drop INSTEAD of posting it — for an app that files captures into its own inbox and
3824
+ * does not want each one to start an assistant turn. It gets the words as spoken (no 🎙: that mark is for a room) and
3825
+ * `meta = { id, room, alias, at }`, where `alias` is the word that was actually said and `at` is when Siri took it.
3826
+ * Want it in the room as well? Call `space.send()` from inside your `deliver` — explicit beats a second flag.
3827
+ * ★ AT-LEAST-ONCE. A `deliver` that throws or rejects is NOT acked, so a failed write never eats a capture; the cost
3828
+ * is that a write which succeeds and whose ack then fails comes back. Dedupe on `meta.id`. */
3829
+ async collect({ deliver } = {}) {
3830
+ const wb = this._wb(), sp = this._space
3831
+ if (deliver !== undefined && typeof deliver !== 'function') throw sdkError('witbitz: collect({ deliver }) takes a function — deliver(text, meta)', 'invalid_argument')
3832
+ return collectSiriDrops({ post: wb._sentinelPost(), auth: wb._auth(), room: sp.room, send: async (t) => { const r = await sp.send(t); if (!r || !r.ok) throw sdkError('witbitz: the Space did not take the capture', 'not_sent') }, deliver: deliver || null, s: wb._siri }) // send never throws (offline → status 0, busy → ok:false): not sent is NOT acked, it is collected next time (sync sweep, 10-17 #3)
3833
+ }
3834
+ }
3835
+