@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
@@ -0,0 +1,1009 @@
1
+ // sdkComputers.js — `wb.computers`: the person's CLOUD COMPUTERS from a builder's page (docs/sdk-cloud-computers.md; the owner,
2
+ // 2026-10-24: "The user pays, full sdk set, the keys are with the user"). The same engine as the Code section — the opening
3
+ // (codeCloud.js: attest the enclave and its Sentinel against the published images, seal the grant and the bundle), the sealed
4
+ // relay to its connector (codeTransport.js), the connector's own route list (codeRelay.js) — and what the Code section keeps,
5
+ // kept in THIS app's account index (sdkAccount.js), sealed like every account document: a computer made here is listed here.
6
+ //
7
+ // The keys are the person's: the workspace's half, the relay secret, the owner/recovery secrets, the model keys and the AWS
8
+ // key that pays for its hours (awsKey.js) sit in the sealed account documents and in this page's memory while it works —
9
+ // as room keys do without a vault. In vault mode (docs/sdk-cloud-computers.md phase 3) they stay in the vault.
10
+ //
11
+ // Every dependency is injectable (`deps`) so the whole thing runs against fakes in tests.
12
+
13
+ import { attachmentWarning, partsFor, parseModel, normRevert, ocPermissionRuleset, OC_ASK_PERMISSIONS } from './opencodeWire.js'
14
+ import { pageQuery, cursorBefore, mayHaveMore, mergeTail, PAGE } from './codeHistory.js'
15
+ import { undoTarget } from './codeUndo.js'
16
+ import { commandTurn, normCommands } from './codeCommands.js'
17
+ import { acceptEditsRules, acceptsEdits, unsuitableCodeModels, wildcardMatch } from './codeModes.js'
18
+ import { sentinelKeys, askGenuine, decideTag } from './codeSentinel.js'
19
+ import { cachedSessions, loadSession, saveSession, clearSession, saveList, loadList, slimSession, prune, forgetComputer } from './codeCache.js'
20
+ import { idb } from './idb.js'
21
+ import { languageNudge, withLanguage } from './codeLanguage.js'
22
+ import { PendingCodeDrafts, providerRefusal, firstOutputStarted, promptLanded } from './codeSent.js'
23
+ import { normProgress, progressLine } from './codeProgress.js'
24
+ import { codeAgentPreference, computerModelPreference } from './sdkAccountSections.js'
25
+ import { FOLDER_ROUTE } from './codeFolders.js'
26
+ import { childIdsOf, childFromEvent, refusalOf, PERSON_REFUSAL } from './codeSubagents.js'
27
+ import { mkdirPath } from './codeMkdir.js'
28
+ import { CLOUD_HOME, newCloudComputer, openCloudComputer, closeCloud, CloudError } from './codeCloud.js'
29
+ import { mintCloudKeys } from './codeCloudKeys.js'
30
+ import { relayTransport, deletePairedCodeSession } from './codeTransport.js'
31
+ import { CLOUD_PICKS_MAX_BYTES, CLOUD_DOC, COMPUTERS_DOC, normCloud, mergeCloud, withCloud, withoutCloud, normRegistry, mergeRegistry, withComputer, withoutComputer, liveComputers } from './codeComputers.js'
32
+ import { normEgress } from './codeEgress.js'
33
+ import { AWS_KEY_DOC, ensureAwsKey, signAws, awsKeyStatus } from './awsKey.js'
34
+ import { sealDoc, openDoc } from './accountSeal.js'
35
+ import { CODE_KEYS_REVOKE } from './codeOrphanKeys.js' // the one address (it was written three times — sync sweep backlog P3)
36
+ import { FILES_DOWNLOAD_ROUTE, FILES_UPLOAD_ROUTE, MAX_FILE_TRANSFER, keepBothName } from './codeFilesRoutes.js' // the Files sheet's routes (codeFiles.js)
37
+ import { validAttachmentRef, parseAttachmentNote, ATTACHMENT_ROUTE } from './codeAttachments.js'
38
+ import { OUTPUT_ROUTE, replyOutputs } from './codeOutputs.js' // what a reply produced, screenshots included (codeOutputCards.js)
39
+ import { watchUrl } from './codeBrowse.js'
40
+ import { setSessionPrivate } from './sdkBrowserPrivate.js'
41
+
42
+ const fail = (code, message, extra = {}) => Object.assign(new Error('witbitz: ' + message), { code, ...extra })
43
+ const SEG = /^(?!\.)[A-Za-z0-9_.-]{1,128}$/
44
+ const seg = (v, what) => { const s = String(v || ''); if (!SEG.test(s)) throw fail('invalid_argument', `${what} is not an id`); return encodeURIComponent(s) }
45
+ const withDir = (p, dir) => (dir ? p + (p.includes('?') ? '&' : '?') + 'directory=' + encodeURIComponent(dir) : p)
46
+ const sidQ = (sid) => encodeURIComponent(seg(sid, 'session') && String(sid))
47
+ const absPath = (p) => { const s = String(p || ''); if (!s.startsWith('/') || s.length > 4096 || /[\0\r\n]/.test(s)) throw fail('invalid_argument', 'a path on the computer is absolute (it starts with /)'); return s }
48
+ // bytes in any common shape → base64 (a builder hands a Blob from a file input, a Uint8Array, or base64 already)
49
+ async function toB64 (data) {
50
+ if (typeof data === 'string') {
51
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(data)) throw fail('invalid_argument', 'upload data as a string is base64')
52
+ const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0
53
+ const digits = data.length - padding
54
+ if (digits % 4 === 1 || (padding && data.length % 4 !== 0)) throw fail('invalid_argument', 'upload data as a string is base64')
55
+ if (Math.floor(digits * 3 / 4) > MAX_FILE_TRANSFER) throw fail('too_large', `a file is at most ${MAX_FILE_TRANSFER / 1024 / 1024} MB`)
56
+ return data
57
+ }
58
+ if (data && typeof data.size === 'number' && data.size > MAX_FILE_TRANSFER) throw fail('too_large', `a file is at most ${MAX_FILE_TRANSFER / 1024 / 1024} MB`) // a Blob: before reading it
59
+ let u8 = null
60
+ if (data instanceof Uint8Array) u8 = data
61
+ else if (data instanceof ArrayBuffer) u8 = new Uint8Array(data)
62
+ else if (data && typeof data.arrayBuffer === 'function') u8 = new Uint8Array(await data.arrayBuffer())
63
+ if (!u8) throw fail('invalid_argument', 'upload data is a Blob, a File, an ArrayBuffer, a Uint8Array or base64')
64
+ if (u8.length > MAX_FILE_TRANSFER) throw fail('too_large', `a file is at most ${MAX_FILE_TRANSFER / 1024 / 1024} MB`)
65
+ let bin = ''; for (let i = 0; i < u8.length; i += 0x8000) bin += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000))
66
+ return btoa(bin)
67
+ }
68
+
69
+ /** What a builder sees of a computer: never a secret. */
70
+ const infoOf = (id, reg, cloud) => {
71
+ const r = reg.computers[id] || {}, c = cloud.cloud[id] || {}
72
+ return { id, name: r.name || 'Cloud computer', cloud: true, version: Number(c.version) || 0, egress: (c.egress && c.egress.mode) || 'none' }
73
+ }
74
+
75
+ export class Computers {
76
+ /** @param {object} wb the Witbitz client; @param {object} [deps] injectable engine (tests) */
77
+ constructor (wb, deps = {}) {
78
+ this._wb = wb
79
+ this._d = { open: openCloudComputer, close: closeCloud, mint: mintCloudKeys, transport: relayTransport, fetch: (...a) => fetch(...a), ...deps }
80
+ this._open = new Map() // id → Computer, while this page has it open
81
+ this._opening = new Map() // id → the open in flight (a second open() of the same id waits for it: one handover — K#3)
82
+ this._removed = new Set() // ids removed in this page: an open that finishes after its remove closes what it opened
83
+ }
84
+
85
+ // ── the account documents (sealed in this app's account index) ──────────────────────────────────────────────────────
86
+ async _store (name) {
87
+ this._guard()
88
+ const acc = this._wb.account
89
+ if (!acc || !acc.enabled) throw fail('not_enabled', 'turn the account on first (wb.backup.enable or restore) — a cloud computer lives in it')
90
+ const loc = await acc._where(), c = acc._client()
91
+ let v = null // the version get() read: put() lands only over it (sync sweep 11-08 #32)
92
+ return {
93
+ get: async () => {
94
+ const r = await c.state(loc.room, loc.mk, name)
95
+ if (!r || r.status !== 200) throw fail('unreadable', 'the account could not be read just now', { status: r && r.status })
96
+ v = Number.isInteger(r.v) ? r.v : null
97
+ const st = r.state
98
+ return st == null || (typeof st === 'object' && !Object.keys(st).length) ? null : openDoc(loc.key, st)
99
+ },
100
+ put: async (doc) => {
101
+ const w = await c.state(loc.room, loc.mk, name, await sealDoc(loc.key, doc), name, 'device', v ?? undefined)
102
+ if (w && w.status === 409) throw fail('moved', 'another device changed the account just now')
103
+ if (!w || w.status !== 200) throw fail('save_failed', 'the account could not be saved just now', { status: w && w.status })
104
+ },
105
+ }
106
+ }
107
+ async _deleteLockedSession(target, current) {
108
+ const { reg } = await this._read()
109
+ const cache = await this._cache(String(target).split('/')[0])
110
+ return deletePairedCodeSession(liveComputers(reg), target, current, cache)
111
+ }
112
+ async _read () {
113
+ const [rs, cs] = await Promise.all([this._store(COMPUTERS_DOC), this._store(CLOUD_DOC)])
114
+ const [reg, cloud] = await Promise.all([rs.get(), cs.get()])
115
+ return { reg: normRegistry(reg), cloud: normCloud(cloud), rs, cs }
116
+ }
117
+ /** Change both documents from what is there NOW (merged per entry by its own clock, as the Code section does). */
118
+ async _write (change) {
119
+ // each doc written only over the version read; another device's write in between → read, change and merge again
120
+ for (let i = 0; ; i++) {
121
+ const cur = await this._read()
122
+ const next = change(cur)
123
+ try {
124
+ await cur.rs.put({ ...mergeRegistry(next.reg, cur.reg), at: Date.now() })
125
+ await cur.cs.put({ ...mergeCloud(next.cloud, cur.cloud), at: Date.now() })
126
+ return
127
+ } catch (e) { if (!(e && e.code === 'moved') || i >= 4) throw e }
128
+ }
129
+ }
130
+ /** Not in vault mode yet (docs/sdk-cloud-computers.md phase 3): the keys must stay in the vault, so nothing here runs. */
131
+ _guard () { if (this._wb.vault) throw fail('vault_mode', 'cloud computers in vault mode come in a later release — the keys must stay in the vault') }
132
+ _token () { return this._wb._auth('a cloud computer belongs').idToken }
133
+ async _awsAdmit () {
134
+ const rec = await ensureAwsKey({ token: this._token(), store: await this._store(AWS_KEY_DOC), fetchImpl: this._d.fetch })
135
+ return signAws(rec, 'admit')
136
+ }
137
+
138
+ /** The account's cloud computers, newest first: `{ id, name, cloud, version, egress }` — never a secret. */
139
+ async list () {
140
+ this._guard()
141
+ const { reg, cloud } = await this._read()
142
+ return liveComputers(reg).filter((c) => cloud.cloud[c.id] && !cloud.cloud[c.id].removed).map((c) => infoOf(c.id, reg, cloud))
143
+ }
144
+
145
+ /**
146
+ * A new cloud computer. Its model keys come from the account (capped, like a paired laptop's) unless `keys` brings the
147
+ * person's own; its hours charge the person's AWS key when it is opened.
148
+ * @param {object} o { name?, keys?: { trustedRouter, tinfoil?, github? }, egress?, browsePrivate? }
149
+ */
150
+ async create ({ name = 'Cloud computer', keys = null, egress = null, browsePrivate = false } = {}) {
151
+ this._guard()
152
+ const k = keys && typeof keys === 'object' ? keys : null
153
+ const c = newCloudComputer({ name, key: k ? k.trustedRouter : '', tinfoil: k ? k.tinfoil : '', github: k ? k.github : '', browsePrivate })
154
+ if (egress != null) {
155
+ const e = normEgress(egress)
156
+ if (e.error) throw fail('invalid_argument', `egress: ${e.error}`)
157
+ c.cloud.egress = e.policy
158
+ }
159
+ if (!k || !k.trustedRouter) {
160
+ const got = await this._d.mint({ computerId: c.id, name: c.name, idToken: this._token(), fetchImpl: this._d.fetch })
161
+ if (!got.ok) throw fail(got.code || 'keys_refused', got.reason || 'the account did not give this computer its keys')
162
+ c.cloud.key = got.tr; if (got.tinfoil) c.cloud.tinfoil = got.tinfoil; if (got.venice) c.cloud.venice = got.venice; c.cloud.codeKey = got.codeKey
163
+ }
164
+ await this._write(({ reg, cloud }) => ({ reg: withComputer(reg, c.id, { name: c.name, relay: c.relay, secret: c.secret }), cloud: withCloud(cloud, c.id, c.cloud) }))
165
+ return { id: c.id, name: c.name, cloud: true, version: 0, egress: (c.cloud.egress && c.cloud.egress.mode) || 'none' }
166
+ }
167
+
168
+ async setDefaultPrivate(id, on) {
169
+ this._guard()
170
+ if (typeof on !== 'boolean') throw fail('invalid_argument', 'choose true or false')
171
+ const { reg, cloud } = await this._read()
172
+ const computer = reg.computers[id]
173
+ if (!computer?.secret || computer.removed || !cloud.cloud[id] || cloud.cloud[id].removed) throw fail('not_found', 'no such cloud computer in this account')
174
+ await this._patchCloud({ id, secret: computer.secret }, { browsePrivate: on ? true : null })
175
+ const held = this._open.get(id)
176
+ if (held?._c.secret === computer.secret) held._c.cloud.browsePrivate = on
177
+ }
178
+
179
+ async connections(id) {
180
+ this._guard()
181
+ const { reg, cloud } = await this._read()
182
+ const pair = reg.computers[id], entry = cloud.cloud[id]
183
+ if (!pair?.secret || pair.removed || !entry || entry.removed) throw fail('not_found', 'no such cloud computer in this account')
184
+ return computerConnections(this, { id, secret: pair.secret })
185
+ }
186
+
187
+ async _cache(id) {
188
+ this._guard()
189
+ const account = this._wb.account
190
+ if (!account?.enabled) throw fail('not_enabled', 'the account must be open to read its cached conversations')
191
+ const state = account._backup?._s
192
+ const check = () => { if (!account.enabled || account._backup?._s !== state) throw fail('account_changed', 'the account changed') }
193
+ const loc = await account._where()
194
+ check()
195
+ const open = async (key, blob) => {
196
+ const data = await openDoc(loc.key, blob.accountBox)
197
+ check()
198
+ if (data.key !== key) throw fail('unreadable', 'the cached conversation has a different identifier')
199
+ return data.value
200
+ }
201
+ const store = {
202
+ get: async key => { const blob = await idb.get(key); return blob ? open(key, blob) : null },
203
+ set: async (key, value) => { const box = await sealDoc(loc.key, { key, value }); check(); return idb.set(key, { accountBox: box }) },
204
+ entries: async prefix => Promise.all((await idb.entries(prefix)).map(async ([k, v]) => [k, await open(k, v)])),
205
+ del: key => idb.del(key),
206
+ delStrict: key => { check(); return idb.delStrict(key) },
207
+ }
208
+ return { cid: 'sdk:' + loc.room + ':' + seg(id, 'computer'), store, check }
209
+ }
210
+ async cachedSessions(id) {
211
+ const { cid, store, check } = await this._cache(id)
212
+ const rows = await cachedSessions(cid, store)
213
+ check()
214
+ return rows
215
+ }
216
+ async cachedDirectory(id) {
217
+ const { cid, store, check } = await this._cache(id)
218
+ const directory = await loadList(cid, store)
219
+ check()
220
+ return directory
221
+ }
222
+ async cachedSession(id, sid) {
223
+ const { cid, store, check } = await this._cache(id)
224
+ const row = await loadSession(cid, seg(sid, 'session'), store)
225
+ check()
226
+ return row
227
+ }
228
+
229
+ async _patchCloud(computer, patch) {
230
+ return this._write(({ reg, cloud }) => {
231
+ if (reg.computers[computer.id]?.removed || reg.computers[computer.id]?.secret !== computer.secret || !cloud.cloud[computer.id] || cloud.cloud[computer.id].removed) throw fail('not_found', 'this computer is no longer registered')
232
+ return { reg, cloud: withCloud(cloud, computer.id, patch) }
233
+ })
234
+ }
235
+
236
+ async _closeComputer(computer) {
237
+ // THE STOP IS WHAT WAS ASKED; `closedAt` only says so to the account's other devices (second review, 2026-11-27). Run together,
238
+ // a failed stamp rejected a close that had stopped the computer, and a failed stop was still published as closed.
239
+ const stopped = await this._d.close(computer, { token: async () => this._token(), fetchImpl: this._d.fetch })
240
+ if (stopped) await this._patchCloud(computer, { closedAt: Date.now() }).catch(() => {})
241
+ return stopped
242
+ }
243
+
244
+ /** Stop a registered computer without starting or removing it. */
245
+ async close (id) {
246
+ this._guard()
247
+ const opening = this._opening.get(id)
248
+ if (opening) await opening.catch(() => {})
249
+ const handle = this._open.get(id)
250
+ if (handle) return handle.close()
251
+ const { reg, cloud } = await this._read()
252
+ const pair = reg.computers[id], entry = cloud.cloud[id]
253
+ if (!pair || pair.removed || !entry || entry.removed) throw fail('not_found', 'no such cloud computer in this account')
254
+ return this._closeComputer({ ...pair, id, cloud: entry })
255
+ }
256
+
257
+ /** Remove a computer: closed (a last save) and its account keys cancelled, best-effort; then dropped from the account. */
258
+ async remove (id) {
259
+ this._guard()
260
+ const { reg, cloud } = await this._read()
261
+ const entry = cloud.cloud[id]
262
+ if (!entry || entry.removed) throw fail('not_found', 'no such cloud computer in this account')
263
+ this._removed.add(id) // an open still in flight closes what it opened when it lands (pass 6, docs/state-machines.md K#3)
264
+ const open = this._open.get(id); if (open) open._stop()
265
+ // ★ THE ACCOUNT FIRST (second review, 2026-11-27). The computer was closed and its keys revoked, the cached transcript read and
266
+ // dropped, and only then was it taken off the account — a failed write (or cache read) left a computer still listed whose keys
267
+ // were gone, and `_removed` stayed set, so every later open() handed over and closed again. A failed write now changes nothing.
268
+ try { await this._write(({ reg: r, cloud: cl }) => ({ reg: withoutComputer(r, id), cloud: withoutCloud(cl, id) })) }
269
+ catch (e) { this._removed.delete(id); throw e }
270
+ let token = ''; try { token = this._token() } catch { /* signed out: removal still goes ahead */ }
271
+ if (token) {
272
+ await this._d.close({ id, ...(reg.computers[id] || {}), cloud: entry }, { token: async () => token, fetchImpl: this._d.fetch }).catch(() => false)
273
+ await this._d.fetch(CODE_KEYS_REVOKE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ idToken: token, computerId: id }) }).catch(() => null)
274
+ }
275
+ try { const cache = await this._cache(id); await forgetComputer(cache.cid) } catch { /* this device's cached transcript: the removal stands */ }
276
+ }
277
+
278
+ /**
279
+ * Open a computer: start or wake it, check it and its key guard run the published Witbitz images (a NEW published image is
280
+ * followed: `images` 'auto' accepts it, 'ask' calls `onNewImage(pcr0, role)` → true to accept), hand it the person's keys
281
+ * sealed, and connect. → a Computer.
282
+ * @param {string} id
283
+ * @param {object} [o] { onStep?(step), images?: 'auto' | 'ask', onNewImage?(pcr0, role) }
284
+ */
285
+ async open (id, o = {}) {
286
+ this._guard()
287
+ if (this._open.has(id)) {
288
+ const live = this._open.get(id)
289
+ if (o.cache) await live._enableCache()
290
+ return live
291
+ }
292
+ // ★ ONE OPENING PER COMPUTER (pass 6, K#3): two open(id) calls not awaited in turn made two handovers and two Computers;
293
+ // the first one's close() then dropped the second from `_open`.
294
+ if (this._opening.has(id)) {
295
+ const live = await this._opening.get(id)
296
+ if (o.cache) await live._enableCache()
297
+ return live
298
+ }
299
+ const p = this._openNow(id, o).finally(() => { if (this._opening.get(id) === p) this._opening.delete(id) })
300
+ this._opening.set(id, p)
301
+ return p
302
+ }
303
+
304
+ async _openNow (id, { cache = false, onStep = () => {}, images = 'auto', onNewImage = null } = {}) {
305
+ const { reg, cloud } = await this._read()
306
+ const entry = cloud.cloud[id], pair = reg.computers[id]
307
+ if (!entry || entry.removed || !pair || pair.removed) throw fail('not_found', 'no such cloud computer in this account')
308
+ const computer = { id, name: pair.name, relay: pair.relay, secret: pair.secret, cloud: entry }
309
+ const token = this._token()
310
+ const follow = { auto: () => images === 'auto', ask: async (p, role) => !!(typeof onNewImage === 'function' && await onNewImage(p, role)), fetch: this._d.fetch }
311
+ let saving = Promise.resolve()
312
+ const save = (_c, patch) => {
313
+ Object.assign(computer.cloud, patch)
314
+ saving = saving.then(() => this._patchCloud(computer, patch))
315
+ saving.catch(() => {}) // the open awaits the writes before handing back the computer
316
+ return saving
317
+ }
318
+ try {
319
+ // mint: null — a computer made with the builder's own keys (create({ keys })) STAYS on them: the app moves its pasted-key computers
320
+ // to account keys at opening (codeCloud.js), the SDK never does (docs: "keys stay yours"; sync sweep 11-21 #1)
321
+ await this._d.open(computer, { mint: null, token: async () => token, aws: () => this._awsAdmit(), save, openOpts: { onStep, follow, fetchImpl: this._d.fetch } })
322
+ } catch (e) {
323
+ if (e instanceof CloudError || (e && e.code)) throw Object.assign(fail(e.code || 'open_failed', String(e.message || e)), { status: e.status })
324
+ throw e
325
+ }
326
+ // ★ REMOVED WHILE IT OPENED (pass 6, K#3): remove() found nothing to close (the enclave was not up yet) and revoked the keys;
327
+ // this open then finished a handover — a removed computer running, and billed, until the host's idle stop. Close it now.
328
+ if (this._removed.has(id)) {
329
+ await this._d.close(computer, { token: async () => token, fetchImpl: this._d.fetch }).catch(() => false)
330
+ throw fail('not_found', 'this cloud computer was removed while it opened')
331
+ }
332
+ // ★ A FAILURE AFTER THE HANDOVER (review of the sweep fixes, 2026-11-27; 1384f426b made these awaited): the enclave is running
333
+ // and nothing holds it — close it before the error goes back, or it runs, and bills, until the host's idle stop.
334
+ let c
335
+ try {
336
+ await saving
337
+ const t = this._d.transport({ computer })
338
+ c = new Computer(this, computer, t, cache ? await this._cache(id) : null)
339
+ } catch (e) {
340
+ await this._d.close(computer, { token: async () => token, fetchImpl: this._d.fetch }).catch(() => false)
341
+ throw e
342
+ }
343
+ this._open.set(id, c)
344
+ return c
345
+ }
346
+
347
+ /** This month on the person's AWS key: `{ live, tier, month: { usd, capUsd }, resetsAt }`, or null before the first opening. */
348
+ async usage () {
349
+ this._guard()
350
+ const rec = await (await this._store(AWS_KEY_DOC)).get()
351
+ return rec && rec.keyId ? awsKeyStatus(rec, { fetchImpl: this._d.fetch }) : null
352
+ }
353
+ }
354
+
355
+ /** One open cloud computer: its coding sessions, the agent's approvals and questions, its files, and its live events. */
356
+ function computerConnections(owner, computer) {
357
+ const currentPicks = ({ reg, cloud }) => {
358
+ const c = cloud.cloud[computer.id]
359
+ if (!c || c.removed || reg.computers[computer.id]?.removed || reg.computers[computer.id]?.secret !== computer.secret) throw fail('not_found', 'this cloud computer is no longer in the account')
360
+ return c.connections || []
361
+ }
362
+ const changePicks = (id, pick) => owner._write(snapshot => {
363
+ const connections = currentPicks(snapshot).filter(c => c.id !== id)
364
+ if (pick) connections.push(pick)
365
+ if (connections.length > 32 || new TextEncoder().encode(JSON.stringify(connections)).length > CLOUD_PICKS_MAX_BYTES) throw fail('too_large', 'the selected connections exceed the computer limit')
366
+ const cloud = withCloud(snapshot.cloud, computer.id, { connections: connections.length ? connections : null })
367
+ if (pick && !cloud.cloud[computer.id]?.connections?.some(c => c.id === id && c.mcp.tools.length === pick.mcp.tools.length)) throw fail('invalid_argument', 'the connection or its selected tools cannot be saved')
368
+ return { reg: snapshot.reg, cloud }
369
+ })
370
+ return {
371
+ list: async () => currentPicks(await owner._read()).map(c => ({ id: c.id, host: c.host, label: c.label, tools: c.mcp.tools.map(t => t.name), auto: [...c.mcp.auto] })),
372
+ grant: async (conn, { tools, auto = [] } = {}) => {
373
+ const account = await owner._wb._account()
374
+ if (!conn?.mcp || !conn.id || !conn.callKey || !conn.host || !account || (conn.account && conn.account !== account)) throw fail('invalid_argument', 'choose an MCP connection belonging to this account')
375
+ const catalog = await owner._wb.connections.mcpTools(conn.id)
376
+ if (!Array.isArray(catalog?.tools)) throw fail('unreadable', 'the service did not return its tools')
377
+ const names = tools ?? catalog.tools.slice(0, 40).map(t => t.name)
378
+ if (!Array.isArray(names) || !names.length || names.length > 40 || !Array.isArray(auto) || auto.some(n => !names.includes(n))) throw fail('invalid_argument', 'choose up to 40 tools and which may run without asking')
379
+ const picked = catalog.tools.filter(t => names.includes(t.name))
380
+ if (picked.length !== names.length) throw fail('invalid_argument', 'choose tools offered by the service')
381
+ await changePicks(conn.id, { account, id: conn.id, callKey: conn.callKey, host: conn.host, label: conn.label || conn.host, mcp: { tools: picked, auto } })
382
+ },
383
+ revoke: async id => { if (!id) throw fail('invalid_argument', 'a connection id is required'); await changePicks(id, null) },
384
+ }
385
+ }
386
+
387
+ export class Computer {
388
+ constructor (owner, computer, transport, cache = null) {
389
+ this._owner = owner
390
+ this._c = computer
391
+ this._enableCache = async () => { cache ||= await owner._cache(computer.id) }
392
+ this._t = transport
393
+ this._streams = new Map() // directory → transport subscription and subscribers
394
+ this._firstOutputWatches = new Set()
395
+ // ★ THE SERVER SCOPES BY `directory` (opencodeApp.js withDir): an unscoped call reaches the server's DEFAULT project, so a
396
+ // session in another folder streamed nothing and its message / abort / todo calls missed it (sync sweep 11-08 #9 — only
397
+ // create scoped). Each session's folder is learned once (create, list, or GET /session/<id>, which answers unscoped)
398
+ // and sent on every call about it.
399
+ this._dirs = new Map() // session id → its directory
400
+ this.id = computer.id
401
+ this.name = computer.name
402
+ const req = (m, p, b) => this._req(m, p, b)
403
+ const learn = (x) => { if (x && typeof x.id === 'string' && typeof x.directory === 'string' && x.directory) this._dirs.set(x.id, x.directory); return x }
404
+ const inDir = async (sid, p) => withDir(p, await this._dirOf(sid))
405
+ // A CALL ABOUT NO ONE SESSION (approvals, questions, status, files) is scoped too (sync sweep 11-09, 11-08 #9 half fixed: the
406
+ // app sends the open session's folder, opencodeApp.js api; unscoped, an approval in another folder was never seen after a
407
+ // reload and the agent waited). `{ dir }` or `{ session }` scopes one call; with neither, a list is asked in EVERY folder the
408
+ // computer's sessions live in (learned from the session list once) and joined by id.
409
+ const scopeOf = async ({ session = '', dir = '' } = {}) => (dir ? String(dir) : session ? this._dirOf(session) : null)
410
+ const allDirs = async () => {
411
+ const list = await req('GET', '/experimental/session?archived=true')
412
+ if (!Array.isArray(list)) throw fail('unreadable', 'the computer did not return its sessions')
413
+ list.forEach(learn)
414
+ return ['', ...new Set(list.map(s => s?.directory).filter(Boolean))]
415
+ }
416
+ const listEverywhere = async (path, opts) => {
417
+ const one = await scopeOf(opts)
418
+ if (one !== null) return (await req('GET', withDir(path, one))) || []
419
+ const seen = new Map()
420
+ for (const d of await allDirs()) { let l = []; try { l = (await req('GET', withDir(path, d))) || [] } catch (e) { if (!d) throw e /* another folder's failure costs only its list */ } for (const x of Array.isArray(l) ? l : []) { const k = x && (x.id || x.requestID); if (k && !seen.has(k)) seen.set(k, x) } }
421
+ return [...seen.values()]
422
+ }
423
+ const recentUserText = new Map()
424
+ const modeAgents = new Map()
425
+ const sessionCall = async (sid, method, suffix = '', body) => req(method, await inDir(sid, '/session/' + seg(sid, 'session') + suffix), body)
426
+ const drafts = this._drafts = new PendingCodeDrafts()
427
+ const sendParts = async (sid, parts, opts) => {
428
+ const original = parts
429
+ const keepDraft = reason => drafts.add(sid, { parts: structuredClone(original), reason })
430
+ const ownText = parts.filter(p => p.type === 'text' && !p.synthetic).map(p => p.text).join('\n')
431
+ const previous = recentUserText.get(sid) || []
432
+ const texts = [ownText, ...previous].slice(0, 12)
433
+ let ref = opts.model
434
+ if (!ref) {
435
+ const preferred = await this.preferredModel().catch(error => { if (error.code === 'account_changed') throw error; return '' })
436
+ if (preferred && (await models(sid).catch(() => [])).some(m => m.ref === preferred)) ref = preferred
437
+ }
438
+ if (!transport.can?.('attachments') && parts.some(p => p.type === 'file' && p.mime?.toLowerCase() === 'application/pdf' && /^data:/i.test(p.url))) {
439
+ const catalog = await modelCatalog(sid).catch(() => ({ offered: [], fallback: '' }))
440
+ const offered = catalog.offered
441
+ ref ||= catalog.fallback
442
+ if (!offered.find(m => m.ref === ref)?.input?.includes('pdf')) {
443
+ try {
444
+ const { pdfToText, pdfTextBlock } = await import('./pdfText.js')
445
+ parts = await Promise.all(parts.map(async p => {
446
+ if (p.type !== 'file' || p.mime?.toLowerCase() !== 'application/pdf' || !/^data:/i.test(p.url)) return p
447
+ const bytes = new Uint8Array(await (await fetch(p.url)).arrayBuffer())
448
+ const doc = await pdfToText(bytes)
449
+ return { type: 'text', text: pdfTextBlock({ name: p.filename, ...doc }) }
450
+ }))
451
+ } catch (cause) {
452
+ throw fail('attachment_unreadable', 'Could not prepare the PDF. The prompt was kept as a draft.', { cause, draftId: keepDraft('unsent') })
453
+ }
454
+ }
455
+ }
456
+ const model = parseModel(ref)
457
+ const saved = opts.effort == null && ref ? this.preferredEffort(ref) : ''
458
+ const effort = opts.effort ?? (saved && (await models(sid).catch(() => [])).some(m => m.ref === ref && m.efforts?.includes(saved)) ? saved : '')
459
+ const agent = opts.agent || await agentFor(sid)
460
+ const nudge = languageNudge(texts)
461
+ const promptPath = await inDir(sid, '/session/' + seg(sid, 'session') + '/message')
462
+ const result = await req('POST', promptPath, { parts: nudge ? [...parts, nudge] : parts, ...(nudge ? { system: withLanguage('', texts).trim() } : {}), ...(agent ? { agent } : {}), ...(model ? { model } : {}), ...(model && effort ? { variant: String(effort) } : {}) }).catch(error => {
463
+ if ((error.code === 'request_failed' && (!error.status || error.status >= 500)) || error.name === 'AbortError' || error.name === 'TimeoutError' || error instanceof TypeError) {
464
+ throw fail('submission_unknown', 'The computer did not confirm the prompt. Check the conversation before sending it again.', { cause: error, draftId: keepDraft('submission_unknown') })
465
+ }
466
+ error.draftId = keepDraft(error.code || 'request_failed')
467
+ throw error
468
+ })
469
+ const refused = providerRefusal(result)
470
+ if (refused) throw fail('provider_refused', refused, { draftId: keepDraft('provider_refused') })
471
+ recentUserText.set(sid, texts)
472
+ return result
473
+ }
474
+ const models = async sid => (await modelCatalog(sid)).offered
475
+ const modelCatalog = async sid => {
476
+ const serviceModels = await this._owner._wb?.models?.().catch(() => [])
477
+ const unsuitable = new Set(unsuitableCodeModels(serviceModels))
478
+ const catalog = await req('GET', await inDir(sid, '/config/providers')).catch(() => null)
479
+ if (!Array.isArray(catalog?.providers)) {
480
+ const legacy = await req('GET', await inDir(sid, '/api/model'))
481
+ const offered = (legacy?.data || []).filter(m => m && !unsuitable.has(m.id) && m.status !== 'deprecated').map(m => ({ ref: m.providerID + '/' + m.id, label: m.name || m.id, input: m.capabilities?.input || m.input, efforts: Object.keys(m.variants || {}) }))
482
+ return { offered, fallback: offered[0]?.ref || '' }
483
+ }
484
+ const owned = catalog.providers.filter(p => p.source !== 'custom')
485
+ const offered = (owned.length ? owned : catalog.providers).flatMap(p => Object.entries(p.models || {}).filter(([id, m]) => m && m.status !== 'deprecated' && !unsuitable.has(id)).map(([id, m]) => ({
486
+ ref: p.id + '/' + id, label: m.name || id, input: m.input, efforts: Array.isArray(m.variants) ? m.variants.map(String) : Object.keys(m.variants || {}),
487
+ })))
488
+ const configured = await req('GET', await inDir(sid, '/config')).catch(() => null)
489
+ const candidates = [configured?.model, ...Object.entries(catalog.default || {}).map(([provider, id]) => provider + '/' + id)]
490
+ return { offered, fallback: candidates.find(ref => offered.some(m => m.ref === ref)) || offered[0]?.ref || '' }
491
+ }
492
+ const agents = async sid => {
493
+ const list = await req('GET', await inDir(sid, '/agent'))
494
+ return list.filter(a => a?.name && a.mode === 'primary' && !a.hidden).map(a => ({ name: a.name, description: a.description || '' }))
495
+ }
496
+ const agentFor = async (sid, available) => {
497
+ if (modeAgents.has(sid)) return modeAgents.get(sid)
498
+ const name = await this.preferredAgent().catch(error => { if (error.code === 'account_changed') throw error; return '' })
499
+ return name && (available || await agents(sid).catch(() => [])).some(a => a.name === name) ? name : ''
500
+ }
501
+ const messagePage = async (sid, { limit = 50, cursor = '' } = {}) => {
502
+ limit = Math.max(1, Math.min(200, Math.trunc(Number(limit)) || 50))
503
+ let messages
504
+ try { messages = await sessionCall(sid, 'GET', '/message?' + pageQuery({ limit, cursor })) }
505
+ catch (error) {
506
+ if (!cursor || error.status !== 400) throw error
507
+ const all = await sessionCall(sid, 'GET', '/message')
508
+ const at = Array.isArray(all) ? all.findIndex(m => cursorBefore(m) === cursor) : -1
509
+ if (at < 0) throw fail('invalid_cursor', 'the older conversation page could not be located')
510
+ messages = all.slice(Math.max(0, at - limit), at)
511
+ }
512
+ if (!Array.isArray(messages)) throw fail('unreadable', 'the computer did not return its messages')
513
+ if (!cursor) {
514
+ recentUserText.set(sid, messages.filter(m => m?.info?.role === 'user').slice(-12).reverse().map(m => (m.parts || []).filter(p => p.type === 'text' && !p.synthetic).map(p => p.text).join('\n')))
515
+ if (cache) {
516
+ cache.check()
517
+ const cacheSid = seg(sid, 'session')
518
+ const previous = await loadSession(cache.cid, cacheSid, cache.store).catch(() => null)
519
+ cache.check()
520
+ const snapshot = messages.length >= limit && messages[0]?.info?.id ? mergeTail(previous?.msgs, messages).messages : messages
521
+ const write = snapshot.length ? saveSession(cache.cid, cacheSid, snapshot, { dir: this._dirs.get(sid) || '' }, cache.store) : clearSession(cache.cid, cacheSid, cache.store)
522
+ await write.then(() => prune(cache.cid, undefined, cache.store)).catch(() => {})
523
+ }
524
+ }
525
+ const next = mayHaveMore(messages, limit) && cursorBefore(messages[0])
526
+ return { messages, cursor: next && next !== cursor ? next : null }
527
+ }
528
+ const changeAuto = async (sid, dir, on) => {
529
+ const transport = this._t
530
+ if (transport.autoSessions?.().includes(sid) === on) return
531
+ await new Promise((resolve, reject) => {
532
+ let off, timer
533
+ const finish = error => { clearTimeout(timer); off?.(); error ? reject(error) : resolve() }
534
+ const confirm = () => { if (transport.autoSessions?.().includes(sid) === on) finish() }
535
+ timer = setTimeout(() => finish(fail('timeout', 'the computer did not confirm Auto mode')), 25000)
536
+ off = transport.onAuto?.(confirm)
537
+ try {
538
+ if (!transport.setAuto(sid, dir, on)) finish(fail('unavailable', 'the computer could not switch Auto mode'))
539
+ else confirm()
540
+ } catch (error) { finish(error) }
541
+ })
542
+ }
543
+ const modeChanges = new Map()
544
+ this.preferredAgent = () => codeAgentPreference(this._owner._wb.account)
545
+ this.setPreferredAgent = async (sid, name) => {
546
+ if (typeof name !== 'string' || name.length > 256 || (name && !(await agents(sid)).some(a => a.name === name))) throw fail('invalid_argument', 'choose a primary agent on this computer')
547
+ return codeAgentPreference(this._owner._wb.account, name)
548
+ }
549
+ this.onAutoVerdict = (sid, fn, { family = false } = {}) => {
550
+ if (!sid || typeof fn !== 'function') throw fail('invalid_argument', 'a session and callback are required')
551
+ if (!family) return transport.onAuto(e => { if (e?.kind === 'verdict' && e.verdict?.sessionID === sid) fn(e.verdict) })
552
+ const children = new Set(), pending = []
553
+ let active = true
554
+ const flush = () => {
555
+ for (let i = 0; i < pending.length;) {
556
+ if (!children.has(pending[i].sessionID)) { i++; continue }
557
+ const [v] = pending.splice(i, 1)
558
+ fn(v)
559
+ }
560
+ }
561
+ const offEvents = this.on('*', event => {
562
+ const id = childFromEvent(event, sid, children)
563
+ if (id) { children.add(id); flush() }
564
+ }, { session: sid })
565
+ const offAuto = transport.onAuto(e => {
566
+ if (e?.kind !== 'verdict' || !e.verdict?.sessionID) return
567
+ if (e.verdict.sessionID === sid || children.has(e.verdict.sessionID)) fn(e.verdict)
568
+ else { pending.push(e.verdict); if (pending.length > 100) pending.shift() }
569
+ })
570
+ Promise.all([this.sessions.list(), this.sessions.messages(sid)]).then(([sessions, messages]) => {
571
+ if (!active) return
572
+ for (const id of childIdsOf(sid, { sessions, messages })) children.add(id)
573
+ flush()
574
+ }).catch(() => {})
575
+ return () => { active = false; pending.length = 0; offEvents(); offAuto() }
576
+ }
577
+ this.onProgress = (sid, fn) => {
578
+ if (!sid || typeof fn !== 'function') throw fail('invalid_argument', 'a session and callback are required')
579
+ return transport.onProgress(m => { const p = normProgress(m); if (p?.sessionID === sid) fn(p) })
580
+ }
581
+ const effortKey = ref => 'wb-sdk:code-effort:' + JSON.stringify([owner._wb._endpoint, owner._wb._tenant, owner._wb._session?.email || '', computer.id, ref])
582
+ this.preferredEffort = ref => {
583
+ const key = effortKey(ref)
584
+ try { return globalThis.localStorage?.getItem(key) || this._efforts?.get(key) || '' } catch { return this._efforts?.get(key) || '' }
585
+ }
586
+ this.setPreferredEffort = async (sid, ref, effort) => {
587
+ const key = effortKey(ref)
588
+ if (typeof ref !== 'string' || !ref || typeof effort !== 'string' || (effort && !(await models(sid)).some(m => m.ref === ref && m.efforts?.includes(effort)))) throw fail('invalid_argument', 'choose an effort offered for this model')
589
+ if (key !== effortKey(ref)) throw fail('account_changed', 'the account changed')
590
+ this._efforts ||= new Map()
591
+ if (effort) this._efforts.set(key, effort)
592
+ else this._efforts.delete(key)
593
+ try { if (effort) globalThis.localStorage?.setItem(key, effort); else globalThis.localStorage?.removeItem(key) } catch { /* current handle still remembers */ }
594
+ }
595
+ this.preferredModel = () => computerModelPreference(this._owner._wb.account, this.id)
596
+ this.setPreferredModel = async (sid, ref) => {
597
+ if (typeof ref !== 'string' || ref.length > 256 || (ref && !(await models(sid)).some(m => m.ref === ref))) throw fail('invalid_argument', 'choose an available model on this computer')
598
+ return computerModelPreference(this._owner._wb.account, this.id, ref)
599
+ }
600
+ this.sessions = {
601
+ list: async () => {
602
+ const list = await req('GET', '/experimental/session?archived=true')
603
+ if (!Array.isArray(list)) throw fail('unreadable', 'the computer did not return its sessions')
604
+ list.forEach(learn)
605
+ if (cache) {
606
+ cache.check()
607
+ await saveList(cache.cid, list.slice(0, 200).map(slimSession), cache.store, { allowEmpty: true }).catch(() => {})
608
+ cache.check()
609
+ }
610
+ return list
611
+ },
612
+ create: async ({ dir = '', title = '', agent = '', model = '' } = {}) => {
613
+ const picked = model ? parseModel(model) : null
614
+ if (model && !picked) throw fail('invalid_argument', 'choose a provider/model reference')
615
+ if (agent && (typeof agent !== 'string' || agent.length > 256)) throw fail('invalid_argument', 'choose a primary agent')
616
+ return learn(await req('POST', withDir('/session', dir), { permission: ocPermissionRuleset(), ...(title ? { title: String(title).slice(0, 200) } : {}), ...(agent ? { agent } : {}), ...(picked ? { model: { providerID: picked.providerID, id: picked.modelID } } : {}) }))
617
+ },
618
+ messages: async (sid, opts) => (await messagePage(sid, opts)).messages,
619
+ messagePage,
620
+ saveDraft: (sid, parts) => {
621
+ seg(sid, 'session')
622
+ if (!Array.isArray(parts) || !parts.length || parts.some(p => !p || typeof p !== 'object' || typeof p.type !== 'string')) throw fail('invalid_argument', 'provide the prompt parts to keep')
623
+ const id = drafts.add(sid, { parts: structuredClone(parts), reason: 'unsent' })
624
+ if (!id) throw fail('computer_closed', 'The computer session is closed')
625
+ return id
626
+ },
627
+ listDrafts: sid => drafts.list(sid).map(({ id, reason }) => ({ id, reason })),
628
+ getDraft: (sid, id) => structuredClone(drafts.get(sid, id)),
629
+ discardDraft: (sid, id) => drafts.discard(sid, id),
630
+ promptLanded: async (sid, text, knownUserIds) => {
631
+ if (typeof text !== 'string' || !(Array.isArray(knownUserIds) || knownUserIds instanceof Set)) throw fail('invalid_argument', 'provide the prompt and the known user message IDs from before sending')
632
+ const known = new Set(knownUserIds), visited = new Set()
633
+ let cursor
634
+ do {
635
+ const page = await this.sessions.messagePage(sid, { cursor })
636
+ if (promptLanded(page.messages, { knownUserIds: known, text })) return true
637
+ if (page.messages.some(m => m?.info?.role === 'user' && known.has(m.info.id))) return false
638
+ cursor = page.cursor
639
+ if (cursor && visited.has(cursor)) throw fail('submission_unknown', 'The computer returned the same history page twice.')
640
+ visited.add(cursor)
641
+ } while (cursor)
642
+ return false
643
+ },
644
+ watchFirstOutput: (sid, userMessageId, onStall, { timeoutMs = 60000 } = {}) => {
645
+ if (!sid || !userMessageId || typeof onStall !== 'function' || !Number.isFinite(timeoutMs) || timeoutMs <= 0) throw fail('invalid_argument', 'a session, user message ID, callback and positive timeout are required')
646
+ let active = true, off = null
647
+ const stop = () => {
648
+ if (!active) return
649
+ active = false
650
+ clearTimeout(timer)
651
+ off?.()
652
+ this._firstOutputWatches.delete(stop)
653
+ }
654
+ const timer = setTimeout(async () => {
655
+ try {
656
+ const messages = await this.sessions.messages(sid)
657
+ const lastUser = messages.findLast(m => m?.info?.role === 'user')
658
+ if (active && lastUser?.info?.id === userMessageId && !firstOutputStarted(messages)) onStall({ sessionId: sid, userMessageId })
659
+ } catch { /* an unreadable conversation cannot establish a stalled reply */ }
660
+ finally { stop() }
661
+ }, timeoutMs)
662
+ this._firstOutputWatches.add(stop)
663
+ if (typeof transport.onProgress === 'function') off = this.onProgress(sid, p => { if (progressLine(p) || p.phase === 'end') stop() })
664
+ return stop
665
+ },
666
+ attachments: (sid, message) => (message?.parts || []).filter(p => p?.synthetic && p.type === 'text')
667
+ .flatMap(p => parseAttachmentNote(p.text) || []).filter(a => a.session === sid && validAttachmentRef(sid, a.file)),
668
+ readAttachment: async (sid, file) => {
669
+ if (!validAttachmentRef(sid, file)) throw fail('invalid_argument', 'an attachment reference from this session is required')
670
+ const result = await req('GET', ATTACHMENT_ROUTE + '?session=' + encodeURIComponent(sid) + '&file=' + encodeURIComponent(file))
671
+ if (typeof result?.b64 !== 'string') throw fail('unreadable', 'the computer did not return the attachment')
672
+ return result
673
+ },
674
+ attachmentWarning: async (sid, ref, file) => {
675
+ if (!file || typeof file.mime !== 'string') throw fail('invalid_argument', 'a file MIME type is required')
676
+ const catalog = await modelCatalog(sid)
677
+ const selected = ref || catalog.fallback
678
+ const model = catalog.offered.find(m => m.ref === selected)
679
+ return attachmentWarning({ mime: file.mime, modelLabel: model?.label || selected || 'this model', input: model?.input })
680
+ },
681
+ agents,
682
+ family: async sid => {
683
+ const [sessions, tail, approvals, questions] = await Promise.all([
684
+ this.sessions.list(), this.sessions.messages(sid), this.approvals.pending({ session: sid }), this.questions.pending({ session: sid }),
685
+ ])
686
+ const children = [...childIdsOf(sid, { sessions, messages: tail })]
687
+ const family = new Set([sid, ...children])
688
+ return { children, approvals: approvals.filter(x => family.has(x.sessionID)), questions: questions.filter(x => family.has(x.sessionID)) }
689
+ },
690
+ approvalMode: async sid => {
691
+ await modeChanges.get(sid)
692
+ const [session, available] = await Promise.all([sessionCall(sid, 'GET'), agents(sid)])
693
+ const modes = ['manual', 'accept']
694
+ if (available.some(a => a.name === 'plan')) modes.push('plan')
695
+ if (this._t.can?.('auto')) modes.push('auto')
696
+ const agent = await agentFor(sid, available) || session?.agent || 'build'
697
+ const rules = Array.isArray(session?.permission) ? session.permission : []
698
+ const guarded = OC_ASK_PERMISSIONS.filter(p => p !== 'edit').every(p => {
699
+ const matching = rules.filter(r => typeof r?.permission === 'string' && wildcardMatch(p, r.permission))
700
+ const at = matching.findLastIndex(r => r.pattern === '*')
701
+ return at >= 0 && matching.slice(at).every(r => r.action === 'ask' || r.action === 'deny')
702
+ })
703
+ const edit = rules.findLast(r => (r.permission === 'edit' || r.permission === '*') && r.pattern === '*')
704
+ let mode = 'unknown'
705
+ if (this._t.autoSessions?.().includes(sid)) mode = 'auto'
706
+ else if (agent === 'plan') mode = 'plan'
707
+ else if (agent === 'build' && guarded && edit) mode = acceptsEdits(rules) ? 'accept' : 'manual'
708
+ return { mode, modes }
709
+ },
710
+ prompt: async (sid, text, opts = {}) => sendParts(sid, partsFor(text, opts.files), opts),
711
+ models,
712
+ archive: (sid, archived = true) => sessionCall(sid, 'PATCH', '', { time: { archived: archived ? Date.now() : 0 } }),
713
+ undo: async sid => {
714
+ const revert = normRevert((await sessionCall(sid, 'GET'))?.revert)
715
+ let cursor, messageID, atBoundary = !revert
716
+ const visited = new Set()
717
+ do {
718
+ const page = await messagePage(sid, { cursor, limit: PAGE })
719
+ if (!atBoundary) atBoundary = page.messages.some(m => m?.info?.id === revert.messageID)
720
+ if (atBoundary) messageID = undoTarget(page.messages, revert)
721
+ cursor = page.cursor
722
+ if (!cursor || visited.has(cursor)) break
723
+ visited.add(cursor)
724
+ } while (!messageID)
725
+ if (!messageID) return { changed: false, files: false }
726
+ const result = await sessionCall(sid, 'POST', '/revert', { messageID })
727
+ return { changed: true, files: !!normRevert(result?.revert)?.files }
728
+ },
729
+ redo: async sid => {
730
+ const revert = normRevert((await sessionCall(sid, 'GET'))?.revert)
731
+ if (!revert) return { changed: false, files: false }
732
+ await sessionCall(sid, 'POST', '/unrevert')
733
+ return { changed: true, files: revert.files }
734
+ },
735
+ compact: async (sid, model) => {
736
+ const selected = parseModel(model)
737
+ if (!selected) throw fail('invalid_argument', 'select a provider/model to summarize this session')
738
+ if ((await sessionCall(sid, 'GET'))?.revert) throw fail('undo_pending', 'redo or send a message before compacting')
739
+ return sessionCall(sid, 'POST', '/summarize', selected)
740
+ },
741
+ commands: async sid => normCommands(await req('GET', await inDir(sid, '/command'))),
742
+ runCommand: async (sid, text, opts = {}) => {
743
+ const original = partsFor(text, opts.files)
744
+ let turn, picked
745
+ try {
746
+ turn = commandTurn(text, await this.sessions.commands(sid))
747
+ if (!turn || turn.blocked) throw fail(turn ? 'not_supported' : 'unknown_command', 'this project command is unavailable here')
748
+ const status = await this.sessions.status({ session: sid })
749
+ if (!status || typeof status !== 'object') throw fail('unreadable', 'the computer did not return its session status')
750
+ if (status[sid] && status[sid].type !== 'idle') throw fail('busy', 'wait for the current Code turn to finish')
751
+ picked = { ...opts }
752
+ if (turn.model && (await models(sid)).some(m => m.ref === turn.model)) picked.model = turn.model
753
+ if (turn.agent) {
754
+ const available = await agents(sid)
755
+ if (available.some(a => a.name === turn.agent)) picked.agent = turn.agent
756
+ }
757
+ } catch (error) {
758
+ error.draftId = drafts.add(sid, { reason: 'unsent', parts: structuredClone(original) })
759
+ throw error
760
+ }
761
+ return sendParts(sid, [{ type: 'text', text: turn.visible }, { type: 'text', text: turn.expanded, synthetic: true }, ...partsFor('', opts.files)], picked)
762
+ },
763
+ setApprovalMode: async (sid, mode) => {
764
+ if (!['manual', 'accept', 'plan', 'auto'].includes(mode)) throw fail('invalid_argument', 'unknown approval mode')
765
+ const auto = mode === 'auto', canAuto = !!this._t.can?.('auto')
766
+ if (auto && !canAuto) throw fail('not_supported', 'this computer does not offer Auto')
767
+ const change = (modeChanges.get(sid) || Promise.resolve()).catch(() => {}).then(async () => {
768
+ if (mode === 'plan' && !(await agents(sid)).some(a => a.name === 'plan')) throw fail('not_supported', 'this computer does not offer Plan')
769
+ const dir = await this._dirOf(sid)
770
+ if (canAuto && !auto) await changeAuto(sid, dir, false)
771
+ const session = await sessionCall(sid, 'GET')
772
+ const rules = Array.isArray(session?.permission) ? session.permission : []
773
+ const permission = []
774
+ for (const base of ocPermissionRuleset()) {
775
+ const last = rules.findLast(r => typeof r?.permission === 'string' && wildcardMatch(base.permission, r.permission) && r.pattern === '*')
776
+ const action = base.permission === 'edit' && mode === 'accept' ? 'allow' : base.action
777
+ if (last?.action === 'deny') continue
778
+ const editRules = base.permission === 'edit' && mode === 'accept' ? acceptEditsRules() : null
779
+ const protectedEdits = !editRules || editRules.every(target => rules.findLast(r => r.permission === 'edit' && r.pattern === target.pattern)?.action === target.action)
780
+ if (last?.action === action && protectedEdits) continue
781
+ permission.push(...(editRules || [{ ...base, action }]))
782
+ const scoped = new Map()
783
+ for (const r of rules) {
784
+ if (r.permission !== base.permission || r.pattern === '*') continue
785
+ if (r.action === 'deny' || base.permission === 'external_directory') scoped.set(r.pattern, r)
786
+ }
787
+ permission.push(...scoped.values())
788
+ }
789
+ if (permission.length) await sessionCall(sid, 'PATCH', '', { permission })
790
+ if (auto) await changeAuto(sid, dir, true)
791
+ modeAgents.set(sid, mode === 'plan' ? 'plan' : 'build')
792
+ return { mode }
793
+ })
794
+ modeChanges.set(sid, change)
795
+ try { return await change } finally { if (modeChanges.get(sid) === change) modeChanges.delete(sid) }
796
+ },
797
+ abort: async (sid) => req('POST', await inDir(sid, `/session/${seg(sid, 'session')}/abort`), {}),
798
+ rename: async (sid, title) => req('PATCH', await inDir(sid, `/session/${seg(sid, 'session')}`), { title: String(title || '').slice(0, 200) }),
799
+ remove: async (sid) => { const r = await req('DELETE', await inDir(sid, `/session/${seg(sid, 'session')}`)); this._dirs.delete(String(sid)); return r },
800
+ todo: async (sid) => req('GET', await inDir(sid, `/session/${seg(sid, 'session')}/todo`)),
801
+ /** { <session id>: status } — `{ session }` or `{ dir }` for one folder; otherwise every folder's, joined. */
802
+ status: async (opts = {}) => {
803
+ const one = await scopeOf(opts)
804
+ if (one !== null) return req('GET', withDir('/session/status', one))
805
+ const out = {}
806
+ for (const d of await allDirs()) { try { Object.assign(out, (await req('GET', withDir('/session/status', d))) || {}) } catch (e) { if (!d) throw e } }
807
+ return out
808
+ },
809
+ }
810
+ this.connections = computerConnections(owner, computer)
811
+ const approveKey = async () => {
812
+ if (!computer.cloud?.grantKey) throw fail('not_supported', 'this computer has no key guard')
813
+ return (await sentinelKeys(computer.cloud.grantKey)).approve
814
+ }
815
+ this.keyGuard = {
816
+ pending: async () => {
817
+ const key = await approveKey()
818
+ const reply = await req('GET', '/witbitz/sentinel/asks')
819
+ if (!Array.isArray(reply?.asks)) throw fail('unreadable', 'the key guard did not return its requests')
820
+ const pending = []
821
+ for (const ask of reply.asks) {
822
+ if (typeof ask?.id === 'string' && ask.expires > Date.now() && await askGenuine(key, ask)) pending.push(ask)
823
+ }
824
+ return pending
825
+ },
826
+ decide: async (ask, allow) => {
827
+ if (typeof allow !== 'boolean' || typeof ask?.id !== 'string' || !(ask.expires > Date.now())) throw fail('invalid_argument', 'a current key-guard request and a decision are required')
828
+ const key = await approveKey()
829
+ const id = ask.id
830
+ if (!(await askGenuine(key, ask))) throw fail('unverified', 'the key guard could not verify this request')
831
+ return req('POST', '/witbitz/sentinel/decide', { id, allow, tag: await decideTag(key, id, allow) })
832
+ },
833
+ }
834
+ this.approvals = {
835
+ refusalOf,
836
+ folders: async (sid, id) => {
837
+ if (!this._t.can?.('folders')) return []
838
+ const result = await req('GET', await inDir(sid, FOLDER_ROUTE + '?ask=' + seg(id, 'approval')))
839
+ return (result?.folders || []).filter(f => f && typeof f.path === 'string')
840
+ },
841
+ allowFolder: async (sid, id) => {
842
+ if (!this._t.can?.('folders')) throw fail('not_supported', 'this computer does not offer folder approvals')
843
+ const pending = await this.approvals.pending({ session: sid })
844
+ if (!pending.some(p => p.sessionID === sid && (p.id || p.requestID) === id && p.permission === 'external_directory')) throw fail('not_pending', 'this session has no matching folder approval')
845
+ if (!(await this.approvals.folders(sid, id)).length) throw fail('not_offered', 'the computer offered no folder for this request')
846
+ return req('POST', await inDir(sid, FOLDER_ROUTE), { ask: id })
847
+ },
848
+ /** Every approval waiting, in every folder — or `{ session }` / `{ dir }` for one. */
849
+ pending: async (opts = {}) => listEverywhere('/permission', opts),
850
+ /** 'once' | 'always' | 'reject'; a reject may carry a message for the model ("stop and ask me"). */
851
+ answer: async (id, response, { session = '', message = '' } = {}) => {
852
+ if (!['once', 'always', 'reject'].includes(response)) throw fail('invalid_argument', "an approval is 'once', 'always' or 'reject'")
853
+ if (response === 'reject') {
854
+ // A connector from before the reply route refuses it (403/404/405): then the bare refusal on the old route, as the app does (codeApprovals.js).
855
+ // in the session's FOLDER (sync sweep 11-08: an approval in another folder than the default was never found)
856
+ const replyPath = `/permission/${seg(id, 'approval')}/reply`
857
+ try { return await req('POST', session ? await inDir(session, replyPath) : replyPath, { reply: 'reject', message: String(message || PERSON_REFUSAL).slice(0, 2000) }) } catch (e) { if (!session || ![403, 404, 405].includes(e.status)) throw e }
858
+ }
859
+ if (!session) throw fail('invalid_argument', 'answering an approval needs its session id (the event carries it as sessionID)')
860
+ return req('POST', await inDir(session, `/session/${seg(session, 'session')}/permissions/${seg(id, 'approval')}`), { response })
861
+ },
862
+ }
863
+ this.questions = {
864
+ pending: async (opts = {}) => listEverywhere('/question', opts),
865
+ /** `{ session }` (the event's sessionID) or `{ dir }`: the folder the question is in — a question in another folder than the
866
+ * computer's default is answered there (sync sweep 11-08); neither = the default folder, as before. */
867
+ answer: async (id, answers, opts = {}) => req('POST', withDir(`/question/${seg(id, 'question')}/reply`, (await scopeOf(opts)) || ''), { answers }),
868
+ dismiss: async (id, opts = {}) => req('POST', withDir(`/question/${seg(id, 'question')}/reject`, (await scopeOf(opts)) || '')),
869
+ }
870
+ const filesCan = () => { if (this._t.can && !this._t.can('files')) throw fail('not_supported', 'this computer does not move files yet (an older image or connector)') }
871
+ // a reply's files are their own capability (the connector's hello says `outputs`; codeOutputCards.js) — a computer that
872
+ // moves files may not serve them yet (sync sweep 11-08 #33)
873
+ const outputsCan = () => { if (this._t.can && !this._t.can('outputs')) throw fail('not_supported', 'this computer does not serve a reply\'s files yet (an older image or connector)') }
874
+ this.files = {
875
+ mkdir: async (sid, parent, name) => {
876
+ const relative = String(parent || ''), leaf = String(name || '').trim()
877
+ if (!leaf || leaf === '.' || leaf === '..' || /[\\/:\x00-\x1f]/.test(leaf) || relative.startsWith('/') || /[\\:\x00-\x1f]/.test(relative) || relative.split('/').includes('..')) throw fail('invalid_argument', 'use a relative parent folder and one folder name')
878
+ return req('POST', sid === null ? withDir(mkdirPath(relative), CLOUD_HOME) : await inDir(sid, mkdirPath(relative)), { name: leaf })
879
+ },
880
+ // the folder's project: `{ session }` (that session's folder) or `{ dir }`; neither = the computer's default project
881
+ list: async (path = '', opts = {}) => req('GET', withDir('/file?path=' + encodeURIComponent(String(path || '')), (await scopeOf(opts)) || '')),
882
+ changes: async (opts = {}) => req('GET', withDir('/vcs/status', (await scopeOf(opts)) || '')),
883
+ diff: async (opts = {}) => req('GET', withDir('/vcs/diff?mode=git', (await scopeOf(opts)) || '')),
884
+ // FILES (the Code section's Files sheet, codeFiles.js — the owner's "build later" list, 2026-10-28): a file of the session's
885
+ // folder, never one outside it or one that looks like a secret (the connector refuses those), at most 20 MB.
886
+ /** → { name, kind, mime, size, mtime, b64 } */
887
+ download: async (session, path) => { filesCan(); return req('GET', `${FILES_DOWNLOAD_ROUTE}?session=${sidQ(session)}&path=${encodeURIComponent(absPath(path))}`) },
888
+ /** Into folder `dir` of the session. A name already there: onExists 'fail' (default — `exists`), 'replace', or 'keepBoth'
889
+ * ("report (2).pdf"). → { ok, name, path, size } */
890
+ upload: async (session, { dir, name, data, onExists = 'fail' } = {}) => {
891
+ filesCan()
892
+ if (!['fail', 'replace', 'keepBoth'].includes(onExists)) throw fail('invalid_argument', "onExists is 'fail', 'replace' or 'keepBoth'")
893
+ const n = String(name || '').trim()
894
+ if (!n || /[/\\\0]/.test(n) || n === '.' || n === '..' || n.length > 255) throw fail('invalid_argument', 'a file name, without a folder')
895
+ const b64 = await toB64(data)
896
+ const route = `${FILES_UPLOAD_ROUTE}?session=${sidQ(session)}`
897
+ const send = async (nm, replace) => this._t.request('POST', route, { dir: absPath(dir), name: nm, b64, ...(replace ? { replace: true } : {}) })
898
+ let r = await send(n, onExists === 'replace')
899
+ if (r && r.status === 409 && r.json && r.json.exists && onExists === 'keepBoth') {
900
+ let taken = new Set(); try { const l = await req('GET', '/file?path=' + encodeURIComponent(absPath(dir))); taken = new Set((Array.isArray(l) ? l : []).map((e) => e && e.name)) } catch { taken = new Set([n]) }
901
+ taken.add(n); r = await send(keepBothName(n, (x) => taken.has(x)), false)
902
+ }
903
+ if (r && r.status === 409 && r.json && r.json.exists) throw fail('exists', `${n} is already in that folder`, { status: 409, replaceable: !!r.json.replaceable })
904
+ if (!r || !r.ok) throw fail(r && r.status === 403 ? 'refused' : 'request_failed', `upload ${n} — ${(r && ((r.json && r.json.error) || r.status)) || 'no answer'}`.slice(0, 300), { status: r && r.status })
905
+ return r.json
906
+ },
907
+ /** A file a reply produced (outputs()), screenshots included → { name, kind, mime, size, b64 } */
908
+ output: async (session, path) => { outputsCan(); return req('GET', `${OUTPUT_ROUTE}?session=${sidQ(session)}&path=${encodeURIComponent(absPath(path))}`) },
909
+ }
910
+ // THE AGENT'S BROWSER: its report, and PRIVATE browsing (codeTransport setBrowsePrivate) — where the computer says it can
911
+ // (`canPrivate`: witbitz-code's browser on the person's own computer; a cloud image without it answers not_supported).
912
+ this.browser = {
913
+ status: () => (this._t.browse ? this._t.browse() : null),
914
+ url: (opts = {}) => { if (opts.session !== undefined && !/^[A-Za-z0-9_-]{1,128}$/.test(String(opts.session))) throw fail('invalid_argument', 'session is not an id'); return watchUrl({ ...this._c.cloud, relay: this._c.relay }, opts) },
915
+ get private () { const b = transport.browse ? transport.browse() : null; return !!(b && b.private) },
916
+ /** → true when sent (the computer's next report confirms it). */
917
+ setPrivate: (on) => {
918
+ const b = this._t.browse ? this._t.browse() : null
919
+ if (!b || !b.canPrivate || typeof this._t.setBrowsePrivate !== 'function') throw fail('not_supported', 'this computer\'s browser has no private mode')
920
+ if (!this._t.setBrowsePrivate(!!on)) throw fail('offline', 'the computer is not connected')
921
+ return true
922
+ },
923
+ setDefaultPrivate: async on => {
924
+ if (typeof on !== 'boolean') throw fail('invalid_argument', 'choose true or false')
925
+ await owner._patchCloud(computer, { browsePrivate: on ? true : null })
926
+ computer.cloud.browsePrivate = on
927
+ },
928
+ setSessionPrivate: (session, on) => setSessionPrivate({ ...this._c.cloud, relay: this._c.relay }, session, on),
929
+ }
930
+ this.egress = { get: () => (this._t.egress ? this._t.egress() : null) }
931
+ }
932
+
933
+ /** What a reply PRODUCED — files it wrote, the browser's screenshots, files its answer names that changed (codeOutputs.js,
934
+ * the Code section's previews). `messages`: the reply's messages (sessions.messages); omitted = the session's latest.
935
+ * → [{ path, kind: 'pdf'|'image'|'table'|'text'|'file', source: 'wrote'|'shot'|'named' }] — fetch one with files.output(). */
936
+ async outputs (session, messages) {
937
+ const sid = String(session || ''); seg(sid, 'session')
938
+ const info = await this._req('GET', `/session/${encodeURIComponent(sid)}`)
939
+ if (info && typeof info.directory === 'string' && info.directory) this._dirs.set(sid, info.directory)
940
+ let ms = Array.isArray(messages) ? messages : ((await this._req('GET', withDir(`/session/${encodeURIComponent(sid)}/message?limit=20`, this._dirs.get(sid) || ''))) || [])
941
+ if (!Array.isArray(messages)) { const k = ms.map((m) => m && m.info && m.info.role).lastIndexOf('user'); ms = k >= 0 ? ms.slice(k + 1) : ms } // the latest reply: after the last prompt
942
+ return replyOutputs(ms, { directory: (info && info.directory) || '', session: sid })
943
+ }
944
+
945
+ /** 'online' | 'connecting' | 'offline' */
946
+ get status () { return this._t.status() }
947
+
948
+ async _req (method, path, body) {
949
+ const r = await this._t.request(method, path, body)
950
+ if (!r || !r.ok) {
951
+ const code = r && r.status === 403 ? 'refused' : r && r.status === 404 ? 'not_found' : 'request_failed'
952
+ throw fail(code, `${method} ${path.split('?')[0]} — ${(r && (r.text || r.status)) || 'no answer'}`.slice(0, 300), { status: r && r.status })
953
+ }
954
+ return r.json
955
+ }
956
+
957
+ /** @private a session's directory — learned once, then kept ('' when the computer does not say) */
958
+ async _dirOf (sid) {
959
+ const id = String(sid || '')
960
+ if (this._dirs.has(id)) return this._dirs.get(id)
961
+ let d = '', known = false
962
+ try { const info = await this._req('GET', `/session/${encodeURIComponent(seg(id, 'session') && id)}`); d = info && typeof info.directory === 'string' ? info.directory : ''; known = true } catch { d = '' }
963
+ if (known) this._dirs.set(id, d) // an answer without a folder is kept too (asked once); a failed ask is asked again next time
964
+ return d
965
+ }
966
+
967
+ /** Live events from the computer (OpenCode's, parsed): `on('message.part.updated', fn)`, or `on('*', fn)` for all. → off
968
+ * The computer streams per FOLDER: pass `{ session }` (its folder is looked up) or `{ dir }` for a session outside the
969
+ * server's default folder — without it, its events never arrive. */
970
+ on (type, fn, { session = '', dir = '' } = {}) {
971
+ if (typeof fn !== 'function') throw fail('invalid_argument', 'on(type, fn) needs a function')
972
+ let off = false, stream = null, streamDir = ''
973
+ const attach = (d) => {
974
+ if (off) return
975
+ streamDir = d
976
+ stream = this._streams.get(d)
977
+ if (!stream) {
978
+ stream = { subs: new Map(), stop: null }
979
+ this._streams.set(d, stream)
980
+ const st = stream
981
+ st.stop = this._t.subscribe(withDir('/event', d), (ev) => {
982
+ for (const key of [ev && ev.type, '*']) for (const f of st.subs.get(key) || []) { try { f(ev) } catch { /* a builder's handler never stops the stream */ } }
983
+ })
984
+ }
985
+ if (!stream.subs.has(type)) stream.subs.set(type, new Set())
986
+ stream.subs.get(type).add(fn)
987
+ }
988
+ if (dir || !session) attach(String(dir || ''))
989
+ else this._dirOf(session).then(attach, () => attach(''))
990
+ return () => {
991
+ off = true
992
+ const listeners = stream?.subs.get(type)
993
+ if (!listeners || !listeners.delete(fn)) return
994
+ if (!listeners.size) stream.subs.delete(type)
995
+ if (!stream.subs.size && this._streams.get(streamDir) === stream) {
996
+ this._streams.delete(streamDir)
997
+ stream.stop?.()
998
+ }
999
+ }
1000
+ }
1001
+
1002
+ _stop () { this._drafts.close(); for (const cancel of this._firstOutputWatches) cancel(); for (const st of this._streams.values()) { try { if (st.stop) st.stop() } catch { /* */ } } this._streams.clear(); try { this._t.close() } catch { /* */ } if (this._owner._open.get(this.id) === this) this._owner._open.delete(this.id) } // only itself: never a newer opening of the same computer
1003
+
1004
+ /** Close it: a last save, then the enclave stops (its hours stop counting). */
1005
+ async close () {
1006
+ this._stop()
1007
+ return this._owner._closeComputer(this._c)
1008
+ }
1009
+ }