@witbitz/sdk 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +26 -5
  3. package/accountErase.js +6 -1
  4. package/accountRecord.js +2 -2
  5. package/agentDoorTools.js +28 -0
  6. package/chatLock.js +16 -0
  7. package/cloudDevicePins.js +2 -2
  8. package/codeAttachments.js +100 -0
  9. package/codeCache.js +149 -0
  10. package/codeCloud.js +0 -2
  11. package/codeComputers.js +1 -0
  12. package/codeFolders.js +116 -0
  13. package/codeHistory.js +76 -0
  14. package/codeLanguage.js +54 -0
  15. package/codeModes.js +2 -0
  16. package/codeProgress.js +54 -0
  17. package/codeSent.js +68 -0
  18. package/codeSubagents.js +107 -0
  19. package/codeTransport.js +22 -0
  20. package/connections.js +17 -18
  21. package/deviceAttest.js +9 -3
  22. package/idb.js +19 -3
  23. package/jobAgents.js +2 -2
  24. package/keptMerge.js +9 -2
  25. package/l1-worker-src.js +1 -1
  26. package/l1-worker.js +93 -30
  27. package/laneAssociation.js +68 -0
  28. package/laneConfig.js +4 -3
  29. package/manifest.json +80 -61
  30. package/memberChange.js +4 -2
  31. package/mirrorBatch.js +47 -0
  32. package/opRouting.js +10 -0
  33. package/package.json +21 -2
  34. package/pdfOptions.js +13 -0
  35. package/pdfText.js +107 -0
  36. package/pdfjs.mjs +28 -0
  37. package/pdfjs.worker.mjs +28 -0
  38. package/protectedLocal.js +18 -2
  39. package/removedMessage.js +1 -1
  40. package/roomEmbed.js +111 -0
  41. package/roomName.js +1 -1
  42. package/roomRoster.js +21 -5
  43. package/rosterCount.js +6 -3
  44. package/sdkA2A.js +160 -40
  45. package/sdkAccount.js +17 -4
  46. package/sdkAccountDoc.js +11 -3
  47. package/sdkAccountSections.js +117 -8
  48. package/sdkBackup.js +35 -8
  49. package/sdkCloudDevice.js +8 -2
  50. package/sdkComputers.js +582 -53
  51. package/sdkDictation.js +114 -24
  52. package/sdkErase.js +9 -4
  53. package/sdkExports.js +4 -2
  54. package/sdkLaneLink.js +3 -3
  55. package/sdkPlan.js +4 -2
  56. package/sdkRekey.js +50 -17
  57. package/sdkReport.js +1 -1
  58. package/sdkSafeMedia.js +1 -1
  59. package/sdkSpeech.js +19 -2
  60. package/sdkTemporaryRooms.js +123 -0
  61. package/sdkVault.js +66 -10
  62. package/sentinelRelease.js +1 -0
  63. package/sharedViews.js +17 -3
  64. package/siri.js +114 -7
  65. package/spaceClient.js +16 -5
  66. package/spaceEmailGate.js +2 -2
  67. package/spaceTemplates.js +99 -0
  68. package/speechOut.js +4 -2
  69. package/store.js +83 -14
  70. package/sw-notif-core.js +9 -7
  71. package/turnVerdict.js +1 -0
  72. package/vault-core.js +480 -112
  73. package/vault-kit.mjs +2 -2
  74. package/vault-screens.js +5 -7
  75. package/vaultAtRest.js +35 -4
  76. package/vaultKeep.js +9 -3
  77. package/vaultWorkerHost.js +23 -4
  78. package/witbitz-admin.mjs +12 -11
  79. package/witbitz-sdk.d.ts +115 -24
  80. package/witbitz-sdk.js +572 -149
package/sdkVault.js CHANGED
@@ -12,6 +12,7 @@
12
12
  // the page replies with the call `answer(id, { result } | { error })`
13
13
  // The page posts ONLY to the pinned vault origin (never '*') and accepts ONLY messages from that origin AND from the
14
14
  // window that frames it — a page we did not write must not broadcast, and nothing else on the page may answer for the vault.
15
+ import { TURN_TIMEOUT_MS } from './sdkTurn.js'
15
16
  import { WORKER_OPS } from './workerClient.js'
16
17
 
17
18
  export const VAULT_PROTOCOL = 1
@@ -34,23 +35,34 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
34
35
  const origin = String(vault || '').replace(/\/+$/, '')
35
36
  if (!isOrigin(origin)) return Promise.reject(Object.assign(new Error('witbitz: `vault` must be the vault\'s origin, e.g. https://vault.example.com'), { code: 'invalid_argument' }))
36
37
  if (!win || win.top === win) return Promise.reject(Object.assign(new Error('witbitz: this page is not framed by a vault — open the vault (' + origin + '), which opens this page inside it'), { code: 'not_in_vault' }))
