@witbitz/sdk 4.3.0 → 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.
- package/README.md +2 -2
- package/a2aCore.js +26 -5
- package/accountErase.js +6 -1
- package/accountRecord.js +2 -2
- package/agentDoorTools.js +28 -0
- package/chatLock.js +16 -0
- package/cloudDevicePins.js +2 -2
- package/codeAttachments.js +100 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +0 -2
- package/codeComputers.js +1 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeModes.js +2 -0
- package/codeProgress.js +54 -0
- package/codeSent.js +68 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +22 -0
- package/connections.js +17 -18
- package/deviceAttest.js +9 -3
- package/idb.js +19 -3
- package/jobAgents.js +2 -2
- package/keptMerge.js +9 -2
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +93 -30
- package/laneAssociation.js +68 -0
- package/laneConfig.js +4 -3
- package/manifest.json +80 -61
- package/memberChange.js +4 -2
- package/mirrorBatch.js +47 -0
- package/opRouting.js +10 -0
- package/package.json +21 -2
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/protectedLocal.js +18 -2
- package/removedMessage.js +1 -1
- package/roomEmbed.js +111 -0
- package/roomName.js +1 -1
- package/roomRoster.js +21 -5
- package/rosterCount.js +6 -3
- package/sdkA2A.js +160 -40
- package/sdkAccount.js +17 -4
- package/sdkAccountDoc.js +11 -3
- package/sdkAccountSections.js +117 -8
- package/sdkBackup.js +35 -8
- package/sdkCloudDevice.js +8 -2
- package/sdkComputers.js +582 -53
- package/sdkDictation.js +114 -24
- package/sdkErase.js +9 -4
- package/sdkExports.js +4 -2
- package/sdkLaneLink.js +3 -3
- package/sdkPlan.js +4 -2
- package/sdkRekey.js +50 -17
- package/sdkReport.js +1 -1
- package/sdkSafeMedia.js +1 -1
- package/sdkSpeech.js +19 -2
- package/sdkTemporaryRooms.js +123 -0
- package/sdkVault.js +66 -10
- package/sentinelRelease.js +1 -0
- package/sharedViews.js +17 -3
- package/siri.js +114 -7
- package/spaceClient.js +16 -5
- package/spaceEmailGate.js +2 -2
- package/spaceTemplates.js +99 -0
- package/speechOut.js +4 -2
- package/store.js +83 -14
- package/sw-notif-core.js +9 -7
- package/turnVerdict.js +1 -0
- package/vault-core.js +480 -112
- package/vault-kit.mjs +2 -2
- package/vault-screens.js +5 -7
- package/vaultAtRest.js +35 -4
- package/vaultKeep.js +9 -3
- package/vaultWorkerHost.js +23 -4
- package/witbitz-admin.mjs +12 -11
- package/witbitz-sdk.d.ts +115 -24
- package/witbitz-sdk.js +572 -149
package/sdkComputers.js
CHANGED
|
@@ -10,20 +10,31 @@
|
|
|
10
10
|
//
|
|
11
11
|
// Every dependency is injectable (`deps`) so the whole thing runs against fakes in tests.
|
|
12
12
|
|
|
13
|
-
import { partsFor, parseModel, normRevert } from './opencodeWire.js'
|
|
13
|
+
import { attachmentWarning, partsFor, parseModel, normRevert, ocPermissionRuleset, OC_ASK_PERMISSIONS } from './opencodeWire.js'
|
|
14
|
+
import { pageQuery, cursorBefore, mayHaveMore, mergeTail, PAGE } from './codeHistory.js'
|
|
14
15
|
import { undoTarget } from './codeUndo.js'
|
|
15
16
|
import { commandTurn, normCommands } from './codeCommands.js'
|
|
16
|
-
import { acceptEditsRules,
|
|
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'
|
|
17
27
|
import { mkdirPath } from './codeMkdir.js'
|
|
18
|
-
import { newCloudComputer, openCloudComputer, closeCloud, CloudError } from './codeCloud.js'
|
|
28
|
+
import { CLOUD_HOME, newCloudComputer, openCloudComputer, closeCloud, CloudError } from './codeCloud.js'
|
|
19
29
|
import { mintCloudKeys } from './codeCloudKeys.js'
|
|
20
|
-
import { relayTransport } from './codeTransport.js'
|
|
21
|
-
import { CLOUD_DOC, COMPUTERS_DOC, normCloud, mergeCloud, withCloud, withoutCloud, normRegistry, mergeRegistry, withComputer, withoutComputer, liveComputers } from './codeComputers.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'
|
|
22
32
|
import { normEgress } from './codeEgress.js'
|
|
23
33
|
import { AWS_KEY_DOC, ensureAwsKey, signAws, awsKeyStatus } from './awsKey.js'
|
|
24
34
|
import { sealDoc, openDoc } from './accountSeal.js'
|
|
25
35
|
import { CODE_KEYS_REVOKE } from './codeOrphanKeys.js' // the one address (it was written three times — sync sweep backlog P3)
|
|
26
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'
|
|
27
38
|
import { OUTPUT_ROUTE, replyOutputs } from './codeOutputs.js' // what a reply produced, screenshots included (codeOutputCards.js)
|
|
28
39
|
import { watchUrl } from './codeBrowse.js'
|
|
29
40
|
import { setSessionPrivate } from './sdkBrowserPrivate.js'
|
|
@@ -38,7 +49,10 @@ const absPath = (p) => { const s = String(p || ''); if (!s.startsWith('/') || s.
|
|
|
38
49
|
async function toB64 (data) {
|
|
39
50
|
if (typeof data === 'string') {
|
|
40
51
|
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(data)) throw fail('invalid_argument', 'upload data as a string is base64')
|
|
41
|
-
|
|
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`)
|
|
42
56
|
return data
|
|
43
57
|
}
|
|
44
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
|
|
@@ -90,6 +104,11 @@ export class Computers {
|
|
|
90
104
|
},
|
|
91
105
|
}
|
|
92
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
|
+
}
|
|
93
112
|
async _read () {
|
|
94
113
|
const [rs, cs] = await Promise.all([this._store(COMPUTERS_DOC), this._store(CLOUD_DOC)])
|
|
95
114
|
const [reg, cloud] = await Promise.all([rs.get(), cs.get()])
|
|
@@ -146,6 +165,95 @@ export class Computers {
|
|
|
146
165
|
return { id: c.id, name: c.name, cloud: true, version: 0, egress: (c.cloud.egress && c.cloud.egress.mode) || 'none' }
|
|
147
166
|
}
|
|
148
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
|
+
|
|
149
257
|
/** Remove a computer: closed (a last save) and its account keys cancelled, best-effort; then dropped from the account. */
|
|
150
258
|
async remove (id) {
|
|
151
259
|
this._guard()
|
|
@@ -154,12 +262,17 @@ export class Computers {
|
|
|
154
262
|
if (!entry || entry.removed) throw fail('not_found', 'no such cloud computer in this account')
|
|
155
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)
|
|
156
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 }
|
|
157
270
|
let token = ''; try { token = this._token() } catch { /* signed out: removal still goes ahead */ }
|
|
158
271
|
if (token) {
|
|
159
|
-
await this._d.close({ id, ...(reg.computers[id] || {}), cloud: entry }, { token, fetchImpl: this._d.fetch }).catch(() => false)
|
|
272
|
+
await this._d.close({ id, ...(reg.computers[id] || {}), cloud: entry }, { token: async () => token, fetchImpl: this._d.fetch }).catch(() => false)
|
|
160
273
|
await this._d.fetch(CODE_KEYS_REVOKE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ idToken: token, computerId: id }) }).catch(() => null)
|
|
161
274
|
}
|
|
162
|
-
await this.
|
|
275
|
+
try { const cache = await this._cache(id); await forgetComputer(cache.cid) } catch { /* this device's cached transcript: the removal stands */ }
|
|
163
276
|
}
|
|
164
277
|
|
|
165
278
|
/**
|
|
@@ -171,23 +284,37 @@ export class Computers {
|
|
|
171
284
|
*/
|
|
172
285
|
async open (id, o = {}) {
|
|
173
286
|
this._guard()
|
|
174
|
-
if (this._open.has(id))
|
|
287
|
+
if (this._open.has(id)) {
|
|
288
|
+
const live = this._open.get(id)
|
|
289
|
+
if (o.cache) await live._enableCache()
|
|
290
|
+
return live
|
|
291
|
+
}
|
|
175
292
|
// ★ ONE OPENING PER COMPUTER (pass 6, K#3): two open(id) calls not awaited in turn made two handovers and two Computers;
|
|
176
293
|
// the first one's close() then dropped the second from `_open`.
|
|
177
|
-
if (this._opening.has(id))
|
|
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
|
+
}
|
|
178
299
|
const p = this._openNow(id, o).finally(() => { if (this._opening.get(id) === p) this._opening.delete(id) })
|
|
179
300
|
this._opening.set(id, p)
|
|
180
301
|
return p
|
|
181
302
|
}
|
|
182
303
|
|
|
183
|
-
async _openNow (id, { onStep = () => {}, images = 'auto', onNewImage = null } = {}) {
|
|
304
|
+
async _openNow (id, { cache = false, onStep = () => {}, images = 'auto', onNewImage = null } = {}) {
|
|
184
305
|
const { reg, cloud } = await this._read()
|
|
185
306
|
const entry = cloud.cloud[id], pair = reg.computers[id]
|
|
186
307
|
if (!entry || entry.removed || !pair || pair.removed) throw fail('not_found', 'no such cloud computer in this account')
|
|
187
308
|
const computer = { id, name: pair.name, relay: pair.relay, secret: pair.secret, cloud: entry }
|
|
188
309
|
const token = this._token()
|
|
189
310
|
const follow = { auto: () => images === 'auto', ask: async (p, role) => !!(typeof onNewImage === 'function' && await onNewImage(p, role)), fetch: this._d.fetch }
|
|
190
|
-
|
|
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
|
+
}
|
|
191
318
|
try {
|
|
192
319
|
// mint: null — a computer made with the builder's own keys (create({ keys })) STAYS on them: the app moves its pasted-key computers
|
|
193
320
|
// to account keys at opening (codeCloud.js), the SDK never does (docs: "keys stay yours"; sync sweep 11-21 #1)
|
|
@@ -199,11 +326,20 @@ export class Computers {
|
|
|
199
326
|
// ★ REMOVED WHILE IT OPENED (pass 6, K#3): remove() found nothing to close (the enclave was not up yet) and revoked the keys;
|
|
200
327
|
// this open then finished a handover — a removed computer running, and billed, until the host's idle stop. Close it now.
|
|
201
328
|
if (this._removed.has(id)) {
|
|
202
|
-
await this._d.close(computer, { token, fetchImpl: this._d.fetch }).catch(() => false)
|
|
329
|
+
await this._d.close(computer, { token: async () => token, fetchImpl: this._d.fetch }).catch(() => false)
|
|
203
330
|
throw fail('not_found', 'this cloud computer was removed while it opened')
|
|
204
331
|
}
|
|
205
|
-
|
|
206
|
-
|
|
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
|
+
}
|
|
207
343
|
this._open.set(id, c)
|
|
208
344
|
return c
|
|
209
345
|
}
|
|
@@ -217,12 +353,45 @@ export class Computers {
|
|
|
217
353
|
}
|
|
218
354
|
|
|
219
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
|
+
|
|
220
387
|
export class Computer {
|
|
221
|
-
constructor (owner, computer, transport) {
|
|
388
|
+
constructor (owner, computer, transport, cache = null) {
|
|
222
389
|
this._owner = owner
|
|
223
390
|
this._c = computer
|
|
391
|
+
this._enableCache = async () => { cache ||= await owner._cache(computer.id) }
|
|
224
392
|
this._t = transport
|
|
225
|
-
this._streams = new Map() // directory
|
|
393
|
+
this._streams = new Map() // directory → transport subscription and subscribers
|
|
394
|
+
this._firstOutputWatches = new Set()
|
|
226
395
|
// ★ THE SERVER SCOPES BY `directory` (opencodeApp.js withDir): an unscoped call reaches the server's DEFAULT project, so a
|
|
227
396
|
// session in another folder streamed nothing and its message / abort / todo calls missed it (sync sweep 11-08 #9 — only
|
|
228
397
|
// create scoped). Each session's folder is learned once (create, list, or GET /session/<id>, which answers unscoped)
|
|
@@ -239,8 +408,10 @@ export class Computer {
|
|
|
239
408
|
// computer's sessions live in (learned from the session list once) and joined by id.
|
|
240
409
|
const scopeOf = async ({ session = '', dir = '' } = {}) => (dir ? String(dir) : session ? this._dirOf(session) : null)
|
|
241
410
|
const allDirs = async () => {
|
|
242
|
-
|
|
243
|
-
|
|
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))]
|
|
244
415
|
}
|
|
245
416
|
const listEverywhere = async (path, opts) => {
|
|
246
417
|
const one = await scopeOf(opts)
|
|
@@ -249,33 +420,308 @@ export class Computer {
|
|
|
249
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) } }
|
|
250
421
|
return [...seen.values()]
|
|
251
422
|
}
|
|
423
|
+
const recentUserText = new Map()
|
|
252
424
|
const modeAgents = new Map()
|
|
253
425
|
const sessionCall = async (sid, method, suffix = '', body) => req(method, await inDir(sid, '/session/' + seg(sid, 'session') + suffix), body)
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
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
|
|
257
473
|
}
|
|
258
|
-
const models = async sid =>
|
|
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))
|
|
259
478
|
const catalog = await req('GET', await inDir(sid, '/config/providers')).catch(() => null)
|
|
260
479
|
if (!Array.isArray(catalog?.providers)) {
|
|
261
480
|
const legacy = await req('GET', await inDir(sid, '/api/model'))
|
|
262
|
-
|
|
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 || '' }
|
|
263
483
|
}
|
|
264
484
|
const owned = catalog.providers.filter(p => p.source !== 'custom')
|
|
265
|
-
|
|
266
|
-
ref: p.id + '/' + id, label: m.name || id, efforts: Array.isArray(m.variants) ? m.variants.map(String) : Object.keys(m.variants || {}),
|
|
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 || {}),
|
|
267
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)
|
|
268
599
|
}
|
|
269
600
|
this.sessions = {
|
|
270
|
-
list: async () => {
|
|
271
|
-
|
|
272
|
-
|
|
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
|
+
},
|
|
273
710
|
prompt: async (sid, text, opts = {}) => sendParts(sid, partsFor(text, opts.files), opts),
|
|
274
711
|
models,
|
|
275
712
|
archive: (sid, archived = true) => sessionCall(sid, 'PATCH', '', { time: { archived: archived ? Date.now() : 0 } }),
|
|
276
713
|
undo: async sid => {
|
|
277
|
-
const
|
|
278
|
-
|
|
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)
|
|
279
725
|
if (!messageID) return { changed: false, files: false }
|
|
280
726
|
const result = await sessionCall(sid, 'POST', '/revert', { messageID })
|
|
281
727
|
return { changed: true, files: !!normRevert(result?.revert)?.files }
|
|
@@ -294,13 +740,23 @@ export class Computer {
|
|
|
294
740
|
},
|
|
295
741
|
commands: async sid => normCommands(await req('GET', await inDir(sid, '/command'))),
|
|
296
742
|
runCommand: async (sid, text, opts = {}) => {
|
|
297
|
-
const
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
const
|
|
303
|
-
if (
|
|
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
|
|
304
760
|
}
|
|
305
761
|
return sendParts(sid, [{ type: 'text', text: turn.visible }, { type: 'text', text: turn.expanded, synthetic: true }, ...partsFor('', opts.files)], picked)
|
|
306
762
|
},
|
|
@@ -308,13 +764,35 @@ export class Computer {
|
|
|
308
764
|
if (!['manual', 'accept', 'plan', 'auto'].includes(mode)) throw fail('invalid_argument', 'unknown approval mode')
|
|
309
765
|
const auto = mode === 'auto', canAuto = !!this._t.can?.('auto')
|
|
310
766
|
if (auto && !canAuto) throw fail('not_supported', 'this computer does not offer Auto')
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
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) }
|
|
318
796
|
},
|
|
319
797
|
abort: async (sid) => req('POST', await inDir(sid, `/session/${seg(sid, 'session')}/abort`), {}),
|
|
320
798
|
rename: async (sid, title) => req('PATCH', await inDir(sid, `/session/${seg(sid, 'session')}`), { title: String(title || '').slice(0, 200) }),
|
|
@@ -329,17 +807,54 @@ export class Computer {
|
|
|
329
807
|
return out
|
|
330
808
|
},
|
|
331
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
|
+
}
|
|
332
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
|
+
},
|
|
333
848
|
/** Every approval waiting, in every folder — or `{ session }` / `{ dir }` for one. */
|
|
334
849
|
pending: async (opts = {}) => listEverywhere('/permission', opts),
|
|
335
850
|
/** 'once' | 'always' | 'reject'; a reject may carry a message for the model ("stop and ask me"). */
|
|
336
851
|
answer: async (id, response, { session = '', message = '' } = {}) => {
|
|
337
852
|
if (!['once', 'always', 'reject'].includes(response)) throw fail('invalid_argument', "an approval is 'once', 'always' or 'reject'")
|
|
338
|
-
if (response === 'reject'
|
|
853
|
+
if (response === 'reject') {
|
|
339
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).
|
|
340
855
|
// in the session's FOLDER (sync sweep 11-08: an approval in another folder than the default was never found)
|
|
341
856
|
const replyPath = `/permission/${seg(id, 'approval')}/reply`
|
|
342
|
-
try { return await req('POST', session ? await inDir(session, replyPath) : replyPath, { reply: 'reject', message: String(message).slice(0, 2000) }) } catch (e) { if (!session || ![403, 404, 405].includes(e.status)) throw e }
|
|
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 }
|
|
343
858
|
}
|
|
344
859
|
if (!session) throw fail('invalid_argument', 'answering an approval needs its session id (the event carries it as sessionID)')
|
|
345
860
|
return req('POST', await inDir(session, `/session/${seg(session, 'session')}/permissions/${seg(id, 'approval')}`), { response })
|
|
@@ -360,7 +875,7 @@ export class Computer {
|
|
|
360
875
|
mkdir: async (sid, parent, name) => {
|
|
361
876
|
const relative = String(parent || ''), leaf = String(name || '').trim()
|
|
362
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')
|
|
363
|
-
return req('POST', await inDir(sid, mkdirPath(relative)), { name: leaf })
|
|
878
|
+
return req('POST', sid === null ? withDir(mkdirPath(relative), CLOUD_HOME) : await inDir(sid, mkdirPath(relative)), { name: leaf })
|
|
364
879
|
},
|
|
365
880
|
// the folder's project: `{ session }` (that session's folder) or `{ dir }`; neither = the computer's default project
|
|
366
881
|
list: async (path = '', opts = {}) => req('GET', withDir('/file?path=' + encodeURIComponent(String(path || '')), (await scopeOf(opts)) || '')),
|
|
@@ -405,6 +920,11 @@ export class Computer {
|
|
|
405
920
|
if (!this._t.setBrowsePrivate(!!on)) throw fail('offline', 'the computer is not connected')
|
|
406
921
|
return true
|
|
407
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
|
+
},
|
|
408
928
|
setSessionPrivate: (session, on) => setSessionPrivate({ ...this._c.cloud, relay: this._c.relay }, session, on),
|
|
409
929
|
}
|
|
410
930
|
this.egress = { get: () => (this._t.egress ? this._t.egress() : null) }
|
|
@@ -449,9 +969,10 @@ export class Computer {
|
|
|
449
969
|
* server's default folder — without it, its events never arrive. */
|
|
450
970
|
on (type, fn, { session = '', dir = '' } = {}) {
|
|
451
971
|
if (typeof fn !== 'function') throw fail('invalid_argument', 'on(type, fn) needs a function')
|
|
452
|
-
let off = false, stream = null
|
|
972
|
+
let off = false, stream = null, streamDir = ''
|
|
453
973
|
const attach = (d) => {
|
|
454
974
|
if (off) return
|
|
975
|
+
streamDir = d
|
|
455
976
|
stream = this._streams.get(d)
|
|
456
977
|
if (!stream) {
|
|
457
978
|
stream = { subs: new Map(), stop: null }
|
|
@@ -466,15 +987,23 @@ export class Computer {
|
|
|
466
987
|
}
|
|
467
988
|
if (dir || !session) attach(String(dir || ''))
|
|
468
989
|
else this._dirOf(session).then(attach, () => attach(''))
|
|
469
|
-
return () => {
|
|
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
|
+
}
|
|
470
1000
|
}
|
|
471
1001
|
|
|
472
|
-
_stop () { 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
|
|
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
|
|
473
1003
|
|
|
474
1004
|
/** Close it: a last save, then the enclave stops (its hours stop counting). */
|
|
475
1005
|
async close () {
|
|
476
1006
|
this._stop()
|
|
477
|
-
|
|
478
|
-
return this._owner._d.close(this._c, { token, fetchImpl: this._owner._d.fetch })
|
|
1007
|
+
return this._owner._closeComputer(this._c)
|
|
479
1008
|
}
|
|
480
1009
|
}
|