@witbitz/sdk 4.3.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 (112) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +41 -5
  3. package/accountErase.js +15 -4
  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/agentDoorTools.js +28 -0
  11. package/awsKey.js +3 -1
  12. package/backupRecord.js +3 -0
  13. package/chatLock.js +16 -0
  14. package/cloudDevicePins.js +2 -2
  15. package/codeAttachments.js +101 -0
  16. package/codeCache.js +173 -0
  17. package/codeCloud.js +2 -2
  18. package/codeComputers.js +9 -0
  19. package/codeFolders.js +116 -0
  20. package/codeHistory.js +76 -0
  21. package/codeLanguage.js +54 -0
  22. package/codeModes.js +2 -0
  23. package/codeProgress.js +54 -0
  24. package/codeSent.js +109 -0
  25. package/codeSubagents.js +107 -0
  26. package/codeTransport.js +46 -5
  27. package/connections.js +37 -20
  28. package/decrypt.html +69 -9
  29. package/deviceAttest.js +9 -3
  30. package/eraseFile.js +15 -0
  31. package/idb.js +19 -3
  32. package/idbSeal.js +5 -2
  33. package/inviteReceive.js +44 -0
  34. package/inviteSend.js +8 -2
  35. package/jobAgents.js +2 -2
  36. package/keptMerge.js +9 -2
  37. package/l1-worker-src.js +1 -1
  38. package/l1-worker.js +122 -43
  39. package/laneAssociation.js +78 -0
  40. package/laneConfig.js +4 -3
  41. package/laneLinkCore.js +9 -0
  42. package/ledgerView.js +30 -4
  43. package/manifest.json +112 -87
  44. package/memberChange.js +4 -2
  45. package/mirrorBatch.js +47 -0
  46. package/offlineBundle.js +21 -0
  47. package/opRouting.js +10 -0
  48. package/package.json +27 -2
  49. package/pdfOptions.js +13 -0
  50. package/pdfText.js +107 -0
  51. package/pdfjs.mjs +28 -0
  52. package/pdfjs.worker.mjs +28 -0
  53. package/protectedLocal.js +52 -13
  54. package/reactionHolders.js +86 -0
  55. package/removedMessage.js +1 -1
  56. package/roomEmbed.js +111 -0
  57. package/roomIntake.js +324 -0
  58. package/roomName.js +1 -1
  59. package/roomRoster.js +30 -7
  60. package/rosterCount.js +6 -3
  61. package/scheduleNext.js +60 -0
  62. package/sdkA2A.js +200 -42
  63. package/sdkAccount.js +88 -18
  64. package/sdkAccountDoc.js +13 -5
  65. package/sdkAccountSections.js +172 -23
  66. package/sdkAgui.js +33 -6
  67. package/sdkBackup.js +53 -11
  68. package/sdkBackupV2.js +15 -3
  69. package/sdkCloudDevice.js +20 -5
  70. package/sdkComputers.js +695 -65
  71. package/sdkDictation.js +115 -25
  72. package/sdkErase.js +12 -5
  73. package/sdkExports.js +19 -8
  74. package/sdkInvitations.js +4 -2
  75. package/sdkKeptAgent.js +19 -3
  76. package/sdkKeptIntake.js +100 -0
  77. package/sdkLaneLink.js +8 -9
  78. package/sdkPlan.js +4 -2
  79. package/sdkRekey.js +122 -22
  80. package/sdkReport.js +1 -1
  81. package/sdkSafeMedia.js +1 -1
  82. package/sdkSchedules.js +8 -1
  83. package/sdkSpeech.js +32 -2
  84. package/sdkTemporaryRooms.js +124 -0
  85. package/sdkTurn.js +12 -4
  86. package/sdkVault.js +66 -10
  87. package/sentinelRelease.js +1 -0
  88. package/sharedViews.js +34 -4
  89. package/siri.js +140 -9
  90. package/spaceClient.js +112 -17
  91. package/spaceEmailGate.js +2 -2
  92. package/spaceExport.js +50 -5
  93. package/spaceFork.js +15 -7
  94. package/spaceTemplates.js +99 -0
  95. package/speechOut.js +21 -5
  96. package/store.js +134 -27
  97. package/sw-notif-core.js +11 -8
  98. package/tapTrail.js +58 -0
  99. package/turnVerdict.js +1 -0
  100. package/usageReceipts.js +12 -5
  101. package/vault-core.js +568 -126
  102. package/vault-kit.mjs +3 -3
  103. package/vault-screens.js +30 -18
  104. package/vaultAtRest.js +38 -6
  105. package/vaultCoreLock.js +3 -1
  106. package/vaultCorePush.js +58 -7
  107. package/vaultKeep.js +9 -3
  108. package/vaultWorkerHost.js +32 -7
  109. package/witbitz-admin.d.ts +3 -0
  110. package/witbitz-admin.mjs +12 -11
  111. package/witbitz-sdk.d.ts +170 -43
  112. package/witbitz-sdk.js +833 -203
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) =>
@@ -785,6 +792,9 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
785
792
  // ONE DECODER for a sealed poll answer (the v3 per-entry wrapper, or a whole v1/v2 blob): pollSealed runs it on the
