@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.
Files changed (112) hide show
  1. package/README.md +2 -2
  2. package/a2aCore.js +41 -5
  3. package/accountErase.js +15 -4
  4. package/accountIndexDoc.js +24 -7
  5. package/accountRecord.js +6 -2
  6. package/accountStores.js +21 -5
  7. package/acctV2App.js +111 -12
  8. package/acctV2Client.js +11 -1
  9. package/acctV2UiCore.js +27 -7
  10. package/agentDoorTools.js +28 -0
  11. package/awsKey.js +3 -1
  12. package/backupRecord.js +3 -0
  13. package/chatLock.js +16 -0
  14. package/cloudDevicePins.js +2 -2
  15. package/codeAttachments.js +101 -0
  16. package/codeCache.js +173 -0
  17. package/codeCloud.js +2 -2
  18. package/codeComputers.js +9 -0
  19. package/codeFolders.js +116 -0
  20. package/codeHistory.js +76 -0
  21. package/codeLanguage.js +54 -0
  22. package/codeModes.js +2 -0
  23. package/codeProgress.js +54 -0
  24. package/codeSent.js +109 -0
  25. package/codeSubagents.js +107 -0
  26. package/codeTransport.js +46 -5
  27. package/connections.js +37 -20
  28. package/decrypt.html +69 -9
  29. package/deviceAttest.js +9 -3
  30. package/eraseFile.js +15 -0
  31. package/idb.js +19 -3
  32. package/idbSeal.js +5 -2
  33. package/inviteReceive.js +44 -0
  34. package/inviteSend.js +8 -2
  35. package/jobAgents.js +2 -2
  36. package/keptMerge.js +9 -2
  37. package/l1-worker-src.js +1 -1
  38. package/l1-worker.js +122 -43
  39. package/laneAssociation.js +78 -0
  40. package/laneConfig.js +4 -3
  41. package/laneLinkCore.js +9 -0
  42. package/ledgerView.js +30 -4
  43. package/manifest.json +112 -87
  44. package/memberChange.js +4 -2
  45. package/mirrorBatch.js +47 -0
  46. package/offlineBundle.js +21 -0
  47. package/opRouting.js +10 -0
  48. package/package.json +27 -2
  49. package/pdfOptions.js +13 -0
  50. package/pdfText.js +107 -0
  51. package/pdfjs.mjs +28 -0
  52. package/pdfjs.worker.mjs +28 -0
  53. package/protectedLocal.js +52 -13
  54. package/reactionHolders.js +86 -0
  55. package/removedMessage.js +1 -1
  56. package/roomEmbed.js +111 -0
  57. package/roomIntake.js +324 -0
  58. package/roomName.js +1 -1
  59. package/roomRoster.js +30 -7
  60. package/rosterCount.js +6 -3
  61. package/scheduleNext.js +60 -0
  62. package/sdkA2A.js +200 -42
  63. package/sdkAccount.js +88 -18
  64. package/sdkAccountDoc.js +13 -5
  65. package/sdkAccountSections.js +172 -23
  66. package/sdkAgui.js +33 -6
  67. package/sdkBackup.js +53 -11
  68. package/sdkBackupV2.js +15 -3
  69. package/sdkCloudDevice.js +20 -5
  70. package/sdkComputers.js +695 -65
  71. package/sdkDictation.js +115 -25
  72. package/sdkErase.js +12 -5
  73. package/sdkExports.js +19 -8
  74. package/sdkInvitations.js +4 -2
  75. package/sdkKeptAgent.js +19 -3
  76. package/sdkKeptIntake.js +100 -0
  77. package/sdkLaneLink.js +8 -9
  78. package/sdkPlan.js +4 -2
  79. package/sdkRekey.js +122 -22
  80. package/sdkReport.js +1 -1
  81. package/sdkSafeMedia.js +1 -1
  82. package/sdkSchedules.js +8 -1
  83. package/sdkSpeech.js +32 -2
  84. package/sdkTemporaryRooms.js +124 -0
  85. package/sdkTurn.js +12 -4
  86. package/sdkVault.js +66 -10
  87. package/sentinelRelease.js +1 -0
  88. package/sharedViews.js +34 -4
  89. package/siri.js +140 -9
  90. package/spaceClient.js +112 -17
  91. package/spaceEmailGate.js +2 -2
  92. package/spaceExport.js +50 -5
  93. package/spaceFork.js +15 -7
  94. package/spaceTemplates.js +99 -0
  95. package/speechOut.js +21 -5
  96. package/store.js +134 -27
  97. package/sw-notif-core.js +11 -8
  98. package/tapTrail.js +58 -0
  99. package/turnVerdict.js +1 -0
  100. package/usageReceipts.js +12 -5
  101. package/vault-core.js +568 -126
  102. package/vault-kit.mjs +3 -3
  103. package/vault-screens.js +30 -18
  104. package/vaultAtRest.js +38 -6
  105. package/vaultCoreLock.js +3 -1
  106. package/vaultCorePush.js +58 -7
  107. package/vaultKeep.js +9 -3
  108. package/vaultWorkerHost.js +32 -7
  109. package/witbitz-admin.d.ts +3 -0
  110. package/witbitz-admin.mjs +12 -11
  111. package/witbitz-sdk.d.ts +170 -43
  112. package/witbitz-sdk.js +833 -203
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, replyNotDelivered, A2A_ENDPOINT, a2aTokenHash, cardUrlOf, mcpUrlOf, normA2A, mergeA2ARecords, peersOf, applyRemovals, removalIntents, pruneGoneIn, enableLaneIn, addPeerIn, setPeerReplyIn, removePeerIn, disableLaneIn, clearLanesIn, recordFor, withIntake, 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,99 @@ 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), ...(reply && typeof reply.state === 'string' ? { taskState: reply.state } : {}) }) })
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
- /** 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) {
132
+ // ⛔ A COPY THAT MISSES WHAT ANOTHER DEVICE ADDED IS NOT PUBLISHED (side sweep: outside-agent-stale-list-drops-pending-jobs): the
133
+ // grant REPLACES the Sentinel's record, and the Sentinel drops the waiting tasks of every agent it leaves out. A lane or an
134
+ // agent the Sentinel holds must be in this record, or closed / removed here (its tombstone, `gone` / `removed`); otherwise
135
+ // this device's copy is older than the account's — refused, nothing sent. A status that cannot be read refuses too.
136
+ async _assertCovers(candidate) {
137
+ const st = await this._plain('a2astatus')
138
+ for (const l of (st && Array.isArray(st.lanes) ? st.lanes : [])) {
139
+ if (!l || typeof l.handle !== 'string' || candidate.gone?.[l.handle]) continue
140
+ const mine = Object.values(candidate.lanes || {}).find((x) => x && x.handle === l.handle)
141
+ const missing = !mine || (Array.isArray(l.peers) ? l.peers : []).some((p) => p && p.id && !mine.peers.some((q) => q.id === p.id) && !mine.removed?.[p.id])
142
+ if (missing) throw fail('stale_record', 'another device changed this account’s outside agents — sync the account (or restore its latest wb.a2a.state) and try again')
143
+ }
144
+ }
145
+ /** Send the whole record (it REPLACES what the Sentinel held) — this account's, or `s`, a changed copy (_change). `intakeOf`
146
+ * (sdkKeptIntake.js): (record) → { room, pub, drops } — the record then names the account's message intake and those peers'
147
+ * drop addresses (a2aCore.withIntake), as the app's push does; without it the Sentinel keeps the intake it holds. */
148
+ async _push(s = this._s, expectedGeneration = this._wb._archiveGeneration, intakeOf = null) {
71
149
  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 })
