@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/streamHint.js ADDED
@@ -0,0 +1,36 @@
1
+ // streamHint.js — what a phone does with a change HINT for the room it has OPEN while it holds that room's stream
2
+ // (docs/change-inbox.md § Room streams). The stream carries what a TURN writes and nothing else, so a hint is explained
3
+ // by the stream only when it is about a turn the stream actually delivered:
4
+ // · the socket is down → poll (the stream explains nothing it did not deliver)
5
+ // · a turn STARTING (t:'start') → nothing: its frames follow on the stream
6
+ // · a turn ENDING (t:'end') → nothing if the stream delivered that turn's END frame; otherwise poll
7
+ // once — a silent turn, a turn that failed before streaming, a lost frame
8
+ // · any other change → poll once: a reaction, a widget, a photo caption, the room's config —
9
+ // and the ALLOW-LIST, whose edit rotates a gated room's stream grant, so
10
+ // this poll is how the members who remain pick up the new one
11
+ // Pure; the page and the emulator (infra/enclave/emulator/lab.mjs) both follow it.
12
+
13
+ /** How long an end hint and its end frame may be apart and still be the same turn. They travel different channels. */
14
+ export const END_FRAME_WINDOW_MS = 5000
15
+ /** How long to wait for the end frame when the end HINT arrives first. */
16
+ export const END_HINT_GRACE_MS = 1000
17
+
18
+ export const isEndFrame = (f) => !!(f && f.k === 'end')
19
+
20
+ /** 'none' | 'poll' | 'wait' ('wait': an end hint with no end frame yet — ask again after END_HINT_GRACE_MS, then poll). */
21
+ export function openRoomHintAction (hint, { streamUp = false, lastEndFrameAt = 0, now = Date.now(), waited = false } = {}) {
22
+ if (!streamUp) return 'poll'
23
+ const t = hint && hint.t
24
+ if (t === 'start') return 'none'
25
+ if (t === 'end') {
26
+ if (lastEndFrameAt && Math.abs(now - lastEndFrameAt) <= END_FRAME_WINDOW_MS) return 'none'
27
+ return waited ? 'poll' : 'wait'
28
+ }
29
+ return 'poll'
30
+ }
31
+
32
+ /** After a poll of a gated room: did its grants change (a rotation)? Then drop the old channels and open the new ones. */
33
+ export function grantsChanged (prev, next) {
34
+ const ids = (l) => (Array.isArray(l) ? l.map((x) => x && x.g).join(',') : '')
35
+ return ids(prev) !== ids(next)
36
+ }
package/sttCloud.js ADDED
@@ -0,0 +1,220 @@
1
+ // sttCloud.js — press-to-talk's CLOUD engine: the microphone streams to Tinfoil's confidential realtime enclave
2
+ // (Voxtral Mini 4B Realtime, Mistral) over a websocket, STRAIGHT from the page — our servers never see the audio.
3
+ //
4
+ // Measured 2026-10-03 (docs/stt-cloud.md): first words ~1.5–3 s into speech, the final text 0.44 s after release, English
5
+ // WER 4.5% on FLEURS (Whisper turbo 3.9%), $0.002 per CONNECTION whatever is said on it — so ONE connection is kept open
6
+ // across presses (commit on release) and closed after a quiet spell. ⚑ No Hebrew: the model's 13 languages do not
7
+ // include it (Hebrew speech comes back in Latin letters), by the owner's choice "leave Hebrew as today".
8
+ //
9
+ // The key: getKey() → { key, url, expiresAt } from op:'stt' (agent/sttKey.mjs) — short-lived, capped, minted for the
10
+ // signed-in account. A browser cannot set headers on a websocket, so the key rides as the `openai-insecure-api-key.`
11
+ // subprotocol, which Tinfoil's router accepts and does NOT echo back (measured: it negotiates plain "realtime").
12
+
13
+ // beside THIS module, whichever page (the room, Code's frame) imported it — addModule() resolves against the document otherwise
14
+ // THE ENDPOINT IS PINNED HERE, in the signed page — not taken from the server's answer. The key comes from op:'stt'; where the
15
+ // microphone goes does not: a compromised server could otherwise point the page at any host its CSP allows (our own relay
16
+ // included). Changing the endpoint is a page release, which the audit reproduces and the certificate signs.
17
+ export const STT_URL = 'wss://inference.tinfoil.sh/v1/realtime?model=voxtral-mini-4b-realtime&intent=transcription'
18
+ // …and before the microphone goes there, the page checks the key's evidence ITSELF (voiceAttest.js) — not only our server.
19
+ import { checkSpeechKey } from './voiceAttest.js'
20
+ // a module run from the vault's copy (a blob: URL; docs/hosted-app-plan.md step 8) has no address to resolve beside — the page's
21
+ const MODULE_BASE = String(import.meta.url).startsWith('blob:') ? location.href : import.meta.url
22
+ const WORKLET_URL = new URL('./sttWorklet.js', MODULE_BASE).href
23
+ const b64 = (ab) => { const u = new Uint8Array(ab); let s = ''; for (let i = 0; i < u.length; i += 0x8000) s += String.fromCharCode.apply(null, u.subarray(i, i + 0x8000)); return btoa(s) }
24
+
25
+ /** One engine per app window (voiceInput.js keeps it on the shared engine, like the on-device one). */
26
+ export function createCloudStt ({ getKey, checkKey = checkSpeechKey, WebSocketImpl = globalThis.WebSocket, now = () => Date.now(), idleMs = 15 * 60_000, commitTimeoutMs = 10_000, connectTimeoutMs = 10_000 }) {
27
+ let key = null, ws = null, connecting = null, idleTimer = 0
28
+ let cur = null // the press in progress: { onPartial, text, cancelled, finish }
29
+ let committing = null // the press whose release is waiting for its final text
30
+ const queue = [] // frames captured while the connection was still opening — so the first words are not lost
31
+
32
+ async function freshKey () {
33
+ if (!key || Date.parse(key.expiresAt) - now() < 10 * 60_000) {
34
+ const k = await getKey()
35
+ if (!k || !k.key) throw new Error('no voice key')
36
+ await checkKey(k) // throws voice_unattested: no socket is opened
37
+ key = k
38
+ }
39
+ return key
40
+ }
41
+ const send = (o) => { if (ws && ws.readyState === 1) ws.send(JSON.stringify(o)) }
42
+ function scheduleIdle () { clearTimeout(idleTimer); idleTimer = setTimeout(() => close(), idleMs) }
43
+ function close () {
44
+ clearTimeout(idleTimer)
45
+ const sock = ws; ws = null
46
+ if (sock) { sock.onclose = null; sock.onmessage = null; try { sock.close() } catch { /* */ } }
47
+ cur = null; committing = null; queue.length = 0
48
+ }
49
+
50
+ function connect () {
51
+ if (ws && ws.readyState === 1) return Promise.resolve()
52
+ if (connecting) return connecting
53
+ connecting = (async () => {
54
+ const k = await freshKey()
55
+ const sock = new WebSocketImpl(STT_URL, ['realtime', 'openai-insecure-api-key.' + k.key])
56
+ await new Promise((resolve, reject) => {
57
+ const t = setTimeout(() => { reject(new Error('the voice service did not answer')); try { sock.close() } catch { /* */ } }, connectTimeoutMs)
58
+ sock.onopen = () => { clearTimeout(t); resolve() }
59
+ sock.onerror = () => { clearTimeout(t); reject(new Error('could not reach the voice service')) }
60
+ sock.onclose = (e) => { clearTimeout(t); reject(new Error('the voice service closed the connection (' + e.code + ')')) }
61
+ })
62
+ ws = sock
63
+ ws.onmessage = (m) => { if (ws === sock) onEvent(m) } // a retired socket's late events reach no press
64
+ ws.onclose = () => {
65
+ if (ws !== sock) return
66
+ ws = null
67
+ if (cur && cur.finish) cur.finish(cur.text) // keep what streamed; the next press reconnects
68
+ else if (cur && !cur.cancelled && cur.onError) cur.onError(new Error('speech connection closed during recording'))
69
+ }
70
+ ws.onerror = () => {}
71
+ send({ type: 'session.update', session: { type: 'transcription', audio: { input: { format: { type: 'audio/pcm', rate: 16000 } } } } })
72
+ while (queue.length) send({ type: 'input_audio_buffer.append', audio: queue.shift() })
73
+ })()
74
+ connecting.finally(() => { connecting = null }).catch(() => {})
75
+ return connecting
76
+ }
77
+
78
+ // ★ A PRESS'S TEXT COMES ONLY FROM ITS OWN AUDIO (pass 5, V#12): the service's events carry no press id, so after a ✕ mid-press
79
+ // or a release whose final text timed out, words still on their way from THAT audio landed in the next press on the same
80
+ // connection. Such a connection is RETIRED — closed, its events ignored — and the next press opens a fresh one (one more
81
+ // $0.002 connection, only in those two cases). A release still waiting when a new press begins keeps what had streamed.
82
+ function retire () {
83
+ const s = ws; ws = null
84
+ if (s) { s.onmessage = null; s.onclose = null; try { s.close() } catch { /* */ } }
85
+ const c = committing; committing = null
86
+ if (c && c.finish) c.finish(c.text)
87
+ }
88
+
89
+ function onEvent (m) {
90
+ let e; try { e = JSON.parse(m.data) } catch { return }
91
+ if (!cur || cur.cancelled) return
92
+ if (/transcription\.delta$/.test(e.type) && typeof e.delta === 'string') { cur.text += e.delta; cur.onPartial(cur.text) }
93
+ else if (/transcription\.completed$/.test(e.type)) { if (cur.finish) cur.finish(typeof e.transcript === 'string' && e.transcript ? e.transcript : cur.text) }
94
+ else if (e.type === 'error' && cur.finish && /commit_empty/.test(JSON.stringify(e))) cur.finish('') // released before any audio arrived
95
+ }
96
+
97
+ return {
98
+ /** A press: start a turn (connection opens if needed — frames are queued meanwhile). */
99
+ begin ({ onPartial, onError }) {
100
+ clearTimeout(idleTimer)
101
+ if (committing) retire() // the last release's final text is still on its way: it must not become this press's
102
+ queue.length = 0
103
+ cur = { onPartial: onPartial || (() => {}), onError, text: '', cancelled: false, finish: null }
104
+ return connect()
105
+ },
106
+ /** One 100 ms PCM16 frame (ArrayBuffer) from the worklet. */
107
+ append (pcm) {
108
+ if (!cur || cur.cancelled) return
109
+ const a = b64(pcm)
110
+ if (ws && ws.readyState === 1) send({ type: 'input_audio_buffer.append', audio: a }); else if (queue.length < 600) queue.push(a) // ≤ 60 s queued
111
+ },
112
+ /** Release: commit and wait for the final text (or keep the streamed partial on timeout/close). → text */
113
+ async commit () {
114
+ if (!cur) return ''
115
+ const c = cur
116
+ committing = c
117
+ const done = new Promise((resolve) => {
118
+ const t = setTimeout(() => { c.finish = null; if (committing === c) retire(); resolve(c.text) }, commitTimeoutMs) // its final text may still come: not into the next press
119
+ c.finish = (text) => { clearTimeout(t); c.finish = null; resolve(text) }
120
+ })
121
+ try { await connect() } catch { /* the queued audio is lost with the connection; what streamed is kept */ }
122
+ if (ws && ws.readyState === 1) send({ type: 'input_audio_buffer.commit' }); else if (c.finish) c.finish(c.text)
123
+ const text = await done
124
+ if (committing === c) committing = null
125
+ if (cur === c) cur = null
126
+ scheduleIdle()
127
+ return text
128
+ },
129
+ /** Cancel the press: drop its audio on the server too, keep the connection for the next one. */
130
+ cancel () {
131
+ const live = !!cur
132
+ if (cur) cur.cancelled = true
133
+ cur = null
134
+ queue.length = 0
135
+ send({ type: 'input_audio_buffer.clear' })
136
+ if (live && ws) retire() // words of the cancelled audio may still be on their way (V#12)
137
+ scheduleIdle()
138
+ },
139
+ close,
140
+ get connected () { return !!(ws && ws.readyState === 1) },
141
+ }
142
+ }
143
+
144
+ /** The microphone → 16 kHz PCM16 frames via the worklet. → { stop() } — stop() releases the audio graph (the caller
145
+ * owns the MediaStream and stops its tracks, as voiceInput.js already does for the on-device engine). */
146
+ export async function startCapture (stream, onFrame, { onError = () => {}, onDiagnostic = () => {}, stallMs = 5000 } = {}) {
147
+ const AC = window.AudioContext || window.webkitAudioContext
148
+ const ctx = new AC()
149
+ const tracks = stream.getAudioTracks ? stream.getAudioTracks() : stream.getTracks()
150
+ let src, node, timer, stopped = false, ready = false, resuming = false, lastFrame = Date.now()
151
+ let mutedAt = tracks.some(tr => tr.muted) ? Date.now() : 0
152
+ let resolveReady, rejectReady
153
+ const firstFrame = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject })
154
+ const trace = (text) => { try { onDiagnostic(text) } catch { /* */ } }
155
+ const stop = () => {
156
+ if (stopped) return
157
+ stopped = true; clearInterval(timer)
158
+ ctx.removeEventListener('statechange', stateChanged)
159
+ for (const tr of tracks) {
160
+ tr.removeEventListener('ended', ended)
161
+ tr.removeEventListener('mute', muteChanged)
162
+ tr.removeEventListener('unmute', muteChanged)
163
+ }
164
+ if (node) { node.port.onmessage = null; try { node.disconnect() } catch { /* */ } }
165
+ try { src && src.disconnect() } catch { /* */ }
166
+ try { Promise.resolve(ctx.close()).catch(() => {}) } catch { /* */ }
167
+ }
168
+ const fail = (error) => {
169
+ if (stopped) return
170
+ stop()
171
+ if (!ready) rejectReady(error); else onError(error)
172
+ }
173
+ const resume = () => {
174
+ if (stopped || resuming || ctx.state === 'running') return
175
+ if (ctx.state === 'closed') { fail(new Error('microphone audio context closed')); return }
176
+ resuming = true
177
+ // WKWebView can interrupt an existing context. Resume when it changes state; the frame watchdog bounds a
178
+ // resume() that never settles, or one that says "running" but produces no audio. Silence still produces frames.
179
+ try { Promise.resolve(ctx.resume()).catch(fail).finally(() => { resuming = false }) } catch (e) { resuming = false; fail(e) }
180
+ }
181
+ function stateChanged () { trace('audio context ' + ctx.state); resume() }
182
+ function ended () { fail(new Error('microphone track ended')) }
183
+ function muteChanged () {
184
+ const muted = tracks.some(tr => tr.muted)
185
+ mutedAt = muted ? mutedAt || Date.now() : 0
186
+ trace(muted ? 'microphone muted by system' : 'microphone unmuted')
187
+ if (!muted) resume()
188
+ }
189
+ ctx.addEventListener('statechange', stateChanged)
190
+ for (const tr of tracks) {
191
+ tr.addEventListener('ended', ended)
192
+ tr.addEventListener('mute', muteChanged)
193
+ tr.addEventListener('unmute', muteChanged)
194
+ }
195
+ timer = setInterval(() => {
196
+ if (mutedAt && Date.now() - mutedAt >= stallMs) fail(new Error('microphone stayed muted by system'))
197
+ else if (Date.now() - lastFrame >= stallMs) fail(new Error('microphone stopped delivering audio (' + ctx.state + ')'))
198
+ }, Math.min(500, stallMs))
199
+ // Start audio activation before waiting for the worklet file. Do not swallow a failed resume and display a fake
200
+ // recording state: startCapture resolves only after the first PCM frame really arrives.
201
+ resume()
202
+ ;(async () => {
203
+ await ctx.audioWorklet.addModule(WORKLET_URL)
204
+ if (stopped) return
205
+ src = ctx.createMediaStreamSource(stream)
206
+ node = new AudioWorkletNode(ctx, 'pcm16k', { numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1] })
207
+ node.port.onmessage = (e) => {
208
+ if (stopped) return
209
+ lastFrame = Date.now()
210
+ if (mutedAt) return // WebKit can keep delivering silence while iOS has muted the live microphone track.
211
+ if (!ready) { ready = true; trace('first audio frame at ' + ctx.sampleRate + ' Hz'); resolveReady() }
212
+ try { onFrame(e.data) } catch { /* */ }
213
+ }
214
+ src.connect(node)
215
+ node.connect(ctx.destination) // output is silence; reaching the destination makes WebKit pull the graph
216
+ if (tracks.some(tr => tr.readyState === 'ended')) ended()
217
+ })().catch(fail)
218
+ await firstFrame
219
+ return { stop }
220
+ }
package/sttWorklet.js ADDED
@@ -0,0 +1,38 @@
1
+ // sttWorklet.js — the microphone → 16 kHz mono PCM16 for press-to-talk's cloud engine (sttCloud.js), on the audio
2
+ // thread. Resamples from the context's own rate (a browser may refuse a 16 kHz AudioContext; iOS often runs at 48 kHz)
3
+ // by linear interpolation, and posts 100 ms frames plus their RMS level (which drives the honest "listening" bars).
4
+ class Pcm16k extends AudioWorkletProcessor {
5
+ constructor () {
6
+ super()
7
+ this.ratio = sampleRate / 16000 // input samples per output sample
8
+ this.pos = 0 // fractional read position into the carried input
9
+ this.carry = new Float32Array(0)
10
+ this.out = new Int16Array(1600) // 100 ms at 16 kHz
11
+ this.n = 0
12
+ this.sumSq = 0
13
+ }
14
+
15
+ process (inputs) {
16
+ const ch = inputs[0] && inputs[0][0]
17
+ if (!ch) return true
18
+ const buf = new Float32Array(this.carry.length + ch.length)
19
+ buf.set(this.carry); buf.set(ch, this.carry.length)
20
+ let p = this.pos
21
+ while (p + 1 < buf.length) {
22
+ const i = Math.floor(p), f = p - i
23
+ const s = Math.max(-1, Math.min(1, buf[i] + (buf[i + 1] - buf[i]) * f))
24
+ this.out[this.n++] = s < 0 ? s * 32768 : s * 32767
25
+ this.sumSq += s * s
26
+ if (this.n === this.out.length) {
27
+ this.port.postMessage({ pcm: this.out.buffer.slice(0), rms: Math.sqrt(this.sumSq / this.n) })
28
+ this.n = 0; this.sumSq = 0
29
+ }
30
+ p += this.ratio
31
+ }
32
+ const keep = Math.floor(p)
33
+ this.carry = buf.slice(keep)
34
+ this.pos = p - keep
35
+ return true
36
+ }
37
+ }
38
+ registerProcessor('pcm16k', Pcm16k)