786
793
  // network's answer, and the L1 worker runs it on an answer the service worker PREFETCHED when the push arrived
787
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 } : {})
788
798
  const decodeSealed = async (room, mk, sinceCount, r) => {
789
799
  const withPartial = async (o) => {
790
800
  let out = o || {}
@@ -820,11 +830,26 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
820
830
  // box and answered "nothing new"). Say so, the way the server's own path does: 422 lifts the couldn't-unlock banner.
821
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 })
822
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
+ }
823
848
  // `done` — entries that have been through a COMPLETED turn (agent/spaceLedgerV3.mjs). Plaintext on the
824
849
  // wrapper, so it costs no key. A turn the agent answers with SILENCE appends nothing, so this
825
850
  // advancing is the ONLY event it produces, and it is what lets a peer stop showing "thinking".
826
851
  // `more`: another page follows from `version` (ledgerView.readAllPages; sync sweep, 2026-10-10)
827
- 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 } : {}) })
828
853
  }
829
854
  let all = null
830
855
  try { all = JSON.parse(await openAny(room, JSON.parse(r.sealed), mk)) } catch { all = null }
@@ -837,6 +862,53 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
837
862
  const from = Number.isInteger(sinceCount) && sinceCount > 0 ? Math.min(sinceCount, all.length) : 0
