@witbitz/sdk 0.0.0-stage → 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 (236) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/a2aCore.js +221 -0
  4. package/a2aShared.js +27 -0
  5. package/accountErase.js +228 -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/agentDoorTools.js +28 -0
  23. package/attestedBox.js +30 -0
  24. package/attestedRooms.js +78 -0
  25. package/awsKey.js +98 -0
  26. package/backupRecord.js +106 -0
  27. package/backupVault.js +97 -0
  28. package/blocks.js +115 -0
  29. package/blocksPush.js +64 -0
  30. package/browseSeal.js +103 -0
  31. package/cbor.js +225 -0
  32. package/changePush.js +75 -0
  33. package/chatLock.js +165 -0
  34. package/chatLockSw.js +13 -0
  35. package/cloudDeviceBuilds.js +11 -0
  36. package/cloudDevicePins.js +33 -0
  37. package/cloudDeviceSeal.js +53 -0
  38. package/codeAttachments.js +100 -0
  39. package/codeBrowse.js +224 -0
  40. package/codeCache.js +149 -0
  41. package/codeCloud.js +650 -0
  42. package/codeCloudKeys.js +112 -0
  43. package/codeCommands.js +167 -0
  44. package/codeComputers.js +389 -0
  45. package/codeEgress.js +123 -0
  46. package/codeFilesRoutes.js +17 -0
  47. package/codeFolders.js +116 -0
  48. package/codeHistory.js +76 -0
  49. package/codeLanguage.js +54 -0
  50. package/codeMkdir.js +8 -0
  51. package/codeModes.js +59 -0
  52. package/codeOrphanKeys.js +42 -0
  53. package/codeOutputs.js +141 -0
  54. package/codeProgress.js +54 -0
  55. package/codeRelay.js +505 -0
  56. package/codeSent.js +68 -0
  57. package/codeSentinel.js +86 -0
  58. package/codeSubagents.js +107 -0
  59. package/codeTransport.js +317 -0
  60. package/codeUndo.js +48 -0
  61. package/compress.js +24 -0
  62. package/config.js +11 -0
  63. package/connCatalog.js +164 -0
  64. package/connDisp.js +76 -0
  65. package/connOtherWays.js +74 -0
  66. package/connPending.js +16 -0
  67. package/connWrap.js +53 -0
  68. package/connectionEntry.js +89 -0
  69. package/connections.js +561 -0
  70. package/credits.js +30 -0
  71. package/csAttest.js +112 -0
  72. package/decrypt.html +384 -0
  73. package/deviceAttest.js +527 -0
  74. package/deviceCall.js +54 -0
  75. package/deviceKeyCore.js +41 -0
  76. package/deviceSeal.js +59 -0
  77. package/e2ee.js +323 -0
  78. package/eat.js +103 -0
  79. package/emailFork.js +275 -0
  80. package/emailSignIn.js +81 -0
  81. package/emptySpaces.js +111 -0
  82. package/encSource.js +55 -0
  83. package/enclaveAccept.js +214 -0
  84. package/enclaveClaim.js +241 -0
  85. package/enclaveRoute.js +102 -0
  86. package/enclaveSnapshotMerge.js +44 -0
  87. package/entrySig.js +165 -0
  88. package/env.js +73 -0
  89. package/eraseFile.js +58 -0
  90. package/followImage.js +86 -0
  91. package/healNames.js +45 -0
  92. package/idb.js +113 -0
  93. package/idbSeal.js +119 -0
  94. package/indexGone.js +12 -0
  95. package/invite.js +51 -0
  96. package/inviteEnroll.js +67 -0
  97. package/inviteSend.js +68 -0
  98. package/jobAgents.js +87 -0
  99. package/keptMerge.js +91 -0
  100. package/l1-worker-src.js +2 -0
  101. package/l1-worker.js +894 -0
  102. package/laneAssociation.js +68 -0
  103. package/laneConfig.js +58 -0
  104. package/laneLinkCore.js +177 -0
  105. package/ledgerView.js +64 -0
  106. package/manifest.json +239 -0
  107. package/mcpRecommended.js +25 -0
  108. package/memberChange.js +125 -0
  109. package/mirrorBatch.js +47 -0
  110. package/mkseal.js +101 -0
  111. package/nativePush.js +153 -0
  112. package/nitroVerify.js +220 -0
  113. package/noble-p256.js +27 -0
  114. package/notice.js +116 -0
  115. package/notifKey.js +58 -0
  116. package/offlineBundle.js +62 -0
  117. package/ohttp.js +177 -0
  118. package/opRouting.js +10 -0
  119. package/opencodeWire.js +282 -0
  120. package/oprf.js +70 -0
  121. package/ownAgentLink.js +96 -0
  122. package/ownerPolicy.js +117 -0
  123. package/package.json +273 -4
  124. package/pdfOptions.js +13 -0
  125. package/pdfText.js +107 -0
  126. package/pdfjs.mjs +28 -0
  127. package/pdfjs.worker.mjs +28 -0
  128. package/pollVerdict.js +33 -0
  129. package/prefetchPoll.js +60 -0
  130. package/protectedLocal.js +426 -0
  131. package/pushCore.js +42 -0
  132. package/recovery.js +107 -0
  133. package/regions.js +42 -0
  134. package/removedMessage.js +11 -0
  135. package/renameRefusal.js +9 -0
  136. package/replyQuote.js +34 -0
  137. package/reqEnvelope.js +126 -0
  138. package/roomDefaultPrefs.js +76 -0
  139. package/roomDelete.js +109 -0
  140. package/roomEmbed.js +111 -0
  141. package/roomName.js +177 -0
  142. package/roomPass.js +256 -0
  143. package/roomRoster.js +305 -0
  144. package/roomSettings.js +61 -0
  145. package/roomState.js +58 -0
  146. package/roomStreamClient.js +115 -0
  147. package/rosterCount.js +52 -0
  148. package/rosterHash.js +13 -0
  149. package/rowSchema.js +113 -0
  150. package/safeMedia.js +116 -0
  151. package/safeMediaPins.js +17 -0
  152. package/schedulesDoc.js +78 -0
  153. package/sdkA2A.js +524 -0
  154. package/sdkAccount.js +483 -0
  155. package/sdkAccountDoc.js +89 -0
  156. package/sdkAccountSections.js +332 -0
  157. package/sdkAgui.js +141 -0
  158. package/sdkAttest.js +34 -0
  159. package/sdkBackup.js +507 -0
  160. package/sdkBackupV2.js +630 -0
  161. package/sdkBrowserPrivate.js +28 -0
  162. package/sdkBuilds.js +208 -0
  163. package/sdkCloudDevice.js +221 -0
  164. package/sdkComputers.js +1009 -0
  165. package/sdkDictation.js +232 -0
  166. package/sdkErase.js +288 -0
  167. package/sdkExports.js +71 -0
  168. package/sdkInvitations.js +34 -0
  169. package/sdkKeptAgent.js +188 -0
  170. package/sdkLaneLink.js +205 -0
  171. package/sdkPlan.js +96 -0
  172. package/sdkProtect.js +228 -0
  173. package/sdkRedact.js +36 -0
  174. package/sdkRekey.js +340 -0
  175. package/sdkReport.js +68 -0
  176. package/sdkSafeMedia.js +255 -0
  177. package/sdkSchedules.js +39 -0
  178. package/sdkSpeech.js +71 -0
  179. package/sdkTemporaryRooms.js +123 -0
  180. package/sdkTurn.js +117 -0
  181. package/sdkVault.js +180 -0
  182. package/sealShare.js +18 -0
  183. package/sealedNames.js +64 -0
  184. package/sealedReceipt.js +17 -0
  185. package/sentinelRelease.js +155 -0
  186. package/shamir.js +85 -0
  187. package/sharedViews.js +52 -0
  188. package/sheetChrome.js +450 -0
  189. package/siri.js +278 -0
  190. package/spaceClient.js +1429 -0
  191. package/spaceConfig.js +81 -0
  192. package/spaceEmailGate.js +813 -0
  193. package/spaceExport.js +125 -0
  194. package/spaceFork.js +216 -0
  195. package/spaceLock.js +358 -0
  196. package/spacePasskey.js +180 -0
  197. package/spaceTemplates.js +99 -0
  198. package/speechOut.js +102 -0
  199. package/splitKeyClient.js +90 -0
  200. package/store.js +656 -0
  201. package/streamHint.js +36 -0
  202. package/sttCloud.js +220 -0
  203. package/sttWorklet.js +38 -0
  204. package/sw-notif-core.js +540 -0
  205. package/tempList.js +48 -0
  206. package/tinfoilVerifier.js +78 -0
  207. package/toolBooks.js +31 -0
  208. package/toolRules.js +52 -0
  209. package/turnCerts.js +254 -0
  210. package/turnFeed.js +58 -0
  211. package/turnVerdict.js +37 -0
  212. package/usageReceipts.js +176 -0
  213. package/usageSummary.js +90 -0
  214. package/util.js +181 -0
  215. package/vault-core.js +2326 -0
  216. package/vault-kit.mjs +354 -0
  217. package/vault-screens.js +261 -0
  218. package/vaultAtRest.js +208 -0
  219. package/vaultCoreLock.js +111 -0
  220. package/vaultCorePush.js +140 -0
  221. package/vaultDeviceKey.js +95 -0
  222. package/vaultEnclaveHandoff.js +114 -0
  223. package/vaultKeep.js +287 -0
  224. package/vaultSealedStore.js +77 -0
  225. package/vaultWorkerHost.js +117 -0
  226. package/vcWorker.js +34 -0
  227. package/voiceAttest.js +50 -0
  228. package/voiceCert.js +51 -0
  229. package/witbitz-admin.d.ts +135 -0
  230. package/witbitz-admin.js +529 -0
  231. package/witbitz-admin.mjs +1460 -0
  232. package/witbitz-sdk.d.ts +1197 -0
  233. package/witbitz-sdk.js +4258 -0
  234. package/workerClient.js +16 -0
  235. package/workerLiveness.js +21 -0
  236. package/x509.js +218 -0
