@witbitz/sdk 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +26 -5
  3. package/accountErase.js +6 -1
  4. package/accountRecord.js +2 -2
  5. package/agentDoorTools.js +28 -0
  6. package/chatLock.js +16 -0
  7. package/cloudDevicePins.js +2 -2
  8. package/codeAttachments.js +100 -0
  9. package/codeCache.js +149 -0
  10. package/codeCloud.js +0 -2
  11. package/codeComputers.js +1 -0
  12. package/codeFolders.js +116 -0
  13. package/codeHistory.js +76 -0
  14. package/codeLanguage.js +54 -0
  15. package/codeModes.js +2 -0
  16. package/codeProgress.js +54 -0
  17. package/codeSent.js +68 -0
  18. package/codeSubagents.js +107 -0
  19. package/codeTransport.js +22 -0
  20. package/connections.js +17 -18
  21. package/deviceAttest.js +9 -3
  22. package/idb.js +19 -3
  23. package/jobAgents.js +2 -2
  24. package/keptMerge.js +9 -2
  25. package/l1-worker-src.js +1 -1
  26. package/l1-worker.js +93 -30
  27. package/laneAssociation.js +68 -0
  28. package/laneConfig.js +4 -3
  29. package/manifest.json +80 -61
  30. package/memberChange.js +4 -2
  31. package/mirrorBatch.js +47 -0
  32. package/opRouting.js +10 -0
  33. package/package.json +21 -2
  34. package/pdfOptions.js +13 -0
  35. package/pdfText.js +107 -0
  36. package/pdfjs.mjs +28 -0
  37. package/pdfjs.worker.mjs +28 -0
  38. package/protectedLocal.js +18 -2
  39. package/removedMessage.js +1 -1
  40. package/roomEmbed.js +111 -0
  41. package/roomName.js +1 -1
  42. package/roomRoster.js +21 -5
  43. package/rosterCount.js +6 -3
  44. package/sdkA2A.js +160 -40
  45. package/sdkAccount.js +17 -4
  46. package/sdkAccountDoc.js +11 -3
  47. package/sdkAccountSections.js +117 -8
  48. package/sdkBackup.js +35 -8
  49. package/sdkCloudDevice.js +8 -2
  50. package/sdkComputers.js +582 -53
  51. package/sdkDictation.js +114 -24
  52. package/sdkErase.js +9 -4
  53. package/sdkExports.js +4 -2
  54. package/sdkLaneLink.js +3 -3
  55. package/sdkPlan.js +4 -2
  56. package/sdkRekey.js +50 -17
  57. package/sdkReport.js +1 -1
  58. package/sdkSafeMedia.js +1 -1
  59. package/sdkSpeech.js +19 -2
  60. package/sdkTemporaryRooms.js +123 -0
  61. package/sdkVault.js +66 -10
  62. package/sentinelRelease.js +1 -0
  63. package/sharedViews.js +17 -3
  64. package/siri.js +114 -7
  65. package/spaceClient.js +16 -5
  66. package/spaceEmailGate.js +2 -2
  67. package/spaceTemplates.js +99 -0
  68. package/speechOut.js +4 -2
  69. package/store.js +83 -14
  70. package/sw-notif-core.js +9 -7
  71. package/turnVerdict.js +1 -0
  72. package/vault-core.js +480 -112
  73. package/vault-kit.mjs +2 -2
  74. package/vault-screens.js +5 -7
  75. package/vaultAtRest.js +35 -4
  76. package/vaultKeep.js +9 -3
  77. package/vaultWorkerHost.js +23 -4
  78. package/witbitz-admin.mjs +12 -11
  79. package/witbitz-sdk.d.ts +115 -24
  80. package/witbitz-sdk.js +572 -149
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
+ }
@@ -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, '.')
@@ -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,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
+ }
@@ -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
  //