38
+ const cacheKey = Symbol.for('witbitz.vault.transports.v1')
39
+ const transports = win[cacheKey] ||= new Map()
40
+ if (transports.has(origin)) return transports.get(origin)
41
+ const connection = openTransport(win, origin, helloMs)
42
+ transports.set(origin, connection)
43
+ connection.catch(() => { if (transports.get(origin) === connection) transports.delete(origin) })
44
+ return connection
45
+ }
46
+
47
+ function openTransport(win, origin, helloMs) {
37
48
  const top = win.top
38
49
  const waiting = new Map()
39
50
  const listeners = new Set()
40
51
  const askers = new Map() // kind → room → the page's handler for the vault's question
41
52
  const streams = new Map() // room → the handlers of every Space on this page showing it (the vault holds one socket per room)
42
- let seq = 0
53
+ const sequenceKey = Symbol.for('witbitz.vault.requestSequence')
54
+ if (!Number.isSafeInteger(win[sequenceKey])) win[sequenceKey] = 0
43
55
  let welcome = null
44
56
  let onWelcome = null
45
- win.addEventListener('message', (e) => {
57
+ const receive = (e) => {
46
58
  if (e.origin !== origin || e.source !== top) return // only the vault that frames us
47
59
  const d = e.data
48
60
  if (!d || d.ch !== 'wbvault') return
49
- if (d.t === 'welcome') { welcome = d; if (onWelcome) onWelcome(d); return }
61
+ if (d.t === 'welcome') { welcome = Object.assign(welcome || {}, d); if (onWelcome) onWelcome(welcome); return }
50
62
  if (d.t === 'res') {
51
63
  const w = waiting.get(d.id); if (!w) return
52
64
  waiting.delete(d.id); clearTimeout(w.timer)
53
- if (d.error) w.rej(Object.assign(new Error(String(d.error)), { code: d.code || 'vault_refused', status: d.status, ...(d.code === 'wrong_pin' && Number.isSafeInteger(d.next) && d.next >= 0 ? { next: d.next } : {}), ...(Array.isArray(d.unavailable) ? { unavailable: d.unavailable } : {}), ...(typeof d.reason === 'string' ? { reason: d.reason } : {}), ...(d.verdict && typeof d.verdict === 'object' ? { verdict: d.verdict } : {}) })); else w.res(d.result)
65
+ if (d.error) w.rej(Object.assign(new Error(String(d.error)), { code: d.code || 'vault_refused', status: d.status, ...(d.code === 'wrong_pin' && Number.isSafeInteger(d.next) && d.next >= 0 ? { next: d.next } : {}), ...(d.code === 'partial_revoke' ? { removedFrom: d.removedFrom || [], unchecked: d.unchecked || [] } : {}), ...(Array.isArray(d.unavailable) ? { unavailable: d.unavailable } : {}), ...(typeof d.reason === 'string' ? { reason: d.reason } : {}), ...(d.verdict && typeof d.verdict === 'object' ? { verdict: d.verdict } : {}) })); else w.res(d.result)
54
66
  return
55
67
  }
56
68
  if (d.t === 'ask' && typeof d.id === 'number') {
@@ -59,13 +71,42 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
59
71
  .then((result) => call('answer', d.id, { result: result === undefined ? null : result }), (err) => call('answer', d.id, { error: String((err && err.message) || err || 'refused').slice(0, 200) })).catch(() => {})
60
72
  return
61
73
  }
74
+ if (d.t === 'event' && welcome) {
75
+ if (d.ev === 'signedOut' || d.ev === 'accountSignedOut') {
76
+ Object.assign(welcome, { signedIn: false, email: '', keyId: '', siri: null })
77
+ if (d.reason !== 'expired') {
78
+ streams.clear(); welcome.rooms = []; welcome.keyStates = []; welcome.account = null
79
+ }
80
+ delete welcome.notifOpen
81
+ }
82
+ if (d.ev === 'signedIn') {
83
+ Object.assign(welcome, { signedIn: true, email: d.email || '', keyId: d.keyId || '' })
84
+ post({ t: 'hello', v: VAULT_PROTOCOL })
85
+ }
86
+ if (d.ev === 'siri' && d.siri) welcome.siri = d.siri
87
+ if (d.ev === 'rooms' && Array.isArray(d.rooms)) {
88
+ welcome.rooms = d.rooms
89
+ const held = new Set(d.rooms.map(r => r.room))
90
+ for (const room of streams.keys()) if (!held.has(room)) streams.delete(room)
91
+ }
92
+ if (d.ev === 'session' || d.ev === 'signedIn') welcome.keyId = d.keyId || ''
93
+ if (d.ev === 'account') welcome.account = d.view
94
+ if (d.ev === 'lock') welcome.lock = d.lock
95
+ if (d.ev === 'push') welcome.push = d.push
96
+ if (d.ev === 'key' && d.room) {
97
+ const prior = (Array.isArray(welcome.keyStates) ? welcome.keyStates : []).filter(k => k.room !== d.room)
98
+ if (d.kind === 'pending' || d.kind === 'removed') prior.push({ room: d.room, kind: d.kind, reason: d.reason || '' })
99
+ welcome.keyStates = prior.slice(-200)
100
+ }
101
+ }
62
102
  if (d.t === 'event' && d.ev === 'stream') { for (const fn of streams.get(d.room) || []) { try { fn(d) } catch { /* */ } } return }
63
103
  if (d.t === 'event') { for (const fn of listeners) { try { fn(d) } catch { /* a listener's error is its own */ } } }
64
- })
104
+ }
105
+ win.addEventListener('message', receive)
65
106
  const post = (msg) => top.postMessage({ ch: 'wbvault', ...msg }, origin)
66
107
  const call = (op, ...args) => new Promise((res, rej) => {
67
- const id = ++seq
68
- const timer = setTimeout(() => { if (waiting.delete(id)) rej(Object.assign(new Error('witbitz: the vault did not answer (' + op + ')'), { code: 'vault_timeout' })) }, PERSON_OPS.has(op) ? PERSON_MS : WAKE_OPS.has(op) ? WAKE_MS : CALL_MS)
108
+ const id = ++win[sequenceKey]
109
+ const timer = setTimeout(() => { if (waiting.delete(id)) rej(Object.assign(new Error('witbitz: the vault did not answer (' + op + ')'), { code: 'vault_timeout' })) }, PERSON_OPS.has(op) ? PERSON_MS : WAKE_OPS.has(op) ? WAKE_MS : op === 'op' && args[0] === 'turn' ? TURN_TIMEOUT_MS : CALL_MS)
69
110
  waiting.set(id, { res, rej, timer })
70
111
  try { post({ t: 'call', id, op, args }) } catch (err) { waiting.delete(id); clearTimeout(timer); rej(err) }
71
112
  })
@@ -84,7 +125,21 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
84
125
  client.streamOpen = (room, onEvent, onState) => {
85
126
  const fn = (d) => { if (d.event) onEvent(d.event); else if ('up' in d && onState) onState(!!d.up) }
86
127
  let set = streams.get(room)
87
- if (!set) { set = new Set(); streams.set(room, set); call('stream', room, true).catch(() => { streams.delete(room) }) } // refused or not held: the Space keeps polling
128
+ if (!set) {
129
+ set = new Set(); streams.set(room, set)
130
+ let delay = 1000
131
+ const subscribe = () => {
132
+ if (streams.get(room) !== set) return
133
+ call('stream', room, true).catch(err => {
134
+ if (streams.get(room) !== set) return
135
+ for (const notify of set) { try { notify({ up: false }) } catch {} }
136
+ if (['not_in_vault', 'bad_room', 'vault_refused'].includes(err?.code)) return
137
+ setTimeout(subscribe, delay)
138
+ delay = Math.min(30000, delay * 2)
139
+ })
140
+ }
141
+ subscribe()
142
+ }
88
143
  set.add(fn)
89
144
  return { stop: () => { if (set.delete(fn) && !set.size && streams.get(room) === set) { streams.delete(room); call('stream', room, false).catch(() => {}) } }, setGrants: () => {}, sync: () => {} }
90
145
  }
@@ -93,9 +148,10 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
93
148
  create: (cfg, opts) => call('create', cfg, ...(opts ? [opts] : [])), // opts { enclave }: dropping it would make a STANDARD Space where a confidential one was asked
94
149
  rooms: () => call('rooms'),
95
150
  share: (room, opts) => call('share', room, opts || {}),
96
- signIn: (opts) => call('signIn', opts || {}),
151
+ signIn: () => call('signIn'),
97
152
  signOut: () => call('signOut'),
98
153
  userToken: (t) => call('userToken', t), // per-user billing: the page's current token, handed over before an op that can spend
154
+ enclaveAvailable: () => call('enclaveAvailable'),
99
155
  whoami: () => call('whoami'),
100
156
  lockSettings: () => call('lockSettings'), // the vault's lock sheet (a vault started with `lock: true`): the person decides there; the page learns { available, on, protect }
101
157
  notifications: () => call('notifications'), // the vault's notifications card (`push: true`): the person decides; the page learns { available, on }
@@ -114,7 +170,7 @@ export function connectVault({ vault, win = (typeof window !== 'undefined' ? win
114
170
  resolve(v)
115
171
  }
116
172
  let stopped = false
117
- const timer = setTimeout(() => { stopped = true; reject(Object.assign(new Error('witbitz: the vault at ' + origin + ' did not answer — is this page framed by it?'), { code: 'not_in_vault' })) }, helloMs)
173
+ const timer = setTimeout(() => { stopped = true; win.removeEventListener?.('message', receive); reject(Object.assign(new Error('witbitz: the vault at ' + origin + ' did not answer — is this page framed by it?'), { code: 'not_in_vault' })) }, helloMs)
118
174
  if (welcome) return done(welcome)
119
175
  onWelcome = (w) => { onWelcome = null; done(w) }
120
176
  // the vault may still be starting its worker: say hello until it answers (or the wait ends)
@@ -10,6 +10,7 @@ import { derSigToRaw } from './x509.js'
10
10
 
11
11
  /** The build-enclave images whose verdicts count — infra/build-enclave/pins.json `buildEnclave` (held equal by a test). */
12
12
  export const BUILD_ENCLAVE_PCR0 = Object.freeze([
13
+ "c6a8cbd0c05d8e003e75b266f1dde2a6426b7cd61f845e4b128e59063e40968b44f30d934bbe1925582fe33bbdd0b1d7",
13
14
  "f490096d57e4287146e8b8d7bf4c75f423984ca52199efab0ee8684fbee6cfe6ab82c72d54f05a38f24a0d4ad6e2f557",
14
15
  "41ec7e0e54beac5759fba7efa06c48081dbd96c7299c29c92a9c619036ce057cec357ad4ad71a165d7f881df120b043b",
15
16
  "9f0801335a952bdbac70b6793150738d7ce30bc3a0d520fec6f573de22a822aa5ef762f78648bc8608ca0b2eeccda556",
package/sharedViews.js CHANGED
@@ -9,7 +9,7 @@ export const SHARED_VIEWS_DOC = 'sharedviews'
9
9
  export const SHARED_VIEWS_MAX = 12000 // the state allows 32 KB; a long multi-week plan must arrive whole
10
10
 
11
11
  /** `views` = [{ label, state }] (a widget's label and its doc's state) → the text, or '' when there is nothing to say. */
12
- export function renderSharedViews(views) {
12
+ export function renderSharedViews(views, source = '') {
13
13
  const parts = []
14
14
  for (const v of Array.isArray(views) ? views : []) {
15
15
  const st = v && v.state
@@ -20,17 +20,31 @@ export function renderSharedViews(views) {
20
20
  parts.push('MAP (' + String((v && v.label) || 'map').replace(/^\W+\s*/, '') + '): ' + st.places.map((pl) => `${(pl && pl.name) || 'place'}${pl && Number.isFinite(pl.rating) ? ` ★${pl.rating}` : ''}${pl && pl.chosen ? ' (shortlisted)' : ''}`).join(', '))
21
21
  }
22
22
  }
23
- return parts.join('\n\n').slice(0, SHARED_VIEWS_MAX)
23
+ const chars = Array.from(parts.join('\n\n').slice(0, SHARED_VIEWS_MAX))
24
+ const size = text => new TextEncoder().encode(JSON.stringify({ source, text })).length
25
+ const text = chars.join('')
26
+ if (size(text) <= 32000) return text
27
+ let low = 0, high = chars.length
28
+ while (low < high) {
29
+ const mid = Math.ceil((low + high) / 2)
30
+ if (size(chars.slice(0, mid).join('')) <= 32000) low = mid
31
+ else high = mid - 1
32
+ }
33
+ return chars.slice(0, low).join('')
24
34
  }
25
35
 
26
36
  /** The views a room's log names: each widget's doc name and label, newest first, at most `max`. */
27
37
  export function viewsNamedIn(entries, max = 12) {
28
38
  const out = [], seen = new Set()
29
39
  const list = Array.isArray(entries) ? entries : []
30
- for (let i = list.length - 1; i >= 0 && out.length < max; i--) {
40
+ for (let i = list.length - 1; i >= 0; i--) {
31
41
  const ws = list[i] && Array.isArray(list[i].widgets) ? list[i].widgets : []
32
42
  for (const w of ws) {
33
43
  if (!w || typeof w.name !== 'string' || !w.name || seen.has(w.name)) continue
44
+ if (out.length >= max) {
45
+ if (w.name !== 'itinerary' || !out.length) continue
46
+ out.pop()
47
+ }
34
48
  seen.add(w.name); out.push({ name: w.name, label: typeof w.title === 'string' && w.title ? w.title : w.name })
35
49
  }
36
50
  }
package/siri.js CHANGED
@@ -43,7 +43,78 @@ export async function siriRecordFor(account, s = loadSiri()) {
43
43
 
44
44
  /** Send the whole record, sealed to the attested Sentinel. Idempotent: the Sentinel REPLACES what it held. `s`: the record to
45
45
  * send — the store's, or a COPY with a change the caller keeps only once the Sentinel took it (pass 9, K#5). */
46
- export async function pushSiriRecord({ post, auth = {}, account, pins, verify, intake = null, s = loadSiri() } = {}) {
46
+ const EDIT_KEY = 'space:siri-pending-edit'
47
+ let publishing = Promise.resolve()
48
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
49
+ function applyEdit(base, next, latest) {
50
+ if ((base.rev || 0) !== (latest.rev || 0) || ((base.token || base.tokenHash) && (base.token || base.tokenHash) !== (latest.token || latest.tokenHash))) return latest
51
+ const result = structuredClone(latest)
52
+ for (const field of ['token', 'tokenHash', 'defaultRoom']) if ((field === 'defaultRoom' || !(latest.token || latest.tokenHash) || (base.token || base.tokenHash)) && !same(base[field], next[field]) && same(base[field], latest[field])) result[field] = next[field]
53
+ for (const room of new Set([...Object.keys(base.rooms), ...Object.keys(next.rooms)])) {
54
+ if (same(base.rooms[room], next.rooms[room]) || !same(base.rooms[room], latest.rooms[room])) continue
55
+ if (next.rooms[room] && (latest.gone?.[room] || 0) < next.rooms[room].at) result.rooms[room] = next.rooms[room]
56
+ else if (!next.rooms[room]) {
57
+ delete result.rooms[room]
58
+ result.gone = { ...(result.gone || {}), [room]: Math.max(Date.now(), (base.rooms[room]?.at || 0) + 1) }
59
+ if (result.defaultRoom === room) result.defaultRoom = ''
60
+ }
61
+ }
62
+ const aliases = Object.values(result.rooms).map(row => row.alias)
63
+ if (new Set(aliases).size !== aliases.length) throw new SiriError('This Siri name is already in use.', 'alias')
64
+ if (Object.keys(result.rooms).length > 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
65
+ return result
66
+ }
67
+ export function pushSiriRecord(options = {}) {
68
+ const { account, s, base = loadSiri() } = options
69
+ const run = async () => {
70
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
71
+ const read = () => JSON.parse(localStorage.getItem(EDIT_KEY) || '{}')
72
+ const drop = entry => { const all = read(); if (same(all[account], entry)) { delete all[account]; if (Object.keys(all).length) localStorage.setItem(EDIT_KEY, JSON.stringify(all)); else localStorage.removeItem(EDIT_KEY) } }
73
+ // ★ A REPLAYED ENTRY THAT IS DROPPED MAY ALREADY BE AT THE SENTINEL (its answer was lost — that is why it was pending). Dropping it
74
+ // alone left the Sentinel aliasing a Space to an inbox key whose private half existed only in the dropped entry: captures
75
+ // accepted that nobody could open (second review, 2026-11-27). So the record this device DOES hold is sent at once; if that
76
+ // fails too, the next Siri change sends it.
77
+ const converge = async () => { try { await publishSiri({ ...options, s: loadSiri() }) } catch { /* the next Siri change sends the record */ } }
78
+ const transmit = async (entry, replayed = false) => {
79
+ for (let attempt = 0; attempt < 4; attempt++) {
80
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
81
+ if (!same(read()[account], entry)) throw new SiriError('The Siri setup changed.', 'siri_busy')
82
+ // An edit that can no longer apply (its name now taken, the 64 limit) is dropped, not kept: it was replayed before every
83
+ // later Siri save and failed each of them, for good (review of the sweep fixes, 2026-11-27; 2ccbc1bff)
84
+ const current = loadSiri()
85
+ let candidate
86
+ try { candidate = applyEdit(entry.base, entry.next, current) } catch (error) { drop(entry); if (replayed) await converge(); throw error }
87
+ if (!attempt && same(candidate, current)) { drop(entry); return { ok: true } }
88
+ const value = localStorage.getItem(EDIT_KEY)
89
+ const saved = options.confirmStored ? await options.confirmStored(EDIT_KEY, value) : localStorage.getItem(EDIT_KEY) === value
90
+ if (!saved) { drop(entry); if (replayed) await converge(); throw new SiriError('Could not save the pending Siri change on this device.', 'storage_failed') } // not kept either: a device that cannot store it would replay it for ever
91
+ if (!same(read()[account], entry) || (options.current && !options.current())) throw new SiriError('The Siri setup changed.', 'siri_busy')
92
+ let result
93
+ try { result = await publishSiri({ ...options, s: candidate }) }
94
+ catch (error) { if (error.definiteRefusal) { drop(entry); if (replayed) await converge() } throw error }
95
+ if (!same(read()[account], entry) || (options.current && !options.current())) throw new SiriError('The Siri setup changed.', 'siri_busy')
96
+ if (!same(current, loadSiri())) continue
97
+ saveSiri(candidate)
98
+ drop(entry)
99
+ return result
100
+ }
101
+ throw new SiriError('The Siri setup is changing. Try again.', 'siri_busy')
102
+ }
103
+ const pending = read()[account]
104
+ if (pending) {
105
+ await transmit(pending, true)
106
+ if (options.current && !options.current()) throw new SiriError('The account changed.', 'account_changed')
107
+ }
108
+ if (!s || same(base, s)) return publishSiri({ ...options, s: loadSiri() })
109
+ const entry = { base, next: s }
110
+ localStorage.setItem(EDIT_KEY, JSON.stringify({ ...read(), [account]: entry }))
111
+ return transmit(entry)
112
+ }
113
+ const operation = publishing.then(run)
114
+ publishing = operation.catch(() => {})
115
+ return operation
116
+ }
117
+ async function publishSiri({ post, auth = {}, account, pins, verify, intake = null, s = loadSiri() } = {}) {
47
118
  if (!s.token && !s.tokenHash) throw new SiriError('no Siri key on this device yet', 'no_key')
48
119
  const rec = await siriRecordFor(account, s)
49
120
  // THE INTAKE (docs/message-intake.md): { room, pub, drop } — the Sentinel then drops what was said into the account's
@@ -52,7 +123,7 @@ export async function pushSiriRecord({ post, auth = {}, account, pins, verify, i
52
123
  const { nonce, key } = await attest({ post, auth, pins, verify })
53
124
  const sealed = await sealTo(key, nonce, rec)
54
125
  const r = await post({ op: 'sentinel', sentinel: { mode: 'sirigrant', sealed }, ...auth })
55
- if (!r || r.error || !r.ok) throw new SiriError(`the Sentinel refused the record (${(r && (r.error || r.reason)) || 'no answer'})`, (r && r.error) || 'refused')
126
+ if (!r || r.error || !r.ok) throw Object.assign(new SiriError(`the Sentinel refused the record (${(r && (r.error || r.reason)) || 'no answer'})`, (r && r.error) || 'refused'), { definiteRefusal: !!r && !!(r.error || r.ok === false) && !(r.status >= 500) && !['busy', 'unreachable', 'sentinel_unavailable', 'timeout'].includes(r.error) })
56
127
  return r
57
128
  }
58
129
  export async function siriStatus({ post, auth = {} }) {
@@ -60,11 +131,33 @@ export async function siriStatus({ post, auth = {} }) {
60
131
  if (!r || r.error) throw new SiriError(`the Sentinel could not be reached (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
61
132
  return r
62
133
  }
63
- export async function siriRevoke({ post, auth = {} }) {
134
+ export function siriRevoke({ post, auth = {}, account, current = () => true, expectedRev }) {
135
+ const run = async () => {
136
+ if (!current()) throw new SiriError('The account changed.', 'account_changed')
137
+ if (expectedRev !== undefined) {
138
+ const s = loadSiri()
139
+ if (s.rev !== expectedRev || s.token || s.tokenHash) throw new SiriError('The Siri setup changed.', 'siri_busy')
140
+ }
141
+ const r = await revokeRecord(post, auth, current, expectedRev === undefined)
142
+ if (account) {
143
+ const pending = JSON.parse(localStorage.getItem(EDIT_KEY) || '{}')
144
+ delete pending[account]
145
+ if (Object.keys(pending).length) localStorage.setItem(EDIT_KEY, JSON.stringify(pending))
146
+ else localStorage.removeItem(EDIT_KEY)
147
+ }
148
+ return r
149
+ }
150
+ const operation = publishing.then(run)
151
+ publishing = operation.catch(() => {})
152
+ return operation
153
+ }
154
+ async function revokeRecord(post, auth, current, save) {
64
155
  const r = await post({ op: 'sentinel', sentinel: { mode: 'sirirevoke' }, ...auth })
65
156
  if (!r || r.error) throw new SiriError(`the Sentinel could not be reached (${(r && r.error) || 'no answer'})`, (r && r.error) || 'unreachable')
66
157
  // the setup is DELETED on every device of the account (pass 9, K#3): `rev` outranks any copy that still holds the old key,
67
158
  // and each Space is marked taken off, so no other device's copy brings an alias or the key back
159
+ if (!current()) throw new SiriError('The account changed.', 'account_changed')
160
+ if (!save) return r
68
161
  const was = loadSiri(), now = Date.now()
69
162
  saveSiri({ token: '', defaultRoom: '', rooms: {}, rev: (was.rev || 0) + 1, gone: { ...(was.gone || {}), ...Object.fromEntries(Object.keys(was.rooms).map((rm) => [rm, now])) } })
70
163
  return r
@@ -75,7 +168,7 @@ export async function siriRevoke({ post, auth = {} }) {
75
168
  // `mint` / `mintToken` (the hosted app, siriSheet.js — only where the vault holds Siri keys, acctHeld.js): the inbox keypair and
76
169
  // the Shortcut key are minted IN THE VAULT (vaultAcctSecrets.js, review § 7.6) → a public half / the key's hash; the room is a
77
170
  // held stub ({ alias, label, pub, at, held: 1 }) and the key is kept here as `tokenHash` only.
78
- export async function enableSiriHere({ room, label = '', alias, makeDefault = false, mint = null, mintToken = null } = {}) {
171
+ export async function enableSiriHere({ room, label = '', alias, makeDefault = false, mint = null, mintToken = null, draft = null } = {}) {
79
172
  const a = normSiriAlias(alias)
80
173
  if (!a) throw new SiriError('an alias is needed — the word you will say to Siri', 'alias')
81
174
  if (/[,:;]/.test(a)) throw new SiriError('an alias cannot contain , : or ;', 'alias')
@@ -83,10 +176,12 @@ export async function enableSiriHere({ room, label = '', alias, makeDefault = fa
83
176
  // THE SLOW PART FIRST, THEN THE CHANGE ON WHAT IS THERE NOW (sync sweep 2026-11-14 #2, as the SDK since 48ddb8733): the vault's mints
84
177
  // (up to 8 s each) or the keypair ran on a copy read BEFORE them, and saving that copy dropped another device's merge that landed
85
178
  // meanwhile — and the record pushed to the Sentinel lacked it.
86
- const s0 = loadSiri(); taken(s0)
179
+ const s0 = draft || loadSiri(); taken(s0)
180
+ if (!s0.rooms[room] && Object.keys(s0.rooms).length >= 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
87
181
  const tokenHash = (!s0.token && !s0.tokenHash && mintToken) ? await mintToken() : ''
88
182
  const fresh = s0.rooms[room] ? null : mint ? { held: 1, pub: await mint() } : { kp: await genRecipientKey() }
89
- const s = loadSiri(); taken(s)
183
+ const s = draft || loadSiri(); taken(s)
184
+ if (!s.rooms[room] && Object.keys(s.rooms).length >= 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
90
185
  if (!s.token && !s.tokenHash) { if (tokenHash) s.tokenHash = tokenHash; else if (mintToken) s.tokenHash = await mintToken(); else s.token = newSiriKey() }
91
186
  const cur = s.rooms[room]
92
187
  if (cur) s.rooms[room] = { ...cur, alias: a, label: label || cur.label, at: Date.now() } // `at` moves on a rename: the newer copy leads a merge
@@ -96,7 +191,7 @@ export async function enableSiriHere({ room, label = '', alias, makeDefault = fa
96
191
  }
97
192
  if (makeDefault) s.defaultRoom = room
98
193
  else if (s.defaultRoom === room) s.defaultRoom = ''
99
- return saveSiri(s)
194
+ return draft ? s : saveSiri(s)
100
195
  }
101
196
  export function disableSiriHere(room) {
102
197
  const s = loadSiri()
@@ -169,3 +264,15 @@ export async function collectSiriDrops({ post, auth = {}, room, send, deliver =
169
264
  for (const e of Array.isArray(r.elsewhere) ? r.elsewhere : []) if (e && typeof e.room === 'string') nameElsewhere(e.room)
170
265
  return { delivered, elsewhere: [...elsewhere.values()], ...(unopened ? { unopened } : {}), ...(more ? { more } : {}) }
171
266
  }
267
+
268
+ export const aliasFor = (title) => String(title || '').replace(/[,:;]/g, ' ').replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 32)
269
+ export function uniqueAlias(base, taken) {
270
+ const b = aliasFor(base) || 'space'
271
+ if (!taken.has(b)) return b
272
+ for (let n = 2; ; n++) { const c = `${b.slice(0, 32 - String(n).length - 1)} ${n}`; if (!taken.has(c)) return c }
273
+ }
274
+
275
+ export function siriAliasesDiffer(rooms, status) {
276
+ const aliases = Array.isArray(status.aliases) ? status.aliases : []
277
+ return aliases.length !== Object.keys(rooms).length || aliases.some(a => !rooms[a.room] || rooms[a.room].alias !== a.alias)
278
+ }
package/spaceClient.js CHANGED
@@ -29,8 +29,15 @@ function embedAttribution() {
29
29
  }
30
30
  import { verifyRoomGovernance } from './ownerPolicy.js'
31
31
  import { staysDirect } from './roomName.js' // a direct chat that gains a third member is a group (rekey)
32
+ import { stageMirrorAttachments } from './mirrorBatch.js'
32
33
  import { memberHash } from './rosterHash.js' // hash the email allow-list (room-bound) before sealing → co-members can't read addresses
33
34
 
35
+ async function directRoster(allow, room) {
36
+ if (!Array.isArray(allow?.emails) || !Array.isArray(allow?.mh) || !allow.mh.length) return allow
37
+ const shown = new Set(await Promise.all(allow.emails.map(email => memberHash(email, room))))
38
+ return { ...allow, mh: allow.mh.filter(hash => !shown.has(hash)) }
39
+ }
40
+
34
41
  // Seal the agent CONFIG (persona/tools/…) under mk so it's ciphertext at rest — the server can't read what a Space is
35
42
  // for; it decrypts-once per turn (same discipline as the ledger). Wire-compatible with the Lambda's envelope.open.
36
43
  const sealConfig = async (config, mk) =>
@@ -1008,10 +1015,14 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1008
1015
  // MIRROR — append entries this device copied from a LINKED room (docs/spaces-private-lane.md) into THIS room's ledger,
1009
1016
  // no agent turn. Deduped by entry id server-side. Files/images ride along so the assistant reads them natively.
1010
1017
  mirror: async (room, mk, entries) => {
1011
- const kf = await keyFields(room, 'mirror', mk) // fail-closed for an enclave room with no key
1012
- // Enclave lane → seal the shared room's plaintext messages to the enclave; otherwise send them as before.
1013
- const ef = enclaveFor(room) ? await sealField(room, 'mirror:entries', JSON.stringify(entries || []), 'mirror') : { entries }
1014
- return post({ op: 'mirror', room, ...kf, ...ef, ...(await authFor(room)) })
1018
+ const send = async batch => {
1019
+ const kf = await keyFields(room, 'mirror', mk)
1020
+ const ef = enclaveFor(room) ? await sealField(room, 'mirror:entries', JSON.stringify(batch), 'mirror') : { entries: batch }
1021
+ return post({ op: 'mirror', room, ...kf, ...ef, ...(await authFor(room)) })
1022
+ }
1023
+ const batch = entries || []
1024
+ const prepared = await stageMirrorAttachments(batch, send)
1025
+ return prepared.error || send(prepared.entries)
1015
1026
  },
1016
1027
  // CARRY — a verified room's MOVE: the SERVER copies the old room's history into this one (minted with forkedFrom = that
1017
1028
  // room), keeping each entry's verified mark as `carried` (agent/spaceService.mjs op 'carry'). One page per call → { carried,
@@ -1389,7 +1400,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1389
1400
  const newCommit = await keyCommit(newMk)
1390
1401
  const next = { ...cur, ...(members ? { allow: members.allow, owners: members.owners, admins: members.admins } : {}), ...(link ? { admission: 'invite', roster: link.roster, gk: link.gk } : {}), keyChain: [...chain, { epoch, commit: await keyCommit(mk), key: mk }] }
1391
1402
  for (const k of ['owners', 'admins']) if (next[k] === undefined) delete next[k]
1392
- if (next.direct === true && members && !staysDirect(next.allow)) delete next.direct // a third member makes a direct chat a group (roomName.js)
1403
+ if (next.direct === true && members && !staysDirect(await directRoster(next.allow, room))) delete next.direct // a third member makes a direct chat a group (roomName.js)
1393
1404
  const configSealed = JSON.stringify(await seal(JSON.stringify(next), { room: newMk }))
1394
1405
  const grant = JSON.stringify(newShare ? { v: 1, kind: 'room-split-key', room, epoch: epoch + 1, userShare: newShare, commit: newCommit } : { v: 1, kind: 'room-key', room, epoch: epoch + 1, mk: newMk })
1395
1406
  const grants = {}
package/spaceEmailGate.js CHANGED
@@ -334,7 +334,7 @@ try { if (typeof window !== 'undefined' && pendingRead()) setTimeout(() => { res
334
334
 
335
335
  /** GOOGLE via the broker. → { idToken, email } | null. `onEnd(why)` hears why a wait ended without one: 'blocked' | 'cancelled' |
336
336
  * 'closed' | 'refused' | 'timeout'. In the Android app Google's own sheet comes first (nativeGoogleToken, above). */
337
- export async function brokerGoogleToken({ nonce, broker = brokerUrl(), onEnd = null }) {
337
+ export async function brokerGoogleToken({ nonce, broker = brokerUrl(), onEnd = null, watchPopup = true }) {
338
338
  if (!broker) return null
339
339
  const native = await nativeGoogleToken({ nonce, broker })
340
340
  if (native && native.cancelled) { if (onEnd) onEnd('cancelled'); return null }
@@ -389,7 +389,7 @@ export async function brokerGoogleToken({ nonce, broker = brokerUrl(), onEnd = n
389
389
  const closeSheet = () => { if (inSheet) { try { sheet.close() } catch { /* already gone */ } } }
390
390
  const ended = (why, code) => { forget(); closeSheet(); if (card) card.close(); signinLog('Google: the wait for the sign-in page ended — ' + why + ' after ' + Math.round((Date.now() - started) / 1000) + ' s'); if (onEnd) onEnd(code); return null }
391
391
  const poll = () => withTimeout(fetch(broker + '/api/handoff/poll', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sid }) }).then((x) => x.json()), BROKER_POLL_TIMEOUT_MS)
392
- let closedAt = 0, pollsSinceClosed = 0, watchClosed = !!w
392
+ let closedAt = 0, pollsSinceClosed = 0, watchClosed = !!w && watchPopup
393
393
  while (Date.now() < deadline) {
394
394
  await wakeOnReturn(BROKER_POLL_MS, ctl)
395
395
  if (ctl.cancelled) return ended('cancelled', 'cancelled')
@@ -0,0 +1,99 @@
1
+ // spaceTemplates.js — the M3 template layer (docs/configurable-space-m3.md).
2
+ //
3
+ // A Space is to a CONFIG what an agent is to a manifest. M3 proved the engine is fully config-driven: the SAME deployed
4
+ // /space Lambda runs any vertical with zero code changes — only the config differs (verified end-to-end on prod with a
5
+ // second vertical, `team-decision`, incl. the Shamir k-of-n key model, a distinct persona, and a propose-gated tool).
6
+ //
7
+ // This is the reusable library the roadmap calls "clinician-authored templates users personalize": pick a template,
8
+ // let the creator tweak the persona/knobs, then `makeSpaceClient().create(template)`. Each template is exactly the
9
+ // config the engine already reads — keyModel + persona/agentName + tools/immediateTools. Nothing here is a new engine
10
+ // axis: a Space's capabilities are just `declaredTools`; presence is the key model (2-of-2 = both present, not a
11
+ // separate flag); an effectful tool is propose-gated unless allow-listed in `immediateTools` (fail-closed).
12
+
13
+ export const SPACE_TEMPLATES = [
14
+ {
15
+ id: 'couples-comedian',
16
+ display: 'Couples — a comedian in the room',
17
+ blurb: 'A private, both-of-you room where a comedian helps you hash something out — funny at the situation, never at a person.',
18
+ keyModel: '2-of-2', // both partners' shares must combine to open it → presence IS the key model
19
+ agentName: 'The Comedian',
20
+ // The persona + safety floor are the VALIDATED, legally-load-bearing text — the canonical copy lives in
21
+ // tools/first-party-agents.json (comedian-therapist) and must not be forked here (it drifts). A Space using this
22
+ // template loads that text; the engine must inject `safetyFloor` as the LAST, un-removable block (exactly as
23
+ // agent.mjs does for the live call). `needsSafetyFloor` flags that a Space config field for it is required.
24
+ personaRef: 'first-party-agents.json#comedian-therapist',
25
+ tools: [],
26
+ immediateTools: [],
27
+ needsSafetyFloor: true,
28
+ },
29
+
30
+ {
31
+ id: 'team-decision',
32
+ display: 'Team — decide together',
33
+ blurb: 'A small team reaches a decision together; the facilitator records it only once you all approve.',
34
+ keyModel: { k: 2, n: 3 }, // any 2 of the team's members can open it (Shamir k-of-n) — the generalized key model
35
+ agentName: 'Facilitator',
36
+ persona:
37
+ 'You are a calm, fair team facilitator helping a small group decide together. Note where they agree, surface the ' +
38
+ 'one open question, and when the group clearly lands on a decision, record it. Neutral, brief, never take a side.',
39
+ tools: [
40
+ { name: 'record_decision', description: 'Record a decision the team has agreed on', parameters: { type: 'object', properties: { decision: { type: 'string' }, rationale: { type: 'string' } }, required: ['decision'] } },
41
+ ],
42
+ immediateTools: [], // record_decision is high-stakes → propose-gated (a human approves before it's recorded)
43
+ },
44
+
45
+ {
46
+ id: 'mediation',
47
+ display: 'Mediation — two parties + a neutral',
48
+ blurb: 'Two parties and a neutral mediator work toward a written agreement; each party approves what gets drafted.',
49
+ keyModel: '2-of-2', // both parties present to open (the money-attached vertical the roadmap flags)
50
+ agentName: 'Mediator',
51
+ persona:
52
+ 'You are a neutral, patient mediator between two parties. Restate each side fairly, find the shared interest, and ' +
53
+ 'when they converge, draft the agreement in plain language. Never advocate for either party; never give legal advice.',
54
+ tools: [
55
+ { name: 'draft_agreement', description: 'Draft the terms both parties have agreed to', parameters: { type: 'object', properties: { terms: { type: 'string' } }, required: ['terms'] } },
56
+ ],
57
+ immediateTools: [],
58
+ needsSafetyFloor: true, // an abuse/coercion floor applies here too (same discipline as couples)
59
+ },
60
+
61
+ {
62
+ // A confidential case room for a lawyer + client(s). The privilege/confidentiality guarantee is the SEALED room
63
+ // (E2EE, content-blind at rest) — exactly where verifiable trust is load-bearing (a third party who could read the
64
+ // communication can WAIVE privilege). No new engine axis: read_file (load case materials) and write_pdf (draft
65
+ // documents) are platform tools available in every Space; the private-lane panel gives each party their own agent +
66
+ // private room (attorney work-product stays out of the shared thread). This template only supplies the persona.
67
+ id: 'legal-case',
68
+ display: 'Legal — a confidential case room',
69
+ blurb: 'A sealed case room for a lawyer and client(s): load case materials, strategize together, and draft documents — readable only inside the room.',
70
+ agentName: 'Case Assistant',
71
+ persona:
72
+ 'You are a meticulous legal case assistant inside a confidential lawyer–client room. Help the team work the case. ' +
73
+ 'When a document is shared you will see a "[shared file: NAME]" marker — call read_file to read it, then lay out ' +
74
+ 'the facts, the issues, key dates and deadlines, and the risks. Help the team respond and strategize: outline ' +
75
+ 'options and their tradeoffs, and when asked, draft correspondence, memos, demand letters, and filings — use ' +
76
+ 'write_pdf to produce a clean document. Ground everything in the materials you were given; NEVER invent facts, ' +
77
+ 'quotes, citations, or case law, and say so plainly when something needs to be checked. You assist the ' +
78
+ 'supervising attorney\'s judgment — you do not replace it, you do not give the client independent legal advice, ' +
79
+ 'and you never promise an outcome. Be precise, organized, and concise.',
80
+ tools: [], // read_file + write_pdf are platform tools (auto-available every turn) — nothing to declare
81
+ immediateTools: [],
82
+ },
83
+ ]
84
+
85
+ /** Look up a template by id. */
86
+ export const spaceTemplate = (id) => SPACE_TEMPLATES.find((t) => t.id === id) || null
87
+
88
+ const TRAVEL_PERSONA = 'A friendly, knowledgeable travel agent who helps plan trips together: destinations, day plans, restaurants, sights, hotels, getting around, and practical tradeoffs. Keep answers concise, concrete, and useful.'
89
+ // The GENERIC assistant — a general-purpose persona, not a specialized one. First in the list ⇒ it's the DEFAULT for a
90
+ // new Space (defaultCreateAgent falls back to builtinAgents()[0]) and the fallback persona in the create handler below.
91
+ export const GENERAL_PERSONA = 'A helpful, friendly assistant for anything that comes up — answering questions, writing and editing, planning, research, brainstorming, summarizing, and thinking through problems together. Be clear, concise, and practical, and ask a short clarifying question when it helps. Use shared docs, images, files, places/maps and flights when they are genuinely useful.'
92
+ export const CREATE_TEMPLATES = [
93
+ { id: 'general', name: 'Assistant', sub: 'A helpful all-purpose assistant', agentName: 'Assistant', persona: GENERAL_PERSONA },
94
+ { id: 'travel', name: 'Travel', sub: 'Plan trips, maps, places, itineraries', agentName: 'Travel Agent', persona: TRAVEL_PERSONA },
95
+ ...SPACE_TEMPLATES.filter((t) => t.persona).map((t) => ({ id: t.id, name: t.display.replace(/\s+—\s+.*/, ''), sub: t.blurb, agentName: t.agentName, persona: t.persona })),
96
+ ]
97
+
98
+ /** Independent copies of the built-in assistant choices. */
99
+ export function assistantTemplates() { return CREATE_TEMPLATES.map(template => ({ ...template })) }
package/speechOut.js CHANGED
@@ -57,9 +57,9 @@ export function isHebrew (text) {
57
57
  * getKey() → { key, model, voice, expiresAt, cert, bundleGz } from op:'tts' (its `url` is not used: TTS_URL). play() resolves when the whole text has played (or
58
58
  * rejects: `no_hebrew`, `empty`, a fetch/HTTP failure); stop() ends playback and aborts fetches in flight. */
59
59
  export function createTtsPlayer ({ getKey, checkKey = checkSpeechKey, fetchImpl = (...a) => globalThis.fetch(...a), AudioImpl = globalThis.Audio, now = () => Date.now(), URLImpl = globalThis.URL } = {}) {
60
- let key = null, session = 0, audio = null, ctrl = null
60
+ let keyEpoch = 0, key = null, session = 0, audio = null, ctrl = null
61
61
  const self = { playing: false }
62
- const freshKey = async () => { if (!key || Date.parse(key.expiresAt) - now() < KEY_SLACK_MS) { const k = await getKey(); await checkKey(k); key = k } return key } // checkKey throws voice_unattested: no text is sent
62
+ const freshKey = async () => { if (!key || Date.parse(key.expiresAt) - now() < KEY_SLACK_MS) { const epoch = keyEpoch; const k = await getKey(); await checkKey(k); if (epoch !== keyEpoch) throw new Error('speech payer changed'); key = k } return key } // checkKey throws voice_unattested: no text is sent
63
63
  const fetchChunk = async (text, k, signal) => {
64
64
  const r = await fetchImpl(TTS_URL, { method: 'POST', headers: { authorization: 'Bearer ' + k.key, 'content-type': 'application/json' }, body: JSON.stringify({ model: k.model, input: text, ...(k.voice ? { voice: k.voice } : {}), response_format: 'mp3' }), signal })
65
65
  if (!r.ok) { if (r.status === 401 || r.status === 402 || r.status === 403) key = null; throw Object.assign(new Error('speech ' + r.status), { code: 'http_' + r.status }) }
@@ -74,6 +74,7 @@ export function createTtsPlayer ({ getKey, checkKey = checkSpeechKey, fetchImpl
74
74
  Promise.resolve(a.play()).catch((e) => done(Object.assign(e || new Error('play refused'), { code: 'play' })))
75
75
  })
76
76
  self.stop = () => { session++; self.playing = false; try { ctrl && ctrl.abort() } catch { /* */ } ctrl = null; try { audio && audio.pause() } catch { /* */ } audio = null }
77
+ self.resetKey = () => { keyEpoch++; key = null; self.stop() }
77
78
  self.play = async (text) => {
78
79
  self.stop()
79
80
  if (isHebrew(text)) throw Object.assign(new Error('Hebrew is not supported by the speech model'), { code: 'no_hebrew' })
@@ -83,6 +84,7 @@ export function createTtsPlayer ({ getKey, checkKey = checkSpeechKey, fetchImpl
83
84
  self.playing = true
84
85
  try {
85
86
  const k = await freshKey()
87
+ if (session !== mine) return
86
88
  let next = fetchChunk(chunks[0], k, signal)
87
89
  for (let i = 0; i < chunks.length; i++) {
88
90
  const blob = await next