@witbitz/sdk 4.4.0 → 4.5.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 (79) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +15 -0
  3. package/accountErase.js +9 -3
  4. package/accountIndexDoc.js +24 -7
  5. package/accountRecord.js +6 -2
  6. package/accountStores.js +21 -5
  7. package/acctV2App.js +111 -12
  8. package/acctV2Client.js +11 -1
  9. package/acctV2UiCore.js +27 -7
  10. package/awsKey.js +3 -1
  11. package/backupRecord.js +3 -0
  12. package/codeAttachments.js +1 -0
  13. package/codeCache.js +27 -3
  14. package/codeCloud.js +2 -0
  15. package/codeComputers.js +8 -0
  16. package/codeSent.js +43 -2
  17. package/codeTransport.js +24 -5
  18. package/connections.js +21 -3
  19. package/decrypt.html +69 -9
  20. package/eraseFile.js +15 -0
  21. package/idbSeal.js +5 -2
  22. package/inviteReceive.js +44 -0
  23. package/inviteSend.js +8 -2
  24. package/l1-worker-src.js +1 -1
  25. package/l1-worker.js +30 -14
  26. package/laneAssociation.js +11 -1
  27. package/laneLinkCore.js +9 -0
  28. package/ledgerView.js +30 -4
  29. package/manifest.json +78 -72
  30. package/offlineBundle.js +21 -0
  31. package/package.json +8 -2
  32. package/protectedLocal.js +34 -11
  33. package/reactionHolders.js +86 -0
  34. package/roomIntake.js +324 -0
  35. package/roomRoster.js +9 -2
  36. package/scheduleNext.js +60 -0
  37. package/sdkA2A.js +46 -8
  38. package/sdkAccount.js +71 -14
  39. package/sdkAccountDoc.js +3 -3
  40. package/sdkAccountSections.js +58 -18
  41. package/sdkAgui.js +33 -6
  42. package/sdkBackup.js +21 -6
  43. package/sdkBackupV2.js +15 -3
  44. package/sdkCloudDevice.js +12 -3
  45. package/sdkComputers.js +118 -17
  46. package/sdkDictation.js +1 -1
  47. package/sdkErase.js +3 -1
  48. package/sdkExports.js +15 -6
  49. package/sdkInvitations.js +4 -2
  50. package/sdkKeptAgent.js +19 -3
  51. package/sdkKeptIntake.js +100 -0
  52. package/sdkLaneLink.js +5 -6
  53. package/sdkRekey.js +72 -5
  54. package/sdkSchedules.js +8 -1
  55. package/sdkSpeech.js +14 -1
  56. package/sdkTemporaryRooms.js +2 -1
  57. package/sdkTurn.js +12 -4
  58. package/sharedViews.js +17 -1
  59. package/siri.js +29 -5
  60. package/spaceClient.js +96 -12
  61. package/spaceExport.js +50 -5
  62. package/spaceFork.js +15 -7
  63. package/spaceTemplates.js +2 -2
  64. package/speechOut.js +17 -3
  65. package/store.js +51 -13
  66. package/sw-notif-core.js +2 -1
  67. package/tapTrail.js +58 -0
  68. package/usageReceipts.js +12 -5
  69. package/vault-core.js +90 -16
  70. package/vault-kit.mjs +2 -2
  71. package/vault-screens.js +25 -11
  72. package/vaultAtRest.js +3 -2
  73. package/vaultCoreLock.js +3 -1
  74. package/vaultCorePush.js +58 -7
  75. package/vaultWorkerHost.js +9 -3
  76. package/witbitz-admin.d.ts +3 -0
  77. package/witbitz-admin.mjs +10 -10
  78. package/witbitz-sdk.d.ts +59 -23
  79. package/witbitz-sdk.js +271 -64
package/sdkSchedules.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { SCHEDULES_DOC, ALWAYSON_DOC, alwaysOnNow, jobsOf, withJob, withoutJob, withPaused, summaryOf } from './schedulesDoc.js'
2
+ import { withNextRuns } from './scheduleNext.js'
2
3
 
4
+ const deviceZone = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' } }
3
5
  const fail = (code, message, status) => Object.assign(new Error('witbitz: ' + message), { code, ...(status ? { status } : {}) })
4
6
 
5
7
  /** The same sealed schedule document edited by the app and executed by the cloud device. */
@@ -10,7 +12,9 @@ export class SpaceSchedules {
10
12
  if (!r || r.status !== 200 || !Number.isInteger(r.v)) throw fail((r && r.error) || 'unreadable', 'the schedule document could not be read', r && r.status)
11
13
  return r
12
14
  }