@@ -293,3 +294,24 @@ export function relayTransport({ computer, WebSocketImpl, now = () => Date.now()
293
294
  },
294
295
  }
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/connections.js CHANGED
@@ -22,7 +22,7 @@ import { sealDisp, withDisplay } from './connDisp.js' // step 2: a connection's
22
22
  /** The standing Sentinel's image, a rollover set of PCR0s (docs/standing-sentinel.md; infra/enclave/sentinel-host/README.md
23
23
  * for the repin). Empty would mean attach REFUSES: the page will not seal an API key to an enclave it cannot name.
24
24
  * Pin it here and in the Lambda's SENTINEL_HOP_PCRS together. */
25
- export const STANDING_SENTINEL_PCR0 = ['1903ce28fc5a75efe2e57a451d667f1ce8b4b6e11872fb2b81d9e62d8cd994ed80fcfa99807f289af5f281aa4e4cc010', '267a82525bbdc8f17ed32792f887dad9b06629350da41c0357ad0a6d67a3b2a8aba0a93e1d3ee9ae56bdd07948eeff98'] // st56 and st55 during the rollout
25
+ export const STANDING_SENTINEL_PCR0 = ['1903ce28fc5a75efe2e57a451d667f1ce8b4b6e11872fb2b81d9e62d8cd994ed80fcfa99807f289af5f281aa4e4cc010'] // st56
26
26
 
27
27
  const b64 = (u8) => btoa(String.fromCharCode(...new Uint8Array(u8)))
28
28
  const unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0))
