@witbitz/sdk 0.0.0-stage → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/a2aCore.js +221 -0
- package/a2aShared.js +27 -0
- package/accountErase.js +228 -0
- package/accountIndexDoc.js +122 -0
- package/accountOwner.js +59 -0
- package/accountRecord.js +90 -0
- package/accountScope.js +114 -0
- package/accountSeal.js +42 -0
- package/accountStores.js +173 -0
- package/acctV2App.js +619 -0
- package/acctV2Check.js +29 -0
- package/acctV2Client.js +382 -0
- package/acctV2Keys.js +43 -0
- package/acctV2Legacy.js +14 -0
- package/acctV2Switch.js +80 -0
- package/acctV2UiCore.js +857 -0
- package/acctV2WebAuthn.js +61 -0
- package/acctV2Wire.js +59 -0
- package/address.js +42 -0
- package/agentDoorTools.js +28 -0
- package/attestedBox.js +30 -0
- package/attestedRooms.js +78 -0
- package/awsKey.js +98 -0
- package/backupRecord.js +106 -0
- package/backupVault.js +97 -0
- package/blocks.js +115 -0
- package/blocksPush.js +64 -0
- package/browseSeal.js +103 -0
- package/cbor.js +225 -0
- package/changePush.js +75 -0
- package/chatLock.js +165 -0
- package/chatLockSw.js +13 -0
- package/cloudDeviceBuilds.js +11 -0
- package/cloudDevicePins.js +33 -0
- package/cloudDeviceSeal.js +53 -0
- package/codeAttachments.js +100 -0
- package/codeBrowse.js +224 -0
- package/codeCache.js +149 -0
- package/codeCloud.js +650 -0
- package/codeCloudKeys.js +112 -0
- package/codeCommands.js +167 -0
- package/codeComputers.js +389 -0
- package/codeEgress.js +123 -0
- package/codeFilesRoutes.js +17 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeMkdir.js +8 -0
- package/codeModes.js +59 -0
- package/codeOrphanKeys.js +42 -0
- package/codeOutputs.js +141 -0
- package/codeProgress.js +54 -0
- package/codeRelay.js +505 -0
- package/codeSent.js +68 -0
- package/codeSentinel.js +86 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +317 -0
- package/codeUndo.js +48 -0
- package/compress.js +24 -0
- package/config.js +11 -0
- package/connCatalog.js +164 -0
- package/connDisp.js +76 -0
- package/connOtherWays.js +74 -0
- package/connPending.js +16 -0
- package/connWrap.js +53 -0
- package/connectionEntry.js +89 -0
- package/connections.js +561 -0
- package/credits.js +30 -0
- package/csAttest.js +112 -0
- package/decrypt.html +384 -0
- package/deviceAttest.js +527 -0
- package/deviceCall.js +54 -0
- package/deviceKeyCore.js +41 -0
- package/deviceSeal.js +59 -0
- package/e2ee.js +323 -0
- package/eat.js +103 -0
- package/emailFork.js +275 -0
- package/emailSignIn.js +81 -0
- package/emptySpaces.js +111 -0
- package/encSource.js +55 -0
- package/enclaveAccept.js +214 -0
- package/enclaveClaim.js +241 -0
- package/enclaveRoute.js +102 -0
- package/enclaveSnapshotMerge.js +44 -0
- package/entrySig.js +165 -0
- package/env.js +73 -0
- package/eraseFile.js +58 -0
- package/followImage.js +86 -0
- package/healNames.js +45 -0
- package/idb.js +113 -0
- package/idbSeal.js +119 -0
- package/indexGone.js +12 -0
- package/invite.js +51 -0
- package/inviteEnroll.js +67 -0
- package/inviteSend.js +68 -0
- package/jobAgents.js +87 -0
- package/keptMerge.js +91 -0
- package/l1-worker-src.js +2 -0
- package/l1-worker.js +894 -0
- package/laneAssociation.js +68 -0
- package/laneConfig.js +58 -0
- package/laneLinkCore.js +177 -0
- package/ledgerView.js +64 -0
- package/manifest.json +239 -0
- package/mcpRecommended.js +25 -0
- package/memberChange.js +125 -0
- package/mirrorBatch.js +47 -0
- package/mkseal.js +101 -0
- package/nativePush.js +153 -0
- package/nitroVerify.js +220 -0
- package/noble-p256.js +27 -0
- package/notice.js +116 -0
- package/notifKey.js +58 -0
- package/offlineBundle.js +62 -0
- package/ohttp.js +177 -0
- package/opRouting.js +10 -0
- package/opencodeWire.js +282 -0
- package/oprf.js +70 -0
- package/ownAgentLink.js +96 -0
- package/ownerPolicy.js +117 -0
- package/package.json +273 -4
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/pollVerdict.js +33 -0
- package/prefetchPoll.js +60 -0
- package/protectedLocal.js +426 -0
- package/pushCore.js +42 -0
- package/recovery.js +107 -0
- package/regions.js +42 -0
- package/removedMessage.js +11 -0
- package/renameRefusal.js +9 -0
- package/replyQuote.js +34 -0
- package/reqEnvelope.js +126 -0
- package/roomDefaultPrefs.js +76 -0
- package/roomDelete.js +109 -0
- package/roomEmbed.js +111 -0
- package/roomName.js +177 -0
- package/roomPass.js +256 -0
- package/roomRoster.js +305 -0
- package/roomSettings.js +61 -0
- package/roomState.js +58 -0
- package/roomStreamClient.js +115 -0
- package/rosterCount.js +52 -0
- package/rosterHash.js +13 -0
- package/rowSchema.js +113 -0
- package/safeMedia.js +116 -0
- package/safeMediaPins.js +17 -0
- package/schedulesDoc.js +78 -0
- package/sdkA2A.js +524 -0
- package/sdkAccount.js +483 -0
- package/sdkAccountDoc.js +89 -0
- package/sdkAccountSections.js +332 -0
- package/sdkAgui.js +141 -0
- package/sdkAttest.js +34 -0
- package/sdkBackup.js +507 -0
- package/sdkBackupV2.js +630 -0
- package/sdkBrowserPrivate.js +28 -0
- package/sdkBuilds.js +208 -0
- package/sdkCloudDevice.js +221 -0
- package/sdkComputers.js +1009 -0
- package/sdkDictation.js +232 -0
- package/sdkErase.js +288 -0
- package/sdkExports.js +71 -0
- package/sdkInvitations.js +34 -0
- package/sdkKeptAgent.js +188 -0
- package/sdkLaneLink.js +205 -0
- package/sdkPlan.js +96 -0
- package/sdkProtect.js +228 -0
- package/sdkRedact.js +36 -0
- package/sdkRekey.js +340 -0
- package/sdkReport.js +68 -0
- package/sdkSafeMedia.js +255 -0
- package/sdkSchedules.js +39 -0
- package/sdkSpeech.js +71 -0
- package/sdkTemporaryRooms.js +123 -0
- package/sdkTurn.js +117 -0
- package/sdkVault.js +180 -0
- package/sealShare.js +18 -0
- package/sealedNames.js +64 -0
- package/sealedReceipt.js +17 -0
- package/sentinelRelease.js +155 -0
- package/shamir.js +85 -0
- package/sharedViews.js +52 -0
- package/sheetChrome.js +450 -0
- package/siri.js +278 -0
- package/spaceClient.js +1429 -0
- package/spaceConfig.js +81 -0
- package/spaceEmailGate.js +813 -0
- package/spaceExport.js +125 -0
- package/spaceFork.js +216 -0
- package/spaceLock.js +358 -0
- package/spacePasskey.js +180 -0
- package/spaceTemplates.js +99 -0
- package/speechOut.js +102 -0
- package/splitKeyClient.js +90 -0
- package/store.js +656 -0
- package/streamHint.js +36 -0
- package/sttCloud.js +220 -0
- package/sttWorklet.js +38 -0
- package/sw-notif-core.js +540 -0
- package/tempList.js +48 -0
- package/tinfoilVerifier.js +78 -0
- package/toolBooks.js +31 -0
- package/toolRules.js +52 -0
- package/turnCerts.js +254 -0
- package/turnFeed.js +58 -0
- package/turnVerdict.js +37 -0
- package/usageReceipts.js +176 -0
- package/usageSummary.js +90 -0
- package/util.js +181 -0
- package/vault-core.js +2326 -0
- package/vault-kit.mjs +354 -0
- package/vault-screens.js +261 -0
- package/vaultAtRest.js +208 -0
- package/vaultCoreLock.js +111 -0
- package/vaultCorePush.js +140 -0
- package/vaultDeviceKey.js +95 -0
- package/vaultEnclaveHandoff.js +114 -0
- package/vaultKeep.js +287 -0
- package/vaultSealedStore.js +77 -0
- package/vaultWorkerHost.js +117 -0
- package/vcWorker.js +34 -0
- package/voiceAttest.js +50 -0
- package/voiceCert.js +51 -0
- package/witbitz-admin.d.ts +135 -0
- package/witbitz-admin.js +529 -0
- package/witbitz-admin.mjs +1460 -0
- package/witbitz-sdk.d.ts +1197 -0
- package/witbitz-sdk.js +4258 -0
- package/workerClient.js +16 -0
- package/workerLiveness.js +21 -0
- package/x509.js +218 -0
package/codeRelay.js
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
// codeRelay.js — the sealed wire between the Code section and the connector on your computer (docs/opencode-relay.md).
|
|
2
|
+
//
|
|
3
|
+
// ONE module for both ends: the page imports it in the browser, tools/opencode-connector.mjs imports it in Node ≥ 22.
|
|
4
|
+
// Pure WebCrypto + the global WebSocket, so the two ends cannot drift. The Python package (witbitz-code) is held to it
|
|
5
|
+
// by the vectors in spaces/test/codeRelay.test.mjs.
|
|
6
|
+
//
|
|
7
|
+
// secret S (32 bytes, per computer × account pairing)
|
|
8
|
+
// ├─ channel = b64url(HKDF(S, "channel")) → wss://code-relay.witbitz.chat/c/<channel> (the relay's routing key)
|
|
9
|
+
// ├─ kC2S = HKDF(S, "client-to-computer") → AES-256-GCM, page → computer
|
|
10
|
+
// └─ kS2C = HKDF(S, "computer-to-client") → AES-256-GCM, computer → page
|
|
11
|
+
//
|
|
12
|
+
// A frame on the socket: {"v":1,"s":<sender id>,"q":<seq>,"n":<iv>,"c":<ciphertext>} — AAD "wbcr1|v|s|q", so the clear
|
|
13
|
+
// header is authenticated; receivers drop any q ≤ the last one seen from that sender (replay).
|
|
14
|
+
|
|
15
|
+
import { sensitivePath } from './codeOutputs.js' // a changed file whose name looks like a secret: its patch stays on the computer
|
|
16
|
+
|
|
17
|
+
export const RELAY_URL = 'wss://code-relay.witbitz.chat'
|
|
18
|
+
const SALT = 'witbitz-code-relay-v1'
|
|
19
|
+
const te = new TextEncoder()
|
|
20
|
+
const td = new TextDecoder()
|
|
21
|
+
|
|
22
|
+
// ── base64url ────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
23
|
+
export function b64u(bytes) {
|
|
24
|
+
let s = ''
|
|
25
|
+
const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
|
|
26
|
+
for (let i = 0; i < b.length; i += 0x8000) s += String.fromCharCode.apply(null, b.subarray(i, i + 0x8000))
|
|
27
|
+
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
28
|
+
}
|
|
29
|
+
export function unb64u(str) {
|
|
30
|
+
const s = String(str).replace(/-/g, '+').replace(/_/g, '/')
|
|
31
|
+
const bin = atob(s + '='.repeat((4 - (s.length % 4)) % 4))
|
|
32
|
+
const out = new Uint8Array(bin.length)
|
|
33
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
34
|
+
return out
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A new pairing secret: 32 random bytes, base64url. */
|
|
38
|
+
export const newRelaySecret = () => b64u(crypto.getRandomValues(new Uint8Array(32)))
|
|
39
|
+
|
|
40
|
+
// ── keys ─────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
41
|
+
/** Secret → { channel, c2s, s2c }. Throws on a secret that is not 32 bytes (a truncated copy must fail loudly). */
|
|
42
|
+
export async function deriveRelay(secret) {
|
|
43
|
+
const raw = unb64u(secret)
|
|
44
|
+
if (raw.length !== 32) throw new Error('relay secret must be 32 bytes')
|
|
45
|
+
const base = await crypto.subtle.importKey('raw', raw, 'HKDF', false, ['deriveBits', 'deriveKey'])
|
|
46
|
+
const params = (info) => ({ name: 'HKDF', hash: 'SHA-256', salt: te.encode(SALT), info: te.encode(info) })
|
|
47
|
+
const channel = b64u(await crypto.subtle.deriveBits(params('channel'), base, 256))
|
|
48
|
+
const key = (info) => crypto.subtle.deriveKey(params(info), base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
|
|
49
|
+
return { channel, c2s: await key('client-to-computer'), s2c: await key('computer-to-client') }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** THE AGENT'S BROWSER ON THIS COMPUTER (tools/browse-local.mjs): its viewer key, derived from the pairing secret the page and
|
|
53
|
+
* the computer already share — nothing new travels, and every paired device can watch. Base64 of 32 bytes, the shape a cloud
|
|
54
|
+
* computer's random `cloud.browse` has (browseSeal.js browseKey). Held equal to relay.py browse_key by a vector test. */
|
|
55
|
+
export async function deriveBrowseKey(secret) {
|
|
56
|
+
const raw = unb64u(secret)
|
|
57
|
+
if (raw.length !== 32) throw new Error('relay secret must be 32 bytes')
|
|
58
|
+
const base = await crypto.subtle.importKey('raw', raw, 'HKDF', false, ['deriveBits'])
|
|
59
|
+
const bits = new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: te.encode(SALT), info: te.encode('browse') }, base, 256))
|
|
60
|
+
let s = ''; for (const b of bits) s += String.fromCharCode(b)
|
|
61
|
+
return btoa(s)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ── frames ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
65
|
+
const aadOf = (v, s, q) => te.encode(`wbcr1|${v}|${s}|${q}`)
|
|
66
|
+
|
|
67
|
+
/** A sealer for ONE socket: its own random sender id and a counter. */
|
|
68
|
+
export function makeSealer(key) {
|
|
69
|
+
const s = b64u(crypto.getRandomValues(new Uint8Array(12)))
|
|
70
|
+
let q = 0
|
|
71
|
+
return {
|
|
72
|
+
sender: s,
|
|
73
|
+
async seal(msg) {
|
|
74
|
+
// ★ Take the sequence number BEFORE the await. Reading the shared counter after encrypt() stamped every frame of a
|
|
75
|
+
// concurrent burst with the LAST number — the page fires several requests at boot — so the header no longer
|
|
76
|
+
// matched the AAD it was sealed with, and the connector dropped them all.
|
|
77
|
+
const seq = ++q
|
|
78
|
+
const iv = crypto.getRandomValues(new Uint8Array(12))
|
|
79
|
+
const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aadOf(1, s, seq) }, key, te.encode(JSON.stringify(msg)))
|
|
80
|
+
return JSON.stringify({ v: 1, s, q: seq, n: b64u(iv), c: b64u(ct) })
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** An opener: the other direction's key + a replay window per sender. Returns the message object, or null for anything
|
|
86
|
+
* that is not a valid, fresh frame for this key (junk, the relay's own control frames, the wrong key, a replay). */
|
|
87
|
+
export function makeOpener(key, { maxSenders = 64, onEvict = () => {} } = {}) {
|
|
88
|
+
const last = new Map() // sender → highest q accepted
|
|
89
|
+
return {
|
|
90
|
+
async open(text) {
|
|
91
|
+
let f
|
|
92
|
+
try { f = typeof text === 'string' ? JSON.parse(text) : null } catch { return null }
|
|
93
|
+
if (!f || f.v !== 1 || typeof f.s !== 'string' || !Number.isSafeInteger(f.q) || f.q < 1 || typeof f.n !== 'string' || typeof f.c !== 'string') return null
|
|
94
|
+
if (f.q <= (last.get(f.s) || 0)) return null
|
|
95
|
+
let pt
|
|
96
|
+
try { pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64u(f.n), additionalData: aadOf(f.v, f.s, f.q) }, key, unb64u(f.c)) } catch { return null }
|
|
97
|
+
// Re-check after the await: two frames from one sender can race through decrypt.
|
|
98
|
+
if (f.q <= (last.get(f.s) || 0)) return null
|
|
99
|
+
last.delete(f.s); last.set(f.s, f.q)
|
|
100
|
+
// A sender pushed out of the window could have its recorded frames replayed from now on — so say so: the connector
|
|
101
|
+
// rotates its nonce, which voids every request that sender ever sealed (review finding, round 2).
|
|
102
|
+
if (last.size > maxSenders) { const gone = last.keys().next().value; last.delete(gone); try { onEvict(gone) } catch { /* */ } }
|
|
103
|
+
try { return JSON.parse(td.decode(pt)) } catch { return null }
|
|
104
|
+
},
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ── the relay's heartbeat ────────────────────────────────────────────────────────────────────────────────────────
|
|
109
|
+
// A dead network path can leave a socket "open" for a quarter of an hour: send() never fails, TCP retries in silence.
|
|
110
|
+
// Measured 2026-09-14: after a blip the connector's relay socket held 942 KB unacknowledged for 10 minutes while its log
|
|
111
|
+
// said "relay open" — the relay still counted it, so the phone found "a computer" that never answered ("my laptop is
|
|
112
|
+
// offline"). The page could tell (no hello for 50 s); the connector could not, since with every phone away it rightly
|
|
113
|
+
// hears nothing. So each end asks the RELAY: it answers RELAY_PING with RELAY_PONG itself (a Cloudflare auto-response —
|
|
114
|
+
// the Durable Object is not woken, the other sockets never see it). No pong within PONG_WAIT_MS → redial.
|
|
115
|
+
// Only enforced once this relay has answered on the socket: an older relay (or a self-hosted one without the answer)
|
|
116
|
+
// broadcasts the first ping to the others instead, which they ignore, and nothing more is sent to it.
|
|
117
|
+
export const RELAY_PING = '{"t":"relay-ping"}'
|
|
118
|
+
export const RELAY_PONG = '{"t":"relay-pong"}'
|
|
119
|
+
export const HEARTBEAT_MS = 25_000
|
|
120
|
+
export const PONG_WAIT_MS = 10_000
|
|
121
|
+
export const DIAL_TIMEOUT_MS = 15_000 // a socket not open by then is on a dead path: dial again (RelayPeer connect)
|
|
122
|
+
|
|
123
|
+
/** Is this socket message the relay's own unsealed peer count? → n, else null. */
|
|
124
|
+
export function peersOf(text) {
|
|
125
|
+
if (typeof text !== 'string' || !text.startsWith('{"t":"peers"')) return null
|
|
126
|
+
try { const m = JSON.parse(text); return Number.isInteger(m.n) ? m.n : null } catch { return null }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ── chunking ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
130
|
+
// Cloudflare caps a WebSocket message at 1 MiB; a sealed frame is ~4/3 of its plaintext. Bodies are split well below.
|
|
131
|
+
export const CHUNK = 192 * 1024
|
|
132
|
+
export const MAX_TOTAL = 32 * 1024 * 1024
|
|
133
|
+
|
|
134
|
+
/** A message whose string field `b` is large → parts {…msg, b: slice, part: i, of: n}; small → [msg]. */
|
|
135
|
+
export function chunkMessage(msg, size = CHUNK) {
|
|
136
|
+
if (typeof msg.b !== 'string' || msg.b.length <= size) return [msg]
|
|
137
|
+
const of = Math.ceil(msg.b.length / size)
|
|
138
|
+
const parts = []
|
|
139
|
+
for (let i = 0; i < of; i++) parts.push({ ...msg, b: msg.b.slice(i * size, (i + 1) * size), part: i, of })
|
|
140
|
+
return parts
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Collects parts by (t, id). push(msg) → the whole message once complete, the message itself if unchunked, else null. */
|
|
144
|
+
export function makeReassembler({ timeoutMs = 60_000, maxTotal = MAX_TOTAL } = {}) {
|
|
145
|
+
const open = new Map()
|
|
146
|
+
return {
|
|
147
|
+
push(msg) {
|
|
148
|
+
if (!msg || msg.of === undefined) return msg
|
|
149
|
+
const { of, part } = msg
|
|
150
|
+
if (!Number.isInteger(of) || of < 1 || !Number.isInteger(part) || part < 0 || part >= of || typeof msg.b !== 'string') return null
|
|
151
|
+
const k = `${msg.t}:${msg.id}`
|
|
152
|
+
const now = Date.now()
|
|
153
|
+
for (const [key, e] of open) if (now - e.at > timeoutMs) open.delete(key)
|
|
154
|
+
let e = open.get(k)
|
|
155
|
+
if (!e) { e = { parts: new Array(of), got: 0, size: 0, at: now }; open.set(k, e) }
|
|
156
|
+
if (e.parts.length !== of) { open.delete(k); return null }
|
|
157
|
+
if (e.parts[part] === undefined) { e.parts[part] = msg.b; e.got++; e.size += msg.b.length }
|
|
158
|
+
if (e.size > maxTotal) { open.delete(k); return null }
|
|
159
|
+
if (e.got < of) return null
|
|
160
|
+
open.delete(k)
|
|
161
|
+
const whole = { ...msg, b: e.parts.join('') }
|
|
162
|
+
delete whole.part; delete whole.of
|
|
163
|
+
return whole
|
|
164
|
+
},
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ── the socket ───────────────────────────────────────────────────────────────────────────────────────────────────
|
|
169
|
+
/**
|
|
170
|
+
* One end of a channel, with reconnect. role 'client' (the page) seals with c2s and opens s2c; 'computer' the reverse.
|
|
171
|
+
* const peer = new RelayPeer({ secret, role: 'client', onMessage, onPeers, onState })
|
|
172
|
+
* peer.start(); await peer.send({ t: 'req', … }); peer.stop()
|
|
173
|
+
* A fresh sealer (new sender id, q from 1) per socket, so a reconnect is never mistaken for a replay.
|
|
174
|
+
*/
|
|
175
|
+
export class RelayPeer {
|
|
176
|
+
constructor({ secret, role, relay = RELAY_URL, WebSocketImpl = globalThis.WebSocket, onMessage = () => {}, onPeers = () => {}, onState = () => {}, onEvict = () => {}, maxSenders = 64, minBackoff = 500, maxBackoff = 15_000, heartbeatMs = HEARTBEAT_MS, pongWaitMs = PONG_WAIT_MS, dialTimeoutMs = DIAL_TIMEOUT_MS }) {
|
|
177
|
+
if (role !== 'client' && role !== 'computer') throw new Error('role must be client or computer')
|
|
178
|
+
Object.assign(this, { secret, role, relay: String(relay).replace(/\/+$/, ''), WebSocketImpl, onMessage, onPeers, onState, onEvict, maxSenders, minBackoff, maxBackoff, heartbeatMs, pongWaitMs, dialTimeoutMs })
|
|
179
|
+
this.beat = 0 // the heartbeat interval of the current socket
|
|
180
|
+
this.relayAnswers = false // this socket's relay has answered a ping
|
|
181
|
+
this.relayKnown = false // …or one of this peer's earlier sockets did: then a missing pong means a dead path from the first ping
|
|
182
|
+
this.peers = 0
|
|
183
|
+
this.state = 'idle' // idle | connecting | open | closed
|
|
184
|
+
this.ws = null
|
|
185
|
+
this.backoff = minBackoff
|
|
186
|
+
this.timer = 0
|
|
187
|
+
this.stopped = true
|
|
188
|
+
this.reasm = makeReassembler()
|
|
189
|
+
this.keys = null
|
|
190
|
+
// ★ ONE AT A TIME, BOTH WAYS. Receivers drop a frame whose sequence is not above the last one opened (replay), so a
|
|
191
|
+
// frame must reach the socket in the order it was numbered and be opened in the order it arrived. Concurrent
|
|
192
|
+
// seal/open awaits reorder them — measured: a burst of 20 lost the 4 large frames, which finished encrypting last.
|
|
193
|
+
this.sendChain = Promise.resolve()
|
|
194
|
+
this.recvChain = Promise.resolve()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async start() {
|
|
198
|
+
if (!this.stopped) return // already started (or starting): a second call must not dial a second socket
|
|
199
|
+
this.stopped = false
|
|
200
|
+
if (!this.keys) this.keys = await deriveRelay(this.secret)
|
|
201
|
+
this.connect()
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
stop() {
|
|
205
|
+
this.stopped = true
|
|
206
|
+
clearTimeout(this.timer); clearTimeout(this.dialTimer)
|
|
207
|
+
this.stopBeat()
|
|
208
|
+
this.waiting = false // a stop during a backoff wait must not leave kick() believing a wait is pending (it dialled a 2nd socket)
|
|
209
|
+
try { if (this.ws) this.ws.close(1000) } catch { /* */ }
|
|
210
|
+
this.ws = null
|
|
211
|
+
this.setState('closed')
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Reconnect now (e.g. the page became visible again) instead of waiting out the backoff. */
|
|
215
|
+
kick() {
|
|
216
|
+
// An "open" socket may be one iOS froze in the background rather than closed: ask the relay now, and redial if it
|
|
217
|
+
// does not answer — instead of waiting for the next heartbeat, or the page's 50-second hello silence.
|
|
218
|
+
if (!this.stopped && this.state === 'open') { this.probe(); return }
|
|
219
|
+
// ★ `connecting` covers two situations: a socket actually dialling (leave it) and a backoff WAIT (skip it). Treating
|
|
220
|
+
// both alike made kick() a no-op exactly when it matters — iOS bringing the page back after killing its socket.
|
|
221
|
+
if (this.stopped || (this.state === 'connecting' && !this.waiting)) return
|
|
222
|
+
clearTimeout(this.timer); this.waiting = false; this.backoff = this.minBackoff; this.connect()
|
|
223
|
+
}
|
|
224
|
+
/** Drop the current socket and dial again now — for a socket that is "open" but has gone silent (a dead network path). */
|
|
225
|
+
reconnect() {
|
|
226
|
+
if (this.stopped) return
|
|
227
|
+
this.stopBeat()
|
|
228
|
+
const ws = this.ws
|
|
229
|
+
this.ws = null
|
|
230
|
+
try { if (ws) ws.close(4000, 'silent') } catch { /* */ }
|
|
231
|
+
this.peers = 0
|
|
232
|
+
clearTimeout(this.timer); this.waiting = false; this.backoff = this.minBackoff
|
|
233
|
+
this.connect()
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Ping the relay on the current socket; no pong within `waitMs` → reconnect(). Once the relay has not answered on this
|
|
237
|
+
* socket, only the first ping is ever sent (see RELAY_PING). */
|
|
238
|
+
probe(waitMs = this.pongWaitMs) {
|
|
239
|
+
const ws = this.ws
|
|
240
|
+
if (this.stopped || !ws || this.state !== 'open') return
|
|
241
|
+
const enforce = this.relayAnswers || this.relayKnown
|
|
242
|
+
if (!enforce && this.pingedUnanswered) return // an older relay: it broadcasts pings — send it no more
|
|
243
|
+
const sentAt = Date.now()
|
|
244
|
+
try { ws.send(RELAY_PING) } catch { return }
|
|
245
|
+
if (!enforce) { this.pingedUnanswered = true; return } // learning whether this relay answers at all
|
|
246
|
+
setTimeout(() => {
|
|
247
|
+
if (this.ws !== ws || this.stopped || this.state !== 'open') return
|
|
248
|
+
if (!(this.lastPongAt >= sentAt)) this.reconnect() // a dead path: the relay did not hear us, or we did not hear it
|
|
249
|
+
}, waitMs)
|
|
250
|
+
}
|
|
251
|
+
stopBeat() { clearInterval(this.beat); this.beat = 0 }
|
|
252
|
+
|
|
253
|
+
get channel() { return this.keys && this.keys.channel }
|
|
254
|
+
get isOpen() { return this.state === 'open' }
|
|
255
|
+
|
|
256
|
+
setState(s) { if (this.state !== s) { this.state = s; try { this.onState(s) } catch { /* */ } } }
|
|
257
|
+
|
|
258
|
+
connect() {
|
|
259
|
+
if (this.stopped) return
|
|
260
|
+
const { c2s, s2c, channel } = this.keys
|
|
261
|
+
const sealer = makeSealer(this.role === 'client' ? c2s : s2c)
|
|
262
|
+
const opener = makeOpener(this.role === 'client' ? s2c : c2s, { maxSenders: this.maxSenders, onEvict: (s) => this.onEvict(s) })
|
|
263
|
+
let ws
|
|
264
|
+
try { ws = new this.WebSocketImpl(`${this.relay}/c/${channel}`) } catch { this.retry(); return }
|
|
265
|
+
this.ws = ws
|
|
266
|
+
this.sealer = sealer
|
|
267
|
+
this.setState('connecting')
|
|
268
|
+
this.stopBeat()
|
|
269
|
+
this.relayAnswers = false; this.pingedUnanswered = false; this.lastPongAt = 0
|
|
270
|
+
// ⛔ A DIAL THAT NEVER ENDS (2026-11-07, the implicit-state-machine review): a socket on a dead path (iOS back from the
|
|
271
|
+
// background, a network that changed) may neither open nor close — 'connecting' for ever, and kick() leaves a dialling
|
|
272
|
+
// socket alone. Not open in `dialTimeoutMs` → dropped and dialled again through the backoff.
|
|
273
|
+
clearTimeout(this.dialTimer)
|
|
274
|
+
if (this.dialTimeoutMs > 0) this.dialTimer = setTimeout(() => {
|
|
275
|
+
if (this.ws !== ws || this.stopped || this.state === 'open') return
|
|
276
|
+
this.ws = null; try { ws.close() } catch { /* */ }
|
|
277
|
+
this.retry()
|
|
278
|
+
}, this.dialTimeoutMs)
|
|
279
|
+
ws.onopen = () => {
|
|
280
|
+
if (this.ws !== ws) return
|
|
281
|
+
clearTimeout(this.dialTimer)
|
|
282
|
+
this.backoff = this.minBackoff; this.setState('open')
|
|
283
|
+
if (this.heartbeatMs > 0) { this.probe(); this.beat = setInterval(() => this.probe(), this.heartbeatMs) }
|
|
284
|
+
}
|
|
285
|
+
ws.onmessage = (e) => {
|
|
286
|
+
this.recvChain = this.recvChain.then(async () => {
|
|
287
|
+
if (this.ws !== ws) return
|
|
288
|
+
const text = typeof e.data === 'string' ? e.data : null
|
|
289
|
+
if (text === RELAY_PONG) { this.relayAnswers = this.relayKnown = true; this.pingedUnanswered = false; this.lastPongAt = Date.now(); return }
|
|
290
|
+
if (text === RELAY_PING) return // another peer's ping, broadcast by a relay that does not answer it
|
|
291
|
+
const n = peersOf(text)
|
|
292
|
+
if (n !== null) { this.peers = n; try { this.onPeers(n) } catch { /* */ } return }
|
|
293
|
+
const msg = this.reasm.push(await opener.open(text))
|
|
294
|
+
if (msg) { try { this.onMessage(msg) } catch { /* a handler bug must not kill the socket */ } }
|
|
295
|
+
}).catch(() => {})
|
|
296
|
+
}
|
|
297
|
+
ws.onclose = () => { if (this.ws !== ws) return; this.stopBeat(); this.ws = null; this.peers = 0; try { this.onPeers(0) } catch { /* */ } this.retry() }
|
|
298
|
+
ws.onerror = () => { try { ws.close() } catch { /* */ } }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
retry() {
|
|
302
|
+
if (this.stopped) return
|
|
303
|
+
this.setState('connecting')
|
|
304
|
+
clearTimeout(this.timer)
|
|
305
|
+
const wait = this.backoff
|
|
306
|
+
this.backoff = Math.min(this.maxBackoff, this.backoff * 2)
|
|
307
|
+
this.waiting = true
|
|
308
|
+
this.timer = setTimeout(() => { this.waiting = false; this.connect() }, wait)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Seal and send (chunked if large). Resolves false when there is no open socket — the caller decides what that means. */
|
|
312
|
+
send(msg) {
|
|
313
|
+
const run = async () => {
|
|
314
|
+
const ws = this.ws
|
|
315
|
+
if (!ws || this.state !== 'open') return false
|
|
316
|
+
const sealer = this.sealer
|
|
317
|
+
for (const part of chunkMessage(msg)) {
|
|
318
|
+
const frame = await sealer.seal(part)
|
|
319
|
+
if (this.ws !== ws) return false
|
|
320
|
+
try { ws.send(frame) } catch { return false }
|
|
321
|
+
}
|
|
322
|
+
return true
|
|
323
|
+
}
|
|
324
|
+
const p = this.sendChain.then(run, run)
|
|
325
|
+
this.sendChain = p.catch(() => false)
|
|
326
|
+
return p
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ── what the connector serves ────────────────────────────────────────────────────────────────────────────────────
|
|
331
|
+
// Only the calls the Code section makes (opencodeApp.js). OpenCode can run shell commands on the computer; a leaked
|
|
332
|
+
// secret must not unlock more than the page itself can do. Paths carry their query string (?directory=…).
|
|
333
|
+
// A segment may contain dots but never START with one: '.' and '..' would be collapsed by fetch onto a route that is not
|
|
334
|
+
// on this list (review finding: `DELETE /session/.` passed).
|
|
335
|
+
const SEG = '(?!\\.)[A-Za-z0-9_.-]{1,128}'
|
|
336
|
+
const ALLOW = [
|
|
337
|
+
['GET', '/experimental/session'],
|
|
338
|
+
['GET', '/agent'],
|
|
339
|
+
['GET', '/api/model'],
|
|
340
|
+
['GET', '/config'], // answered through projectResponse — never as OpenCode sent it
|
|
341
|
+
['GET', '/config/providers'], // the model menu: what is CONNECTED on this computer (projectResponse, no keys)
|
|
342
|
+
['POST', '/session'],
|
|
343
|
+
['GET', `/session/${SEG}/message`],
|
|
344
|
+
['POST', `/session/${SEG}/message`],
|
|
345
|
+
['POST', `/session/${SEG}/abort`],
|
|
346
|
+
['POST', `/session/${SEG}/permissions/${SEG}`],
|
|
347
|
+
// The same answer with a MESSAGE for the model — how a person's Deny says "stop and ask me" (the route above takes none).
|
|
348
|
+
// It grants nothing the route above does not: it only answers an ask that is already pending.
|
|
349
|
+
['POST', `/permission/${SEG}/reply`],
|
|
350
|
+
// What is still waiting for an answer — so a card comes back after switching sessions or reloading, while the agent sits
|
|
351
|
+
// blocked. The same asks (and details) the page already receives live as permission.asked; answering is the route above.
|
|
352
|
+
['GET', '/permission'],
|
|
353
|
+
// One session's record — its folder above all: the SDK's Computer learns a session's folder here (sdkComputers.js _dirOf,
|
|
354
|
+
// outputs()). A read: the same record GET /experimental/session lists, for one id. Only the record — /children, /message/<id>
|
|
355
|
+
// and the rest under it are not this pattern. (Docs sync 2026-11-22: it was missing, so outputs() failed with 403.)
|
|
356
|
+
['GET', `/session/${SEG}`],
|
|
357
|
+
['PATCH', `/session/${SEG}`],
|
|
358
|
+
['DELETE', `/session/${SEG}`],
|
|
359
|
+
// New session's folder picker: the computer's home, and folder listings under it (names, never contents). Neither
|
|
360
|
+
// raises the ceiling — a session the page can already create reads files with `read`/`list` allowed.
|
|
361
|
+
['GET', '/path'],
|
|
362
|
+
['GET', '/file'],
|
|
363
|
+
// The agent's question tool: what is pending, and the answer or the dismissal. Inside the agent loop — answering a
|
|
364
|
+
// question grants nothing; the turn it resumes is still held to the session's permission prompts.
|
|
365
|
+
// The "/" menu READS commands and skills. Running one is an ordinary message the page builds (codeCommands.js):
|
|
366
|
+
// POST /session/:id/command runs !`…` from its arguments in a shell, unprompted — it must never be on this list.
|
|
367
|
+
['GET', '/command'],
|
|
368
|
+
['GET', `/session/${SEG}/todo`], // the agent's todo list, as it stands
|
|
369
|
+
['GET', '/question'],
|
|
370
|
+
['POST', `/question/${SEG}/reply`],
|
|
371
|
+
['POST', `/question/${SEG}/reject`],
|
|
372
|
+
// /undo /redo /compact. Undo puts the session's files back to a snapshot OpenCode took before the turn; redo puts them
|
|
373
|
+
// forward again; compact asks the model to summarize. None runs anything the session's permission prompts do not hold.
|
|
374
|
+
['POST', `/session/${SEG}/revert`],
|
|
375
|
+
['POST', `/session/${SEG}/unrevert`],
|
|
376
|
+
['POST', `/session/${SEG}/summarize`],
|
|
377
|
+
['GET', '/session/status'], // which sessions are running a turn — for the list (codeStatus.js); reads only
|
|
378
|
+
// The Changes view (codeChanges.js): the folder's changed files and their git diff — reads only. /vcs/diff is answered
|
|
379
|
+
// through projectResponse (a secret-looking file's patch never leaves the computer); POST /vcs/apply is never listed.
|
|
380
|
+
['GET', '/vcs/status'],
|
|
381
|
+
['GET', '/vcs/diff'],
|
|
382
|
+
].map(([m, p]) => [m, new RegExp(`^${p}$`)])
|
|
383
|
+
|
|
384
|
+
/** Is `method path?query` something the connector will forward? The event stream is NOT here: it is `sub`, not a req. */
|
|
385
|
+
export function allowedRequest(method, pathWithQuery) {
|
|
386
|
+
const m = String(method || '').toUpperCase()
|
|
387
|
+
const p = String(pathWithQuery || '')
|
|
388
|
+
if (!p.startsWith('/') || p.includes('..') || p.includes('//') || p.includes('#')) return false
|
|
389
|
+
const path = p.split('?')[0]
|
|
390
|
+
return ALLOW.some(([am, re]) => am === m && re.test(path))
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** The event-stream path a `sub` may name: /event, optionally ?directory=… (and nothing else). */
|
|
394
|
+
export function allowedEventPath(p) {
|
|
395
|
+
const s = String(p || '')
|
|
396
|
+
if (s === '/event') return true
|
|
397
|
+
const m = s.match(/^\/event\?directory=([^&#]*)$/)
|
|
398
|
+
return !!m
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// ── what the connector gives back ────────────────────────────────────────────────────────────────────────────────
|
|
402
|
+
// Two routes the page needs answer with SECRETS in them, measured on opencode 1.18:
|
|
403
|
+
// • GET /config resolves every `{env:…}` in the provider options — the owner's TrustedRouter key came back in plain text.
|
|
404
|
+
// • GET /config/providers carries each connected provider's stored API key in `key` (from `opencode auth login`).
|
|
405
|
+
// The page needs names, not credentials, and the key must never leave the computer. So the connector does not pass these
|
|
406
|
+
// answers through: it rebuilds them from an ALLOWLIST of fields (a blocklist would miss the next field OpenCode adds).
|
|
407
|
+
// Anything that does not parse, or is not a success, goes back as a plain error — never the raw body.
|
|
408
|
+
const PROJECTED = new Set(['/config', '/config/providers', '/vcs/diff'])
|
|
409
|
+
const MAX_PROVIDERS = 100, MAX_MODELS = 2000
|
|
410
|
+
const s200 = (v) => (typeof v === 'string' ? v.slice(0, 200) : undefined)
|
|
411
|
+
const dict = () => Object.create(null) // a model named "__proto__" is a key like any other
|
|
412
|
+
const MEDIA = ['text', 'image', 'pdf', 'audio', 'video']
|
|
413
|
+
function projectInput(caps) {
|
|
414
|
+
const input = caps && typeof caps === 'object' ? caps.input : null
|
|
415
|
+
if (Array.isArray(input)) return MEDIA.filter((k) => input.includes(k))
|
|
416
|
+
if (input && typeof input === 'object') return MEDIA.filter((k) => input[k] === true)
|
|
417
|
+
return undefined
|
|
418
|
+
}
|
|
419
|
+
// A model's reasoning VARIANTS (OpenCode's per-model effort levels): their names only, never the options behind them.
|
|
420
|
+
const VARIANT_NAME = /^[a-z][a-z0-9_-]{0,15}$/
|
|
421
|
+
function projectVariants(v) {
|
|
422
|
+
if (!v || typeof v !== 'object' || Array.isArray(v)) return undefined
|
|
423
|
+
const names = Object.keys(v).filter((k) => VARIANT_NAME.test(k)).slice(0, 8)
|
|
424
|
+
return names.length ? names : undefined
|
|
425
|
+
}
|
|
426
|
+
function projectModels(models, keep) {
|
|
427
|
+
const out = dict()
|
|
428
|
+
if (!models || typeof models !== 'object' || Array.isArray(models)) return out
|
|
429
|
+
for (const k of Object.keys(models).slice(0, MAX_MODELS)) {
|
|
430
|
+
const id = s200(k)
|
|
431
|
+
if (!id) continue
|
|
432
|
+
const m = models[k] && typeof models[k] === 'object' ? models[k] : {}
|
|
433
|
+
out[id] = keep(m)
|
|
434
|
+
}
|
|
435
|
+
return out
|
|
436
|
+
}
|
|
437
|
+
/** GET /config → the declared model names and the default model. Nothing else (no options, no MCP, no permissions). */
|
|
438
|
+
function projectConfig(c) {
|
|
439
|
+
const out = {}
|
|
440
|
+
if (s200(c.model)) out.model = s200(c.model)
|
|
441
|
+
if (s200(c.small_model)) out.small_model = s200(c.small_model)
|
|
442
|
+
const provider = dict()
|
|
443
|
+
const src = c.provider && typeof c.provider === 'object' && !Array.isArray(c.provider) ? c.provider : {}
|
|
444
|
+
for (const pid of Object.keys(src).slice(0, MAX_PROVIDERS)) {
|
|
445
|
+
if (!s200(pid)) continue
|
|
446
|
+
const p = src[pid] && typeof src[pid] === 'object' ? src[pid] : {}
|
|
447
|
+
const entry = { models: projectModels(p.models, (m) => (s200(m.name) ? { name: s200(m.name) } : {})) }
|
|
448
|
+
if (s200(p.name)) entry.name = s200(p.name)
|
|
449
|
+
provider[s200(pid)] = entry
|
|
450
|
+
}
|
|
451
|
+
out.provider = provider
|
|
452
|
+
return out
|
|
453
|
+
}
|
|
454
|
+
/** GET /config/providers → for each connected provider: id, name, source, and its models' names and input kinds. */
|
|
455
|
+
function projectProviders(d) {
|
|
456
|
+
const providers = (Array.isArray(d.providers) ? d.providers : []).slice(0, MAX_PROVIDERS).filter((p) => p && s200(p.id)).map((p) => {
|
|
457
|
+
const entry = { id: s200(p.id), models: projectModels(p.models, (m) => {
|
|
458
|
+
const o = {}
|
|
459
|
+
if (s200(m.name)) o.name = s200(m.name)
|
|
460
|
+
if (s200(m.status)) o.status = s200(m.status)
|
|
461
|
+
const input = projectInput(m.capabilities)
|
|
462
|
+
if (input) o.input = input
|
|
463
|
+
const variants = projectVariants(m.variants)
|
|
464
|
+
if (variants) o.variants = variants
|
|
465
|
+
return o
|
|
466
|
+
}) }
|
|
467
|
+
if (s200(p.name)) entry.name = s200(p.name)
|
|
468
|
+
if (s200(p.source)) entry.source = s200(p.source)
|
|
469
|
+
return entry
|
|
470
|
+
})
|
|
471
|
+
const def = dict()
|
|
472
|
+
if (d.default && typeof d.default === 'object' && !Array.isArray(d.default)) {
|
|
473
|
+
for (const k of Object.keys(d.default).slice(0, MAX_PROVIDERS)) if (s200(k) && s200(d.default[k])) def[s200(k)] = s200(d.default[k])
|
|
474
|
+
}
|
|
475
|
+
return { providers, default: def }
|
|
476
|
+
}
|
|
477
|
+
// GET /vcs/diff → each changed file with its patch — except where the name looks like a secret (an untracked .env comes back
|
|
478
|
+
// WHOLE in a git diff; codeOutputs.js sensitivePath, the rule the previews use) or the patch is too large for a phone: then
|
|
479
|
+
// the name and the counts, and why the lines are withheld.
|
|
480
|
+
export const MAX_PATCH_CHARS = 1_000_000
|
|
481
|
+
const MAX_DIFF_FILES = 5000
|
|
482
|
+
const count = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0)
|
|
483
|
+
function projectVcsDiff(list) {
|
|
484
|
+
return list.slice(0, MAX_DIFF_FILES).filter((x) => x && typeof x === 'object' && !Array.isArray(x) && typeof x.file === 'string' && x.file).map((x) => {
|
|
485
|
+
const o = { file: x.file.slice(0, 4096), status: ['added', 'deleted', 'modified'].includes(x.status) ? x.status : 'modified', additions: count(x.additions), deletions: count(x.deletions) }
|
|
486
|
+
const patch = typeof x.patch === 'string' ? x.patch : ''
|
|
487
|
+
if (sensitivePath('/' + o.file)) o.withheld = 'secret'
|
|
488
|
+
else if (patch.length > MAX_PATCH_CHARS) o.withheld = 'size'
|
|
489
|
+
else o.patch = patch
|
|
490
|
+
return o
|
|
491
|
+
})
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** The answer the connector sends for `method path` — projected for the routes above, untouched otherwise.
|
|
495
|
+
* Returns { st, b } (status, body text). */
|
|
496
|
+
export function projectResponse(method, pathWithQuery, status, text) {
|
|
497
|
+
const path = String(pathWithQuery || '').split('?')[0]
|
|
498
|
+
if (String(method || '').toUpperCase() !== 'GET' || !PROJECTED.has(path)) return { st: status, b: text }
|
|
499
|
+
if (!(status >= 200 && status < 300)) return { st: status, b: JSON.stringify({ error: `OpenCode answered ${status} for ${path}` }) }
|
|
500
|
+
let v
|
|
501
|
+
try { v = JSON.parse(text) } catch { v = null }
|
|
502
|
+
if (path === '/vcs/diff') return Array.isArray(v) ? { st: status, b: JSON.stringify(projectVcsDiff(v)) } : { st: 502, b: JSON.stringify({ error: `OpenCode sent an unexpected answer for ${path}` }) }
|
|
503
|
+
if (!v || typeof v !== 'object' || Array.isArray(v)) return { st: 502, b: JSON.stringify({ error: `OpenCode sent an unexpected answer for ${path}` }) }
|
|
504
|
+
return { st: status, b: JSON.stringify(path === '/config' ? projectConfig(v) : projectProviders(v)) }
|
|
505
|
+
}
|
package/codeSent.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// spaces/public/codeSent.js — did a prompt reach the computer? For a turn whose REQUEST failed.
|
|
2
|
+
//
|
|
3
|
+
// A turn POST answers only when the model has finished, so on a long run it outlives the connection that carried it: the
|
|
4
|
+
// phone sleeps, the relay redials, a minute offline and the transport gives up on it (codeTransport.js GIVE_UP_MS) — while
|
|
5
|
+
// the computer is still working on the prompt. The page used to take that as a failed send and put the prompt back in the
|
|
6
|
+
// box (the owner: "When there is a long run I sometimes get my prompt back in the input box"). Now it asks the computer
|
|
7
|
+
// first: a prompt it has is a turn that ran or is running. Pure: no DOM.
|
|
8
|
+
|
|
9
|
+
import { splitPdfBlocks } from './pdfText.js'
|
|
10
|
+
import { unwrapJsonMessage } from './opencodeWire.js'
|
|
11
|
+
|
|
12
|
+
export function providerRefusal(result) {
|
|
13
|
+
const err = result?.info?.error
|
|
14
|
+
return err ? unwrapJsonMessage(err.data?.message || err.message || err.name || 'the provider refused this turn') : ''
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const words = (s) => String(s == null ? '' : s).trim()
|
|
18
|
+
|
|
19
|
+
/** The ids of the user messages there are now — taken when a prompt is sent. */
|
|
20
|
+
export const userIds = (messages) => new Set((Array.isArray(messages) ? messages : []).filter((m) => m && m.info && m.info.role === 'user' && m.info.id).map((m) => m.info.id))
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Is there a user message that was not there when the prompt was sent, carrying its words? (A prompt with only files has no
|
|
24
|
+
* words, so history alone cannot confirm delivery.) `text` is what the person typed; the message may carry more after it (a PDF's text)
|
|
25
|
+
* and a language line beside it, never less.
|
|
26
|
+
*/
|
|
27
|
+
export function promptLanded(messages, { knownUserIds, text }) {
|
|
28
|
+
const known = knownUserIds instanceof Set ? knownUserIds : new Set()
|
|
29
|
+
const want = words(text)
|
|
30
|
+
const history = Array.isArray(messages) ? messages : []
|
|
31
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
32
|
+
const m = history[i], info = m?.info
|
|
33
|
+
if (info?.role !== 'user' || !info.id) continue
|
|
34
|
+
if (known.has(info.id)) break
|
|
35
|
+
if (want && (m.parts || []).some(p => p?.type === 'text' && !p.synthetic && (words(p.text) === want || splitPdfBlocks(words(p.text)).text === want))) return true
|
|
36
|
+
}
|
|
37
|
+
return false
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function firstOutputStarted(messages) {
|
|
41
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
42
|
+
const message = messages[i]
|
|
43
|
+
if (message?.info?.role === 'user') break
|
|
44
|
+
if (message?.parts?.some(part => part && part.type !== 'step-start')) return true
|
|
45
|
+
}
|
|
46
|
+
return false
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** In-memory failed submissions, scoped to the computer/session chosen by the caller. */
|
|
50
|
+
export class PendingCodeDrafts {
|
|
51
|
+
constructor() { this.sessions = new Map(); this.sequence = 0 }
|
|
52
|
+
list(key) { return [...(this.sessions.get(key)?.values() || [])] }
|
|
53
|
+
get(key, id) { return this.sessions.get(key)?.get(id) || null }
|
|
54
|
+
close() { this.closed = true; this.sessions.clear() }
|
|
55
|
+
add(key, draft) {
|
|
56
|
+
if (this.closed) return null
|
|
57
|
+
const id = String(++this.sequence)
|
|
58
|
+
if (!this.sessions.has(key)) this.sessions.set(key, new Map())
|
|
59
|
+
this.sessions.get(key).set(id, { ...draft, id })
|
|
60
|
+
return id
|
|
61
|
+
}
|
|
62
|
+
discard(key, id) {
|
|
63
|
+
const queue = this.sessions.get(key)
|
|
64
|
+
if (!queue?.delete(id)) return false
|
|
65
|
+
if (!queue.size) this.sessions.delete(key)
|
|
66
|
+
return true
|
|
67
|
+
}
|
|
68
|
+
}
|