@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/sdkA2A.js CHANGED
@@ -16,19 +16,19 @@ import { isKeptSpace, assertNotKept } from './sdkCloudDevice.js'
16
16
 
17
17
  export async function assertAgentTarget(space) {
18
18
  if (space._sharedRoom) return
19
- const session = space._wb && space._wb._session
19
+ const session = space._wb && space._wb._session, generation = space._wb?._archiveGeneration
20
20
  const cfg = await space._client.getConfig(space.room, space._mk, { plainMark: true })
21
21
  if (!session || !session.email || !cfg || cfg.admission !== 'email' || !cfg.allow) throw fail('solo_verified_required', 'outside agents need a private lane or a solo verified Space')
22
22
  if (!(await isSoloVerified(cfg, space.room, session.email))) throw fail('solo_verified_required', 'outside agents need a verified Space with only you in it')
23
23
  const book = await space._client.state(space.room, space._mk, 'roster')
24
24
  if (!book || book.status !== 200 || await rosterParticipants(cfg, space.room, { seen: book.seen || book.state?.seen }) !== 1) throw fail('solo_verified_required', 'outside agents need a solo verified Space')
25
- if (space._wb._session !== session) throw fail('account_changed', 'the account changed while checking the Space')
25
+ if (space._wb._archiveGeneration !== generation || space._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed while checking the Space')
26
26
  }
27
27
  import { readAllPages } from './ledgerView.js'
28
28
  import { sealTo as sealToEnclave } from './sealShare.js'
29
29
  // The rules — the record, letting a peer in, the Sentinel calls, opening a collected message — are a2aCore.js, which the
30
30
  // Spaces app's a2aLane.js shares. This module is the SDK's classes and storage around them.
31
- import { A2A_COLLECT_WINDOW_MS, finishedTask, A2A_ENDPOINT, a2aTokenHash, cardUrlOf, mcpUrlOf, normA2A, mergeA2ARecords, peersOf, enableLaneIn, addPeerIn, setPeerReplyIn, removePeerIn, disableLaneIn, clearLanesIn, recordFor, sentinelCalls, openItem, a2aMessage, a2aInstructions, isJobPeer } from './a2aCore.js'
31
+ import { A2A_COLLECT_WINDOW_MS, finishedTask, A2A_ENDPOINT, a2aTokenHash, cardUrlOf, mcpUrlOf, normA2A, mergeA2ARecords, peersOf, applyRemovals, removalIntents, pruneGoneIn, enableLaneIn, addPeerIn, setPeerReplyIn, removePeerIn, disableLaneIn, clearLanesIn, recordFor, sentinelCalls, openItem, a2aMessage, a2aInstructions, isJobPeer } from './a2aCore.js'
32
32
  import { isLaneCopy } from './roomName.js' // a lane's copy of its shared room's line is never a draft
33
33
  import { A2A_PENDING_DOC, A2A_PEERS_DOC, peersFromDoc, pendingFromDoc, withoutShared } from './a2aShared.js'
34
34
  /** The Sentinel's answer for a task that already has its reply (infra/cloud-computer/sentinel/a2a.mjs). */
@@ -36,7 +36,7 @@ export { finishedTask } // a2aCore.js — one test for the app and the SDK
36
36
  export { A2A_ENDPOINT, a2aTokenHash }
37
37
  /** Persisted state → its checked form (a2aCore.normA2A — the app's rules: room, handle and key shapes, ≤ 32 lanes and peers). */
38
38
  export const a2aStateOf = normA2A
39
- const fail = (code, msg) => Object.assign(new Error('witbitz: ' + msg), { code })
39
+ const fail = (code, msg, details = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...details })
40
40
  /** The pending tasks as a snapshot carries them (JSON-safe, bounded): a lane's snapshot() / resume (sync sweep 10-24 #17). */
41
41
  export const pendingOf = (xs) => (Array.isArray(xs) ? xs : []).filter((p) => p && typeof p.taskId === 'string' && p.taskId && p.peer && typeof p.peer === 'object').slice(-50)
