@witbitz/sdk 0.0.0-stage → 4.3.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -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/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
@@ -0,0 +1,388 @@
1
+ // codeComputers.js — the account's PAIRED COMPUTERS registry (docs/opencode-relay.md §3.1).
2
+ //
3
+ // A sealed `op:'state'` doc named 'computers' in the account's index room, beside 'index' and 'index2'. Every signed-in
4
+ // device reads it (roomSync.js) and hands the live entries to the Code section (codeView.js); the pairing tool
5
+ // (tools/opencode-pair.mjs) writes it from the computer. ONE merge rule for all of them, defined here:
6
+ //
7
+ // { v: 1, computers: { <id>: { name, relay, secret, pairedAt, mod } | { removed: true, mod } } }
8
+ //
9
+ // Last-writer-wins PER ENTRY on `mod`; on a tie a removal wins. A removal is a tombstone that keeps no secret, so an
10
+ // unpair propagates instead of being re-added by a device that has not heard of it yet.
11
+ //
12
+ // ⚠ A separate doc on purpose: older builds strip unknown fields from index2.code and write it back; they never touch a
13
+ // doc called 'computers', so they cannot unpair anyone.
14
+
15
+ import { takeCodeKey } from './codeCloudKeys.js' // a cloud computer's account-issued keys (validator)
16
+ import { normEgress } from './codeEgress.js' // what this computer may reach — validated here so a bad policy is refused where it was typed
17
+ import { gunzipB64 } from './compress.js' // a plain doc the computer wrote large arrives gzipped ({ z }) — confirmScannedComputer reads it
18
+
19
+ export const COMPUTERS_KEY = 'space:computers'
20
+ export const COMPUTERS_DOC = 'computers'
21
+
22
+ const ID = /^[A-Za-z0-9_-]{8,64}$/
23
+ const SECRET = /^[A-Za-z0-9_-]{43}$/
24
+ const okRelay = (u) => { try { const x = new URL(String(u)); return x.protocol === 'wss:' || (x.protocol === 'ws:' && ['127.0.0.1', 'localhost'].includes(x.hostname)) } catch { return false } }
25
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0) // a real number — not true, not "0x10"
26
+ // Entry maps have NO prototype: an id is only ever data, even one spelled like a built-in ("constructor", "__proto__").
27
+ const dict = (src) => Object.assign(Object.create(null), src || {})
28
+
29
+ /** One entry → its canonical shape, or null when it is not usable. */
30
+ export function normEntry(e) {
31
+ if (!e || typeof e !== 'object') return null
32
+ const mod = num(e.mod)
33
+ if (!mod) return null
34
+ if (e.removed) return { removed: true, mod }
35
+ if (typeof e.secret !== 'string' || !SECRET.test(e.secret) || !okRelay(e.relay)) return null
36
+ return { name: Array.from(String(e.name || 'computer')).slice(0, 80).join(''), relay: String(e.relay), secret: e.secret, pairedAt: num(e.pairedAt) || mod, mod, ...deviceOf(e) } // cut by character, never mid-emoji
37
+ }
38
+ // A computer the account's service REGISTERED at pairing (witbitz-code 1.15.5+, through a giver on the new service) carries its
39
+ // device key and that service: `spk` (the key, b64url) and `svc` (the service's address) — together or not at all. A computer
40
+ // paired before, or through an account on the old service, has neither and is never judged by the service (signedOutIds).
41
+ const SPK = /^[A-Za-z0-9_-]{40,128}$/
42
+ const okSvc = (u) => { try { const x = new URL(String(u)); return String(u).length <= 200 && (x.protocol === 'https:' || (x.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(x.hostname))) } catch { return false } }
43
+ const deviceOf = (e) => (e && SPK.test(String(e.spk || '')) && okSvc(e.svc) ? { spk: String(e.spk), svc: String(e.svc) } : {})
44
+
45
+ /** Any doc (or nothing) → { v: 1, computers: {…} } with only well-formed entries. */
46
+ export function normRegistry(doc) {
47
+ const out = { v: 1, computers: dict() }
48
+ const src = doc && typeof doc === 'object' && doc.computers && typeof doc.computers === 'object' ? doc.computers : {}
49
+ for (const [id, e] of Object.entries(src)) { if (!ID.test(id)) continue; const n = normEntry(e); if (n) out.computers[id] = n }
50
+ return out
51
+ }
52
+
53
+ /** Merge two registries: per id the higher `mod` wins; a tie goes to the removal. Pure. */
54
+ export function mergeRegistry(a, b) {
55
+ const x = normRegistry(a), y = normRegistry(b)
56
+ const out = { v: 1, computers: dict(x.computers) }
57
+ for (const [id, e] of Object.entries(y.computers)) {
58
+ const cur = out.computers[id]
59
+ if (!cur || e.mod > cur.mod || (e.mod === cur.mod && e.removed && !cur.removed)) out.computers[id] = e
60
+ }
61
+ return out
62
+ }
63
+
64
+ export const sameRegistry = (a, b) => JSON.stringify(sortKeys(normRegistry(a))) === JSON.stringify(sortKeys(normRegistry(b)))
65
+ function sortKeys(r) { const c = dict(); for (const id of Object.keys(r.computers).sort()) c[id] = r.computers[id]; return { v: 1, computers: c } }
66
+
67
+ /** The computers you can connect to, oldest pairing first: [{ id, name, relay, secret }]. */
68
+ export function liveComputers(reg) {
69
+ return Object.entries(normRegistry(reg).computers)
70
+ .filter(([, e]) => !e.removed)
71
+ .sort((p, q) => p[1].pairedAt - q[1].pairedAt || (p[0] < q[0] ? -1 : 1))
72
+ .map(([id, e]) => ({ id, name: e.name, relay: e.relay, secret: e.secret }))
73
+ }
74
+
75
+ /** Add or update one computer (the pairing tool's write). */
76
+ export function withComputer(reg, id, { name, relay, secret }, now = Date.now()) {
77
+ const prev = normRegistry(reg).computers[id]
78
+ const mod = Math.max(now, prev ? prev.mod + 1 : 0)
79
+ return mergeRegistry(reg, { computers: dict({ [id]: { name, relay, secret, pairedAt: prev && !prev.removed ? prev.pairedAt : now, mod } }) })
80
+ }
81
+
82
+ /** Does this id still need its pairing written? A RESTORE from a key file (codeKeyFile.js) finds the removal's tombstone
83
+ * here — an entry, but one that keeps no secret — so "already known" must not be read as "nothing to write". */
84
+ export function needsPairing(reg, id) {
85
+ const e = normRegistry(reg).computers[id]
86
+ return !e || !!e.removed
87
+ }
88
+
89
+ /** Tombstone one computer (unpair / "Remove" in Settings). */
90
+ export function withoutComputer(reg, id, now = Date.now()) {
91
+ const prev = normRegistry(reg).computers[id]
92
+ return mergeRegistry(reg, { computers: dict({ [id]: { removed: true, mod: Math.max(now, prev ? prev.mod + 1 : 0) } }) })
93
+ }
94
+
95
+ // ── THE SCAN, CONFIRMED BY A DEVICE OF THE ACCOUNT (state machines pass 9, C#3, step b) ──────────────────────────────
96
+ // A paired computer writes only the PLAIN 'computers' doc (it holds no account key), and every app folds that doc in by
97
+ // `mod` — so a computer removed on the phone could write itself back live and be listed again, and nothing told a scan the
98
+ // person made from a self-revive. Now the device that GAVE the keys, told by the computer's report which computer it
99
+ // paired (deviceLink.js `cid`), copies exactly that entry into the SEALED list ('xcomputers'), with a `mod` over any
100
+ // tombstone or older entry this account holds for it. Only a holder of the account key can write there, which is the point:
101
+ // the sealed copy then says "a device of this account confirmed this computer". (Step c — the merge no longer letting a
102
+ // plain entry outrank a sealed tombstone — ships only once computers send their id, or a re-scanned computer stays hidden.)
103
+
104
+ /** The sealed list's write for a confirmed scan: `plainDoc`'s live entry for exactly `cid`, with a `mod` that beats what
105
+ * `knownDoc` (the account's list as this device reads it) holds for that id — a removal, or another pairing's entry — or
106
+ * null when the plain doc has no live entry for it. Pure. */
107
+ export function confirmedEntry(plainDoc, cid, knownDoc, dev = null) {
108
+ if (!ID.test(String(cid || ''))) return null
109
+ const e = normRegistry(plainDoc).computers[cid]
110
+ if (!e || e.removed) return null
111
+ const k = normRegistry(knownDoc).computers[cid]
112
+ const mod = k && k.mod >= e.mod && (k.removed || k.secret !== e.secret) ? k.mod + 1 : e.mod
113
+ // THE DEVICE KEY THE SERVICE JUST REGISTERED (`dev`: { spk, svc }, from this giver — never from the computer's own write): kept
114
+ // in the sealed entry so a later sign-out takes it off the list (pruneSignedOutComputers). Its `mod` beats the plain entry and
115
+ // whatever this account holds for it, so no copy without the key wins a tie (every merge keeps the one it has on a tie).
116
+ const d = deviceOf(dev)
117
+ if (d.spk) return { v: 1, computers: dict({ [cid]: { ...e, ...d, mod: Math.max(mod, e.mod, k ? k.mod : 0) + 1 } }) }
118
+ return { v: 1, computers: dict({ [cid]: { ...e, mod } }) }
119
+ }
120
+
121
+ /** Confirm the computer a scan just paired. Three doors, each { status, state } like the account transport:
122
+ * `readKnown()` the account's list as this device reads it; `readPlain()` the PLAIN doc, raw; `write(doc)` the account
123
+ * store's sealed write (accountStores put: it merges per entry with what is there). → { ok, mod? , why? }. Never throws.
124
+ * Nothing is written when anything is unknown: a read that is not a 200, an entry missing or removed (logged). */
125
+ export async function confirmScannedComputer(cid, { readKnown, readPlain, write, dev = null, log = () => {} } = {}) {
126
+ const no = (why) => { try { log('confirm ' + String(cid || '').slice(0, 64) + ': ' + why + ' — nothing written') } catch { /* */ } return { ok: false, why } }
127
+ if (!ID.test(String(cid || ''))) return no('no computer named')
128
+ try {
129
+ const kr = await readKnown()
130
+ if (!(kr && kr.status === 200)) return no('the account\'s list could not be read (' + ((kr && kr.status) || 0) + ')')
131
+ const pr = await readPlain()
132
+ if (!(pr && pr.status === 200)) return no('the computer\'s list could not be read (' + ((pr && pr.status) || 0) + ')')
133
+ let plain = pr.state
134
+ if (plain && typeof plain === 'object' && typeof plain.z === 'string') plain = await gunzipB64(plain.z)
135
+ const doc = confirmedEntry(plain, cid, kr.state, dev)
136
+ if (!doc) return no('the computer\'s list has no live entry for it')
137
+ const wr = await write(doc)
138
+ if (!(wr && wr.status === 200)) return no('the sealed write was refused (' + ((wr && wr.status) || 0) + ')')
139
+ return { ok: true, mod: doc.computers[cid].mod }
140
+ } catch (e) { return no(String((e && e.message) || e).slice(0, 120)) }
141
+ }
142
+
143
+ // ── A COMPUTER SIGNED OUT OF THE ACCOUNT LEAVES THE LIST (docs/TODO.md; the owner, 2026-11-17: "fix it") ─────────────────
144
+ // A computer paired for Code is one of the account's devices on the new service, and a sign-out from another device wipes it —
145
+ // but then it can no longer write the removal of its own entry, so it stayed listed until someone pressed Remove. A device of the
146
+ // account now asks the service, once per load, about the computers whose key it registered (`spk` + `svc`, confirmedEntry), and
147
+ // removes the ones the service says are signed out — the way a manual Remove does, so both copies and every device follow.
148
+ // ONLY an answer naming the key removes: 'revoked' (signed out) or 'not_ours' (no device of this account — asked of the same
149
+ // service it was registered on). 'active', 'provisional' (never signed out), a key missing from the answer, an answer from
150
+ // another service, no answer (offline, an error, an account on the old service) — the entry stays. No key, no question.
151
+ export const SIGNED_OUT = Object.freeze(['revoked', 'not_ours'])
152
+
153
+ /** The live computers the service can be asked about: [{ id, name, spk, svc }]. */
154
+ export function registeredComputers(reg) {
155
+ return Object.entries(normRegistry(reg).computers).filter(([, e]) => !e.removed && e.spk && e.svc).map(([id, e]) => ({ id, name: e.name, spk: e.spk, svc: e.svc }))
156
+ }
157
+ /** The ids an answer ({ base, states }) signs out — only entries registered on `base`, only a state in SIGNED_OUT. Pure. */
158
+ export function signedOutIds(reg, answer) {
159
+ if (!answer || typeof answer !== 'object' || typeof answer.base !== 'string' || !answer.base || !answer.states || typeof answer.states !== 'object') return []
160
+ const st = answer.states
161
+ return registeredComputers(reg).filter((c) => c.svc === answer.base && Object.prototype.hasOwnProperty.call(st, c.spk) && SIGNED_OUT.includes(st[c.spk])).map((c) => c.id)
162
+ }
163
+ /** One pass: `load()` the list, `ask(spks)` → { base, states } | null (throws = unknown), `remove(id)` each signed-out one
164
+ * (the manual Remove). → { asked, removed: [{ id, name }] , why? }. Never throws; nothing is removed on anything unknown. */
165
+ export async function pruneSignedOutComputers({ load = loadRegistry, ask, remove, log = () => {} } = {}) {
166
+ const say = (line) => { try { log(line) } catch { /* */ } }
167
+ const reg = load()
168
+ const regd = registeredComputers(reg)
169
+ if (!regd.length || typeof ask !== 'function' || typeof remove !== 'function') return { asked: 0, removed: [] }
170
+ let answer = null
171
+ try { answer = await ask([...new Set(regd.map((c) => c.spk))].slice(0, 50)) } catch (e) { say('computers: the account service did not answer (' + String((e && (e.code || e.message)) || e).slice(0, 80) + ') — the list stays as it is'); return { asked: regd.length, removed: [], why: 'unknown' } }
172
+ if (!answer) return { asked: regd.length, removed: [], why: 'off' } // no account on the new service here
173
+ const now = load() // what the list holds NOW: an entry re-paired (a new key) or removed meanwhile is not judged by the old answer
174
+ const ids = signedOutIds(now, { base: answer.base, states: Object.fromEntries(Object.entries(answer.states || {}).filter(([spk]) => regd.some((c) => c.spk === spk))) })
175
+ const removed = []
176
+ for (const id of ids) {
177
+ const c = regd.find((x) => x.id === id)
178
+ try { await remove(id); removed.push({ id, name: c ? c.name : '' }); say('computers: "' + (c ? c.name : id) + '" was signed out of your account — taken off the list') } catch (e) { say('computers: could not take "' + (c ? c.name : id) + '" off the list (' + String((e && e.message) || e).slice(0, 80) + ')') }
179
+ }
180
+ return { asked: regd.length, removed }
181
+ }
182
+
183
+ // ── this device's cached copy (browser only) ─────────────────────────────────────────────────────────────────────
184
+ export function loadRegistry() { try { return normRegistry(JSON.parse(localStorage.getItem(COMPUTERS_KEY) || 'null')) } catch { return normRegistry(null) } }
185
+ export function saveRegistry(reg) { try { localStorage.setItem(COMPUTERS_KEY, JSON.stringify(normRegistry(reg))) } catch { /* private mode */ } }
186
+ /** Fold a remote copy into ours. Returns true when what this device holds changed. */
187
+ export function adoptRegistry(remote) {
188
+ const cur = loadRegistry()
189
+ const next = mergeRegistry(cur, remote)
190
+ if (sameRegistry(cur, next)) return false
191
+ saveRegistry(next)
192
+ return true
193
+ }
194
+ export function removeComputerLocally(id, now = Date.now()) { saveRegistry(withoutComputer(loadRegistry(), id, now)) }
195
+
196
+ // ── CLOUD COMPUTERS (docs/cloud-computer.md §10.4) ──────────────────────────────────────────────────────────────────
197
+ // A cloud computer is listed in 'computers' like any paired one (a relay and a secret: its connector runs inside the
198
+ // enclave). What only this account may know about it lives in a SECOND sealed doc, 'cloudComputers', keyed by the same id:
199
+ //
200
+ // { v: 1, cloud: { <id>: { workspace, half, key, tinfoil, github, grantKey, version, mod } | { removed: true, mod } } }
201
+ //
202
+ // `half` is the device's half of the workspace's disk key — lose it and the workspace cannot be opened again. `key`,
203
+ // `tinfoil` and `github` are the TrustedRouter key, Tinfoil key and GitHub token its agent uses — handed only to the
204
+ // host's Credential Sentinel, never to the cloud computer (docs/credential-sentinel.md §9). `grantKey` makes the keys that
205
+ // tag the Sentinel's asks and seal its log (codeSentinel.js). `version` is the newest saved workspace version this account has seen: a host
206
+ // offering an older one is refused. A separate doc for the same reason as above: an older build keeps only the fields it
207
+ // knows and would write the computers back without these. Same merge rule: last writer wins per entry, a removal on a tie.
208
+ export const CLOUD_KEY = 'space:cloud-computers'
209
+ export const CLOUD_DOC = 'cloudComputers'
210
+ const WORKSPACE = /^[a-z0-9]{20,40}$/
211
+ const HALF = /^[A-Za-z0-9+/]{43}=$/ // 32 bytes, base64
212
+
213
+ /**
214
+ * ★ ONE LIST, ITERATED BY BOTH ALLOWLISTS, because "remember to edit both" has now failed three times for three
215
+ * different fields — the owner secret (2026-09-14), and the egress policy (2026-09-17), each shipping INERT with
216
+ * nothing failing loudly, each found late by comparing an artifact rather than by the test meant to catch it. A
217
+ * capitalised comment saying "add it in both places" was read and half-obeyed by two careful people on different
218
+ * days. So the second allowlist stops existing as a separate thing: `normCloudEntry` here and `cloudOf` in
219
+ * opencodeApp.js both walk THIS, and adding a cloud field is one edit in one place.
220
+ *
221
+ * `take` returns the value to keep, or undefined to drop it. Dropping is always the safe direction: a field neither
222
+ * side can validate is absent, and absent means the strictest reading of whatever it controls.
223
+ */
224
+ export const CLOUD_FIELDS = [
225
+ { key: 'key', take: (v) => str400(v) }, // the TrustedRouter key its agent runs on
226
+ { key: 'tinfoil', take: (v) => str400(v) || undefined }, // optional: pictures and files for text-only models
227
+ { key: 'venice', take: (v) => str400(v) || undefined }, // optional: the zero-retention models (Venice) — an account-keyed computer's own
228
+ { key: 'github', take: (v) => str400(v) || undefined }, // optional: clone, push, pull requests
229
+ { key: 'grantKey', take: (v) => (HALF.test(String(v)) ? String(v) : undefined) }, // makes the Sentinel's ask tags and log keys
230
+ // The workspace's own secrets (codeCloud.js `newCloudSecrets`): `owner` is who it belongs to, on every call;
231
+ // `recovery` is the one the KEY FILE carries, which only moves it to a new owner; `pendingMove` is an old recovery
232
+ // secret a restore has not spent yet, kept until the move lands so a failed one can be tried again.
233
+ { key: 'owner', take: (v) => (SECRET.test(String(v)) ? String(v) : undefined) },
234
+ { key: 'recovery', take: (v) => (SECRET.test(String(v)) ? String(v) : undefined) },
235
+ { key: 'pendingMove', take: (v) => (SECRET.test(String(v)) ? String(v) : undefined) },
236
+ // What this computer may reach (codeEgress.js). ★ A POLICY THAT DOES NOT VALIDATE IS DROPPED, not kept and not
237
+ // "corrected": dropped, it reads back as `none` — the strictest mode — so a doc corrupted in transit, or written by
238
+ // a newer page, reaches NOTHING rather than something nobody chose.
239
+ { key: 'egress', take: (v) => { const r = normEgress(v); return r.policy && r.policy.mode !== 'none' ? r.policy : undefined } },
240
+ // The key the agent's browser is watched under (docs/cloud-computer.md § 12, spaces/public/browseSeal.js). It
241
+ // rides the sealed BUNDLE to the enclave and stays here for the viewer, which derives the relay channel from it —
242
+ // so the relay is told a hash and never the key. Same shape as the disk half: 32 bytes, base64.
243
+ { key: 'browse', take: (v) => (HALF.test(String(v)) ? String(v) : undefined) },
244
+ // PRIVATE BROWSING (2026-09-22, the anonymity work, point 4): the browser's profile — cookies, logins, history — is
245
+ // wiped every time this computer opens and again when it closes, inside the enclave (browse.go), never as a page-side
246
+ // promise. Absent = false: a computer made before this keeps its profile exactly as it did.
247
+ { key: 'browsePrivate', take: (v) => (v === true ? true : undefined) },
248
+ // THE ACCOUNT'S KEYS for this computer (codeCloudKeys.js, 2026-10-12): its id and the two private keys that open its sealed
249
+ // keys and sign its status — what renews the Tinfoil cap each month. Absent on a computer made with pasted keys.
250
+ { key: 'codeKey', take: takeCodeKey },
251
+ // THE ACCOUNT'S CONNECTIONS this computer's agent may use (docs/cloud-computer-connections.md): picked here, none by
252
+ // default (the owner, 2026-10-19). Each carries its callKey — the account's own material, which already rides the
253
+ // account (store.js space:connectionKeys) — and the tools picked, with those that run without asking.
254
+ { key: 'connections', take: takeCloudConnections },
255
+ // The Witbitz GitHub App installation that replaces a pasted token: its connection id and callKey, and the GitHub login.
256
+ { key: 'githubApp', take: (v) => { const r = takeConnRef(v); return r ? { ...r, login: String(v.login || '').slice(0, 100) } : undefined } },
257
+ // CLOSED, FOR EVERY DEVICE (2026-11-07, the implicit-state-machine review): when the person closed it (ms). The closed mark was
258
+ // the closing page's alone, so another device's open Code page saw "offline", took it for asleep and opened it again. A page
259
+ // opens it by itself only for someone who used it AFTER this (opencodeApp.js mayAutoOpen); an Open tap always does.
260
+ { key: 'closedAt', take: (v) => (Number.isFinite(v) && v > 0 && v < 1e14 ? Math.floor(v) : undefined) },
261
+ ]
262
+ const str400 = (v) => (typeof v === 'string' && v.length <= 400 ? v : '')
263
+ const CONN_ID = /^[A-Za-z0-9_-]{8,64}$/, CALL_KEY = /^[A-Za-z0-9+/]{43}=$/, ACCT = /^[^\s@]{1,200}@[^\s@]{1,63}$/, TOOL_NAME = /^[A-Za-z0-9_.\-]{1,64}$/
264
+ // `held: 1` and no callKey: the hosted app's vault holds the key (vaultConnKeys.js); it is asked for at each open (codeCloud.js
265
+ // withCallKeys) and never saved here
266
+ function takeConnRef (v) {
267
+ if (!v || typeof v !== 'object' || !ACCT.test(String(v.account || '')) || !CONN_ID.test(String(v.id || ''))) return null
268
+ if (CALL_KEY.test(String(v.callKey || ''))) return { account: String(v.account), id: String(v.id), callKey: String(v.callKey) }
269
+ return (v.held === 1 || v.held === true) && !v.callKey ? { account: String(v.account), id: String(v.id), held: 1 } : null
270
+ }
271
+ function takeCloudConnections (v) {
272
+ if (!Array.isArray(v)) return undefined
273
+ const out = []
274
+ for (const c of v.slice(0, 32)) {
275
+ const r = takeConnRef(c)
276
+ if (!r || !c.mcp || !Array.isArray(c.mcp.tools)) continue
277
+ const tools = c.mcp.tools.filter((t) => t && TOOL_NAME.test(String(t.name))).slice(0, 40).map((t) => ({
278
+ name: String(t.name), title: String(t.title || '').slice(0, 120), description: String(t.description || '').slice(0, 1000),
279
+ ...(t.inputSchema && typeof t.inputSchema === 'object' && !Array.isArray(t.inputSchema) && JSON.stringify(t.inputSchema).length <= 20000 ? { inputSchema: t.inputSchema } : {}),
280
+ }))
281
+ if (!tools.length) continue
282
+ const auto = (Array.isArray(c.mcp.auto) ? c.mcp.auto : []).map(String).filter((n) => tools.some((t) => t.name === n))
283
+ out.push({ ...r, label: String(c.label || '').slice(0, 80), host: String(c.host || '').slice(0, 253), mcp: { tools, auto } })
284
+ }
285
+ return out.length ? out : undefined
286
+ }
287
+
288
+ /** Copy every cloud field that survives its own validator from `src` onto `out`. Both allowlists end with this. */
289
+ export function takeCloudFields(src, out) {
290
+ for (const f of CLOUD_FIELDS) {
291
+ const v = f.take(src ? src[f.key] : undefined)
292
+ if (v !== undefined) out[f.key] = v
293
+ }
294
+ return out
295
+ }
296
+
297
+ export function normCloudEntry(e) {
298
+ if (!e || typeof e !== 'object') return null
299
+ const mod = num(e.mod)
300
+ if (!mod) return null
301
+ if (e.removed) return { removed: true, mod }
302
+ if (!WORKSPACE.test(String(e.workspace)) || !HALF.test(String(e.half))) return null
303
+ const version = Number.isInteger(e.version) && e.version >= 0 ? e.version : 0
304
+ return takeCloudFields(e, { workspace: e.workspace, half: e.half, version, mod })
305
+ }
306
+ export function normCloud(doc) {
307
+ const out = { v: 1, cloud: dict() }
308
+ const src = doc && typeof doc === 'object' && doc.cloud && typeof doc.cloud === 'object' ? doc.cloud : {}
309
+ for (const [id, e] of Object.entries(src)) { if (!ID.test(id)) continue; const n = normCloudEntry(e); if (n) out.cloud[id] = n }
310
+ return out
311
+ }
312
+ export function mergeCloud(a, b) {
313
+ const x = normCloud(a), y = normCloud(b)
314
+ const out = { v: 1, cloud: dict(x.cloud) }
315
+ for (const [id, e] of Object.entries(y.cloud)) {
316
+ const cur = out.cloud[id]
317
+ if (!cur || e.mod > cur.mod || (e.mod === cur.mod && e.removed && !cur.removed)) out.cloud[id] = e
318
+ }
319
+ return out
320
+ }
321
+ export const sameCloud = (a, b) => {
322
+ const s = (r) => { const c = dict(); for (const id of Object.keys(r.cloud).sort()) c[id] = r.cloud[id]; return JSON.stringify(c) }
323
+ return s(normCloud(a)) === s(normCloud(b))
324
+ }
325
+ /** Add a cloud computer, or change one (a newer version). The version never goes down, whatever the caller passes. */
326
+ export function withCloud(reg, id, fields, now = Date.now()) {
327
+ const prev = normCloud(reg).cloud[id]
328
+ const live = prev && !prev.removed ? prev : null
329
+ // ★ A FIELD SENT AS null IS REMOVED (the owner, 2026-11-18: "I tried to turn private off but couldn't"): a save is merged over
330
+ // the entry, so a field the page DELETED (Private off, the last Connection unpicked, GitHub disconnected) came back from it.
331
+ const next = { ...(live || {}), ...fields, mod: Math.max(now, prev ? prev.mod + 1 : 0) }
332
+ for (const [k, v] of Object.entries(fields || {})) if (v === null) delete next[k]
333
+ if (live) next.version = Math.max(live.version, Number.isInteger(fields.version) ? fields.version : 0)
334
+ return mergeCloud(reg, { cloud: dict({ [id]: next }) })
335
+ }
336
+ export function withoutCloud(reg, id, now = Date.now()) {
337
+ const prev = normCloud(reg).cloud[id]
338
+ if (!prev) return normCloud(reg)
339
+ return mergeCloud(reg, { cloud: dict({ [id]: { removed: true, mod: Math.max(now, prev.mod + 1) } }) })
340
+ }
341
+ /** The live computers, each cloud one carrying what opening it needs: [{ id, name, relay, secret, cloud? }]. */
342
+ export function withCloudInfo(computers, cloudReg) {
343
+ const cloud = normCloud(cloudReg).cloud
344
+ return computers.map((c) => {
345
+ const e = cloud[c.id]
346
+ if (!e || e.removed) return c
347
+ const { mod, ...part } = e
348
+ return { ...c, cloud: part }
349
+ })
350
+ }
351
+ // ⛔ A RECORD THAT NAMES A CONNECTION BY ID (`held: 1`) IS DROPPED BY ANY BUILD BEFORE THIS ONE: its takeConnRef wanted a callKey, so
352
+ // an older device (Official behind Beta, the same account) loses the connection at load and its next save syncs the loss to every
353
+ // device (review, 2026-11-14). This build READS such records (takeConnRef, codeCloud.js withCallKeys); nothing WRITES them until every
354
+ // served hosted build reads them — turn this on once the hosted app's floor (spaces/channels-policy.json tenant.minVersion) is at or
355
+ // above the release that carries this (docs/TODO.md § 4). Off: the Code bridge hands whole keys and records keep them, as before.
356
+ export const CLOUD_HELD_REFS = false
357
+ // A CLOUD COMPUTER'S SAVED CALLKEYS MOVE INTO THE VAULT (the hosted app; the owner, 2026-11-14: "Close the gaps"). A record saved
358
+ // before kept each picked connection's callKey whole; they are asked into the vault (`hold(keys)` → the ids it now holds under THAT
359
+ // key — store.js holdCallKeysInVault), and a record keeps `held: 1` only for those. The Code page asks for the keys at each open
360
+ // (codeCloud.js withCallKeys). No answer, or none held: the record stays whole. → how many computers changed.
361
+ export async function moveCloudCallKeys ({ hold, load = loadCloud, save = saveCloud, push = () => {} } = {}) {
362
+ const refs = (e) => [...(Array.isArray(e.connections) ? e.connections : []), ...(e.githubApp ? [e.githubApp] : [])]
363
+ const keys = {}
364
+ for (const e of Object.values(load().cloud)) if (e && !e.removed) for (const c of refs(e)) if (c && c.callKey && !keys[c.id]) keys[c.id] = { callKey: c.callKey, account: c.account || '', label: c.label || '', host: c.host || '' }
365
+ if (!Object.keys(keys).length) return 0
366
+ let ids = []; try { ids = (await hold(keys)) || [] } catch { ids = [] }
367
+ const held = new Set(ids); if (!held.size) return 0
368
+ const strip = (c) => { if (!c || !c.callKey || !held.has(c.id) || keys[c.id].callKey !== c.callKey) return c; const { callKey: _k, ...rest } = c; return { ...rest, held: 1 } }
369
+ let reg = load(), n = 0
370
+ for (const [id, e] of Object.entries(reg.cloud)) {
371
+ if (!e || e.removed) continue
372
+ const patch = {}
373
+ if (Array.isArray(e.connections) && e.connections.some((c) => strip(c) !== c)) patch.connections = e.connections.map(strip)
374
+ if (e.githubApp && strip(e.githubApp) !== e.githubApp) patch.githubApp = strip(e.githubApp)
375
+ if (Object.keys(patch).length) { reg = withCloud(reg, id, patch); n++ }
376
+ }
377
+ if (n) { save(reg); try { push() } catch { /* the next push carries it */ } }
378
+ return n
379
+ }
380
+ export function loadCloud() { try { return normCloud(JSON.parse(localStorage.getItem(CLOUD_KEY) || 'null')) } catch { return normCloud(null) } }
381
+ export function saveCloud(reg) { try { localStorage.setItem(CLOUD_KEY, JSON.stringify(normCloud(reg))) } catch { /* private mode */ } }
382
+ export function adoptCloud(remote) {
383
+ const cur = loadCloud()
384
+ const next = mergeCloud(cur, remote)
385
+ if (sameCloud(cur, next)) return false
386
+ saveCloud(next)
387
+ return true
388
+ }
package/codeEgress.js ADDED
@@ -0,0 +1,123 @@
1
+ // codeEgress.js — what a cloud computer is allowed to reach, as the person chose it (docs/cloud-computer-egress.md).
2
+ //
3
+ // Pure: no DOM, no storage, no network. The page uses it to validate what it stores and seals; the settings sheet uses
4
+ // it to say what a choice means; and `egressHash` lets the page check the policy the ENCLAVE reports having loaded
5
+ // against the one it sealed — which is the whole point of the design and the only part that cannot be faked by
6
+ // anything between.
7
+ //
8
+ // ★ THIS MUST REFUSE EXACTLY WHAT THE ENCLAVE'S parsePolicy REFUSES. If the page can store a policy the enclave will
9
+ // reject, the refusal arrives at open time as "your computer would not start", with the person nowhere near the
10
+ // setting that caused it. Refusing here puts the error next to the field.
11
+ //
12
+ // ★ THERE IS NO 'full'. The owner struck it on 2026-09-17: a mode with unrestricted egress makes "the operator cannot
13
+ // read your workspace" stop meaning anything, because the agent can post the workspace anywhere. It is refused BY
14
+ // NAME rather than merely absent from the list, so a stored doc that names it fails loudly instead of falling back
15
+ // to something permissive.
16
+
17
+ export const EGRESS_MODES = ['none', 'trusted', 'custom']
18
+ export const MAX_CUSTOM_HOSTS = 64
19
+
20
+ /** What `trusted` reaches, for the page to SHOW. The enclave's copy is the authoritative one — this is a label, and if
21
+ * the two ever disagree the attested story is right and this is stale.
22
+ *
23
+ * ★ GITHUB IS IN THE POLICY, not outside it, and that is a security decision rather than a tidiness one. GitHub is a
24
+ * WRITE channel with the person's token: `git push` sends a workspace somewhere it can be read. Leaving it always-on
25
+ * under `none` would put back exactly the hole we refused on the registry side, where a relay that could not see a
26
+ * PUT was rejected for that reason alone. So `none` closes GitHub too — no push, no API, no raw fetch — because that
27
+ * is what the word has to mean once the attested story claims it. Custom can name these hosts explicitly.
28
+ * (witbitz-1c's review found them being served BEFORE the policy check: a workspace sealed `none` attested 0 hosts
29
+ * while five GitHub hosts were reachable with the real token. The story was lying, which is the worst failure this
30
+ * design has.) */
31
+ export const TRUSTED_HOSTS = [
32
+ 'api.github.com', 'codeload.github.com', 'files.pythonhosted.org', 'github.com',
33
+ 'objects.githubusercontent.com', 'pypi.org', 'raw.githubusercontent.com', 'registry.npmjs.org',
34
+ ]
35
+
36
+ /** ★ The ONE channel outside the policy in every mode, including `none`: the model. Without it there is no agent at
37
+ * all. It is named in the UI rather than hidden, because "reaches nothing" would otherwise be a lie a person could
38
+ * act on — what you send the model is seen by the model, which is what the per-turn receipt is for. */
39
+ export const ALWAYS_ON = 'the model, through the Credential Sentinel'
40
+
41
+ const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
42
+ const IPV4 = /^\d{1,3}(?:\.\d{1,3}){3}$/
43
+
44
+ /**
45
+ * A hostname the person may add to a custom list. Deliberately narrow:
46
+ * · lower-cased, DNS labels only, at least two of them — a bare word is a typo or an internal name that will resolve
47
+ * to nothing here, and either way it should be rejected where it was typed;
48
+ * · never an IP literal — the allow-list is checked by NAME in both enforcers, so an address would be a hole that
49
+ * looks like an entry;
50
+ * · no wildcards. `.example.com` would let one entry stand for a domain the person has not seen, and the point of
51
+ * Custom is that they can read their own list. (The enclave's allow.go understands suffixes; we do not offer them.)
52
+ */
53
+ export function normHost(h) {
54
+ const s = String(h || '').trim().toLowerCase().replace(/\.$/, '')
55
+ if (!s || s.length > 253 || IPV4.test(s) || s.includes('/') || s.includes(':') || s.includes('*')) return ''
56
+ const parts = s.split('.')
57
+ if (parts.length < 2 || !parts.every((p) => LABEL.test(p))) return ''
58
+ if (!/^[a-z]{2,63}$/.test(parts[parts.length - 1])) return '' // a numeric or empty TLD is not a name
59
+ return s
60
+ }
61
+
62
+ /**
63
+ * A stored or typed policy → the canonical one, or null with a reason.
64
+ * @returns {{ policy: {mode: string, hosts: string[]} } | { error: string }}
65
+ */
66
+ export function normEgress(e) {
67
+ const mode = String((e && e.mode) || 'none').trim().toLowerCase()
68
+ if (mode === 'full') return { error: 'there is no unrestricted mode — choose the hosts this computer may reach' }
69
+ if (!EGRESS_MODES.includes(mode)) return { error: `unknown mode "${mode.slice(0, 20)}"` }
70
+ const raw = Array.isArray(e && e.hosts) ? e.hosts : []
71
+ if (mode !== 'custom') {
72
+ // ★ `trusted` carries no list of its own: its hosts are the IMAGE's, and are measured with it. A stored list here
73
+ // would be a second source of truth for something the attestation already answers.
74
+ if (raw.length) return { error: `${mode} does not take a list of hosts` }
75
+ return { policy: { mode, hosts: [] } }
76
+ }
77
+ const hosts = []
78
+ for (const h of raw) {
79
+ const n = normHost(h)
80
+ if (!n) return { error: `"${String(h).slice(0, 40)}" is not a hostname this computer can be given` }
81
+ if (!hosts.includes(n)) hosts.push(n)
82
+ }
83
+ if (!hosts.length) return { error: 'add at least one host, or choose another mode' }
84
+ if (hosts.length > MAX_CUSTOM_HOSTS) return { error: `at most ${MAX_CUSTOM_HOSTS} hosts` }
85
+ return { policy: { mode, hosts: hosts.sort() } }
86
+ }
87
+
88
+ /**
89
+ * The exact bytes both sides hash. Sorted, lower-cased, one host per line under the mode — so the page and the enclave
90
+ * agree on the preimage without sharing code.
91
+ *
92
+ * ★ IF THIS EVER DISAGREES WITH THE ENCLAVE'S CANONICAL FORM, the check it exists for silently passes nothing: every
93
+ * comparison would fail and the page would report drift that is not there, or — worse, if someone "fixes" it by
94
+ * comparing loosely — stop comparing at all. It is pinned by a vector in the tests on both sides.
95
+ */
96
+ export function canonicalEgress(policy) {
97
+ const p = (policy && policy.mode) ? policy : { mode: 'none', hosts: [] }
98
+ return ['witbitz-egress-v1', p.mode, ...(p.hosts || []).slice().sort()].join('\n') + '\n' + (p.github ? '+github\n' : '') // github: GitHub connected (policy.go)
99
+ }
100
+
101
+ /** sha256 of the canonical form, hex — what the enclave reports as `policyHash` for the policy it LOADED. */
102
+ export async function egressHash(policy) {
103
+ const bytes = new TextEncoder().encode(canonicalEgress(policy))
104
+ const digest = await crypto.subtle.digest('SHA-256', bytes)
105
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
106
+ }
107
+
108
+ /** One line for a person: what this computer may reach, in words rather than a mode name. */
109
+ export function describeEgress(policy) {
110
+ const p = (policy && policy.mode) ? policy : { mode: 'none', hosts: [] }
111
+ // ★ Every sentence names the model channel, because it is on in every mode and a person reading "reaches nothing"
112
+ // would otherwise believe something false about where their work can go.
113
+ // ★★ AND EVERY SENTENCE NAMES THE BROWSER (the owner, 2026-10-23: "my cloud computer in the regular app is completely
114
+ // open"). Since 2026-09-21 its browser reaches the whole web by construction (docs/cloud-computer-free-browsing.md),
115
+ // and the agent can drive it — so this mode limits the agent's OWN network only; "reaches nothing" alone was false.
116
+ let own
117
+ if (p.mode === 'none') own = `Its own network reaches nothing on the internet — only ${ALWAYS_ON}`
118
+ else if (p.mode === 'trusted') own = `Its own network can fetch packages and reach GitHub (${TRUSTED_HOSTS.length} hosts), plus ${ALWAYS_ON}`
119
+ else { const n = (p.hosts || []).length; own = `Its own network can reach ${n} host${n === 1 ? '' : 's'} you chose (${(p.hosts || []).join(', ')}), plus ${ALWAYS_ON}` }
120
+ return `${own}. ${BROWSER_OPEN}`
121
+ }
122
+ /** The browser's half, the same in every mode. */
123
+ export const BROWSER_OPEN = 'Its browser reaches the whole web in every mode, and the agent can use it — so through the browser the agent can reach the web too.'
@@ -0,0 +1,17 @@
1
+ // codeFilesRoutes.js — the Files sheet's two routes and their limits, shared by the page (codeFiles.js) and the connector
2
+ // (tools/code-files.mjs), as codeOutputs.js shares OUTPUT_ROUTE. Both routes are the CONNECTOR's own: answered on the computer,
3
+ // never forwarded to OpenCode, so neither is on the relay's allowlist (codeRelay.js).
4
+ export const FILES_DOWNLOAD_ROUTE = '/witbitz/download' // GET ?session=&path= → { name, kind, mime, size, mtime, b64 }
5
+ export const FILES_UPLOAD_ROUTE = '/witbitz/upload' // POST ?session= body { dir, name, b64, replace? } → { ok, name, path, size }
6
+ // One file's bytes, base64, in one relay message: the relay reassembles at most 32 MiB (codeRelay.js MAX_TOTAL), and base64
7
+ // is 4/3 of the bytes — so 20 MB, the same as a reply's file preview (tools/code-attachments.mjs MAX_SERVE_BYTES).
8
+ export const MAX_FILE_TRANSFER = 20 * 1024 * 1024
9
+
10
+ /** "report.pdf" taken → "report (2).pdf", then (3)… — Keep both, never overwriting. `taken(name)` says whether a name is used. */
11
+ export function keepBothName(name, taken) {
12
+ const s = String(name || '')
13
+ const dot = s.lastIndexOf('.')
14
+ const base = dot > 0 ? s.slice(0, dot) : s, ext = dot > 0 ? s.slice(dot) : ''
15
+ for (let n = 2; n < 1000; n++) { const c = `${base} (${n})${ext}`; if (!taken(c)) return c }
16
+ return `${base} (${Date.now()})${ext}`
17
+ }
package/codeMkdir.js ADDED
@@ -0,0 +1,8 @@
1
+ // spaces/public/codeMkdir.js — the page-side constant + helper for "New folder" in the New-session picker
2
+ // (tools/code-mkdir.mjs is the connector side; this module holds what the browser needs, so no fs leaks into the page).
3
+ // The route is connector-owned and never reaches OpenCode — the page names the home (directory) and the relative path
4
+ // under it (path) it is already browsing, plus one clean leaf (name). Pure: no DOM, no fs.
5
+ export const MKDIR_ROUTE = '/witbitz/mkdir'
6
+
7
+ /** Build the mkdir request path: `/witbitz/mkdir?path=<rel>` (withDir appends `directory=`). */
8
+ export const mkdirPath = (rel) => MKDIR_ROUTE + (rel ? '?path=' + encodeURIComponent(rel) : '')
package/codeModes.js ADDED
@@ -0,0 +1,57 @@
1
+ // spaces/public/codeModes.js — the Code composer's ACCEPT EDITS mode, as OpenCode permission rules.
2
+ //
3
+ // The owner, beside Claude Code's modes: "What about an equivalent of accept edits" — and chose "secrets still ask".
4
+ // Unlike Auto (decided by the connector), Accept edits is decided by OpenCode ITSELF: the page appends rules to the
5
+ // session (PATCH /session/:id {permission}), so it holds with every phone closed and on any connector.
6
+ //
7
+ // Measured on opencode 1.18.30 (the evaluator and matcher below are copied from its bundle, and a real turn confirmed it):
8
+ // • evaluate = rules.flat().findLast(match permission && match pattern) ?? ask — the LAST matching rule wins
9
+ // • PATCH /session/:id {permission} APPENDS to the session's rules; it never replaces them
10
+ // • the edit/write/apply_patch tools ask as `edit`, with the path RELATIVE to the worktree ("src/a.ts", ".env")
11
+ // • a wildcard `*` crosses "/", the match is anchored and case-sensitive
12
+ // So switching appends: Accept edits = allow every edit, then ask again for protected files; Manual = one "ask" rule.
13
+ // Edits outside the project still ask first through `external_directory`, which these rules never touch.
14
+
15
+ /** OpenCode 1.18 Wildcard.match. */
16
+ export function wildcardMatch(str, pattern) {
17
+ const s = String(str).replaceAll('\\', '/')
18
+ let re = String(pattern).replaceAll('\\', '/').replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
19
+ if (re.endsWith(' .*')) re = re.slice(0, -3) + '( .*)?'
20
+ return new RegExp('^' + re + '$', 's').test(s)
21
+ }
22
+
23
+ /** OpenCode 1.18 Permission.evaluate over one ruleset → 'allow' | 'ask' | 'deny'. */
24
+ export function evaluateRules(permission, pattern, rules) {
25
+ const hit = (Array.isArray(rules) ? rules : []).findLast((r) => r && wildcardMatch(permission, r.permission) && wildcardMatch(pattern, r.pattern))
26
+ return hit ? hit.action : 'ask'
27
+ }
28
+
29
+ // Protected files — the same families tools/code-auto.mjs keeps out of Auto's fast allow. Each name is matched at the
30
+ // project root AND under any folder ("*/" — a wildcard crosses "/"). OpenCode's match is case-sensitive, so the common
31
+ // spellings are listed.
32
+ const DIRS = ['.git', '.ssh', '.aws', '.gnupg', '.kube', '.docker']
33
+ const NAMES = ['.env', '.env.*', '.npmrc', '.netrc', '.pypirc', ...['id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519'].flatMap((k) => [k, k + '.pub'])]
34
+ const KEY_EXTS = ['pem', 'key', 'p12', 'pfx', 'jks', 'keystore'].flatMap((e) => [e, e.toUpperCase()])
35
+ const WORDS = ['secret', 'Secret', 'SECRET', 'credential', 'Credential', 'CREDENTIAL']
36
+ const SAFE_ENV = ['.env.example', '.env.sample', '.env.template', '.env.dist']
37
+
38
+ const rule = (pattern, action) => ({ permission: 'edit', pattern, action })
39
+ const atAnyDepth = (p) => [p, '*/' + p]
40
+
41
+ /** Appended to switch a session to Accept edits. */
42
+ export function acceptEditsRules() {
43
+ return [
44
+ rule('*', 'allow'),
45
+ ...NAMES.flatMap(atAnyDepth).map((p) => rule(p, 'ask')),
46
+ ...SAFE_ENV.flatMap(atAnyDepth).map((p) => rule(p, 'allow')), // a template is not a secret — but only here: the
47
+ ...DIRS.flatMap((d) => atAnyDepth(d + '/*')).map((p) => rule(p, 'ask')), // asks after it still win (.git/…, secrets/…)
48
+ ...KEY_EXTS.map((e) => rule('*.' + e, 'ask')),
49
+ ...WORDS.map((w) => rule('*' + w + '*', 'ask')),
50
+ ]
51
+ }
52
+
53
+ /** Appended to go back: the last matching rule wins, so one rule undoes all of the above. */
54
+ export const askEditsRules = () => [rule('*', 'ask')]
55
+
56
+ /** Whether a session's rules let an ordinary edit through without asking — how the chip knows the mode. */
57
+ export const acceptsEdits = (rules) => evaluateRules('edit', 'src/index.ts', rules) === 'allow'