@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
@@ -0,0 +1,480 @@
1
+ // sdkComputers.js — `wb.computers`: the person's CLOUD COMPUTERS from a builder's page (docs/sdk-cloud-computers.md; the owner,
2
+ // 2026-10-24: "The user pays, full sdk set, the keys are with the user"). The same engine as the Code section — the opening
3
+ // (codeCloud.js: attest the enclave and its Sentinel against the published images, seal the grant and the bundle), the sealed
4
+ // relay to its connector (codeTransport.js), the connector's own route list (codeRelay.js) — and what the Code section keeps,
5
+ // kept in THIS app's account index (sdkAccount.js), sealed like every account document: a computer made here is listed here.
6
+ //
7
+ // The keys are the person's: the workspace's half, the relay secret, the owner/recovery secrets, the model keys and the AWS
8
+ // key that pays for its hours (awsKey.js) sit in the sealed account documents and in this page's memory while it works —
9
+ // as room keys do without a vault. In vault mode (docs/sdk-cloud-computers.md phase 3) they stay in the vault.
10
+ //
11
+ // Every dependency is injectable (`deps`) so the whole thing runs against fakes in tests.
12
+
13
+ import { partsFor, parseModel, normRevert } from './opencodeWire.js'
14
+ import { undoTarget } from './codeUndo.js'
15
+ import { commandTurn, normCommands } from './codeCommands.js'
16
+ import { acceptEditsRules, askEditsRules, acceptsEdits } from './codeModes.js'
17
+ import { mkdirPath } from './codeMkdir.js'
18
+ import { newCloudComputer, openCloudComputer, closeCloud, CloudError } from './codeCloud.js'
19
+ import { mintCloudKeys } from './codeCloudKeys.js'
20
+ import { relayTransport } from './codeTransport.js'
21
+ import { CLOUD_DOC, COMPUTERS_DOC, normCloud, mergeCloud, withCloud, withoutCloud, normRegistry, mergeRegistry, withComputer, withoutComputer, liveComputers } from './codeComputers.js'
22
+ import { normEgress } from './codeEgress.js'
23
+ import { AWS_KEY_DOC, ensureAwsKey, signAws, awsKeyStatus } from './awsKey.js'
24
+ import { sealDoc, openDoc } from './accountSeal.js'
25
+ import { CODE_KEYS_REVOKE } from './codeOrphanKeys.js' // the one address (it was written three times — sync sweep backlog P3)
26
+ import { FILES_DOWNLOAD_ROUTE, FILES_UPLOAD_ROUTE, MAX_FILE_TRANSFER, keepBothName } from './codeFilesRoutes.js' // the Files sheet's routes (codeFiles.js)
27
+ import { OUTPUT_ROUTE, replyOutputs } from './codeOutputs.js' // what a reply produced, screenshots included (codeOutputCards.js)
28
+ import { watchUrl } from './codeBrowse.js'
29
+ import { setSessionPrivate } from './sdkBrowserPrivate.js'
30
+
31
+ const fail = (code, message, extra = {}) => Object.assign(new Error('witbitz: ' + message), { code, ...extra })
32
+ const SEG = /^(?!\.)[A-Za-z0-9_.-]{1,128}$/
33
+ const seg = (v, what) => { const s = String(v || ''); if (!SEG.test(s)) throw fail('invalid_argument', `${what} is not an id`); return encodeURIComponent(s) }
34
+ const withDir = (p, dir) => (dir ? p + (p.includes('?') ? '&' : '?') + 'directory=' + encodeURIComponent(dir) : p)
35
+ const sidQ = (sid) => encodeURIComponent(seg(sid, 'session') && String(sid))
36
+ const absPath = (p) => { const s = String(p || ''); if (!s.startsWith('/') || s.length > 4096 || /[\0\r\n]/.test(s)) throw fail('invalid_argument', 'a path on the computer is absolute (it starts with /)'); return s }
37
+ // bytes in any common shape → base64 (a builder hands a Blob from a file input, a Uint8Array, or base64 already)
38
+ async function toB64 (data) {
39
+ if (typeof data === 'string') {
40
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(data)) throw fail('invalid_argument', 'upload data as a string is base64')
41
+ if (data.length * 3 / 4 > MAX_FILE_TRANSFER) throw fail('too_large', `a file is at most ${MAX_FILE_TRANSFER / 1024 / 1024} MB`)
42
+ return data
43
+ }
44
+ if (data && typeof data.size === 'number' && data.size > MAX_FILE_TRANSFER) throw fail('too_large', `a file is at most ${MAX_FILE_TRANSFER / 1024 / 1024} MB`) // a Blob: before reading it
45
+ let u8 = null
46
+ if (data instanceof Uint8Array) u8 = data
47
+ else if (data instanceof ArrayBuffer) u8 = new Uint8Array(data)
48
+ else if (data && typeof data.arrayBuffer === 'function') u8 = new Uint8Array(await data.arrayBuffer())
49
+ if (!u8) throw fail('invalid_argument', 'upload data is a Blob, a File, an ArrayBuffer, a Uint8Array or base64')
50
+ if (u8.length > MAX_FILE_TRANSFER) throw fail('too_large', `a file is at most ${MAX_FILE_TRANSFER / 1024 / 1024} MB`)
51
+ let bin = ''; for (let i = 0; i < u8.length; i += 0x8000) bin += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000))
52
+ return btoa(bin)
53
+ }
54
+
55
+ /** What a builder sees of a computer: never a secret. */
56
+ const infoOf = (id, reg, cloud) => {
57
+ const r = reg.computers[id] || {}, c = cloud.cloud[id] || {}
58
+ return { id, name: r.name || 'Cloud computer', cloud: true, version: Number(c.version) || 0, egress: (c.egress && c.egress.mode) || 'none' }
59
+ }
60
+
61
+ export class Computers {
62
+ /** @param {object} wb the Witbitz client; @param {object} [deps] injectable engine (tests) */
63
+ constructor (wb, deps = {}) {
64
+ this._wb = wb
65
+ this._d = { open: openCloudComputer, close: closeCloud, mint: mintCloudKeys, transport: relayTransport, fetch: (...a) => fetch(...a), ...deps }
66
+ this._open = new Map() // id → Computer, while this page has it open
67
+ this._opening = new Map() // id → the open in flight (a second open() of the same id waits for it: one handover — K#3)
68
+ this._removed = new Set() // ids removed in this page: an open that finishes after its remove closes what it opened
69
+ }
70
+
71
+ // ── the account documents (sealed in this app's account index) ──────────────────────────────────────────────────────
72
+ async _store (name) {
73
+ this._guard()
74
+ const acc = this._wb.account
75
+ if (!acc || !acc.enabled) throw fail('not_enabled', 'turn the account on first (wb.backup.enable or restore) — a cloud computer lives in it')
76
+ const loc = await acc._where(), c = acc._client()
77
+ let v = null // the version get() read: put() lands only over it (sync sweep 11-08 #32)
78
+ return {
79
+ get: async () => {
80
+ const r = await c.state(loc.room, loc.mk, name)
81
+ if (!r || r.status !== 200) throw fail('unreadable', 'the account could not be read just now', { status: r && r.status })
82
+ v = Number.isInteger(r.v) ? r.v : null
83
+ const st = r.state
84
+ return st == null || (typeof st === 'object' && !Object.keys(st).length) ? null : openDoc(loc.key, st)
85
+ },
86
+ put: async (doc) => {
87
+ const w = await c.state(loc.room, loc.mk, name, await sealDoc(loc.key, doc), name, 'device', v ?? undefined)
88
+ if (w && w.status === 409) throw fail('moved', 'another device changed the account just now')
89
+ if (!w || w.status !== 200) throw fail('save_failed', 'the account could not be saved just now', { status: w && w.status })
90
+ },
91
+ }
92
+ }
93
+ async _read () {
94
+ const [rs, cs] = await Promise.all([this._store(COMPUTERS_DOC), this._store(CLOUD_DOC)])
95
+ const [reg, cloud] = await Promise.all([rs.get(), cs.get()])
96
+ return { reg: normRegistry(reg), cloud: normCloud(cloud), rs, cs }
97
+ }
98
+ /** Change both documents from what is there NOW (merged per entry by its own clock, as the Code section does). */
99
+ async _write (change) {
100
+ // each doc written only over the version read; another device's write in between → read, change and merge again
101
+ for (let i = 0; ; i++) {
102
+ const cur = await this._read()
103
+ const next = change(cur)
104
+ try {
105
+ await cur.rs.put({ ...mergeRegistry(next.reg, cur.reg), at: Date.now() })
106
+ await cur.cs.put({ ...mergeCloud(next.cloud, cur.cloud), at: Date.now() })
107
+ return
108
+ } catch (e) { if (!(e && e.code === 'moved') || i >= 4) throw e }
109
+ }
110
+ }
111
+ /** Not in vault mode yet (docs/sdk-cloud-computers.md phase 3): the keys must stay in the vault, so nothing here runs. */
112
+ _guard () { if (this._wb.vault) throw fail('vault_mode', 'cloud computers in vault mode come in a later release — the keys must stay in the vault') }
113
+ _token () { return this._wb._auth('a cloud computer belongs').idToken }
114
+ async _awsAdmit () {
115
+ const rec = await ensureAwsKey({ token: this._token(), store: await this._store(AWS_KEY_DOC), fetchImpl: this._d.fetch })
116
+ return signAws(rec, 'admit')
117
+ }
118
+
119
+ /** The account's cloud computers, newest first: `{ id, name, cloud, version, egress }` — never a secret. */
120
+ async list () {
121
+ this._guard()
122
+ const { reg, cloud } = await this._read()
123
+ return liveComputers(reg).filter((c) => cloud.cloud[c.id] && !cloud.cloud[c.id].removed).map((c) => infoOf(c.id, reg, cloud))
124
+ }
125
+
126
+ /**
127
+ * A new cloud computer. Its model keys come from the account (capped, like a paired laptop's) unless `keys` brings the
128
+ * person's own; its hours charge the person's AWS key when it is opened.
129
+ * @param {object} o { name?, keys?: { trustedRouter, tinfoil?, github? }, egress?, browsePrivate? }
130
+ */
131
+ async create ({ name = 'Cloud computer', keys = null, egress = null, browsePrivate = false } = {}) {
132
+ this._guard()
133
+ const k = keys && typeof keys === 'object' ? keys : null
134
+ const c = newCloudComputer({ name, key: k ? k.trustedRouter : '', tinfoil: k ? k.tinfoil : '', github: k ? k.github : '', browsePrivate })
135
+ if (egress != null) {
136
+ const e = normEgress(egress)
137
+ if (e.error) throw fail('invalid_argument', `egress: ${e.error}`)
138
+ c.cloud.egress = e.policy
139
+ }
140
+ if (!k || !k.trustedRouter) {
141
+ const got = await this._d.mint({ computerId: c.id, name: c.name, idToken: this._token(), fetchImpl: this._d.fetch })
142
+ if (!got.ok) throw fail(got.code || 'keys_refused', got.reason || 'the account did not give this computer its keys')
143
+ c.cloud.key = got.tr; if (got.tinfoil) c.cloud.tinfoil = got.tinfoil; if (got.venice) c.cloud.venice = got.venice; c.cloud.codeKey = got.codeKey
144
+ }
145
+ await this._write(({ reg, cloud }) => ({ reg: withComputer(reg, c.id, { name: c.name, relay: c.relay, secret: c.secret }), cloud: withCloud(cloud, c.id, c.cloud) }))
146
+ return { id: c.id, name: c.name, cloud: true, version: 0, egress: (c.cloud.egress && c.cloud.egress.mode) || 'none' }
147
+ }
148
+
149
+ /** Remove a computer: closed (a last save) and its account keys cancelled, best-effort; then dropped from the account. */
150
+ async remove (id) {
151
+ this._guard()
152
+ const { reg, cloud } = await this._read()
153
+ const entry = cloud.cloud[id]
154
+ if (!entry || entry.removed) throw fail('not_found', 'no such cloud computer in this account')
155
+ this._removed.add(id) // an open still in flight closes what it opened when it lands (pass 6, docs/state-machines.md K#3)
156
+ const open = this._open.get(id); if (open) open._stop()
157
+ let token = ''; try { token = this._token() } catch { /* signed out: removal still goes ahead */ }
158
+ if (token) {
159
+ await this._d.close({ id, ...(reg.computers[id] || {}), cloud: entry }, { token, fetchImpl: this._d.fetch }).catch(() => false)
160
+ await this._d.fetch(CODE_KEYS_REVOKE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ idToken: token, computerId: id }) }).catch(() => null)
161
+ }
162
+ await this._write(({ reg: r, cloud: cl }) => ({ reg: withoutComputer(r, id), cloud: withoutCloud(cl, id) }))
163
+ }
164
+
165
+ /**
166
+ * Open a computer: start or wake it, check it and its key guard run the published Witbitz images (a NEW published image is
167
+ * followed: `images` 'auto' accepts it, 'ask' calls `onNewImage(pcr0, role)` → true to accept), hand it the person's keys
168
+ * sealed, and connect. → a Computer.
169
+ * @param {string} id
170
+ * @param {object} [o] { onStep?(step), images?: 'auto' | 'ask', onNewImage?(pcr0, role) }
171
+ */
172
+ async open (id, o = {}) {
173
+ this._guard()
174
+ if (this._open.has(id)) return this._open.get(id)
175
+ // ★ ONE OPENING PER COMPUTER (pass 6, K#3): two open(id) calls not awaited in turn made two handovers and two Computers;
176
+ // the first one's close() then dropped the second from `_open`.
177
+ if (this._opening.has(id)) return this._opening.get(id)
178
+ const p = this._openNow(id, o).finally(() => { if (this._opening.get(id) === p) this._opening.delete(id) })
179
+ this._opening.set(id, p)
180
+ return p
181
+ }
182
+
183
+ async _openNow (id, { onStep = () => {}, images = 'auto', onNewImage = null } = {}) {
184
+ const { reg, cloud } = await this._read()
185
+ const entry = cloud.cloud[id], pair = reg.computers[id]
186
+ if (!entry || entry.removed || !pair || pair.removed) throw fail('not_found', 'no such cloud computer in this account')
187
+ const computer = { id, name: pair.name, relay: pair.relay, secret: pair.secret, cloud: entry }
188
+ const token = this._token()
189
+ const follow = { auto: () => images === 'auto', ask: async (p, role) => !!(typeof onNewImage === 'function' && await onNewImage(p, role)), fetch: this._d.fetch }
190
+ const save = (_c, patch) => { this._write(({ reg: r, cloud: cl }) => ({ reg: r, cloud: withCloud(cl, id, { ...cl.cloud[id], ...patch }) })).catch(() => {}) }
191
+ try {
192
+ // mint: null — a computer made with the builder's own keys (create({ keys })) STAYS on them: the app moves its pasted-key computers
193
+ // to account keys at opening (codeCloud.js), the SDK never does (docs: "keys stay yours"; sync sweep 11-21 #1)
194
+ await this._d.open(computer, { mint: null, token: async () => token, aws: () => this._awsAdmit(), save, openOpts: { onStep, follow, fetchImpl: this._d.fetch } })
195
+ } catch (e) {
196
+ if (e instanceof CloudError || (e && e.code)) throw Object.assign(fail(e.code || 'open_failed', String(e.message || e)), { status: e.status })
197
+ throw e
198
+ }
199
+ // ★ REMOVED WHILE IT OPENED (pass 6, K#3): remove() found nothing to close (the enclave was not up yet) and revoked the keys;
200
+ // this open then finished a handover — a removed computer running, and billed, until the host's idle stop. Close it now.
201
+ if (this._removed.has(id)) {
202
+ await this._d.close(computer, { token, fetchImpl: this._d.fetch }).catch(() => false)
203
+ throw fail('not_found', 'this cloud computer was removed while it opened')
204
+ }
205
+ const t = this._d.transport({ computer })
206
+ const c = new Computer(this, computer, t)
207
+ this._open.set(id, c)
208
+ return c
209
+ }
210
+
211
+ /** This month on the person's AWS key: `{ live, tier, month: { usd, capUsd }, resetsAt }`, or null before the first opening. */
212
+ async usage () {
213
+ this._guard()
214
+ const rec = await (await this._store(AWS_KEY_DOC)).get()
215
+ return rec && rec.keyId ? awsKeyStatus(rec, { fetchImpl: this._d.fetch }) : null
216
+ }
217
+ }
218
+
219
+ /** One open cloud computer: its coding sessions, the agent's approvals and questions, its files, and its live events. */
220
+ export class Computer {
221
+ constructor (owner, computer, transport) {
222
+ this._owner = owner
223
+ this._c = computer
224
+ this._t = transport
225
+ this._streams = new Map() // directory ('' = the server's default) → { stop, subs: Map(type → Set(fn)) }
226
+ // ★ THE SERVER SCOPES BY `directory` (opencodeApp.js withDir): an unscoped call reaches the server's DEFAULT project, so a
227
+ // session in another folder streamed nothing and its message / abort / todo calls missed it (sync sweep 11-08 #9 — only
228
+ // create scoped). Each session's folder is learned once (create, list, or GET /session/<id>, which answers unscoped)
229
+ // and sent on every call about it.
230
+ this._dirs = new Map() // session id → its directory
231
+ this.id = computer.id
232
+ this.name = computer.name
233
+ const req = (m, p, b) => this._req(m, p, b)
234
+ const learn = (x) => { if (x && typeof x.id === 'string' && typeof x.directory === 'string' && x.directory) this._dirs.set(x.id, x.directory); return x }
235
+ const inDir = async (sid, p) => withDir(p, await this._dirOf(sid))
236
+ // A CALL ABOUT NO ONE SESSION (approvals, questions, status, files) is scoped too (sync sweep 11-09, 11-08 #9 half fixed: the
237
+ // app sends the open session's folder, opencodeApp.js api; unscoped, an approval in another folder was never seen after a
238
+ // reload and the agent waited). `{ dir }` or `{ session }` scopes one call; with neither, a list is asked in EVERY folder the
239
+ // computer's sessions live in (learned from the session list once) and joined by id.
240
+ const scopeOf = async ({ session = '', dir = '' } = {}) => (dir ? String(dir) : session ? this._dirOf(session) : null)
241
+ const allDirs = async () => {
242
+ if (!this._dirs.size) { try { const l = await req('GET', '/experimental/session?archived=true'); if (Array.isArray(l)) l.forEach(learn) } catch { /* the default folder still answers */ } }
243
+ return ['', ...new Set([...this._dirs.values()].filter(Boolean))]
244
+ }
245
+ const listEverywhere = async (path, opts) => {
246
+ const one = await scopeOf(opts)
247
+ if (one !== null) return (await req('GET', withDir(path, one))) || []
248
+ const seen = new Map()
249
+ for (const d of await allDirs()) { let l = []; try { l = (await req('GET', withDir(path, d))) || [] } catch (e) { if (!d) throw e /* another folder's failure costs only its list */ } for (const x of Array.isArray(l) ? l : []) { const k = x && (x.id || x.requestID); if (k && !seen.has(k)) seen.set(k, x) } }
250
+ return [...seen.values()]
251
+ }
252
+ const modeAgents = new Map()
253
+ const sessionCall = async (sid, method, suffix = '', body) => req(method, await inDir(sid, '/session/' + seg(sid, 'session') + suffix), body)
254
+ const sendParts = (sid, parts, opts) => {
255
+ const model = parseModel(opts.model), agent = opts.agent || modeAgents.get(sid)
256
+ return sessionCall(sid, 'POST', '/message', { parts, ...(agent ? { agent } : {}), ...(model ? { model } : {}), ...(model && opts.effort ? { variant: String(opts.effort) } : {}) })
257
+ }
258
+ const models = async sid => {
259
+ const catalog = await req('GET', await inDir(sid, '/config/providers')).catch(() => null)
260
+ if (!Array.isArray(catalog?.providers)) {
261
+ const legacy = await req('GET', await inDir(sid, '/api/model'))
262
+ return (legacy?.data || []).map(m => ({ ref: m.providerID + '/' + m.id, label: m.name || m.id, efforts: Object.keys(m.variants || {}) }))
263
+ }
264
+ const owned = catalog.providers.filter(p => p.source !== 'custom')
265
+ return (owned.length ? owned : catalog.providers).flatMap(p => Object.entries(p.models || {}).filter(([, m]) => m && m.status !== 'deprecated').map(([id, m]) => ({
266
+ ref: p.id + '/' + id, label: m.name || id, efforts: Array.isArray(m.variants) ? m.variants.map(String) : Object.keys(m.variants || {}),
267
+ })))
268
+ }
269
+ this.sessions = {
270
+ list: async () => { const l = (await req('GET', '/experimental/session?archived=true')) || []; if (Array.isArray(l)) l.forEach(learn); return l },
271
+ create: async ({ dir = '', title = '' } = {}) => learn(await req('POST', withDir('/session', dir), title ? { title: String(title).slice(0, 200) } : {})),
272
+ messages: async (sid, { limit = 50 } = {}) => req('GET', await inDir(sid, `/session/${seg(sid, 'session')}/message?limit=${Math.max(1, Math.min(200, Number(limit) || 50))}`)),
273
+ prompt: async (sid, text, opts = {}) => sendParts(sid, partsFor(text, opts.files), opts),
274
+ models,
275
+ archive: (sid, archived = true) => sessionCall(sid, 'PATCH', '', { time: { archived: archived ? Date.now() : 0 } }),
276
+ undo: async sid => {
277
+ const [session, messages] = await Promise.all([sessionCall(sid, 'GET'), sessionCall(sid, 'GET', '/message')])
278
+ const messageID = undoTarget(messages, normRevert(session?.revert))
279
+ if (!messageID) return { changed: false, files: false }
280
+ const result = await sessionCall(sid, 'POST', '/revert', { messageID })
281
+ return { changed: true, files: !!normRevert(result?.revert)?.files }
282
+ },
283
+ redo: async sid => {
284
+ const revert = normRevert((await sessionCall(sid, 'GET'))?.revert)
285
+ if (!revert) return { changed: false, files: false }
286
+ await sessionCall(sid, 'POST', '/unrevert')
287
+ return { changed: true, files: revert.files }
288
+ },
289
+ compact: async (sid, model) => {
290
+ const selected = parseModel(model)
291
+ if (!selected) throw fail('invalid_argument', 'select a provider/model to summarize this session')
292
+ if ((await sessionCall(sid, 'GET'))?.revert) throw fail('undo_pending', 'redo or send a message before compacting')
293
+ return sessionCall(sid, 'POST', '/summarize', selected)
294
+ },
295
+ commands: async sid => normCommands(await req('GET', await inDir(sid, '/command'))),
296
+ runCommand: async (sid, text, opts = {}) => {
297
+ const turn = commandTurn(text, await this.sessions.commands(sid))
298
+ if (!turn || turn.blocked) throw fail(turn ? 'not_supported' : 'unknown_command', 'this project command is unavailable here')
299
+ const picked = { ...opts }
300
+ if (turn.model && (await models(sid)).some(m => m.ref === turn.model)) picked.model = turn.model
301
+ if (turn.agent) {
302
+ const agents = await req('GET', await inDir(sid, '/agent'))
303
+ if (agents.some(a => a.name === turn.agent && a.mode === 'primary' && !a.hidden)) picked.agent = turn.agent
304
+ }
305
+ return sendParts(sid, [{ type: 'text', text: turn.visible }, { type: 'text', text: turn.expanded, synthetic: true }, ...partsFor('', opts.files)], picked)
306
+ },
307
+ setApprovalMode: async (sid, mode) => {
308
+ if (!['manual', 'accept', 'plan', 'auto'].includes(mode)) throw fail('invalid_argument', 'unknown approval mode')
309
+ const auto = mode === 'auto', canAuto = !!this._t.can?.('auto')
310
+ if (auto && !canAuto) throw fail('not_supported', 'this computer does not offer Auto')
311
+ const session = await sessionCall(sid, 'GET'), dir = await this._dirOf(sid)
312
+ const autoOn = this._t.autoSessions?.().includes(sid) || false
313
+ if (autoOn && !auto && !this._t.setAuto(sid, dir, false)) throw fail('unavailable', 'could not turn off Auto')
314
+ if (acceptsEdits(session?.permission || []) !== (mode === 'accept')) await sessionCall(sid, 'PATCH', '', { permission: mode === 'accept' ? acceptEditsRules() : askEditsRules() })
315
+ if (!autoOn && auto && !this._t.setAuto(sid, dir, true)) throw fail('unavailable', 'could not turn on Auto')
316
+ modeAgents.set(sid, mode === 'plan' ? 'plan' : 'build')
317
+ return { mode }
318
+ },
319
+ abort: async (sid) => req('POST', await inDir(sid, `/session/${seg(sid, 'session')}/abort`), {}),
320
+ rename: async (sid, title) => req('PATCH', await inDir(sid, `/session/${seg(sid, 'session')}`), { title: String(title || '').slice(0, 200) }),
321
+ remove: async (sid) => { const r = await req('DELETE', await inDir(sid, `/session/${seg(sid, 'session')}`)); this._dirs.delete(String(sid)); return r },
322
+ todo: async (sid) => req('GET', await inDir(sid, `/session/${seg(sid, 'session')}/todo`)),
323
+ /** { <session id>: status } — `{ session }` or `{ dir }` for one folder; otherwise every folder's, joined. */
324
+ status: async (opts = {}) => {
325
+ const one = await scopeOf(opts)
326
+ if (one !== null) return req('GET', withDir('/session/status', one))
327
+ const out = {}
328
+ for (const d of await allDirs()) { try { Object.assign(out, (await req('GET', withDir('/session/status', d))) || {}) } catch (e) { if (!d) throw e } }
329
+ return out
330
+ },
331
+ }
332
+ this.approvals = {
333
+ /** Every approval waiting, in every folder — or `{ session }` / `{ dir }` for one. */
334
+ pending: async (opts = {}) => listEverywhere('/permission', opts),
335
+ /** 'once' | 'always' | 'reject'; a reject may carry a message for the model ("stop and ask me"). */
336
+ answer: async (id, response, { session = '', message = '' } = {}) => {
337
+ if (!['once', 'always', 'reject'].includes(response)) throw fail('invalid_argument', "an approval is 'once', 'always' or 'reject'")
338
+ if (response === 'reject' && message) {
339
+ // A connector from before the reply route refuses it (403/404/405): then the bare refusal on the old route, as the app does (codeApprovals.js).
340
+ // in the session's FOLDER (sync sweep 11-08: an approval in another folder than the default was never found)
341
+ const replyPath = `/permission/${seg(id, 'approval')}/reply`
342
+ try { return await req('POST', session ? await inDir(session, replyPath) : replyPath, { reply: 'reject', message: String(message).slice(0, 2000) }) } catch (e) { if (!session || ![403, 404, 405].includes(e.status)) throw e }
343
+ }
344
+ if (!session) throw fail('invalid_argument', 'answering an approval needs its session id (the event carries it as sessionID)')
345
+ return req('POST', await inDir(session, `/session/${seg(session, 'session')}/permissions/${seg(id, 'approval')}`), { response })
346
+ },
347
+ }
348
+ this.questions = {
349
+ pending: async (opts = {}) => listEverywhere('/question', opts),
350
+ /** `{ session }` (the event's sessionID) or `{ dir }`: the folder the question is in — a question in another folder than the
351
+ * computer's default is answered there (sync sweep 11-08); neither = the default folder, as before. */
352
+ answer: async (id, answers, opts = {}) => req('POST', withDir(`/question/${seg(id, 'question')}/reply`, (await scopeOf(opts)) || ''), { answers }),
353
+ dismiss: async (id, opts = {}) => req('POST', withDir(`/question/${seg(id, 'question')}/reject`, (await scopeOf(opts)) || '')),
354
+ }
355
+ const filesCan = () => { if (this._t.can && !this._t.can('files')) throw fail('not_supported', 'this computer does not move files yet (an older image or connector)') }
356
+ // a reply's files are their own capability (the connector's hello says `outputs`; codeOutputCards.js) — a computer that
357
+ // moves files may not serve them yet (sync sweep 11-08 #33)
358
+ const outputsCan = () => { if (this._t.can && !this._t.can('outputs')) throw fail('not_supported', 'this computer does not serve a reply\'s files yet (an older image or connector)') }
359
+ this.files = {
360
+ mkdir: async (sid, parent, name) => {
361
+ const relative = String(parent || ''), leaf = String(name || '').trim()
362
+ if (!leaf || leaf === '.' || leaf === '..' || /[\\/:\x00-\x1f]/.test(leaf) || relative.startsWith('/') || /[\\:\x00-\x1f]/.test(relative) || relative.split('/').includes('..')) throw fail('invalid_argument', 'use a relative parent folder and one folder name')
363
+ return req('POST', await inDir(sid, mkdirPath(relative)), { name: leaf })
364
+ },
365
+ // the folder's project: `{ session }` (that session's folder) or `{ dir }`; neither = the computer's default project
366
+ list: async (path = '', opts = {}) => req('GET', withDir('/file?path=' + encodeURIComponent(String(path || '')), (await scopeOf(opts)) || '')),
367
+ changes: async (opts = {}) => req('GET', withDir('/vcs/status', (await scopeOf(opts)) || '')),
368
+ diff: async (opts = {}) => req('GET', withDir('/vcs/diff?mode=git', (await scopeOf(opts)) || '')),
369
+ // FILES (the Code section's Files sheet, codeFiles.js — the owner's "build later" list, 2026-10-28): a file of the session's
370
+ // folder, never one outside it or one that looks like a secret (the connector refuses those), at most 20 MB.
371
+ /** → { name, kind, mime, size, mtime, b64 } */
372
+ download: async (session, path) => { filesCan(); return req('GET', `${FILES_DOWNLOAD_ROUTE}?session=${sidQ(session)}&path=${encodeURIComponent(absPath(path))}`) },
373
+ /** Into folder `dir` of the session. A name already there: onExists 'fail' (default — `exists`), 'replace', or 'keepBoth'
374
+ * ("report (2).pdf"). → { ok, name, path, size } */
375
+ upload: async (session, { dir, name, data, onExists = 'fail' } = {}) => {
376
+ filesCan()
377
+ if (!['fail', 'replace', 'keepBoth'].includes(onExists)) throw fail('invalid_argument', "onExists is 'fail', 'replace' or 'keepBoth'")
378
+ const n = String(name || '').trim()
379
+ if (!n || /[/\\\0]/.test(n) || n === '.' || n === '..' || n.length > 255) throw fail('invalid_argument', 'a file name, without a folder')
380
+ const b64 = await toB64(data)
381
+ const route = `${FILES_UPLOAD_ROUTE}?session=${sidQ(session)}`
382
+ const send = async (nm, replace) => this._t.request('POST', route, { dir: absPath(dir), name: nm, b64, ...(replace ? { replace: true } : {}) })
383
+ let r = await send(n, onExists === 'replace')
384
+ if (r && r.status === 409 && r.json && r.json.exists && onExists === 'keepBoth') {
385
+ let taken = new Set(); try { const l = await req('GET', '/file?path=' + encodeURIComponent(absPath(dir))); taken = new Set((Array.isArray(l) ? l : []).map((e) => e && e.name)) } catch { taken = new Set([n]) }
386
+ taken.add(n); r = await send(keepBothName(n, (x) => taken.has(x)), false)
387
+ }
388
+ if (r && r.status === 409 && r.json && r.json.exists) throw fail('exists', `${n} is already in that folder`, { status: 409, replaceable: !!r.json.replaceable })
389
+ if (!r || !r.ok) throw fail(r && r.status === 403 ? 'refused' : 'request_failed', `upload ${n} — ${(r && ((r.json && r.json.error) || r.status)) || 'no answer'}`.slice(0, 300), { status: r && r.status })
390
+ return r.json
391
+ },
392
+ /** A file a reply produced (outputs()), screenshots included → { name, kind, mime, size, b64 } */
393
+ output: async (session, path) => { outputsCan(); return req('GET', `${OUTPUT_ROUTE}?session=${sidQ(session)}&path=${encodeURIComponent(absPath(path))}`) },
394
+ }
395
+ // THE AGENT'S BROWSER: its report, and PRIVATE browsing (codeTransport setBrowsePrivate) — where the computer says it can
396
+ // (`canPrivate`: witbitz-code's browser on the person's own computer; a cloud image without it answers not_supported).
397
+ this.browser = {
398
+ status: () => (this._t.browse ? this._t.browse() : null),
399
+ url: (opts = {}) => { if (opts.session !== undefined && !/^[A-Za-z0-9_-]{1,128}$/.test(String(opts.session))) throw fail('invalid_argument', 'session is not an id'); return watchUrl({ ...this._c.cloud, relay: this._c.relay }, opts) },
400
+ get private () { const b = transport.browse ? transport.browse() : null; return !!(b && b.private) },
401
+ /** → true when sent (the computer's next report confirms it). */
402
+ setPrivate: (on) => {
403
+ const b = this._t.browse ? this._t.browse() : null
404
+ if (!b || !b.canPrivate || typeof this._t.setBrowsePrivate !== 'function') throw fail('not_supported', 'this computer\'s browser has no private mode')
405
+ if (!this._t.setBrowsePrivate(!!on)) throw fail('offline', 'the computer is not connected')
406
+ return true
407
+ },
408
+ setSessionPrivate: (session, on) => setSessionPrivate({ ...this._c.cloud, relay: this._c.relay }, session, on),
409
+ }
410
+ this.egress = { get: () => (this._t.egress ? this._t.egress() : null) }
411
+ }
412
+
413
+ /** What a reply PRODUCED — files it wrote, the browser's screenshots, files its answer names that changed (codeOutputs.js,
414
+ * the Code section's previews). `messages`: the reply's messages (sessions.messages); omitted = the session's latest.
415
+ * → [{ path, kind: 'pdf'|'image'|'table'|'text'|'file', source: 'wrote'|'shot'|'named' }] — fetch one with files.output(). */
416
+ async outputs (session, messages) {
417
+ const sid = String(session || ''); seg(sid, 'session')
418
+ const info = await this._req('GET', `/session/${encodeURIComponent(sid)}`)
419
+ if (info && typeof info.directory === 'string' && info.directory) this._dirs.set(sid, info.directory)
420
+ let ms = Array.isArray(messages) ? messages : ((await this._req('GET', withDir(`/session/${encodeURIComponent(sid)}/message?limit=20`, this._dirs.get(sid) || ''))) || [])
421
+ if (!Array.isArray(messages)) { const k = ms.map((m) => m && m.info && m.info.role).lastIndexOf('user'); ms = k >= 0 ? ms.slice(k + 1) : ms } // the latest reply: after the last prompt
422
+ return replyOutputs(ms, { directory: (info && info.directory) || '', session: sid })
423
+ }
424
+
425
+ /** 'online' | 'connecting' | 'offline' */
426
+ get status () { return this._t.status() }
427
+
428
+ async _req (method, path, body) {
429
+ const r = await this._t.request(method, path, body)
430
+ if (!r || !r.ok) {
431
+ const code = r && r.status === 403 ? 'refused' : r && r.status === 404 ? 'not_found' : 'request_failed'
432
+ throw fail(code, `${method} ${path.split('?')[0]} — ${(r && (r.text || r.status)) || 'no answer'}`.slice(0, 300), { status: r && r.status })
433
+ }
434
+ return r.json
435
+ }
436
+
437
+ /** @private a session's directory — learned once, then kept ('' when the computer does not say) */
438
+ async _dirOf (sid) {
439
+ const id = String(sid || '')
440
+ if (this._dirs.has(id)) return this._dirs.get(id)
441
+ let d = '', known = false
442
+ try { const info = await this._req('GET', `/session/${encodeURIComponent(seg(id, 'session') && id)}`); d = info && typeof info.directory === 'string' ? info.directory : ''; known = true } catch { d = '' }
443
+ if (known) this._dirs.set(id, d) // an answer without a folder is kept too (asked once); a failed ask is asked again next time
444
+ return d
445
+ }
446
+
447
+ /** Live events from the computer (OpenCode's, parsed): `on('message.part.updated', fn)`, or `on('*', fn)` for all. → off
448
+ * The computer streams per FOLDER: pass `{ session }` (its folder is looked up) or `{ dir }` for a session outside the
449
+ * server's default folder — without it, its events never arrive. */
450
+ on (type, fn, { session = '', dir = '' } = {}) {
451
+ if (typeof fn !== 'function') throw fail('invalid_argument', 'on(type, fn) needs a function')
452
+ let off = false, stream = null
453
+ const attach = (d) => {
454
+ if (off) return
455
+ stream = this._streams.get(d)
456
+ if (!stream) {
457
+ stream = { subs: new Map(), stop: null }
458
+ this._streams.set(d, stream)
459
+ const st = stream
460
+ st.stop = this._t.subscribe(withDir('/event', d), (ev) => {
461
+ for (const key of [ev && ev.type, '*']) for (const f of st.subs.get(key) || []) { try { f(ev) } catch { /* a builder's handler never stops the stream */ } }
462
+ })
463
+ }
464
+ if (!stream.subs.has(type)) stream.subs.set(type, new Set())
465
+ stream.subs.get(type).add(fn)
466
+ }
467
+ if (dir || !session) attach(String(dir || ''))
468
+ else this._dirOf(session).then(attach, () => attach(''))
469
+ return () => { off = true; const s = stream && stream.subs.get(type); if (s) s.delete(fn) }
470
+ }
471
+
472
+ _stop () { for (const st of this._streams.values()) { try { if (st.stop) st.stop() } catch { /* */ } } this._streams.clear(); try { this._t.close() } catch { /* */ } if (this._owner._open.get(this.id) === this) this._owner._open.delete(this.id) } // only itself: never a newer opening of the same computer
473
+
474
+ /** Close it: a last save, then the enclave stops (its hours stop counting). */
475
+ async close () {
476
+ this._stop()
477
+ let token = ''; try { token = this._owner._token() } catch { return false }
478
+ return this._owner._d.close(this._c, { token, fetchImpl: this._owner._d.fetch })
479
+ }
480
+ }
@@ -0,0 +1,142 @@
1
+ // sdkDictation.js — wb.dictation(): press-to-talk for a builder's page, the same engine the Spaces app runs (sttCloud.js).
2
+ //
3
+ // const mic = wb.dictation()
4
+ // await mic.start({ onPartial: (t) => (input.value = t) }) // on press: asks for the mic, the words stream in
5
+ // input.value = await mic.stop() // on release: the final text (~0.5 s)
6
+ // mic.cancel() // a press thrown away (its audio dropped server-side too)
7
+ //
8
+ // The microphone streams STRAIGHT from the page to Tinfoil's confidential realtime enclave (Voxtral Mini 4B Realtime) —
9
+ // never through Witbitz. Witbitz only mints the page a short-lived, capped key (op:'stt', agent/sttKey.mjs), and only for
10
+ // a signed-in person (wb.signIn) or a user the tenant's backend vouched for (wb.useUserToken). One connection is kept
11
+ // across presses and closed after 15 quiet minutes ($0.002 per connection, whatever is said on it). https://witbitz.chat/docs/sdk-assistant.md#dictation.
12
+ // ⚑ 13 languages, NOT Hebrew. ⚑ The page's own CSP must allow `connect-src wss://inference.tinfoil.sh` and the worklet
13
+ // script from this origin; the microphone needs a secure context and the browser's permission.
14
+
15
+ import { voicePayload } from './voiceCert.js'
16
+
17
+ const certifications = new WeakMap()
18
+ export function voiceForDictation(result, room) {
19
+ const held = certifications.get(result)
20
+ if (!held || held.room !== room) throw err('dictation_room_mismatch', 'use the dictation result from this room')
21
+ return voicePayload(room, held.stt)
22
+ }
23
+
24
+ const err = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
25
+
26
+ export class Dictation {
27
+ constructor(wb, { WebSocketImpl, getUserMedia } = {}) {
28
+ this._wb = wb
29
+ this._WS = WebSocketImpl
30
+ this._gum = getUserMedia || ((c) => navigator.mediaDevices.getUserMedia(c))
31
+ this._engine = null // sttCloud's engine, made on the first press
32
+ this._mod = null
33
+ this._stream = null
34
+ this._capture = null
35
+ this._live = false
36
+ }
37
+
38
+ /** true between start() and stop()/cancel(). */
39
+ get listening() { return this._live }
40
+
41
+ /** @private who the key is for: a signed-in session first (the person), else the tenant's user token. */
42
+ async _who() {
43
+ const wb = this._wb
44
+ const sess = wb._session
45
+ const idToken = sess && sess.idToken && !(sess.exp && sess.exp <= Date.now()) ? sess.idToken : ''
46
+ let userToken = ''
47
+ try { const t = typeof wb._userToken === 'function' ? await wb._userToken() : wb._userToken; userToken = typeof t === 'string' ? t : '' } catch { userToken = '' }
48
+ if (!idToken && !userToken && !wb.vault) throw err('sign_in_required', 'dictation needs a signed-in user (wb.signIn) or a user token (wb.useUserToken)') // in a vault, the vault's sign-in mints the key
49
+ return { idToken, userToken }
50
+ }
51
+
52
+ /** @private the page's key (op:'stt'). */
53
+ async _key() {
54
+ const { idToken, userToken } = await this._who()
55
+ const wb = this._wb
56
+ const r = await wb._client.stt(idToken, userToken)
57
+ if (r && r.status === 200 && r.key) {
58
+ this._stt = r.cert?.bundle ? { model: r.model, cert: structuredClone(r.cert), bundleGz: r.bundleGz } : null
59
+ return r
60
+ } // the endpoint itself is pinned in sttCloud.js, never taken from here
61
+ const raw = (r && r.error) || 'stt_unavailable'
62
+ const code = raw === 'signin_required' ? 'sign_in_required' : raw // the SDK's one spelling (sync sweep, 2026-10-10; the server says signin_required)
63
+ throw err(code, code === 'sign_in_required' ? 'the sign-in or user token was refused — sign in again'
64
+ : code === 'stt_rate_limited' ? `too many voice keys this hour — try again in ${(r && r.retryAfterS) || 60} s`
65
+ : 'the voice service could not issue a key')
66
+ }
67
+
68
+ async _load() {
69
+ if (!this._mod) this._mod = await import('./sttCloud.js')
70
+ if (!this._engine) this._engine = this._mod.createCloudStt({ getKey: () => this._key(), ...(this._WS ? { WebSocketImpl: this._WS } : {}) })
71
+ return this._engine
72
+ }
73
+
74
+ /** Begin a press. Resolves once the microphone is live and the connection is up (audio said meanwhile is queued).
75
+ * @param {{ onPartial?: (text:string)=>void, onLevel?: (rms:number)=>void }} [opts] */
76
+ async start({ onPartial, onLevel, room } = {}) {
77
+ if (this._live) throw err('already_listening', 'dictation is already listening — stop() or cancel() first')
78
+ await this._who() // refuse before asking for the microphone
79
+ const engine = await this._load()
80
+ this._live = true
81
+ this._room = typeof room === 'string' ? room : null
82
+ try {
83
+ this._stream = await this._gum({ audio: { channelCount: 1, echoCancellation: true, autoGainControl: true, noiseSuppression: true } })
84
+ } catch (e) {
85
+ this._live = false
86
+ throw err('mic_denied', 'microphone access was refused: ' + String((e && e.message) || e))
87
+ }
88
+ const ready = engine.begin({ onPartial: (t) => { try { onPartial && onPartial(t) } catch { /* the page's callback */ } } })
89
+ ready.catch(() => {}) // awaited below; this only keeps a capture failure from leaving it unhandled
90
+ try {
91
+ this._capture = await this._mod.startCapture(this._stream, ({ pcm, rms }) => {
92
+ engine.append(pcm)
93
+ if (onLevel) { try { onLevel(rms) } catch { /* the page's callback */ } }
94
+ })
95
+ await ready
96
+ } catch (e) {
97
+ this._release()
98
+ try { engine.cancel() } catch { /* */ }
99
+ this._live = false
100
+ throw e && e.code ? e : err('stt_unavailable', String((e && e.message) || e))
101
+ }
102
+ }
103
+
104
+ /** End the press. → the final text ('' if nothing was said). */
105
+ async stop() {
106
+ if (!this._live) return ''
107
+ this._live = false
108
+ this._release()
109
+ return this._engine.commit()
110
+ }
111
+
112
+ /** Finish room-bound dictation and return the public certificate alongside the transcript. */
113
+ async stopCertified() {
114
+ if (!this._live || !this._room) throw err('dictation_room_required', 'start dictation with the destination room')
115
+ const room = this._room, stt = this._stt
116
+ const text = await this.stop()
117
+ const result = Object.freeze({ text, room, certificate: stt?.cert ? structuredClone(stt.cert) : null })
118
+ certifications.set(result, { room, stt })
119
+ return result
120
+ }
121
+
122
+ /** Throw the press away. */
123
+ cancel() {
124
+ if (!this._live) return
125
+ this._live = false
126
+ this._release()
127
+ try { this._engine.cancel() } catch { /* */ }
128
+ }
129
+
130
+ /** Close the connection now (otherwise it closes itself after 15 quiet minutes). */
131
+ close() {
132
+ this.cancel()
133
+ try { this._engine && this._engine.close() } catch { /* */ }
134
+ }
135
+
136
+ _release() {
137
+ try { this._capture && this._capture.stop() } catch { /* */ }
138
+ this._capture = null
139
+ try { this._stream && this._stream.getTracks().forEach((t) => t.stop()) } catch { /* */ }
140
+ this._stream = null
141
+ }
142
+ }