42
42
  .map((p) => ({ taskId: p.taskId, n: Number(p.n) || 0, peer: { id: String(p.peer.id || ''), name: String(p.peer.name || '').slice(0, 80), reply: p.peer.reply === 'auto' ? 'auto' : 'ask', ...(p.peer.job ? { job: true } : {}) },
@@ -46,12 +46,16 @@ export const pendingOf = (xs) => (Array.isArray(xs) ? xs : []).filter((p) => p &
46
46
  export class A2AAccount {
47
47
  /** @param wb the Witbitz client; `deps` lets a test replace the Sentinel path ({ post, auth, attest, seal }). */
48
48
  constructor(wb, { endpoint = A2A_ENDPOINT, state = null, deps = null } = {}) {
49
- this._wb = wb; this._endpoint = String(endpoint).replace(/\/+$/, ''); this._s = a2aStateOf(state); this._deps = deps
49
+ this._wb = wb; this._endpoint = String(endpoint).replace(/\/+$/, ''); this.restore(state); this._deps = deps
50
50
  /** Called with the new state whenever it changes — persist it (it holds the lanes' inbox private keys). */
51
51
  this.onState = null
52
52
  }
53
- get state() { return JSON.parse(JSON.stringify(this._s)) }
54
- restore(state) { this._s = a2aStateOf(state); return this }
53
+ get state() { return JSON.parse(JSON.stringify({ ...this._s, ...(this._removals.length ? { pendingRemovals: this._removals } : {}) })) }
54
+ restore(state) {
55
+ this._s = a2aStateOf(state)
56
+ this._removals = Array.isArray(state?.pendingRemovals) ? state.pendingRemovals.filter(x => Array.isArray(x) && x.length === 3 && x.every(v => typeof v === 'string') && this._s.lanes[x[0]]?.handle === x[1]).map(x => [...x]) : []
57
+ return this
58
+ }
55
59
  get endpoint() { const c = this._wb && this._wb._client; return c && c.vault ? A2A_ENDPOINT : this._endpoint } // in a vault the vault's door answers (it is built with the default; sync sweep backlog P7) — never the page's own setting
56
60
  _d() {
57
61
  const wb = this._wb
@@ -59,18 +63,79 @@ export class A2AAccount {
59
63
  return { post: wb._sentinelPost(), auth: wb._auth(), attest: (o) => attestStandingSentinel({ ...o, pins: wb._sentinel.pins, verify: wb._sentinel.verify, follow: wb._sentinel.follow }), seal: sealToEnclave }
60
64
  }
61
65
  async _account() { const s = this._wb._session; if (!s || !s.email) throw fail('sign_in_required', 'A2A belongs to an account — sign in first (' + (this._wb && this._wb.vault ? 'wb.vault.signIn' : 'wb.signIn') + ')'); return this._wb._account() } // the app-scoped account on a builder's page (accountScope.js)
66
+ _dropMoved(removed = []) {
67
+ for (const lane of this._wb._agentHandles || []) for (const item of removed) {
68
+ if (item.source !== lane.room) continue
69
+ lane._a2a?._dropDrafts(item.id)
70
+ if (lane._a2aResume) lane._a2aResume = lane._a2aResume.filter(task => task.peer?.id !== item.id)
71
+ }
72
+ }
73
+ async _disconnectConnection(id, binding) {
74
+ const removed = []
75
+ await this._change(record => {
76
+ for (const [source, lane] of Object.entries(record.lanes)) {
77
+ for (const peer of [...lane.peers]) {
78
+ const bound = binding?.peerId === peer.id && binding?.peerRoom === source
79
+ if (!isJobPeer(peer) || (peer.connectionId ? peer.connectionId !== id : !bound)) continue
80
+ removePeerIn(record, source, peer.id)
81
+ removed.push({ source, id: peer.id })
82
+ }
83
+ }
84
+ return removed.length || NO_CHANGE
85
+ })
86
+ this._dropMoved(removed)
87
+ return removed
88
+ }
89
+ async stopJobAgent(name) {
90
+ if (typeof name !== 'string' || !name.trim()) throw fail('invalid_argument', 'Choose a named job agent')
91
+ const removed = []
92
+ await this._change(s => {
93
+ for (const [source, lane] of Object.entries(s.lanes)) for (const peer of [...lane.peers]) {
94
+ if (peer.name === name.trim() && isJobPeer(peer)) { removePeerIn(s, source, peer.id); removed.push({ source, id: peer.id }) }
95
+ }
96
+ return removed.length || NO_CHANGE
97
+ })
98
+ this._dropMoved(removed)
99
+ return { removed }
100
+ }
101
+ _dropAllDrafts() {
102
+ for (const lane of this._wb._agentHandles || []) { lane._a2aResume = null; lane._a2aReceipts = []; lane._a2a?._posted.clear(); lane._a2a?._dropDrafts() }
103
+ }
104
+ _resetAccount() {
105
+ this._dropAllDrafts()
106
+ clearTimeout(this._pruneRetry)
107
+ this._pruneRetry = null
108
+ this._s = a2aStateOf(null); this._removals = []
109
+ }
110
+ _pruneForgotten() {
111
+ const wb = this._wb, generation = wb._archiveGeneration, state = wb.backup?._s
112
+ if (!wb._session || !state || this._pruneRun) return
113
+ const rooms = new Map((state.rooms || []).map(r => [r.room, Number(r.at) || 0]))
114
+ const gone = new Set((state.tomb || []).filter(t => !rooms.has(t.room) || Number(t.at) >= rooms.get(t.room)).map(t => t.room))
115
+ if (!Object.keys(this._s.lanes).some(room => gone.has(room))) return
116
+ this._pruneRun = this._change(next => pruneGoneIn(next, room => gone.has(room)) || NO_CHANGE).then(() => {
117
+ clearTimeout(this._pruneRetry)
118
+ }, () => {
119
+ if (generation !== wb._archiveGeneration || wb.backup?._s !== state) return
120
+ clearTimeout(this._pruneRetry)
121
+ this._pruneRetry = setTimeout(() => this._pruneForgotten(), 30000)
122
+ this._pruneRetry.unref?.()
123
+ }).finally(() => { this._pruneRun = null })
124
+ }
62
125
  _changed() { if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback */ } } }
63
126
  _calls() {
64
127
  const { post, auth, attest, seal } = this._d()
65
- return sentinelCalls({ post, auth, attest, seal, err: (kind, m) => fail(kind === 'refused' ? 'sentinel_refused' : 'sentinel_unreachable', m) })
128
+ return sentinelCalls({ post, auth, attest, seal, err: (kind, m, reply) => fail(kind === 'refused' ? 'sentinel_refused' : 'sentinel_unreachable', m, { definiteRefusal: kind === 'refused' && !!reply && (reply.ok === false || !!reply.error) && !(reply.status >= 500) && !['sentinel_unavailable', 'unreachable', 'timeout', 'busy'].includes(reply.error) }) })
66
129
  }
67
130
  _sealed(mode, obj) { return this._calls().sealed(mode, obj) }
68
131
  _plain(mode, extra = {}) { return this._calls().plain(mode, extra) }
69
132
  /** Send the whole record (it REPLACES what the Sentinel held) — this account's, or `s`, a changed copy (_change). */
70
- async _push(s = this._s, expectedSession = this._wb._session) {
133
+ async _push(s = this._s, expectedGeneration = this._wb._archiveGeneration) {
71
134
  const account = await this._account()
72
- if (this._wb._session !== expectedSession) throw fail('account_changed', 'the account changed while sharing its agent record')
73
- const r = await this._sealed('a2agrant', { ...recordFor(s, account), preserveIntake: true })
135
+ if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
136
+ const candidate = this._removals.length ? structuredClone(s) : s
137
+ if (this._removals.length) applyRemovals(candidate, this._removals)
138
+ const r = await this._sealed('a2agrant', { ...recordFor(candidate, account), preserveIntake: true })
74
139
  if (s === this._s) this._changed()
75
140
  return r
76
141
  }
@@ -82,14 +147,24 @@ export class A2AAccount {
82
147
  // push was out (a vault applying the account's kept copy) is merged with the change, not overwritten (a2aCore.js rules).
83
148
  // `fn` returns NO_CHANGE when there is nothing to do (nothing pushed).
84
149
  _change(fn) {
150
+ const generation = this._wb._archiveGeneration, email = this._wb._session?.email
151
+ const changed = () => generation !== this._wb._archiveGeneration || email !== this._wb._session?.email
85
152
  const run = async () => {
86
- const session = this._wb._session
153
+ if (changed()) throw fail('account_changed', 'the account changed before the agent update')
87
154
  const base = this._s, next = JSON.parse(JSON.stringify(base))
155
+ const previous = this._removals.slice()
88
156
  const out = await fn(next)
89
- if (out === NO_CHANGE) return out
90
- if (this._wb._session !== session) throw fail('account_changed', 'the account changed during the agent update')
91
- await this._push(next, session)
92
- if (this._wb._session !== session) throw fail('account_changed', 'the account changed during the agent update')
157
+ if (out === NO_CHANGE && !previous.length) return out
158
+ applyRemovals(next, previous)
159
+ const existing = new Set(previous.map(x => JSON.stringify(x)))
160
+ const added = this._stageInbox ? [] : removalIntents(base, next).filter(x => !existing.has(JSON.stringify(x)))
161
+ if (changed()) throw fail('account_changed', 'the account changed during the agent update')
162
+ if (added.length) { this._removals.push(...added); this._changed() }
163
+ const finish = await this._stageInbox?.(next)
164
+ try { await this._push(next, generation) } catch (e) { if (!changed() && (e.definiteRefusal || (e.status >= 400 && e.status < 500))) { finish?.(false); if (added.length) { this._removals = previous; this._changed() } } throw e }
165
+ if (changed()) throw fail('account_changed', 'the account changed during the agent update')
166
+ finish?.(true)
167
+ this._removals = []
93
168
  this._s = this._s === base ? a2aStateOf(next) : mergeA2ARecords(next, this._s)
94
169
  this._changed()
95
170
  return out
@@ -102,7 +177,7 @@ export class A2AAccount {
102
177
  status() { return this._plain('a2astatus') }
103
178
  /** Turn A2A off everywhere for this account: every lane's card and every token stop working. Each inbox is marked switched
104
179
  * off, so no other device's copy of the account's record switches one back on (pass 9, K#3). */
105
- async revoke() { const r = await this._plain('a2arevoke'); this._s = a2aStateOf(clearLanesIn(this._s)); this._changed(); return r }
180
+ async revoke() { const generation = this._wb._archiveGeneration; const r = await this._plain('a2arevoke'); if (this._wb._archiveGeneration !== generation) throw fail('account_changed', 'the account changed during revocation'); this._s = a2aStateOf(clearLanesIn(this._s)); this._removals = []; this._dropAllDrafts(); this._changed(); return r }
106
181
  }
107
182
  const deliveryKey = (taskId, n, at) => JSON.stringify([taskId, Number(n) || 1, Number(at) || 0])
108
183
  const NO_CHANGE = Symbol('no change')
@@ -115,7 +190,7 @@ export class LaneA2A {
115
190
  // the lane's snapshot(): a message is acked as it is posted, so a reload that lost these left the agent's task "working"
116
191
  // for ever (sync sweep 10-24 #17). Resumed: watched again, and a draft that already came is offered again.
117
192
  this._pending = pendingOf(lane._a2aResume)
118
- this._posted = new Set(this._pending.map((p) => deliveryKey(p.taskId, p.n, p.at))) // posted in this lane already (an ack that failed must not repost it)
193
+ this._posted = new Set([...(lane._a2aReceipts || []), ...this._pending.map((p) => deliveryKey(p.taskId, p.n, p.at))]) // posted in this lane already (an ack that failed must not repost it)
119
194
  this._ambiguous = new Map()
120
195
  this._sendingDrafts = new Set()
121
196
  this._seenDrafts = new WeakSet()
@@ -146,16 +221,32 @@ export class LaneA2A {
146
221
  * assistant answers it on its own). `job: true`: an agent that TAKES JOBS — it reports and its run ends, reading no reply,
147
222
  * so its messages are told to the member and a follow-up is a new job (docs/sdk-agents.md). → { id, token, cardUrl } — the
148
223
  * token is shown ONCE; only its hash is kept. */
149
- async addPeer(name, { reply = 'ask', job = false } = {}) {
224
+ async addPeer(name, { reply = 'ask', job = false, reconnect = false, previousPeerId, connectionId } = {}) {
150
225
  if (reply === 'auto') await assertNotKept(this._lane)
151
226
  await assertAgentTarget(this._lane)
152
227
  const a = this._acct()
153
- const { id, token } = await a._change((s) => addPeerIn(s, this._lane.room, name, { reply, job: job === true }, (code, m) => fail(code, code === 'not_enabled' ? 'enable A2A on this lane first (lane.a2a.enable())' : m)))
228
+ const moved = [], room = this._lane.room
229
+ const { id, token } = await a._change(async s => {
230
+ if (previousPeerId && !s.lanes[room]?.peers.some(peer => peer.id === previousPeerId)) throw fail('not_found', 'The previous peer is not on this lane.')
231
+ if (reconnect || previousPeerId) {
232
+ for (const [source, lane] of Object.entries(s.lanes)) for (const peer of [...lane.peers]) {
233
+ if ((reconnect && peer.name === String(name).trim()) || (source === room && previousPeerId && peer.id === previousPeerId)) { removePeerIn(s, source, peer.id); moved.push({ source, id: peer.id }) }
234
+ }
235
+ if (!s.lanes[room]) await enableLaneIn(s, room, { name: 'Private assistant' })
236
+ }
237
+ return addPeerIn(s, room, name, { reply, job: job === true, connectionId }, (code, m) => fail(code, code === 'not_enabled' ? 'enable A2A on this lane first (lane.a2a.enable())' : m))
238
+ })
239
+ a._dropMoved(moved)
240
+ for (const previous of moved) {
241
+ const old = previous.source === room ? this._lane : [...(this._lane._wb._agentHandles || []), ...(this._lane._wb._archiveHandles || [])].find(sp => sp.room === previous.source)
242
+ if (old?._a2a) { old._a2a._dropDrafts(previous.id); await old._a2a._syncRoomPeer(previous.id).catch(() => {}) }
243
+ }
154
244
  try { await this._syncRoomPeer(id) } catch (error) {
245
+ if (reconnect || previousPeerId) return { id, token, ...(moved.length ? { moved } : {}), cardUrl: this.cardUrl, mcpUrl: this.mcpUrl, roomListPending: true }
155
246
  await a._change((s) => removePeerIn(s, this._lane.room, id) || NO_CHANGE)
156
247
  throw error
157
248
  }
158
- return { id, token, cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
249
+ return { id, token, ...(moved.length ? { moved } : {}), cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
159
250
  }
160
251
  /** Change whether this peer's answers wait for you ('ask') or go on their own ('auto'). */
161
252
  async setReply(peerId, reply) {
@@ -176,11 +267,11 @@ export class LaneA2A {
176
267
  async _syncRoomPeer(id) {
177
268
  const sp = this._lane
178
269
  if (sp._sharedRoom) return
179
- const session = sp._wb._session
270
+ const session = sp._wb._session, generation = sp._wb._archiveGeneration
180
271
  await assertAgentTarget(sp)
181
272
  for (let i = 0; i < 5; i++) {
182
273
  const doc = await sp._client.state(sp.room, sp._mk, A2A_PEERS_DOC)
183
- if (session !== sp._wb._session) throw fail('account_changed', 'the account changed while saving the peer')
274
+ if (sp._wb._archiveGeneration !== generation || sp._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed while saving the peer')
184
275
  if (!doc || doc.status !== 200) throw fail('unreadable', 'the room peer list could not be read')
185
276
  const peers = peersFromDoc(doc).filter((p) => p.id !== id)
186
277
  const peer = this.peers.find((p) => p.id === id)
@@ -195,25 +286,25 @@ export class LaneA2A {
195
286
  async disable() { const a = this._acct(); const r = await a._change((s) => disableLaneIn(s, this._lane.room) || NO_CHANGE); this._dropDrafts(); return { disabled: r === true } }
196
287
 
197
288
  async _sharedDrafts() {
198
- const space = this._lane, session = space._wb._session
289
+ const space = this._lane, session = space._wb._session, generation = space._wb._archiveGeneration
199
290
  if (space._sharedRoom) throw fail('solo_verified_required', 'shared drafts belong to a solo verified Space')
200
291
  await assertAgentTarget(space)
201
292
  const doc = await space._client.state(space.room, space._mk, A2A_PENDING_DOC)
202
- if (space._wb._session !== session) throw fail('account_changed', 'the account changed while reading shared drafts')
293
+ if (space._wb._archiveGeneration !== generation || space._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed while reading shared drafts')
203
294
  if (doc?.status !== 200 || !Number.isInteger(doc.v)) throw fail('unreadable', 'shared drafts could not be read')
204
295
  return { items: pendingFromDoc(doc), version: doc.v }
205
296
  }
206
297
  /** Replies drafted on another device, including the cloud device. */
207
298
  async sharedDrafts() { return (await this._sharedDrafts()).items }
208
299
  async reviewDraft(draft, text, options = {}) {
209
- const space = this._lane, session = space._wb._session
300
+ const space = this._lane, session = space._wb._session, generation = space._wb._archiveGeneration
210
301
  const matches = (p) => p.taskId === draft?.taskId && p.at === draft.at && p.peerId === draft.peerId && p.draft === draft.draft && p.text === draft.text
211
302
  let doc = await this._sharedDrafts()
212
303
  const current = doc.items.find(matches)
213
304
  if (!current) throw fail('draft_changed', 'refresh the shared drafts before reviewing this reply')
214
305
  const result = await this.reply(current.taskId, options.reject ? '' : (text ?? current.draft), options)
215
306
  for (let attempt = 0; attempt < 5; attempt++) {
216
- if (space._wb._session !== session) throw fail('account_changed', 'the account changed during draft review')
307
+ if (space._wb._archiveGeneration !== generation || space._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed during draft review')
217
308
  if (!doc.items.some(matches)) return result
218
309
  const items = withoutShared(doc.items, current.taskId)
219
310
  const saved = await space._client.state(space.room, space._mk, A2A_PENDING_DOC, { items }, `${items.length} outside-agent replies wait for review`, 'you', doc.version)
@@ -281,7 +372,7 @@ export class LaneA2A {
281
372
  _peerPost: true, // the agent's name is not the member's (sweep 10-24 #13)
282
373
  })
283
374
  if (!sent) continue // not in the lane: left un-acked, the next collect delivers it
284
- this._posted.add(key)
375
+ this._posted.add(key); if (this._posted.size > 512) this._posted.delete(this._posted.values().next().value)
285
376
  if (!isJobPeer(peer)) this._registerDraft({ taskId: m.taskId, peer, text: m.text, at: m.at, n: it.n, cursor }) // a job agent reads no answer: nothing to draft (sweep 10-25 #5)
286
377
  }
287
378
  await a._plain('a2aack', { items: [{ taskId: it.taskId, n: it.n }] })
@@ -321,6 +412,7 @@ export class LaneA2A {
321
412
  this._offer(t)
322
413
  }
323
414
  _listen() {
415
+ if (this._lane._wb) (this._lane._wb._agentHandles ||= new Set()).add(this._lane)
324
416
  if (this._sub) return
325
417
  this._sub = (m) => this._matchDraft(m, (this._lane.messages || []).lastIndexOf(m))
326
418
  this._lane.on('message', this._sub)
@@ -329,10 +421,13 @@ export class LaneA2A {
329
421
  _flushHeld() { const h = this._held.splice(0); for (const t of h) if (this._pending.includes(t)) this._offer(t) }
330
422
  /** A task's draft: 'auto' → sent; 'ask' → an `a2a` event for the member. */
331
423
  _offer(t) {
332
- if (t.peer.reply === 'auto') {
424
+ if (this._lane._wb?.a2a?._draftsSuspended) { if (!this._held.includes(t)) this._held.push(t); return }
425
+ if (t.peer.reply === 'auto' && this.peers.some(peer => peer.id === t.peer.id && peer.reply === 'auto')) {
333
426
  if (this._sendingDrafts.has(t.taskId)) return
334
427
  this._sendingDrafts.add(t.taskId)
335
- this.reply(t.taskId, t.draft).catch(e => this._lane._emit('error', e)).finally(() => this._sendingDrafts.delete(t.taskId))
428
+ this.reply(t.taskId, t.draft, { autoPeerId: t.peer.id }).then(result => {
429
+ if (result?.held && this._pending.includes(t)) { t.peer.reply = 'ask'; this._offer(t) }
430
+ }).catch(e => this._lane._emit('error', e)).finally(() => this._sendingDrafts.delete(t.taskId))
336
431
  return
337
432
  }
338
433
  if (!((this._lane._subs && this._lane._subs.a2a) || []).length) { if (!this._held.includes(t)) this._held.push(t); return } // nobody listens yet: kept for the first
@@ -349,24 +444,48 @@ export class LaneA2A {
349
444
  * keys, per account — and makes the Sentinel calls: enable, peers, the pull (it opens each message) and the ack. This
350
445
  * page does what it does outside a vault: posts each opened message into the lane BEFORE the vault acks it, and runs the
351
446
  * draft flow (the `a2a` event, approve / askBack / decline). `conn` is the vault connection (sdkVault.js). */
447
+ function readVaultA2AView(conn, room) {
448
+ const slot = { epoch: conn.a2aEpoch, view: null }
449
+ conn.a2aViews.set(room, slot)
450
+ const discard = () => { if (conn.a2aViews.get(room) === slot) conn.a2aViews.delete(room) }
451
+ conn.roomAccount(room, 'a2a', 'view').then(r => {
452
+ if (!r || !('view' in r)) return discard()
453
+ if (conn.a2aViews.get(room) === slot) slot.view = r.view
454
+ }, discard)
455
+ }
456
+
457
+ export function refreshVaultA2AViews(conn, event) {
458
+ if (conn.lastA2AChange === event) return
459
+ conn.lastA2AChange = event
460
+ conn.a2aEpoch = (conn.a2aEpoch || 0) + 1
461
+ for (const room of conn.a2aViews?.keys() || []) readVaultA2AView(conn, room)
462
+ }
463
+
352
464
  export class VaultLaneA2A extends LaneA2A {
353
465
  constructor(lane, conn) {
354
- super(lane); this._conn = conn; this._view = null
355
- conn.roomAccount(lane.room, 'a2a', 'view').then((r) => { if (r && 'view' in r && this._view === null) this._view = r.view }, () => {}) // what the vault holds for this lane (cardUrl, peers)
466
+ super(lane)
467
+ this._conn = conn
468
+ conn.a2aViews ||= new Map()
469
+ if (!conn.a2aViews.has(lane.room) || conn.a2aViews.get(lane.room).epoch !== conn.a2aEpoch) readVaultA2AView(conn, lane.room)
470
+ }
471
+ get _view() {
472
+ const slot = this._conn.a2aViews.get(this._lane.room)
473
+ return slot?.epoch === this._conn.a2aEpoch ? slot?.view : null
356
474
  }
357
475
  async _call(m, ...a) {
476
+ const epoch = this._conn.a2aEpoch
358
477
  const r = await this._conn.roomAccount(this._lane.room, 'a2a', m, ...a)
359
- if (r && 'view' in r) this._view = r.view // { endpoint, handle, peers } | null — never a key
478
+ if (epoch === this._conn.a2aEpoch && r && 'view' in r) this._conn.a2aViews.set(this._lane.room, { epoch, view: r.view })
360
479
  return r ? r.result : r
361
480
  }
362
- get cardUrl() { const v = this._view; return v && v.handle ? cardUrlOf(v.endpoint, v.handle) : null }
363
- get mcpUrl() { const v = this._view; return v && v.handle ? mcpUrlOf(v.endpoint, v.handle) : null }
364
- get peers() { return this._view ? this._view.peers.map((p) => ({ ...p })) : [] }
481
+ get cardUrl() { const v = this._view; return v?.handle ? cardUrlOf(v.endpoint, v.handle) : null }
482
+ get mcpUrl() { const v = this._view; return v?.handle ? mcpUrlOf(v.endpoint, v.handle) : null }
483
+ get peers() { return (this._view?.peers || []).map(p => ({ ...p })) }
365
484
  async enable({ name = '', description = '' } = {}) {
366
485
  await this._call('enable', { name, description }); return { cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
367
486
  }
368
487
  // in a vault the token is shown on the VAULT's screen and never reaches this page (sync sweep 2026-11-14 #3): `token` is null, `shown` true
369
- async addPeer(name, { reply = 'ask', job = false } = {}) { const r = await this._call('addPeer', name, { reply, job: job === true }); return { id: r.id, token: r.token || null, shown: !!r.shown, cardUrl: this.cardUrl, mcpUrl: this.mcpUrl } }
488
+ async addPeer(name, { reply = 'ask', job = false, reconnect = false, previousPeerId, connectionId } = {}) { const r = await this._call('addPeer', name, { reply, job: job === true, ...(connectionId !== undefined ? { connectionId } : {}), ...(reconnect ? { reconnect: true } : {}), ...(previousPeerId ? { previousPeerId } : {}) }); const { cardUrl, mcpUrl } = this; this._acct()._dropMoved(r.moved); if (r.moved?.length) refreshVaultA2AViews(this._conn, r); return { id: r.id, token: r.token || null, shown: !!r.shown, ...(r.roomListPending ? { roomListPending: true } : {}), cardUrl, mcpUrl } }
370
489
  async setReply(peerId, reply) { return this._call('setReply', peerId, reply) }
371
490
  async removePeer(peerId) { const result = await this._call('removePeer', peerId); this._dropDrafts(peerId); return result }
372
491
  async disable() { const result = await this._call('disable'); this._dropDrafts(); return result }
@@ -387,7 +506,7 @@ export class VaultLaneA2A extends LaneA2A {
387
506
  if (!this._posted.has(key)) { // as above (sync sweep 2026-11-23 #3): acked only once it landed, posted once
388
507
  const sent = await this._sendOnce(key, msg, { from: msg.from, mode: 'always', instructions: a2aInstructions(peer), _peerPost: true })
389
508
  if (!sent) continue
390
- this._posted.add(key)
509
+ this._posted.add(key); if (this._posted.size > 512) this._posted.delete(this._posted.values().next().value)
391
510
  if (!isJobPeer(peer)) this._registerDraft({ taskId: m.taskId, peer, text: m.text, at: m.at, n, cursor }) // a job agent reads no answer: nothing to draft (sweep 10-25 #5)
392
511
  }
393
512
  await this._call('ack', { taskId, n })
@@ -395,9 +514,10 @@ export class VaultLaneA2A extends LaneA2A {
395
514
  }
396
515
  return { delivered, ...(more ? { more } : {}) }
397
516
  }
398
- async reply(taskId, text, { ask = false, reject = false } = {}) {
517
+ async reply(taskId, text, { ask = false, reject = false, autoPeerId } = {}) {
399
518
  let r
400
- try { r = await this._call('reply', String(taskId), String(text || ''), { ask: !!ask, reject: !!reject }) } catch (e) { if (!finishedTask(e)) throw e; r = { state: 'completed' } } // already answered: done (see above)
519
+ try { r = await this._call('reply', String(taskId), String(text || ''), { ask: !!ask, reject: !!reject, ...(autoPeerId ? { autoPeerId } : {}) }) } catch (e) { if (!finishedTask(e)) throw e; r = { state: 'completed' } } // already answered: done (see above)
520
+ if (r?.held) return r
401
521
  this._pending = this._pending.filter((p) => p.taskId !== taskId)
402
522
  return { state: r && r.state }
403
523
  }
package/sdkAccount.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { preferredAssociation, reconcileAccountLanes } from './laneAssociation.js'
1
2
  // spaces/public/sdkAccount.js — `wb.account`: the account's LIVE index for a builder's app (2026-10-03; the owner, on what
2
3
  // the SDK lacked next to the Spaces app: "And what about the index room etc." → "Yes"). wb.backup puts the room list in
3
4
  // the vault for a RESTORE on a new device; this keeps two LIVE devices in step, the way the app's own index room does:
@@ -68,7 +69,14 @@ export function mergeIndex(a, b, maxRooms = 500) {
68
69
  for (const r of [...(a.rooms || []), ...(b.rooms || [])]) {
69
70
  if (!r || !r.room) continue
70
71
  const prev = rooms.get(r.room)
71
- const newer = !prev || num(r.at) > num(prev.at) ? r : prev
72
+ const latest = !prev || num(r.at) > num(prev.at) ? r : prev
73
+ const assoc = preferredAssociation(prev, r)
74
+ const newer = { ...latest, kind: assoc.kind, ...(assoc.associationAt ? { associationAt: assoc.associationAt } : {}) }
75
+ if (assoc.mintedFor || prev?.mintedFor || r.mintedFor) newer.mintedFor = assoc.mintedFor || prev?.mintedFor || r.mintedFor
76
+ if (assoc.laneOrigin === 'minted' && !assoc.detachedLane) newer.laneOrigin = 'minted'
77
+ else delete newer.laneOrigin
78
+ if (assoc.detachedLane) { newer.detachedLane = true; delete newer.shared }
79
+ else { delete newer.detachedLane; if (assoc.shared) newer.shared = assoc.shared; else delete newer.shared }
72
80
  const pin = !prev || num(r.pinnedAt) > num(prev.pinnedAt) ? r : prev
73
81
  rooms.set(r.room, pin.pinnedAt || pin.pinned ? { ...newer, pinned: !!pin.pinned, pinnedAt: num(pin.pinnedAt) } : newer)
74
82
  }
@@ -90,7 +98,7 @@ export function mergeIndex(a, b, maxRooms = 500) {
90
98
  }
91
99
  const keepDevices = Object.entries(devices).sort((x, y) => num(y[1].seenAt) - num(x[1].seenAt)).slice(0, MAX_DEVICES)
92
100
  return {
93
- rooms: [...rooms.values()].sort((x, y) => num(x.at) - num(y.at)).slice(-maxRooms),
101
+ rooms: reconcileAccountLanes([...rooms.values()]).sort((x, y) => num(x.at) - num(y.at)).slice(-maxRooms),
94
102
  tomb: [...tomb.entries()].map(([room, at]) => ({ room, at })).sort((x, y) => x.at - y.at).slice(-MAX_TOMBS),
95
103
  devices: Object.fromEntries(keepDevices),
96
104
  links: [...links.values()].sort((x, y) => num(x.at) - num(y.at)).slice(-200),
@@ -183,7 +191,12 @@ export class AccountIndex {
183
191
  rename(room, label) { return this._edit(room, (r) => ({ ...r, label: String(label || '').slice(0, 120), renamed: true })) }
184
192
  /** Drop a room from the account on EVERY device — the room itself is not deleted (that is wb.rooms.delete, for a
185
193
  * tenant). Opening its link again later brings it back. */
186
- forget(room) { this._backup.remove(room); return this }
194
+ forget(room) {
195
+ for (const child of this._backup.rooms || []) if (child.shared === room) this._backup._detachLane(child.room, room)
196
+ this._backup.remove(room)
197
+ this._pruneAgents?.()
198
+ return this
199
+ }
187
200
  async repairNames() { return this._repairNames(this._readName) }
188
201
  async _repairNames(read) {
189
202
  const state = this._backup._s
@@ -295,7 +308,7 @@ export class AccountIndex {
295
308
  if (!this._again) this._again = this._running.catch(() => null).then(() => { this._again = null; return this.enabled ? this.sync() : { ok: false, rooms: this.rooms, devices: this.devices } })
296
309
  return this._again
297
310
  }
298
- this._running = this._sync().finally(() => { this._running = null; this._syncSettled?.() })
311
+ this._running = this._sync().finally(() => { this._running = null; this._syncSettled?.(); this._pruneAgents?.() })
299
312
  return this._running
300
313
  }
301
314
 
package/sdkAccountDoc.js CHANGED
@@ -8,6 +8,7 @@
8
8
  // hold, a split room's ASSEMBLED key (decision 5). A forgotten room is `forgot: <at>` — the SDK's RE-OPENABLE mark — never the
9
9
  // app's final `deleted` (decision 4). Devices: { name, seenAt, out } ↔ { label, lastSeenAt } + `signouts`; `sdk` (the release a
10
10
  // device runs) rides along. Entries the SDK cannot read (no link, no mark) are carried over as they were.
11
+ import { preferredAssociation } from './laneAssociation.js'
11
12
  import { indexDoc, indexRoomEntry } from './accountIndexDoc.js'
12
13
  import { keyInLink, roomPin } from './accountRecord.js'
13
14
  import { normUsageKey } from './usageReceipts.js'
@@ -25,7 +26,14 @@ export function toAppIndex ({ rooms = [], tomb = [], links = [], devices = {}, u
25
26
  if (!r || !r.room || typeof r.link !== 'string' || !r.link) continue
26
27
  const mk = keyInLink(r.link) || (typeof r.mk === 'string' ? r.mk : '')
27
28
  const at = num(r.at), e = indexRoomEntry({ room: r.room, title: r.label || '', titleAt: at, ...roomPin(r), renamed: typeof r.renamed === 'boolean' ? r.renamed : !!(r.label && r.label !== 'Space' && r.label !== r.room), at, archived: !!r.archived, archivedAt: at }, obj(p.rooms)[r.room] || undefined, mk ? { mk } : {}) // prev: the app's per-field rules, and the "always on" mark it keeps (sync sweep 2026-11-23 #13 — every SDK write dropped it)
28
- map[r.room] = { ...e, link: r.link, kind: r.kind === 'lane' ? 'lane' : 'space', ...(r.kind === 'lane' && r.shared ? { shared: r.shared } : {}), ...(r.label && e.title !== r.label ? { label: r.label } : {}) }
29
+ const association = preferredAssociation(r, obj(p.rooms)[r.room])
30
+ const detached = !!association.detachedLane
31
+ map[r.room] = { ...e, ...(num(association.associationAt) ? { associationAt: association.associationAt } : {}), ...(detached ? { detachedLane: true } : {}), link: r.link, kind: !detached && association.kind === 'lane' ? 'lane' : 'space', ...(association.kind === 'lane' && association.shared ? { shared: association.shared } : {}), ...(r.label && e.title !== r.label ? { label: r.label } : {}) }
32
+ if (association.mintedFor || r.mintedFor || e.mintedFor) map[r.room].mintedFor = association.mintedFor || r.mintedFor || e.mintedFor
33
+ if (association.laneOrigin === 'minted' && !detached) map[r.room].laneOrigin = 'minted'
34
+ else delete map[r.room].laneOrigin
35
+ if (detached) delete map[r.room].shared
36
+ else delete map[r.room].detachedLane
29
37
  }
30
38
  for (const t of tomb) if (t && t.room) map[t.room] = { ...(map[t.room] || {}), forgot: Math.max(num(t.at), num((map[t.room] || {}).forgot)) || 1 }
31
39
  for (const [room, e] of Object.entries(obj(p.rooms))) if (!(room in map) && e && typeof e === 'object' && !e.link && !e.forgot) map[room] = e
@@ -62,8 +70,8 @@ export function fromAppIndex (doc) {
62
70
  if (deletedAt) tomb.push({ room, at: deletedAt })
63
71
  if (typeof e.link !== 'string' || !e.link || e.deleted) continue
64
72
  const label = e.label !== undefined ? e.label : (e.title && e.title !== 'Space' && e.title !== room || e.manual ? e.title : undefined)
65
- rooms.push({ room, ...roomPin(e), ...(num(e.at) ? { at: e.at } : {}), ...(e.archived ? { archived: true } : {}), link: e.link, kind: e.kind === 'lane' ? 'lane' : 'space',
66
- ...(label ? { label } : {}), ...(label && !e.manual ? { renamed: false } : e.manual && (label === 'Space' || label === room) ? { renamed: true } : {}), ...(e.kind === 'lane' && e.shared ? { shared: e.shared } : {}), ...(typeof e.mk === 'string' && e.mk && e.mk !== keyInLink(e.link) ? { mk: e.mk } : {}) })
73
+ rooms.push({ room, ...roomPin(e), ...(e.mintedFor ? { mintedFor: e.mintedFor } : {}), ...(e.laneOrigin === 'minted' && !e.detachedLane ? { laneOrigin: 'minted' } : {}), ...(num(e.associationAt) ? { associationAt: e.associationAt } : {}), ...(e.detachedLane ? { detachedLane: true } : {}), ...(num(e.at) ? { at: e.at } : {}), ...(e.archived ? { archived: true } : {}), link: e.link, kind: !e.detachedLane && e.kind === 'lane' ? 'lane' : 'space',
74
+ ...(label ? { label } : {}), ...(label && !e.manual ? { renamed: false } : e.manual && (label === 'Space' || label === room) ? { renamed: true } : {}), ...(!e.detachedLane && e.kind === 'lane' && e.shared ? { shared: e.shared } : {}), ...(typeof e.mk === 'string' && e.mk && e.mk !== keyInLink(e.link) ? { mk: e.mk } : {}) })
67
75
  }
68
76
  // …and the app's ERASED mark is the SDK's reason (#8): an SDK device whose stamp is no newer than the mark was signed out by Delete my
69
77
  // account in the app — its onSignedOut hears { reason: 'erased' }, as when the SDK deleted it