13
- async list() { const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'list'); return jobsOf(await this._read(SCHEDULES_DOC)) }
15
+ /** Each active daily job carries `next`: when it runs next (ms), by this device's time zone rules — on the night the clocks skip
16
+ * its time, the moment they jump (side sweep daily-schedule-display-omits-spring-gap-run-time). */
17
+ async list() { const s = this._sp; if (s._wb?.vault) return withNextRuns(await s._wb.vault._c.roomAccount(s.room, 'schedules', 'list')); return withNextRuns(jobsOf(await this._read(SCHEDULES_DOC))) }
14
18
  async _edit(fn, needsDevice = false) {
15
19
  const s = this._sp
16
20
  if (needsDevice && !alwaysOnNow(await this._read(ALWAYSON_DOC))) throw fail('not_always_on', 'this Space needs an active cloud device for schedules')
@@ -26,6 +30,9 @@ export class SpaceSchedules {
26
30
  throw fail('version_conflict', 'the schedules kept changing; try again', 409)
27
31
  }
28
32
  async add({ when, text } = {}) {
33
+ // a daily time with no zone is THIS device's zone, as the app saves it (cloudDeviceSheet.js) — UTC would move it an hour on
34
+ // the local clock at the next clock change (side sweep: sdk-daily-schedule-omitted-zone-defaults-to-utc)
35
+ if (when && typeof when.at === 'string' && !when.tz) when = { ...when, tz: deviceZone() }
29
36
  const s = this._sp; if (s._wb?.vault) return s._wb.vault._c.roomAccount(s.room, 'schedules', 'add', { when, text })
30
37
  let id
31
38
  const jobs = await this._edit((jobs) => { const next = withJob(jobs, { when, text, by: this._sp._who() }); id = next.at(-1).id; return next }, true)
package/sdkSpeech.js CHANGED
@@ -14,6 +14,18 @@
14
14
  import { createTtsPlayer } from './speechOut.js'
15
15
 
16
16
  const err = (code, message) => Object.assign(new Error('witbitz: ' + message), { code })
17
+ // WHO PAYS, not which token: a refreshed user token (a later exp) for the same tenant user is the same payer, so its key is
18
+ // kept — each new key spends one of the account's hourly issuances (side sweep). The token is base64url(JSON{v,t,u,exp}) +
19
+ // '.' + signature (control-plane tenantUsers.mjs issueTurnToken); anything else is compared whole, as before.
20
+ export function tokenPayer (token) {
21
+ if (!token) return ''
22
+ try {
23
+ const b = String(token).split('.')[0].replace(/-/g, '+').replace(/_/g, '/')
24
+ const j = JSON.parse(atob(b + '='.repeat((4 - (b.length % 4)) % 4)))
25
+ if (j && typeof j.t === 'string' && typeof j.u === 'string' && j.t && j.u) return 'tu:' + j.t + '|' + j.u
26
+ } catch { /* not that format */ }
27
+ return token
28
+ }
17
29
 
18
30
  export class Speech {
19
31
  constructor (wb, { fetchImpl, AudioImpl, URLImpl, checkKey } = {}) { // checkKey: a test seam — the page's own evidence check (voiceAttest.js) by default
@@ -31,7 +43,7 @@ export class Speech {
31
43
  let userToken = ''
32
44
  try { const t = typeof wb._userToken === 'function' ? await wb._userToken() : wb._userToken; userToken = typeof t === 'string' ? t : '' } catch { userToken = '' }
33
45
  if (!idToken && !userToken && !wb.vault) throw err('sign_in_required', 'speak needs a signed-in user (wb.signIn) or a user token (wb.useUserToken)') // in a vault, the vault's sign-in mints the key
34
- return { idToken, userToken, payer: userToken || sess?.email || '' }
46
+ return { idToken, userToken, payer: tokenPayer(userToken) || sess?.email || '' }
35
47
  }
36
48
  async _key () {
37
49
  const { idToken, userToken } = this._playAuth || await this._who()
@@ -55,6 +67,7 @@ export class Speech {
55
67
  async play (text) {
56
68
  const seq = this._sequence = (this._sequence || 0) + 1
57
69
  const epoch = this._epoch
70
+ this._player.stop() // the reading in progress stops NOW, not after this call's token arrives (side sweep)
58
71
  const auth = await this._who()
59
72
  if (seq !== this._sequence) return
60
73
  if (epoch !== this._epoch) throw err('account_changed', 'the voice payer changed')
@@ -18,11 +18,12 @@ export class TemporaryRooms {
18
18
  return pendingScope(this._wb)
19
19
  }
20
20
 
21
- async _remember(sp, scope, { days, title } = {}) {
21
+ async _remember(sp, scope, { days, title, onlyIfListed = false } = {}) {
22
22
  if (scope !== this._scope()) return
23
23
  const generation = this._generation, name = storagePrefix(scope) + sp.room
24
24
  const previous = this._memory.get(name) || (await this._records(scope, sp.room)).get(name)
25
25
  if (scope !== this._scope() || generation !== this._generation) return
26
+ if (onlyIfListed && !previous) return // a closed handle's new key: never puts back a room the list no longer has
26
27
  const record = { ...previous, room: sp.room, link: sp.shareLink, at: previous?.at || Date.now() }
27
28
  if (days) record.days = days
28
29
  const label = sp.title || title
package/sdkTurn.js CHANGED
@@ -51,6 +51,8 @@ export class Turn {
51
51
  this._stopKey = randStopKey()
52
52
  this._mark = null // messages.length when the attempt that RAN was posted
53
53
  this._replyText = null // the server's word on the reply, when it gave one
54
+ this._promptId = null // the ledger id of this turn's own message, when the server names it
55
+ this._sent = String(text == null ? '' : text) // this turn's own message, as it lands in the room
54
56
  /** 'running' until it settles; then 'done' | 'silent' | 'failed' | 'aborted' | 'timeout'. */
55
57
  this.status = 'running'
56
58
  /** The reply as it has streamed so far ('' before the first token). */
@@ -84,7 +86,7 @@ export class Turn {
84
86
  this.result = r
85
87
  const v = turnVerdict(r)
86
88
  if (v.kind === 'silent') return this._settle('silent')
87
- if (v.kind === 'ok') { this._replyText = typeof r.reply === 'string' ? r.reply : null; if (this._replyText === '') return this._settle('silent'); return this._look() }
89
+ if (v.kind === 'ok') { this._replyText = typeof r.reply === 'string' ? r.reply : null; this._promptId = typeof r.promptId === 'string' && r.promptId ? r.promptId : null; if (this._replyText === '') return this._settle('silent'); return this._look() }
88
90
  if (r && r.pending) return this._look() // cut at the front door; the reply still comes on the poll
89
91
  // NO ANSWER at all (status 0) settles as failed with its code — it MAY have posted (sdk.md): read the room before resending
90
92
  this._settle('failed', { error: (r && r.error) || v.code || v.kind, reason: (r && r.reason) || v.reason }) // the server's sentence too (sweep 11-04 P3: TurnResult had no reason)
@@ -94,9 +96,15 @@ export class Turn {
94
96
  _look() {
95
97
  if (this.status !== 'running' || this._mark === null) return
96
98
  if (this.result === null) return // the request is still out: a reply that lands now may be a previous turn's
97
- const list = this._space.messages
98
- const after = list.slice(this._mark).filter(isReply)
99
- const m = (this._replyText ? after.find((x) => String(x.text || '') === this._replyText) : null) || after[0]
99
+ const slice = this._space.messages.slice(this._mark)
100
+ const after = slice.filter(isReply)
101
+ // Not the server's exact words → the first reply AFTER this turn's own message: a delayed poll can bring an EARLIER answer in
102
+ // past the mark, and it was taken for this turn's (side sweep 2026-11-28). With the server's words in hand, nothing else is
103
+ // guessed while its own message has not landed; without them (a turn cut at the front door) the first reply, as before.
104
+ // …and its own message by the ledger id the server named (side sweep round 2: an EARLIER message with the same text, brought in
105
+ // by a late poll, was taken for it, and that message's answer for the reply); a server that names none: the first same text
106
+ const own = this._promptId ? slice.findIndex((x) => x && x.id === this._promptId) : slice.findIndex((x) => !isReply(x) && String(x.text || '') === this._sent)
107
+ const m = (this._replyText ? after.find((x) => String(x.text || '') === this._replyText) : null) || (own >= 0 ? slice.slice(own + 1).find(isReply) : this._replyText ? null : after[0])
100
108
  if (m) this._settle(m.stopped ? 'aborted' : 'done', { reply: m })
101
109
  }
102
110
 
package/sharedViews.js CHANGED
@@ -18,6 +18,8 @@ export function renderSharedViews(views, source = '') {
18
18
  parts.push('ITINERARY' + (st.title ? ' — ' + st.title : '') + '\n' + st.days.map((d) => `${(d && d.name) || 'Day'}: ${((d && d.items) || []).map((i) => `${i && i.when ? i.when + ' — ' : ''}${(i && i.text) || ''}`).filter(Boolean).join('; ')}`).join('\n'))
19
19
  } else if (Array.isArray(st.places) && st.places.length) {
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
+ } else if (Array.isArray(st.places)) {
22
+ parts.push('MAP (' + String((v && v.label) || 'map').replace(/^\W+\s*/, '') + '): no stops') // an empty map is "no stops" (owner decision 14)
21
23
  }
22
24
  }
23
25
  const chars = Array.from(parts.join('\n\n').slice(0, SHARED_VIEWS_MAX))
@@ -33,6 +35,20 @@ export function renderSharedViews(views, source = '') {
33
35
  return chars.slice(0, low).join('')
34
36
  }
35
37
 
38
+ /** ONE VIEW'S READ → what the lane is told (side sweep: empty-map-card-blocks-lane-view-refresh; owner decision 14: an empty map means
39
+ * "no stops", not "unchanged"). A map whose places all failed to resolve has a card and no doc, so an ANSWERED read with no state is
40
+ * that map with no stops — it used to stop the whole `sharedviews` write, and the lane's assistant kept the previous plan. A FAILED
41
+ * read (none, or a non-200) is unknown → null: the caller writes nothing. Not a map: a missing doc says nothing. */
42
+ export function viewFromRead({ label, map } = {}, r) {
43
+ if (!r || (r.status && r.status !== 200)) return null
44
+ if (r.state) return { label, state: r.state }
45
+ if (r.status !== 200) return null // no state and no answer that says so: unknown
46
+ return { label, state: map ? { places: [] } : null }
47
+ }
48
+ /** Is a view a MAP? The log names its kind ('places' when the agent drew a map); an older entry with none is a map unless it is the
49
+ * itinerary — the app's widget card makes the same default (widgetCard.js). */
50
+ export const isMapView = (v) => (v && v.kind ? v.kind === 'places' : !(v && v.name === 'itinerary'))
51
+
36
52
  /** The views a room's log names: each widget's doc name and label, newest first, at most `max`. */
37
53
  export function viewsNamedIn(entries, max = 12) {
38
54
  const out = [], seen = new Set()
@@ -45,7 +61,7 @@ export function viewsNamedIn(entries, max = 12) {
45
61
  if (w.name !== 'itinerary' || !out.length) continue
46
62
  out.pop()
47
63
  }
48
- seen.add(w.name); out.push({ name: w.name, label: typeof w.title === 'string' && w.title ? w.title : w.name })
64
+ seen.add(w.name); out.push({ name: w.name, label: typeof w.title === 'string' && w.title ? w.title : w.name, ...(typeof w.kind === 'string' && w.kind ? { kind: w.kind } : {}) })
49
65
  }
50
66
  }
51
67
  return out
package/siri.js CHANGED
@@ -31,12 +31,17 @@ export async function siriKeyHash(key) { return b64(await crypto.subtle.digest('
31
31
 
32
32
  /** The account's record as the Sentinel wants it (siri.mjs normSiriRecord), from the store's copy. */
33
33
  export async function siriRecordFor(account, s = loadSiri()) {
34
- const rooms = Object.entries(s.rooms || {})
34
+ // ONE SPOKEN NAME, ONE SPACE (side sweep siri-merge-keeps-duplicate-spoken-names): renames made on two devices merge per Space, so a
35
+ // name can end up on two — and the Sentinel refuses the whole record, keeping every Space on its old names. The Space renamed LAST
36
+ // (`at`) keeps the name; the other is left out of what is sent until it is given another.
37
+ const owner = new Map()
38
+ for (const [room, r] of Object.entries(s.rooms || {})) { const was = owner.get(r.alias); if (!was || (Number(r.at) || 0) > (Number(s.rooms[was].at) || 0)) owner.set(r.alias, room) }
39
+ const rooms = Object.entries(s.rooms || {}).filter(([room, r]) => owner.get(r.alias) === room)
35
40
  return {
36
41
  // a key the hosted app's vault holds is here only as its hash (`tokenHash`; vaultAcctSecrets.js, review § 7.6) — the same value
37
42
  account, tokenHash: s.token ? await siriKeyHash(s.token) : String(s.tokenHash || ''),
38
43
  aliases: rooms.map(([room, r]) => ({ alias: r.alias, room, label: r.label || '', inboxPub: { x: r.pub.x, y: r.pub.y } })),
39
- defaultAlias: s.defaultRoom && s.rooms[s.defaultRoom] ? s.rooms[s.defaultRoom].alias : '',
44
+ defaultAlias: s.defaultRoom && s.rooms[s.defaultRoom] && owner.get(s.rooms[s.defaultRoom].alias) === s.defaultRoom ? s.rooms[s.defaultRoom].alias : '',
40
45
  created: Date.now(),
41
46
  }
42
47
  }
@@ -64,6 +69,15 @@ function applyEdit(base, next, latest) {
64
69
  if (Object.keys(result.rooms).length > 64) throw new SiriError('Siri can use up to 64 Spaces.', 'too_many_rooms')
65
70
  return result
66
71
  }
72
+ /** Does `cur` show every change the edit (base → next) made? */
73
+ function editShows(base, next, cur) {
74
+ // a FIRST setup's own new key yields to one another device made meanwhile (applyEdit): that is the merge, not a conflict
75
+ const minted = !(base.token || base.tokenHash)
76
+ for (const f of ['token', 'tokenHash', 'defaultRoom']) if (!(minted && f !== 'defaultRoom') && !same(base[f], next[f]) && !same(cur[f], next[f])) return false
77
+ const b = base.rooms || {}, n = next.rooms || {}, c = cur.rooms || {}
78
+ for (const room of new Set([...Object.keys(b), ...Object.keys(n)])) if (!same(b[room], n[room]) && !same(c[room], n[room])) return false
79
+ return true
80
+ }
67
81
  export function pushSiriRecord(options = {}) {
68
82
  const { account, s, base = loadSiri() } = options
69
83
  const run = async () => {
@@ -84,7 +98,9 @@ export function pushSiriRecord(options = {}) {
84
98
  const current = loadSiri()
85
99
  let candidate
86
100
  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 } }
101
+ // nothing to send: the edit is already in place — or another device changed the same Space or setting meanwhile and its change
102
+ // stands, which is no save to report (side sweep: siri-conflicting-edit-reported-as-saved: "Renamed" / "Off" was shown)
103
+ if (!attempt && same(candidate, current)) { drop(entry); if (!replayed && !editShows(entry.base, entry.next, current)) throw new SiriError('Another device changed this Siri setting first — check it and try again.', 'siri_conflict'); return { ok: true } }
88
104
  const value = localStorage.getItem(EDIT_KEY)
89
105
  const saved = options.confirmStored ? await options.confirmStored(EDIT_KEY, value) : localStorage.getItem(EDIT_KEY) === value
90
106
  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
@@ -96,6 +112,10 @@ export function pushSiriRecord(options = {}) {
96
112
  if (!same(current, loadSiri())) continue
97
113
  saveSiri(candidate)
98
114
  drop(entry)
115
+ // SENT, BUT NOT THIS EDIT (side sweep: siri-conflicting-edit-reported-as-saved — the rest): another device changed the same Space
116
+ // or setting while this edit was being published; the retry sent the record as it now stands (the Sentinel must hold what the
117
+ // device holds), without this edit's change — said as a conflict, never "Renamed" / "Off"
118
+ if (!replayed && !editShows(entry.base, entry.next, candidate)) throw new SiriError('Another device changed this Siri setting first — check it and try again.', 'siri_conflict')
99
119
  return result
100
120
  }
101
121
  throw new SiriError('The Siri setup is changing. Try again.', 'siri_busy')
@@ -272,7 +292,11 @@ export function uniqueAlias(base, taken) {
272
292
  for (let n = 2; ; n++) { const c = `${b.slice(0, 32 - String(n).length - 1)} ${n}`; if (!taken.has(c)) return c }
273
293
  }
274
294
 
275
- export function siriAliasesDiffer(rooms, status) {
295
+ /** The service's record differs from this list. `defaultRoom` (this device's default Space, '' for none): a changed default is
296
+ * a difference too — an unnamed phrase follows the service's default (side sweep). Not passed: aliases only, as before. */
297
+ export function siriAliasesDiffer(rooms, status, defaultRoom) {
276
298
  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)
299
+ if (aliases.length !== Object.keys(rooms).length || aliases.some(a => !rooms[a.room] || rooms[a.room].alias !== a.alias)) return true
300
+ if (defaultRoom === undefined) return false
301
+ return ((defaultRoom && rooms[defaultRoom] && rooms[defaultRoom].alias) || '') !== (status.defaultAlias || '')
278
302
  }
package/spaceClient.js CHANGED
@@ -792,6 +792,9 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
792
792
  // ONE DECODER for a sealed poll answer (the v3 per-entry wrapper, or a whole v1/v2 blob): pollSealed runs it on the
793
793
  // network's answer, and the L1 worker runs it on an answer the service worker PREFETCHED when the push arrived
794
794
  // (prefetchPoll.js) — so a room opened from a notification shows the new message without waiting for a round trip.
795
+ // `sinceEdit`: the ledger's edit record a reader last saw (agent/ledgerEdits.mjs) — a plain tag naming no content; the answer's `edits`
796
+ // names the entries changed in place since (side sweep: reaction-refresh-misses-edited-history). Only a string the server gave.
797
+ const editField = (opts) => (opts && typeof opts.sinceEdit === 'string' && opts.sinceEdit.length <= 64 ? { sinceEdit: opts.sinceEdit } : {})
795
798
  const decodeSealed = async (room, mk, sinceCount, r) => {
796
799
  const withPartial = async (o) => {
797
800
  let out = o || {}
@@ -827,11 +830,26 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
827
830
  // box and answered "nothing new"). Say so, the way the server's own path does: 422 lifts the couldn't-unlock banner.
828
831
  if (wrap.boxes.length && !entries.length && unopenable === wrap.boxes.length) return await withPartial({ status: 422, etag: r.etag, changed: true, reason: 'undecodable', boxes: wrap.boxes.length, challenge: r.challenge })
829
832
  const total = Number.isInteger(r.count) ? r.count : sinceCount + entries.length
833
+ // EDITED IN PLACE since the reader's `sinceEdit` (agent/ledgerEdits.mjs; side sweep: reaction-refresh-misses-edited-history): the
834
+ // entries it already holds that changed (a reaction added or removed far back), opened here like the slice. `since` is the record
835
+ // the server answered for: a reader adopts `tag` only when that is the one it sent. `missing`: edited, but not carried (too large) —
836
+ // the reader reads it itself. `lost`: the record cannot say — the reader re-reads as it did before.
837
+ let edits
838
+ if (r.edits && typeof r.edits === 'object' && typeof r.edits.tag === 'string') {
839
+ const got = [], have = new Set()
840
+ for (const pair of Array.isArray(r.edits.boxes) ? r.edits.boxes : []) {
841
+ const i = Array.isArray(pair) ? pair[0] : null
842
+ if (!Number.isInteger(i) || typeof pair[1] !== 'string') continue
843
+ try { const pt = await openAny(room, JSON.parse(pair[1]), mk, ledgerAad(room, i)); if (pt != null) { got.push(JSON.parse(pt)); have.add(i) } } catch { /* an unopenable box: read below as missing */ }
844
+ }
845
+ const missing = (Array.isArray(r.edits.at) ? r.edits.at : []).filter((i) => Number.isInteger(i) && !have.has(i))
846
+ edits = { since: typeof r.edits.since === 'string' ? r.edits.since : undefined, tag: r.edits.tag, entries: got, missing, ...(r.edits.lost === true ? { lost: true } : {}) }
847
+ }
830
848
  // `done` — entries that have been through a COMPLETED turn (agent/spaceLedgerV3.mjs). Plaintext on the
831
849
  // wrapper, so it costs no key. A turn the agent answers with SILENCE appends nothing, so this
832
850
  // advancing is the ONLY event it produces, and it is what lets a peer stop showing "thinking".
833
851
  // `more`: another page follows from `version` (ledgerView.readAllPages; sync sweep, 2026-10-10)
834
- return await withPartial({ status: 200, etag: r.etag, changed: true, version: total, entries, ...(r.more ? { more: true } : {}), challenge: r.challenge, done: r.done, partial: r.partial, partialSeq: r.partialSeq, boxes: wrap.boxes.length, ...(unopenable ? { refused: unopenable } : {}) })
852
+ return await withPartial({ status: 200, etag: r.etag, changed: true, version: total, entries, ...(r.more ? { more: true, ...(Number.isInteger(r.total) ? { total: r.total } : {}) } : {}), challenge: r.challenge, done: r.done, partial: r.partial, partialSeq: r.partialSeq, boxes: wrap.boxes.length, ...(unopenable ? { refused: unopenable } : {}), ...(edits ? { edits } : {}) })
835
853
  }
836
854
  let all = null
837
855
  try { all = JSON.parse(await openAny(room, JSON.parse(r.sealed), mk)) } catch { all = null }
@@ -844,6 +862,53 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
844
862
  const from = Number.isInteger(sinceCount) && sinceCount > 0 ? Math.min(sinceCount, all.length) : 0
845
863
  return await withPartial({ status: 200, etag: r.etag, changed: true, version: all.length, entries: all.slice(from), challenge: r.challenge, partial: r.partial, partialSeq: r.partialSeq })
846
864
  }
865
+ // THE OFFLINE COPY CARRIES THE STORED ATTACHMENTS (side sweep: sealed-offline-archive-omits-stored-attachments; the owner,
866
+ // 2026-11-28: "Put the files in."). A photo or document a member shared is stored out of line (agent/attachmentBlobs.mjs):
867
+ // the ledger keeps only `ref` or `parts`, so an offline copy of the ledger alone showed a name and lost the bytes once the
868
+ // Space was gone. The archive's entries are opened HERE (the key never leaves), every stored attachment's blobs are read
869
+ // exactly as the `blob` op serves them — SEALED, never opened and sealed again — and kept as `blobs: { ref: envelope }`;
870
+ // the offline reader (decrypt.html) opens them with the same keys as the messages. An attachment that would pass `budget`
871
+ // (bytes of sealed text) or whose read fails is left out and counted; the reader says "not in this copy" for it.
872
+ const archiveAttachments = async (room, mk, ledger, budget) => {
873
+ const blobs = {}, stats = { total: 0, included: 0, tooLarge: 0, failed: 0, bytes: 0 }
874
+ let entries = []
875
+ if (ledger && ledger.v === 3 && Array.isArray(ledger.boxes)) {
876
+ const base = Number(ledger.from) || 0
877
+ for (let j = 0; j < ledger.boxes.length; j++) {
878
+ try { const box = ledger.boxes[j], pt = await openAny(room, typeof box === 'string' ? JSON.parse(box) : box, mk, ledgerAad(room, base + j)); if (pt != null) entries.push(JSON.parse(pt)) } catch { /* an unopenable box carries nothing we can name */ }
879
+ }
880
+ } else {
881
+ try { let all = JSON.parse(await openAny(room, ledger, mk)); if (all && !Array.isArray(all)) all = all.entries; if (Array.isArray(all)) entries = all } catch { entries = [] }
882
+ }
883
+ const seen = new Set(), list = []
884
+ for (const e of entries) {
885
+ for (const k of ['images', 'files']) {
886
+ for (const a of (e && Array.isArray(e[k]) ? e[k] : [])) {
887
+ if (!a || (typeof a.b64 === 'string' && a.b64)) continue // inline bytes are already in the box
888
+ const refs = Array.isArray(a.parts) && a.parts.length ? a.parts : (typeof a.ref === 'string' && a.ref ? [a.ref] : [])
889
+ if (!refs.length || refs.some((x) => typeof x !== 'string' || !x)) continue
890
+ const id = refs.join(' '); if (seen.has(id)) continue
891
+ seen.add(id); list.push({ refs, size: Number(a.size) || 0 })
892
+ }
893
+ }
894
+ }
895
+ stats.total = list.length
896
+ for (const { refs, size } of list) {
897
+ if (size > 0 && stats.bytes + Math.ceil(size * 4 / 3) > budget) { stats.tooLarge++; continue } // its base64 alone would pass the cap: not downloaded at all
898
+ const got = []; let n = 0, failed = false
899
+ for (const ref of refs) {
900
+ let r = null
901
+ try { r = await withVerified(room, async () => sealedRead(room, mk, 'blob', { ref })) } catch { r = null }
902
+ if (!r || r.status !== 200 || r.sealed == null) { failed = true; break }
903
+ got.push([ref, r.sealed]); n += (typeof r.sealed === 'string' ? r.sealed : JSON.stringify(r.sealed)).length
904
+ }
905
+ if (failed) { stats.failed++; continue }
906
+ if (stats.bytes + n > budget) { stats.tooLarge++; continue }
907
+ for (const [ref, sealed] of got) blobs[ref] = sealed
908
+ stats.bytes += n; stats.included++
909
+ }
910
+ return { blobs, stats }
911
+ }
847
912
  const api = {
848
913
  _openAny: openAny, // internal: a box opened with the room's key or, after an in-place change, an earlier one (tests)
849
914
  /** Mint a Space from a config, register its PUBLIC record (commit + config) with the server, and return
@@ -982,8 +1047,11 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
982
1047
  if (identity && identity.googleIdToken && identity.sign && identity.sign.priv && identity.sign.pub) {
983
1048
  const ts = Date.now()
984
1049
  const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`
985
- const { sig } = await signEntry(identity.sign.priv, { room, author: identity.email, ts, kind: 'text', id, text, ...(message && message.chal ? { chal: message.chal } : {}) }) // chal: the room's fresh challenge rides in the signed core when the turn carries one (deviceAttest.js; the server folds it the same way)
986
- m = { ...message, from: identity.email, ts, id, kind: 'text', sig, spk: identity.sign.pub, idToken: identity.googleIdToken }
1050
+ // the member's CHOSEN NAME stays the author (side sweep: verified-turn-replaces-display-name-with-email): the server verifies
1051
+ // the signature over `from` and keeps it as a display name (spaceOidc verifyEmailTurn) — the address is proven by the token
1052
+ const author = message && typeof message.from === 'string' && message.from.trim() ? message.from : identity.email
1053
+ const { sig } = await signEntry(identity.sign.priv, { room, author, ts, kind: 'text', id, text, ...(message && message.chal ? { chal: message.chal } : {}) }) // chal: the room's fresh challenge rides in the signed core when the turn carries one (deviceAttest.js; the server folds it the same way)
1054
+ m = { ...message, from: author, ts, id, kind: 'text', sig, spk: identity.sign.pub, idToken: identity.googleIdToken }
987
1055
  } else if (identity && identity.grant && identity.sign && identity.sign.priv) {
988
1056
  const ts = Date.now()
989
1057
  const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}` // client nonce → the signed core's id (anti-replay)
@@ -1011,7 +1079,9 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1011
1079
  // Seed the Space from a PUBLIC ChatGPT share link → continue a one-on-one chat together. The Lambda fetches +
1012
1080
  // parses it (SSRF-guarded) and seals the history into the ledger; the URL is public so this carries no secret.
1013
1081
  importChat: async (room, mk, chatgptUrl, billingToken) => post({ op: 'import', room, ...(await keyFields(room, 'import', mk)), chatgptUrl, ...(await authFor(room)) }, billingToken),
1014
- importWhatsApp: async (room, mk, whatsappText, billingToken) => post({ op: 'import', room, ...(await keyFields(room, 'import', mk)), whatsappText, ...(await authFor(room)) }, billingToken), // WhatsApp export: client unzipped the _chat.txt → server parses + seals
1082
+ // `hints` { tz, order }: the client's time zone (getTimezoneOffset) and date order — each message keeps its own WhatsApp time (side
1083
+ // sweep: sdk-whatsapp-import-restamps-message-times); an older server ignores them
1084
+ importWhatsApp: async (room, mk, whatsappText, billingToken, hints) => post({ op: 'import', room, ...(await keyFields(room, 'import', mk)), whatsappText, ...(hints && Number.isInteger(hints.tz) ? { whatsappTz: hints.tz } : {}), ...(hints && typeof hints.zone === 'string' && /^[A-Za-z0-9_+\-/]{1,64}$/.test(hints.zone) ? { whatsappZone: hints.zone } : {}), ...(hints && (hints.order === 'mdy' || hints.order === 'dmy') ? { whatsappOrder: hints.order } : {}), ...(await authFor(room)) }, billingToken), // WhatsApp export: client unzipped the _chat.txt → server parses + seals
1015
1085
  // MIRROR — append entries this device copied from a LINKED room (docs/spaces-private-lane.md) into THIS room's ledger,
1016
1086
  // no agent turn. Deduped by entry id server-side. Files/images ride along so the assistant reads them natively.
1017
1087
  mirror: async (room, mk, entries) => {
@@ -1044,14 +1114,15 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1044
1114
  // answers `poll` with the whole DECRYPTED history, and that answer crosses the Lambda and the enclave's parent host in
1045
1115
  // the clear. Read it sealed and open it here. Every caller (the room loop, the unread sweep, lanes, mail, pins…) comes
1046
1116
  // through this one function, so none can send the readable read by accident. Same answer shape (pollSealed's contract).
1047
- if (enclaveFor(room)) return api.pollSealed(room, mk, sinceEtag, sinceCount, ci)
1117
+ const ed = editField(opts) // the edit record this reader last saw (agent/ledgerEdits.mjs)
1118
+ if (enclaveFor(room)) return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, ...ed })
1048
1119
  // …AND A REGULAR ROOM IS READ SEALED TOO (the owner, 2026-11-06: "Do then regular rooms read sealed too"): `poll` sent the
1049
1120
  // room key about every 600 ms and the Lambda decrypted the whole history to answer it. The sealed read is opened here; the
1050
1121
  // key rides only the read that registers this device's CHANGE INBOX (the first of a session — inboxForPoll), because the
1051
1122
  // server follows the room for it only once that read proves the key (spaceHandler pollProvedKey). A verified room's sealed
1052
1123
  // read carries no key either: its server checks the sign-in against its sealed copy of the list (sealedRead). Older apps keep `poll`.
1053
1124
  // (a room re-keyed in place: pollSealed asks once more WITH the key when the boxes do not open — see there)
1054
- return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, proveKey: !!ci.changeInbox })
1125
+ return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, ...ed, proveKey: !!ci.changeInbox })
1055
1126
  },
1056
1127
 
1057
1128
  /** CONTENT-BLIND poll — the same contract as `poll`, but `mk` NEVER leaves this device. The server returns the
@@ -1064,7 +1135,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1064
1135
  const ci = opts && typeof opts.changeInbox === 'string' ? { changeInbox: opts.changeInbox } : {} // ONLY the inbox id: a plain op carries nothing a caller hands it by mistake (confidentialWire.test.mjs) // ci: { changeInbox } when poll() reads a confidential room sealed — the drawer's follow rides it (agent/changeFeed.mjs pollSubscribeIntent takes both ops)
1065
1136
  // the key rides only as sealedRead says (proveKey: a regular room's read that registers the change inbox)
1066
1137
  const sent = { keyed: false }
1067
- const send = async () => sealedRead(room, mk, 'pollsealed', { sinceEtag, sinceCount, ...ci }, { proveKey: !!(opts && opts.proveKey && mk && !enclaveFor(room)), sent })
1138
+ const send = async () => sealedRead(room, mk, 'pollsealed', { sinceEtag, sinceCount, ...ci, ...editField(opts) }, { proveKey: !!(opts && opts.proveKey && mk && !enclaveFor(room)), sent })
1068
1139
  const r = await withVerified(room, send) // + attach a client-release attestation for a verified room (learned lazily)
1069
1140
  // The IN-PROGRESS reply, opened here like everything else — the server passed it through sealed. It rides EVERY
1070
1141
  // response including the unchanged one, which is the whole point: while a reply is still being written the
@@ -1077,7 +1148,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1077
1148
  // this case (linkMembers.test.mjs caught it). HERE, not in poll(): the SDK and a vault read with pollSealed, and an
1078
1149
  // open confidential room's poll() came straight here — neither ever asked (sweep 11-07 #1, #2).
1079
1150
  if (out && out.status === 422 && out.reason === 'undecodable' && mk && !sent.keyed) {
1080
- const r2 = await withVerified(room, async () => sealedRead(room, mk, 'pollsealed', { sinceEtag, sinceCount, ...ci }, { proveKey: true })) // ci kept: this keyed read is the one that can register the inbox (state machines pass 7, T#3)
1151
+ const r2 = await withVerified(room, async () => sealedRead(room, mk, 'pollsealed', { sinceEtag, sinceCount, ...ci, ...editField(opts) }, { proveKey: true })) // ci kept: this keyed read is the one that can register the inbox (state machines pass 7, T#3)
1081
1152
  return decodeSealed(room, mk, sinceCount, r2)
1082
1153
  }
1083
1154
  return out
@@ -1086,7 +1157,11 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1086
1157
  // { v:3, boxes:[…] } wrapper), NOT opened here. sinceCount:0 ⇒ everything. Same gated-retry as pollSealed. The
1087
1158
  // downloaded file carries no plaintext — it is only readable with the room key, via the offline decryptor
1088
1159
  // (/decrypt.html). Returns { status, sealed, count, etag }.
1089
- exportSealed: async (room, mk) => {
1160
+ // `opts.attachments = { budget }` (bytes, > 0): the OFFLINE COPY also carries the attachments stored out of line
1161
+ // (agent/attachmentBlobs.mjs) — their sealed envelopes exactly as stored, under `blobs` beside the boxes, up to `budget`;
1162
+ // the answer's `attachments` says how many went in and how many were left out (archiveAttachments below). Without it the
1163
+ // answer is unchanged — sealedProof hashes it (witbitz-sdk.js receipt).
1164
+ exportSealed: async (room, mk, opts = {}) => {
1090
1165
  const archive = await readSealedArchive(sinceCount => withVerified(room, () => sealedRead(room, mk, 'pollsealed', { sinceCount })))
1091
1166
  if (archive?.status !== 200 || !archive.sealed) return archive
1092
1167
  const ledger = JSON.parse(archive.sealed)
@@ -1102,7 +1177,11 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1102
1177
  }
1103
1178
  if (previous?.length) ledger.keyHistory = await seal(JSON.stringify({ room, keys: previous }), { room: mk })
1104
1179
  }
1105
- return { ...archive, sealed: JSON.stringify(ledger) }
1180
+ const budget = Number(opts && opts.attachments && opts.attachments.budget)
1181
+ if (!(budget > 0)) return { ...archive, sealed: JSON.stringify(ledger) }
1182
+ const { blobs, stats } = await archiveAttachments(room, mk, ledger, budget)
1183
+ if (Object.keys(blobs).length) ledger.blobs = blobs
1184
+ return { ...archive, sealed: JSON.stringify(ledger), attachments: stats }
1106
1185
  },
1107
1186
  pending: async (room, mk) => post({ op: 'pending', room, ...(await keyFields(room, 'pending', mk)), ...(await authFor(room)) }),
1108
1187
  /** APPROVAL REMINDERS for Code (agent/approvalRemind.mjs): this device's push address, signed by the server, for the
@@ -1171,6 +1250,8 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1171
1250
  deviceVerify: async ({ platform, keyId, nonce, assertion, sig, integrity }) => post({ op: 'device-verify', device: { platform, keyId, nonce, ...(assertion ? { assertion } : {}), ...(sig ? { sig } : {}), ...(integrity ? { integrity } : {}) } }),
1172
1251
  // the ATTESTED BACKUP (agent/attestedBackup.mjs): op 'attested-chal' | 'attested-get' | 'attested-put', the fields in `attested`
1173
1252
  attestedOp: async (op, attested, chal) => post({ op, attested, ...(chal ? { chal } : {}) }),
1253
+ // the record of the account's EARLIER keys beside it (agent/attestedPrev.mjs): `mode` chal | get (attested) | put (the new master's proof)
1254
+ attestedPrevOp: async (mode, prev, chal) => post({ op: 'attested-prev', prev: { ...(prev || {}), mode }, ...(chal ? { chal } : {}) }),
1174
1255
  // K_att (infra/cloud-computer/sentinel/attkey.mjs): `mode` chal | get — the standing Sentinel's challenge, then the secret sealed to
1175
1256
  // the device's one-time key (attested.epk), after the attestation it verifies itself. The Space Lambda only relays.
1176
1257
  attkeyOp: async (mode, attested, chal) => post({ op: 'attkey', ...(mode === 'chal' ? { mode: 'chal' } : {}), attested, ...(chal ? { chal } : {}) }),
@@ -1225,7 +1306,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1225
1306
  userTag: async (username, room) => call(endpoint, { op: 'user', mode: 'tag', username, room }, f), // a DIRECTORY op (the room is only its salt): the Lambda answers it for a room of either tier — through post() a confidential room's went to the enclave, which has no directory (sync sweep 10-21 #5)
1226
1307
  userWhoami: async (idToken) => post({ op: 'user', mode: 'whoami', idToken }),
1227
1308
  userClaim: async (username, idToken, { name, publish } = {}) => extrasCache.clear() || post({ op: 'user', mode: 'claim', username, idToken, ...(publish ? { publish: true, ...(name ? { name } : {}) } : {}) }),
1228
- userRelease: async (idToken) => extrasCache.clear() || post({ op: 'user', mode: 'release', idToken }),
1309
+ userRelease: async (idToken, username) => extrasCache.clear() || post({ op: 'user', mode: 'release', idToken, ...(username ? { username } : {}) }), // username (optional): only that name — the server refuses 'changed' when the account holds another now
1229
1310
  dirErase: async (idToken, scope) => post({ op: 'dir', mode: 'erase', idToken, ...(scope ? { dirScope: scope } : {}) }), // DELETE MY ACCOUNT (docs/user-erasure.md): the token's own directory row + inboxes
1230
1311
  // The invite inbox: drop a sealed box into a recipient's mailbox; inboxFetch reads YOUR mailbox (openBox with boxPriv).
1231
1312
  drop: async (inbox, box) => post({ op: 'drop', inbox, box }),
@@ -1233,6 +1314,8 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1233
1314
  // "Which of my rooms changed since `since`?" — the change inbox, standard tier (docs/change-inbox.md). Keyless.
1234
1315
  changes: async (inbox, since = 0) => post({ op: 'changes', inbox, since }),
1235
1316
  inboxSubscribe: async (inbox, subscription) => post({ op: 'inboxsub', inbox, subscription }), // register this device for a real-time invite tickle
1317
+ // a signed-out device's address off the invite inbox's list (the endpoint alone; an older server answers 400 — never an add)
1318
+ inboxUnsubscribe: async (inbox, subscription) => post({ op: 'inboxsub', inbox, remove: true, subscription: { endpoint: subscription && subscription.endpoint } }),
1236
1319
  decide: async (room, mk, id, approve, by, { bridgeMk, bridgeRoom, editText, deviceExec, recordResult } = {}, billingToken) => post({ op: 'decide', room, ...(await keyFields(room, 'decide', mk)), id, approve, by, ...(await crossingPush(bridgeRoom)), ...(await otherAuth([bridgeRoom])), ...(await authFor(room)), ...(bridgeMk ? await bridgeFields(room, 'decide', bridgeMk) : {}), ...(bridgeRoom ? { bridgeRoom } : {}), ...(editText ? { editText } : {}), ...(deviceExec ? { deviceExec } : {}), ...(recordResult === false ? { recordResult: false } : {}) }, billingToken), // editText: the approver's edit of the pending crossing // bridgeMk: approving a cross_to_shared posts into the linked shared room // deviceExec: a client-executed action (calendar write) — the server must skip its executor
1237
1320
 
1238
1321
  // Shared WIDGET state (co-edited by members; the agent reads its `summary` on turns). SET with a `patch` (+ a short
@@ -1265,7 +1348,8 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1265
1348
  intakeReg: async (room, mk, ops) => post({ op: 'intakereg', room, ...(await keyFields(room, 'intakereg', mk)), ops: Array.isArray(ops) ? ops.slice(0, 50) : [] }),
1266
1349
  intakePush: async (room, mk, subscription, remove = false) => post({ op: 'intakepush', room, ...(await keyFields(room, 'intakepush', mk)), subscription, ...(remove ? { remove: true } : {}) }), // this device on the intake's wake list (messageIntake.mjs)
1267
1350
  intakeDeviceWake: async (room, mk, remove = false) => post({ op: 'intakepush', room, ...(await keyFields(room, 'intakepush', mk)), cloudDevice: true, ...(remove ? { remove: true } : {}) }), // the cloud device on the wake list (docs/cloud-device.md § 12)
1268
- intake: async (room, mk) => post({ op: 'intake', room, ...(await keyFields(room, 'intake', mk)) }),
1351
+ // `from` { drop, n }: start the read at that position (a later page past boxes that must stay — roomIntake.js collect)
1352
+ intake: async (room, mk, from) => post({ op: 'intake', room, ...(from && typeof from === 'object' ? { from: { drop: String(from.drop), n: Number(from.n) } } : {}), ...(await keyFields(room, 'intake', mk)) }),
1269
1353
  intakeAck: async (room, mk, items) => post({ op: 'intakeack', room, ...(await keyFields(room, 'intakeack', mk)), ops: Array.isArray(items) ? items.slice(0, 50) : [] }),
1270
1354
  // SAFE MEDIA (docs/safe-media.md § 5): the safe copy a device made of a photo or PDF in the room → stored beside it (agent/safeCopy.mjs)
1271
1355
  safeCopy: async (room, mk, safe, by) => post({ op: 'safe', room, ...(await keyFields(room, 'safe', mk)), safe, ...(by ? { by: String(by).slice(0, 80) } : {}), ...(await authFor(room)) }),
package/spaceExport.js CHANGED
@@ -16,11 +16,17 @@ const EXPORT_KIND = 'witbitz-space-export'
16
16
  //
17
17
  // `reader` needs exactly two methods, both already l1 ops: poll(room, undefined, 0) and getConfig(room).
18
18
  import { readAllPages } from './ledgerView.js'
19
+ const EXPORT_READS = 3 // whole reads of a room that keeps changing between its pages, before the export asks for a retry
19
20
  export async function exportSpace(room, reader, meta = {}) {
20
21
  if (!room || !reader || typeof reader.poll !== 'function') throw new Error('bad_args')
21
- const p = await readAllPages((since) => reader.poll(room, undefined, since)) // the whole history, every page
22
+ // the whole history, every page — ONE revision of it: pages read while the room changed are read again, a few times, before the
23
+ // export gives up and asks for a retry (side sweep: portable-export-mixes-history-revisions)
24
+ let p = null
25
+ for (let tries = 0; tries < EXPORT_READS; tries++) { p = await readAllPages((since) => reader.poll(room, undefined, since)); if (!(p && p.mixed && !p.incomplete)) break }
22
26
  // A page that failed would make a SHORT export look whole: refuse it, so the person tries again (sync sweep, 2026-10-10).
23
- if (p && p.incomplete) throw Object.assign(new Error('export_incomplete'), { userMsg: 'Part of this Space’s history couldn’t be read — try the export again.' })
27
+ // …and so would a page that opened only part of its entries (`refused`: an earlier room key out of reach just now — side sweep 2026-11-28)
28
+ if (p && (p.incomplete || p.refused)) throw Object.assign(new Error('export_incomplete'), { userMsg: 'Part of this Space’s history couldn’t be read — try the export again.' })
29
+ if (p && p.mixed) throw Object.assign(new Error('export_changing'), { userMsg: 'This Space changed while it was being exported — try the export again.' })
24
30
  const raw = p && Array.isArray(p.entries) ? p.entries : []
25
31
  // Collapse fork/relink mirror duplicates by canonical id (a fork changes the `sh:<sharedRoom>:` prefix), so an export
26
32
  // matches what's shown in-app and a recreate doesn't carry doubles — even if the server ledger hasn't been collapsed yet.
@@ -28,7 +34,7 @@ export async function exportSpace(room, reader, meta = {}) {
28
34
  const seenC = new Set()
29
35
  const entries = raw.filter((e) => { if (!e || e.id == null) return true; const c = canon(e.id); if (seenC.has(c)) return false; seenC.add(c); return true })
30
36
  let config = null
31
- try { config = typeof reader.getConfig === 'function' ? await reader.getConfig(room) : null } catch { /* config is best-effort — a ledger-only export is still useful */ }
37
+ try { config = typeof reader.getConfig === 'function' ? portableConfig(await reader.getConfig(room)) : null } catch { /* config is best-effort — a ledger-only export is still useful */ }
32
38
  const withBytes = typeof reader.blob === 'function' ? await Promise.all(entries.map((e) => inlineAttachments(e, room, reader))) : entries
33
39
  // DIAGNOSTICS (the owner, 2026-10-04, after a members sheet nobody could explain from the file: "add more info to the
34
40
  // export"). The guest book and the server's sign-in records are what the members sheet is built from; the authors
@@ -36,7 +42,9 @@ export async function exportSpace(room, reader, meta = {}) {
36
42
  let guestBook = null
37
43
  try {
38
44
  const g = typeof reader.state === 'function' ? await reader.state(room, 'roster') : null
39
- if (g && (g.state || g.seen)) guestBook = { people: (g.state && Array.isArray(g.state.people)) ? g.state.people : [], ...(g.seen ? { seen: g.seen } : {}) }
45
+ // The roster is kept as `{ people: [...] }` OR as a bare array (roomRoster.js `rows`, the SDK keeps that shape).
46
+ const people = Array.isArray(g && g.state) ? g.state : (g && g.state && Array.isArray(g.state.people)) ? g.state.people : []
47
+ if (g && (g.state || g.seen)) guestBook = { people, ...(g.seen ? { seen: g.seen } : {}) }
40
48
  } catch { /* best-effort, like the config */ }
41
49
  return {
42
50
  v: 1, kind: EXPORT_KIND, room, title: meta.title || '', exportedAt: meta.now || Date.now(), count: entries.length,
@@ -48,6 +56,16 @@ export async function exportSpace(room, reader, meta = {}) {
48
56
  }
49
57
  }
50
58
 
59
+ /** A readable file carries no credential: a connection's callKey spends it, and keyChain holds the room's earlier keys. The
60
+ * connections stay listed by name. Every export goes through it — the regular app's as the SDK's (side sweep:
61
+ * portable-export-includes-room-credentials). A new copy; the room's config object is not changed. */
62
+ export function portableConfig(config) {
63
+ if (!config || typeof config !== 'object') return config
64
+ const { keyChain, ...out } = config
65
+ if (Array.isArray(out.connections)) out.connections = out.connections.map((c) => { if (!c || typeof c !== 'object') return c; const { callKey, ...rest } = c; return rest })
66
+ return out
67
+ }
68
+
51
69
  const keyIdOf = (k) => (k && k.x && k.y ? k.x.slice(0, 8) + '…' : '')
52
70
  /** Per author: how many entries, under which signing keys, verified or not, the attested @username, first/last time. */
53
71
  export function authorsOf(entries = []) {
@@ -91,6 +109,30 @@ async function inlineAttachments(e, room, reader) {
91
109
  return out
92
110
  }
93
111
 
112
+ /** A linked continuation's EARLIER VERSIONS' entries (bundle.earlier): their attachments are sealed to the version each entry came
113
+ * from (`epochRoom`, spaceFork readEpochChain), so `blob(epochRoom, ref)` reads them with that version's key — bytes inline, as the
114
+ * room's own; one that will not open keeps its pointer and is counted (side sweep: portable-export-silent-attachment-read-failure). */
115
+ export async function inlineEarlier(entries, blob) {
116
+ if (!Array.isArray(entries) || typeof blob !== 'function') return entries
117
+ return Promise.all(entries.map((e) => inlineAttachments(e, e && e.epochRoom, { blob })))
118
+ }
119
+
120
+ /** How many attachments an export still carries only as a pointer to the room (their bytes could not be read): the export
121
+ * says so — a recreated room cannot open them (side sweep: portable-export-silent-attachment-read-failure). The earlier
122
+ * versions' entries count too. */
123
+ export function missingAttachments(bundle) {
124
+ let n = 0
125
+ const all = [...(bundle && Array.isArray(bundle.entries) ? bundle.entries : []), ...(bundle && bundle.earlier && Array.isArray(bundle.earlier.entries) ? bundle.earlier.entries : [])]
126
+ for (const e of all) for (const k of ['images', 'files']) for (const a of (e && Array.isArray(e[k]) ? e[k] : [])) if (isStored(a)) n++
127
+ return n
128
+ }
129
+
130
+ /** How many MESSAGES an export holds, as the member saw them: a photo's Safe media copy (`kind: 'safe'`) is its own stored entry but is
131
+ * drawn in the photo's place, so it is not counted (it stays in the file) — side sweep: room-export-counts-hidden-records-as-messages. */
132
+ export function messageCount(entries) {
133
+ return (Array.isArray(entries) ? entries : []).filter((e) => !(e && e.kind === 'safe')).length
134
+ }
135
+
94
136
  export function isExport(bundle) { return !!bundle && bundle.kind === EXPORT_KIND && Array.isArray(bundle.entries) }
95
137
 
96
138
  // Recreate a room from an export: mint a NEW room carrying the exported agent config, then replay the entries. Injected
@@ -120,6 +162,9 @@ export async function recreateSpace(bundle, { createSpace, mirror }) {
120
162
  // it, or the new room's poll follows a stale move (spaceFork.js; sync sweep, 2026-10-10).
121
163
  // Rows ride as DATA (`carry: 'fork'`, as spaceFork.js marks them), so the new room's store holds the same rows.
122
164
  const entries = bundle.entries.filter((e) => e && e.kind !== 'fork').map((e) => (e.kind === 'data' && Array.isArray(e.ops) ? { ...e, carry: 'fork' } : e))
123
- const carried = entries.length ? await mirrorInBatches(mirror, made.room, made.mk, entries) : 0
165
+ const sent = entries.length ? await mirrorInBatches(mirror, made.room, made.mk, entries) : 0
166
+ // a message with no id (an older open room's) is skipped by the server's mirror, which still answers 200 — it is not copied, and
167
+ // the short-copy warning must say so (side sweep 2026-11-28)
168
+ const carried = sent - entries.slice(0, sent).filter((e) => e.id == null).length
124
169
  return { ...made, carried, total: entries.length }
125
170
  }
package/spaceFork.js CHANGED
@@ -20,9 +20,11 @@ import { mirrorInBatches } from './spaceExport.js' // the whole history in slice
20
20
  import { roomRegion } from './regions.js' // a room's home region is in its id (docs/multi-region.md)
21
21
  import { readAllPages } from './ledgerView.js'
22
22
 
23
- async function readForkHistory(client, room, mk) {
23
+ // `whole`: a page that opened only part of its entries (`refused`) is not the whole history either — the export asks it (side
24
+ // sweep: portable-export-accepts-partly-readable-history); a fork and the conversation's drawing keep what they could open
25
+ async function readForkHistory(client, room, mk, { whole = false } = {}) {
24
26
  const poll = await readAllPages((since) => client.pollSealed(room, mk, undefined, since))
25
- if (poll.incomplete) throw Object.assign(new Error('history_incomplete'), { code: 'history_incomplete' })
27
+ if (poll.incomplete || (whole && poll.refused)) throw Object.assign(new Error('history_incomplete'), { code: 'history_incomplete' })
26
28
  return poll
27
29
  }
28
30
 
@@ -146,14 +148,20 @@ export async function forkRoom(client, oldRoom, oldMk, { self, remove = [], add
146
148
  * `parent` and the caller holds that epoch's key — recurses into the parent, oldest-first. A reader missing an ancestor
147
149
  * key simply stops there (forward-only from that epoch). Past epochs are immutable sealed history, so this is a one-shot
148
150
  * read on entry; the live poll loop still handles only the current epoch. `epochKeys` maps room → mk for each ancestor. */
149
- export async function readEpochChain(client, room, mk, epochKeys = {}, depth = 0) {
150
- const poll = await readForkHistory(client, room, mk)
151
- const here = ((poll && poll.entries) || []).filter((e) => e && e.kind !== 'fork')
151
+ // `{ whole: true }` (the export): every version read whole — a partly readable page, or settings that would not open (the chain
152
+ // may go on past them), THROW instead of a shorter list (side sweep: portable-export-accepts-partly-readable-history)
153
+ export async function readEpochChain(client, room, mk, epochKeys = {}, depth = 0, { whole = false, seen = [] } = {}) {
154
+ const poll = await readForkHistory(client, room, mk, { whole })
155
+ // each entry names the version it came from (`epochRoom`, additive, on this device only): a call announcement, a reaction, a pin
156
+ // of it belongs to THAT Space, not the open one (side sweep: call-join-uses-open-space and its siblings)
157
+ const here = ((poll && poll.entries) || []).filter((e) => e && e.kind !== 'fork').map((e) => ({ ...e, epochRoom: room }))
152
158
  if (depth >= 64) return here // cycle / runaway guard
153
- const cfg = await client.getConfig(room, mk).catch(() => null)
159
+ const cfg = await client.getConfig(room, mk).catch((e) => { if (whole) throw e; return null })
160
+ // settings that did not open (null) while this device still holds a key of a version not reached yet: the chain may go on
161
+ if (whole && !cfg && Object.keys(epochKeys || {}).some((k) => k !== room && !seen.includes(k))) throw Object.assign(new Error('history_incomplete'), { code: 'history_incomplete' })
154
162
  const parent = cfg && cfg.parent && cfg.parent.room
155
163
  if (parent && epochKeys && epochKeys[parent]) {
156
- const older = await readEpochChain(client, parent, epochKeys[parent], epochKeys, depth + 1)
164
+ const older = await readEpochChain(client, parent, epochKeys[parent], epochKeys, depth + 1, { whole, seen: [...seen, room] })
157
165
  return [...older, ...here]
158
166
  }
159
167
  return here