838
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 })
839
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
+ }
840
912
  const api = {
841
913
  _openAny: openAny, // internal: a box opened with the room's key or, after an in-place change, an earlier one (tests)
842
914
  /** Mint a Space from a config, register its PUBLIC record (commit + config) with the server, and return
@@ -975,8 +1047,11 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
975
1047
  if (identity && identity.googleIdToken && identity.sign && identity.sign.priv && identity.sign.pub) {
976
1048
  const ts = Date.now()
977
1049
  const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}`
978
- 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)
979
- 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 }
980
1055
  } else if (identity && identity.grant && identity.sign && identity.sign.priv) {
981
1056
  const ts = Date.now()
982
1057
  const id = `c:${ts}:${Math.random().toString(36).slice(2, 8)}` // client nonce → the signed core's id (anti-replay)
@@ -1004,14 +1079,20 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1004
1079
  // Seed the Space from a PUBLIC ChatGPT share link → continue a one-on-one chat together. The Lambda fetches +
1005
1080
  // parses it (SSRF-guarded) and seals the history into the ledger; the URL is public so this carries no secret.
1006
1081
  importChat: async (room, mk, chatgptUrl, billingToken) => post({ op: 'import', room, ...(await keyFields(room, 'import', mk)), chatgptUrl, ...(await authFor(room)) }, billingToken),
1007
- 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
1008
1085
  // MIRROR — append entries this device copied from a LINKED room (docs/spaces-private-lane.md) into THIS room's ledger,
1009
1086
  // no agent turn. Deduped by entry id server-side. Files/images ride along so the assistant reads them natively.
1010
1087
  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)) })
1088
+ const send = async batch => {
1089
+ const kf = await keyFields(room, 'mirror', mk)
1090
+ const ef = enclaveFor(room) ? await sealField(room, 'mirror:entries', JSON.stringify(batch), 'mirror') : { entries: batch }
1091
+ return post({ op: 'mirror', room, ...kf, ...ef, ...(await authFor(room)) })
1092
+ }
1093
+ const batch = entries || []
1094
+ const prepared = await stageMirrorAttachments(batch, send)
1095
+ return prepared.error || send(prepared.entries)
1015
1096
  },
1016
1097
  // CARRY — a verified room's MOVE: the SERVER copies the old room's history into this one (minted with forkedFrom = that
1017
1098
  // room), keeping each entry's verified mark as `carried` (agent/spaceService.mjs op 'carry'). One page per call → { carried,
@@ -1033,14 +1114,15 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1033
1114
  // answers `poll` with the whole DECRYPTED history, and that answer crosses the Lambda and the enclave's parent host in
1034
1115
  // the clear. Read it sealed and open it here. Every caller (the room loop, the unread sweep, lanes, mail, pins…) comes
1035
1116
  // through this one function, so none can send the readable read by accident. Same answer shape (pollSealed's contract).
1036
- 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 })
1037
1119
  // …AND A REGULAR ROOM IS READ SEALED TOO (the owner, 2026-11-06: "Do then regular rooms read sealed too"): `poll` sent the
1038
1120
  // room key about every 600 ms and the Lambda decrypted the whole history to answer it. The sealed read is opened here; the
1039
1121
  // key rides only the read that registers this device's CHANGE INBOX (the first of a session — inboxForPoll), because the
1040
1122
  // server follows the room for it only once that read proves the key (spaceHandler pollProvedKey). A verified room's sealed
1041
1123
  // read carries no key either: its server checks the sign-in against its sealed copy of the list (sealedRead). Older apps keep `poll`.
1042
1124
  // (a room re-keyed in place: pollSealed asks once more WITH the key when the boxes do not open — see there)
1043
- return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, proveKey: !!ci.changeInbox })
1125
+ return api.pollSealed(room, mk, sinceEtag, sinceCount, { ...ci, ...ed, proveKey: !!ci.changeInbox })
1044
1126
  },
1045
1127
 
1046
1128
  /** CONTENT-BLIND poll — the same contract as `poll`, but `mk` NEVER leaves this device. The server returns the
@@ -1053,7 +1135,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1053
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)
1054
1136
  // the key rides only as sealedRead says (proveKey: a regular room's read that registers the change inbox)
1055
1137
  const sent = { keyed: false }
1056
- 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 })
1057
1139
  const r = await withVerified(room, send) // + attach a client-release attestation for a verified room (learned lazily)
1058
1140
  // The IN-PROGRESS reply, opened here like everything else — the server passed it through sealed. It rides EVERY
1059
1141
  // response including the unchanged one, which is the whole point: while a reply is still being written the
@@ -1066,7 +1148,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1066
1148
  // this case (linkMembers.test.mjs caught it). HERE, not in poll(): the SDK and a vault read with pollSealed, and an
1067
1149
  // open confidential room's poll() came straight here — neither ever asked (sweep 11-07 #1, #2).
1068
1150
  if (out && out.status === 422 && out.reason === 'undecodable' && mk && !sent.keyed) {
1069
- 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)
1070
1152
  return decodeSealed(room, mk, sinceCount, r2)
1071
1153
  }
1072
1154
  return out
@@ -1075,7 +1157,11 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1075
1157
  // { v:3, boxes:[…] } wrapper), NOT opened here. sinceCount:0 ⇒ everything. Same gated-retry as pollSealed. The
1076
1158
  // downloaded file carries no plaintext — it is only readable with the room key, via the offline decryptor
1077
1159
  // (/decrypt.html). Returns { status, sealed, count, etag }.
1078
- 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 = {}) => {
1079
1165
  const archive = await readSealedArchive(sinceCount => withVerified(room, () => sealedRead(room, mk, 'pollsealed', { sinceCount })))
1080
1166
  if (archive?.status !== 200 || !archive.sealed) return archive
1081
1167
  const ledger = JSON.parse(archive.sealed)
@@ -1091,7 +1177,11 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1091
1177
  }
1092
1178
  if (previous?.length) ledger.keyHistory = await seal(JSON.stringify({ room, keys: previous }), { room: mk })
1093
1179
  }
1094
- 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 }
1095
1185
  },
1096
1186
  pending: async (room, mk) => post({ op: 'pending', room, ...(await keyFields(room, 'pending', mk)), ...(await authFor(room)) }),
1097
1187
  /** APPROVAL REMINDERS for Code (agent/approvalRemind.mjs): this device's push address, signed by the server, for the
@@ -1160,6 +1250,8 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1160
1250
  deviceVerify: async ({ platform, keyId, nonce, assertion, sig, integrity }) => post({ op: 'device-verify', device: { platform, keyId, nonce, ...(assertion ? { assertion } : {}), ...(sig ? { sig } : {}), ...(integrity ? { integrity } : {}) } }),
1161
1251
  // the ATTESTED BACKUP (agent/attestedBackup.mjs): op 'attested-chal' | 'attested-get' | 'attested-put', the fields in `attested`
1162
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 } : {}) }),
1163
1255
  // K_att (infra/cloud-computer/sentinel/attkey.mjs): `mode` chal | get — the standing Sentinel's challenge, then the secret sealed to
1164
1256
  // the device's one-time key (attested.epk), after the attestation it verifies itself. The Space Lambda only relays.
1165
1257
  attkeyOp: async (mode, attested, chal) => post({ op: 'attkey', ...(mode === 'chal' ? { mode: 'chal' } : {}), attested, ...(chal ? { chal } : {}) }),
@@ -1214,7 +1306,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1214
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)
1215
1307
  userWhoami: async (idToken) => post({ op: 'user', mode: 'whoami', idToken }),
1216
1308
  userClaim: async (username, idToken, { name, publish } = {}) => extrasCache.clear() || post({ op: 'user', mode: 'claim', username, idToken, ...(publish ? { publish: true, ...(name ? { name } : {}) } : {}) }),
1217
- 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
1218
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
1219
1311
  // The invite inbox: drop a sealed box into a recipient's mailbox; inboxFetch reads YOUR mailbox (openBox with boxPriv).
1220
1312
  drop: async (inbox, box) => post({ op: 'drop', inbox, box }),
@@ -1222,6 +1314,8 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1222
1314
  // "Which of my rooms changed since `since`?" — the change inbox, standard tier (docs/change-inbox.md). Keyless.
1223
1315
  changes: async (inbox, since = 0) => post({ op: 'changes', inbox, since }),
1224
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 } }),
1225
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
1226
1320
 
1227
1321
  // Shared WIDGET state (co-edited by members; the agent reads its `summary` on turns). SET with a `patch` (+ a short
@@ -1254,7 +1348,8 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1254
1348
  intakeReg: async (room, mk, ops) => post({ op: 'intakereg', room, ...(await keyFields(room, 'intakereg', mk)), ops: Array.isArray(ops) ? ops.slice(0, 50) : [] }),
1255
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)
1256
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)
1257
- 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)) }),
1258
1353
  intakeAck: async (room, mk, items) => post({ op: 'intakeack', room, ...(await keyFields(room, 'intakeack', mk)), ops: Array.isArray(items) ? items.slice(0, 50) : [] }),
1259
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)
1260
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)) }),
@@ -1389,7 +1484,7 @@ export function makeSpaceClient({ endpoint = DEFAULT_ENDPOINT, fetch: fetchImpl,
1389
1484
  const newCommit = await keyCommit(newMk)
1390
1485
  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
1486
  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)
1487
+ 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
1488
  const configSealed = JSON.stringify(await seal(JSON.stringify(next), { room: newMk }))
1394
1489
  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
1490
  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')
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
@@ -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 works toward a decision together; the facilitator notes where you agree and the question still open.', // no approval step: a template is a name + persona (side sweep: sdk-template-preview-promises-group-approval)
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, drafted in plain language once you converge.',
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' })
@@ -82,12 +83,27 @@ export function createTtsPlayer ({ getKey, checkKey = checkSpeechKey, fetchImpl
82
83
  const mine = ++session; ctrl = new AbortController(); const signal = ctrl.signal
83
84
  self.playing = true
84
85
  try {
85
- const k = await freshKey()
86
- let next = fetchChunk(chunks[0], k, signal)
86
+ let k = await freshKey()
87
+ if (session !== mine) return
88
+ // ⛔ A KEY'S CAP IS NOT THE END OF THE READING (side sweep: read-aloud-key-cap-restarts-long-reply): every chunk of one reading
89
+ // used one capped key; its 402 cleared the key and ended playback, and the next Play started again at chunk one — a reply
90
+ // longer than one key's allowance stopped at the same place every time. A 402 now takes a NEW key (op 'tts' — its own hourly
91
+ // limit bounds this) once, and the same chunk is asked again; a chunk asked with an older key just goes again on the new one.
92
+ let renewing = null
93
+ const fetchRenewing = async (text) => {
94
+ const used = k
95
+ try { return await fetchChunk(text, used, signal) } catch (e) {
96
+ if (!(e && e.code === 'http_402') || session !== mine) throw e
97
+ if (k === used) { renewing = renewing || freshKey().then((nk) => { k = nk; renewing = null; return nk }, (er) => { renewing = null; throw er }); await renewing }
98
+ if (session !== mine) throw Object.assign(new Error('stopped'), { code: 'stopped' })
99
+ return fetchChunk(text, k, signal)
100
+ }
101
+ }
102
+ let next = fetchRenewing(chunks[0])
87
103
  for (let i = 0; i < chunks.length; i++) {
88
104
  const blob = await next
89
105
  if (session !== mine) return
90
- next = i + 1 < chunks.length ? fetchChunk(chunks[i + 1], k, signal) : null // one ahead, while this one plays
106
+ next = i + 1 < chunks.length ? fetchRenewing(chunks[i + 1]) : null // one ahead, while this one plays
91
107
  if (next) next.catch(() => {}) // judged when awaited; never an unhandled rejection
92
108
  await playBlob(blob, signal)
93
109
  if (session !== mine) return