@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/codeCloud.js ADDED
@@ -0,0 +1,650 @@
1
+ // codeCloud.js — open a CLOUD COMPUTER from the Code page (docs/cloud-computer.md §3, §10.4).
2
+ //
3
+ // A cloud computer is your own Nitro enclave running OpenCode and the Witbitz connector, on a host that runs only while
4
+ // it is used. Once it is open it is reached like any paired computer — the sealed relay (codeTransport.js). Opening it is
5
+ // what this file does, the same steps infra/cloud-computer/device.mjs proved on hardware:
6
+ //
7
+ // open the controller (POST /v1/cloud-computer, your account's sign-in token) starts the host if it is asleep and
8
+ // hands the workspace a blank enclave — or says the workspace is already running (then there is nothing to do).
9
+ // It carries this page's two fresh nonces, so the same answer brings both attestations below
10
+ // attest the enclave's attestation over a fresh nonce, checked against AWS's root and the PUBLISHED image measurement
11
+ // (PCR0, pinned below). A host that is not running that image fails here, before anything is sent to it.
12
+ // sentinel the host's Credential Sentinel's attestation too, pinned to ITS published image (docs/credential-sentinel.md §9)
13
+ // grant your keys — TrustedRouter, and Tinfoil and GitHub when saved — sealed to the SENTINEL, bound to this cloud
14
+ // computer's channel key (from its attestation). The cloud computer never receives a key.
15
+ // seal the device half of the workspace key, the relay pairing and the Sentinel's channel pin, sealed to the cloud
16
+ // computer (ECDH P-384 → HKDF(salt = nonce) → AES-GCM, the nonce as associated data)
17
+ // assign the enclave opens the workspace (or, the first time, creates it) and starts OpenCode and the connector —
18
+ // sent with the grant in ONE call (handover): the controller assigns only once the Sentinel took the grant
19
+ //
20
+ // The controller and the host see none of what is sealed. What they could still do is refuse, or offer an older saved
21
+ // version — the account keeps the newest version it has seen and the enclave refuses anything older.
22
+
23
+ import { cloudKeyStatus, mintCloudKeys } from './codeCloudKeys.js' // an account-keyed cloud computer's status at each opening; a pasted-key one's move
24
+ import { verifyAttestation } from './nitroVerify.js'
25
+ import { sealTo } from './sealShare.js'
26
+ import { trustedSentinelPins } from './connections.js' // the standing Sentinel builds this device trusts — named in the grant (below)
27
+ import { RELAY_URL, newRelaySecret } from './codeRelay.js'
28
+ import { sentinelKeys } from './codeSentinel.js'
29
+ import { normEgress, egressHash } from './codeEgress.js' // what this computer may reach: one reading, three destinations
30
+
31
+ export const CLOUD_API = 'https://api.witbitz.chat/v1/cloud-computer'
32
+ // The published cloud-computer image. A rollover lists two: the outgoing and the incoming measurement.
33
+ // ★ p1n IS THE FIRST MEASUREMENT IN THIS FILE THAT ANYONE COULD CHECK. Every pin above it was a one-shot artifact of
34
+ // its own build's clock: nitro-cli measures file mtimes, and until 83a33432 every apt-get, mkdir, useradd and tar at
35
+ // build time wrote the moment of the build into the image. Two people rebuilding the same commit got different
36
+ // numbers, and nobody — including us — could verify one. p1n reproduced across two --no-cache builds on each of two
37
+ // machines with different umasks, in both directions, to the last digit (docs/cloud-computer.md § 11).
38
+ // p1j's 40f3f1bf is dropped here, and leaves the KMS policy only AFTER this is deployed: the other order breaks
39
+ // anything still running it, this order means nothing can be launched with it before the key stops opening for it.
40
+ // ★ p1o IS p1n PLUS THE AGENT'S BROWSER (docs/cloud-computer.md § 12): Chromium + KasmVNC's X server under uid 1001,
41
+ // the publisher, browse.go's CDP gate. +437,671,570 B on the image (+34 %), the Sentinel's sources untouched.
42
+ // Reproduced against itself on the host (two --no-cache builds, gate exit 0); the cross-machine row was NOT run for
43
+ // this tag — there was no second machine, and launching one was declined as its own decision (§ 11, the cycle doc).
44
+ // Built at c3181136, epoch 1789695180 — the same epoch master's tip gives today, so a rebuild at the tip reproduces it.
45
+ // ★ p1p MOVES THIS NUMBER WITH THE CLOUD IMAGE'S CONTENT BYTE-IDENTICAL TO p1o — `ccvm.eif` is 1,711,586,406 bytes in
46
+ // both. Nothing in the agent's image changed: the whole of p1p is the Sentinel answering `mayReach`, so the parent can
47
+ // let a Custom workspace reach the hosts its owner sealed. The measurement moved because `SOURCE_DATE_EPOCH` is ONE
48
+ // value for the whole build and stamps every member's mtime — the same coupling that restamped the SENTINEL at p1o,
49
+ // now seen in the other direction. Per-image epochs remain the fix, and until they land NEITHER number is a usable
50
+ // stop condition on its own; the check that holds is the file-by-file tarball diff.
51
+ export const CLOUD_PCR0 = [
52
+ '66c77a098b36a21fa4a7612ecad202ef2c8e46e34f14e9ab56a3a2a9f3108190f6d2bac14c526f501b1e0109d9605a72', // p3i, reproduced twice from c6ca1e6b
53
+ ]
54
+ // The published Credential Sentinel image.
55
+ // ★ A NEW KERNEL MOVES THIS ONE TOO, with an untouched sentinel userland: PCR0 measures kernel and ramdisk together
56
+ // and make-eif.sh builds both images against the same blobs. Forgetting it would leave every cloud computer unable
57
+ // to reach its own credentials.
58
+ // ★ THIS ONE MOVED FOR A REASON THAT IS NOT THE KERNEL, which is worth recording because the last two cycles held it
59
+ // as a stop condition. The kernel is the same bzImage; `ccsentinel` hashes identical to p1h and p1i; the Dockerfile
60
+ // is identical. The ONLY file that differs in the sentinel image is `sentinel.mjs`, and the only difference in it is
61
+ // the registry broker (toRegistry / decideRegistry / stripRegistryAuth). Verified by diffing p1i's sentinel.tgz
62
+ // against p1j's file by file, not by assuming the change I made was the change that landed.
63
+ // ★ p1k MOVED THIS ONE WITH NOT A LINE OF SENTINEL CODE CHANGED, and the reason is worth reading before anyone treats
64
+ // a moved Sentinel measurement as evidence of a change. esbuild writes each module's path into the bundle relative to
65
+ // the CWD IT WAS RUN FROM, so p1j (built from one directory) and p1k (built from another) differ in those strings and
66
+ // nowhere else: `git log -- sentinel/` is empty across the two, ccsentinel and the Dockerfile hash identically, the
67
+ // kernel is the same bzImage, and normalising the path prefixes makes the two bundles hash the same.
68
+ // The cause is fixed in build-image.sh (the build runs from the repo root, with a guard), so this is a ONE-TIME move
69
+ // from a rendering nobody chose to the reproducible one — and it was taken deliberately rather than avoided, because
70
+ // the alternative was leaving a pinned measurement that the committed build script cannot reproduce.
71
+ // ⛔ RETRACTED (2026-09-17, same day): the "control" cited here — rebuilding p1j from its stored artifacts and getting
72
+ // both pins back — was a CACHE HIT. docker build found every layer present and returned the existing image, so
73
+ // nitro-cli measured an image built nine hours earlier. The pipeline is NOT known to be deterministic; in fact the
74
+ // build does not reproduce against itself on one machine, because nitro-cli measures file mtimes and every
75
+ // apt-get/mkdir/tar at build time writes the clock in. ✅ TRUE OF EVERY MEASUREMENT ABOVE p1n AND NO LONGER TRUE
76
+ // OF p1n: make-eif.sh now builds twice with --no-cache and records nothing unless both agree, and p1n cleared that
77
+ // gate on two machines. So the outgoing pins here are historical numbers nobody can re-derive, and the incoming
78
+ // ones are checkable — which is the difference this file exists to assert. docs/cloud-computer.md § 11.
79
+ // ★ p1o MOVED THIS ONE WITH THE SENTINEL'S SOURCES UNTOUCHED, and the reason can be said in one sentence: SOURCE_DATE_EPOCH
80
+ // is ONE value for the whole build and tarball() stamps it as every member's mtime, so an epoch moved by a CLOUD-image
81
+ // change (the browser) restamps the Sentinel's tarball too — ccsentinel, sentinel.mjs and its Dockerfile are IDENTICAL
82
+ // to p1n's, file by file; only the mtimes differ. The fix is per-image epochs (build-image.sh, not yet done); until it
83
+ // lands, "SENTINEL_PCR0 must not move" is NOT a usable stop condition, and the check that holds is the file-by-file diff.
84
+ // ★★ AND THIS NUMBER WENT BACKWARDS, WHICH IS THE POINT. p1s carries PER-IMAGE EPOCHS (build-image.sh): the Sentinel's
85
+ // is derived from the last commit touching ITS OWN inputs, so it is 1789761669 — p1p's — and the measurement came
86
+ // back to p1p's `abad1ca9…`, byte for byte, after four cycles of moving for changes in the OTHER image. p1q's and
87
+ // p1r's Sentinel numbers were noise: the sources were identical each time, and only the shared stamp differed.
88
+ // ⚑ So "SENTINEL_PCR0 must not move when the Sentinel did not change" is a usable stop condition again — the check
89
+ // that caught the esbuild-cwd leak, and which caught nothing for four cycles because the number always moved.
90
+ export const SENTINEL_PCR0 = [
91
+ 'aaeb3d3f64efa4f072372a7f257eaa89fd969614139ca08a8ce817ec46cd0d32cf2b4e6103b984a2b7f9d7ce3354c248', // p3i, reproduced twice from c6ca1e6b
92
+ ]
93
+ export const GRANT_TTL_MS = 24 * 3600_000
94
+ export const PUSH_PATTERN = 'witbitz/*'
95
+
96
+ const enc = new TextEncoder()
97
+ const b64 = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s) }
98
+ const unb64 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0))
99
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
100
+ const b32 = 'abcdefghijklmnopqrstuvwxyz234567'
101
+ const b64u = (u8) => b64(u8).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
102
+
103
+ /**
104
+ * The two secrets a workspace belongs to (docs/cloud-computer.md step 3). Ownership used to follow the EMAIL, so an
105
+ * address that changed — or an allowlist that dropped one — locked a person out of their own files.
106
+ * · `owner` stays in the account alone and rides every ordinary call: it is who this workspace belongs to.
107
+ * · `recovery` goes in the KEY FILE too (codeKeyFile.js), and buys one thing — moving the workspace to a new owner,
108
+ * spending itself in the act. It is never accepted as the way in.
109
+ * Neither reaches the host: the controller hashes both and stores opaque hex.
110
+ */
111
+ export const newCloudSecrets = () => ({ owner: b64u(crypto.getRandomValues(new Uint8Array(32))), recovery: b64u(crypto.getRandomValues(new Uint8Array(32))) })
112
+
113
+ /** A new cloud computer's entry: a relay pairing like any computer's, plus what only this account holds about it. */
114
+ export function newCloudComputer({ name = 'Cloud computer', key = '', tinfoil = '', github = '', browsePrivate = false } = {}) {
115
+ const id = 'cloud-' + b64(crypto.getRandomValues(new Uint8Array(12))).replace(/\+/g, '-').replace(/\//g, '_')
116
+ const workspace = Array.from(crypto.getRandomValues(new Uint8Array(26)), (b) => b32[b & 31]).join('')
117
+ return {
118
+ id, name: String(name).trim().slice(0, 80) || 'Cloud computer', relay: RELAY_URL, secret: newRelaySecret(),
119
+ cloud: {
120
+ workspace, half: b64(crypto.getRandomValues(new Uint8Array(32))), key: String(key).trim(), version: 0,
121
+ tinfoil: String(tinfoil).trim(), github: String(github).trim(), grantKey: b64(crypto.getRandomValues(new Uint8Array(32))),
122
+ // The browse key: minted here, sealed into the bundle, kept for the viewer. Never in the Sentinel's grant —
123
+ // the Sentinel holds what the agent must never see, and this is what the machine needs to act (§ 12).
124
+ browse: b64(crypto.getRandomValues(new Uint8Array(32))),
125
+ ...(browsePrivate ? { browsePrivate: true } : {}), // absent unless chosen, so older entries are untouched
126
+ ...newCloudSecrets(),
127
+ },
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Close a cloud computer: a last save, then the enclave is terminated (the host's revoke drops its Sentinel grants with
133
+ * it). Used when one is REMOVED, so a running enclave does not go on until its idle timeout — and, by the same rule,
134
+ * never allowed to hold the removal up: no token, a refusal, no answer, a service that hangs → false, and the caller
135
+ * removes anyway (the idle timeout is the backstop). Never throws.
136
+ * @returns {Promise<boolean>} whether the service took it
137
+ */
138
+ export async function closeCloud(computer, { token, fetchImpl = fetch, api = CLOUD_API, waitMs = 8000 } = {}) {
139
+ const c = computer && computer.cloud
140
+ if (!c || !c.workspace) return false
141
+ const give = new Promise((r) => setTimeout(() => r(false), waitMs)) // the person is waiting on this: give up early
142
+ const close = (async () => {
143
+ let t = null
144
+ try { const got = await token(); t = typeof got === 'string' ? got : (got && got.token) || null } catch { t = null }
145
+ if (!t) return false
146
+ try {
147
+ const r = await fetchImpl(api, { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + t }, body: JSON.stringify({ action: 'close', workspace: c.workspace, ...(c.owner ? { owner: c.owner } : {}) }) })
148
+ return r.status === 200
149
+ } catch { return false }
150
+ })()
151
+ return Promise.race([close, give])
152
+ }
153
+
154
+ /** DELETE MY ACCOUNT (accountEraseUi.js; the owner, 2026-11-17: "We should delete everything we can"): the workspace's every
155
+ * object in S3, gone — not Remove (which keeps them, so a key file can restore). The controller closes an open one first and
156
+ * answers 409 while it is still saving, 202 while a long purge goes on. → { ok, why? } */
157
+ export async function destroyCloud(computer, { token, fetchImpl = fetch, api = CLOUD_API, tries = 30, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
158
+ const c = computer && computer.cloud
159
+ if (!c || !c.workspace) return { ok: true }
160
+ for (let i = 0; i < tries; i++) {
161
+ let r, j = {}
162
+ try {
163
+ r = await fetchImpl(api, { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + token }, body: JSON.stringify({ action: 'destroy', workspace: c.workspace, ...(c.owner ? { owner: c.owner } : {}) }) })
164
+ j = await r.json().catch(() => ({}))
165
+ } catch { return { ok: false, why: 'the cloud computer service did not answer' } }
166
+ if (r.status === 200 && j.destroyed) return { ok: true }
167
+ if (r.status === 403) return { ok: true } // no longer this account's (moved to another owner): not ours to delete
168
+ if (r.status === 202 || r.status === 409 || r.status === 503) { await sleep(Math.min(Number(j.retryMs) || 2000, 10_000)); continue }
169
+ return { ok: false, why: 'cloud computer ' + r.status + (j.error ? ' (' + j.error + ')' : '') }
170
+ }
171
+ return { ok: false, why: 'your cloud computer is still closing — run Delete my account again in a few minutes' }
172
+ }
173
+
174
+ /** What the person sees while a step runs. */
175
+ export const CLOUD_STEPS = {
176
+ requesting: 'Opening your cloud computer…',
177
+ starting: 'Waking your cloud computer — about a minute when it was asleep…', // only when the host says it is starting
178
+ verifying: 'Checking your cloud computer and its key guard run the published Witbitz images…',
179
+ opening: 'Opening your workspace…',
180
+ connecting: 'Connecting to your cloud computer…',
181
+ }
182
+
183
+ export class CloudError extends Error {
184
+ constructor(message, { status = 0, code = '' } = {}) { super(message); this.status = status; this.code = code }
185
+ }
186
+
187
+ /**
188
+ * Move a workspace to a NEW owner — what a key file's recovery secret buys, and all it buys. Two ways to prove the right
189
+ * to do it, and the service decides which applies: the RECOVERY secret from a key file (break-glass, after a removal or
190
+ * an account lost), or being the current owner already (rotating a file that was lost or leaked, and how a workspace
191
+ * made before any of this adopts an owner of its own). It spends the old secrets either way.
192
+ *
193
+ * ★ Write the new secrets into the account BEFORE calling this. If the move lands and the page dies before saving, the
194
+ * old key file is already dead and the new secrets were never kept — the workspace would be lost for the sake of an
195
+ * ordering. The caller keeps the old recovery secret alongside until this returns, so a failure can be tried again.
196
+ * @returns {Promise<true>} throws CloudError otherwise — `code: 'open'` when the workspace is open right now
197
+ */
198
+ export async function rebindCloud(computer, { token, fetchImpl = fetch, api = CLOUD_API, recovery = '', newOwner = '', newRecovery = '' } = {}) {
199
+ const c = computer && computer.cloud
200
+ if (!c || !c.workspace) throw new CloudError('this is not a cloud computer')
201
+ if (!newOwner || !newRecovery) throw new CloudError('moving a workspace needs its new secrets')
202
+ let t = null
203
+ try { const got = await token(); t = typeof got === 'string' ? got : (got && got.token) || null } catch { t = null }
204
+ if (!t) throw new CloudError('sign in with your email to bring this workspace back', { code: 'no_token' })
205
+ let r, out
206
+ try {
207
+ r = await fetchImpl(api, {
208
+ method: 'POST',
209
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + t },
210
+ body: JSON.stringify({ action: 'rebind', workspace: c.workspace, newOwner, newRecovery, ...(c.owner ? { owner: c.owner } : {}), ...(recovery ? { recovery } : {}) }),
211
+ })
212
+ out = await r.json().catch(() => ({}))
213
+ } catch { throw new CloudError('the cloud computer service did not answer') }
214
+ if (r.status === 200) return true
215
+ // 409 has two shapes and both are things a person can act on: the workspace is open (close it), or someone else is
216
+ // moving it at this moment (wait). Neither is a failure of the file.
217
+ if (r.status === 409) throw new CloudError(/being moved/.test(String(out.error || '')) ? 'that workspace is being moved right now — try again in a moment' : 'that workspace is open right now — close it on the device that has it open, then try again', { status: 409, code: 'open' })
218
+ if (r.status === 403) throw new CloudError('that key file does not open this workspace — it may already have been used', { status: 403, code: 'refused' })
219
+ throw new CloudError(out.error || `the cloud computer service said ${r.status}`, { status: r.status, code: out.error || '' })
220
+ }
221
+
222
+ /**
223
+ * Spend a restore's pending move, if it has one. A key file brings a workspace back by MOVING it to this account, and
224
+ * that move may not land at once — the device is offline, or the workspace is still open elsewhere. The account keeps
225
+ * the old recovery secret (`pendingMove`) until it does, so this is simply tried again: at the restore, and before
226
+ * every opening after it. Until it lands, the workspace still belongs to whoever had it, and an open would be refused.
227
+ * @returns {Promise<boolean>} whether there was a move to make (it threw if there was one and it failed)
228
+ */
229
+ export async function spendPendingMove(computer, { move = rebindCloud, ...opts } = {}) {
230
+ const c = computer && computer.cloud
231
+ if (!c || !c.pendingMove) return false
232
+ if (!c.owner || !c.recovery) throw new CloudError('this computer has no secrets of its own to move its workspace to')
233
+ await move(computer, { ...opts, recovery: c.pendingMove, newOwner: c.owner, newRecovery: c.recovery })
234
+ return true
235
+ }
236
+
237
+ /**
238
+ * Open a cloud computer so its connector comes online on the relay.
239
+ * @param {{ id, name, relay, secret, cloud: { workspace, half, key, version } }} computer
240
+ * @param {object} o
241
+ * @param {() => Promise<string|{ token: string|null, reason?: string }|null>} o.token — the account's sign-in token, asked of
242
+ * the app once per opening and again only when the service does not accept it; `reason` says why there is none
243
+ * @param {(step: keyof CLOUD_STEPS) => void} [o.onStep]
244
+ * @returns {Promise<{ live: boolean, version: number, grantKey?: string }>} `version`: the workspace version now open, and a
245
+ * `grantKey` made here for an older entry that had none — both to keep in the account
246
+ */
247
+ // ★★ A NEW PUBLISHED IMAGE IS FOLLOWED, NOT REFUSED — in the SDK (docs/sdk-cloud-computers.md phase 1). An SDK version is
248
+ // immutable, so its pins would go stale at the next image cycle and every app on it would lose its cloud computers (the
249
+ // Sentinel's lesson, connections.js verifyFollowing). Witbitz publishes the live set at /cloud-claim.json (held equal to
250
+ // the pins below by test, network-only in both workers); `follow` reads it on a PCR0 mismatch and accepts an image named
251
+ // there — at once (`auto`) or when the person says yes (`ask(pcr0, role)`). The app passes none: its pins move with it.
252
+ export const CLOUD_CLAIM_URL = 'https://witbitz-spaces.pages.dev/cloud-claim.json'
253
+ const PCR = /^[0-9a-f]{96}$/
254
+ export async function publishedCloudPins (fetchImpl = (u, o) => fetch(u, o), url = CLOUD_CLAIM_URL) {
255
+ try {
256
+ const r = await fetchImpl(url, { cache: 'no-store' })
257
+ if (!r || !r.ok) return { cc: [], sentinel: [] }
258
+ const c = await r.json()
259
+ const list = (v) => (Array.isArray(v) ? v.filter((x) => PCR.test(String(x))) : [])
260
+ return { cc: list(c && c.pcr0), sentinel: list(c && c.sentinelPcr0) }
261
+ } catch { return { cc: [], sentinel: [] } }
262
+ }
263
+ // ★★ A PIN MISMATCH IS USUALLY A STALE PAGE (codeCloudStale.js): the app passes its build and a reload, and a mismatch on a
264
+ // page older than the published build reloads it once. Without them (the SDK, a test) a mismatch means what it says.
265
+ export async function openCloud(computer, { token, aws = null, onStep = () => {}, onSession = () => {}, onGitHub = () => {}, fetchImpl = fetch, verify = verifyAttestation, api = CLOUD_API, pcr0 = CLOUD_PCR0, sentinelPcr0 = SENTINEL_PCR0, waitMs = 600_000, now = () => Date.now(), pageBuild = '', reload = () => {}, publishedBuild = async () => null, follow = null } = {}) {
266
+ const c = computer && computer.cloud
267
+ if (!c || !c.workspace || !c.half) throw new CloudError('this is not a cloud computer')
268
+ if (!c.key) throw new CloudError('no TrustedRouter key is saved for this cloud computer', { code: 'no_key' })
269
+ const until = now() + waitMs
270
+
271
+ // One token for the whole opening: a host that is starting answers 503 for a minute, and asking the app on every retry
272
+ // turned one slow refresh into "sign in with your email" (the owner's report).
273
+ let held = null
274
+ const tokenNow = async (fresh) => {
275
+ if (!held || fresh) {
276
+ const t = await token()
277
+ held = typeof t === 'string' ? { token: t, reason: '' } : { token: (t && t.token) || null, reason: (t && t.reason) || '' }
278
+ }
279
+ if (!held.token) throw new CloudError(`sign in with your email to use cloud computers${held.reason ? ` (${held.reason})` : ''}`, { code: 'no_token' })
280
+ return held.token
281
+ }
282
+ let askedAgain = false
283
+ async function call(body) {
284
+ let sent = false
285
+ for (;;) {
286
+ // ⚑ A RETRY SIGNS AGAIN (2026-11-14): the AWS key's admission carries a one-time nonce the server takes once, and the
287
+ // loop below resends while a host wakes (503 "starting") or the network blips — the same admission came back "this
288
+ // signed request was already used". Every send after the first takes a fresh one (none to give → sent without).
289
+ if (sent && body && body.aws) { const { aws: _used, ...rest } = body; body = await admitted(rest) }
290
+ sent = true
291
+ const t = await tokenNow(false)
292
+ let r, out
293
+ try {
294
+ // The workspace's own owner rides every call. An entry without one is from before secrets existed: the service
295
+ // falls back to the email hash, exactly as it always did.
296
+ // ⛔ A CALL THAT NEVER ANSWERS ENDS (2026-11-08, docs/state-machines.md I16 / C#13): there was no timeout — after iOS froze and
297
+ // resumed the page the request could hang for good, the opening stayed "Waking…" and retry could not replace it until a reload.
298
+ // 60 s per call; the loop above retries within `until`, as for a network error.
299
+ r = await fetchImpl(api, { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + t }, body: JSON.stringify(c.owner ? { ...body, owner: c.owner } : body), ...(typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? { signal: AbortSignal.timeout(CALL_TIMEOUT_MS) } : {}) })
300
+ out = await r.json().catch(() => ({}))
301
+ } catch {
302
+ if (now() > until) throw new CloudError('the cloud computer service did not answer')
303
+ await sleep(3000); continue
304
+ }
305
+ if (r.status === 503 && out.state && now() < until) { onStep('starting'); await sleep(Math.min(Math.max(out.retryMs || 3000, 1000), 10_000)); continue }
306
+ // A 401 WITH A CODE is the AWS key's (controller.mjs AWS_REFUSAL: unauthorized / not_found), not the sign-in's — it said
307
+ // "your sign-in was not accepted" for a key signature the page had mangled (2026-11-14), and signing in again changed nothing.
308
+ if (r.status === 401 && out.code) throw new CloudError(`your AWS key was not accepted: ${out.error || out.code}`, { status: 401, code: out.code })
309
+ if (r.status === 401 && !askedAgain) { askedAgain = true; await tokenNow(true); continue } // once more, with a fresh one
310
+ if (r.status === 401) throw new CloudError(`your sign-in was not accepted${out.reason ? ` (${out.reason})` : ''} — sign in again with your email`, { status: 401, code: 'no_token' })
311
+ if (r.status === 429 && out.code === 'aws_limit') throw new CloudError(`this month's cloud computer allowance is used${out.resetsAt ? ` — it starts again on ${String(out.resetsAt).slice(0, 10)}` : ''}`, { status: 429, code: 'aws_limit' })
312
+ if (r.status !== 200 || out.error) throw new CloudError(out.error || `the cloud computer service said ${r.status}`, { status: r.status, code: out.code || out.error || '' })
313
+ return out
314
+ }
315
+ }
316
+ // THE PERSON'S AWS KEY PAYS FOR THE HOURS (docs/aws-keys.md): the app signs an admission for each call that spends — the
317
+ // open and the handover — and the private half never enters this page. No key (an app without it) = the call as before.
318
+ const admitted = async (body) => { let a = null; try { a = aws ? await aws() : null } catch { a = null } return a && a.keyId ? { ...body, aws: a } : body }
319
+
320
+ onStep('requesting')
321
+ let create = c.version === 0
322
+ const nonces = { cc: crypto.getRandomValues(new Uint8Array(32)), sentinel: crypto.getRandomValues(new Uint8Array(32)) }
323
+ // ★ ONE READING OF THE POLICY, FOR ALL THREE PLACES IT GOES: the open request (which the host authenticates and uses
324
+ // for its own coarse list), the sealed bundle (the enclave's copy, enforced there and reported in its story), and
325
+ // the grant (the Sentinel's copy, which decides GitHub). Reading the stored doc three times would be three chances
326
+ // to disagree, and a workspace attesting `trusted` while its grant said `none` is a story that is not quite true.
327
+ // A policy that does not validate is a REFUSAL here, not a fallback: the person is looking at the setting.
328
+ const eg = normEgress(c.egress)
329
+ if (eg.error) throw new CloudError(`this computer's network setting cannot be used (${eg.error})`, { code: 'egress' })
330
+ const policy = eg.policy
331
+ const openBody = () => ({ action: 'open', workspace: c.workspace, create, egressMode: policy.mode, ...(create && c.recovery ? { recovery: c.recovery } : {}), attest: { cc: b64(nonces.cc), sentinel: b64(nonces.sentinel) } })
332
+ let opened
333
+ try {
334
+ opened = await call(await admitted(openBody()))
335
+ } catch (e) {
336
+ // Made before, but this account never heard back that it was (the page closed mid-way): open it instead.
337
+ if (!(create && e.status === 409)) throw e
338
+ create = false
339
+ opened = await call(await admitted(openBody()))
340
+ }
341
+ const alreadyOpen = !!opened.live
342
+ if (!alreadyOpen && !create && opened.version < c.version) {
343
+ throw new CloudError(`the host offered an older copy of your workspace (version ${opened.version}; this account has seen ${c.version}) — refused`, { code: 'rollback' })
344
+ }
345
+
346
+ onStep('verifying')
347
+ // Both attestations below run in parallel and both fail on a stale page: the published build is read once and the
348
+ // reload asked for once per open, whichever of the two arrives first.
349
+ let livePromise = null, reloadAsked = false
350
+ const staleAgainst = async () => { livePromise = livePromise || publishedBuild(fetchImpl); const live = await livePromise; return live && live !== pageBuild ? live : null }
351
+ // A PUBLISHED newer image (above, publishedCloudPins): read once per open; each pin tried on its own (a verifier refuses a set
352
+ // of three); accepted at once (`auto`) or on the person's yes. null = not published, the usual refusal follows.
353
+ let claimPromise = null
354
+ const followed = async (docB64, nonce, pins, role) => {
355
+ claimPromise = claimPromise || publishedCloudPins(follow.fetch || fetchImpl, follow.claimUrl || CLOUD_CLAIM_URL)
356
+ const claim = await claimPromise
357
+ for (const p of (role === 'sentinel' ? claim.sentinel : claim.cc).filter((x) => !pins.includes(x))) {
358
+ let doc = null
359
+ try { doc = await verify(unb64(docB64), { nonce, maxAgeMs: 120_000, expectedPCRs: { 0: [p] } }) } catch { continue }
360
+ if ((typeof follow.auto === 'function' && follow.auto()) || (typeof follow.ask === 'function' && await follow.ask(p, role))) return doc
361
+ throw new CloudError('you did not accept the new Witbitz image, so nothing was sent to your cloud computer', { code: 'declined' })
362
+ }
363
+ return null
364
+ }
365
+ // The attestation the open answer brought, or — from a controller without it, or one that failed there — asked for alone.
366
+ const attested = async (op, nonce, brought, pins, role) => {
367
+ const docB64 = typeof brought === 'string' && brought ? brought : (await call({ action: 'op', workspace: c.workspace, cid: opened.cid, req: { op, nonce: b64(nonce) } })).doc
368
+ let doc = null, failure = null
369
+ try { doc = await verify(unb64(docB64), { nonce, maxAgeMs: 120_000, expectedPCRs: { 0: pins } }) } catch (e) { failure = e }
370
+ const reason = failure ? String((failure && failure.message) || failure).split('\n')[0] : ''
371
+ if (!doc && follow && /PCR0/i.test(reason)) doc = await followed(docB64, nonce, pins, role)
372
+ if (!doc) {
373
+ if (/PCR/i.test(reason) && pageBuild && pageBuild.indexOf('__') !== 0) {
374
+ const live = await staleAgainst()
375
+ if (live) {
376
+ if (!reloadAsked) { reloadAsked = true; reload(live) } // once per open; reloadForBuild is once per target build besides
377
+ throw new CloudError(`this page is an older build (${pageBuild}) than the one published (${live}) and does not know the image your cloud computer now runs — reloading the page`, { code: 'stale' })
378
+ }
379
+ }
380
+ const what = role === 'sentinel' ? 'its key guard (the Credential Sentinel) is not running the published Witbitz image' : 'it is not running the published Witbitz image'
381
+ throw new CloudError(`${what}, so nothing was sent to it (` + reason + ')', { code: 'attestation' })
382
+ }
383
+ let said = null
384
+ try { said = JSON.parse(new TextDecoder().decode(doc.userData || new Uint8Array(0))) } catch { /* below */ }
385
+ if (!said || said.role !== role || !/^[0-9a-f]{64}$/.test(String(said.tls))) throw new CloudError(`the ${role} attestation does not name its channel key, so nothing was sent to it`, { code: 'attestation' })
386
+ const key = await crypto.subtle.importKey('spki', doc.publicKey, { name: 'ECDH', namedCurve: 'P-384' }, false, [])
387
+ return { nonce, key, tls: said.tls }
388
+ }
389
+ const brought = (opened.attest && typeof opened.attest === 'object') ? opened.attest : {}
390
+ const [cc, sentinel] = await Promise.all([
391
+ attested('attest', nonces.cc, brought.cc, pcr0, 'cloud-computer'),
392
+ attested('attest-sentinel', nonces.sentinel, brought.sentinel, sentinelPcr0, 'sentinel'),
393
+ ])
394
+
395
+ // ★★ AN ENCLAVE THAT IS ALREADY OPEN STOPS HERE — but it stops here, AFTER attestation, and not before it.
396
+ // It used to return the moment the controller said `live`, which cost two things. The small one: this page
397
+ // connected to a running enclave having verified NOTHING about it, while the cold path refuses anything whose
398
+ // PCR0 is not pinned. The large one: the session handle — cid, attested key, browse nonce — is minted by
399
+ // `assign`, and assign only runs on the cold path, so free browsing worked on exactly ONE page-load: the one
400
+ // that opened the computer. A reload, a second device, or any reconnect had no handle and the sheet refused
401
+ // with "this computer was not opened by this page". The owner hit it as "it refuses to open the web"
402
+ // (2026-09-21) on a computer that had been up for hours.
403
+ // ⚑ Same lesson as the browse key a week earlier, one notch further in: a capability that only reaches
404
+ // computers created after it shipped is not shipped — and this one only reached the page-load that opened it.
405
+ if (alreadyOpen) {
406
+ // The nonce, from an op that does NOT re-assign: the workspace is live and its policy is sealed. Authenticated
407
+ // by the device half, exactly as the free-browsing ask itself is (vm/main.go opBrowseNonce).
408
+ try {
409
+ const sealed = await sealTo(cc.key, crypto.getRandomValues(new Uint8Array(32)), { deviceHalf: c.half })
410
+ const out = await call({ action: 'op', workspace: c.workspace, cid: opened.cid, ...(c.owner ? { owner: c.owner } : {}), req: { op: 'browse-nonce', sealed } })
411
+ if (out && out.nonce) onSession({ cid: opened.cid, enclaveKey: cc.key, browseNonce: out.nonce })
412
+ } catch (e) {
413
+ // ⛑ NOT FATAL, and deliberately so: an enclave still running the outgoing image has no browse-nonce op, and
414
+ // refusing to reconnect to it would be a worse failure than the one this fixes. The handle is simply
415
+ // absent, which is exactly where this path was before — and the sheet already says so in words.
416
+ }
417
+ // ⛑⛑ ALWAYS, AND ON EVERY PATH THROUGH HERE. The opener starts each opening at step 'starting' and only moves
418
+ // when a step arrives (cloudOpener: `const entry = { step: 'starting' }`), so a path that stops emitting them
419
+ // leaves the page saying "Waking your cloud computer — about a minute when it was asleep…" about a computer
420
+ // that is open and serving. I made this conditional when the nonce fetch went in, so the HAPPY path was the
421
+ // one that went quiet (2026-09-21). The step is the product telling the owner where it got to; it is not
422
+ // bookkeeping for the success case to skip.
423
+ onStep('connecting')
424
+ return { live: true, version: c.version }
425
+ }
426
+
427
+ onStep('opening')
428
+ // Your keys go to the Sentinel only, bound to THIS cloud computer's channel key.
429
+ const grantKey = c.grantKey || b64(crypto.getRandomValues(new Uint8Array(32)))
430
+ // ★ AND THE BROWSE KEY, MINTED HERE FOR AN OLDER ENTRY — exactly as grantKey is, and for the same reason. It was
431
+ // minted only in newCloudComputer (2026-09-18), so every computer made before that morning carried none, the
432
+ // bundle said `browse: undefined`, browse.go reported `offered: false`, and the agent's browser was silently
433
+ // unavailable on it FOREVER with no way for the owner to tell (the row is deliberately quiet when not running).
434
+ // A feature that only reaches computers created after it shipped is not shipped. It is a random 32 bytes the page
435
+ // keeps — nothing derives from it and nothing remembers an older one — so minting it late is safe, and the account
436
+ // keeps it through the same `save(computer, patch)` the grant key uses.
437
+ const browseKey = c.browse || b64(crypto.getRandomValues(new Uint8Array(32)))
438
+ const grant = {
439
+ id: 'grant_' + b64(crypto.getRandomValues(new Uint8Array(12))).replace(/\+/g, '-').replace(/\//g, '_'),
440
+ source: 'session', computer: computer.id, workspace: c.workspace, peer: cc.tls,
441
+ credentials: { tr: c.key, ...(c.tinfoil ? { tinfoil: c.tinfoil } : {}), ...(c.venice ? { venice: c.venice } : {}), ...(c.github ? { github: c.github } : {}) },
442
+ ...(c.codeKey ? { accountKeys: true } : {}), // the account's keys: the Sentinel lets them spend only Witbitz's models (from its next image)
443
+ // THE ACCOUNT'S CONNECTIONS picked for this computer, and the GitHub App installation (docs/cloud-computer-connections.md):
444
+ // sealed to the Sentinel with their callKeys, which it spends through the standing Sentinel — never a service's token.
445
+ ...(Array.isArray(c.connections) && c.connections.length ? { connections: c.connections } : {}),
446
+ ...(c.githubApp ? { githubApp: { account: c.githubApp.account, id: c.githubApp.id, callKey: c.githubApp.callKey } } : {}),
447
+ // THE STANDING SENTINEL'S PINS (docs/standing-sentinel.md § step 1d (ii)): the cloud computer's Sentinel attests the standing one
448
+ // against these itself, then seals each connection's callKey to it for that call — so the standing Sentinel can keep the
449
+ // connection locked under the key instead of holding it. This device's trusted builds: a newer one it accepted by its release first.
450
+ ...((Array.isArray(c.connections) && c.connections.length) || c.githubApp ? { standing: trustedSentinelPins() } : {}),
451
+ // ★ THE SAME `policy` OBJECT THE BUNDLE GETS, not a second reading of the stored doc. The Sentinel and the enclave
452
+ // enforce independently, which is the point — but they must enforce the SAME policy, and two `normEgress` calls
453
+ // are two chances to disagree (witbitz-1c). Derived once above; both copies are that one result.
454
+ // ★ THE CUSTOM HOSTS RIDE THE GRANT, and this is the whole road behind "Hosts I choose". The parent forwards only
455
+ // {kms, code-relay} in every mode and refuses to hold a per-workspace list — rightly, since that would hand the
456
+ // operator every person's hosts, and host.py is not measured anyway. So the SEALED grant carries the list to the
457
+ // Sentinel, which is measured and pinned, and the parent asks it yes/no per host at dial time
458
+ // (docs/cloud-computer-egress.md § "Hosts I choose has no road behind it"). Same shape as the bundle's `egress`
459
+ // above and from the same `policy` object, so the two enforcers cannot disagree about what was chosen.
460
+ rules: { github: { pushPattern: PUSH_PATTERN }, egress: policy.mode === 'custom' ? { mode: policy.mode, hosts: policy.hosts } : { mode: policy.mode } },
461
+ keys: await sentinelKeys(grantKey),
462
+ expires: now() + GRANT_TTL_MS,
463
+ }
464
+ const sealedGrant = await sealTo(sentinel.key, sentinel.nonce, grant)
465
+ const sealed = await sealTo(cc.key, cc.nonce, {
466
+ deviceHalf: c.half,
467
+ index: `index-${create ? 1 : opened.version}`,
468
+ minVersion: Math.max(c.version, 1),
469
+ repo: '',
470
+ pairing: { name: computer.name, computerId: computer.id, secret: computer.secret, relay: computer.relay },
471
+ sentinel: sentinel.tls,
472
+ // github: GitHub CONNECTED (the app or a token) — the enclave lets the agent reach GitHub's hosts in every mode, still only
473
+ // through the Sentinel's broker (vm/policy.go; the owner, 2026-11-18: "GitHub when connected"). An older image ignores it.
474
+ ...(c.githubApp && c.githubApp.login ? { githubLogin: String(c.githubApp.login).slice(0, 39) } : {}), // git's name when the app's token cannot say who (vm/stub.go setGitIdentity)
475
+ egress: { ...(policy.mode === 'custom' ? { mode: policy.mode, hosts: policy.hosts } : { mode: policy.mode }), ...(c.github || c.githubApp ? { github: true } : {}) },
476
+ // ★ The browse key goes in the BUNDLE and never in the grant above. The split is the product claim: the
477
+ // Sentinel holds what the agent must never see (credentials); the cloud computer holds what it needs to act.
478
+ // A browse key is the second kind — putting it in the grant would make the Sentinel a party to every frame.
479
+ // Minted above when the entry had none, so a computer made before this shipped gains it on its next open.
480
+ // `private` rides the bundle so the ENCLAVE wipes the profile at open and close (browse.go) — a page-side wipe
481
+ // would be a promise about a machine the page cannot reach. Absent = the profile persists, as it always has.
482
+ browse: { key: browseKey, relay: computer.relay || RELAY_URL, ...(c.browsePrivate ? { private: true } : {}) },
483
+ create,
484
+ })
485
+ const refusedGrant = (g) => new CloudError(`the key guard refused the grant (${(g && g.error) || 'no reason'})`, { code: 'grant' })
486
+ let assigned
487
+ try {
488
+ const out = await call(await admitted({ action: 'handover', workspace: c.workspace, cid: opened.cid, grant: sealedGrant, assign: sealed }))
489
+ if (!out.granted || !out.granted.ok) throw refusedGrant(out.granted)
490
+ if (out.granted.github) { try { onGitHub(out.granted.github) } catch { /* a notice, never the opening's failure */ } } // the GitHub token, tested once by the Sentinel (github.mjs checkGitHubToken)
491
+ assigned = out.assigned || {}
492
+ } catch (e) {
493
+ if (!(e.status === 400 && /unknown action/.test(e.message))) throw e
494
+ // A controller from before handover: the same two steps, one call each.
495
+ const granted = await call({ action: 'op', workspace: c.workspace, cid: opened.cid, req: { op: 'grant', sealed: sealedGrant } })
496
+ if (!granted.ok) throw refusedGrant(granted)
497
+ if (granted.github) { try { onGitHub(granted.github) } catch { /* */ } }
498
+ assigned = await call({ action: 'op', workspace: c.workspace, cid: opened.cid, req: { op: 'assign', sealed } })
499
+ }
500
+ onStep('connecting')
501
+ // ★ THE SESSION HANDLE GOES OUT THROUGH A CALLBACK, NOT THE RETURN VALUE. What openCloud RETURNS is merged into the
502
+ // account's sealed entry, and `normCloudEntry` is an allowlist — a new field there is either dropped silently or
503
+ // persisted when it must not be. This handle is good for exactly one opening (the cid dies with the enclave, the
504
+ // nonce is spent on first use), so it lives in the page's memory and nowhere else.
505
+ onSession({ cid: opened.cid, enclaveKey: cc.key, browseNonce: assigned.browseNonce || '' })
506
+ return { live: false, version: Number.isInteger(assigned.version) ? assigned.version : opened.version, ...(c.grantKey ? {} : { grantKey }), ...(c.browse ? {} : { browse: browseKey }) }
507
+ }
508
+
509
+ /**
510
+ * Free browsing: open the whole web for the browser THE OWNER IS HOLDING, or close it again
511
+ * (docs/cloud-computer-free-browsing.md).
512
+ *
513
+ * ★★ WHAT AUTHENTICATES THIS IS THE DEVICE HALF, NOT THE ENVELOPE. Sealing to the enclave proves nothing — it
514
+ * derives against the enclave's PUBLISHED key, so anyone who can reach the service can seal a payload it will open.
515
+ * The half is the secret only this account holds, the enclave compares it in constant time against the one the
516
+ * assign carried, and a one-time nonce stops the service replaying a widen it saw once. Same shape as `assign`,
517
+ * for the same reason.
518
+ *
519
+ * ★ It REFUSES unless the controls are already held. Free browsing is what take-over buys; a page that could open
520
+ * the web without one would be offering Full with extra steps, which is the thing the owner struck.
521
+ *
522
+ * @param session the handle openCloud handed to `onSession` for THIS opening
523
+ * @returns {Promise<{nonce: string, egress: object, browse: object}>} the next nonce, and the enclave's own story
524
+ */
525
+ export async function setCloudFreeBrowsing(computer, session, on, { token, fetchImpl = fetch, api = CLOUD_API } = {}) {
526
+ const c = computer && computer.cloud
527
+ if (!c || !c.workspace || !c.half) throw new CloudError('this is not a cloud computer')
528
+ if (!session || !session.cid || !session.enclaveKey || !session.browseNonce) {
529
+ throw new CloudError('this computer was not opened by this page — reopen it before opening the web', { code: 'no_session' })
530
+ }
531
+ const nonce = crypto.getRandomValues(new Uint8Array(32))
532
+ const sealed = await sealTo(session.enclaveKey, nonce, { deviceHalf: c.half, nonce: session.browseNonce, free: !!on })
533
+ const t = await token()
534
+ const r = await fetchImpl(api, {
535
+ method: 'POST',
536
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + (typeof t === 'string' ? t : (t && t.token)) },
537
+ body: JSON.stringify({ action: 'op', workspace: c.workspace, cid: session.cid, ...(c.owner ? { owner: c.owner } : {}), req: { op: 'browse-policy', sealed } }),
538
+ })
539
+ const out = await r.json().catch(() => ({}))
540
+ // ⛑ A SPENT NONCE IS STILL SPENT ON A REFUSAL, and the enclave hands the next one back with the error — so the
541
+ // handle is updated before throwing, or a refused ask (no browser, controls not held, a second tab) would leave
542
+ // this page unable to try again with the reason fixed.
543
+ if (out && out.nonce) session.browseNonce = out.nonce
544
+ if (Number(r.status) >= 400 || out.error) throw new CloudError(out.error || `the computer refused (${r.status})`, { code: 'free_browsing' })
545
+ return { nonce: out.nonce, egress: out.egress, browse: out.browse }
546
+ }
547
+
548
+ /** Seal a bundle to the enclave's attested key — sealShare.js, shared with connections.js (one writer of that wire). */
549
+ export { sealTo }
550
+
551
+ /** Where a new session starts on a cloud computer: its workspace, the folder that is saved. */
552
+ export const CLOUD_HOME = '/work'
553
+
554
+ /**
555
+ * One opening at a time per cloud computer, and a pause after a failure so a page that keeps seeing it offline does
556
+ * not keep asking. The page calls ensure() whenever its cloud computer is offline; retry() is a tap on the error.
557
+ *
558
+ * ★ `allow` IS WHAT STOPS A FORGOTTEN TAB BILLING ALL NIGHT. A cloud computer closes itself after 30 minutes unused,
559
+ * and a Code page that is merely OPEN notices it go offline within seconds and opens it again — so the machine never
560
+ * stops, and a phone left on a bedside table cost a day's compute before anybody looked (2026-09-16). `ensure` is
561
+ * automatic and therefore asks first; `retry` is a person tapping and never does.
562
+ */
563
+ /**
564
+ * ONE OPENING, with what it must keep: a restored workspace's pending move spent first, the account keys' signed status (it
565
+ * renews the Tinfoil cap at a month change, or mints one that failed), then openCloud — and what the opening brings back that
566
+ * the entry must keep (a newer version, a grant key, a browse key) handed to `save(computer, patch)`. Rejects when the opening
567
+ * fails: cloudOpener (the app) turns that into its callbacks; the SDK (sdkComputers.js) lets it reach the builder.
568
+ */
569
+ // A CONNECTION'S CALLKEY IS ASKED AT OPEN, NOT KEPT (the owner, 2026-11-14: "Close the gaps"): in the hosted app the vault holds the
570
+ // account's callKeys (vaultConnKeys.js), so a computer's saved record names a connection by id (`held: 1`) and this asks the app for
571
+ // the keys (`callKeys(ids)` → { id: { callKey } }) for this one grant — they are sealed to the Sentinel and never saved. One the app
572
+ // does not answer is left out of this opening (the agent cannot spend it), and the rest open as before. A record with keys: as before.
573
+ export async function withCallKeys (computer, callKeys) {
574
+ const c = computer && computer.cloud; if (!c) return computer
575
+ const conns = Array.isArray(c.connections) ? c.connections : []
576
+ const want = [...conns.filter((x) => x && !x.callKey).map((x) => x.id), ...(c.githubApp && !c.githubApp.callKey ? [c.githubApp.id] : [])].filter(Boolean)
577
+ if (!want.length) return computer
578
+ let got = {}; try { got = (typeof callKeys === 'function' && (await callKeys(want))) || {} } catch { got = {} }
579
+ const keyOf = (id) => { const k = got[id]; const v = k && typeof k === 'object' ? k.callKey : k; return typeof v === 'string' && v ? v : '' }
580
+ const fill = (x) => { if (!x || x.callKey) return x; const k = keyOf(x.id); if (!k) return null; const { held: _h, ...rest } = x; return { ...rest, callKey: k } }
581
+ const next = { ...c, connections: conns.map(fill).filter(Boolean) }
582
+ if (!next.connections.length) delete next.connections
583
+ if (c.githubApp && !c.githubApp.callKey) { const g = fill(c.githubApp); if (g) next.githubApp = g; else delete next.githubApp }
584
+ return { ...computer, cloud: next }
585
+ }
586
+
587
+ export async function openCloudComputer (computer, { open = openCloud, move = rebindCloud, renew = cloudKeyStatus, mint = mintCloudKeys, onKeysRefused = () => {}, token, aws = null, save = () => {}, openOpts = {}, callKeys = null } = {}) {
588
+ // A workspace restored from a key file has to come over to this account before it can be opened at all; if that did not
589
+ // land at the restore, it is finished here. Its failure IS the opening's failure, and says why far better than the 403 an
590
+ // unmoved workspace would answer with.
591
+ if (computer.cloud.pendingMove) { await spendPendingMove(computer, { token, move }); save(computer, { pendingMove: '' }) }
592
+ // A PASTED-KEY COMPUTER MOVES TO THE ACCOUNT'S KEYS (the owner, 2026-11-20: "Move to account keys"): one made before 2026-10-12
593
+ // ran on keys pasted at creation, so it never had a Venice key — the zero-retention models are the account's alone. At its next
594
+ // opening it is given its own keys from the account, as a new one is, and stops using the pasted ones (a GitHub token stays).
595
+ // A refusal (three computers already, not signed in) leaves it on the pasted keys, opening as before.
596
+ if (!computer.cloud.codeKey && mint) {
597
+ const got = await (async () => {
598
+ let t = null
599
+ try { const g = await token(); t = typeof g === 'string' ? g : (g && g.token) || null } catch { t = null }
600
+ return t ? mint({ computerId: computer.id, name: computer.name, idToken: t }) : null
601
+ })().catch(() => null)
602
+ // ⚑ SAID, NOT SILENT (the owner's phone, 2026-11-20: three computers already, so the move was refused and the zero-retention
603
+ // models kept answering "no key … close it and open it again" — which could never help). Not signed in says nothing.
604
+ if (got && !got.ok && got.reason) { try { onKeysRefused(got.reason) } catch { /* a notice, never the opening's failure */ } }
605
+ if (got && got.ok) {
606
+ const patch = { key: got.tr, codeKey: got.codeKey, tinfoil: got.tinfoil || null, venice: got.venice || null } // null removes a pasted one (withCloud)
607
+ computer = { ...computer, cloud: { ...computer.cloud, ...patch } }
608
+ save(computer, patch)
609
+ }
610
+ }
611
+ // ACCOUNT KEYS (codeCloudKeys.js): a signed status first, as a laptop's connector does at start. Never holds the opening up.
612
+ if (computer.cloud.codeKey) {
613
+ const st = await renew(computer.cloud.codeKey).catch(() => null)
614
+ for (const f of ['tinfoil', 'venice']) { // a key minted (or sent again) server-side after the computer was made
615
+ if (st && st[f] && st[f] !== computer.cloud[f]) { computer = { ...computer, cloud: { ...computer.cloud, [f]: st[f] } }; save(computer, { [f]: st[f] }) }
616
+ }
617
+ }
618
+ const r = await open(await withCallKeys(computer, callKeys), { token, aws, ...openOpts }) // the keys for this grant only — never saved
619
+ const patch = {}
620
+ if (r && Number.isInteger(r.version) && r.version > (computer.cloud.version || 0)) patch.version = r.version
621
+ if (r && r.grantKey) patch.grantKey = r.grantKey
622
+ if (r && r.browse) patch.browse = r.browse // an older entry that had no browse key: kept, or the viewer link changes every open
623
+ if (Object.keys(patch).length) save(computer, patch)
624
+ return r
625
+ }
626
+
627
+ export const CALL_TIMEOUT_MS = 60_000 // one call to the cloud computer service (openCloud's call): longer than its slowest answer, shorter than forever
628
+ export function cloudOpener({ open = openCloud, move = rebindCloud, renew = cloudKeyStatus, mint = mintCloudKeys, onKeysRefused = () => {}, token, aws = null, callKeys = null, stale = {}, save = () => {}, onStep = () => {}, onSession = () => {}, onGitHub = () => {}, onDone = () => {}, onError = () => {}, allow = () => true, onHeld = () => {}, cooldownMs = 60_000, now = () => Date.now() } = {}) {
629
+ const busy = new Map() // id → { step, promise }
630
+ const failedAt = new Map()
631
+ const ensure = (computer, { auto = true } = {}) => {
632
+ if (!computer || !computer.cloud) return null
633
+ const id = computer.id
634
+ if (busy.has(id)) return busy.get(id).promise
635
+ if (failedAt.has(id) && now() - failedAt.get(id) < cooldownMs) return null
636
+ // Held back, not failed: nothing is wrong and nothing is retried on a timer. The page says so and waits for a tap.
637
+ if (auto && !allow(computer)) { onHeld(computer); return null }
638
+ const entry = { step: 'starting', promise: null }
639
+ busy.set(id, entry)
640
+ entry.promise = openCloudComputer(computer, { open, move, renew, mint, onKeysRefused: (why) => onKeysRefused(computer, why), token, aws, save, callKeys, openOpts: { ...stale, onStep: (s) => { entry.step = s; onStep(computer, s) }, onSession: (h) => onSession(computer, h), onGitHub: (v) => onGitHub(computer, v) } })
641
+ .then((r) => { failedAt.delete(id); onDone(computer, r) }, (e) => { failedAt.set(id, now()); onError(computer, e) })
642
+ .finally(() => { busy.delete(id) })
643
+ return entry.promise
644
+ }
645
+ return {
646
+ ensure,
647
+ retry: (computer) => { if (computer) failedAt.delete(computer.id); return ensure(computer, { auto: false }) },
648
+ step: (id) => (busy.has(id) ? busy.get(id).step : ''),
649
+ }
650
+ }