@witbitz/sdk 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/turnCerts.js ADDED
@@ -0,0 +1,254 @@
1
+ // turnCerts.js — verify every reply's TURN CERTIFICATE in an enclave room, on this device (docs/turn-certificates.md).
2
+ //
3
+ // Each certified reply carries `cert` (signed inside the enclave) and, once per room per enclave boot, `certDoc` (the
4
+ // Nitro attestation whose public_key is the signing key). A reply is VERIFIED when all of these hold:
5
+ // 1. its certDoc is a genuine Nitro attestation (AWS root, COSE signature), checked as of its own timestamp;
6
+ // 2. that document's public_key hashes to the cert's kid, and its PCR0/16/17 equal the cert's;
7
+ // 3. the build has a PASS verdict in the published audit log (/audit/turn-enclave.jsonl — what pin D gates repins on);
8
+ // 4. the ECDSA signature verifies over the canonical body, the body names THIS room and this entry, and its `text`
9
+ // is sha256 of the reply exactly as the ledger holds it.
10
+ // History older than the first certified reply is "before certificates" — never a failure. A reply AFTER a certified
11
+ // one with no certificate IS a failure: the enclave signs every reply, so a missing one means something else wrote it.
12
+ import { verifyAttestation, b64ToBytes, toHex } from './nitroVerify.js'
13
+
14
+ // Beside THIS module, on the Witbitz origin — also when the SDK imports it into a builder's page (served CORS-open).
15
+ const AUDIT_LOG = new URL('/audit/turn-enclave.jsonl', String(import.meta.url).startsWith('blob:') ? location.href : import.meta.url).href // a module run from a blob: (the vault's copy, plan step 8) resolves against the page // root-absolute: the log is live data at the site root, also for a versioned SDK copy under /sdk/<v>/
16
+ const enc = new TextEncoder()
17
+ const sha256Hex = async (s) => toHex(new Uint8Array(await crypto.subtle.digest('SHA-256', typeof s === 'string' ? enc.encode(s) : s)))
18
+
19
+ /** Byte-identical to agent/turnCert.mjs canonical(): object keys sorted at every depth. */
20
+ export function canonical(v) {
21
+ if (Array.isArray(v)) return '[' + v.map(canonical).join(',') + ']'
22
+ if (v && typeof v === 'object') return '{' + Object.keys(v).filter((k) => v[k] !== undefined).sort().map((k) => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}'
23
+ return JSON.stringify(v === undefined ? null : v)
24
+ }
25
+ // Repin 33/34 certificates recorded the receipt's model OBJECT as "[object Object]" (fixed in turnCert.mjs). The record
26
+ // is signed as it is, so it cannot be repaired — only read sensibly.
27
+ const modelName = (k) => (k && k.model && k.model !== '[object Object]' ? k.model : 'the model') + (k && k.provider ? ` on ${k.provider}` : '')
28
+ const certBody = (c) => { const { sig, ...rest } = c || {}; return rest }
29
+ // v2 (docs/rats-eat.md): the signature covers the JWT signing input, so the certificate IS a JWT EAT (RFC 9711).
30
+ const b64uText = (t) => { const u = new TextEncoder().encode(t); let s = ''; for (let i = 0; i < u.length; i++) s += String.fromCharCode(u[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
31
+ export const EAT_JWT_HEADER = b64uText(canonical({ alg: 'ES256', typ: 'JWT' }))
32
+ export const signingInput = (body) => EAT_JWT_HEADER + '.' + b64uText(canonical(body))
33
+ /** A v2 certificate as its standard JWT EAT — eat.js verifyEat(token, { key: <the certDoc's public_key> }). */
34
+ export const certToEat = (c) => (c && c.v === 2 && c.sig ? signingInput(certBody(c)) + '.' + c.sig : null)
35
+ const b64urlToBytes = (s) => b64ToBytes(String(s).replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((String(s).length + 3) % 4))
36
+
37
+ // The audit log, cached per fetch function. A build missing from it re-reads it (at most once a minute): a repin's
38
+ // verdict is published with the release, and a page open across that release must not call the new build unaudited.
39
+ const _verdicts = new WeakMap() // fetchImpl → { at, list: Promise<verdict[]> }
40
+ const REREAD_MS = 60_000
41
+ function readLog(fetchImpl) {
42
+ return (async () => {
43
+ const r = await fetchImpl(AUDIT_LOG, { cache: 'no-store' })
44
+ if (!r.ok) throw new Error('audit log http ' + r.status)
45
+ return (await r.text()).split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
46
+ })()
47
+ }
48
+ async function verdictFor(fetchImpl, pcrs) {
49
+ let c = _verdicts.get(fetchImpl)
50
+ if (!c) { c = { at: Date.now(), list: readLog(fetchImpl) }; _verdicts.set(fetchImpl, c) }
51
+ let list
52
+ try { list = await c.list } catch (e) { _verdicts.delete(fetchImpl); throw e }
53
+ let hit = passFor(list, pcrs)
54
+ if (!hit && Date.now() - c.at > REREAD_MS) {
55
+ const fresh = { at: Date.now(), list: readLog(fetchImpl) }
56
+ _verdicts.set(fetchImpl, fresh)
57
+ try { hit = passFor(await fresh.list, pcrs) } catch { _verdicts.delete(fetchImpl) }
58
+ }
59
+ return hit
60
+ }
61
+ function passFor(verdicts, pcrs) {
62
+ const p16 = String(pcrs && pcrs[16] || '').toLowerCase(), p17 = String(pcrs && pcrs[17] || '').toLowerCase()
63
+ return verdicts.find((v) => v.verdict === 'pass' && v.measurement && String(v.measurement.pcr16).toLowerCase() === p16 && String(v.measurement.pcr17).toLowerCase() === p17) || null
64
+ }
65
+
66
+ const _docs = new Map() // kid → Promise<{ key, pcrs, at } | { error }>
67
+ // An ERROR is not kept (state machines pass 7, T#7): one bad copy of a key's attestation (a damaged or forged doc in the history,
68
+ // a verify at a bad moment) failed every later reply signed by that key for the page's life, even once the genuine doc arrived.
69
+ async function docFor(kid, certDocB64, opts) {
70
+ if (!_docs.has(kid)) {
71
+ const p = (async () => {
72
+ try {
73
+ const doc = await verifyAttestation(b64ToBytes(certDocB64), { atDocTime: true, ...(opts.root ? { root: opts.root } : {}) })
74
+ if (!doc.publicKey) return { error: 'the attestation carries no signing key' }
75
+ if ((await sha256Hex(doc.publicKey)).slice(0, 16) !== kid) return { error: 'the attestation is for a different key' }
76
+ const key = await crypto.subtle.importKey('spki', doc.publicKey, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])
77
+ return { key, pcrs: doc.pcrs, at: doc.timestamp }
78
+ } catch (e) { return { error: 'the attestation does not verify: ' + String((e && e.message) || e).slice(0, 120) } }
79
+ })()
80
+ _docs.set(kid, p)
81
+ p.then((d) => { if (d && d.error && _docs.get(kid) === p) _docs.delete(kid) })
82
+ }
83
+ return _docs.get(kid)
84
+ }
85
+
86
+ /** Verify one certified entry. → { ok: true, build } | { ok: false, reason } */
87
+ export async function verifyEntryCert(entry, { room, docs, fetchImpl = fetch, root } = {}) {
88
+ const c = entry && entry.cert
89
+ if (!c || (c.v !== 1 && c.v !== 2) || !c.kid || !c.sig) return { ok: false, reason: 'no certificate' }
90
+ if (c.room !== room) return { ok: false, reason: 'the certificate is for another room' }
91
+ if (c.id !== entry.id || c.ts !== entry.ts) return { ok: false, reason: 'the certificate is for another message' }
92
+ const docB64 = docs.get(c.kid)
93
+ // NOT a failure: the proof rides only the first reply after each enclave boot, and this device keeps the room's last 200
94
+ // messages — it may simply not hold that reply. Soft (never cached), and the page reads the older history for it.
95
+ if (!docB64) return { ok: false, reason: 'the attestation for this key is not on this device yet', soft: true, missingDoc: true }
96
+ const d = await docFor(c.kid, docB64, { root })
97
+ if (d.error) return { ok: false, reason: d.error }
98
+ for (const i of [0, 16, 17]) if (String(d.pcrs[i] || '').toLowerCase() !== String((c.pcrs || {})[i] || '').toLowerCase()) return { ok: false, reason: `PCR${i} differs from the attested build` }
99
+ let ok = false
100
+ try { ok = await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, d.key, b64urlToBytes(c.sig), enc.encode(c.v === 2 ? signingInput(certBody(c)) : canonical(certBody(c)))) } catch { ok = false }
101
+ if (!ok) return { ok: false, reason: 'the signature does not verify' }
102
+ if (c.text !== await sha256Hex(String(entry.text || ''))) return { ok: false, reason: 'the reply was changed after it was signed' }
103
+ let verdict = null
104
+ try { verdict = await verdictFor(fetchImpl, c.pcrs) } catch { return { ok: false, reason: 'the audit log could not be read', soft: true } }
105
+ if (!verdict) return { ok: false, reason: 'this build has no passing audit verdict', soft: true } // soft: re-checked, never cached as final
106
+ return { ok: true, build: { pcr16: c.pcrs[16], pcr17: c.pcrs[17], audit: String(verdict.source && verdict.source.commit || '').slice(0, 8) } }
107
+ }
108
+
109
+ /** A copy the SERVER vouches for (pass 9, X#2): a lane's `sh:` line, or one it stamped `carried`. Not every mirrored entry. */
110
+ const vouchedCopy = (e) => !!e && e.source === 'shared' && (String(e.id == null ? '' : e.id).startsWith('sh:') || !!(e.carried && typeof e.carried === 'object'))
111
+
112
+ /** Verify a room's whole history. → { verified, failed: [{ id, reason }], before, copies, builds, calls, tools } */
113
+ export async function verifyRoom(entries, { room, fetchImpl = fetch, root, cache = new Map(), docs: known } = {}) {
114
+ const docs = new Map(known || []) // proofs found in older history this device read on purpose (setCertDocFetcher)
115
+ for (const e of entries) if (e && e.certDoc && e.cert && e.cert.kid && !docs.has(e.cert.kid)) docs.set(e.cert.kid, e.certDoc)
116
+ const out = { verified: 0, failed: [], unchecked: 0, missing: new Set(), before: 0, copies: 0, builds: new Map(), calls: new Map(), tools: new Map() }
117
+ let started = false
118
+ for (const e of entries) {
119
+ if (!e || !e.self || e.sys) continue // the enclave certifies the ASSISTANT's replies
120
+ // ⛔ A COPY FROM THE SPACE IS NOT A REPLY OF THIS ROOM (the owner, 2026-11-11: "⚠ 2 UNVERIFIED" on a confidential Space's
121
+ // private assistant). A lane's mirror copies the Space's messages in (agent/spaceService.mjs sets `source: 'shared'`, and keeps
122
+ // `self` on the Space's assistant's replies so they draw as Markdown). This room's enclave turn never signed them, so each
123
+ // one after the lane's first certified reply read "no certificate". Counted as copies, never as failures.
124
+ // ⚑ WIDER THAN roomName.js isLaneCopy BY ONE CASE (sync sweep 2026-11-12, Unclear): a copy CARRIED into a lane that was moved
125
+ // (`carried`; isLaneCopy says no, for the render) is still not this room's reply — under the narrower rule a moved lane's
126
+ // carried copies, which sit after its carried certified replies, would read "no certificate" again.
127
+ // ⛔ BUT NOT "EVERYTHING THAT CAME THROUGH op mirror" (state machines pass 9, X#2). `source: 'shared'` is stamped by the server
128
+ // on every mirrored text entry, with the sender's `self` kept — so any member of a confidential Space could put an
129
+ // "assistant" reply into the SHARED room through `mirror` and it was exempt here: drawn as the assistant's, never flagged.
130
+ // The certificate is the only thing that tells the enclave's reply from a key holder's text. A copy is what the SERVER
131
+ // vouches for: an `sh:` line of a lane (drawn as a copy), or one it stamped `carried` (never taken from a client —
132
+ // agent/spaceService.mjs carriedMarks). An imported chat's reply added after the room's first certified one is, truly,
133
+ // not certified.
134
+ if (!e.cert && vouchedCopy(e)) { out.copies++; continue }
135
+ if (!e.cert) { if (started) out.failed.push({ id: e.id, reason: 'no certificate' }); else out.before++; continue }
136
+ started = true
137
+ const key = e.id + '|' + e.cert.sig
138
+ let v = cache.get(key)
139
+ if (!v) { v = await verifyEntryCert(e, { room, docs, fetchImpl, root }); if (!v.soft) cache.set(key, v) }
140
+ if (!v.ok && v.missingDoc) { out.unchecked++; out.missing.add(e.cert.kid); continue } // not on this device yet — not a failure
141
+ if (!v.ok) { out.failed.push({ id: e.id, reason: v.reason }); continue }
142
+ out.verified++
143
+ const b = out.builds.get(v.build.pcr16) || { ...v.build, replies: 0 }
144
+ b.replies++; out.builds.set(v.build.pcr16, b)
145
+ for (const k of e.cert.calls || []) { const n = `${modelName(k)} · ${k.policy || k.tier || '?'}`; out.calls.set(n, (out.calls.get(n) || 0) + 1) }
146
+ for (const t of e.cert.tools || []) {
147
+ for (const r of t.ran || []) {
148
+ const where = r.in === 'tinfoil' ? `Tinfoil ${r.repo ? r.repo.split('/').pop() : r.host}${r.release ? ' ' + r.release : ''}` : r.in === 'nitro-tools' ? 'Witbitz tools enclave' : 'this enclave'
149
+ const n = `${t.name} → ${where}`; out.tools.set(n, (out.tools.get(n) || 0) + 1)
150
+ }
151
+ }
152
+ }
153
+ return out
154
+ }
155
+
156
+ // ── the page: entries noted as they render, the room re-verified (debounced), the badge + sheet fed from the result ──
157
+ const _rooms = new Map() // room → { entries: Map(id → entry), cache, result, timer }
158
+ let _onChange = () => {}
159
+ let _opts = {} // { root, fetchImpl } — tests only (a synthetic Nitro chain); the page uses AWS's root and fetch
160
+ export const configureCerts = (o = {}) => { _opts = { ...o } }
161
+ export const onCertChange = (fn) => { _onChange = typeof fn === 'function' ? fn : () => {} }
162
+ // The room's OLDER history, read once when a proof is not on this device (the owner, 2026-10-11: "26 unverified" in Help —
163
+ // the proofs were in replies past the 200 messages a device keeps). `fn(room)` → that room's entries. The page sets it.
164
+ let _fetchHistory = null
165
+ export const setCertDocFetcher = (fn) => { _fetchHistory = typeof fn === 'function' ? fn : null }
166
+ function verifySoon(room, r) {
167
+ clearTimeout(r.timer)
168
+ r.timer = setTimeout(async () => {
169
+ const list = [...r.entries.values()].sort((a, b) => (a.ts || 0) - (b.ts || 0))
170
+ try { r.result = await verifyRoom(list, { room, cache: r.cache, docs: r.docs, ..._opts }) } catch { /* a verifier fault is not a verdict */ }
171
+ try { _onChange(room) } catch { /* */ }
172
+ if (r.result && r.result.missing.size && _fetchHistory && !r.fetched) { // look the missing proofs up, once per room per page
173
+ r.fetched = true
174
+ try {
175
+ for (const e of (await _fetchHistory(room)) || []) if (e && e.certDoc && e.cert && e.cert.kid && !r.docs.has(e.cert.kid)) r.docs.set(e.cert.kid, e.certDoc)
176
+ } catch { /* stays unchecked — still not a failure */ }
177
+ verifySoon(room, r)
178
+ }
179
+ }, 300)
180
+ }
181
+ export function noteEntry(room, e) {
182
+ if (!room || !e || e.id == null || !(e.cert || e.self)) return
183
+ let r = _rooms.get(room)
184
+ if (!r) { r = { entries: new Map(), cache: new Map(), docs: new Map(), fetched: false, result: null, timer: 0 }; _rooms.set(room, r) }
185
+ r.entries.set(String(e.id), e)
186
+ verifySoon(room, r)
187
+ }
188
+ export const roomCertResult = (room) => (_rooms.get(room) || {}).result || null
189
+
190
+ /** The badge's suffix: '' when every reply verified (the owner, 2026-10-14: "don't show the count next to the enclave" —
191
+ * the count is in the enclave sheet), or '⚠ N UNVERIFIED' with `warn` — a failure is a warning, and it stays. */
192
+ export function certBadge(room) {
193
+ const r = roomCertResult(room)
194
+ if (!r || !r.failed.length) return { text: '', warn: false }
195
+ return { text: `⚠ ${r.failed.length} UNVERIFIED`, warn: true }
196
+ }
197
+
198
+ /** The Certificates section of the enclave sheet. */
199
+ export function renderCertSection(el, room) {
200
+ if (!el) return
201
+ const r = roomCertResult(room)
202
+ el.textContent = ''
203
+ const line = (t, cls) => { const d = document.createElement('div'); d.textContent = t; if (cls) d.className = cls; el.appendChild(d); return d }
204
+ line('Turn certificates', 'tc-h')
205
+ // a private lane's copies of the Space's replies: said, so nobody wonders why they carry no certificate here
206
+ const copies = () => { if (r && r.copies) line(`${r.copies} ${r.copies === 1 ? 'reply' : 'replies'} copied from the Space ${r.copies === 1 ? 'is' : 'are'} not this room’s — no certificate here.`) }
207
+ if (r && !r.verified && !r.failed.length && r.unchecked) { line(`${r.unchecked} ${r.unchecked === 1 ? 'reply' : 'replies'} not checked yet — their proof is in older messages; looking it up.`); copies(); return }
208
+ if (!r || (!r.verified && !r.failed.length)) { line(r && r.before ? `No certified replies yet (${r.before} from before certificates).` : 'No certified replies yet.'); copies(); return }
209
+ line(`${r.verified} ${r.verified === 1 ? 'reply' : 'replies'} verified on this device${r.failed.length ? `, ${r.failed.length} failed` : ''}${r.unchecked ? `, ${r.unchecked} not checked yet (their proof is in older messages)` : ''}${r.before ? ` · ${r.before} from before certificates` : ''}.`)
210
+ for (const b of r.builds.values()) line(`Build ${String(b.pcr16).slice(0, 12)}… · audited PASS @ ${b.audit} · ${b.replies} ${b.replies === 1 ? 'reply' : 'replies'}`)
211
+ for (const [n, c] of r.calls) line(`Model: ${n} ×${c}`)
212
+ for (const [n, c] of r.tools) line(`Tool: ${n} ×${c}`)
213
+ for (const f of r.failed.slice(0, 5)) line(`⚠ ${f.reason}`, 'tc-bad')
214
+ copies()
215
+ }
216
+
217
+ /** The long-press sheet's lines for one reply: its own verdict, what produced it, what it called. */
218
+ export function describeEntryCert(room, e) {
219
+ if (!e || !e.self) return []
220
+ const c = e.cert
221
+ if (!c && vouchedCopy(e)) return ['↗ A copy from the Space — not a reply of this room, so it carries no turn certificate here.']
222
+ if (!c) {
223
+ const r = roomCertResult(room)
224
+ return r && r.failed.some((f) => f.id === e.id) ? ['⚠ No turn certificate — every reply after the first certified one should carry one.'] : []
225
+ }
226
+ const v = ((_rooms.get(room) || {}).cache || new Map()).get(e.id + '|' + c.sig)
227
+ const lines = [!v ? '🔏 Turn certificate — checking…' : v.ok
228
+ ? `🔏 Turn certificate verified on this device: enclave build ${String(c.pcrs && c.pcrs[16]).slice(0, 12)}…, audited PASS @ ${v.build.audit}.`
229
+ : `⚠ Turn certificate NOT verified: ${v.reason}.`]
230
+ return lines.concat(certCallLines(c))
231
+ }
232
+
233
+ /** What a certified reply called, GROUPED so it fits the long-press menu (2026-10-05, the owner: a turn with 5 model calls
234
+ * and 23 tool calls drew 29 lines and pushed Reply/Copy off the screen). One line per model+route with its call count
235
+ * (a single call keeps its receipt id), one line per place the tools ran with each tool's count in first-seen order,
236
+ * and a failed tool on a line of its own. The facts are the certificate's; only the layout changed. */
237
+ export function certCallLines(c) {
238
+ const out = []
239
+ const models = new Map() // label → { n, jti }
240
+ for (const k of (c && c.calls) || []) {
241
+ const label = `${modelName(k)} via ${k.policy || k.tier || 'an attested upstream'}`
242
+ const m = models.get(label) || { n: 0, jti: k.jti }; m.n++; models.set(label, m)
243
+ }
244
+ for (const [label, m] of models) out.push(`Model: ${label}` + (m.n > 1 ? ` — ${m.n} calls` : ` (receipt ${String(m.jti || '').slice(0, 12)}…)`))
245
+ const places = new Map() // where → Map(tool name → count)
246
+ const failed = []
247
+ for (const t of (c && c.tools) || []) {
248
+ const where = (t.ran || []).map((r) => (r.in === 'tinfoil' ? `Tinfoil ${r.repo || r.host}${r.release ? ' ' + r.release : ''}` : r.in === 'nitro-tools' ? 'the Witbitz tools enclave' : 'this enclave')).join(', ') || 'this enclave'
249
+ if (t.error) { failed.push(`Tool failed: ${t.name} → ${where}`); continue }
250
+ const tools = places.get(where) || new Map(); tools.set(t.name, (tools.get(t.name) || 0) + 1); places.set(where, tools)
251
+ }
252
+ for (const [where, tools] of places) out.push(`Tools → ${where}: ` + [...tools].map(([n, k]) => (k > 1 ? `${n} ×${k}` : n)).join(', '))
253
+ return out.concat(failed)
254
+ }
package/turnFeed.js ADDED
@@ -0,0 +1,58 @@
1
+ // turnFeed.js — what a room says about a running turn, read ONE way for the Spaces app and the SDK (docs/sdk-convergence.md,
2
+ // phase 3). Both used to read it separately and drifted: the app hid the status on a stream's `end` frame and on a poll
3
+ // that carried none; the SDK did neither, so an Auto "Deciding whether to reply…" that ended in silence stayed on a
4
+ // builder's screen. Every rule here is the SERVER's word, never a guess:
5
+ // • text — the reply so far. A sequence number only moves forward (an out-of-order poll never rewinds what you read).
6
+ // • status — what the turn is doing before its first word ({ phase } | { tool }, + since).
7
+ // • turn over — a fresh poll with neither (the server keeps a running turn's status in every poll), or a stream `end`.
8
+ // It decides; the page draws. Each call returns only what changed: { text?: string|null, status?: object|null, refetch? }
9
+ // (a key that is absent means "unchanged"; null means "none any more").
10
+ import { isEndFrame } from './streamHint.js'
11
+
12
+ export const normStep = (s) => (s && typeof s === 'object')
13
+ ? { ...(s.tool ? { tool: String(s.tool) } : { phase: s.phase || 'thinking' }), ...(Number.isFinite(s.since) ? { since: s.since } : {}) }
14
+ : null
15
+
16
+ export function makeTurnFeed () {
17
+ let seq = -1
18
+ const forward = (q) => { if (!Number.isInteger(q)) return true; if (q < seq) return false; seq = q; return true }
19
+ // A REPLY ALREADY STORED IS NEVER STREAMED AGAIN (the owner, 2026-10-14, a recording: a long answer landed whole and its
20
+ // late stream frames, read as new after the landing reset the order, replayed it in a second bubble — 4ea26b29 fixed the
21
+ // app; the SDK did the same: sync sweep 2026-10-15 #16). Words the stored answer already contains are not a reply in
22
+ // progress. `landed(text)` names it; `sent()` (a new turn, another room) forgets it.
23
+ let stored = ''
24
+ const already = (t) => !!stored && stored.startsWith(String(t).trim().slice(0, 4000))
25
+ return {
26
+ /** A poll answer (spaceClient's shape: partialText / partialStatus / partialSeq / prefetched). */
27
+ poll (r) {
28
+ if (!r || r.status !== 200) return {}
29
+ const text = typeof r.partialText === 'string' ? r.partialText : ''
30
+ if (text) return already(text) ? {} : forward(r.partialSeq) ? { text } : {}
31
+ seq = -1 // no live text: the next turn numbers from the start again
32
+ if (r.partialStatus) {
33
+ // A status is THERE (a turn is running) but may not have opened (spaceClient passes an unreadable one through as
34
+ // the raw string): then it says nothing new — the line keeps its last words, never "the turn is over".
35
+ const st = normStep(r.partialStatus)
36
+ return st ? { text: null, status: st } : { text: null }
37
+ }
38
+ // A push-time prefetch is not a fresh answer — it carries no status by construction, so it says nothing about the turn.
39
+ return r.prefetched ? { text: null } : { text: null, status: null }
40
+ },
41
+ /** A room-stream frame (roomStreamClient): partial / poll / end. */
42
+ stream (ev) {
43
+ if (!ev) return {}
44
+ if (isEndFrame(ev)) return { status: null, end: true } // "no reply in progress" — the finished entry comes by poll
45
+ if (ev.k === 'poll') return { refetch: true }
46
+ if (ev.k !== 'partial') return {}
47
+ if (ev.text) return already(ev.text) ? {} : forward(ev.pseq) ? { text: ev.text } : {}
48
+ if (ev.step) return { status: normStep(ev.step) }
49
+ return {}
50
+ },
51
+ /** The page moved to another room, or the live bubble was superseded by the finished entry. */
52
+ reset () { seq = -1 },
53
+ /** A stored answer landed (a long one: its late frames are dropped). */
54
+ landed (text) { const t = String(text || '').trim(); if (t.length > 40) stored = t },
55
+ /** A new turn was sent, or the page moved to another room: nothing is held back any more. */
56
+ sent () { stored = '' },
57
+ }
58
+ }
package/turnVerdict.js ADDED
@@ -0,0 +1,37 @@
1
+ // turnVerdict.js — what a turn's answer MEANS, one reading for the Spaces app's send and the SDK's (docs/sdk-convergence.md,
2
+ // phase 4c). Each side still decides what to SHOW.
3
+ // ok · silent (posted; the assistant stays quiet) · busy (a reply is running: HOLD the message and resend — the server
4
+ // stores nothing new meanwhile, docs/spaces-turn-queue.md) · warming (the enclave is starting) · stale_key (the enclave
5
+ // cannot open the key we sealed to it) · not_admitted (401/403: the gate) · refused (another 4xx) · pending (a 5xx with
6
+ // none of our codes: the API front door cut the request at ~30 s while the server finishes — the reply still comes;
7
+ // never resend) · failed (a 5xx we raised) · no_answer
8
+ export const CLOCK_REASON = 'This device’s clock is more than a minute off, so the confidential Space refused the request — set the clock to the right time (automatic), then try again.'
9
+ export const CONTINUATION_WINDOW_MS = 10 * 60 * 1000
10
+ export const QUEUE_RETRY_MS = 1500
11
+ export const QUEUE_MAX_TRIES = 640 // ~16 min of holding: longer than the longest turn (13 min since 2026-11-18; was 120 ≈ 180 s)
12
+
13
+ export function turnVerdict (r) {
14
+ if (!r) return { kind: 'no_answer' }
15
+ // status 0 = the request got NO answer (OHTTP returns one rather than throwing; the SDK's transport failure): it may have
16
+ // been posted, so it is never a refusal to resend (sync sweep, 2026-10-10)
17
+ if (!r.status) return { kind: 'no_answer', ...(r.error ? { code: String(r.error) } : {}) }
18
+ const v = (kind) => ({ kind, ...(r.error ? { code: String(r.error) } : {}), ...(r.reason ? { reason: String(r.reason) } : {}) })
19
+ if (r.status === 200 && r.ok === false && r.error) return v('refused') // a refusal that came back as a 200 is not a send (sweep 11-06 #1)
20
+ if (r.status === 200) return { kind: r.busy ? 'busy' : r.silent ? 'silent' : 'ok' }
21
+ if (r.error === 'enclave_warming' || r.warming) return v('warming')
22
+ if (r.error === 'enclave_policy_unknown') return v('warming') // nothing was sent: the enclave could not be checked yet — wait and send again, as for a warming one (sweep 11-06 #8)
23
+ if (r.status === 401 && r.error === 'bad_mkseal') return v('stale_key')
24
+ // a request ENVELOPE sealed to an enclave since replaced (pollVerdict.js, 2026-11-09): nothing ran, so re-attest and send again
25
+ if (r.status === 400 && r.error === 'bad_envelope') return v('stale_key')
26
+ // ⛔ A DEVICE CLOCK OFF BY MORE THAN A MINUTE (state machines pass 7, T#2): the enclave refuses an envelope outside its window
27
+ // (agent/mkUnseal.mjs DEFAULT_SKEW_MS) and every send said only "Couldn't send that. Try again." — say what to fix.
28
+ if (r.error === 'envelope_stale') return { kind: 'refused', code: 'envelope_stale', reason: CLOCK_REASON }
29
+ if (r.status === 401 || r.status === 403) return v('not_admitted')
30
+ if (r.status >= 400 && r.status < 500) return v('refused')
31
+ // 'refused' with no sentence on a 5xx is reqEnvelope.openAnswer's own default for a BARE reply (no server sets it): an older opener
32
+ // — the hosted app's vault worker follows Official — still tags a gateway cut-off (30 s, a long confidential turn) that way.
33
+ // The Lambda runs on and stores the reply: pending (the owner, 2026-11-11: "Not sent" on a turn that was answering it)
34
+ if (r.status >= 500 && r.error === 'refused' && !r.reason) return v('pending')
35
+ if (r.status >= 500) return v(r.error ? 'failed' : 'pending')
36
+ return v('refused')
37
+ }
@@ -0,0 +1,176 @@
1
+ // usageReceipts.js — the DEVICE half of usage receipts (docs/usage-receipts.md). The account's USAGE KEY (a P-256 box pair
2
+ // + a secret) rides the account like the invite key; a turn this device sends carries `receipt: { drop, pub }`, where the
3
+ // drop is HMAC(secret, room) — a different opaque id in every room, so the server cannot link this account's rooms. The
4
+ // collector reads each room's receipts, opens them, and folds them into the SIDECAR: one doc per month in the account's
5
+ // index room, `usage-YYYY-MM`, holding every receipt by id (so two devices folding the same receipt count it once).
6
+ // Settings → Usage reads only the sidecar.
7
+ import { genRecipientKey, openBox } from './e2ee.js'
8
+
9
+ export const USAGE_KEY = 'space:usagekey'
10
+ export const PAYERS = ['you', 'admin', 'app', 'witbitz']
11
+ const enc = new TextEncoder()
12
+ const b64u = (u8) => { let x = ''; for (const b of u8) x += String.fromCharCode(b); return btoa(x).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') }
13
+ const ub64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0))
14
+ const B43 = /^[A-Za-z0-9_-]{43}$/
15
+
16
+ /** A well-formed usage key, or null. { id, pub:{x,y}, priv:jwk, secret } — `id` picks one key when two devices made one. */
17
+ export function normUsageKey (k) {
18
+ if (!k || typeof k !== 'object' || typeof k.id !== 'string' || !k.id || !k.pub || !B43.test(String(k.pub.x)) || !B43.test(String(k.pub.y)) || !k.priv || typeof k.priv.d !== 'string' || !B43.test(String(k.secret || ''))) return null
19
+ return { id: k.id.slice(0, 32), pub: { x: k.pub.x, y: k.pub.y }, priv: { kty: 'EC', crv: 'P-256', x: k.priv.x, y: k.priv.y, d: k.priv.d, ext: true }, secret: k.secret }
20
+ }
21
+ export const loadUsageKey = (ls = globalThis.localStorage) => { try { return normUsageKey(JSON.parse(ls.getItem(USAGE_KEY) || 'null')) } catch { return null } }
22
+ export const saveUsageKey = (k, ls = globalThis.localStorage) => { const n = normUsageKey(k); if (n) { try { ls.setItem(USAGE_KEY, JSON.stringify(n)) } catch { /* private mode */ } } return n }
23
+ /** Two devices that each made a key converge on one: the smaller id wins, the same choice on both sides. */
24
+ export const pickUsageKey = (a, b) => { const x = normUsageKey(a), y = normUsageKey(b); return !x ? y : !y ? x : (x.id <= y.id ? x : y) }
25
+
26
+ export const USAGE_KEYS_OLD = 'space:usagekey:old'
27
+ export const loadOldUsageKeys = (ls = globalThis.localStorage) => { try { const a = JSON.parse(ls.getItem(USAGE_KEYS_OLD) || '[]'); return Array.isArray(a) ? a.map(normUsageKey).filter(Boolean) : [] } catch { return [] } }
28
+ /**
29
+ * Converge this device's usage key with the one the account's index carries. The smaller id wins on every device; the
30
+ * LOSER is kept as a retired key (receipts already sealed to it, at drops derived from it, are still collected — a key
31
+ * that lost a race must not lose its receipts). → { key, old } after saving both.
32
+ */
33
+ export function mergeUsageKeys (remote, { ls = globalThis.localStorage } = {}) {
34
+ const local = loadUsageKey(ls), rk = normUsageKey(remote && remote.usageKey)
35
+ const key = pickUsageKey(local, rk)
36
+ const all = [...loadOldUsageKeys(ls), ...((remote && Array.isArray(remote.usageKeysOld)) ? remote.usageKeysOld.map(normUsageKey).filter(Boolean) : []), local, rk].filter(Boolean)
37
+ const seen = new Set(key ? [key.id] : []), old = []
38
+ for (const k of all) if (!seen.has(k.id)) { seen.add(k.id); old.push(k) }
39
+ const keep = old.slice(-4)
40
+ if (key) saveUsageKey(key, ls)
41
+ try { ls.setItem(USAGE_KEYS_OLD, JSON.stringify(keep)) } catch { /* private mode */ }
42
+ return { key, old: keep }
43
+ }
44
+
45
+ export async function newUsageKey () {
46
+ const kp = await genRecipientKey()
47
+ return normUsageKey({ id: b64u(crypto.getRandomValues(new Uint8Array(12))), pub: { x: kp.publicJwk.x, y: kp.publicJwk.y }, priv: kp.privateJwk, secret: b64u(crypto.getRandomValues(new Uint8Array(32))) })
48
+ }
49
+
50
+ /** This account's drop in `room`: HMAC-SHA256(secret, room). */
51
+ export async function dropFor (key, room) {
52
+ const k = await crypto.subtle.importKey('raw', ub64u(key.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
53
+ return b64u(new Uint8Array(await crypto.subtle.sign('HMAC', k, enc.encode('witbitz-usage-drop:' + room))))
54
+ }
55
+ /** The receipt address a turn in `room` carries. */
56
+ export async function receiptFor (key, room) { return key ? { drop: await dropFor(key, room), pub: { ...key.pub } } : null }
57
+
58
+ // ── the sidecar: `usage-YYYY-MM` = { v:1, r: { <receipt id>: [day, payer, costMicros, in, out] } } ──
59
+ export const monthOf = (ts) => { const d = new Date(ts); return d.getUTCFullYear() + '-' + String(d.getUTCMonth() + 1).padStart(2, '0') }
60
+ export const docNameFor = (month) => 'usage-' + month
61
+ const row = (b) => [new Date(b.ts).getUTCDate(), Math.max(0, PAYERS.indexOf(b.payer)), Math.max(0, Math.round(Number(b.costMicros) || 0)), Math.max(0, Math.round(Number(b.in) || 0)), Math.max(0, Math.round(Number(b.out) || 0))]
62
+
63
+ /** Merge receipts into a month doc (idempotent by receipt id). */
64
+ export function foldInto (doc, bodies) {
65
+ const r = { ...((doc && doc.r) || {}) }
66
+ for (const b of bodies) if (b && typeof b.id === 'string' && Number.isFinite(b.ts)) r[b.id] = row(b)
67
+ return { v: 1, r }
68
+ }
69
+ /** A month doc → totals: costMicros overall and by payer, replies, tokens, and per day. */
70
+ export function usageTotals (doc) {
71
+ const t = { costMicros: 0, replies: 0, in: 0, out: 0, byPayer: Object.fromEntries(PAYERS.map((p) => [p, 0])), byDay: {} }
72
+ for (const v of Object.values((doc && doc.r) || {})) {
73
+ if (!Array.isArray(v)) continue
74
+ const [day, pi, cost, i, o] = v
75
+ const payer = PAYERS[pi] || 'witbitz'
76
+ t.costMicros += cost; t.replies++; t.in += i; t.out += o; t.byPayer[payer] += cost
77
+ t.byDay[day] = (t.byDay[day] || 0) + cost
78
+ }
79
+ return t
80
+ }
81
+
82
+ export const HOLD_MS = 30 * 86400000 // receipts stay in their room this long after folding — the sidecar can be rebuilt from them
83
+ /** This device's read positions (device-local, safe to lose: re-reading is idempotent). `${keyId}|${room}` →
84
+ * { pos: next absolute position to read, pend: [[pos, ts], …] folded but not yet cleared }. */
85
+ export function cursorStore (ls = globalThis.localStorage, KEY = 'space:usagecur') {
86
+ const all = () => { try { return JSON.parse(ls.getItem(KEY) || '{}') || {} } catch { return {} } }
87
+ return {
88
+ get: (k) => { const c = all()[k]; return c && Number.isInteger(c.pos) ? { pos: c.pos, pend: Array.isArray(c.pend) ? c.pend : [] } : null },
89
+ set: (k, v) => { try { const a = all(); a[k] = v; ls.setItem(KEY, JSON.stringify(a)) } catch { /* private mode: we re-read next time */ } },
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Collect: for each room, read this account's receipts from where this device stopped, open them, fold them into the
95
+ * month docs, write, READ BACK, and move on only once the read-back shows every receipt. Receipts are CLEARED from the
96
+ * room only HOLD_MS after they were sent, so the sidecar can be rebuilt from them for a month.
97
+ * deps: { key, rooms, read(room, drop, since), ack(room, drop, upTo), readDoc(name) → doc | null when absent, THROWS when
98
+ * unknown; writeDoc(name, doc), cursor (cursorStore()), now } → { folded, rooms, cleared }
99
+ */
100
+ const READS_AT_ONCE = 8
101
+ // `pace` (optional, MUTABLE — read before every read): { atOnce, gapMs }. A run in the background reads a few at a time with a gap
102
+ // (e2e 2026-11-24: a fresh restore's first run read 400 Spaces × 5 usage keys, 8 at a time, and with the rest of the restore met the
103
+ // API route's shared limit — 429s, and a Space's first read held back); Your usage's open raises it to READS_AT_ONCE, no gap, even
104
+ // for a run already going.
105
+ export const PACE_FAST = Object.freeze({ atOnce: READS_AT_ONCE, gapMs: 0 })
106
+
107
+ export async function collectUsage ({ key, rooms, read, ack, readDoc, writeDoc, cursor = cursorStore(), now = Date.now(), holdMs = HOLD_MS, pace = PACE_FAST }) {
108
+ if (!key || !Array.isArray(rooms)) return { folded: 0, rooms: 0, cleared: 0 }
109
+ const perRoom = [] // { room, drop, ck, c, end, items:[{id,pos,ts}] }
110
+ const byMonth = new Map()
111
+ // The reads go out CONCURRENTLY (READS_AT_ONCE at a time): one at a time, ~200 Spaces kept "Your usage" on "Updating…"
112
+ // for tens of seconds (the owner, 2026-10-09: "Your usage take too long. Why?"). They are then handled in the rooms'
113
+ // order, exactly as before.
114
+ const fetched = new Array(rooms.length)
115
+ let next = 0
116
+ const nap = (ms) => new Promise((res) => setTimeout(res, ms))
117
+ const worker = async (w) => {
118
+ while (next < rooms.length) {
119
+ if (w >= Math.max(1, Number(pace.atOnce) || 1)) { await nap(200); continue } // a worker the pace does not use waits for it to rise
120
+ const i = next++, room = rooms[i]
121
+ const drop = await dropFor(key, room), ck = key.id + '|' + room
122
+ const c = cursor.get(ck) || { pos: 0, pend: [] }
123
+ let r = null
124
+ try { r = await read(room, drop, c.pos) } catch { r = null }
125
+ fetched[i] = { room, drop, ck, c, r }
126
+ if (pace.gapMs > 0 && next < rooms.length) await nap(pace.gapMs)
127
+ }
128
+ }
129
+ await Promise.all(Array.from({ length: Math.min(READS_AT_ONCE, rooms.length) }, (_, w) => worker(w)))
130
+ for (const f of fetched) {
131
+ if (!f) continue
132
+ const { room, drop, ck, c, r } = f
133
+ if (!r || r.status !== 200 || !Array.isArray(r.boxes)) continue
134
+ const items = []
135
+ for (let i = 0; i < r.boxes.length; i++) {
136
+ let b = null
137
+ try { b = JSON.parse(await openBox(JSON.parse(r.boxes[i]), key.priv)) } catch { b = null }
138
+ if (!b || typeof b.id !== 'string' || !Number.isFinite(b.ts)) continue // not ours (or garbage): cleared with its neighbours, never counted
139
+ items.push({ id: b.id, pos: (r.base || 0) + i, ts: b.ts })
140
+ const m = monthOf(b.ts)
141
+ if (!byMonth.has(m)) byMonth.set(m, [])
142
+ byMonth.get(m).push(b)
143
+ }
144
+ perRoom.push({ room, drop, ck, c, end: r.end, items })
145
+ }
146
+ const confirmed = new Set()
147
+ for (const [m, bodies] of byMonth) {
148
+ for (let attempt = 0; attempt < 3; attempt++) {
149
+ let cur
150
+ try { cur = await readDoc(docNameFor(m)) } catch { break } // UNKNOWN, not empty: a write REPLACES the doc, so writing now could erase the month — skip it; nothing moves on
151
+ await writeDoc(docNameFor(m), foldInto(cur, bodies)).catch(() => null)
152
+ const back = await readDoc(docNameFor(m)).catch(() => null)
153
+ for (const b of bodies) if (back && back.r && back.r[b.id]) confirmed.add(b.id)
154
+ if (bodies.every((b) => confirmed.has(b.id))) break
155
+ }
156
+ }
157
+ let folded = 0, cleared = 0
158
+ for (const p of perRoom) {
159
+ if (!p.items.every((it) => confirmed.has(it.id))) continue // the next run reads them again from the same place
160
+ folded += p.items.length
161
+ const pend = [...p.c.pend, ...p.items.map((it) => [it.pos, it.ts])].sort((a, b) => a[0] - b[0]).slice(-1000)
162
+ // Clear the OLD prefix only: everything up to the last receipt sent before the hold, with nothing newer before it.
163
+ let upTo = 0, keep = pend
164
+ for (let i = 0; i < pend.length && pend[i][1] <= now - holdMs; i++) { upTo = pend[i][0] + 1; keep = pend.slice(i + 1) }
165
+ if (upTo) {
166
+ try {
167
+ const r = await ack(p.room, p.drop, upTo)
168
+ if (r && r.status === 200) cleared += pend.length - keep.length
169
+ else keep = pend // an HTTP refusal resolves normally; keep it pending just like a transport failure
170
+ } catch { keep = pend }
171
+ }
172
+ const pos = Number.isInteger(p.end) ? p.end : p.c.pos
173
+ if (pos !== p.c.pos || keep.length !== p.c.pend.length) cursor.set(p.ck, { pos, pend: keep }) // a quiet room costs no write
174
+ }
175
+ return { folded, rooms: perRoom.filter((p) => p.items.length).length, cleared }
176
+ }
@@ -0,0 +1,90 @@
1
+ // usageSummary.js — a Space's usage, added up ON THE DEVICE from the sealed per-reply records (2026-10-01;
2
+ // docs/tenant-billing.md § 8.1; spaces/test/usageSummary.test.mjs). Pure: no DOM, no imports.
3
+ //
4
+ // Every AI reply carries `usage` (agent/turnUsage.mjs): who asked, tokens, and the provider's own cost per call. The room's
5
+ // members see their room's cost by person and by model; Witbitz never sees these totals. A turn some of whose calls
6
+ // reported no price is marked `provider-partial`, and the view says so rather than presenting the total as complete.
7
+ // It is analysis, not the bill — the bill is the provider's per-key report.
8
+
9
+ const DAY = 86_400_000
10
+ const num = (v) => (Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : 0)
11
+ const str = (v, n = 80) => String(v == null ? '' : v).slice(0, n)
12
+
13
+ const usageOf = (e) => (e && e.self && e.usage && typeof e.usage === 'object' ? e.usage : null)
14
+
15
+ function bucket () { return { turns: 0, calls: 0, in: 0, out: 0, cached: 0, costMicros: 0 } }
16
+ function add (b, u, isReply = true) {
17
+ if (isReply) b.turns++ // a room title costs, but it is not a reply
18
+ b.calls += num(u.calls)
19
+ b.in += num(u.in)
20
+ b.out += num(u.out)
21
+ b.cached += num(u.cached)
22
+ b.costMicros += num(u.costMicros)
23
+ }
24
+
25
+ /** @param {object[]} entries the room's decrypted ledger @param {{now?: number, days?: number}} [o] */
26
+ export function roomUsageRecords (entries, titles = []) {
27
+ const records = []
28
+ function record(u, at, title) {
29
+ // Export billing fields only. A reply and a title can both contain other room data.
30
+ const ts = num(at)
31
+ records.push({ self: true, ts: ts <= 8.64e15 ? ts : 0, title, usage: {
32
+ by: title ? 'Room titles' : str(u.by), calls: num(u.calls), in: num(u.in),
33
+ out: num(u.out), cached: num(u.cached), costMicros: num(u.costMicros),
34
+ models: Array.isArray(u.models) ? u.models.slice(0, 8).map(m => str(m)) : [], source: str(u.source, 20),
35
+ } })
36
+ }
37
+ for (const e of entries || []) if (usageOf(e)) record(e.usage, e.ts, false)
38
+ for (const u of Array.isArray(titles) ? titles : []) if (u && typeof u === 'object') record(u, u.at, true)
39
+ return records
40
+ }
41
+
42
+ export function summarizeUsage (entries, { now = Date.now(), days = 7, titles = [] } = {}) {
43
+ const all = bucket(), week = bucket()
44
+ const people = new Map(), models = new Map()
45
+ let partial = false
46
+ for (const e of roomUsageRecords(entries, titles)) {
47
+ const u = usageOf(e)
48
+ if (!u) continue
49
+ add(all, u, !e.title)
50
+ if (num(e.ts) >= now - days * DAY) add(week, u, !e.title)
51
+ const who = str(u.by) || 'Someone'
52
+ if (!people.has(who)) people.set(who, { name: who, ...bucket() })
53
+ add(people.get(who), u)
54
+ for (const m of Array.isArray(u.models) ? u.models.slice(0, 8) : []) {
55
+ const k = str(m, 80)
56
+ if (!models.has(k)) models.set(k, { model: k, turns: 0 })
57
+ models.get(k).turns++
58
+ }
59
+ if (u.source !== 'provider') partial = true
60
+ }
61
+ const byCost = (a, b) => b.costMicros - a.costMicros || b.turns - a.turns
62
+ return { all, week, byPerson: [...people.values()].sort(byCost), byModel: [...models.values()].sort((a, b) => b.turns - a.turns), partial, empty: people.size === 0 }
63
+ }
64
+
65
+ /** Micro-dollars → a price a person can read: four decimals while it is small, cents once it is not. */
66
+ export const money = (micros) => {
67
+ const m = Math.round(num(micros))
68
+ if (m === 0) return '$0.00'
69
+ // Round in INTEGER micro-dollars, half up — toFixed on the float shows 12,650 µ$ ($0.01265) as $0.0126.
70
+ if (m < 1_000_000) return '$' + (Math.max(Math.round(m / 100), 1) / 10_000).toFixed(4)
71
+ return '$' + (Math.round(m / 10_000) / 100).toFixed(2)
72
+ }
73
+
74
+ const csvCell = (v) => {
75
+ let s = String(v == null ? '' : v)
76
+ if (/^[=+\-@\t\r]/.test(s)) s = "'" + s // a spreadsheet must not run a member's name as a formula
77
+ return /[",\n\r']/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s
78
+ }
79
+
80
+ /** One CSV line per AI reply that carries a record — for a member who wants the numbers in a spreadsheet. */
81
+ export function usageCsv (entries) {
82
+ const lines = ['date,asked_by,calls,input_tokens,output_tokens,cached_tokens,cost_usd,credits,models,cost_source']
83
+ for (const e of entries || []) {
84
+ const u = usageOf(e)
85
+ if (!u) continue
86
+ const date = num(e.ts) ? new Date(num(e.ts)).toISOString() : ''
87
+ lines.push([date, str(u.by), num(u.calls), num(u.in), num(u.out), num(u.cached), (num(u.costMicros) / 1e6).toFixed(6), (num(u.costMicros) / 1e4).toFixed(4), (Array.isArray(u.models) ? u.models : []).map((m) => str(m)).join(' '), str(u.source, 20)].map(csvCell).join(','))
88
+ }
89
+ return lines.join('\n') + '\n'
90
+ }