@witbitz/sdk 4.3.0 → 4.5.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 +41 -5
- package/accountErase.js +15 -4
- package/accountIndexDoc.js +24 -7
- package/accountRecord.js +6 -2
- package/accountStores.js +21 -5
- package/acctV2App.js +111 -12
- package/acctV2Client.js +11 -1
- package/acctV2UiCore.js +27 -7
- package/agentDoorTools.js +28 -0
- package/awsKey.js +3 -1
- package/backupRecord.js +3 -0
- package/chatLock.js +16 -0
- package/cloudDevicePins.js +2 -2
- package/codeAttachments.js +101 -0
- package/codeCache.js +173 -0
- package/codeCloud.js +2 -2
- package/codeComputers.js +9 -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 +109 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +46 -5
- package/connections.js +37 -20
- package/decrypt.html +69 -9
- package/deviceAttest.js +9 -3
- package/eraseFile.js +15 -0
- package/idb.js +19 -3
- package/idbSeal.js +5 -2
- package/inviteReceive.js +44 -0
- package/inviteSend.js +8 -2
- package/jobAgents.js +2 -2
- package/keptMerge.js +9 -2
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +122 -43
- package/laneAssociation.js +78 -0
- package/laneConfig.js +4 -3
- package/laneLinkCore.js +9 -0
- package/ledgerView.js +30 -4
- package/manifest.json +112 -87
- package/memberChange.js +4 -2
- package/mirrorBatch.js +47 -0
- package/offlineBundle.js +21 -0
- package/opRouting.js +10 -0
- package/package.json +27 -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 +52 -13
- package/reactionHolders.js +86 -0
- package/removedMessage.js +1 -1
- package/roomEmbed.js +111 -0
- package/roomIntake.js +324 -0
- package/roomName.js +1 -1
- package/roomRoster.js +30 -7
- package/rosterCount.js +6 -3
- package/scheduleNext.js +60 -0
- package/sdkA2A.js +200 -42
- package/sdkAccount.js +88 -18
- package/sdkAccountDoc.js +13 -5
- package/sdkAccountSections.js +172 -23
- package/sdkAgui.js +33 -6
- package/sdkBackup.js +53 -11
- package/sdkBackupV2.js +15 -3
- package/sdkCloudDevice.js +20 -5
- package/sdkComputers.js +695 -65
- package/sdkDictation.js +115 -25
- package/sdkErase.js +12 -5
- package/sdkExports.js +19 -8
- package/sdkInvitations.js +4 -2
- package/sdkKeptAgent.js +19 -3
- package/sdkKeptIntake.js +100 -0
- package/sdkLaneLink.js +8 -9
- package/sdkPlan.js +4 -2
- package/sdkRekey.js +122 -22
- package/sdkReport.js +1 -1
- package/sdkSafeMedia.js +1 -1
- package/sdkSchedules.js +8 -1
- package/sdkSpeech.js +32 -2
- package/sdkTemporaryRooms.js +124 -0
- package/sdkTurn.js +12 -4
- package/sdkVault.js +66 -10
- package/sentinelRelease.js +1 -0
- package/sharedViews.js +34 -4
- package/siri.js +140 -9
- package/spaceClient.js +112 -17
- package/spaceEmailGate.js +2 -2
- package/spaceExport.js +50 -5
- package/spaceFork.js +15 -7
- package/spaceTemplates.js +99 -0
- package/speechOut.js +21 -5
- package/store.js +134 -27
- package/sw-notif-core.js +11 -8
- package/tapTrail.js +58 -0
- package/turnVerdict.js +1 -0
- package/usageReceipts.js +12 -5
- package/vault-core.js +568 -126
- package/vault-kit.mjs +3 -3
- package/vault-screens.js +30 -18
- package/vaultAtRest.js +38 -6
- package/vaultCoreLock.js +3 -1
- package/vaultCorePush.js +58 -7
- package/vaultKeep.js +9 -3
- package/vaultWorkerHost.js +32 -7
- package/witbitz-admin.d.ts +3 -0
- package/witbitz-admin.mjs +12 -11
- package/witbitz-sdk.d.ts +170 -43
- package/witbitz-sdk.js +833 -203
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'
|
|
14
|
-
import {
|
|
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, visibleMessages } 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, removeCachedSession } 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,17 +353,59 @@ 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)
|
|
229
398
|
// and sent on every call about it.
|
|
230
399
|
this._dirs = new Map() // session id → its directory
|
|
400
|
+
// a listener whose folder lookups all failed waits here, and moves when any later read learns the folder (side sweep round 2)
|
|
401
|
+
this._dirWaiters = new Map() // session id → Set of (dir) => void
|
|
402
|
+
const setDir = this._dirs.set.bind(this._dirs)
|
|
403
|
+
this._dirs.set = (k, v) => {
|
|
404
|
+
setDir(k, v)
|
|
405
|
+
const w = this._dirWaiters.get(k)
|
|
406
|
+
if (w) { this._dirWaiters.delete(k); for (const f of w) { try { f(v) } catch { /* */ } } }
|
|
407
|
+
return this._dirs
|
|
408
|
+
}
|
|
231
409
|
this.id = computer.id
|
|
232
410
|
this.name = computer.name
|
|
233
411
|
const req = (m, p, b) => this._req(m, p, b)
|
|
@@ -237,10 +415,12 @@ export class Computer {
|
|
|
237
415
|
// app sends the open session's folder, opencodeApp.js api; unscoped, an approval in another folder was never seen after a
|
|
238
416
|
// reload and the agent waited). `{ dir }` or `{ session }` scopes one call; with neither, a list is asked in EVERY folder the
|
|
239
417
|
// computer's sessions live in (learned from the session list once) and joined by id.
|
|
240
|
-
const scopeOf = async ({ session = '', dir = '' } = {}) => (dir ? String(dir) : session ? this._dirOf(session) : null)
|
|
418
|
+
const scopeOf = async ({ session = '', dir = '' } = {}) => (dir ? String(dir) : session ? this._dirOf(session, { strict: true }) : null)
|
|
241
419
|
const allDirs = async () => {
|
|
242
|
-
|
|
243
|
-
|
|
420
|
+
const list = await req('GET', '/experimental/session?archived=true')
|
|
421
|
+
if (!Array.isArray(list)) throw fail('unreadable', 'the computer did not return its sessions')
|
|
422
|
+
list.forEach(learn)
|
|
423
|
+
return ['', ...new Set(list.map(s => s?.directory).filter(Boolean))]
|
|
244
424
|
}
|
|
245
425
|
const listEverywhere = async (path, opts) => {
|
|
246
426
|
const one = await scopeOf(opts)
|
|
@@ -249,33 +429,322 @@ export class Computer {
|
|
|
249
429
|
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
430
|
return [...seen.values()]
|
|
251
431
|
}
|
|
432
|
+
const recentUserText = new Map()
|
|
252
433
|
const modeAgents = new Map()
|
|
253
434
|
const sessionCall = async (sid, method, suffix = '', body) => req(method, await inDir(sid, '/session/' + seg(sid, 'session') + suffix), body)
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
435
|
+
const drafts = this._drafts = new PendingCodeDrafts()
|
|
436
|
+
const sendParts = async (sid, parts, opts) => {
|
|
437
|
+
const original = parts
|
|
438
|
+
const keepDraft = reason => drafts.add(sid, { parts: structuredClone(original), reason })
|
|
439
|
+
const ownText = parts.filter(p => p.type === 'text' && !p.synthetic).map(p => p.text).join('\n')
|
|
440
|
+
const previous = recentUserText.get(sid) || []
|
|
441
|
+
const texts = [ownText, ...previous].slice(0, 12)
|
|
442
|
+
let ref = opts.model
|
|
443
|
+
if (!ref) {
|
|
444
|
+
const preferred = await this.preferredModel().catch(error => { if (error.code === 'account_changed') throw error; return '' })
|
|
445
|
+
if (preferred && (await models(sid).catch(() => [])).some(m => m.ref === preferred)) ref = preferred
|
|
446
|
+
}
|
|
447
|
+
if (!transport.can?.('attachments') && parts.some(p => p.type === 'file' && p.mime?.toLowerCase() === 'application/pdf' && /^data:/i.test(p.url))) {
|
|
448
|
+
const catalog = await modelCatalog(sid).catch(() => ({ offered: [], fallback: '' }))
|
|
449
|
+
const offered = catalog.offered
|
|
450
|
+
ref ||= catalog.fallback
|
|
451
|
+
if (!offered.find(m => m.ref === ref)?.input?.includes('pdf')) {
|
|
452
|
+
try {
|
|
453
|
+
const { pdfToText, pdfTextBlock } = await import('./pdfText.js')
|
|
454
|
+
parts = await Promise.all(parts.map(async p => {
|
|
455
|
+
if (p.type !== 'file' || p.mime?.toLowerCase() !== 'application/pdf' || !/^data:/i.test(p.url)) return p
|
|
456
|
+
const bytes = new Uint8Array(await (await fetch(p.url)).arrayBuffer())
|
|
457
|
+
const doc = await pdfToText(bytes)
|
|
458
|
+
return { type: 'text', text: pdfTextBlock({ name: p.filename, ...doc }) }
|
|
459
|
+
}))
|
|
460
|
+
} catch (cause) {
|
|
461
|
+
throw fail('attachment_unreadable', 'Could not prepare the PDF. The prompt was kept as a draft.', { cause, draftId: keepDraft('unsent') })
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
const model = parseModel(ref)
|
|
466
|
+
const saved = opts.effort == null && ref ? this.preferredEffort(ref) : ''
|
|
467
|
+
const effort = opts.effort ?? (saved && (await models(sid).catch(() => [])).some(m => m.ref === ref && m.efforts?.includes(saved)) ? saved : '')
|
|
468
|
+
const agent = opts.agent || await agentFor(sid)
|
|
469
|
+
const nudge = languageNudge(texts)
|
|
470
|
+
const promptPath = await inDir(sid, '/session/' + seg(sid, 'session') + '/message')
|
|
471
|
+
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 => {
|
|
472
|
+
if ((error.code === 'request_failed' && (!error.status || error.status >= 500)) || error.name === 'AbortError' || error.name === 'TimeoutError' || error instanceof TypeError) {
|
|
473
|
+
throw fail('submission_unknown', 'The computer did not confirm the prompt. Check the conversation before sending it again.', { cause: error, draftId: keepDraft('submission_unknown') })
|
|
474
|
+
}
|
|
475
|
+
error.draftId = keepDraft(error.code || 'request_failed')
|
|
476
|
+
throw error
|
|
477
|
+
})
|
|
478
|
+
const refused = providerRefusal(result)
|
|
479
|
+
if (refused) throw fail('provider_refused', refused, { draftId: keepDraft('provider_refused') })
|
|
480
|
+
recentUserText.set(sid, texts)
|
|
481
|
+
return result
|
|
257
482
|
}
|
|
258
|
-
const models = async sid =>
|
|
483
|
+
const models = async sid => (await modelCatalog(sid)).offered
|
|
484
|
+
const modelCatalog = async sid => {
|
|
485
|
+
const serviceModels = await this._owner._wb?.models?.().catch(() => [])
|
|
486
|
+
const unsuitable = new Set(unsuitableCodeModels(serviceModels))
|
|
259
487
|
const catalog = await req('GET', await inDir(sid, '/config/providers')).catch(() => null)
|
|
260
488
|
if (!Array.isArray(catalog?.providers)) {
|
|
261
489
|
const legacy = await req('GET', await inDir(sid, '/api/model'))
|
|
262
|
-
|
|
490
|
+
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 || {}) }))
|
|
491
|
+
return { offered, fallback: offered[0]?.ref || '' }
|
|
263
492
|
}
|
|
264
493
|
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 || {}),
|
|
494
|
+
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]) => ({
|
|
495
|
+
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
496
|
})))
|
|
497
|
+
const configured = await req('GET', await inDir(sid, '/config')).catch(() => null)
|
|
498
|
+
const candidates = [configured?.model, ...Object.entries(catalog.default || {}).map(([provider, id]) => provider + '/' + id)]
|
|
499
|
+
return { offered, fallback: candidates.find(ref => offered.some(m => m.ref === ref)) || offered[0]?.ref || '' }
|
|
500
|
+
}
|
|
501
|
+
const agents = async sid => {
|
|
502
|
+
const list = await req('GET', await inDir(sid, '/agent'))
|
|
503
|
+
return list.filter(a => a?.name && a.mode === 'primary' && !a.hidden).map(a => ({ name: a.name, description: a.description || '' }))
|
|
504
|
+
}
|
|
505
|
+
const agentFor = async (sid, available) => {
|
|
506
|
+
if (modeAgents.has(sid)) return modeAgents.get(sid)
|
|
507
|
+
const name = await this.preferredAgent().catch(error => { if (error.code === 'account_changed') throw error; return '' })
|
|
508
|
+
return name && (available || await agents(sid).catch(() => [])).some(a => a.name === name) ? name : ''
|
|
509
|
+
}
|
|
510
|
+
const messagePage = async (sid, { limit = 50, cursor = '' } = {}) => {
|
|
511
|
+
limit = Math.max(1, Math.min(200, Math.trunc(Number(limit)) || 50))
|
|
512
|
+
let messages
|
|
513
|
+
try { messages = await sessionCall(sid, 'GET', '/message?' + pageQuery({ limit, cursor })) }
|
|
514
|
+
catch (error) {
|
|
515
|
+
if (!cursor || error.status !== 400) throw error
|
|
516
|
+
const all = await sessionCall(sid, 'GET', '/message')
|
|
517
|
+
const at = Array.isArray(all) ? all.findIndex(m => cursorBefore(m) === cursor) : -1
|
|
518
|
+
if (at < 0) throw fail('invalid_cursor', 'the older conversation page could not be located')
|
|
519
|
+
messages = all.slice(Math.max(0, at - limit), at)
|
|
520
|
+
}
|
|
521
|
+
if (!Array.isArray(messages)) throw fail('unreadable', 'the computer did not return its messages')
|
|
522
|
+
if (!cursor) {
|
|
523
|
+
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')))
|
|
524
|
+
if (cache) {
|
|
525
|
+
cache.check()
|
|
526
|
+
const cacheSid = seg(sid, 'session')
|
|
527
|
+
const previous = await loadSession(cache.cid, cacheSid, cache.store).catch(() => null)
|
|
528
|
+
cache.check()
|
|
529
|
+
const snapshot = messages.length >= limit && messages[0]?.info?.id ? mergeTail(previous?.msgs, messages).messages : messages
|
|
530
|
+
const write = snapshot.length ? saveSession(cache.cid, cacheSid, snapshot, { dir: this._dirs.get(sid) || '' }, cache.store) : clearSession(cache.cid, cacheSid, cache.store)
|
|
531
|
+
await write.then(() => prune(cache.cid, undefined, cache.store)).catch(() => {})
|
|
532
|
+
}
|
|
533
|
+
} else if (cache && messages.length) {
|
|
534
|
+
// AN OLDER PAGE joins the offline copy when it is the page just before what the copy holds (side sweep: sdk-offline-older-code-pages):
|
|
535
|
+
// it was returned and never kept, so the same page read again offline was missing. A copy that starts elsewhere is left alone.
|
|
536
|
+
cache.check()
|
|
537
|
+
const cacheSid = seg(sid, 'session')
|
|
538
|
+
const previous = await loadSession(cache.cid, cacheSid, cache.store).catch(() => null)
|
|
539
|
+
cache.check()
|
|
540
|
+
const held = Array.isArray(previous?.msgs) ? previous.msgs : []
|
|
541
|
+
// …or a page whose cursor falls INSIDE the copy (a tail refresh after a new message hands a cursor there): the page ends
|
|
542
|
+
// right before a held message, so it runs on from the copy without a gap (side sweep round 2)
|
|
543
|
+
if (held.length && held.some(m => cursorBefore(m) === cursor)) {
|
|
544
|
+
const ids = new Set(held.map(m => m?.info?.id).filter(Boolean))
|
|
545
|
+
await saveSession(cache.cid, cacheSid, [...messages.filter(m => !ids.has(m?.info?.id)), ...held], { ...(typeof previous.title === 'string' ? { title: previous.title } : {}), dir: this._dirs.get(sid) || previous.dir || '' }, cache.store).catch(() => {})
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
const next = mayHaveMore(messages, limit) && cursorBefore(messages[0])
|
|
549
|
+
return { messages, cursor: next && next !== cursor ? next : null }
|
|
550
|
+
}
|
|
551
|
+
const changeAuto = async (sid, dir, on) => {
|
|
552
|
+
const transport = this._t
|
|
553
|
+
if (transport.autoSessions?.().includes(sid) === on) return
|
|
554
|
+
await new Promise((resolve, reject) => {
|
|
555
|
+
let off, timer
|
|
556
|
+
const finish = error => { clearTimeout(timer); off?.(); error ? reject(error) : resolve() }
|
|
557
|
+
const confirm = () => { if (transport.autoSessions?.().includes(sid) === on) finish() }
|
|
558
|
+
timer = setTimeout(() => finish(fail('timeout', 'the computer did not confirm Auto mode')), 25000)
|
|
559
|
+
off = transport.onAuto?.(confirm)
|
|
560
|
+
try {
|
|
561
|
+
if (!transport.setAuto(sid, dir, on)) finish(fail('unavailable', 'the computer could not switch Auto mode'))
|
|
562
|
+
else confirm()
|
|
563
|
+
} catch (error) { finish(error) }
|
|
564
|
+
})
|
|
565
|
+
}
|
|
566
|
+
const modeChanges = new Map()
|
|
567
|
+
this.preferredAgent = () => codeAgentPreference(this._owner._wb.account)
|
|
568
|
+
this.setPreferredAgent = async (sid, name) => {
|
|
569
|
+
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')
|
|
570
|
+
return codeAgentPreference(this._owner._wb.account, name)
|
|
571
|
+
}
|
|
572
|
+
this.onAutoVerdict = (sid, fn, { family = false } = {}) => {
|
|
573
|
+
if (!sid || typeof fn !== 'function') throw fail('invalid_argument', 'a session and callback are required')
|
|
574
|
+
if (!family) return transport.onAuto(e => { if (e?.kind === 'verdict' && e.verdict?.sessionID === sid) fn(e.verdict) })
|
|
575
|
+
const children = new Set(), pending = []
|
|
576
|
+
let active = true
|
|
577
|
+
const flush = () => {
|
|
578
|
+
for (let i = 0; i < pending.length;) {
|
|
579
|
+
if (!children.has(pending[i].sessionID)) { i++; continue }
|
|
580
|
+
const [v] = pending.splice(i, 1)
|
|
581
|
+
fn(v)
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
const offEvents = this.on('*', event => {
|
|
585
|
+
const id = childFromEvent(event, sid, children)
|
|
586
|
+
if (id) { children.add(id); flush() }
|
|
587
|
+
}, { session: sid })
|
|
588
|
+
const offAuto = transport.onAuto(e => {
|
|
589
|
+
if (e?.kind !== 'verdict' || !e.verdict?.sessionID) return
|
|
590
|
+
if (e.verdict.sessionID === sid || children.has(e.verdict.sessionID)) fn(e.verdict)
|
|
591
|
+
else { pending.push(e.verdict); if (pending.length > 100) pending.shift() }
|
|
592
|
+
})
|
|
593
|
+
Promise.all([this.sessions.list(), this.sessions.messages(sid)]).then(([sessions, messages]) => {
|
|
594
|
+
if (!active) return
|
|
595
|
+
for (const id of childIdsOf(sid, { sessions, messages })) children.add(id)
|
|
596
|
+
flush()
|
|
597
|
+
}).catch(() => {})
|
|
598
|
+
return () => { active = false; pending.length = 0; offEvents(); offAuto() }
|
|
599
|
+
}
|
|
600
|
+
this.onProgress = (sid, fn) => {
|
|
601
|
+
if (!sid || typeof fn !== 'function') throw fail('invalid_argument', 'a session and callback are required')
|
|
602
|
+
return transport.onProgress(m => { const p = normProgress(m); if (p?.sessionID === sid) fn(p) })
|
|
603
|
+
}
|
|
604
|
+
const effortKey = ref => 'wb-sdk:code-effort:' + JSON.stringify([owner._wb._endpoint, owner._wb._tenant, owner._wb._session?.email || '', computer.id, ref])
|
|
605
|
+
this.preferredEffort = ref => {
|
|
606
|
+
const key = effortKey(ref)
|
|
607
|
+
try { return globalThis.localStorage?.getItem(key) || this._efforts?.get(key) || '' } catch { return this._efforts?.get(key) || '' }
|
|
608
|
+
}
|
|
609
|
+
this.setPreferredEffort = async (sid, ref, effort) => {
|
|
610
|
+
const key = effortKey(ref)
|
|
611
|
+
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')
|
|
612
|
+
if (key !== effortKey(ref)) throw fail('account_changed', 'the account changed')
|
|
613
|
+
this._efforts ||= new Map()
|
|
614
|
+
if (effort) this._efforts.set(key, effort)
|
|
615
|
+
else this._efforts.delete(key)
|
|
616
|
+
try { if (effort) globalThis.localStorage?.setItem(key, effort); else globalThis.localStorage?.removeItem(key) } catch { /* current handle still remembers */ }
|
|
617
|
+
}
|
|
618
|
+
this.preferredModel = () => computerModelPreference(this._owner._wb.account, this.id)
|
|
619
|
+
this.setPreferredModel = async (sid, ref) => {
|
|
620
|
+
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')
|
|
621
|
+
return computerModelPreference(this._owner._wb.account, this.id, ref)
|
|
268
622
|
}
|
|
269
623
|
this.sessions = {
|
|
270
|
-
list: async () => {
|
|
271
|
-
|
|
272
|
-
|
|
624
|
+
list: async () => {
|
|
625
|
+
const list = await req('GET', '/experimental/session?archived=true')
|
|
626
|
+
if (!Array.isArray(list)) throw fail('unreadable', 'the computer did not return its sessions')
|
|
627
|
+
list.forEach(learn)
|
|
628
|
+
if (cache) {
|
|
629
|
+
cache.check()
|
|
630
|
+
await saveList(cache.cid, list.slice(0, 200).map(slimSession), cache.store, { allowEmpty: true }).catch(() => {})
|
|
631
|
+
cache.check()
|
|
632
|
+
}
|
|
633
|
+
return list
|
|
634
|
+
},
|
|
635
|
+
create: async ({ dir = '', title = '', agent = '', model = '' } = {}) => {
|
|
636
|
+
const picked = model ? parseModel(model) : null
|
|
637
|
+
if (model && !picked) throw fail('invalid_argument', 'choose a provider/model reference')
|
|
638
|
+
if (agent && (typeof agent !== 'string' || agent.length > 256)) throw fail('invalid_argument', 'choose a primary agent')
|
|
639
|
+
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 } } : {}) }))
|
|
640
|
+
},
|
|
641
|
+
messages: async (sid, opts) => (await messagePage(sid, opts)).messages,
|
|
642
|
+
messagePage,
|
|
643
|
+
saveDraft: (sid, parts) => {
|
|
644
|
+
seg(sid, 'session')
|
|
645
|
+
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')
|
|
646
|
+
const id = drafts.add(sid, { parts: structuredClone(parts), reason: 'unsent' })
|
|
647
|
+
if (!id) throw fail('computer_closed', 'The computer session is closed')
|
|
648
|
+
return id
|
|
649
|
+
},
|
|
650
|
+
listDrafts: sid => drafts.list(sid).map(({ id, reason }) => ({ id, reason })),
|
|
651
|
+
getDraft: (sid, id) => structuredClone(drafts.get(sid, id)),
|
|
652
|
+
discardDraft: (sid, id) => drafts.discard(sid, id),
|
|
653
|
+
promptLanded: async (sid, text, knownUserIds) => {
|
|
654
|
+
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')
|
|
655
|
+
const known = new Set(knownUserIds), visited = new Set()
|
|
656
|
+
let cursor
|
|
657
|
+
do {
|
|
658
|
+
const page = await this.sessions.messagePage(sid, { cursor })
|
|
659
|
+
if (promptLanded(page.messages, { knownUserIds: known, text })) return true
|
|
660
|
+
if (page.messages.some(m => m?.info?.role === 'user' && known.has(m.info.id))) return false
|
|
661
|
+
cursor = page.cursor
|
|
662
|
+
if (cursor && visited.has(cursor)) throw fail('submission_unknown', 'The computer returned the same history page twice.')
|
|
663
|
+
visited.add(cursor)
|
|
664
|
+
} while (cursor)
|
|
665
|
+
return false
|
|
666
|
+
},
|
|
667
|
+
watchFirstOutput: (sid, userMessageId, onStall, { timeoutMs = 60000 } = {}) => {
|
|
668
|
+
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')
|
|
669
|
+
let active = true, off = null
|
|
670
|
+
const stop = () => {
|
|
671
|
+
if (!active) return
|
|
672
|
+
active = false
|
|
673
|
+
clearTimeout(timer)
|
|
674
|
+
off?.()
|
|
675
|
+
this._firstOutputWatches.delete(stop)
|
|
676
|
+
}
|
|
677
|
+
const timer = setTimeout(async () => {
|
|
678
|
+
try {
|
|
679
|
+
const messages = await this.sessions.messages(sid)
|
|
680
|
+
const lastUser = messages.findLast(m => m?.info?.role === 'user')
|
|
681
|
+
if (active && lastUser?.info?.id === userMessageId && !firstOutputStarted(messages)) onStall({ sessionId: sid, userMessageId })
|
|
682
|
+
} catch { /* an unreadable conversation cannot establish a stalled reply */ }
|
|
683
|
+
finally { stop() }
|
|
684
|
+
}, timeoutMs)
|
|
685
|
+
this._firstOutputWatches.add(stop)
|
|
686
|
+
if (typeof transport.onProgress === 'function') off = this.onProgress(sid, p => { if (progressLine(p) || p.phase === 'end') stop() })
|
|
687
|
+
return stop
|
|
688
|
+
},
|
|
689
|
+
attachments: (sid, message) => (message?.parts || []).filter(p => p?.synthetic && p.type === 'text')
|
|
690
|
+
.flatMap(p => parseAttachmentNote(p.text) || []).filter(a => a.session === sid && validAttachmentRef(sid, a.file)),
|
|
691
|
+
readAttachment: async (sid, file) => {
|
|
692
|
+
if (!validAttachmentRef(sid, file)) throw fail('invalid_argument', 'an attachment reference from this session is required')
|
|
693
|
+
const result = await req('GET', ATTACHMENT_ROUTE + '?session=' + encodeURIComponent(sid) + '&file=' + encodeURIComponent(file))
|
|
694
|
+
if (typeof result?.b64 !== 'string') throw fail('unreadable', 'the computer did not return the attachment')
|
|
695
|
+
return result
|
|
696
|
+
},
|
|
697
|
+
attachmentWarning: async (sid, ref, file) => {
|
|
698
|
+
if (!file || typeof file.mime !== 'string') throw fail('invalid_argument', 'a file MIME type is required')
|
|
699
|
+
const catalog = await modelCatalog(sid)
|
|
700
|
+
const selected = ref || catalog.fallback
|
|
701
|
+
const model = catalog.offered.find(m => m.ref === selected)
|
|
702
|
+
return attachmentWarning({ mime: file.mime, modelLabel: model?.label || selected || 'this model', input: model?.input })
|
|
703
|
+
},
|
|
704
|
+
agents,
|
|
705
|
+
family: async sid => {
|
|
706
|
+
const [sessions, tail, approvals, questions] = await Promise.all([
|
|
707
|
+
this.sessions.list(), this.sessions.messages(sid), this.approvals.pending({ session: sid }), this.questions.pending({ session: sid }),
|
|
708
|
+
])
|
|
709
|
+
const children = [...childIdsOf(sid, { sessions, messages: tail })]
|
|
710
|
+
const family = new Set([sid, ...children])
|
|
711
|
+
return { children, approvals: approvals.filter(x => family.has(x.sessionID)), questions: questions.filter(x => family.has(x.sessionID)) }
|
|
712
|
+
},
|
|
713
|
+
approvalMode: async sid => {
|
|
714
|
+
await modeChanges.get(sid)
|
|
715
|
+
const [session, available] = await Promise.all([sessionCall(sid, 'GET'), agents(sid)])
|
|
716
|
+
const modes = ['manual', 'accept']
|
|
717
|
+
if (available.some(a => a.name === 'plan')) modes.push('plan')
|
|
718
|
+
if (this._t.can?.('auto')) modes.push('auto')
|
|
719
|
+
const agent = await agentFor(sid, available) || session?.agent || 'build'
|
|
720
|
+
const rules = Array.isArray(session?.permission) ? session.permission : []
|
|
721
|
+
const guarded = OC_ASK_PERMISSIONS.filter(p => p !== 'edit').every(p => {
|
|
722
|
+
const matching = rules.filter(r => typeof r?.permission === 'string' && wildcardMatch(p, r.permission))
|
|
723
|
+
const at = matching.findLastIndex(r => r.pattern === '*')
|
|
724
|
+
return at >= 0 && matching.slice(at).every(r => r.action === 'ask' || r.action === 'deny')
|
|
725
|
+
})
|
|
726
|
+
const edit = rules.findLast(r => (r.permission === 'edit' || r.permission === '*') && r.pattern === '*')
|
|
727
|
+
let mode = 'unknown'
|
|
728
|
+
if (this._t.autoSessions?.().includes(sid)) mode = 'auto'
|
|
729
|
+
else if (agent === 'plan') mode = 'plan'
|
|
730
|
+
else if (agent === 'build' && guarded && edit) mode = acceptsEdits(rules) ? 'accept' : 'manual'
|
|
731
|
+
return { mode, modes }
|
|
732
|
+
},
|
|
273
733
|
prompt: async (sid, text, opts = {}) => sendParts(sid, partsFor(text, opts.files), opts),
|
|
274
734
|
models,
|
|
275
735
|
archive: (sid, archived = true) => sessionCall(sid, 'PATCH', '', { time: { archived: archived ? Date.now() : 0 } }),
|
|
276
736
|
undo: async sid => {
|
|
277
|
-
const
|
|
278
|
-
|
|
737
|
+
const revert = normRevert((await sessionCall(sid, 'GET'))?.revert)
|
|
738
|
+
let cursor, messageID, atBoundary = !revert
|
|
739
|
+
const visited = new Set()
|
|
740
|
+
do {
|
|
741
|
+
const page = await messagePage(sid, { cursor, limit: PAGE })
|
|
742
|
+
if (!atBoundary) atBoundary = page.messages.some(m => m?.info?.id === revert.messageID)
|
|
743
|
+
if (atBoundary) messageID = undoTarget(page.messages, revert)
|
|
744
|
+
cursor = page.cursor
|
|
745
|
+
if (!cursor || visited.has(cursor)) break
|
|
746
|
+
visited.add(cursor)
|
|
747
|
+
} while (!messageID)
|
|
279
748
|
if (!messageID) return { changed: false, files: false }
|
|
280
749
|
const result = await sessionCall(sid, 'POST', '/revert', { messageID })
|
|
281
750
|
return { changed: true, files: !!normRevert(result?.revert)?.files }
|
|
@@ -294,13 +763,23 @@ export class Computer {
|
|
|
294
763
|
},
|
|
295
764
|
commands: async sid => normCommands(await req('GET', await inDir(sid, '/command'))),
|
|
296
765
|
runCommand: async (sid, text, opts = {}) => {
|
|
297
|
-
const
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
const
|
|
303
|
-
if (
|
|
766
|
+
const original = partsFor(text, opts.files)
|
|
767
|
+
let turn, picked
|
|
768
|
+
try {
|
|
769
|
+
turn = commandTurn(text, await this.sessions.commands(sid))
|
|
770
|
+
if (!turn || turn.blocked) throw fail(turn ? 'not_supported' : 'unknown_command', 'this project command is unavailable here')
|
|
771
|
+
const status = await this.sessions.status({ session: sid })
|
|
772
|
+
if (!status || typeof status !== 'object') throw fail('unreadable', 'the computer did not return its session status')
|
|
773
|
+
if (status[sid] && status[sid].type !== 'idle') throw fail('busy', 'wait for the current Code turn to finish')
|
|
774
|
+
picked = { ...opts }
|
|
775
|
+
if (turn.model && (await models(sid)).some(m => m.ref === turn.model)) picked.model = turn.model
|
|
776
|
+
if (turn.agent) {
|
|
777
|
+
const available = await agents(sid)
|
|
778
|
+
if (available.some(a => a.name === turn.agent)) picked.agent = turn.agent
|
|
779
|
+
}
|
|
780
|
+
} catch (error) {
|
|
781
|
+
error.draftId = drafts.add(sid, { reason: 'unsent', parts: structuredClone(original) })
|
|
782
|
+
throw error
|
|
304
783
|
}
|
|
305
784
|
return sendParts(sid, [{ type: 'text', text: turn.visible }, { type: 'text', text: turn.expanded, synthetic: true }, ...partsFor('', opts.files)], picked)
|
|
306
785
|
},
|
|
@@ -308,17 +787,47 @@ export class Computer {
|
|
|
308
787
|
if (!['manual', 'accept', 'plan', 'auto'].includes(mode)) throw fail('invalid_argument', 'unknown approval mode')
|
|
309
788
|
const auto = mode === 'auto', canAuto = !!this._t.can?.('auto')
|
|
310
789
|
if (auto && !canAuto) throw fail('not_supported', 'this computer does not offer Auto')
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
790
|
+
const change = (modeChanges.get(sid) || Promise.resolve()).catch(() => {}).then(async () => {
|
|
791
|
+
if (mode === 'plan' && !(await agents(sid)).some(a => a.name === 'plan')) throw fail('not_supported', 'this computer does not offer Plan')
|
|
792
|
+
const dir = await this._dirOf(sid)
|
|
793
|
+
if (canAuto && !auto) await changeAuto(sid, dir, false)
|
|
794
|
+
const session = await sessionCall(sid, 'GET')
|
|
795
|
+
const rules = Array.isArray(session?.permission) ? session.permission : []
|
|
796
|
+
const permission = []
|
|
797
|
+
for (const base of ocPermissionRuleset()) {
|
|
798
|
+
const last = rules.findLast(r => typeof r?.permission === 'string' && wildcardMatch(base.permission, r.permission) && r.pattern === '*')
|
|
799
|
+
const action = base.permission === 'edit' && mode === 'accept' ? 'allow' : base.action
|
|
800
|
+
if (last?.action === 'deny') continue
|
|
801
|
+
const editRules = base.permission === 'edit' && mode === 'accept' ? acceptEditsRules() : null
|
|
802
|
+
const protectedEdits = !editRules || editRules.every(target => rules.findLast(r => r.permission === 'edit' && r.pattern === target.pattern)?.action === target.action)
|
|
803
|
+
if (last?.action === action && protectedEdits) continue
|
|
804
|
+
permission.push(...(editRules || [{ ...base, action }]))
|
|
805
|
+
const scoped = new Map()
|
|
806
|
+
for (const r of rules) {
|
|
807
|
+
if (r.permission !== base.permission || r.pattern === '*') continue
|
|
808
|
+
if (r.action === 'deny' || base.permission === 'external_directory') scoped.set(r.pattern, r)
|
|
809
|
+
}
|
|
810
|
+
permission.push(...scoped.values())
|
|
811
|
+
}
|
|
812
|
+
if (permission.length) await sessionCall(sid, 'PATCH', '', { permission })
|
|
813
|
+
if (auto) await changeAuto(sid, dir, true)
|
|
814
|
+
modeAgents.set(sid, mode === 'plan' ? 'plan' : 'build')
|
|
815
|
+
return { mode }
|
|
816
|
+
})
|
|
817
|
+
modeChanges.set(sid, change)
|
|
818
|
+
try { return await change } finally { if (modeChanges.get(sid) === change) modeChanges.delete(sid) }
|
|
318
819
|
},
|
|
319
820
|
abort: async (sid) => req('POST', await inDir(sid, `/session/${seg(sid, 'session')}/abort`), {}),
|
|
320
821
|
rename: async (sid, title) => req('PATCH', await inDir(sid, `/session/${seg(sid, 'session')}`), { title: String(title || '').slice(0, 200) }),
|
|
321
|
-
remove: async (sid) => {
|
|
822
|
+
remove: async (sid) => {
|
|
823
|
+
const r = await req('DELETE', await inDir(sid, `/session/${seg(sid, 'session')}`))
|
|
824
|
+
this._dirs.delete(String(sid))
|
|
825
|
+
// …and its saved transcript on this device: cachedSession() still returned the deleted conversation (side sweep 2026-11-28).
|
|
826
|
+
// The cache is read through the account whether or not THIS handle opened it, so it is cleared the same way.
|
|
827
|
+
const saved = cache || await owner._cache(computer.id).catch(() => null)
|
|
828
|
+
if (saved) await removeCachedSession(saved.cid, seg(sid, 'session'), saved.store)
|
|
829
|
+
return r
|
|
830
|
+
},
|
|
322
831
|
todo: async (sid) => req('GET', await inDir(sid, `/session/${seg(sid, 'session')}/todo`)),
|
|
323
832
|
/** { <session id>: status } — `{ session }` or `{ dir }` for one folder; otherwise every folder's, joined. */
|
|
324
833
|
status: async (opts = {}) => {
|
|
@@ -329,17 +838,54 @@ export class Computer {
|
|
|
329
838
|
return out
|
|
330
839
|
},
|
|
331
840
|
}
|
|
841
|
+
this.connections = computerConnections(owner, computer)
|
|
842
|
+
const approveKey = async () => {
|
|
843
|
+
if (!computer.cloud?.grantKey) throw fail('not_supported', 'this computer has no key guard')
|
|
844
|
+
return (await sentinelKeys(computer.cloud.grantKey)).approve
|
|
845
|
+
}
|
|
846
|
+
this.keyGuard = {
|
|
847
|
+
pending: async () => {
|
|
848
|
+
const key = await approveKey()
|
|
849
|
+
const reply = await req('GET', '/witbitz/sentinel/asks')
|
|
850
|
+
if (!Array.isArray(reply?.asks)) throw fail('unreadable', 'the key guard did not return its requests')
|
|
851
|
+
const pending = []
|
|
852
|
+
for (const ask of reply.asks) {
|
|
853
|
+
if (typeof ask?.id === 'string' && ask.expires > Date.now() && await askGenuine(key, ask)) pending.push(ask)
|
|
854
|
+
}
|
|
855
|
+
return pending
|
|
856
|
+
},
|
|
857
|
+
decide: async (ask, allow) => {
|
|
858
|
+
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')
|
|
859
|
+
const key = await approveKey()
|
|
860
|
+
const id = ask.id
|
|
861
|
+
if (!(await askGenuine(key, ask))) throw fail('unverified', 'the key guard could not verify this request')
|
|
862
|
+
return req('POST', '/witbitz/sentinel/decide', { id, allow, tag: await decideTag(key, id, allow) })
|
|
863
|
+
},
|
|
864
|
+
}
|
|
332
865
|
this.approvals = {
|
|
866
|
+
refusalOf,
|
|
867
|
+
folders: async (sid, id) => {
|
|
868
|
+
if (!this._t.can?.('folders')) return []
|
|
869
|
+
const result = await req('GET', await inDir(sid, FOLDER_ROUTE + '?ask=' + seg(id, 'approval')))
|
|
870
|
+
return (result?.folders || []).filter(f => f && typeof f.path === 'string')
|
|
871
|
+
},
|
|
872
|
+
allowFolder: async (sid, id) => {
|
|
873
|
+
if (!this._t.can?.('folders')) throw fail('not_supported', 'this computer does not offer folder approvals')
|
|
874
|
+
const pending = await this.approvals.pending({ session: sid })
|
|
875
|
+
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')
|
|
876
|
+
if (!(await this.approvals.folders(sid, id)).length) throw fail('not_offered', 'the computer offered no folder for this request')
|
|
877
|
+
return req('POST', await inDir(sid, FOLDER_ROUTE), { ask: id })
|
|
878
|
+
},
|
|
333
879
|
/** Every approval waiting, in every folder — or `{ session }` / `{ dir }` for one. */
|
|
334
880
|
pending: async (opts = {}) => listEverywhere('/permission', opts),
|
|
335
881
|
/** 'once' | 'always' | 'reject'; a reject may carry a message for the model ("stop and ask me"). */
|
|
336
882
|
answer: async (id, response, { session = '', message = '' } = {}) => {
|
|
337
883
|
if (!['once', 'always', 'reject'].includes(response)) throw fail('invalid_argument', "an approval is 'once', 'always' or 'reject'")
|
|
338
|
-
if (response === 'reject'
|
|
884
|
+
if (response === 'reject') {
|
|
339
885
|
// 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
886
|
// in the session's FOLDER (sync sweep 11-08: an approval in another folder than the default was never found)
|
|
341
887
|
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 }
|
|
888
|
+
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
889
|
}
|
|
344
890
|
if (!session) throw fail('invalid_argument', 'answering an approval needs its session id (the event carries it as sessionID)')
|
|
345
891
|
return req('POST', await inDir(session, `/session/${seg(session, 'session')}/permissions/${seg(id, 'approval')}`), { response })
|
|
@@ -360,7 +906,7 @@ export class Computer {
|
|
|
360
906
|
mkdir: async (sid, parent, name) => {
|
|
361
907
|
const relative = String(parent || ''), leaf = String(name || '').trim()
|
|
362
908
|
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 })
|
|
909
|
+
return req('POST', sid === null ? withDir(mkdirPath(relative), CLOUD_HOME) : await inDir(sid, mkdirPath(relative)), { name: leaf })
|
|
364
910
|
},
|
|
365
911
|
// the folder's project: `{ session }` (that session's folder) or `{ dir }`; neither = the computer's default project
|
|
366
912
|
list: async (path = '', opts = {}) => req('GET', withDir('/file?path=' + encodeURIComponent(String(path || '')), (await scopeOf(opts)) || '')),
|
|
@@ -405,6 +951,11 @@ export class Computer {
|
|
|
405
951
|
if (!this._t.setBrowsePrivate(!!on)) throw fail('offline', 'the computer is not connected')
|
|
406
952
|
return true
|
|
407
953
|
},
|
|
954
|
+
setDefaultPrivate: async on => {
|
|
955
|
+
if (typeof on !== 'boolean') throw fail('invalid_argument', 'choose true or false')
|
|
956
|
+
await owner._patchCloud(computer, { browsePrivate: on ? true : null })
|
|
957
|
+
computer.cloud.browsePrivate = on
|
|
958
|
+
},
|
|
408
959
|
setSessionPrivate: (session, on) => setSessionPrivate({ ...this._c.cloud, relay: this._c.relay }, session, on),
|
|
409
960
|
}
|
|
410
961
|
this.egress = { get: () => (this._t.egress ? this._t.egress() : null) }
|
|
@@ -417,9 +968,57 @@ export class Computer {
|
|
|
417
968
|
const sid = String(session || ''); seg(sid, 'session')
|
|
418
969
|
const info = await this._req('GET', `/session/${encodeURIComponent(sid)}`)
|
|
419
970
|
if (info && typeof info.directory === 'string' && info.directory) this._dirs.set(sid, info.directory)
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
971
|
+
const page = async (cursor) => (await this._req('GET', withDir(`/session/${encodeURIComponent(sid)}/message?${pageQuery({ limit: PAGE, cursor })}`, this._dirs.get(sid) || ''))) || []
|
|
972
|
+
let ms = Array.isArray(messages) ? messages : await page('')
|
|
973
|
+
// A LONG REPLY runs past one page: read back (a page at a time) until its prompt is in view or the session's start, so a file it
|
|
974
|
+
// wrote early is not left out (side sweep: sdk-code-outputs-truncate-long-reply; round 5: a bound of 25 pages cut a longer reply
|
|
975
|
+
// with no sign of it).
|
|
976
|
+
if (!Array.isArray(messages)) {
|
|
977
|
+
const rev = normRevert(info && info.revert)
|
|
978
|
+
for (let got = ms; mayHaveMore(got, PAGE) && !visibleMessages(ms, rev).some((m) => m && m.info && m.info.role === 'user');) {
|
|
979
|
+
const cursor = cursorBefore(ms[0]); if (!cursor) break
|
|
980
|
+
got = await page(cursor)
|
|
981
|
+
if (!Array.isArray(got) || !got.length) break
|
|
982
|
+
const have = new Set(ms.map((m) => m && m.info && m.info.id))
|
|
983
|
+
const older = got.filter((m) => m && m.info && !have.has(m.info.id))
|
|
984
|
+
if (!older.length) break // a page with nothing new (a server that ignored the cursor): never ask for it again
|
|
985
|
+
ms = [...older, ...ms]
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
let asked = 0 // when the prompt was sent, when known: a named file must have changed since (as the app's cards ask)
|
|
989
|
+
// the latest reply: after the last prompt STILL SHOWING — an undone turn (the session's revert point) is hidden first, as the app
|
|
990
|
+
// does before it draws output cards (side sweep: sdk-code-outputs-include-undone-reply)
|
|
991
|
+
// A revert point OLDER than the page read: every message read is undone — read back until it is found, with a prompt before it
|
|
992
|
+
// (side sweep round 2). Not found within the bound: no reply shows, and nothing is listed rather than an undone file.
|
|
993
|
+
const rv = !Array.isArray(messages) && normRevert(info && info.revert)
|
|
994
|
+
if (rv) {
|
|
995
|
+
const at = () => ms.findIndex((m) => m && m.info && m.info.id === rv.messageID)
|
|
996
|
+
const userBefore = () => ms.slice(0, at()).some((m) => m && m.info && m.info.role === 'user')
|
|
997
|
+
let more = mayHaveMore(ms, 20)
|
|
998
|
+
for (let n = 0; more && (at() < 0 || !userBefore()) && n < 10; n++) {
|
|
999
|
+
const page = (await this._req('GET', withDir(`/session/${encodeURIComponent(sid)}/message?${pageQuery({ limit: PAGE, cursor: cursorBefore(ms[0]) })}`, this._dirs.get(sid) || ''))) || []
|
|
1000
|
+
if (!Array.isArray(page) || !page.length) { more = false; break }
|
|
1001
|
+
const have = new Set(ms.map((m) => m && m.info && m.info.id))
|
|
1002
|
+
ms = [...page.filter((m) => m && m.info && !have.has(m.info.id)), ...ms]
|
|
1003
|
+
more = mayHaveMore(page, PAGE)
|
|
1004
|
+
}
|
|
1005
|
+
if (more && at() < 0) ms = [] // stopped at the bound with the revert point still further back (a point not in the history hides nothing)
|
|
1006
|
+
}
|
|
1007
|
+
if (!Array.isArray(messages)) { ms = visibleMessages(ms, rv); const k = ms.map((m) => m && m.info && m.info.role).lastIndexOf('user'); asked = k >= 0 ? Number(ms[k].info.time && ms[k].info.time.created) || 0 : 0; ms = k >= 0 ? ms.slice(k + 1) : ms } // the latest reply: after the last prompt
|
|
1008
|
+
const outs = replyOutputs(ms, { directory: (info && info.directory) || '', session: sid })
|
|
1009
|
+
// A path the answer only NAMES is an output only once the computer says the file is there — and, when the prompt's time is
|
|
1010
|
+
// known, that it changed since (codeOutputCards.js, the same rule; side sweep: sdk-code-outputs-list-unconfirmed-file-mentions).
|
|
1011
|
+
// A file the reply wrote, and a screenshot, come from its tools and are listed as before.
|
|
1012
|
+
const named = outs.filter((o) => o.source === 'named')
|
|
1013
|
+
if (!named.length) return outs
|
|
1014
|
+
const ok = new Set()
|
|
1015
|
+
await Promise.all(named.map(async (o) => {
|
|
1016
|
+
try {
|
|
1017
|
+
const r = await this._t.request('GET', `${OUTPUT_ROUTE}?session=${encodeURIComponent(sid)}&path=${encodeURIComponent(o.path)}&stat=1`)
|
|
1018
|
+
if (r && r.ok && r.json && (!asked || Number(r.json.mtime) >= asked - 2000)) ok.add(o)
|
|
1019
|
+
} catch { /* not confirmed: left out, as the app hides its card */ }
|
|
1020
|
+
}))
|
|
1021
|
+
return outs.filter((o) => o.source !== 'named' || ok.has(o))
|
|
423
1022
|
}
|
|
424
1023
|
|
|
425
1024
|
/** 'online' | 'connecting' | 'offline' */
|
|
@@ -435,13 +1034,21 @@ export class Computer {
|
|
|
435
1034
|
}
|
|
436
1035
|
|
|
437
1036
|
/** @private a session's directory — learned once, then kept ('' when the computer does not say) */
|
|
438
|
-
|
|
1037
|
+
// `strict`: a failed ask THROWS instead of answering '' (the default project) — a call scoped to one session must not run in
|
|
1038
|
+
// another folder (side sweep: sdk-code-file-list-default-after-folder-lookup-failure)
|
|
1039
|
+
async _dirOf (sid, { strict = false } = {}) {
|
|
1040
|
+
const r = await this._dirLookup(sid)
|
|
1041
|
+
if (!r.known && strict) throw fail('unreadable', 'could not find the session’s folder on the computer', { cause: r.err })
|
|
1042
|
+
return r.d
|
|
1043
|
+
}
|
|
1044
|
+
/** @private → { d, known, err }: `known` false = the ask failed (asked again next time) */
|
|
1045
|
+
async _dirLookup (sid) {
|
|
439
1046
|
const id = String(sid || '')
|
|
440
|
-
if (this._dirs.has(id)) return this._dirs.get(id)
|
|
441
|
-
let d = '', known = false
|
|
442
|
-
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 = '' }
|
|
1047
|
+
if (this._dirs.has(id)) return { d: this._dirs.get(id), known: true }
|
|
1048
|
+
let d = '', known = false, err = null
|
|
1049
|
+
try { const info = await this._req('GET', `/session/${encodeURIComponent(seg(id, 'session') && id)}`); d = info && typeof info.directory === 'string' ? info.directory : ''; known = true } catch (e) { d = ''; err = e }
|
|
443
1050
|
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
|
|
444
|
-
return d
|
|
1051
|
+
return { d, known, err }
|
|
445
1052
|
}
|
|
446
1053
|
|
|
447
1054
|
/** Live events from the computer (OpenCode's, parsed): `on('message.part.updated', fn)`, or `on('*', fn)` for all. → off
|
|
@@ -449,9 +1056,10 @@ export class Computer {
|
|
|
449
1056
|
* server's default folder — without it, its events never arrive. */
|
|
450
1057
|
on (type, fn, { session = '', dir = '' } = {}) {
|
|
451
1058
|
if (typeof fn !== 'function') throw fail('invalid_argument', 'on(type, fn) needs a function')
|
|
452
|
-
let off = false, stream = null
|
|
1059
|
+
let off = false, stream = null, streamDir = '', waiter = null
|
|
453
1060
|
const attach = (d) => {
|
|
454
1061
|
if (off) return
|
|
1062
|
+
streamDir = d
|
|
455
1063
|
stream = this._streams.get(d)
|
|
456
1064
|
if (!stream) {
|
|
457
1065
|
stream = { subs: new Map(), stop: null }
|
|
@@ -464,17 +1072,39 @@ export class Computer {
|
|
|
464
1072
|
if (!stream.subs.has(type)) stream.subs.set(type, new Set())
|
|
465
1073
|
stream.subs.get(type).add(fn)
|
|
466
1074
|
}
|
|
1075
|
+
const detach = () => {
|
|
1076
|
+
const listeners = stream?.subs.get(type)
|
|
1077
|
+
if (!listeners || !listeners.delete(fn)) return
|
|
1078
|
+
if (!listeners.size) stream.subs.delete(type)
|
|
1079
|
+
if (!stream.subs.size && this._streams.get(streamDir) === stream) {
|
|
1080
|
+
this._streams.delete(streamDir)
|
|
1081
|
+
stream.stop?.()
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
467
1084
|
if (dir || !session) attach(String(dir || ''))
|
|
468
|
-
else
|
|
469
|
-
|
|
1085
|
+
else {
|
|
1086
|
+
// A FAILED FOLDER LOOKUP is asked again (side sweep: sdk-code-event-listener-keeps-default-folder): the listener waits on the
|
|
1087
|
+
// default stream meanwhile, and MOVES to the session's folder once it is learned — it stayed on the default one for good.
|
|
1088
|
+
const lookup = (n) => this._dirLookup(session).then(({ d, known }) => {
|
|
1089
|
+
if (off) return
|
|
1090
|
+
if (known) { if (!stream) attach(d); else if (d !== streamDir) { detach(); stream = null; attach(d) } return }
|
|
1091
|
+
if (!stream) attach('')
|
|
1092
|
+
if (n < 5) { setTimeout(() => lookup(n + 1), (this._dirRetryMs ?? 2000) * 2 ** n); return }
|
|
1093
|
+
// the retries are spent: move when any later read (a session list, a message read) learns the folder
|
|
1094
|
+
waiter = (d) => { waiter = null; if (!off && d !== streamDir) { detach(); stream = null; attach(d) } }
|
|
1095
|
+
if (!this._dirWaiters.has(String(session))) this._dirWaiters.set(String(session), new Set())
|
|
1096
|
+
this._dirWaiters.get(String(session)).add(waiter)
|
|
1097
|
+
}, () => { if (!off && !stream) attach('') })
|
|
1098
|
+
lookup(0)
|
|
1099
|
+
}
|
|
1100
|
+
return () => { off = true; if (waiter) this._dirWaiters.get(String(session))?.delete(waiter); detach() }
|
|
470
1101
|
}
|
|
471
1102
|
|
|
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
|
|
1103
|
+
_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
1104
|
|
|
474
1105
|
/** Close it: a last save, then the enclave stops (its hours stop counting). */
|
|
475
1106
|
async close () {
|
|
476
1107
|
this._stop()
|
|
477
|
-
|
|
478
|
-
return this._owner._d.close(this._c, { token, fetchImpl: this._owner._d.fetch })
|
|
1108
|
+
return this._owner._closeComputer(this._c)
|
|
479
1109
|
}
|
|
480
1110
|
}
|