@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/codeSentinel.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// codeSentinel.js — what the page and the Credential Sentinel must agree on byte for byte (docs/credential-sentinel.md §9).
|
|
2
|
+
// One file, imported by both: the page (browser WebCrypto) and the Sentinel enclave (Node's WebCrypto).
|
|
3
|
+
//
|
|
4
|
+
// keys a cloud computer's `grantKey` (32 bytes, kept in the account) → the approve key and the log key, by HKDF.
|
|
5
|
+
// The page hands both to the Sentinel inside the sealed grant; the agent's VM never holds either.
|
|
6
|
+
// asks a request the Sentinel holds for the person carries a tag (HMAC, approve key) over what it is, so the page
|
|
7
|
+
// shows only asks the Sentinel really made — the agent, which relays them, cannot invent or relabel one.
|
|
8
|
+
// The person's answer carries a tag too, so the agent cannot answer for them.
|
|
9
|
+
// the log one sealed entry per call, AES-GCM under the log key, each naming the hash of the entry before it; stored
|
|
10
|
+
// through the host, which can hold entries back but cannot read, change or reorder them unnoticed.
|
|
11
|
+
|
|
12
|
+
const enc = new TextEncoder()
|
|
13
|
+
const dec = new TextDecoder()
|
|
14
|
+
const b64 = (u8) => { let s = ''; for (const b of u8) s += String.fromCharCode(b); return btoa(s) }
|
|
15
|
+
const unb64 = (s) => Uint8Array.from(atob(String(s)), (c) => c.charCodeAt(0))
|
|
16
|
+
const hex = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
17
|
+
const subtle = globalThis.crypto.subtle
|
|
18
|
+
|
|
19
|
+
async function hkdf(rootB64, info) {
|
|
20
|
+
const k = await subtle.importKey('raw', unb64(rootB64), 'HKDF', false, ['deriveBits'])
|
|
21
|
+
return new Uint8Array(await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: enc.encode(info) }, k, 256))
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** grantKey (base64, 32 bytes) → { approve, log } (base64). */
|
|
25
|
+
export async function sentinelKeys(grantKeyB64) {
|
|
26
|
+
return { approve: b64(await hkdf(grantKeyB64, 'witbitz-sentinel approve v1')), log: b64(await hkdf(grantKeyB64, 'witbitz-sentinel log v1')) }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Canonical JSON (sorted keys) — what a tag signs. */
|
|
30
|
+
export function canon(o) {
|
|
31
|
+
if (o === null || typeof o !== 'object') return JSON.stringify(o)
|
|
32
|
+
if (Array.isArray(o)) return '[' + o.map(canon).join(',') + ']'
|
|
33
|
+
return '{' + Object.keys(o).sort().map((k) => JSON.stringify(k) + ':' + canon(o[k])).join(',') + '}'
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function hmac(keyB64, text) {
|
|
37
|
+
const k = await subtle.importKey('raw', unb64(keyB64), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
38
|
+
return hex(new Uint8Array(await subtle.sign('HMAC', k, enc.encode(text))))
|
|
39
|
+
}
|
|
40
|
+
const same = (a, b) => { if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false; let d = 0; for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i); return d === 0 }
|
|
41
|
+
|
|
42
|
+
/** An ask's tag: over its id, when it expires and what it is. */
|
|
43
|
+
export const askTag = (approveB64, ask) => hmac(approveB64, 'ask\n' + canon({ id: ask.id, expires: ask.expires, summary: ask.summary }))
|
|
44
|
+
export const askGenuine = async (approveB64, ask) => same(await askTag(approveB64, ask), ask.tag)
|
|
45
|
+
/** The person's answer to one ask. */
|
|
46
|
+
export const decideTag = (approveB64, id, allow) => hmac(approveB64, `decide\n${id}\n${allow ? 'allow' : 'deny'}`)
|
|
47
|
+
export const decideGenuine = async (approveB64, id, allow, tag) => same(await decideTag(approveB64, id, allow), tag)
|
|
48
|
+
|
|
49
|
+
// ── the log ────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
50
|
+
const aadOf = (workspace, grantId, seq) => enc.encode(`witbitz-sentinel log v1\n${workspace}\n${grantId}\n${seq}`)
|
|
51
|
+
export const logName = (grantId, seq) => `log-${grantId}-${String(seq).padStart(8, '0')}`
|
|
52
|
+
|
|
53
|
+
/** Seal entry `seq` of a grant's log. `prev`: the hash of entry seq-1 ('' for the first). → { name, blob, hash } */
|
|
54
|
+
export async function sealLogEntry({ logKey, workspace, grantId, seq, prev = '', at = Date.now(), entry }) {
|
|
55
|
+
const key = await subtle.importKey('raw', unb64(logKey), 'AES-GCM', false, ['encrypt'])
|
|
56
|
+
const iv = globalThis.crypto.getRandomValues(new Uint8Array(12))
|
|
57
|
+
const ct = new Uint8Array(await subtle.encrypt({ name: 'AES-GCM', iv, additionalData: aadOf(workspace, grantId, seq) }, key, enc.encode(JSON.stringify({ seq, prev, at, entry }))))
|
|
58
|
+
const blob = new Uint8Array(12 + ct.length)
|
|
59
|
+
blob.set(iv); blob.set(ct, 12)
|
|
60
|
+
return { name: logName(grantId, seq), blob, hash: hex(new Uint8Array(await subtle.digest('SHA-256', blob))) }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Open a grant's log and check it is whole: every entry opens, the numbers run 0,1,2… with no gap, and each names the
|
|
65
|
+
* hash of the one before. → { entries: [{ seq, at, entry }], ok, problem? }. An entry the host held back at the END cannot
|
|
66
|
+
* be told from one never written; the page compares with what it saw live.
|
|
67
|
+
*/
|
|
68
|
+
export async function openLog({ logKey, workspace, grantId, blobs }) {
|
|
69
|
+
const key = await subtle.importKey('raw', unb64(logKey), 'AES-GCM', false, ['decrypt'])
|
|
70
|
+
const sorted = [...blobs].filter((b) => b.name.startsWith(`log-${grantId}-`)).sort((a, b) => (a.name < b.name ? -1 : 1))
|
|
71
|
+
const entries = []
|
|
72
|
+
let prevHash = ''
|
|
73
|
+
for (let i = 0; i < sorted.length; i++) {
|
|
74
|
+
const blob = sorted[i].blob instanceof Uint8Array ? sorted[i].blob : unb64(sorted[i].blob)
|
|
75
|
+
if (sorted[i].name !== logName(grantId, i)) return { entries, ok: false, problem: `entry ${i} is missing` }
|
|
76
|
+
let rec
|
|
77
|
+
try {
|
|
78
|
+
const pt = await subtle.decrypt({ name: 'AES-GCM', iv: blob.slice(0, 12), additionalData: aadOf(workspace, grantId, i) }, key, blob.slice(12))
|
|
79
|
+
rec = JSON.parse(dec.decode(pt))
|
|
80
|
+
} catch { return { entries, ok: false, problem: `entry ${i} does not open — changed, or not this grant's` } }
|
|
81
|
+
if (rec.seq !== i || rec.prev !== prevHash) return { entries, ok: false, problem: `entry ${i} does not follow entry ${i - 1}` }
|
|
82
|
+
entries.push({ seq: rec.seq, at: rec.at, entry: rec.entry })
|
|
83
|
+
prevHash = hex(new Uint8Array(await subtle.digest('SHA-256', blob)))
|
|
84
|
+
}
|
|
85
|
+
return { entries, ok: true }
|
|
86
|
+
}
|
package/codeSubagents.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// codeSubagents: how the Code section shows an agent's SUBAGENTS — the child sessions OpenCode's task tool starts.
|
|
2
|
+
//
|
|
3
|
+
// Every subagent is a session of its own (parentID set, titled "<task> (@explore subagent)"). Listed as peers they filled
|
|
4
|
+
// the drawer with conversations nobody started, and their approval asks — which carry the CHILD's session id — never
|
|
5
|
+
// reached the conversation the person was reading. So:
|
|
6
|
+
// · the drawer lists only top-level sessions; a parent shows how many agents it ran, and its ✶ while any of them runs.
|
|
7
|
+
// A child whose parent is not in the list (deleted, or outside it) is still listed, so nothing becomes unreachable.
|
|
8
|
+
// · the open session's children are known (list, task steps, live session.created events), and their asks and Auto
|
|
9
|
+
// verdicts are shown IN the parent, naming the agent.
|
|
10
|
+
// · a refused step says who refused it — OpenCode words every rejection "The user rejected permission…", including the
|
|
11
|
+
// ones it CASCADES onto the other pending asks of a session when one is rejected (tools/code-opencode-policy.mjs).
|
|
12
|
+
|
|
13
|
+
/** What a person's Deny tells the model. With continue_loop_on_deny the turn goes on — this makes it stop and ask. */
|
|
14
|
+
export const PERSON_REFUSAL = 'The person refused this in Witbitz — stop and ask them how to proceed.'
|
|
15
|
+
const AUTO_MARK = 'Witbitz Auto mode refused this'
|
|
16
|
+
const CORRECTED_PREFIX = 'The user rejected permission to use this specific tool call with the following feedback: '
|
|
17
|
+
const BARE_REJECTION = 'The user rejected permission to use this specific tool call.'
|
|
18
|
+
|
|
19
|
+
const textOf = (s) => ((s && s.title) || '') + ' ' + ((s && s.slug) || '') + ' ' + ((s && s.directory) || '')
|
|
20
|
+
|
|
21
|
+
/** Who a subagent session belongs to, by id → parent id, for the sessions in `all`. */
|
|
22
|
+
function parentsOf(all) {
|
|
23
|
+
const ids = new Set(all.map((s) => s && s.id).filter(Boolean))
|
|
24
|
+
const parent = new Map()
|
|
25
|
+
for (const s of all) if (s && s.id && typeof s.parentID === 'string' && s.parentID && ids.has(s.parentID)) parent.set(s.id, s.parentID)
|
|
26
|
+
return parent
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The top-level session a session sits under (itself when it has no listed parent). */
|
|
30
|
+
function rootOf(id, parent) {
|
|
31
|
+
let cur = id
|
|
32
|
+
for (let i = 0; i < 8 && parent.has(cur); i++) cur = parent.get(cur)
|
|
33
|
+
return cur
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The drawer's rows for `shown` (the active or the archived list), with `all` (both lists) to resolve parents.
|
|
38
|
+
* → [{ session, agents, agentRunning }] in `shown`'s order. `running`: Map of session id → state, from /session/status.
|
|
39
|
+
*/
|
|
40
|
+
export function drawerRows(shown, { all = shown, running = new Map(), query = '' } = {}) {
|
|
41
|
+
const parent = parentsOf(all)
|
|
42
|
+
const q = String(query || '').trim().toLowerCase()
|
|
43
|
+
const agents = new Map() // root id → how many subagents ran under it
|
|
44
|
+
const agentRunning = new Set()
|
|
45
|
+
const childMatch = new Set() // root ids a search found through one of their subagents
|
|
46
|
+
for (const s of all) {
|
|
47
|
+
if (!s || !parent.has(s.id)) continue
|
|
48
|
+
const root = rootOf(s.id, parent)
|
|
49
|
+
agents.set(root, (agents.get(root) || 0) + 1)
|
|
50
|
+
if (running.has(s.id)) agentRunning.add(root)
|
|
51
|
+
if (q && textOf(s).toLowerCase().includes(q)) childMatch.add(root)
|
|
52
|
+
}
|
|
53
|
+
return shown
|
|
54
|
+
.filter((s) => s && !parent.has(s.id))
|
|
55
|
+
.filter((s) => !q || textOf(s).toLowerCase().includes(q) || childMatch.has(s.id))
|
|
56
|
+
.map((s) => ({ session: s, agents: agents.get(s.id) || 0, agentRunning: agentRunning.has(s.id) }))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The subagent sessions under `sid` that this page knows of: from the session list and from the transcript's task steps. */
|
|
60
|
+
export function childIdsOf(sid, { sessions = [], messages = [] } = {}) {
|
|
61
|
+
const out = new Set()
|
|
62
|
+
if (!sid) return out
|
|
63
|
+
const parent = parentsOf(sessions)
|
|
64
|
+
for (const s of sessions) if (s && s.id && parent.has(s.id) && rootOf(s.id, parent) === sid) out.add(s.id)
|
|
65
|
+
for (const m of messages || []) {
|
|
66
|
+
for (const p of (m && m.parts) || []) {
|
|
67
|
+
const meta = p && p.type === 'tool' && p.state && p.state.metadata
|
|
68
|
+
if (meta && typeof meta.sessionId === 'string' && meta.sessionId && meta.sessionId !== sid) out.add(meta.sessionId)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return out
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** What a live event says about the family: a session created or updated under `sid` → its id, else ''. */
|
|
75
|
+
export function childFromEvent(ev, sid, known = new Set()) {
|
|
76
|
+
const type = ev && ev.type
|
|
77
|
+
if (type !== 'session.created' && type !== 'session.updated') return ''
|
|
78
|
+
const info = ev.properties && ev.properties.info
|
|
79
|
+
if (!info || typeof info.id !== 'string' || typeof info.parentID !== 'string') return ''
|
|
80
|
+
return info.parentID === sid || known.has(info.parentID) ? info.id : ''
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A subagent's short name for a card: "explore" out of "Explore the repo (@explore subagent)", else its title. */
|
|
84
|
+
export function agentLabel(session) {
|
|
85
|
+
const title = String((session && session.title) || '')
|
|
86
|
+
const m = title.match(/\(@([^\s)]+) subagent\)\s*$/)
|
|
87
|
+
const task = title.replace(/\s*\(@[^)]*subagent\)\s*$/, '').trim()
|
|
88
|
+
return { name: m ? m[1] : 'subagent', task }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Who refused a step, from OpenCode's error text.
|
|
93
|
+
* → { kind: 'auto', reason } Auto mode refused it (the reason it gave the agent)
|
|
94
|
+
* → { kind: 'person', reason } the person denied it from the Code section
|
|
95
|
+
* → { kind: 'cancelled' } a bare rejection: OpenCode cancelled it because ANOTHER ask in the session was rejected
|
|
96
|
+
* → { kind: 'other', reason } refused with some other feedback (another client)
|
|
97
|
+
* → null not a refusal at all
|
|
98
|
+
*/
|
|
99
|
+
export function refusalOf(error) {
|
|
100
|
+
const e = String(error || '').trim()
|
|
101
|
+
if (e === BARE_REJECTION) return { kind: 'cancelled' }
|
|
102
|
+
if (!e.startsWith(CORRECTED_PREFIX)) return null
|
|
103
|
+
const feedback = e.slice(CORRECTED_PREFIX.length).trim()
|
|
104
|
+
if (feedback.includes(AUTO_MARK)) return { kind: 'auto', reason: feedback.replace(/\s*\(Witbitz Auto mode refused this[^)]*\)\s*$/, '').trim() }
|
|
105
|
+
if (feedback === PERSON_REFUSAL) return { kind: 'person', reason: '' }
|
|
106
|
+
return { kind: 'other', reason: feedback }
|
|
107
|
+
}
|
package/codeTransport.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import { removeCachedSession } from './codeCache.js'
|
|
2
|
+
// codeTransport.js — how the Code section reaches OpenCode. Two interchangeable transports behind one shape, so the rest
|
|
3
|
+
// of opencodeApp.js never knows which it is using (docs/opencode-relay.md §5):
|
|
4
|
+
//
|
|
5
|
+
// relay — the normal path: a sealed WebSocket to the connector on a paired computer (codeRelay.js). No server address,
|
|
6
|
+
// no password in the page, no third-party origin in the CSP.
|
|
7
|
+
// direct — development only: fetch + SSE straight to an OpenCode server the page can reach (http://127.0.0.1:4096).
|
|
8
|
+
//
|
|
9
|
+
// t.request(method, pathWithQuery, bodyObject?) → { ok, status, json, text }
|
|
10
|
+
// t.subscribe(pathWithQuery, onEvent) → stop() (onEvent gets each parsed OpenCode event)
|
|
11
|
+
// t.status() → 'online' | 'connecting' | 'offline'
|
|
12
|
+
// t.onChange(fn) t.kick() t.close()
|
|
13
|
+
import { RelayPeer } from './codeRelay.js'
|
|
14
|
+
import { makeSseParser } from './opencodeWire.js'
|
|
15
|
+
|
|
16
|
+
const parse = (text) => { try { return text ? JSON.parse(text) : null } catch { return null } }
|
|
17
|
+
const rid = () => Array.from(crypto.getRandomValues(new Uint8Array(9)), (b) => b.toString(36).padStart(2, '0')).join('')
|
|
18
|
+
|
|
19
|
+
// ── direct ───────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
20
|
+
export function directTransport({ base, pass, fetchImpl = (...a) => fetch(...a) }) {
|
|
21
|
+
const root = String(base || '').replace(/\/+$/, '')
|
|
22
|
+
const auth = () => (pass ? { authorization: 'Basic ' + btoa('opencode:' + pass) } : {})
|
|
23
|
+
return {
|
|
24
|
+
kind: 'direct',
|
|
25
|
+
label: root,
|
|
26
|
+
status: () => 'online',
|
|
27
|
+
onChange: () => () => {},
|
|
28
|
+
can: () => false, // Auto mode lives in the connector — a direct server has none
|
|
29
|
+
autoSessions: () => [],
|
|
30
|
+
onAuto: () => () => {},
|
|
31
|
+
onProgress: () => () => {}, // the confidential-model proxy lives in the connector too
|
|
32
|
+
setAuto: () => false,
|
|
33
|
+
setBrowsePrivate: () => false,
|
|
34
|
+
askTools: async () => null, // a direct server has no connector to look
|
|
35
|
+
kick: () => {},
|
|
36
|
+
close: () => {},
|
|
37
|
+
async request(method, p, body) {
|
|
38
|
+
const init = { method, headers: { ...auth(), ...(body !== undefined ? { 'content-type': 'application/json' } : {}) } }
|
|
39
|
+
if (body !== undefined) init.body = JSON.stringify(body)
|
|
40
|
+
const r = await fetchImpl(root + p, init) // a network failure throws — the caller explains it
|
|
41
|
+
const text = await r.text().catch(() => '')
|
|
42
|
+
return { ok: r.ok, status: r.status, json: parse(text), text }
|
|
43
|
+
},
|
|
44
|
+
subscribe(p, onEvent, onError = () => {}) {
|
|
45
|
+
const ctrl = new AbortController()
|
|
46
|
+
;(async () => {
|
|
47
|
+
let r
|
|
48
|
+
try { r = await fetchImpl(root + p, { headers: { ...auth(), accept: 'text/event-stream' }, signal: ctrl.signal }) }
|
|
49
|
+
catch (err) { if (!ctrl.signal.aborted) onError(err); return }
|
|
50
|
+
if (!r.ok || !r.body) { onError(new Error(`event stream ${r.status}`)); return }
|
|
51
|
+
const feed = makeSseParser(onEvent)
|
|
52
|
+
const reader = r.body.getReader()
|
|
53
|
+
const dec = new TextDecoder()
|
|
54
|
+
try { for (;;) { const { done, value } = await reader.read(); if (done) break; feed(dec.decode(value, { stream: true })) } }
|
|
55
|
+
catch { /* aborted, or the server went away */ }
|
|
56
|
+
})()
|
|
57
|
+
return () => ctrl.abort()
|
|
58
|
+
},
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ── relay ────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
63
|
+
const PEERS_WAIT_MS = 3_000 // a relay that never says who is on the channel: offline after this, not "connecting" for good
|
|
64
|
+
const HELLO_FRESH_MS = 30_000 // the connector says hello every 20 s while someone is here
|
|
65
|
+
const WAIT_ONLINE_MS = 8_000 // a request made while connecting waits this long for the computer
|
|
66
|
+
const REQUEST_TIMEOUT_MS = 35_000 // the connector's own timeout is 30 s
|
|
67
|
+
const RESUB_MS = 30_000 // the connector drops a subscription nobody renewed for 75 s
|
|
68
|
+
const GIVE_UP_MS = 60_000
|
|
69
|
+
const SILENT_MS = 50_000 // an "open" socket with a computer on it but no hello for this long is a dead path: redial
|
|
70
|
+
const WAKE_GAP_MS = 15_000 // the 5-second tick went this long without running: the page was frozen in the background
|
|
71
|
+
const WAKE_WAIT_MS = 4_000 // back from the background: how long the computer has to answer before "offline" may show
|
|
72
|
+
|
|
73
|
+
export function relayTransport({ computer, WebSocketImpl, now = () => Date.now() }) {
|
|
74
|
+
const listeners = new Set()
|
|
75
|
+
const pending = new Map() // id → { resolve, timer, resend: (() => void) | null }
|
|
76
|
+
const subs = new Map() // path → Set(onEvent)
|
|
77
|
+
let lastHello = 0
|
|
78
|
+
// The connector's nonce for its CURRENT socket (sealed in its hello). Every request carries it; a request recorded before
|
|
79
|
+
// the connector restarted carries a stale one and is refused there (replay protection across restarts).
|
|
80
|
+
let nonce = ''
|
|
81
|
+
let lastHelloTs = 0 // a replayed OLD hello (earlier ts) must not move this page back onto a dead nonce
|
|
82
|
+
// This device's id for its event-stream interest, so one device leaving never closes a stream another is reading.
|
|
83
|
+
const cid = rid()
|
|
84
|
+
let last = 'connecting'
|
|
85
|
+
// Auto mode (docs/code-auto-mode.md §5): what the connector says it can do, which sessions it decides for, and its verdicts.
|
|
86
|
+
let caps = []
|
|
87
|
+
let omitted = [] // what the connector leaves out on purpose (its hello's `omits`): no update adds it (state machines pass 9, C#8)
|
|
88
|
+
let autoList = []
|
|
89
|
+
const autoListeners = new Set()
|
|
90
|
+
const toolWaiters = [] // askTools() calls waiting for the computer's {t:'tools'} answer
|
|
91
|
+
const tellAuto = (e) => { for (const fn of autoListeners) { try { fn(e) } catch { /* */ } } }
|
|
92
|
+
const progressListeners = new Set() // what a confidential model is doing (codeProgress.js)
|
|
93
|
+
// The enclave's own report of the agent's browser, which rides its hello beside `egress` and `agent`
|
|
94
|
+
// (vm/main.go, docs/cloud-computer.md § 12). A local computer never sends one, and then this stays null.
|
|
95
|
+
const browseListeners = new Set()
|
|
96
|
+
let browseState = null
|
|
97
|
+
// The egress story rides the same hello, and the browser's row needs it: free browsing is reported there, by the
|
|
98
|
+
// same state the enclave's own decision reads (vm/policy.go freeReport). Kept beside `browse` and announced with
|
|
99
|
+
// it, so the row cannot show one of the two as stale.
|
|
100
|
+
let egressState = null
|
|
101
|
+
let resubTimer = 0
|
|
102
|
+
let freshTimer = 0
|
|
103
|
+
|
|
104
|
+
let openedAt = 0
|
|
105
|
+
// The relay says who is on the channel only just AFTER the socket opens. Counting the page alone before then said
|
|
106
|
+
// "offline" for a moment on every open (the owner: "I get this brief red warning. It is transient and shouldnt show up").
|
|
107
|
+
let peersKnown = false
|
|
108
|
+
// ★ BACK FROM THE BACKGROUND. iOS freezes the page with its socket still "open"; on return the computer's last hello is
|
|
109
|
+
// old because nothing ran, not because the computer left — and the first tick said offline before anyone had asked it
|
|
110
|
+
// again (the owner: "When I switch apps and return to spaces I get this transient red notice"). A frozen tick, or the
|
|
111
|
+
// page saying it is visible again (kick), asks the computer and holds "offline" back until it has had time to answer.
|
|
112
|
+
let lastTick = now()
|
|
113
|
+
let wokeAt = -Infinity
|
|
114
|
+
const status = () => {
|
|
115
|
+
if (!peer.isOpen) return 'connecting' // still dialling the relay (or retrying)
|
|
116
|
+
if (peer.peers >= 2 && now() - lastHello < HELLO_FRESH_MS) return 'online'
|
|
117
|
+
if (now() - lastTick > WAKE_GAP_MS || now() - wokeAt < WAKE_WAIT_MS) return 'connecting' // just back: asking again
|
|
118
|
+
if (peer.peers < 2) return !peersKnown && now() - openedAt < PEERS_WAIT_MS ? 'connecting' : 'offline' // alone on the channel: the computer is not running
|
|
119
|
+
// Someone else is here but has not said hello — maybe the computer is just answering, maybe it is only another of
|
|
120
|
+
// your devices. Give it a moment, then call it offline.
|
|
121
|
+
return now() - openedAt < 5_000 ? 'connecting' : 'offline'
|
|
122
|
+
}
|
|
123
|
+
let giveUpTimer = 0
|
|
124
|
+
const changed = () => {
|
|
125
|
+
const s = status()
|
|
126
|
+
if (s === last) return
|
|
127
|
+
last = s
|
|
128
|
+
clearTimeout(giveUpTimer)
|
|
129
|
+
if (s === 'online') { resubscribe(); for (const e of pending.values()) if (e.resend) e.resend() }
|
|
130
|
+
// A turn waiting on a computer that went away would leave the page "busy" forever. After a minute offline, every
|
|
131
|
+
// request that cannot be safely re-asked resolves as failed; reads stay pending and re-ask when it returns.
|
|
132
|
+
if (s === 'offline') giveUpTimer = setTimeout(() => {
|
|
133
|
+
for (const [id, e] of pending) if (!e.resend) { pending.delete(id); clearTimeout(e.timer); e.resolve({ ok: false, status: 0, json: null, text: 'offline' }) }
|
|
134
|
+
}, GIVE_UP_MS)
|
|
135
|
+
for (const fn of listeners) { try { fn(s) } catch { /* */ } }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function onHello(m) {
|
|
139
|
+
// A hello OLDER than the last one is a replay (the relay can record and resend frames): ignore it, or the page would
|
|
140
|
+
// move back onto a nonce the connector no longer accepts.
|
|
141
|
+
if (typeof m.ts === 'number' && m.ts <= lastHelloTs) return
|
|
142
|
+
if (typeof m.ts === 'number') lastHelloTs = m.ts
|
|
143
|
+
const renewed = typeof m.k === 'string' && m.k && m.k !== nonce
|
|
144
|
+
if (typeof m.k === 'string' && m.k) nonce = m.k
|
|
145
|
+
lastHello = now()
|
|
146
|
+
const nextCaps = Array.isArray(m.caps) ? m.caps.filter((c) => typeof c === 'string').slice(0, 16) : []
|
|
147
|
+
omitted = Array.isArray(m.omits) ? m.omits.filter((c) => typeof c === 'string').slice(0, 16) : []
|
|
148
|
+
const nextAuto = nextCaps.includes('auto') && Array.isArray(m.auto) ? m.auto.filter((s) => typeof s === 'string' && /^ses[A-Za-z0-9_-]{1,80}$/.test(s)) : []
|
|
149
|
+
if (nextCaps.join() !== caps.join() || nextAuto.join() !== autoList.join()) { caps = nextCaps; autoList = nextAuto; tellAuto({ kind: 'sessions', sessions: [...autoList] }) }
|
|
150
|
+
// A NEW nonce = the connector restarted, redialled or rotated: anything it has not answered was refused or lost —
|
|
151
|
+
// re-ask the reads with the new nonce and renew the streams. (Mutations are never re-sent.)
|
|
152
|
+
if (renewed && last === 'online') { resubscribe(); for (const e of pending.values()) if (e.resend) e.resend() }
|
|
153
|
+
// ★ Only a CHANGE is announced. A hello arrives every 20 s and the browser's row must not be rebuilt under the
|
|
154
|
+
// owner's finger — `changed()` below has the same discipline for the status string.
|
|
155
|
+
const nextBrowse = (m.browse && typeof m.browse === 'object') ? m.browse : null
|
|
156
|
+
const nextEgress = (m.egress && typeof m.egress === 'object') ? m.egress : null
|
|
157
|
+
if (JSON.stringify(nextBrowse) !== JSON.stringify(browseState) || JSON.stringify(nextEgress) !== JSON.stringify(egressState)) {
|
|
158
|
+
browseState = nextBrowse
|
|
159
|
+
egressState = nextEgress
|
|
160
|
+
for (const fn of browseListeners) { try { fn(browseState) } catch { /* a listener's fault is not the socket's */ } }
|
|
161
|
+
}
|
|
162
|
+
changed()
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const peer = new RelayPeer({
|
|
166
|
+
secret: computer.secret,
|
|
167
|
+
role: 'client',
|
|
168
|
+
relay: computer.relay,
|
|
169
|
+
WebSocketImpl,
|
|
170
|
+
onState: (s) => { peersKnown = false; if (s === 'open') { openedAt = now(); peer.send({ t: 'ping' }); setTimeout(changed, PEERS_WAIT_MS + 50) } else { lastHello = 0; nonce = '' } changed() },
|
|
171
|
+
onPeers: (n) => { peersKnown = peer.isOpen; if (n < 2) lastHello = 0; else peer.send({ t: 'ping' }); changed() },
|
|
172
|
+
onMessage: (m) => {
|
|
173
|
+
if (m.t === 'hello') { onHello(m); return }
|
|
174
|
+
if (m.t === 'progress') { for (const fn of progressListeners) { try { fn(m) } catch { /* */ } } return }
|
|
175
|
+
if (m.t === 'tools') { const waiting = toolWaiters.splice(0); for (const w of waiting) w(m); return }
|
|
176
|
+
if (m.t === 'autoverdict') { if (typeof m.sessionID === 'string' && typeof m.action === 'string') tellAuto({ kind: 'verdict', verdict: m }); return }
|
|
177
|
+
if (m.t === 'res') {
|
|
178
|
+
const e = pending.get(m.id)
|
|
179
|
+
if (!e) return // another device's request, or one we gave up on
|
|
180
|
+
if (m.st === 409 && e.resend) return // stale nonce on a read: the connector's new hello re-sends it
|
|
181
|
+
pending.delete(m.id)
|
|
182
|
+
clearTimeout(e.timer)
|
|
183
|
+
e.resolve({ ok: m.st >= 200 && m.st < 300, status: m.st, json: parse(m.b), text: m.b || '' })
|
|
184
|
+
return
|
|
185
|
+
}
|
|
186
|
+
if (m.t === 'evts') {
|
|
187
|
+
const handlers = subs.get(m.p)
|
|
188
|
+
if (!handlers) return
|
|
189
|
+
const batch = parse(m.b)
|
|
190
|
+
if (!Array.isArray(batch)) return
|
|
191
|
+
for (const d of batch) { const ev = parse(d); if (ev) for (const h of handlers) { try { h(ev) } catch { /* */ } } }
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
})
|
|
195
|
+
const resubscribe = () => { if (nonce) for (const p of subs.keys()) peer.send({ t: 'sub', c: cid, k: nonce, p }) }
|
|
196
|
+
const wake = () => {
|
|
197
|
+
lastTick = now()
|
|
198
|
+
wokeAt = now()
|
|
199
|
+
if (peer.isOpen) peer.send({ t: 'ping' }) // the connector answers a ping with its hello
|
|
200
|
+
setTimeout(changed, WAKE_WAIT_MS + 50)
|
|
201
|
+
changed()
|
|
202
|
+
}
|
|
203
|
+
peer.start()
|
|
204
|
+
freshTimer = setInterval(() => {
|
|
205
|
+
if (now() - lastTick > WAKE_GAP_MS) wake() // the page was frozen: this tick is the first thing to run
|
|
206
|
+
lastTick = now()
|
|
207
|
+
// ★ A dead network path can leave a socket "open" forever (send() never fails). The connector says hello every 20 s
|
|
208
|
+
// while anyone is here, so silence for 50 s with a peer present means the path is gone: redial.
|
|
209
|
+
if (peer.isOpen && peer.peers >= 2 && lastHello && now() - lastHello > SILENT_MS) peer.reconnect()
|
|
210
|
+
changed() // a hello that stops arriving must turn into "offline"
|
|
211
|
+
}, 5_000)
|
|
212
|
+
resubTimer = setInterval(() => { if (status() === 'online') resubscribe() }, RESUB_MS)
|
|
213
|
+
|
|
214
|
+
const waitOnline = () => new Promise((resolve) => {
|
|
215
|
+
if (status() === 'online') return resolve(true)
|
|
216
|
+
const off = () => { listeners.delete(fn); clearTimeout(timer) }
|
|
217
|
+
const fn = (s) => { if (s === 'online') { off(); resolve(true) } }
|
|
218
|
+
const timer = setTimeout(() => { off(); resolve(false) }, WAIT_ONLINE_MS)
|
|
219
|
+
listeners.add(fn)
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
kind: 'relay',
|
|
224
|
+
label: computer.name || 'your computer',
|
|
225
|
+
_nonce: () => nonce, // test hooks
|
|
226
|
+
_hello: (m) => onHello(m),
|
|
227
|
+
computer,
|
|
228
|
+
status,
|
|
229
|
+
onChange(fn) { listeners.add(fn); return () => listeners.delete(fn) },
|
|
230
|
+
can: (cap) => caps.includes(cap),
|
|
231
|
+
omits: (cap) => omitted.includes(cap),
|
|
232
|
+
autoSessions: () => [...autoList],
|
|
233
|
+
onAuto(fn) { autoListeners.add(fn); return () => autoListeners.delete(fn) },
|
|
234
|
+
onProgress(fn) { progressListeners.add(fn); return () => progressListeners.delete(fn) },
|
|
235
|
+
/** The enclave's `browse` report from its last hello, or null (a local computer, or one from before § 12). */
|
|
236
|
+
browse: () => browseState,
|
|
237
|
+
egress: () => egressState,
|
|
238
|
+
onBrowse(fn) { browseListeners.add(fn); return () => browseListeners.delete(fn) },
|
|
239
|
+
/** Switch Auto for one session on the computer (nonce-checked there). The next hello confirms it. */
|
|
240
|
+
setAuto(sid, dir, on) { if (!nonce || !caps.includes('auto')) return false; peer.send({ t: 'auto', k: nonce, sid, dir, on: !!on }); return true },
|
|
241
|
+
/** Private browsing for the agent's browser on this computer — only where its browse report says `canPrivate` (an older
|
|
242
|
+
* witbitz-code never does). Nonce-checked there; the next hello carries the new state. */
|
|
243
|
+
setBrowsePrivate(on) { if (!nonce || !(browseState && browseState.canPrivate)) return false; peer.send({ t: 'browse', k: nonce, private: !!on }); return true },
|
|
244
|
+
/** Which suggested tools the computer has ("Set up this computer"): its `{t:'tools'}` answer, or null when it does not
|
|
245
|
+
* answer in `ms` — a connector from before this never does. */
|
|
246
|
+
askTools(ms = 6000) {
|
|
247
|
+
if (!nonce) return Promise.resolve(null)
|
|
248
|
+
return new Promise((resolve) => {
|
|
249
|
+
const done = (m) => { clearTimeout(timer); const i = toolWaiters.indexOf(done); if (i >= 0) toolWaiters.splice(i, 1); resolve(m) }
|
|
250
|
+
const timer = setTimeout(() => done(null), ms)
|
|
251
|
+
toolWaiters.push(done)
|
|
252
|
+
peer.send({ t: 'tools', k: nonce })
|
|
253
|
+
})
|
|
254
|
+
},
|
|
255
|
+
/** Tell the computer which models this account is offered as CONFIDENTIAL today. The connector ADDS them to what it
|
|
256
|
+
* was built with and never removes any, so this can only widen what is enforced, never narrow it. */
|
|
257
|
+
/** "Waiting for your approval" (codeRemind.js): with a prompt, who to tickle when an approval in this session waits — this
|
|
258
|
+
* device's signed push grant and its own key. Only to a computer that says it can (`remind`). */
|
|
259
|
+
sendRemind(sid, dir, r) { if (!nonce || !caps.includes('remind') || !r || !sid) return false; peer.send({ t: 'remind', k: nonce, sid, dir, grant: r.grant, key: r.key, url: r.url }); return true },
|
|
260
|
+
sendModels(list) { if (!nonce || !Array.isArray(list) || !list.length) return false; peer.send({ t: 'models', k: nonce, confidential: list.slice(0, 100) }); return true },
|
|
261
|
+
kick: () => { wake(); peer.kick() }, // the page is visible again: ask the computer, and redial a dead socket
|
|
262
|
+
close() {
|
|
263
|
+
clearInterval(resubTimer); clearInterval(freshTimer); clearTimeout(giveUpTimer)
|
|
264
|
+
for (const e of pending.values()) { clearTimeout(e.timer); e.resolve({ ok: false, status: 0, json: null, text: 'closed' }) }
|
|
265
|
+
pending.clear(); subs.clear(); listeners.clear(); autoListeners.clear(); progressListeners.clear(); browseListeners.clear()
|
|
266
|
+
peer.stop()
|
|
267
|
+
},
|
|
268
|
+
async request(method, p, body) {
|
|
269
|
+
if (!(await waitOnline())) return { ok: false, status: 0, json: null, text: 'offline' }
|
|
270
|
+
return new Promise((resolve) => {
|
|
271
|
+
const id = rid()
|
|
272
|
+
const b = body !== undefined ? { b: JSON.stringify(body) } : {}
|
|
273
|
+
const msg = () => ({ t: 'req', id, k: nonce, m: method, p, ...b }) // built at send time: always the CURRENT nonce
|
|
274
|
+
// A turn POST returns only when the model has finished; its progress rides the event stream, so no timeout.
|
|
275
|
+
const turn = method === 'POST' && /\/message$/.test(p.split('?')[0])
|
|
276
|
+
const entry = { resolve, timer: 0, resend: null }
|
|
277
|
+
// Reads are safe to re-ask after a reconnect; anything that changes state is never sent twice.
|
|
278
|
+
if (method === 'GET') entry.resend = () => peer.send(msg())
|
|
279
|
+
if (!turn) entry.timer = setTimeout(() => { pending.delete(id); resolve({ ok: false, status: 0, json: null, text: 'timeout' }) }, globalThis.__codeRequestMs || REQUEST_TIMEOUT_MS) // __codeRequestMs: tests only (as __codeListMs)
|
|
280
|
+
pending.set(id, entry)
|
|
281
|
+
peer.send(msg()).then((sent) => { if (!sent && method !== 'GET') { pending.delete(id); clearTimeout(entry.timer); resolve({ ok: false, status: 0, json: null, text: 'offline' }) } })
|
|
282
|
+
})
|
|
283
|
+
},
|
|
284
|
+
subscribe(p, onEvent) {
|
|
285
|
+
if (!subs.has(p)) subs.set(p, new Set())
|
|
286
|
+
subs.get(p).add(onEvent)
|
|
287
|
+
if (status() === 'online' && nonce) peer.send({ t: 'sub', c: cid, k: nonce, p })
|
|
288
|
+
return () => {
|
|
289
|
+
const set = subs.get(p)
|
|
290
|
+
if (!set) return
|
|
291
|
+
set.delete(onEvent)
|
|
292
|
+
if (!set.size) { subs.delete(p); if (nonce) peer.send({ t: 'unsub', c: cid, k: nonce, p }) }
|
|
293
|
+
}
|
|
294
|
+
},
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Delete a recorded session on its paired computer without switching the visible Code session. */
|
|
299
|
+
export async function deletePairedCodeSession(computers, target, current, cache) {
|
|
300
|
+
const [id, sid, extra] = String(target).split('/')
|
|
301
|
+
if (!id || extra !== undefined || !/^(?!\.)[A-Za-z0-9_.-]{1,128}$/.test(sid || '')) return false
|
|
302
|
+
const computer = computers.find(c => c.id === id)
|
|
303
|
+
if (!computer || !current()) return false
|
|
304
|
+
const transport = relayTransport({ computer })
|
|
305
|
+
try {
|
|
306
|
+
const path = '/session/' + encodeURIComponent(sid)
|
|
307
|
+
const info = await transport.request('GET', path)
|
|
308
|
+
if (!current()) return false
|
|
309
|
+
if (info.status === 404) { await removeCachedSession(cache.cid, sid, cache.store, cache.local); return true }
|
|
310
|
+
if (!info.ok || info.json?.id !== sid) return false
|
|
311
|
+
const folder = info.json.directory
|
|
312
|
+
const r = await transport.request('DELETE', path + (folder ? '?directory=' + encodeURIComponent(folder) : ''))
|
|
313
|
+
if ((!r.ok && r.status !== 404) || !current()) return false
|
|
314
|
+
await removeCachedSession(cache.cid, sid, cache.store, cache.local)
|
|
315
|
+
return true
|
|
316
|
+
} finally { transport.close() }
|
|
317
|
+
}
|
package/codeUndo.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// spaces/public/codeUndo.js — /undo, /redo and /compact in the Code section.
|
|
2
|
+
//
|
|
3
|
+
// Measured on opencode 1.18.30 (2026-09-13), a real agent writing a file in a scratch git repo:
|
|
4
|
+
// undo POST /session/:id/revert {messageID} → the Session, revert {messageID, snapshot, diff}; the files are back as
|
|
5
|
+
// they were before that turn ("two" → "one"). GET …/message still lists EVERY message — hiding is the page's.
|
|
6
|
+
// redo POST /session/:id/unrevert → files forward again, revert cleared.
|
|
7
|
+
// final a new message while undone drops the undone turns for good (and clears revert).
|
|
8
|
+
// compact POST /session/:id/summarize {providerID, modelID} → true; a user `compaction` part + an assistant summary.
|
|
9
|
+
// events session.updated carries the revert point, so an undo made elsewhere reaches this page.
|
|
10
|
+
// The pure rules are tested in spaces/test/codeUndo.test.mjs.
|
|
11
|
+
|
|
12
|
+
import { normRevert } from './opencodeWire.js' // the pure wire shape lives with the rest of the wire
|
|
13
|
+
export { normRevert }
|
|
14
|
+
|
|
15
|
+
const indexOf = (messages, revert) => (revert ? messages.findIndex((m) => m && m.info && m.info.id === revert.messageID) : -1)
|
|
16
|
+
const isUser = (m) => m && m.info && m.info.role === 'user'
|
|
17
|
+
|
|
18
|
+
/** The transcript as it stands: everything before the undone turn. A revert point not in the list hides nothing. */
|
|
19
|
+
export function visibleMessages(messages, revert) {
|
|
20
|
+
const at = indexOf(messages, revert)
|
|
21
|
+
return at < 0 ? messages : messages.slice(0, at)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** What /undo takes back: the last of your turns still showing (its message id), or null when there is none. */
|
|
25
|
+
export function undoTarget(messages, revert) {
|
|
26
|
+
const shown = visibleMessages(messages, revert)
|
|
27
|
+
for (let i = shown.length - 1; i >= 0; i--) if (isUser(shown[i])) return shown[i].info.id
|
|
28
|
+
return null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The page's own commands, listed after the computer's in the "/" menu (menu-shaped like normCommands' entries). They
|
|
32
|
+
// win over a computer command of the same name, as OpenCode's TUI's do.
|
|
33
|
+
export const UNDO_COMMANDS = [
|
|
34
|
+
{ name: 'undo', description: 'Take back your last turn, and the changes it made to files', source: 'built-in', template: '', agent: '', model: '', needsComputer: false },
|
|
35
|
+
{ name: 'redo', description: 'Bring back what undo took away', source: 'built-in', template: '', agent: '', model: '', needsComputer: false },
|
|
36
|
+
{ name: 'compact', description: 'Summarize the conversation so far, to free the model\'s context', source: 'built-in', template: '', agent: '', model: '', needsComputer: false },
|
|
37
|
+
]
|
|
38
|
+
/** "/undo", "/redo", "/compact" (anything after the name is ignored) → its name; anything else → null. */
|
|
39
|
+
export function undoCommand(text) {
|
|
40
|
+
const m = /^\/(\S+)(?:\s[\s\S]*)?$/.exec(String(text || '').trim())
|
|
41
|
+
return m && UNDO_COMMANDS.some((c) => c.name === m[1]) ? m[1] : null
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** How many of your turns the undo took away (what the note says). */
|
|
45
|
+
export function undoneTurns(messages, revert) {
|
|
46
|
+
const at = indexOf(messages, revert)
|
|
47
|
+
return at < 0 ? 0 : messages.slice(at).filter(isUser).length
|
|
48
|
+
}
|
package/compress.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// spaces/public/compress.js — gzip codec for synced docs (native CompressionStream, no dep).
|
|
2
|
+
// Large index/pipes docs are wrapped { z: <gzip-b64> } to dodge the 413 ceiling; small docs stay
|
|
3
|
+
// PLAIN so any reader unwraps transparently. LEAF: pure functions, zero back-deps. $( -clean.
|
|
4
|
+
|
|
5
|
+
// the SMALL compressed bytes, and any reader unwraps it. Small docs stay PLAIN (readable without the codec). If the
|
|
6
|
+
// browser lacks CompressionStream we push plain — a truly huge doc can still 413, i.e. no worse than before.
|
|
7
|
+
export const _hasGzip = typeof CompressionStream !== 'undefined' && typeof DecompressionStream !== 'undefined'
|
|
8
|
+
export const _jsonBytes = (v) => { try { return new TextEncoder().encode(JSON.stringify(v ?? null)).length } catch { return Infinity } }
|
|
9
|
+
async function _streamToU8(stream) {
|
|
10
|
+
const reader = stream.getReader(); const chunks = []; let n = 0
|
|
11
|
+
for (;;) { const { value, done } = await reader.read(); if (done) break; chunks.push(value); n += value.length }
|
|
12
|
+
const out = new Uint8Array(n); let o = 0; for (const c of chunks) { out.set(c, o); o += c.length }; return out
|
|
13
|
+
}
|
|
14
|
+
function _u8ToB64(u8) { let s = ''; for (let i = 0; i < u8.length; i++) s += String.fromCharCode(u8[i]); return btoa(s) }
|
|
15
|
+
function _b64ToU8(b64) { const s = atob(b64); const u8 = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) u8[i] = s.charCodeAt(i); return u8 }
|
|
16
|
+
export async function gzipB64(obj) {
|
|
17
|
+
const bytes = new TextEncoder().encode(JSON.stringify(obj ?? null))
|
|
18
|
+
const stream = new Response(bytes).body.pipeThrough(new CompressionStream('gzip'))
|
|
19
|
+
return _u8ToB64(await _streamToU8(stream))
|
|
20
|
+
}
|
|
21
|
+
export async function gunzipB64(b64) {
|
|
22
|
+
const stream = new Response(_b64ToU8(b64)).body.pipeThrough(new DecompressionStream('gzip'))
|
|
23
|
+
return JSON.parse(new TextDecoder().decode(await _streamToU8(stream)))
|
|
24
|
+
}
|
package/config.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// config.js — baked, dep-free configuration constants (Verified-Client Phase 1). App tag, the solo key
|
|
2
|
+
// model, and the PUBLIC Google OAuth client id + VAPID key. Imported wherever needed so no module owns them.
|
|
3
|
+
|
|
4
|
+
export const APP_TAG = 'spaces'
|
|
5
|
+
export const SOLO = { keyModel: '1-of-1' }
|
|
6
|
+
export const GOOGLE_CLIENT_ID = '138139257987-2s658reba6jjsc6rmuahputsts3qvjlk.apps.googleusercontent.com'
|
|
7
|
+
export const VAPID_PUBLIC_KEY = 'BADZvvI-iJ1LUpormHIdAvhtNiiArDSf30QRJ6kFh2grgAob6oP_X1GKQdDOXlogfUvgtDt3a74rIVfsw0tMvms' // public by design; unset ⇒ the notify row stays hidden
|
|
8
|
+
// Raw-bytes cap for a document attachment (PDF/Word/Excel) — kept under the server's 5MB base64 cap; the agent reads
|
|
9
|
+
// them via read_file (text extraction), and the turn POSTs straight to API Gateway (10MB limit). Shared by the composer's
|
|
10
|
+
// attachments and the WhatsApp import (both stage documents through the same reader).
|
|
11
|
+
export const MAX_FILE_BYTES = 3_500_000
|