package/sdkA2A.js ADDED
@@ -0,0 +1,524 @@
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, generation = space._wb?._archiveGeneration
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._archiveGeneration !== generation || space._wb._session?.email !== session?.email) 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, applyRemovals, removalIntents, pruneGoneIn, 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, details = {}) => Object.assign(new Error('witbitz: ' + msg), { code, ...details })
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.restore(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, ...(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
+ }
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
60
+ _d() {
61
+ const wb = this._wb
62
+ if (this._deps) return this._deps
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 }
64
+ }
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
+ }
125
+ _changed() { if (typeof this.onState === 'function') { try { this.onState(this.state) } catch { /* the app's callback */ } } }
126
+ _calls() {
127
+ const { post, auth, attest, seal } = this._d()
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) }) })
129
+ }
130
+ _sealed(mode, obj) { return this._calls().sealed(mode, obj) }
131
+ _plain(mode, extra = {}) { return this._calls().plain(mode, extra) }
132
+ /** Send the whole record (it REPLACES what the Sentinel held) — this account's, or `s`, a changed copy (_change). */
133
+ async _push(s = this._s, expectedGeneration = this._wb._archiveGeneration) {
134
+ const account = await this._account()
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 })
139
+ if (s === this._s) this._changed()
140
+ return r
141
+ }
142
+ // ⛔ A CHANGE IS KEPT ONLY ONCE THE SENTINEL TOOK IT (state machines pass 9, K#5): the record was changed in place and pushed
143
+ // after — a push that failed left this device believing an agent removed (or a lane closed) while the Sentinel still let it
144
+ // in, and a retry found nothing to remove and pushed nothing: the token stayed valid. `disable` had already dropped the lane's
145
+ // inbox private key while its door stayed open. Now `fn` changes a COPY, the copy is pushed, and only then is it the state.
146
+ // One change at a time (each starts from the last one's result: two at once lost one). A restore() that landed while the
147
+ // push was out (a vault applying the account's kept copy) is merged with the change, not overwritten (a2aCore.js rules).
148
+ // `fn` returns NO_CHANGE when there is nothing to do (nothing pushed).
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
152
+ const run = async () => {
153
+ if (changed()) throw fail('account_changed', 'the account changed before the agent update')
154
+ const base = this._s, next = JSON.parse(JSON.stringify(base))
155
+ const previous = this._removals.slice()
156
+ const out = await fn(next)
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 = []
168
+ this._s = this._s === base ? a2aStateOf(next) : mergeA2ARecords(next, this._s)
169
+ this._changed()
170
+ return out
171
+ }
172
+ const p = (this._q || Promise.resolve()).then(run, run)
173
+ this._q = p.catch(() => {})
174
+ return p
175
+ }
176
+ /** What the Sentinel holds for this account (lanes, peers by name, open tasks). */
177
+ status() { return this._plain('a2astatus') }
178
+ /** Turn A2A off everywhere for this account: every lane's card and every token stop working. Each inbox is marked switched
179
+ * off, so no other device's copy of the account's record switches one back on (pass 9, K#3). */
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 }
181
+ }
182
+ const deliveryKey = (taskId, n, at) => JSON.stringify([taskId, Number(n) || 1, Number(at) || 0])
183
+ const NO_CHANGE = Symbol('no change')
184
+
185
+ /** `lane.a2a` — this lane's door for outside agents. */
186
+ export class LaneA2A {
187
+ constructor(lane) {
188
+ this._lane = lane
189
+ // [{ taskId, peer, text, at, cursor, draft? }] — waiting for the assistant's draft, or for the member, oldest first. It rides
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"
191
+ // for ever (sync sweep 10-24 #17). Resumed: watched again, and a draft that already came is offered again.
192
+ this._pending = pendingOf(lane._a2aResume)
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)
194
+ this._ambiguous = new Map()
195
+ this._sendingDrafts = new Set()
196
+ this._seenDrafts = new WeakSet()
197
+ this._sub = null
198
+ this._held = [] // drafts for the member while nobody listens for 'a2a' — given to the first listener (Lane.on; sync sweep 10-26 #8)
199
+ if (this._pending.length) {
200
+ this._listen()
201
+ Promise.resolve().then(() => { for (const t of this._pending.slice()) if (t.draft !== undefined) this._offer(t) })
202
+ }
203
+ }
204
+ _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 }
205
+ _cfg() { return this._acct()._s.lanes[this._lane.room] || null }
206
+ /** The lane's public Agent Card URL (null until enabled) — hand it, with a token, to the agents you choose. */
207
+ get cardUrl() { const c = this._cfg(); return c ? cardUrlOf(this._acct()._endpoint, c.handle) : null }
208
+ /** The lane's MCP address (null until enabled) — the same door for an agent that speaks MCP instead of A2A (Claude Code,
209
+ * Grok, Cursor…): tools message_member / get_reply, the SAME per-peer token (portal/docs/outside-agents.md). */
210
+ get mcpUrl() { const c = this._cfg(); return c ? mcpUrlOf(this._acct()._endpoint, c.handle) : null }
211
+ /** The peers that may reach this lane: [{ id, name, reply }] — never a token. */
212
+ get peers() { return peersOf(this._acct()._s, this._lane.room) }
213
+ /** Let outside agents reach this lane. `name`/`description` are what its public card says. → { cardUrl } */
214
+ async enable({ name = '', description = '' } = {}) {
215
+ const a = this._acct(), room = this._lane.room
216
+ await assertAgentTarget(this._lane)
217
+ await a._change((s) => enableLaneIn(s, room, { name, description })) // kept only once the Sentinel took it (pass 9, K#5)
218
+ return { cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
219
+ }
220
+ /** Issue a token to one outside agent. `reply`: 'ask' (default — you approve every answer) or 'auto' (the lane's
221
+ * assistant answers it on its own). `job: true`: an agent that TAKES JOBS — it reports and its run ends, reading no reply,
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
223
+ * token is shown ONCE; only its hash is kept. */
224
+ async addPeer(name, { reply = 'ask', job = false, reconnect = false, previousPeerId, connectionId } = {}) {
225
+ if (reply === 'auto') await assertNotKept(this._lane)
226
+ await assertAgentTarget(this._lane)
227
+ const a = this._acct()
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
+ }
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 }
246
+ await a._change((s) => removePeerIn(s, this._lane.room, id) || NO_CHANGE)
247
+ throw error
248
+ }
249
+ return { id, token, ...(moved.length ? { moved } : {}), cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
250
+ }
251
+ /** Change whether this peer's answers wait for you ('ask') or go on their own ('auto'). */
252
+ async setReply(peerId, reply) {
253
+ await assertNotKept(this._lane)
254
+ const a = this._acct()
255
+ const r = await a._change((s) => setPeerReplyIn(s, this._lane.room, peerId, reply, fail))
256
+ await this._syncRoomPeer(peerId)
257
+ return { id: peerId, reply: r }
258
+ }
259
+ /** Revoke one agent's token; its unanswered messages are dropped. */
260
+ async removePeer(peerId) {
261
+ const a = this._acct(); if (!this._cfg()) return { removed: false }
262
+ 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)
263
+ this._dropDrafts(peerId)
264
+ await this._syncRoomPeer(peerId)
265
+ return { removed: r === true }
266
+ }
267
+ async _syncRoomPeer(id) {
268
+ const sp = this._lane
269
+ if (sp._sharedRoom) return
270
+ const session = sp._wb._session, generation = sp._wb._archiveGeneration
271
+ await assertAgentTarget(sp)
272
+ for (let i = 0; i < 5; i++) {
273
+ const doc = await sp._client.state(sp.room, sp._mk, A2A_PEERS_DOC)
274
+ if (sp._wb._archiveGeneration !== generation || sp._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed while saving the peer')
275
+ if (!doc || doc.status !== 200) throw fail('unreadable', 'the room peer list could not be read')
276
+ const peers = peersFromDoc(doc).filter((p) => p.id !== id)
277
+ const peer = this.peers.find((p) => p.id === id)
278
+ if (peer) peers.push(peer)
279
+ 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)
280
+ if (r?.status === 200) return
281
+ if (r?.status !== 409) throw fail('save_failed', 'the room peer list could not be saved')
282
+ }
283
+ throw fail('version_conflict', 'the room peer list kept changing')
284
+ }
285
+ /** Close this lane to outside agents: its card and every token stop working. */
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 } }
287
+
288
+ async _sharedDrafts() {
289
+ const space = this._lane, session = space._wb._session, generation = space._wb._archiveGeneration
290
+ if (space._sharedRoom) throw fail('solo_verified_required', 'shared drafts belong to a solo verified Space')
291
+ await assertAgentTarget(space)
292
+ const doc = await space._client.state(space.room, space._mk, A2A_PENDING_DOC)
293
+ if (space._wb._archiveGeneration !== generation || space._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed while reading shared drafts')
294
+ if (doc?.status !== 200 || !Number.isInteger(doc.v)) throw fail('unreadable', 'shared drafts could not be read')
295
+ return { items: pendingFromDoc(doc), version: doc.v }
296
+ }
297
+ /** Replies drafted on another device, including the cloud device. */
298
+ async sharedDrafts() { return (await this._sharedDrafts()).items }
299
+ async reviewDraft(draft, text, options = {}) {
300
+ const space = this._lane, session = space._wb._session, generation = space._wb._archiveGeneration
301
+ const matches = (p) => p.taskId === draft?.taskId && p.at === draft.at && p.peerId === draft.peerId && p.draft === draft.draft && p.text === draft.text
302
+ let doc = await this._sharedDrafts()
303
+ const current = doc.items.find(matches)
304
+ if (!current) throw fail('draft_changed', 'refresh the shared drafts before reviewing this reply')
305
+ const result = await this.reply(current.taskId, options.reject ? '' : (text ?? current.draft), options)
306
+ for (let attempt = 0; attempt < 5; attempt++) {
307
+ if (space._wb._archiveGeneration !== generation || space._wb._session?.email !== session?.email) throw fail('account_changed', 'the account changed during draft review')
308
+ if (!doc.items.some(matches)) return result
309
+ const items = withoutShared(doc.items, current.taskId)
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)
311
+ if (saved?.status === 200) return result
312
+ if (saved?.status !== 409) throw fail('save_failed', 'the reply was sent but its shared draft could not be cleared')
313
+ doc = await this._sharedDrafts()
314
+ }
315
+ throw fail('version_conflict', 'the reply was sent but shared drafts kept changing')
316
+ }
317
+
318
+ /** Collect: open every waiting message for this lane and post it into the lane; its assistant drafts an answer. For an
319
+ * 'ask' peer the draft arrives as an `a2a` event on the lane — { taskId, peer, text, draft, approve(text?), askBack(text),
320
+ * decline() }; for an 'auto' peer it is sent back on its own. → { delivered }. At-least-once: a message posted but not
321
+ * acked comes back, so `taskId` + its order is the dedupe key. */
322
+ _dropDrafts(peerId) {
323
+ const keep = t => peerId && t.peer.id !== peerId
324
+ this._pending = this._pending.filter(keep)
325
+ this._held = this._held.filter(keep)
326
+ }
327
+ async _sendOnce(key, msg, opts) {
328
+ const lane = this._lane
329
+ if (this._ambiguous.has(key)) {
330
+ const { offset: cursor } = this._ambiguous.get(key)
331
+ const result = await readAllPages(since => lane._client.poll(lane.room, lane._mk, undefined, since || cursor))
332
+ if (result.incomplete) return false
333
+ if (result.entries.some(e => e.text === msg.text && (e.from || e.name) === msg.from)) { this._ambiguous.delete(key); return true }
334
+ this._ambiguous.delete(key)
335
+ }
336
+ const cursor = { offset: lane._count || 0, draft: lane.messages?.length || 0 }
337
+ let sent
338
+ try { sent = await lane.send(msg.text, opts) } catch (err) { this._ambiguous.set(key, cursor); throw err }
339
+ if (sent?.ok === true && !sent.pending) return true
340
+ if (sent?.status === 0 || sent?.pending) this._ambiguous.set(key, cursor)
341
+ return false
342
+ }
343
+ collect() {
344
+ for (const t of this._pending) if (t.peer.reply === 'auto' && t.draft !== undefined) this._offer(t)
345
+ if (!this._collecting) this._collecting = this._collectInbox().finally(() => { this._collecting = null })
346
+ return this._collecting
347
+ }
348
+ async _collectInbox() {
349
+ // The cloud device takes intake drops. Only fallback boxes sealed to this inbox are returned by a2apull.
350
+ if (await isKeptSpace(this._lane) && !this._lane._wb?.a2a?._s?.lanes?.[this._lane.room]) return { delivered: 0 }
351
+ await assertAgentTarget(this._lane)
352
+ const a = this._acct(), c = this._cfg(), lane = this._lane
353
+ if (!c) return { delivered: 0 }
354
+ const t0 = Date.now()
355
+ const r = await a._plain('a2apull', { handle: c.handle })
356
+ const items = Array.isArray(r.items) ? r.items : []
357
+ this._listen()
358
+ let delivered = 0, more = false
359
+ for (const it of items) {
360
+ 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)
361
+ const opened = await openItem(c, it); if (!opened) continue // not for this lane's key: leave it for a device that can
362
+ const { m, peer } = opened
363
+ const msg = a2aMessage(peer, m.text)
364
+ // POSTED ONCE, ACKED ONLY WHEN IT LANDED (sync sweep 2026-11-23 #3 + its unclear P1): lane.send never throws — busy, refused or
365
+ // closed resolve ok:false — and acking that lost the message; an ack that threw reposted it at the next collect
366
+ const key = deliveryKey(it.taskId, it.n, m.at)
367
+ const cursor = this._ambiguous.get(key)?.draft ?? (lane.messages || []).length
368
+ if (!this._posted.has(key)) {
369
+ const sent = await this._sendOnce(key, msg, {
370
+ from: msg.from, mode: 'always',
371
+ instructions: a2aInstructions(peer),
372
+ _peerPost: true, // the agent's name is not the member's (sweep 10-24 #13)
373
+ })
374
+ if (!sent) continue // not in the lane: left un-acked, the next collect delivers it
375
+ this._posted.add(key); if (this._posted.size > 512) this._posted.delete(this._posted.values().next().value)
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)
377
+ }
378
+ await a._plain('a2aack', { items: [{ taskId: it.taskId, n: it.n }] })
379
+ delivered++
380
+ }
381
+ return { delivered, ...(more ? { more } : {}) }
382
+ }
383
+ /** Answer a task yourself (or after editing a draft). `ask: true` asks the peer something back; `reject: true` declines. */
384
+ async reply(taskId, text, { ask = false, reject = false } = {}) {
385
+ const a = this._acct()
386
+ let r
387
+ try { r = await a._sealed('a2areply', { account: await a._account(), taskId: String(taskId), text: String(text || ''), ask: !!ask, reject: !!reject }) } catch (e) {
388
+ // a task already answered (a resumed 'auto' task taken mid-send was re-sent on every resume, an error each time —
389
+ // sync sweep backlog): it is done, not failed — dropped, never offered again
390
+ if (!finishedTask(e)) throw e
391
+ r = { state: 'completed' }
392
+ }
393
+ this._pending = this._pending.filter((p) => p.taskId !== taskId)
394
+ return { state: r.state }
395
+ }
396
+
397
+ // The lane's assistant answers after each posted message: the first agent message after a pending task's cursor is
398
+ // its draft (oldest task first). 'auto' → sent; 'ask' → an `a2a` event for the member.
399
+ _registerDraft(task) {
400
+ this._pending.push(task)
401
+ const messages = this._lane.messages || []
402
+ for (let i = task.cursor; i < messages.length && task.draft === undefined; i++) this._matchDraft(messages[i], i)
403
+ }
404
+ _matchDraft(m, idx) {
405
+ if (!m || m.self !== true || isLaneCopy(m)) return // the lane's assistant, never the shared room's mirrored in (sweep 10-24 #16)
406
+ 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)
407
+ if (this._seenDrafts.has(m)) return
408
+ const t = this._pending.find((p) => p.draft === undefined && idx >= p.cursor)
409
+ if (!t) return
410
+ this._seenDrafts.add(m)
411
+ t.draft = String(m.text || '')
412
+ this._offer(t)
413
+ }
414
+ _listen() {
415
+ if (this._lane._wb) (this._lane._wb._agentHandles ||= new Set()).add(this._lane)
416
+ if (this._sub) return
417
+ this._sub = (m) => this._matchDraft(m, (this._lane.messages || []).lastIndexOf(m))
418
+ this._lane.on('message', this._sub)
419
+ }
420
+ /** The drafts held while nobody listened, to the listener that came (Lane.on). */
421
+ _flushHeld() { const h = this._held.splice(0); for (const t of h) if (this._pending.includes(t)) this._offer(t) }
422
+ /** A task's draft: 'auto' → sent; 'ask' → an `a2a` event for the member. */
423
+ _offer(t) {
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')) {
426
+ if (this._sendingDrafts.has(t.taskId)) return
427
+ this._sendingDrafts.add(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))
431
+ return
432
+ }
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
434
+ this._lane._emit('a2a', {
435
+ taskId: t.taskId, peer: { id: t.peer.id, name: t.peer.name }, text: t.text, draft: t.draft,
436
+ approve: (text) => this.reply(t.taskId, text === undefined ? t.draft : text),
437
+ askBack: (text) => this.reply(t.taskId, text, { ask: true }),
438
+ decline: () => this.reply(t.taskId, '', { reject: true }),
439
+ })
440
+ }
441
+ }
442
+
443
+ /** `lane.a2a` IN A VAULT (docs/sdk-vault-mode.md § The account). The vault keeps the A2A state — the lanes' inbox private
444
+ * keys, per account — and makes the Sentinel calls: enable, peers, the pull (it opens each message) and the ack. This
445
+ * page does what it does outside a vault: posts each opened message into the lane BEFORE the vault acks it, and runs the
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
+
464
+ export class VaultLaneA2A extends LaneA2A {
465
+ constructor(lane, conn) {
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
474
+ }
475
+ async _call(m, ...a) {
476
+ const epoch = this._conn.a2aEpoch
477
+ const r = await this._conn.roomAccount(this._lane.room, 'a2a', m, ...a)
478
+ if (epoch === this._conn.a2aEpoch && r && 'view' in r) this._conn.a2aViews.set(this._lane.room, { epoch, view: r.view })
479
+ return r ? r.result : r
480
+ }
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 })) }
484
+ async enable({ name = '', description = '' } = {}) {
485
+ await this._call('enable', { name, description }); return { cardUrl: this.cardUrl, mcpUrl: this.mcpUrl }
486
+ }
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
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 } }
489
+ async setReply(peerId, reply) { return this._call('setReply', peerId, reply) }
490
+ async removePeer(peerId) { const result = await this._call('removePeer', peerId); this._dropDrafts(peerId); return result }
491
+ async disable() { const result = await this._call('disable'); this._dropDrafts(); return result }
492
+ sharedDrafts() { return this._call('sharedDrafts') }
493
+ reviewDraft(draft, text, options = {}) { return this._call('reviewDraft', draft, text, options) }
494
+ async _collectInbox() {
495
+ const lane = this._lane
496
+ const t0 = Date.now()
497
+ const items = await this._call('pull')
498
+ if (!Array.isArray(items)) return { delivered: 0 }
499
+ this._listen()
500
+ let delivered = 0, more = false
501
+ for (const { taskId, n, m, peer } of items) {
502
+ if (Date.now() - t0 > A2A_COLLECT_WINDOW_MS) { more = true; break } // as above: the vault's pull leased them (pass 9, K#9)
503
+ const msg = a2aMessage(peer, m.text)
504
+ const key = deliveryKey(taskId, n, m.at)
505
+ const cursor = this._ambiguous.get(key)?.draft ?? (lane.messages || []).length
506
+ if (!this._posted.has(key)) { // as above (sync sweep 2026-11-23 #3): acked only once it landed, posted once
507
+ const sent = await this._sendOnce(key, msg, { from: msg.from, mode: 'always', instructions: a2aInstructions(peer), _peerPost: true })
508
+ if (!sent) continue
509
+ this._posted.add(key); if (this._posted.size > 512) this._posted.delete(this._posted.values().next().value)
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)
511
+ }
512
+ await this._call('ack', { taskId, n })
513
+ delivered++
514
+ }
515
+ return { delivered, ...(more ? { more } : {}) }
516
+ }
517
+ async reply(taskId, text, { ask = false, reject = false, autoPeerId } = {}) {
518
+ let r
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
521
+ this._pending = this._pending.filter((p) => p.taskId !== taskId)
522
+ return { state: r && r.state }
523
+ }
524
+ }