150
+ if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
151
+ const candidate = this._removals.length ? structuredClone(s) : s
152
+ if (this._removals.length) applyRemovals(candidate, this._removals)
153
+ await this._assertCovers(candidate)
154
+ if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
155
+ const intake = intakeOf ? await intakeOf(candidate) : null
156
+ if (this._wb._archiveGeneration !== expectedGeneration) throw fail('account_changed', 'the account changed while sharing its agent record')
157
+ const rec = recordFor(candidate, account)
158
+ const r = await this._sealed('a2agrant', intake && intake.room && intake.pub ? withIntake(rec, intake) : { ...rec, preserveIntake: true })
74
159
  if (s === this._s) this._changed()
75
160
  return r
76
161
  }
@@ -81,15 +166,25 @@ export class A2AAccount {
81
166
  // One change at a time (each starts from the last one's result: two at once lost one). A restore() that landed while the
82
167
  // push was out (a vault applying the account's kept copy) is merged with the change, not overwritten (a2aCore.js rules).
83
168
  // `fn` returns NO_CHANGE when there is nothing to do (nothing pushed).
84
- _change(fn) {
169
+ _change(fn, { intake = null } = {}) {
170
+ const generation = this._wb._archiveGeneration, email = this._wb._session?.email
171
+ const changed = () => generation !== this._wb._archiveGeneration || email !== this._wb._session?.email
85
172
  const run = async () => {
86
- const session = this._wb._session
173
+ if (changed()) throw fail('account_changed', 'the account changed before the agent update')
87
174
  const base = this._s, next = JSON.parse(JSON.stringify(base))
175
+ const previous = this._removals.slice()
88
176
  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')
177
+ if (out === NO_CHANGE && !previous.length) return out
178
+ applyRemovals(next, previous)
179
+ const existing = new Set(previous.map(x => JSON.stringify(x)))
180
+ const added = this._stageInbox ? [] : removalIntents(base, next).filter(x => !existing.has(JSON.stringify(x)))
181
+ if (changed()) throw fail('account_changed', 'the account changed during the agent update')
182
+ if (added.length) { this._removals.push(...added); this._changed() }
183
+ const finish = await this._stageInbox?.(next)
184
+ try { await this._push(next, generation, intake) } catch (e) { if (!changed() && (e.definiteRefusal || (e.status >= 400 && e.status < 500))) { finish?.(false); if (added.length) { this._removals = previous; this._changed() } } throw e }
185
+ if (changed()) throw fail('account_changed', 'the account changed during the agent update')
186
+ finish?.(true)
187
+ this._removals = []
93
188
  this._s = this._s === base ? a2aStateOf(next) : mergeA2ARecords(next, this._s)
94
189
  this._changed()
95
190
  return out
@@ -98,11 +193,25 @@ export class A2AAccount {
98
193
  this._q = p.catch(() => {})
99
194
  return p
100
195
  }
196
+ /** Send the record again, naming the account's message intake (`intakeOf`, see _push) — a kept assistant's peer then gets its
197
+ * jobs delivered to the cloud device (sdkKeptIntake.js). In the edit queue like every change; the record itself is unchanged. */
198
+ _pushIntake(intakeOf) { return this._change(() => true, { intake: intakeOf }) }
101
199
  /** What the Sentinel holds for this account (lanes, peers by name, open tasks). */
102
200
  status() { return this._plain('a2astatus') }
103
201
  /** Turn A2A off everywhere for this account: every lane's card and every token stop working. Each inbox is marked switched
104
202
  * 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 }
203
+ // in the edit queue, after any edit already on its way (side sweep 2026-11-28: an earlier addPeer could reach the Sentinel after the
204
+ // revocation and switch pairings back on) — as the Siri revoke is
205
+ revoke() {
206
+ const generation = this._wb._archiveGeneration
207
+ const run = async () => {
208
+ if (this._wb._archiveGeneration !== generation) throw fail('account_changed', 'the account changed before revocation')
209
+ 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
210
+ }
211
+ const p = (this._q || Promise.resolve()).then(run, run)
212
+ this._q = p.catch(() => {})
213
+ return p
214
+ }
106
215
  }
107
216
  const deliveryKey = (taskId, n, at) => JSON.stringify([taskId, Number(n) || 1, Number(at) || 0])
108
217
  const NO_CHANGE = Symbol('no change')
@@ -115,7 +224,7 @@ export class LaneA2A {
115
224
  // 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
225
  // for ever (sync sweep 10-24 #17). Resumed: watched again, and a draft that already came is offered again.
117
226
  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)
227
+ 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
228
  this._ambiguous = new Map()
120
229
  this._sendingDrafts = new Set()
121
230
  this._seenDrafts = new WeakSet()
@@ -146,16 +255,32 @@ export class LaneA2A {
146
255
  * assistant answers it on its own). `job: true`: an agent that TAKES JOBS — it reports and its run ends, reading no reply,
147
256
  * 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
257
  * token is shown ONCE; only its hash is kept. */
149
- async addPeer(name, { reply = 'ask', job = false } = {}) {
258
+ async addPeer(name, { reply = 'ask', job = false, reconnect = false, previousPeerId, connectionId } = {}) {
150
259
  if (reply === 'auto') await assertNotKept(this._lane)
151
260
  await assertAgentTarget(this._lane)
152
261
  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)))
262
+ const moved = [], room = this._lane.room
263
+ const { id, token } = await a._change(async s => {
264
+ if (previousPeerId && !s.lanes[room]?.peers.some(peer => peer.id === previousPeerId)) throw fail('not_found', 'The previous peer is not on this lane.')
265
+ if (reconnect || previousPeerId) {
266
+ for (const [source, lane] of Object.entries(s.lanes)) for (const peer of [...lane.peers]) {
267
+ if ((reconnect && peer.name === String(name).trim()) || (source === room && previousPeerId && peer.id === previousPeerId)) { removePeerIn(s, source, peer.id); moved.push({ source, id: peer.id }) }
268
+ }
269
+ if (!s.lanes[room]) await enableLaneIn(s, room, { name: 'Private assistant' })
270
+ }
271
+ 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))
272
+ })
273
+ a._dropMoved(moved)
274
+ for (const previous of moved) {
275
+ const old = previous.source === room ? this._lane : [...(this._lane._wb._agentHandles || []), ...(this._lane._wb._archiveHandles || [])].find(sp => sp.room === previous.source)
276
+ if (old?._a2a) { old._a2a._dropDrafts(previous.id); await old._a2a._syncRoomPeer(previous.id).catch(() => {}) }
277
+ }
154
278
  try { await this._syncRoomPeer(id) } catch (error) {
279
+ if (reconnect || previousPeerId) return { id, token, ...(moved.length ? { moved } : {}), cardUrl: this.cardUrl, mcpUrl: this.mcpUrl, roomListPending: true }
155
280
  await a._change((s) => removePeerIn(s, this._lane.room, id) || NO_CHANGE)
156
281
  throw error
157
282
  }
158
- return { id, token, cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
283
+ return { id, token, ...(moved.length ? { moved } : {}), cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
159
284
  }
160
285
  /** Change whether this peer's answers wait for you ('ask') or go on their own ('auto'). */
161
286
  async setReply(peerId, reply) {
@@ -176,11 +301,11 @@ export class LaneA2A {
176
301
  async _syncRoomPeer(id) {
177
302
  const sp = this._lane
178
303
  if (sp._sharedRoom) return
179
- const session = sp._wb._session
304
+ const session = sp._wb._session, generation = sp._wb._archiveGeneration
180
305
  await assertAgentTarget(sp)
181
306
  for (let i = 0; i < 5; i++) {
182
307
  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')
308
+ if (sp._wb._archiveGeneration !== generation || sp._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed while saving the peer')
184
309
  if (!doc || doc.status !== 200) throw fail('unreadable', 'the room peer list could not be read')
185
310
  const peers = peersFromDoc(doc).filter((p) => p.id !== id)
186
311
  const peer = this.peers.find((p) => p.id === id)
@@ -195,25 +320,25 @@ export class LaneA2A {
195
320
  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
321
 
197
322
  async _sharedDrafts() {
198
- const space = this._lane, session = space._wb._session
323
+ const space = this._lane, session = space._wb._session, generation = space._wb._archiveGeneration
199
324
  if (space._sharedRoom) throw fail('solo_verified_required', 'shared drafts belong to a solo verified Space')
200
325
  await assertAgentTarget(space)
201
326
  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')
327
+ if (space._wb._archiveGeneration !== generation || space._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed while reading shared drafts')
203
328
  if (doc?.status !== 200 || !Number.isInteger(doc.v)) throw fail('unreadable', 'shared drafts could not be read')
204
329
  return { items: pendingFromDoc(doc), version: doc.v }
205
330
  }
206
331
  /** Replies drafted on another device, including the cloud device. */
207
332
  async sharedDrafts() { return (await this._sharedDrafts()).items }
208
333
  async reviewDraft(draft, text, options = {}) {
209
- const space = this._lane, session = space._wb._session
334
+ const space = this._lane, session = space._wb._session, generation = space._wb._archiveGeneration
210
335
  const matches = (p) => p.taskId === draft?.taskId && p.at === draft.at && p.peerId === draft.peerId && p.draft === draft.draft && p.text === draft.text
211
336
  let doc = await this._sharedDrafts()
212
337
  const current = doc.items.find(matches)
213
338
  if (!current) throw fail('draft_changed', 'refresh the shared drafts before reviewing this reply')
214
339
  const result = await this.reply(current.taskId, options.reject ? '' : (text ?? current.draft), options)
215
340
  for (let attempt = 0; attempt < 5; attempt++) {
216
- if (space._wb._session !== session) throw fail('account_changed', 'the account changed during draft review')
341
+ if (space._wb._archiveGeneration !== generation || space._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed during draft review')
217
342
  if (!doc.items.some(matches)) return result
218
343
  const items = withoutShared(doc.items, current.taskId)
219
344
  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 +406,7 @@ export class LaneA2A {
281
406
  _peerPost: true, // the agent's name is not the member's (sweep 10-24 #13)
282
407
  })
283
408
  if (!sent) continue // not in the lane: left un-acked, the next collect delivers it
284
- this._posted.add(key)
409
+ this._posted.add(key); if (this._posted.size > 512) this._posted.delete(this._posted.values().next().value)
285
410
  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
411
  }
287
412
  await a._plain('a2aack', { items: [{ taskId: it.taskId, n: it.n }] })
@@ -297,6 +422,10 @@ export class LaneA2A {
297
422
  // a task already answered (a resumed 'auto' task taken mid-send was re-sent on every resume, an error each time —
298
423
  // sync sweep backlog): it is done, not failed — dropped, never offered again
299
424
  if (!finishedTask(e)) throw e
425
+ if (replyNotDelivered(e, { reject })) { // the requester ended it: the reply never reached them — said so, not "sent" (side sweep 2026-11-28)
426
+ this._pending = this._pending.filter((p) => p.taskId !== taskId)
427
+ throw fail('task_ended', String(e.taskState).toUpperCase() === 'CANCELED' ? 'the peer canceled this task: the reply was not sent' : 'the task has already ended: this reply was not sent', { taskState: e.taskState })
428
+ }
300
429
  r = { state: 'completed' }
301
430
  }
302
431
  this._pending = this._pending.filter((p) => p.taskId !== taskId)
@@ -321,6 +450,7 @@ export class LaneA2A {
321
450
  this._offer(t)
322
451
  }
323
452
  _listen() {
453
+ if (this._lane._wb) (this._lane._wb._agentHandles ||= new Set()).add(this._lane)
324
454
  if (this._sub) return
325
455
  this._sub = (m) => this._matchDraft(m, (this._lane.messages || []).lastIndexOf(m))
326
456
  this._lane.on('message', this._sub)
@@ -329,10 +459,13 @@ export class LaneA2A {
329
459
  _flushHeld() { const h = this._held.splice(0); for (const t of h) if (this._pending.includes(t)) this._offer(t) }
330
460
  /** A task's draft: 'auto' → sent; 'ask' → an `a2a` event for the member. */
331
461
  _offer(t) {
332
- if (t.peer.reply === 'auto') {
462
+ if (this._lane._wb?.a2a?._draftsSuspended) { if (!this._held.includes(t)) this._held.push(t); return }
463
+ if (t.peer.reply === 'auto' && this.peers.some(peer => peer.id === t.peer.id && peer.reply === 'auto')) {
333
464
  if (this._sendingDrafts.has(t.taskId)) return
334
465
  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))
466
+ this.reply(t.taskId, t.draft, { autoPeerId: t.peer.id }).then(result => {
467
+ if (result?.held && this._pending.includes(t)) { t.peer.reply = 'ask'; this._offer(t) }
468
+ }).catch(e => this._lane._emit('error', e)).finally(() => this._sendingDrafts.delete(t.taskId))
336
469
  return
337
470
  }
338
471
  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 +482,48 @@ export class LaneA2A {
349
482
  * keys, per account — and makes the Sentinel calls: enable, peers, the pull (it opens each message) and the ack. This
350
483
  * page does what it does outside a vault: posts each opened message into the lane BEFORE the vault acks it, and runs the
351
484
  * draft flow (the `a2a` event, approve / askBack / decline). `conn` is the vault connection (sdkVault.js). */
485
+ function readVaultA2AView(conn, room) {
486
+ const slot = { epoch: conn.a2aEpoch, view: null }
487
+ conn.a2aViews.set(room, slot)
488
+ const discard = () => { if (conn.a2aViews.get(room) === slot) conn.a2aViews.delete(room) }
489
+ conn.roomAccount(room, 'a2a', 'view').then(r => {
490
+ if (!r || !('view' in r)) return discard()
491
+ if (conn.a2aViews.get(room) === slot) slot.view = r.view
492
+ }, discard)
493
+ }
494
+
495
+ export function refreshVaultA2AViews(conn, event) {
496
+ if (conn.lastA2AChange === event) return
497
+ conn.lastA2AChange = event
498
+ conn.a2aEpoch = (conn.a2aEpoch || 0) + 1
499
+ for (const room of conn.a2aViews?.keys() || []) readVaultA2AView(conn, room)
500
+ }
501
+
352
502
  export class VaultLaneA2A extends LaneA2A {
353
503
  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)
504
+ super(lane)
505
+ this._conn = conn
506
+ conn.a2aViews ||= new Map()
507
+ if (!conn.a2aViews.has(lane.room) || conn.a2aViews.get(lane.room).epoch !== conn.a2aEpoch) readVaultA2AView(conn, lane.room)
508
+ }
509
+ get _view() {
510
+ const slot = this._conn.a2aViews.get(this._lane.room)
511
+ return slot?.epoch === this._conn.a2aEpoch ? slot?.view : null
356
512
  }
357
513
  async _call(m, ...a) {
514
+ const epoch = this._conn.a2aEpoch
358
515
  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
516
+ if (epoch === this._conn.a2aEpoch && r && 'view' in r) this._conn.a2aViews.set(this._lane.room, { epoch, view: r.view })
360
517
  return r ? r.result : r
361
518
  }
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 })) : [] }
519
+ get cardUrl() { const v = this._view; return v?.handle ? cardUrlOf(v.endpoint, v.handle) : null }
520
+ get mcpUrl() { const v = this._view; return v?.handle ? mcpUrlOf(v.endpoint, v.handle) : null }
521
+ get peers() { return (this._view?.peers || []).map(p => ({ ...p })) }
365
522
  async enable({ name = '', description = '' } = {}) {
366
523
  await this._call('enable', { name, description }); return { cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
367
524
  }
368
525
  // 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 } }
526
+ 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
527
  async setReply(peerId, reply) { return this._call('setReply', peerId, reply) }
371
528
  async removePeer(peerId) { const result = await this._call('removePeer', peerId); this._dropDrafts(peerId); return result }
372
529
  async disable() { const result = await this._call('disable'); this._dropDrafts(); return result }
@@ -387,7 +544,7 @@ export class VaultLaneA2A extends LaneA2A {
387
544
  if (!this._posted.has(key)) { // as above (sync sweep 2026-11-23 #3): acked only once it landed, posted once
388
545
  const sent = await this._sendOnce(key, msg, { from: msg.from, mode: 'always', instructions: a2aInstructions(peer), _peerPost: true })
389
546
  if (!sent) continue
390
- this._posted.add(key)
547
+ this._posted.add(key); if (this._posted.size > 512) this._posted.delete(this._posted.values().next().value)
391
548
  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
549
  }
393
550
  await this._call('ack', { taskId, n })
@@ -395,9 +552,10 @@ export class VaultLaneA2A extends LaneA2A {
395
552
  }
396
553
  return { delivered, ...(more ? { more } : {}) }
397
554
  }
398
- async reply(taskId, text, { ask = false, reject = false } = {}) {
555
+ async reply(taskId, text, { ask = false, reject = false, autoPeerId } = {}) {
399
556
  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)
557
+ 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)
558
+ if (r?.held) return r
401
559
  this._pending = this._pending.filter((p) => p.taskId !== taskId)
402
560
  return { state: r && r.state }
403
561
  }