@witbitz/sdk 4.3.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/a2aCore.js +41 -5
- package/accountErase.js +15 -4
- package/accountIndexDoc.js +24 -7
- package/accountRecord.js +6 -2
- package/accountStores.js +21 -5
- package/acctV2App.js +111 -12
- package/acctV2Client.js +11 -1
- package/acctV2UiCore.js +27 -7
- package/agentDoorTools.js +28 -0
- package/awsKey.js +3 -1
- package/backupRecord.js +3 -0
- package/chatLock.js +16 -0
- package/cloudDevicePins.js +2 -2
- package/codeAttachments.js +101 -0
- package/codeCache.js +173 -0
- package/codeCloud.js +2 -2
- package/codeComputers.js +9 -0
- package/codeFolders.js +116 -0
- package/codeHistory.js +76 -0
- package/codeLanguage.js +54 -0
- package/codeModes.js +2 -0
- package/codeProgress.js +54 -0
- package/codeSent.js +109 -0
- package/codeSubagents.js +107 -0
- package/codeTransport.js +46 -5
- package/connections.js +37 -20
- package/decrypt.html +69 -9
- package/deviceAttest.js +9 -3
- package/eraseFile.js +15 -0
- package/idb.js +19 -3
- package/idbSeal.js +5 -2
- package/inviteReceive.js +44 -0
- package/inviteSend.js +8 -2
- package/jobAgents.js +2 -2
- package/keptMerge.js +9 -2
- package/l1-worker-src.js +1 -1
- package/l1-worker.js +122 -43
- package/laneAssociation.js +78 -0
- package/laneConfig.js +4 -3
- package/laneLinkCore.js +9 -0
- package/ledgerView.js +30 -4
- package/manifest.json +112 -87
- package/memberChange.js +4 -2
- package/mirrorBatch.js +47 -0
- package/offlineBundle.js +21 -0
- package/opRouting.js +10 -0
- package/package.json +27 -2
- package/pdfOptions.js +13 -0
- package/pdfText.js +107 -0
- package/pdfjs.mjs +28 -0
- package/pdfjs.worker.mjs +28 -0
- package/protectedLocal.js +52 -13
- package/reactionHolders.js +86 -0
- package/removedMessage.js +1 -1
- package/roomEmbed.js +111 -0
- package/roomIntake.js +324 -0
- package/roomName.js +1 -1
- package/roomRoster.js +30 -7
- package/rosterCount.js +6 -3
- package/scheduleNext.js +60 -0
- package/sdkA2A.js +200 -42
- package/sdkAccount.js +88 -18
- package/sdkAccountDoc.js +13 -5
- package/sdkAccountSections.js +172 -23
- package/sdkAgui.js +33 -6
- package/sdkBackup.js +53 -11
- package/sdkBackupV2.js +15 -3
- package/sdkCloudDevice.js +20 -5
- package/sdkComputers.js +695 -65
- package/sdkDictation.js +115 -25
- package/sdkErase.js +12 -5
- package/sdkExports.js +19 -8
- package/sdkInvitations.js +4 -2
- package/sdkKeptAgent.js +19 -3
- package/sdkKeptIntake.js +100 -0
- package/sdkLaneLink.js +8 -9
- package/sdkPlan.js +4 -2
- package/sdkRekey.js +122 -22
- package/sdkReport.js +1 -1
- package/sdkSafeMedia.js +1 -1
- package/sdkSchedules.js +8 -1
- package/sdkSpeech.js +32 -2
- package/sdkTemporaryRooms.js +124 -0
- package/sdkTurn.js +12 -4
- package/sdkVault.js +66 -10
- package/sentinelRelease.js +1 -0
- package/sharedViews.js +34 -4
- package/siri.js +140 -9
- package/spaceClient.js +112 -17
- package/spaceEmailGate.js +2 -2
- package/spaceExport.js +50 -5
- package/spaceFork.js +15 -7
- package/spaceTemplates.js +99 -0
- package/speechOut.js +21 -5
- package/store.js +134 -27
- package/sw-notif-core.js +11 -8
- package/tapTrail.js +58 -0
- package/turnVerdict.js +1 -0
- package/usageReceipts.js +12 -5
- package/vault-core.js +568 -126
- package/vault-kit.mjs +3 -3
- package/vault-screens.js +30 -18
- package/vaultAtRest.js +38 -6
- package/vaultCoreLock.js +3 -1
- package/vaultCorePush.js +58 -7
- package/vaultKeep.js +9 -3
- package/vaultWorkerHost.js +32 -7
- package/witbitz-admin.d.ts +3 -0
- package/witbitz-admin.mjs +12 -11
- package/witbitz-sdk.d.ts +170 -43
- package/witbitz-sdk.js +833 -203
package/codeHistory.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// codeHistory: a conversation's messages without re-reading all of them (the owner: "When I change code sessions it
|
|
2
|
+
// reloads every time. Can't it be cached somehow? … only the last part of the conv, and when scrolled back gets the past
|
|
3
|
+
// context. A lazy load will also be fine.").
|
|
4
|
+
//
|
|
5
|
+
// Measured on opencode 1.18.30 (the owner's computer, 2026-09-14):
|
|
6
|
+
// • GET /session/:id/message sent the WHOLE history: "Witbitz 1" was 9,753,679 bytes (136 messages; one message alone
|
|
7
|
+
// 2.5 MB of tool output) — through the relay to a phone on every switch, and again after EVERY step of a turn.
|
|
8
|
+
// • `?limit=N` returns the LAST N messages (the last 20 of that session: 206 KB), oldest first, with an `x-next-cursor`
|
|
9
|
+
// header and `Link: …&before=<cursor>; rel="next"` for the page before them. `before=<message id>` is refused (400).
|
|
10
|
+
// • The cursor is base64url(JSON {"id": <oldest message id>, "time": <its info.time.created>}) — built here it equals
|
|
11
|
+
// the header byte for byte, and walking back 40 at a time returned all 136 messages in order, none twice. The relay
|
|
12
|
+
// does not forward response headers, so the page builds it itself.
|
|
13
|
+
// The page keeps a window: the newest messages, plus whatever older pages were scrolled into, per session in memory.
|
|
14
|
+
|
|
15
|
+
// Sizes from the owner's longest conversation: its newest 30 messages were 1,325 KB, 20 → 206 KB, 8 → 34 KB, 4 → 20 KB
|
|
16
|
+
// (tool output makes recent messages heavy). A turn's step needs only what changed since the last read.
|
|
17
|
+
export const TAIL = 20 // messages read when a conversation opens
|
|
18
|
+
export const STEP_TAIL = 6 // messages re-read after each step of a running turn (more is read only when they do not overlap)
|
|
19
|
+
export const PAGE = 20 // messages read each time you scroll back past the top
|
|
20
|
+
export const CACHED_SESSIONS = 8
|
|
21
|
+
|
|
22
|
+
const b64url = (s) => (typeof btoa === 'function' ? btoa(s) : Buffer.from(s, 'binary').toString('base64')).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
23
|
+
|
|
24
|
+
/** The cursor for the page BEFORE `message` (the oldest one you hold) — '' when it cannot be built. */
|
|
25
|
+
export function cursorBefore(message) {
|
|
26
|
+
const info = (message && message.info) || {}
|
|
27
|
+
const time = info.time && Number(info.time.created)
|
|
28
|
+
if (typeof info.id !== 'string' || !info.id || !Number.isFinite(time)) return ''
|
|
29
|
+
return b64url(JSON.stringify({ id: info.id, time }))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The query for the newest `limit` messages, or the `limit` before `cursor`. */
|
|
33
|
+
export const pageQuery = ({ limit = TAIL, cursor = '' } = {}) => `limit=${limit}${cursor ? `&before=${encodeURIComponent(cursor)}` : ''}`
|
|
34
|
+
|
|
35
|
+
/** Did a page come back full, i.e. may there be more before it? */
|
|
36
|
+
export const mayHaveMore = (page, limit) => Array.isArray(page) && page.length >= limit
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Fold a freshly read TAIL into the messages you hold. The tail's oldest message is found in yours, and everything from
|
|
40
|
+
* there on is taken from the server (a step's parts grew, a message was added — or removed by an undo that went final).
|
|
41
|
+
* No overlap (more new messages than one tail, e.g. after a long time offline): `overlap:false` — the caller reads further
|
|
42
|
+
* back, or starts a new window.
|
|
43
|
+
*/
|
|
44
|
+
export function mergeTail(current, tail) {
|
|
45
|
+
const cur = Array.isArray(current) ? current : []
|
|
46
|
+
if (!Array.isArray(tail)) return { messages: cur, overlap: true }
|
|
47
|
+
if (!tail.length) return { messages: [], overlap: true } // the server holds none: the conversation is empty
|
|
48
|
+
const at = cur.findIndex((m) => m && m.info && m.info.id === tail[0].info.id)
|
|
49
|
+
if (at < 0) return { messages: tail, overlap: false }
|
|
50
|
+
return { messages: [...cur.slice(0, at), ...tail], overlap: true }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** An older page in front of the messages you hold, without a message twice. */
|
|
54
|
+
export function prependOlder(current, older) {
|
|
55
|
+
const cur = Array.isArray(current) ? current : []
|
|
56
|
+
const have = new Set(cur.map((m) => m && m.info && m.info.id))
|
|
57
|
+
return [...(older || []).filter((m) => m && m.info && !have.has(m.info.id)), ...cur]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Per-session windows, the most recently used kept. { messages, cursor } — cursor '' once the start is reached. */
|
|
61
|
+
export class HistoryCache {
|
|
62
|
+
constructor(max = CACHED_SESSIONS) { this.max = max; this.map = new Map() }
|
|
63
|
+
get(sid) {
|
|
64
|
+
const v = this.map.get(sid)
|
|
65
|
+
if (v) { this.map.delete(sid); this.map.set(sid, v) }
|
|
66
|
+
return v || null
|
|
67
|
+
}
|
|
68
|
+
set(sid, value) {
|
|
69
|
+
if (!sid) return
|
|
70
|
+
this.map.delete(sid)
|
|
71
|
+
this.map.set(sid, value)
|
|
72
|
+
while (this.map.size > this.max) this.map.delete(this.map.keys().next().value)
|
|
73
|
+
}
|
|
74
|
+
drop(sid) { this.map.delete(sid) }
|
|
75
|
+
clear() { this.map.clear() }
|
|
76
|
+
}
|
package/codeLanguage.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// spaces/public/codeLanguage.js — the language the person writes in, so the coding agent narrates in it.
|
|
2
|
+
//
|
|
3
|
+
// The owner: "when deepseek is in a hebew project it thinks in english". Measured (2026-09-14, DeepSeek V4 Flash through
|
|
4
|
+
// OpenCode, a Hebrew request): no reasoning comes back — the English was the NARRATION between steps ("I'll analyze the
|
|
5
|
+
// case file…"), because everything around the model is English (OpenCode's prompt, the tools, this page's PROGRESS rule).
|
|
6
|
+
// An English "answer in the person's language" line changed nothing; a line written IN HEBREW, first in the turn's
|
|
7
|
+
// `system`, made the narration Hebrew and kept the answers right at the same token cost (spaces/test/codeLanguage.test.mjs).
|
|
8
|
+
// Only Hebrew is measured; another language gets no line until it is.
|
|
9
|
+
|
|
10
|
+
export const HEBREW_LINE = 'שפה: האדם כותב בעברית. כתוב בעברית כל טקסט שאתה מציג — גם את עדכוני ההתקדמות הקצרים לפני פעולה ובין שלבים, וגם את התשובה. שמות קבצים, פקודות וקוד נשארים כפי שהם.'
|
|
11
|
+
|
|
12
|
+
// …and beside the question itself. In a long session (the owner's: ≈677k tokens, mostly English narration) the line alone
|
|
13
|
+
// was not enough — the answer opened with an English paragraph. A synthetic part right after the person's words was.
|
|
14
|
+
export const HEBREW_NUDGE = '(ענה בעברית בלבד — גם עדכוני ההתקדמות, ההסברים וכל משפט אחר שאתה כותב. שמות קבצים, פקודות וקוד נשארים כפי שהם.)'
|
|
15
|
+
|
|
16
|
+
const HEBREW = /[א-ת]/g
|
|
17
|
+
const LATIN = /[A-Za-z]/g
|
|
18
|
+
|
|
19
|
+
/** 'he' | 'other' | '' (too few letters to say). Code, links and path-like words are left out of the count. */
|
|
20
|
+
export function languageOf(text) {
|
|
21
|
+
const words = String(text || '')
|
|
22
|
+
.replace(/```[\s\S]*?```/g, ' ')
|
|
23
|
+
.replace(/`[^`]*`/g, ' ')
|
|
24
|
+
.replace(/\bhttps?:\/\/\S+/g, ' ')
|
|
25
|
+
.split(/\s+/)
|
|
26
|
+
.filter((w) => !/[/\\._]/.test(w.replace(/^[א-ת]-/, '')) || !/[A-Za-z]/.test(w))
|
|
27
|
+
.join(' ')
|
|
28
|
+
const he = (words.match(HEBREW) || []).length
|
|
29
|
+
const latin = (words.match(LATIN) || []).length
|
|
30
|
+
if (he + latin < 3) return ''
|
|
31
|
+
return he / (he + latin) >= 0.3 ? 'he' : 'other'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The line for the person's messages, newest first: the first one that says anything decides. */
|
|
35
|
+
export function languageLine(texts) {
|
|
36
|
+
for (const t of texts || []) {
|
|
37
|
+
const lang = languageOf(t)
|
|
38
|
+
if (lang === 'he') return HEBREW_LINE
|
|
39
|
+
if (lang) return ''
|
|
40
|
+
}
|
|
41
|
+
return ''
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The turn's instructions with the language line FIRST — where it was measured to work. */
|
|
45
|
+
export function withLanguage(system, texts) {
|
|
46
|
+
const line = languageLine(texts)
|
|
47
|
+
return line ? `${line}\n\n${system}` : system
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The reminder that rides beside the person's words on a Hebrew turn — a synthetic part (the model reads it, the
|
|
51
|
+
* transcript does not show it) — or null. */
|
|
52
|
+
export function languageNudge(texts) {
|
|
53
|
+
return languageLine(texts) === HEBREW_LINE ? { type: 'text', text: HEBREW_NUDGE, synthetic: true } : null
|
|
54
|
+
}
|
package/codeModes.js
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
// Edits outside the project still ask first through `external_directory`, which these rules never touch.
|
|
14
14
|
|
|
15
15
|
/** OpenCode 1.18 Wildcard.match. */
|
|
16
|
+
export const unsuitableCodeModels = catalog => (catalog || []).filter(m => m?.maxTools).map(m => String(m.wire || '')).filter(Boolean)
|
|
17
|
+
|
|
16
18
|
export function wildcardMatch(str, pattern) {
|
|
17
19
|
const s = String(str).replaceAll('\\', '/')
|
|
18
20
|
let re = String(pattern).replaceAll('\\', '/').replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
|
package/codeProgress.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// codeProgress: what a confidential model is doing while nothing of its answer has reached OpenCode yet.
|
|
2
|
+
//
|
|
3
|
+
// The owner, watching Kimi K3 · confidential show "Thinking…" for minutes: "Why can't we see what he is thinking about".
|
|
4
|
+
// Measured on that turn: no thinking was sent at all (0 reasoning tokens) — 154 s went to reading a 78,518-token
|
|
5
|
+
// conversation before the first word, and a later step spent 4½ minutes writing a whole document as ONE tool call, which
|
|
6
|
+
// the confidential proxy holds back until TrustedRouter's receipt verifies. OpenCode cannot be told any of that (its AI SDK
|
|
7
|
+
// runs every tool call still open when a stream closes), so the proxy tells the connector, and the connector tells the
|
|
8
|
+
// phone: { t:'progress', sessionID, label, phase, attempt, tool?, subject?, chars?, bytes? } (tools/code-confidential.mjs).
|
|
9
|
+
// Never the tool call's contents — its name, the file it names, and how big it has grown.
|
|
10
|
+
|
|
11
|
+
export const PHASES = new Set(['waiting', 'answering', 'writing', 'checking', 'retrying', 'end'])
|
|
12
|
+
|
|
13
|
+
const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '')
|
|
14
|
+
const num = (v) => (Number.isFinite(v) && v >= 0 ? v : 0)
|
|
15
|
+
|
|
16
|
+
/** A progress message from the connector, checked — or null. */
|
|
17
|
+
export function normProgress(m) {
|
|
18
|
+
if (!m || typeof m !== 'object') return null
|
|
19
|
+
if (typeof m.sessionID !== 'string' || !/^ses[A-Za-z0-9_-]{1,80}$/.test(m.sessionID)) return null
|
|
20
|
+
if (!PHASES.has(m.phase)) return null
|
|
21
|
+
return {
|
|
22
|
+
sessionID: m.sessionID,
|
|
23
|
+
phase: m.phase,
|
|
24
|
+
label: str(m.label, 60),
|
|
25
|
+
attempt: Math.min(num(m.attempt) || 1, 9),
|
|
26
|
+
tool: str(m.tool, 40),
|
|
27
|
+
subject: str(m.subject, 200),
|
|
28
|
+
chars: num(m.chars),
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const fileName = (p) => String(p).split(/[\\/]/).filter(Boolean).pop() || ''
|
|
33
|
+
const size = (n) => (n >= 1000 ? `${Math.round(n / 1000).toLocaleString('en-US')} KB` : '')
|
|
34
|
+
|
|
35
|
+
function writingWhat(tool, subject) {
|
|
36
|
+
const file = fileName(subject)
|
|
37
|
+
if (tool === 'write') return file ? `Writing ${file}` : 'Writing a file'
|
|
38
|
+
if (tool === 'edit' || tool === 'multiedit' || tool === 'patch' || tool === 'apply_patch') return file ? `Editing ${file}` : 'Editing a file'
|
|
39
|
+
if (tool === 'bash') return 'Preparing a command'
|
|
40
|
+
if (tool === 'todowrite') return 'Updating the to-do list'
|
|
41
|
+
if (tool === 'task') return 'Starting an agent'
|
|
42
|
+
return tool ? `Preparing ${tool}` : 'Preparing a step'
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The working line's words for a progress report — '' when the transcript itself says it better (words are arriving). */
|
|
46
|
+
export function progressLine(p) {
|
|
47
|
+
if (!p) return ''
|
|
48
|
+
const who = p.label || 'The model'
|
|
49
|
+
if (p.phase === 'waiting') return p.attempt > 1 ? `Asking ${who} again` : `${who} is reading the conversation`
|
|
50
|
+
if (p.phase === 'writing') { const s = size(p.chars), what = writingWhat(p.tool, p.subject); return s ? `${what} · ${s}` : what }
|
|
51
|
+
if (p.phase === 'checking') return "Checking TrustedRouter's receipt"
|
|
52
|
+
if (p.phase === 'retrying') return 'TrustedRouter renewed its proof — asking again'
|
|
53
|
+
return ''
|
|
54
|
+
}
|
package/codeSent.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
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
|
+
import { parseAttachmentNote, shownName } from './codeAttachments.js'
|
|
12
|
+
|
|
13
|
+
export function providerRefusal(result) {
|
|
14
|
+
const err = result?.info?.error
|
|
15
|
+
return err ? unwrapJsonMessage(err.data?.message || err.message || err.name || 'the provider refused this turn') : ''
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const words = (s) => String(s == null ? '' : s).trim()
|
|
19
|
+
|
|
20
|
+
/** The ids of the user messages there are now — taken when a prompt is sent. */
|
|
21
|
+
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))
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Is there a user message that was not there when the prompt was sent, carrying its words? (A prompt with only files has no
|
|
25
|
+
* words, so history alone cannot confirm delivery.) `text` is what the person typed; the message may carry more after it (a PDF's text)
|
|
26
|
+
* and a language line beside it, never less.
|
|
27
|
+
*/
|
|
28
|
+
// The files a user message carries: its file parts' names, and the PDFs read in the page (their text blocks name them —
|
|
29
|
+
// in a /command's synthetic expansion too).
|
|
30
|
+
/** The names a list of staged files goes out under (opencodeWire.partsFor's filename). */
|
|
31
|
+
export const sentNames = (list) => (Array.isArray(list) ? list : []).map((f) => String((f && f.name) || 'attachment'))
|
|
32
|
+
// …and the files the CONNECTOR saved (side sweep round 5): it replaces a document's file part with its saved-attachment note
|
|
33
|
+
// (codeAttachments.js), so those names are read from the note; an image keeps its part and is listed as `inline` — counted once.
|
|
34
|
+
// Names compare in the note's shown form (shownName), on both sides.
|
|
35
|
+
const namesOf = (m) => {
|
|
36
|
+
const names = []
|
|
37
|
+
for (const p of m.parts || []) {
|
|
38
|
+
if (p?.type === 'file') names.push(shownName(String(p.filename || '')))
|
|
39
|
+
else if (p?.type === 'text') {
|
|
40
|
+
const note = p.synthetic ? parseAttachmentNote(p.text) : null
|
|
41
|
+
if (note) { for (const e of note) if (!e.inline) names.push(e.name); continue }
|
|
42
|
+
for (const d of splitPdfBlocks(words(p.text)).pdfs) names.push(shownName(String(d.name)))
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return names.sort()
|
|
46
|
+
}
|
|
47
|
+
// `files` (optional: the names of the files sent; side sweep round 3, code-attachment-delivery-matched-by-caption): when given,
|
|
48
|
+
// the message must carry exactly those files too — a caption alone confirmed files that never arrived, and a file-only
|
|
49
|
+
// prompt (no words) could never be confirmed. Without it, the words alone decide, as before.
|
|
50
|
+
export function promptLanded(messages, { knownUserIds, text, files }) {
|
|
51
|
+
const known = knownUserIds instanceof Set ? knownUserIds : new Set()
|
|
52
|
+
const want = words(text)
|
|
53
|
+
const wantFiles = Array.isArray(files) ? files.map((f) => shownName(String(f || ''))).sort() : null
|
|
54
|
+
if (!want && !(wantFiles && wantFiles.length)) return false
|
|
55
|
+
const history = Array.isArray(messages) ? messages : []
|
|
56
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
57
|
+
const m = history[i], info = m?.info
|
|
58
|
+
if (info?.role !== 'user' || !info.id) continue
|
|
59
|
+
if (known.has(info.id)) break
|
|
60
|
+
const saidIt = !want || (m.parts || []).some(p => p?.type === 'text' && !p.synthetic && (words(p.text) === want || splitPdfBlocks(words(p.text)).text === want))
|
|
61
|
+
if (!saidIt) continue
|
|
62
|
+
if (!wantFiles) return true
|
|
63
|
+
const got = namesOf(m)
|
|
64
|
+
if (got.length === wantFiles.length && got.every((n, j) => n === wantFiles[j])) return true
|
|
65
|
+
}
|
|
66
|
+
return false
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Has the prompt waiting on screen (`state.pending`) come back from the computer? By ITS message — the user ids known at send,
|
|
71
|
+
* its words and files — not by the count of user messages, which another device's message raised as well and so cleared the
|
|
72
|
+
* waiting prompt and its filenames (side sweep round 3: code-pending-attachment-cleared-by-unrelated-message). A pending
|
|
73
|
+
* prompt that carries no `known` set falls back to the count (`shownUsers` = user messages drawn now).
|
|
74
|
+
*/
|
|
75
|
+
export function pendingEchoed(messages, pending, shownUsers) {
|
|
76
|
+
if (!pending) return false
|
|
77
|
+
if (!(pending.known instanceof Set)) return shownUsers > pending.users
|
|
78
|
+
return promptLanded(messages, { knownUserIds: pending.known, text: pending.landed != null ? pending.landed : pending.text, files: pending.files })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function firstOutputStarted(messages) {
|
|
82
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
83
|
+
const message = messages[i]
|
|
84
|
+
if (message?.info?.role === 'user') break
|
|
85
|
+
if (message?.parts?.some(part => part && part.type !== 'step-start')) return true
|
|
86
|
+
}
|
|
87
|
+
return false
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** In-memory failed submissions, scoped to the computer/session chosen by the caller. */
|
|
91
|
+
export class PendingCodeDrafts {
|
|
92
|
+
constructor() { this.sessions = new Map(); this.sequence = 0 }
|
|
93
|
+
list(key) { return [...(this.sessions.get(key)?.values() || [])] }
|
|
94
|
+
get(key, id) { return this.sessions.get(key)?.get(id) || null }
|
|
95
|
+
close() { this.closed = true; this.sessions.clear() }
|
|
96
|
+
add(key, draft) {
|
|
97
|
+
if (this.closed) return null
|
|
98
|
+
const id = String(++this.sequence)
|
|
99
|
+
if (!this.sessions.has(key)) this.sessions.set(key, new Map())
|
|
100
|
+
this.sessions.get(key).set(id, { ...draft, id })
|
|
101
|
+
return id
|
|
102
|
+
}
|
|
103
|
+
discard(key, id) {
|
|
104
|
+
const queue = this.sessions.get(key)
|
|
105
|
+
if (!queue?.delete(id)) return false
|
|
106
|
+
if (!queue.size) this.sessions.delete(key)
|
|
107
|
+
return true
|
|
108
|
+
}
|
|
109
|
+
}
|
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
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { removeCachedSession } from './codeCache.js'
|
|
1
2
|
// codeTransport.js — how the Code section reaches OpenCode. Two interchangeable transports behind one shape, so the rest
|
|
2
3
|
// of opencodeApp.js never knows which it is using (docs/opencode-relay.md §5):
|
|
3
4
|
//
|
|
@@ -85,6 +86,7 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
|
|
|
85
86
|
let caps = []
|
|
86
87
|
let omitted = [] // what the connector leaves out on purpose (its hello's `omits`): no update adds it (state machines pass 9, C#8)
|
|
87
88
|
let autoList = []
|
|
89
|
+
let autoAsk = null // { sid, on, hellos }: a switch of Auto sent, not yet settled by a hello (side sweep: code-auto-choice-before-computer-confirmation)
|
|
88
90
|
const autoListeners = new Set()
|
|
89
91
|
const toolWaiters = [] // askTools() calls waiting for the computer's {t:'tools'} answer
|
|
90
92
|
const tellAuto = (e) => { for (const fn of autoListeners) { try { fn(e) } catch { /* */ } } }
|
|
@@ -145,9 +147,22 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
|
|
|
145
147
|
const nextCaps = Array.isArray(m.caps) ? m.caps.filter((c) => typeof c === 'string').slice(0, 16) : []
|
|
146
148
|
omitted = Array.isArray(m.omits) ? m.omits.filter((c) => typeof c === 'string').slice(0, 16) : []
|
|
147
149
|
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)) : []
|
|
148
|
-
|
|
150
|
+
const autoChanged = nextCaps.join() !== caps.join() || nextAuto.join() !== autoList.join()
|
|
151
|
+
if (autoChanged) { caps = nextCaps; autoList = nextAuto; tellAuto({ kind: 'sessions', sessions: [...autoList] }) }
|
|
152
|
+
// A SENT SWITCH OF AUTO IS SETTLED HERE (side sweep: code-auto-choice-before-computer-confirmation): applied → confirmed; still
|
|
153
|
+
// not applied two hellos on (the first may have left before the switch arrived) → the page is told, never left showing it.
|
|
154
|
+
if (autoAsk) {
|
|
155
|
+
autoAsk.hellos++
|
|
156
|
+
const done = autoList.includes(autoAsk.sid) === autoAsk.on
|
|
157
|
+
if (done || autoAsk.hellos >= 2) {
|
|
158
|
+
const a = autoAsk; autoAsk = null
|
|
159
|
+
if (!autoChanged) tellAuto({ kind: 'sessions', sessions: [...autoList] })
|
|
160
|
+
if (!done) tellAuto({ kind: 'autoRefused', sid: a.sid, on: a.on })
|
|
161
|
+
}
|
|
162
|
+
}
|
|
149
163
|
// A NEW nonce = the connector restarted, redialled or rotated: anything it has not answered was refused or lost —
|
|
150
164
|
// re-ask the reads with the new nonce and renew the streams. (Mutations are never re-sent.)
|
|
165
|
+
if (renewed) dropTurns('reconnected')
|
|
151
166
|
if (renewed && last === 'online') { resubscribe(); for (const e of pending.values()) if (e.resend) e.resend() }
|
|
152
167
|
// ★ Only a CHANGE is announced. A hello arrives every 20 s and the browser's row must not be rebuilt under the
|
|
153
168
|
// owner's finger — `changed()` below has the same discipline for the status string.
|
|
@@ -166,7 +181,7 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
|
|
|
166
181
|
role: 'client',
|
|
167
182
|
relay: computer.relay,
|
|
168
183
|
WebSocketImpl,
|
|
169
|
-
onState: (s) => { peersKnown = false; if (s === 'open') { openedAt = now(); peer.send({ t: 'ping' }); setTimeout(changed, PEERS_WAIT_MS + 50) } else { lastHello = 0; nonce = '' } changed() },
|
|
184
|
+
onState: (s) => { peersKnown = false; if (s === 'open') { if (openedAt) dropTurns('reconnected'); openedAt = now(); peer.send({ t: 'ping' }); setTimeout(changed, PEERS_WAIT_MS + 50) } else { lastHello = 0; nonce = '' } changed() },
|
|
170
185
|
onPeers: (n) => { peersKnown = peer.isOpen; if (n < 2) lastHello = 0; else peer.send({ t: 'ping' }); changed() },
|
|
171
186
|
onMessage: (m) => {
|
|
172
187
|
if (m.t === 'hello') { onHello(m); return }
|
|
@@ -191,6 +206,10 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
|
|
|
191
206
|
}
|
|
192
207
|
},
|
|
193
208
|
})
|
|
209
|
+
// A TURN WHOSE ANSWER MAY HAVE BEEN LOST (side sweep 2026-11-28): a turn has no timeout and is never re-sent, so an answer sent while
|
|
210
|
+
// the socket was being redialled (or by a connector that restarted) left it waiting for ever. Settled as failed, the page asks the
|
|
211
|
+
// computer whether the prompt landed (opencodeApp.js promptLanded) — it is never sent twice.
|
|
212
|
+
function dropTurns(why) { for (const [id, e] of pending) if (e.turn) { pending.delete(id); clearTimeout(e.timer); e.resolve({ ok: false, status: 0, json: null, text: why }) } }
|
|
194
213
|
const resubscribe = () => { if (nonce) for (const p of subs.keys()) peer.send({ t: 'sub', c: cid, k: nonce, p }) }
|
|
195
214
|
const wake = () => {
|
|
196
215
|
lastTick = now()
|
|
@@ -236,7 +255,7 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
|
|
|
236
255
|
egress: () => egressState,
|
|
237
256
|
onBrowse(fn) { browseListeners.add(fn); return () => browseListeners.delete(fn) },
|
|
238
257
|
/** Switch Auto for one session on the computer (nonce-checked there). The next hello confirms it. */
|
|
239
|
-
setAuto(sid, dir, on) { if (!nonce || !caps.includes('auto')) return false; peer.send({ t: 'auto', k: nonce, sid, dir, on: !!on }); return true },
|
|
258
|
+
setAuto(sid, dir, on) { if (!nonce || !caps.includes('auto')) return false; peer.send({ t: 'auto', k: nonce, sid, dir, on: !!on }); autoAsk = { sid, on: !!on, hellos: 0 }; return true },
|
|
240
259
|
/** Private browsing for the agent's browser on this computer — only where its browse report says `canPrivate` (an older
|
|
241
260
|
* witbitz-code never does). Nonce-checked there; the next hello carries the new state. */
|
|
242
261
|
setBrowsePrivate(on) { if (!nonce || !(browseState && browseState.canPrivate)) return false; peer.send({ t: 'browse', k: nonce, private: !!on }); return true },
|
|
@@ -255,7 +274,8 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
|
|
|
255
274
|
* was built with and never removes any, so this can only widen what is enforced, never narrow it. */
|
|
256
275
|
/** "Waiting for your approval" (codeRemind.js): with a prompt, who to tickle when an approval in this session waits — this
|
|
257
276
|
* device's signed push grant and its own key. Only to a computer that says it can (`remind`). */
|
|
258
|
-
|
|
277
|
+
// → the send itself (a promise, truthy): a retiring connection waits for it — sealed and on the wire — before it closes (side sweep round 5)
|
|
278
|
+
sendRemind(sid, dir, r) { if (!nonce || !caps.includes('remind') || !r || !sid) return false; return peer.send({ t: 'remind', k: nonce, sid, dir, grant: r.grant, key: r.key, url: r.url }).then((ok) => ok !== false, () => false) },
|
|
259
279
|
sendModels(list) { if (!nonce || !Array.isArray(list) || !list.length) return false; peer.send({ t: 'models', k: nonce, confidential: list.slice(0, 100) }); return true },
|
|
260
280
|
kick: () => { wake(); peer.kick() }, // the page is visible again: ask the computer, and redial a dead socket
|
|
261
281
|
close() {
|
|
@@ -272,7 +292,7 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
|
|
|
272
292
|
const msg = () => ({ t: 'req', id, k: nonce, m: method, p, ...b }) // built at send time: always the CURRENT nonce
|
|
273
293
|
// A turn POST returns only when the model has finished; its progress rides the event stream, so no timeout.
|
|
274
294
|
const turn = method === 'POST' && /\/message$/.test(p.split('?')[0])
|
|
275
|
-
const entry = { resolve, timer: 0, resend: null }
|
|
295
|
+
const entry = { resolve, timer: 0, resend: null, turn }
|
|
276
296
|
// Reads are safe to re-ask after a reconnect; anything that changes state is never sent twice.
|
|
277
297
|
if (method === 'GET') entry.resend = () => peer.send(msg())
|
|
278
298
|
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)
|
|
@@ -293,3 +313,24 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
|
|
|
293
313
|
},
|
|
294
314
|
}
|
|
295
315
|
}
|
|
316
|
+
|
|
317
|
+
/** Delete a recorded session on its paired computer without switching the visible Code session. */
|
|
318
|
+
export async function deletePairedCodeSession(computers, target, current, cache) {
|
|
319
|
+
const [id, sid, extra] = String(target).split('/')
|
|
320
|
+
if (!id || extra !== undefined || !/^(?!\.)[A-Za-z0-9_.-]{1,128}$/.test(sid || '')) return false
|
|
321
|
+
const computer = computers.find(c => c.id === id)
|
|
322
|
+
if (!computer || !current()) return false
|
|
323
|
+
const transport = relayTransport({ computer })
|
|
324
|
+
try {
|
|
325
|
+
const path = '/session/' + encodeURIComponent(sid)
|
|
326
|
+
const info = await transport.request('GET', path)
|
|
327
|
+
if (!current()) return false
|
|
328
|
+
if (info.status === 404) { await removeCachedSession(cache.cid, sid, cache.store, cache.local); return true }
|
|
329
|
+
if (!info.ok || info.json?.id !== sid) return false
|
|
330
|
+
const folder = info.json.directory
|
|
331
|
+
const r = await transport.request('DELETE', path + (folder ? '?directory=' + encodeURIComponent(folder) : ''))
|
|
332
|
+
if ((!r.ok && r.status !== 404) || !current()) return false
|
|
333
|
+
await removeCachedSession(cache.cid, sid, cache.store, cache.local)
|
|
334
|
+
return true
|
|
335
|
+
} finally { transport.close() }
|
|
336
|
+
}
|