@@ -112,7 +112,7 @@ export const roomEntry = (c) => ({ account: c.account, id: c.id, callKey: c.call
112
112
  * façade by structured clone, and spaceClient.setConfig applies it to the room's current list under its own key.
113
113
  * @returns {{ id: string, label: string, host: string, callKey: string }}
114
114
  */
115
- export async function attachConnection({ post, auth = {}, record, by, account, label, host, secret, rules, limits, pins, verify, follow, tenant, bearerWebhook, dispKey } = {}) { // dispKey: connDisp.js — the name also goes sealed to the person's devices (step 2)
115
+ export async function attachConnection({ post, pendingStore, auth = {}, record, by, account, label, host, secret, rules, limits, pins, verify, follow, tenant, bearerWebhook, dispKey } = {}) { // dispKey: connDisp.js — the name also goes sealed to the person's devices (step 2)
116
116
  const acct = String(account || '').trim().toLowerCase()
117
117
  if (!/^[^\s@]{1,200}@[^\s@]{1,63}$/.test(acct)) throw new ConnectionError('sign in with your email first — a connection belongs to an account', 'account')
118
118
  const s = String(secret || '')
@@ -141,7 +141,7 @@ export async function attachConnection({ post, auth = {}, record, by, account, l
141
141
  ? { id, account: acct, provider: 'bearer', host: h, secret: s.trim(), label: lbl, ...(disp ? { disp } : {}), sign: /^whsec_/.test(s.trim()) ? 'standard-webhooks' : 'bearer', rules: { paths: [path] }, own: true, ...(limits ? { limits } : {}) } // a SIGNED WEBHOOK is the member's own, never under a tenant: the tenant vouches for API hosts, and a webhook's host is wherever the member's routine lives (the app's rule, now here for every caller — the SDK filed it under its tenant and the Sentinel refused the host; sync sweep, 2026-10-10)
142
142
  : { id, account: acct, provider: 'bearer', host: h, secret: s.trim(), label: lbl, ...(disp ? { disp } : {}), ...(tenant ? { tenant: String(tenant) } : {}), ...(rules ? { rules } : {}), ...(limits ? { limits } : {}) }
143
143
  const sk = await sealWithCallKey(att, grant, id, { label: lbl, host: h, account: acct })
144
- const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host: h, account: acct, at: Date.now() }, sk)
144
+ const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host: h, account: acct, at: Date.now() }, sk, undefined, undefined, pendingStore)
145
145
  if (!g || g.error || !g.ok) throw new ConnectionError(`the Sentinel refused the connection (${(g && g.error) || 'no answer'})`, (g && g.error) || 'refused')
146
146
  // ⛔ THE CONNECTION IS RETURNED EVEN WHEN THE SPACE COULD NOT RECORD IT (2026-11-08, docs/state-machines.md I16 / C#11): this threw
147
147
  // after the Sentinel had taken the grant — the callKey was dropped with the error, the Sentinel kept a connection no device
@@ -162,11 +162,10 @@ export async function attachConnection({ post, auth = {}, record, by, account, l
162
162
  // dropped on a definite answer (the caller keeps a granted one), and adopted when the account's list shows it.
163
163
  let _pendingStore = { keep () {}, drop () {} }
164
164
  export const setPendingKeyStore = (s) => { _pendingStore = { keep () {}, drop () {}, ...(s || {}) } }
165
- export async function postWithPendingKey (post, body, id, rec) {
166
- const store = _pendingStore
165
+ export async function postWithPendingKey (post, body, id, rec, store = _pendingStore) {
167
166
  try { await store.keep(id, rec) } catch (e) { if (store.durable) throw e }
168
167
  const r = await post(body) // a throw (no answer) leaves it pending
169
- if (r && (r.error || (r.ok && !store.durable))) { try { await store.drop(id) } catch { /* */ } }
168
+ if (r && (r.error || (r.ok && !store.durable))) { try { await store.drop(id, rec?.callKey) } catch { /* */ } }
170
169
  return r
171
170
  }
172
171
  export { adoptPendingKeys } // connPending.js — the rule, shared with the hosted app's vault (vaultConnKeys.js)
@@ -181,9 +180,9 @@ export { adoptPendingKeys } // connPending.js — the rule, shared with the host
181
180
  let _minter = null
182
181
  export const setCallKeyMinter = (m) => { _minter = m && typeof m.seal === 'function' ? m : null }
183
182
  /** `payload` + a fresh callKey, sealed to the attested Sentinel → { sealed, callKey ('' when the vault holds it), held, settle } */
184
- async function sealWithCallKey (att, payload, id, rec) {
185
- if (_minter && att.spki) {
186
- let v = null; try { v = await _minter.seal({ spki: att.spki, nonce: att.nonce, payload, id, rec }) } catch { v = null }
183
+ async function sealWithCallKey (att, payload, id, rec, minter = _minter) {
184
+ if (minter && att.spki) {
185
+ let v = null; try { v = await minter.seal({ spki: att.spki, nonce: att.nonce, payload, id, rec }) } catch (e) { if (e?.code === 'connection_limit') throw e; v = null }
187
186
  if (v && v.sealed) return { sealed: v.sealed, callKey: '', held: true, settle: v.settle }
188
187
  }
189
188
  const callKey = b64(crypto.getRandomValues(new Uint8Array(32)))
@@ -191,8 +190,8 @@ async function sealWithCallKey (att, payload, id, rec) {
191
190
  }
192
191
  /** Post a grant; while its answer is out the key is PENDING — in this page's store (rec = null: none), or the vault's, which a
193
192
  * definite answer settles: `filed` = it was filed (r.ok), `final(r)` = what the Sentinel filed it as ({ id, label, account }). */
194
- async function postGrant (post, body, id, rec, sk, filed = (r) => !!(r && r.ok && !r.error), final = () => ({})) {
195
- if (!sk.held) return rec ? postWithPendingKey(post, body, id, { ...rec, callKey: sk.callKey }) : post(body)
193
+ async function postGrant (post, body, id, rec, sk, filed = (r) => !!(r && r.ok && !r.error), final = () => ({}), pendingStore) {
194
+ if (!sk.held) return rec ? postWithPendingKey(post, body, id, { ...rec, callKey: sk.callKey }, pendingStore) : post(body)
196
195
  const r = await post(body) // a throw (no answer): the vault keeps it pending, adopted when the account lists it
197
196
  if (r && (r.ok || r.error)) { let ok = false; try { ok = !!(await sk.settle(filed(r), filed(r) ? final(r) : {})) } catch { ok = false } if (filed(r) && !ok) throw new ConnectionError('the connection was made, but your vault did not keep its key — open Connections again to finish', 'vault') }
198
197
  return r
@@ -263,7 +262,7 @@ export function connectionName (c) {
263
262
  * reachable while this connection lives, and a tenant's declared hosts vouch only for plain keys. (The SDK passed its tenant
264
263
  * here, and the Sentinel refused every MCP host the builder had not declared — DeepWiki included; docs sync, 2026-11-22.)
265
264
  * "Your own server" on a room's card is another mark: a server not in the catalog (connectionEntry.js, isCurated). */
266
- export async function attachMcp({ post, auth = {}, account, label, url, token = '', pins, verify, follow, dispKey, sealGrant = sealWithCallKey } = {}) {
265
+ export async function attachMcp({ post, pendingStore, auth = {}, account, label, url, token = '', pins, verify, follow, dispKey, sealGrant = sealWithCallKey } = {}) {
267
266
  const acct = String(account || '').trim().toLowerCase()
268
267
  if (!/^[^\s@]{1,200}@[^\s@]{1,63}$/.test(acct)) throw new ConnectionError('sign in with your email first — a connection belongs to an account', 'account')
269
268
  const { host, path } = parseMcpUrl(url)
@@ -275,7 +274,7 @@ export async function attachMcp({ post, auth = {}, account, label, url, token =
275
274
  const disp = dispKey ? await sealDisp(dispKey, id, { label: lbl }).catch(() => '') : ''
276
275
  const grant = { id, account: acct, provider: 'bearer', host, secret: t, label: lbl, ...(disp ? { disp } : {}), mcp: { path }, own: true }
277
276
  const sk = await sealGrant(att, grant, id, { label: lbl, host, account: acct })
278
- const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, account: acct, at: Date.now() }, sk)
277
+ const g = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'credgrant', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, account: acct, at: Date.now() }, sk, undefined, undefined, pendingStore)
279
278
  if (!g || g.error || !g.ok) throw new ConnectionError(`the Sentinel refused the connection (${(g && g.error) || 'no answer'})`, (g && g.error) || 'refused')
280
279
  return { id, label: lbl, host, callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}) }
281
280
  }
@@ -464,7 +463,7 @@ export async function connectorConsent (state, { trip, authUrl, win, broker, sig
464
463
  }
465
464
 
466
465
  /** Finish: seal { state, code, callKey, id, label } to the Sentinel, which exchanges the code and files the connection. */
467
- export async function finishMcpSignIn({ post, auth = {}, state, code, label, host, pins, verify, follow, dispKey }) {
466
+ export async function finishMcpSignIn({ post, pendingStore, auth = {}, state, code, label, host, pins, verify, follow, dispKey }) {
468
467
  const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
469
468
  const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
470
469
  const lbl = String(label || '').trim().slice(0, 80) || connectionName({ host }) // empty → the server's known name (GitHub), else the host
@@ -472,7 +471,7 @@ export async function finishMcpSignIn({ post, auth = {}, state, code, label, hos
472
471
  // clear label only) keeps it as it does a grant's; until then this record shows the Sentinel's label
473
472
  const disp = dispKey ? await sealDisp(dispKey, id, { label: lbl }).catch(() => '') : ''
474
473
  const sk = await sealWithCallKey(att, { state, code, id, label: lbl, ...(disp ? { disp } : {}) }, id, { label: lbl, host })
475
- const r = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'mcpoauthfinish', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, at: Date.now() }, sk)
474
+ const r = await postGrant(post, { op: 'sentinel', sentinel: { mode: 'mcpoauthfinish', sealed: sk.sealed }, ...auth }, id, { label: lbl, host, at: Date.now() }, sk, undefined, undefined, pendingStore)
476
475
  if (!r || r.error || !r.ok) throw new ConnectionError(`${host}: ${(r && r.error) || 'the sign-in did not finish'}`, 'signin')
477
476
  return { id, label: lbl, host, callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}) }
478
477
  }
@@ -534,13 +533,13 @@ export function awaitGitHubInstall(state, { timeoutMs = 15 * 60_000, drop = null
534
533
  })
535
534
  }
536
535
  /** Finish: seal { code, installationId, callKey, id } to the Sentinel, which checks the install is this person's and files it. */
537
- export async function finishGitHubInstall({ post, auth = {}, code, installationId, pins, verify, follow }) {
536
+ export async function finishGitHubInstall({ post, auth = {}, pendingStore, minter, code, installationId, pins, verify, follow }) {
538
537
  const att = await attestStandingSentinel({ post, auth, pins, verify, follow })
539
538
  const id = 'conn_' + b64u(crypto.getRandomValues(new Uint8Array(12)))
540
- const sk = await sealWithCallKey(att, { code: String(code || ''), installationId: Number(installationId), id }, id, { label: 'GitHub', host: 'api.github.com' })
539
+ const sk = await sealWithCallKey(att, { code: String(code || ''), installationId: Number(installationId), id }, id, { label: 'GitHub', host: 'api.github.com' }, minter)
541
540
  // no pending key in the page here (as before: the Sentinel may file it under its own id); a vault's is settled under the filed one
542
541
  const body = { op: 'sentinel', sentinel: { mode: 'ghappfinish', sealed: sk.sealed }, ...auth }
543
- const r = sk.held ? await postGrant(post, body, id, null, sk, undefined, (x) => ({ id: String(x.id || id), label: `GitHub · ${x.login || 'app'}`, account: String(x.account || '') })) : await post(body)
542
+ const r = await postGrant(post, body, id, { label: 'GitHub', host: 'api.github.com', at: Date.now() }, sk, undefined, (x) => ({ id: String(x.id || id), label: `GitHub · ${x.login || 'app'}`, account: String(x.account || '') }), pendingStore)
544
543
  if (!r || r.error || !r.ok) throw new ConnectionError(`GitHub: ${(r && r.error) || 'the install could not be connected'}`, 'ghapp')
545
544
  return { id: String(r.id || id), callKey: sk.callKey, ...(sk.held ? { held: 1 } : {}), account: String(r.account || ''), login: String(r.login || ''), installationId: Number(r.installationId || installationId), label: `GitHub · ${r.login || 'app'}` }
546
545
  }
package/deviceAttest.js CHANGED
@@ -510,10 +510,16 @@ export function makeDeviceAttest ({ bridge: bridgeOpt = deviceBridge(), client,
510
510
  // THE PHONE SIGNS WITH ANOTHER KEY than the one this page names (the owner's iPhone, 2026-11-24: the key enrolled at 09:20 never
511
511
  // signed once; every attested backup "ios: bad assertion signature"): forgotten, so the next proof enrols the key the phone holds —
512
512
  // at most once an hour, so a verifier that refuses every key cannot make a new hardware key per request
513
- if (/\b(ios|macos): bad assertion signature/.test(reason)) {
513
+ const expiredEnrollment = (['ios', 'macos'].includes(platform()) && /(?:^|: )enroll again: certificate expired\/not-yet-valid$/.test(reason)) ||
514
+ (platform() === 'android' && /(?:^|: )enroll again: a chain certificate is expired\/not-yet-valid$/.test(reason))
515
+ if (expiredEnrollment || /\b(ios|macos): bad assertion signature/.test(reason)) {
514
516
  const m = readMemo()
515
- if (sentKeyId && m.keyId && sentKeyId !== m.keyId) log('attest: a refused signature named an earlier key — the key enrolled since is kept')
516
- else if (m.keyId && !(m.badSigAt && now() - m.badSigAt < 60 * 60_000)) { writeMemo({ platform: m.platform, badSigAt: now() }); log('attest: the server could not verify this key\'s signature — will enroll again') }
517
+ if (sentKeyId && m.keyId && sentKeyId !== m.keyId) return true // another page already renewed it
518
+ if (!m.keyId) return !!sentKeyId
519
+ if (m.badSigAt && now() - m.badSigAt < 60 * 60_000) return false
520
+ writeMemo({ platform: m.platform, badSigAt: now() })
521
+ log(expiredEnrollment ? 'attest: the enrollment certificate is outside its validity period — will enroll again' : 'attest: the server could not verify this key’s signature — will enroll again')
522
+ return true
517
523
  }
518
524
  if (/windows_needs_activation/.test(reason)) { const m = readMemo(); const { act: _a, ...rest } = m; writeMemo(rest); log('attest: an enclave does not know this key\'s activation — will activate again') }
519
525
  },
package/idb.js CHANGED
@@ -27,10 +27,10 @@ export const idb = (() => {
27
27
  if (typeof indexedDB === 'undefined' || !indexedDB) { rej(Object.assign(new Error('no IndexedDB'), { noIdb: true })); return }
28
28
  let r
29
29
  try { r = indexedDB.open('spaces', 1) } catch (e) { rej(Object.assign(e instanceof Error ? e : new Error(String(e)), { noIdb: true })); return }
30
- r.onupgradeneeded = () => r.result.createObjectStore('kv'); r.onsuccess = () => res(r.result); r.onerror = () => rej(Object.assign(r.error || new Error('open failed'), { noIdb: true }))
30
+ r.onupgradeneeded = () => r.result.createObjectStore('kv'); r.onsuccess = () => { const db = r.result; db.onversionchange = () => { db.close(); dbp = null }; res(db) }; r.onerror = () => rej(Object.assign(r.error || new Error('open failed'), { noIdb: true }))
31
31
  }))
32
32
  // `fn` on IndexedDB, or `onMem(map)` when there is none (it never opened — a failed TRANSACTION stays a failure, as before)
33
- const tx = (mode, fn, onMem) => open().then((db) => new Promise((res, rej) => { const t = db.transaction('kv', mode), rq = fn(t.objectStore('kv')); t.oncomplete = () => res(rq && rq.result); t.onerror = () => rej(t.error) }),
33
+ const tx = (mode, fn, onMem) => open().then((db) => new Promise((res, rej) => { const t = db.transaction('kv', mode), rq = fn(t.objectStore('kv')); t.oncomplete = () => res(rq && rq.result); t.onerror = t.onabort = () => rej(t.error || new Error('IndexedDB transaction aborted')) }),
34
34
  (e) => { if (e && e.noIdb && onMem) return onMem(memory()); throw e })
35
35
  const inRange = (k, pfx) => !pfx || String(k).startsWith(pfx)
36
36
  // §APP STORE (appStore.js; docs/hosted-app-design.md §6): in the hosted app every raw call below is the VAULT's — its store
@@ -54,7 +54,16 @@ export const idb = (() => {
54
54
  // Keys only — a scan over a prefix that never loads the values (the protection migration walks the content ONE entry at a
55
55
  // time with it: a getAll() of the values holds every cached room in memory at once, and that killed the page on an iPhone).
56
56
  const keysRaw = (pfx) => (vault() ? vault()('keys', pfx || '') : tx('readonly', (s) => s.getAllKeys(range(pfx)), (m) => [...m.keys()])).then((ks) => (ks || []).map(String).filter((k) => k.startsWith(pfx))).catch(() => [])
57
- const delRaw = (k) => (vault() ? vault()('del', k) : tx('readwrite', (s) => s.delete(k), (m) => { m.delete(k) })).catch(() => {})
57
+ const delRawStrict = (k) => vault() ? vault()('del', k) : tx('readwrite', (s) => s.delete(k), (m) => { m.delete(k) })
58
+ const delRaw = (k) => delRawStrict(k).catch(() => {})
59
+ const delStrict = async (k) => {
60
+ if (isNamed(k)) {
61
+ const namer = idbNamingState().namer
62
+ if (!namer) throw new Error('cannot delete a protected key before unlocking')
63
+ await delRawStrict(await namer.opaque(k))
64
+ }
65
+ await delRawStrict(k)
66
+ }
58
67
  const delPrefixRaw = (pfx) => (vault() ? vault()('delPrefix', pfx || '') : tx('readwrite', (s) => { const rq = s.getAllKeys(range(pfx)); rq.onsuccess = () => { for (const k of (rq.result || [])) if (String(k).startsWith(pfx)) s.delete(k) } },
59
68
  (m) => { for (const k of [...m.keys()]) if (String(k).startsWith(pfx)) m.delete(k) })).catch(() => {})
60
69
  // §NAMES: the real names behind every opaque key (keys only — no value is read), [opaque, real] pairs.
@@ -71,6 +80,13 @@ export const idb = (() => {
71
80
  set: (k, v) => (!isNamed(k) ? wrapForStore(k, v).then((stored) => (stored === undefined ? undefined : setRaw(k, stored)))
72
81
  : !idbNamingState().namer ? Promise.resolve(undefined) // locked or memory-only: dropped, never a write under a real name
73
82
  : (async () => { const nm = idbNamingState().namer, key = idbNamingState().key; const o = await nm.opaque(k); const stored = await seal(key, v); await setRaw(o, stored); await delRaw(k) })()).catch(() => {}),
83
+ async clearStrict() {
84
+ if (vault()) return vault()('delPrefix', '')
85
+ if (typeof indexedDB === 'undefined' || !indexedDB) { memory().clear(); return }
86
+ await tx('readwrite', store => store.clear())
87
+ if (mem) mem.clear()
88
+ },
89
+ delStrict,
74
90
  del: (k) => (!isNamed(k) || !idbNamingState().namer ? delRaw(k) : idbNamingState().namer.opaque(k).then((o) => Promise.all([delRaw(o), delRaw(k)]))).catch(() => {}),
75
91
  delPrefix: (pfx) => (!idbNamingState().on || !idbNamingState().namer ? delPrefixRaw(pfx)
76
92
  : nameIndex().then((ix) => Promise.all([...ix.filter(([, n]) => n.startsWith(pfx)).map(([o]) => delRaw(o)), delPrefixRaw(pfx)]))).catch(() => {}),
package/jobAgents.js CHANGED
@@ -53,9 +53,9 @@ export function jobAgentOf(c) {
53
53
  export const isJobAgentConn = (c) => !!jobAgentOf(c)
54
54
 
55
55
  /** The names one Space's agent goes by: its connector on the agent's side ("Witbitz · Kyoto") and its peer here. */
56
- export function jobNames(agent, spaceName) {
56
+ export function jobNames(agent, spaceName, lane) {
57
57
  const s = clean(spaceName, 40) || 'my Space'
58
- return { connector: 'Witbitz · ' + s, peer: agent.name + ' · ' + s }
58
+ return { connector: 'Witbitz · ' + s, peer: agent.name + ' · ' + (lane || s) }
59
59
  }
60
60
 
61
61
  /** The saved prompt for the agent's task: act on the job it is sent, and always report back through this Space's connector. */
package/keptMerge.js CHANGED
@@ -27,8 +27,15 @@ export function unionMarks (a, b, max = MAX_MARKS) {
27
27
  export function mergePeers (pref, other, max = MAX_MARKS) {
28
28
  const removed = unionMarks(pref && pref.removed, other && other.removed, max)
29
29
  const mine = Array.isArray(pref && pref.peers) ? pref.peers : [], theirs = Array.isArray(other && other.peers) ? other.peers : []
30
- const have = new Set(mine.map((p) => p && p.id))
31
- const peers = [...mine, ...theirs.filter((p) => p && !have.has(p.id))].filter((p) => p && !removed[p.id])
30
+ const others = new Map(theirs.map(p => [p?.id, p]))
31
+ const peers = mine.map(peer => {
32
+ const remote = others.get(peer?.id)
33
+ others.delete(peer?.id)
34
+ if (!remote || !peer) return peer
35
+ const a = Number(peer.replyAt) || 0, b = Number(remote.replyAt) || 0
36
+ if (b > a || (b && b === a && remote.reply === 'ask')) return { ...peer, reply: remote.reply, replyAt: b }
37
+ return peer
38
+ }).concat([...others.values()]).filter(p => p && !removed[p.id])
32
39
  return { ...pref, peers, ...(Object.keys(removed).length ? { removed } : {}) }
33
40
  }
34
41