@witbitz/sdk 0.0.0-stage → 4.3.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 (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +200 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +223 -0
  6. package/accountIndexDoc.js +122 -0
  7. package/accountOwner.js +59 -0
  8. package/accountRecord.js +90 -0
  9. package/accountScope.js +114 -0
  10. package/accountSeal.js +42 -0
  11. package/accountStores.js +173 -0
  12. package/acctV2App.js +619 -0
  13. package/acctV2Check.js +29 -0
  14. package/acctV2Client.js +382 -0
  15. package/acctV2Keys.js +43 -0
  16. package/acctV2Legacy.js +14 -0
  17. package/acctV2Switch.js +80 -0
  18. package/acctV2UiCore.js +857 -0
  19. package/acctV2WebAuthn.js +61 -0
  20. package/acctV2Wire.js +59 -0
  21. package/address.js +42 -0
  22. package/attestedBox.js +30 -0
  23. package/attestedRooms.js +78 -0
  24. package/awsKey.js +98 -0
  25. package/backupRecord.js +106 -0
  26. package/backupVault.js +97 -0
  27. package/blocks.js +115 -0
  28. package/blocksPush.js +64 -0
  29. package/browseSeal.js +103 -0
  30. package/cbor.js +225 -0
  31. package/changePush.js +75 -0
  32. package/chatLock.js +149 -0
  33. package/chatLockSw.js +13 -0
  34. package/cloudDeviceBuilds.js +11 -0
  35. package/cloudDevicePins.js +33 -0
  36. package/cloudDeviceSeal.js +53 -0
  37. package/codeBrowse.js +224 -0
  38. package/codeCloud.js +652 -0
  39. package/codeCloudKeys.js +112 -0
  40. package/codeCommands.js +167 -0
  41. package/codeComputers.js +388 -0
  42. package/codeEgress.js +123 -0
  43. package/codeFilesRoutes.js +17 -0
  44. package/codeMkdir.js +8 -0
  45. package/codeModes.js +57 -0
  46. package/codeOrphanKeys.js +42 -0
  47. package/codeOutputs.js +141 -0
  48. package/codeRelay.js +505 -0
  49. package/codeSentinel.js +86 -0
  50. package/codeTransport.js +295 -0
  51. package/codeUndo.js +48 -0
  52. package/compress.js +24 -0
  53. package/config.js +11 -0
  54. package/connCatalog.js +164 -0
  55. package/connDisp.js +76 -0
  56. package/connOtherWays.js +74 -0
  57. package/connPending.js +16 -0
  58. package/connWrap.js +53 -0
  59. package/connectionEntry.js +89 -0
  60. package/connections.js +562 -0
  61. package/credits.js +30 -0
  62. package/csAttest.js +112 -0
  63. package/decrypt.html +384 -0
  64. package/deviceAttest.js +521 -0
  65. package/deviceCall.js +54 -0
  66. package/deviceKeyCore.js +41 -0
  67. package/deviceSeal.js +59 -0
  68. package/e2ee.js +323 -0
  69. package/eat.js +103 -0
  70. package/emailFork.js +275 -0
  71. package/emailSignIn.js +81 -0
  72. package/emptySpaces.js +111 -0
  73. package/encSource.js +55 -0
  74. package/enclaveAccept.js +214 -0
  75. package/enclaveClaim.js +241 -0
  76. package/enclaveRoute.js +102 -0
  77. package/enclaveSnapshotMerge.js +44 -0
  78. package/entrySig.js +165 -0
  79. package/env.js +73 -0
  80. package/eraseFile.js +58 -0
  81. package/followImage.js +86 -0
  82. package/healNames.js +45 -0
  83. package/idb.js +97 -0
  84. package/idbSeal.js +119 -0
  85. package/indexGone.js +12 -0
  86. package/invite.js +51 -0
  87. package/inviteEnroll.js +67 -0
  88. package/inviteSend.js +68 -0
  89. package/jobAgents.js +87 -0
  90. package/keptMerge.js +84 -0
  91. package/l1-worker-src.js +2 -0
  92. package/l1-worker.js +831 -0
  93. package/laneConfig.js +57 -0
  94. package/laneLinkCore.js +177 -0
  95. package/ledgerView.js +64 -0
  96. package/manifest.json +220 -0
  97. package/mcpRecommended.js +25 -0
  98. package/memberChange.js +123 -0
  99. package/mkseal.js +101 -0
  100. package/nativePush.js +153 -0
  101. package/nitroVerify.js +220 -0
  102. package/noble-p256.js +27 -0
  103. package/notice.js +116 -0
  104. package/notifKey.js +58 -0
  105. package/offlineBundle.js +62 -0
  106. package/ohttp.js +177 -0
  107. package/opencodeWire.js +282 -0
  108. package/oprf.js +70 -0
  109. package/ownAgentLink.js +96 -0
  110. package/ownerPolicy.js +117 -0
  111. package/package.json +254 -4
  112. package/pollVerdict.js +33 -0
  113. package/prefetchPoll.js +60 -0
  114. package/protectedLocal.js +410 -0
  115. package/pushCore.js +42 -0
  116. package/recovery.js +107 -0
  117. package/regions.js +42 -0
  118. package/removedMessage.js +11 -0
  119. package/renameRefusal.js +9 -0
  120. package/replyQuote.js +34 -0
  121. package/reqEnvelope.js +126 -0
  122. package/roomDefaultPrefs.js +76 -0
  123. package/roomDelete.js +109 -0
  124. package/roomName.js +177 -0
  125. package/roomPass.js +256 -0
  126. package/roomRoster.js +289 -0
  127. package/roomSettings.js +61 -0
  128. package/roomState.js +58 -0
  129. package/roomStreamClient.js +115 -0
  130. package/rosterCount.js +49 -0
  131. package/rosterHash.js +13 -0
  132. package/rowSchema.js +113 -0
  133. package/safeMedia.js +116 -0
  134. package/safeMediaPins.js +17 -0
  135. package/schedulesDoc.js +78 -0
  136. package/sdkA2A.js +404 -0
  137. package/sdkAccount.js +470 -0
  138. package/sdkAccountDoc.js +81 -0
  139. package/sdkAccountSections.js +223 -0
  140. package/sdkAgui.js +141 -0
  141. package/sdkAttest.js +34 -0
  142. package/sdkBackup.js +480 -0
  143. package/sdkBackupV2.js +630 -0
  144. package/sdkBrowserPrivate.js +28 -0
  145. package/sdkBuilds.js +208 -0
  146. package/sdkCloudDevice.js +215 -0
  147. package/sdkComputers.js +480 -0
  148. package/sdkDictation.js +142 -0
  149. package/sdkErase.js +283 -0
  150. package/sdkExports.js +69 -0
  151. package/sdkInvitations.js +34 -0
  152. package/sdkKeptAgent.js +188 -0
  153. package/sdkLaneLink.js +205 -0
  154. package/sdkPlan.js +94 -0
  155. package/sdkProtect.js +228 -0
  156. package/sdkRedact.js +36 -0
  157. package/sdkRekey.js +307 -0
  158. package/sdkReport.js +68 -0
  159. package/sdkSafeMedia.js +255 -0
  160. package/sdkSchedules.js +39 -0
  161. package/sdkSpeech.js +54 -0
  162. package/sdkTurn.js +117 -0
  163. package/sdkVault.js +124 -0
  164. package/sealShare.js +18 -0
  165. package/sealedNames.js +64 -0
  166. package/sealedReceipt.js +17 -0
  167. package/sentinelRelease.js +154 -0
  168. package/shamir.js +85 -0
  169. package/sharedViews.js +38 -0
  170. package/sheetChrome.js +450 -0
  171. package/siri.js +171 -0
  172. package/spaceClient.js +1418 -0
  173. package/spaceConfig.js +81 -0
  174. package/spaceEmailGate.js +813 -0
  175. package/spaceExport.js +125 -0
  176. package/spaceFork.js +216 -0
  177. package/spaceLock.js +358 -0
  178. package/spacePasskey.js +180 -0
  179. package/speechOut.js +100 -0
  180. package/splitKeyClient.js +90 -0
  181. package/store.js +587 -0
  182. package/streamHint.js +36 -0
  183. package/sttCloud.js +220 -0
  184. package/sttWorklet.js +38 -0
  185. package/sw-notif-core.js +538 -0
  186. package/tempList.js +48 -0
  187. package/tinfoilVerifier.js +78 -0
  188. package/toolBooks.js +31 -0
  189. package/toolRules.js +52 -0
  190. package/turnCerts.js +254 -0
  191. package/turnFeed.js +58 -0
  192. package/turnVerdict.js +36 -0
  193. package/usageReceipts.js +176 -0
  194. package/usageSummary.js +90 -0
  195. package/util.js +181 -0
  196. package/vault-core.js +1958 -0
  197. package/vault-kit.mjs +354 -0
  198. package/vault-screens.js +263 -0
  199. package/vaultAtRest.js +177 -0
  200. package/vaultCoreLock.js +111 -0
  201. package/vaultCorePush.js +140 -0
  202. package/vaultDeviceKey.js +95 -0
  203. package/vaultEnclaveHandoff.js +114 -0
  204. package/vaultKeep.js +281 -0
  205. package/vaultSealedStore.js +77 -0
  206. package/vaultWorkerHost.js +98 -0
  207. package/vcWorker.js +34 -0
  208. package/voiceAttest.js +50 -0
  209. package/voiceCert.js +51 -0
  210. package/witbitz-admin.d.ts +135 -0
  211. package/witbitz-admin.js +529 -0
  212. package/witbitz-admin.mjs +1459 -0
  213. package/witbitz-sdk.d.ts +1106 -0
  214. package/witbitz-sdk.js +3835 -0
  215. package/workerClient.js +16 -0
  216. package/workerLiveness.js +21 -0
  217. package/x509.js +218 -0
package/sdkA2A.js ADDED
@@ -0,0 +1,404 @@
1
+ // spaces/public/sdkA2A.js — OUTSIDE AGENTS INTO A MEMBER'S PRIVATE LANE, over A2A (https://witbitz.chat/docs/sdk-agents.md#a2a): the device's half.
2
+ // The Sentinel (infra/cloud-computer/sentinel/a2a.mjs) is the door: TLS ends inside the enclave, a peer's words are sealed
3
+ // to the lane's INBOX public key and kept until a device collects them. This module is everything the device does:
4
+ // • wb.a2a — the ACCOUNT's record (which lanes take A2A, each peer's token HASH and reply rule, the lanes'
5
+ // inbox public keys), sealed to the attested Sentinel and pushed whole; its state is the app's to
6
+ // persist (it holds the lanes' inbox PRIVATE keys), exactly like wb.siri.
7
+ // • lane.a2a — this lane: enable / addPeer (the token is shown ONCE, only its hash leaves) / setReply / removePeer
8
+ // / disable, and collect(): open each waiting message with the lane's inbox key and post it into the
9
+ // lane, where the lane's assistant drafts an answer. The member approves it (reply 'ask', the
10
+ // default) or it goes back on its own (reply 'auto') — the owner's D2: configurable per peer.
11
+ // A peer's text is someone else's words: it lands as a message the assistant READS, with a one-turn instruction to treat
12
+ // it as information and not as instructions; nothing crosses to the shared room except through the usual proposals.
13
+ import { attestStandingSentinel } from './connections.js'
14
+ import { rosterParticipants, isSoloVerified } from './rosterCount.js'
15
+ import { isKeptSpace, assertNotKept } from './sdkCloudDevice.js'
16
+
17
+ export async function assertAgentTarget(space) {
18
+ if (space._sharedRoom) return
19
+ const session = space._wb && space._wb._session
20
+ const cfg = await space._client.getConfig(space.room, space._mk, { plainMark: true })
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
+ 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
+ const book = await space._client.state(space.room, space._mk, 'roster')
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')
26
+ }
27
+ import { readAllPages } from './ledgerView.js'
28
+ import { sealTo as sealToEnclave } from './sealShare.js'
29
+ // The rules — the record, letting a peer in, the Sentinel calls, opening a collected message — are a2aCore.js, which the
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'
32
+ import { isLaneCopy } from './roomName.js' // a lane's copy of its shared room's line is never a draft
33
+ import { A2A_PENDING_DOC, A2A_PEERS_DOC, peersFromDoc, pendingFromDoc, withoutShared } from './a2aShared.js'
34
+ /** The Sentinel's answer for a task that already has its reply (infra/cloud-computer/sentinel/a2a.mjs). */
35
+ export { finishedTask } // a2aCore.js — one test for the app and the SDK
36
+ export { A2A_ENDPOINT, a2aTokenHash }
37
+ /** Persisted state → its checked form (a2aCore.normA2A — the app's rules: room, handle and key shapes, ≤ 32 lanes and peers). */
38
+ export const a2aStateOf = normA2A
39
+ const fail = (code, msg) => Object.assign(new Error('witbitz: ' + msg), { code })
40
+ /** The pending tasks as a snapshot carries them (JSON-safe, bounded): a lane's snapshot() / resume (sync sweep 10-24 #17). */
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
+ .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 } : {}) },
43
+ text: String(p.text || '').slice(0, 4000), at: Number(p.at) || 0, cursor: Math.max(0, Number(p.cursor) || 0), ...(typeof p.draft === 'string' ? { draft: p.draft } : {}) }))
44
+
45
+ /** `wb.a2a` — the account's A2A record. */
46
+ export class A2AAccount {
47
+ /** @param wb the Witbitz client; `deps` lets a test replace the Sentinel path ({ post, auth, attest, seal }). */
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
50
+ /** Called with the new state whenever it changes — persist it (it holds the lanes' inbox private keys). */
51
+ this.onState = null
52
+ }
53
+ get state() { return JSON.parse(JSON.stringify(this._s)) }
54
+ restore(state) { this._s = a2aStateOf(state); return this }
55
+ 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
+ _d() {
57
+ const wb = this._wb
58
+ if (this._deps) return this._deps
59
+ 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
+ }
61
+ 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)
62
+ _changed() { if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback */ } } }
63
+ _calls() {
64
+ 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) })
66
+ }
67
+ _sealed(mode, obj) { return this._calls().sealed(mode, obj) }
68
+ _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) {
71
+ 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 })
74
+ if (s === this._s) this._changed()
75
+ return r
76
+ }
77
+ // ⛔ A CHANGE IS KEPT ONLY ONCE THE SENTINEL TOOK IT (state machines pass 9, K#5): the record was changed in place and pushed
78
+ // after — a push that failed left this device believing an agent removed (or a lane closed) while the Sentinel still let it
79
+ // in, and a retry found nothing to remove and pushed nothing: the token stayed valid. `disable` had already dropped the lane's
80
+ // inbox private key while its door stayed open. Now `fn` changes a COPY, the copy is pushed, and only then is it the state.
81
+ // 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
+ // push was out (a vault applying the account's kept copy) is merged with the change, not overwritten (a2aCore.js rules).
83
+ // `fn` returns NO_CHANGE when there is nothing to do (nothing pushed).
84
+ _change(fn) {
85
+ const run = async () => {
86
+ const session = this._wb._session
87
+ const base = this._s, next = JSON.parse(JSON.stringify(base))
88
+ 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')
93
+ this._s = this._s === base ? a2aStateOf(next) : mergeA2ARecords(next, this._s)
94
+ this._changed()
95
+ return out
96
+ }
97
+ const p = (this._q || Promise.resolve()).then(run, run)
98
+ this._q = p.catch(() => {})
99
+ return p
100
+ }
101
+ /** What the Sentinel holds for this account (lanes, peers by name, open tasks). */
102
+ status() { return this._plain('a2astatus') }
103
+ /** Turn A2A off everywhere for this account: every lane's card and every token stop working. Each inbox is marked switched
104
+ * 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 }
106
+ }
107
+ const deliveryKey = (taskId, n, at) => JSON.stringify([taskId, Number(n) || 1, Number(at) || 0])
108
+ const NO_CHANGE = Symbol('no change')
109
+
110
+ /** `lane.a2a` — this lane's door for outside agents. */
111
+ export class LaneA2A {
112
+ constructor(lane) {
113
+ this._lane = lane
114
+ // [{ taskId, peer, text, at, cursor, draft? }] — waiting for the assistant's draft, or for the member, oldest first. It rides
115
+ // 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
+ // for ever (sync sweep 10-24 #17). Resumed: watched again, and a draft that already came is offered again.
117
+ 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)
119
+ this._ambiguous = new Map()
120
+ this._sendingDrafts = new Set()
121
+ this._seenDrafts = new WeakSet()
122
+ this._sub = null
123
+ this._held = [] // drafts for the member while nobody listens for 'a2a' — given to the first listener (Lane.on; sync sweep 10-26 #8)
124
+ if (this._pending.length) {
125
+ this._listen()
126
+ Promise.resolve().then(() => { for (const t of this._pending.slice()) if (t.draft !== undefined) this._offer(t) })
127
+ }
128
+ }
129
+ _acct() { const wb = this._lane._wb; if (!wb || !wb.a2a) throw fail('no_client', 'this lane has no Witbitz client behind it — open it through a Witbitz instance'); return wb.a2a }
130
+ _cfg() { return this._acct()._s.lanes[this._lane.room] || null }
131
+ /** The lane's public Agent Card URL (null until enabled) — hand it, with a token, to the agents you choose. */
132
+ get cardUrl() { const c = this._cfg(); return c ? cardUrlOf(this._acct()._endpoint, c.handle) : null }
133
+ /** The lane's MCP address (null until enabled) — the same door for an agent that speaks MCP instead of A2A (Claude Code,
134
+ * Grok, Cursor…): tools message_member / get_reply, the SAME per-peer token (portal/docs/outside-agents.md). */
135
+ get mcpUrl() { const c = this._cfg(); return c ? mcpUrlOf(this._acct()._endpoint, c.handle) : null }
136
+ /** The peers that may reach this lane: [{ id, name, reply }] — never a token. */
137
+ get peers() { return peersOf(this._acct()._s, this._lane.room) }
138
+ /** Let outside agents reach this lane. `name`/`description` are what its public card says. → { cardUrl } */
139
+ async enable({ name = '', description = '' } = {}) {
140
+ const a = this._acct(), room = this._lane.room
141
+ await assertAgentTarget(this._lane)
142
+ await a._change((s) => enableLaneIn(s, room, { name, description })) // kept only once the Sentinel took it (pass 9, K#5)
143
+ return { cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
144
+ }
145
+ /** Issue a token to one outside agent. `reply`: 'ask' (default — you approve every answer) or 'auto' (the lane's
146
+ * assistant answers it on its own). `job: true`: an agent that TAKES JOBS — it reports and its run ends, reading no reply,
147
+ * 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
+ * token is shown ONCE; only its hash is kept. */
149
+ async addPeer(name, { reply = 'ask', job = false } = {}) {
150
+ if (reply === 'auto') await assertNotKept(this._lane)
151
+ await assertAgentTarget(this._lane)
152
+ 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)))
154
+ try { await this._syncRoomPeer(id) } catch (error) {
155
+ await a._change((s) => removePeerIn(s, this._lane.room, id) || NO_CHANGE)
156
+ throw error
157
+ }
158
+ return { id, token, cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
159
+ }
160
+ /** Change whether this peer's answers wait for you ('ask') or go on their own ('auto'). */
161
+ async setReply(peerId, reply) {
162
+ await assertNotKept(this._lane)
163
+ const a = this._acct()
164
+ const r = await a._change((s) => setPeerReplyIn(s, this._lane.room, peerId, reply, fail))
165
+ await this._syncRoomPeer(peerId)
166
+ return { id: peerId, reply: r }
167
+ }
168
+ /** Revoke one agent's token; its unanswered messages are dropped. */
169
+ async removePeer(peerId) {
170
+ const a = this._acct(); if (!this._cfg()) return { removed: false }
171
+ const r = await a._change((s) => removePeerIn(s, this._lane.room, peerId) || NO_CHANGE) // a failed push rejects and keeps the agent: a retry pushes (K#5)
172
+ this._dropDrafts(peerId)
173
+ await this._syncRoomPeer(peerId)
174
+ return { removed: r === true }
175
+ }
176
+ async _syncRoomPeer(id) {
177
+ const sp = this._lane
178
+ if (sp._sharedRoom) return
179
+ const session = sp._wb._session
180
+ await assertAgentTarget(sp)
181
+ for (let i = 0; i < 5; i++) {
182
+ 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')
184
+ if (!doc || doc.status !== 200) throw fail('unreadable', 'the room peer list could not be read')
185
+ const peers = peersFromDoc(doc).filter((p) => p.id !== id)
186
+ const peer = this.peers.find((p) => p.id === id)
187
+ if (peer) peers.push(peer)
188
+ const r = await sp._client.state(sp.room, sp._mk, A2A_PEERS_DOC, { peers }, `${peers.length} outside agents may write here`, 'you', doc.v || 0)
189
+ if (r?.status === 200) return
190
+ if (r?.status !== 409) throw fail('save_failed', 'the room peer list could not be saved')
191
+ }
192
+ throw fail('version_conflict', 'the room peer list kept changing')
193
+ }
194
+ /** Close this lane to outside agents: its card and every token stop working. */
195
+ 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
+
197
+ async _sharedDrafts() {
198
+ const space = this._lane, session = space._wb._session
199
+ if (space._sharedRoom) throw fail('solo_verified_required', 'shared drafts belong to a solo verified Space')
200
+ await assertAgentTarget(space)
201
+ 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')
203
+ if (doc?.status !== 200 || !Number.isInteger(doc.v)) throw fail('unreadable', 'shared drafts could not be read')
204
+ return { items: pendingFromDoc(doc), version: doc.v }
205
+ }
206
+ /** Replies drafted on another device, including the cloud device. */
207
+ async sharedDrafts() { return (await this._sharedDrafts()).items }
208
+ async reviewDraft(draft, text, options = {}) {
209
+ const space = this._lane, session = space._wb._session
210
+ const matches = (p) => p.taskId === draft?.taskId && p.at === draft.at && p.peerId === draft.peerId && p.draft === draft.draft && p.text === draft.text
211
+ let doc = await this._sharedDrafts()
212
+ const current = doc.items.find(matches)
213
+ if (!current) throw fail('draft_changed', 'refresh the shared drafts before reviewing this reply')
214
+ const result = await this.reply(current.taskId, options.reject ? '' : (text ?? current.draft), options)
215
+ for (let attempt = 0; attempt < 5; attempt++) {
216
+ if (space._wb._session !== session) throw fail('account_changed', 'the account changed during draft review')
217
+ if (!doc.items.some(matches)) return result
218
+ const items = withoutShared(doc.items, current.taskId)
219
+ 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)
220
+ if (saved?.status === 200) return result
221
+ if (saved?.status !== 409) throw fail('save_failed', 'the reply was sent but its shared draft could not be cleared')
222
+ doc = await this._sharedDrafts()
223
+ }
224
+ throw fail('version_conflict', 'the reply was sent but shared drafts kept changing')
225
+ }
226
+
227
+ /** Collect: open every waiting message for this lane and post it into the lane; its assistant drafts an answer. For an
228
+ * 'ask' peer the draft arrives as an `a2a` event on the lane — { taskId, peer, text, draft, approve(text?), askBack(text),
229
+ * decline() }; for an 'auto' peer it is sent back on its own. → { delivered }. At-least-once: a message posted but not
230
+ * acked comes back, so `taskId` + its order is the dedupe key. */
231
+ _dropDrafts(peerId) {
232
+ const keep = t => peerId && t.peer.id !== peerId
233
+ this._pending = this._pending.filter(keep)
234
+ this._held = this._held.filter(keep)
235
+ }
236
+ async _sendOnce(key, msg, opts) {
237
+ const lane = this._lane
238
+ if (this._ambiguous.has(key)) {
239
+ const { offset: cursor } = this._ambiguous.get(key)
240
+ const result = await readAllPages(since => lane._client.poll(lane.room, lane._mk, undefined, since || cursor))
241
+ if (result.incomplete) return false
242
+ if (result.entries.some(e => e.text === msg.text && (e.from || e.name) === msg.from)) { this._ambiguous.delete(key); return true }
243
+ this._ambiguous.delete(key)
244
+ }
245
+ const cursor = { offset: lane._count || 0, draft: lane.messages?.length || 0 }
246
+ let sent
247
+ try { sent = await lane.send(msg.text, opts) } catch (err) { this._ambiguous.set(key, cursor); throw err }
248
+ if (sent?.ok === true && !sent.pending) return true
249
+ if (sent?.status === 0 || sent?.pending) this._ambiguous.set(key, cursor)
250
+ return false
251
+ }
252
+ collect() {
253
+ for (const t of this._pending) if (t.peer.reply === 'auto' && t.draft !== undefined) this._offer(t)
254
+ if (!this._collecting) this._collecting = this._collectInbox().finally(() => { this._collecting = null })
255
+ return this._collecting
256
+ }
257
+ async _collectInbox() {
258
+ // The cloud device takes intake drops. Only fallback boxes sealed to this inbox are returned by a2apull.
259
+ if (await isKeptSpace(this._lane) && !this._lane._wb?.a2a?._s?.lanes?.[this._lane.room]) return { delivered: 0 }
260
+ await assertAgentTarget(this._lane)
261
+ const a = this._acct(), c = this._cfg(), lane = this._lane
262
+ if (!c) return { delivered: 0 }
263
+ const t0 = Date.now()
264
+ const r = await a._plain('a2apull', { handle: c.handle })
265
+ const items = Array.isArray(r.items) ? r.items : []
266
+ this._listen()
267
+ let delivered = 0, more = false
268
+ for (const it of items) {
269
+ if (Date.now() - t0 > A2A_COLLECT_WINDOW_MS) { more = true; break } // its lease runs out before it is posted and acked: the next collect (pass 9, K#9)
270
+ const opened = await openItem(c, it); if (!opened) continue // not for this lane's key: leave it for a device that can
271
+ const { m, peer } = opened
272
+ const msg = a2aMessage(peer, m.text)
273
+ // POSTED ONCE, ACKED ONLY WHEN IT LANDED (sync sweep 2026-11-23 #3 + its unclear P1): lane.send never throws — busy, refused or
274
+ // closed resolve ok:false — and acking that lost the message; an ack that threw reposted it at the next collect
275
+ const key = deliveryKey(it.taskId, it.n, m.at)
276
+ const cursor = this._ambiguous.get(key)?.draft ?? (lane.messages || []).length
277
+ if (!this._posted.has(key)) {
278
+ const sent = await this._sendOnce(key, msg, {
279
+ from: msg.from, mode: 'always',
280
+ instructions: a2aInstructions(peer),
281
+ _peerPost: true, // the agent's name is not the member's (sweep 10-24 #13)
282
+ })
283
+ if (!sent) continue // not in the lane: left un-acked, the next collect delivers it
284
+ this._posted.add(key)
285
+ 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
+ }
287
+ await a._plain('a2aack', { items: [{ taskId: it.taskId, n: it.n }] })
288
+ delivered++
289
+ }
290
+ return { delivered, ...(more ? { more } : {}) }
291
+ }
292
+ /** Answer a task yourself (or after editing a draft). `ask: true` asks the peer something back; `reject: true` declines. */
293
+ async reply(taskId, text, { ask = false, reject = false } = {}) {
294
+ const a = this._acct()
295
+ let r
296
+ try { r = await a._sealed('a2areply', { account: await a._account(), taskId: String(taskId), text: String(text || ''), ask: !!ask, reject: !!reject }) } catch (e) {
297
+ // a task already answered (a resumed 'auto' task taken mid-send was re-sent on every resume, an error each time —
298
+ // sync sweep backlog): it is done, not failed — dropped, never offered again
299
+ if (!finishedTask(e)) throw e
300
+ r = { state: 'completed' }
301
+ }
302
+ this._pending = this._pending.filter((p) => p.taskId !== taskId)
303
+ return { state: r.state }
304
+ }
305
+
306
+ // The lane's assistant answers after each posted message: the first agent message after a pending task's cursor is
307
+ // its draft (oldest task first). 'auto' → sent; 'ask' → an `a2a` event for the member.
308
+ _registerDraft(task) {
309
+ this._pending.push(task)
310
+ const messages = this._lane.messages || []
311
+ for (let i = task.cursor; i < messages.length && task.draft === undefined; i++) this._matchDraft(messages[i], i)
312
+ }
313
+ _matchDraft(m, idx) {
314
+ if (!m || m.self !== true || isLaneCopy(m)) return // the lane's assistant, never the shared room's mirrored in (sweep 10-24 #16)
315
+ if (!String(m.text || '').trim()) return // an empty line is no draft, as in the app (a2aLane.js) — an 'auto' peer was sent '' (sweep 10-26 #9)
316
+ if (this._seenDrafts.has(m)) return
317
+ const t = this._pending.find((p) => p.draft === undefined && idx >= p.cursor)
318
+ if (!t) return
319
+ this._seenDrafts.add(m)
320
+ t.draft = String(m.text || '')
321
+ this._offer(t)
322
+ }
323
+ _listen() {
324
+ if (this._sub) return
325
+ this._sub = (m) => this._matchDraft(m, (this._lane.messages || []).lastIndexOf(m))
326
+ this._lane.on('message', this._sub)
327
+ }
328
+ /** The drafts held while nobody listened, to the listener that came (Lane.on). */
329
+ _flushHeld() { const h = this._held.splice(0); for (const t of h) if (this._pending.includes(t)) this._offer(t) }
330
+ /** A task's draft: 'auto' → sent; 'ask' → an `a2a` event for the member. */
331
+ _offer(t) {
332
+ if (t.peer.reply === 'auto') {
333
+ if (this._sendingDrafts.has(t.taskId)) return
334
+ 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))
336
+ return
337
+ }
338
+ 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
339
+ this._lane._emit('a2a', {
340
+ taskId: t.taskId, peer: { id: t.peer.id, name: t.peer.name }, text: t.text, draft: t.draft,
341
+ approve: (text) => this.reply(t.taskId, text === undefined ? t.draft : text),
342
+ askBack: (text) => this.reply(t.taskId, text, { ask: true }),
343
+ decline: () => this.reply(t.taskId, '', { reject: true }),
344
+ })
345
+ }
346
+ }
347
+
348
+ /** `lane.a2a` IN A VAULT (docs/sdk-vault-mode.md § The account). The vault keeps the A2A state — the lanes' inbox private
349
+ * keys, per account — and makes the Sentinel calls: enable, peers, the pull (it opens each message) and the ack. This
350
+ * page does what it does outside a vault: posts each opened message into the lane BEFORE the vault acks it, and runs the
351
+ * draft flow (the `a2a` event, approve / askBack / decline). `conn` is the vault connection (sdkVault.js). */
352
+ export class VaultLaneA2A extends LaneA2A {
353
+ 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)
356
+ }
357
+ async _call(m, ...a) {
358
+ 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
360
+ return r ? r.result : r
361
+ }
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 })) : [] }
365
+ async enable({ name = '', description = '' } = {}) {
366
+ await this._call('enable', { name, description }); return { cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
367
+ }
368
+ // 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 } }
370
+ async setReply(peerId, reply) { return this._call('setReply', peerId, reply) }
371
+ async removePeer(peerId) { const result = await this._call('removePeer', peerId); this._dropDrafts(peerId); return result }
372
+ async disable() { const result = await this._call('disable'); this._dropDrafts(); return result }
373
+ sharedDrafts() { return this._call('sharedDrafts') }
374
+ reviewDraft(draft, text, options = {}) { return this._call('reviewDraft', draft, text, options) }
375
+ async _collectInbox() {
376
+ const lane = this._lane
377
+ const t0 = Date.now()
378
+ const items = await this._call('pull')
379
+ if (!Array.isArray(items)) return { delivered: 0 }
380
+ this._listen()
381
+ let delivered = 0, more = false
382
+ for (const { taskId, n, m, peer } of items) {
383
+ if (Date.now() - t0 > A2A_COLLECT_WINDOW_MS) { more = true; break } // as above: the vault's pull leased them (pass 9, K#9)
384
+ const msg = a2aMessage(peer, m.text)
385
+ const key = deliveryKey(taskId, n, m.at)
386
+ const cursor = this._ambiguous.get(key)?.draft ?? (lane.messages || []).length
387
+ if (!this._posted.has(key)) { // as above (sync sweep 2026-11-23 #3): acked only once it landed, posted once
388
+ const sent = await this._sendOnce(key, msg, { from: msg.from, mode: 'always', instructions: a2aInstructions(peer), _peerPost: true })
389
+ if (!sent) continue
390
+ this._posted.add(key)
391
+ 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
+ }
393
+ await this._call('ack', { taskId, n })
394
+ delivered++
395
+ }
396
+ return { delivered, ...(more ? { more } : {}) }
397
+ }
398
+ async reply(taskId, text, { ask = false, reject = false } = {}) {
399
+ 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)
401
+ this._pending = this._pending.filter((p) => p.taskId !== taskId)
402
+ return { state: r && r.state }
403
+ }
404
+ }