@agentvault/claude-bridge 0.8.12 → 0.8.14

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.
package/dist/index.js CHANGED
@@ -1122,6 +1122,58 @@ var init_mls_commit_classify = __esm2({
1122
1122
  "use strict";
1123
1123
  }
1124
1124
  });
1125
+ function parseMentions(text) {
1126
+ const mentions = [];
1127
+ const re22 = new RegExp(MENTION_RE.source, MENTION_RE.flags);
1128
+ let match;
1129
+ while ((match = re22.exec(text)) !== null) {
1130
+ mentions.push(match[1].toLowerCase());
1131
+ }
1132
+ return mentions;
1133
+ }
1134
+ function resolveOwn(mention, names) {
1135
+ if (names.has(mention)) return mention;
1136
+ const parts = mention.split("-");
1137
+ for (let i2 = parts.length - 1; i2 > 0; i2--) {
1138
+ const candidate = parts.slice(0, i2).join("-");
1139
+ if (names.has(candidate)) return candidate;
1140
+ }
1141
+ return null;
1142
+ }
1143
+ function owesRoomReply(plaintext, agentName, accountId, senderIsAgent, roomDisplayName, ownDisplayName, selfResolved = true) {
1144
+ const mentions = parseMentions(plaintext);
1145
+ if (mentions.length === 0) return false;
1146
+ const ownNames = ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName);
1147
+ if (mentions.some((m22) => resolveOwn(m22, ownNames) !== null)) return true;
1148
+ if (mentions.some((m22) => resolveOwn(m22, BROADCAST_NAMES) !== null)) {
1149
+ return senderIsAgent !== true;
1150
+ }
1151
+ if (!selfResolved) return true;
1152
+ return false;
1153
+ }
1154
+ function ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName) {
1155
+ const names = /* @__PURE__ */ new Set();
1156
+ const add4 = (n22) => {
1157
+ if (!n22) return;
1158
+ const lower = n22.toLowerCase();
1159
+ names.add(lower);
1160
+ names.add(lower.split(/[\s(]/)[0]);
1161
+ };
1162
+ add4(agentName);
1163
+ add4(accountId);
1164
+ add4(roomDisplayName);
1165
+ add4(ownDisplayName);
1166
+ return names;
1167
+ }
1168
+ var MENTION_RE;
1169
+ var BROADCAST_NAMES;
1170
+ var init_room_protocol = __esm2({
1171
+ "src/room-protocol.ts"() {
1172
+ "use strict";
1173
+ MENTION_RE = /@([\w-]+)/gi;
1174
+ BROADCAST_NAMES = /* @__PURE__ */ new Set(["all", "everyone"]);
1175
+ }
1176
+ });
1125
1177
  var __filename;
1126
1178
  var __dirname;
1127
1179
  var url2;
@@ -64024,10 +64076,10 @@ var init_mls_group = __esm2({
64024
64076
  const commits = [];
64025
64077
  if (leavesToRemove.length > 0) {
64026
64078
  const { commit } = await this.removeMembers(leavesToRemove);
64027
- commits.push({ commit, epoch: this.epoch });
64079
+ commits.push({ commit, epoch: this.epoch, state: this.exportState() });
64028
64080
  }
64029
64081
  const added = await this.addMembers(toAdd);
64030
- commits.push({ commit: added.commit, epoch: this.epoch });
64082
+ commits.push({ commit: added.commit, epoch: this.epoch, state: this.exportState() });
64031
64083
  return { commits, welcome: added.welcome };
64032
64084
  }
64033
64085
  async removeMembers(memberIndices) {
@@ -64612,11 +64664,11 @@ var init_mls_kp_pool = __esm2({
64612
64664
  }
64613
64665
  });
64614
64666
  function ownIdentity() {
64615
- const v22 = true ? "0.23.39" : FALLBACK;
64667
+ const v22 = true ? "0.23.41" : FALLBACK;
64616
64668
  return `${PACKAGE}@${v22}`;
64617
64669
  }
64618
64670
  function buildSha() {
64619
- const raw = true ? "9982fc8-dirty" : "";
64671
+ const raw = true ? "916d6c5-dirty" : "";
64620
64672
  const cleaned = (raw ?? "").trim();
64621
64673
  return !cleaned || cleaned === "unknown" ? null : cleaned;
64622
64674
  }
@@ -65523,6 +65575,7 @@ var CREDENTIAL_MESSAGE_TYPES;
65523
65575
  var CATCHUP_MESSAGE_TYPES;
65524
65576
  var POLL_INTERVAL_MS;
65525
65577
  var RECONNECT_BASE_MS;
65578
+ var UUID_RE;
65526
65579
  var RECONNECT_MAX_MS;
65527
65580
  var PENDING_POLL_INTERVAL_MS;
65528
65581
  var OUTBOUND_DEDUPE_WINDOW_MS;
@@ -65538,6 +65591,7 @@ var init_channel = __esm2({
65538
65591
  "use strict";
65539
65592
  init_abstention();
65540
65593
  init_mls_commit_classify();
65594
+ init_room_protocol();
65541
65595
  await init_libsodium_wrappers();
65542
65596
  await init_dist();
65543
65597
  await init_dist();
@@ -65569,6 +65623,7 @@ var init_channel = __esm2({
65569
65623
  ]);
65570
65624
  POLL_INTERVAL_MS = 6e3;
65571
65625
  RECONNECT_BASE_MS = 1e3;
65626
+ UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
65572
65627
  RECONNECT_MAX_MS = 3e4;
65573
65628
  PENDING_POLL_INTERVAL_MS = 15e3;
65574
65629
  OUTBOUND_DEDUPE_WINDOW_MS = 3e3;
@@ -65740,6 +65795,35 @@ var init_channel = __esm2({
65740
65795
 
65741
65796
  ${text}`;
65742
65797
  }
65798
+ /**
65799
+ * #1161: room attachments whose caption addressed nobody, NOT yet fetched.
65800
+ * The reply gate lives in every consumer of `room_message` (openclaw-entry
65801
+ * and the three native bridges), but its first clause is shared and needs no
65802
+ * identity: a caption with no mention token owes nobody a reply (#1107), so
65803
+ * nobody needs the file yet. Kept per room, newest last, and fetched on the
65804
+ * room's next ADDRESSED turn — the owner attaches, then asks (#1159/#1181).
65805
+ * Hermes does the same (`_defer_room_attachment`).
65806
+ */
65807
+ _deferredRoomAttachments = /* @__PURE__ */ new Map();
65808
+ static DEFERRED_ROOM_ATTACHMENT_MAX = 5;
65809
+ static DEFERRED_ROOM_ATTACHMENT_MS = 60 * 60 * 1e3;
65810
+ _deferRoomAttachment(roomId, info) {
65811
+ const list = this._deferredRoomAttachments.get(roomId) ?? [];
65812
+ list.push({ info, at: Date.now() });
65813
+ while (list.length > _SecureChannel.DEFERRED_ROOM_ATTACHMENT_MAX) list.shift();
65814
+ this._deferredRoomAttachments.set(roomId, list);
65815
+ console.log(
65816
+ `[SecureChannel] room ${roomId.slice(0, 8)}: attachment ${String(info?.filename ?? "file")} deferred \u2014 caption addresses nobody, fetch on the next @-addressed turn (#1161)`
65817
+ );
65818
+ }
65819
+ /** Drain the room's deferred attachments that are still fresh (oldest first). */
65820
+ _takeDeferredRoomAttachments(roomId) {
65821
+ const list = this._deferredRoomAttachments.get(roomId);
65822
+ if (!list?.length) return [];
65823
+ this._deferredRoomAttachments.delete(roomId);
65824
+ const cutoff = Date.now() - _SecureChannel.DEFERRED_ROOM_ATTACHMENT_MS;
65825
+ return list.filter((d22) => d22.at >= cutoff).map((d22) => d22.info);
65826
+ }
65743
65827
  /** In-flight roster-refresh promises (per room) — dedup concurrent refreshes. */
65744
65828
  _roomRosterRefreshInFlight = /* @__PURE__ */ new Map();
65745
65829
  /** Dedup buffer for A2A message IDs (prevents double-delivery via direct + Redis) */
@@ -66835,7 +66919,7 @@ ${text}`;
66835
66919
  */
66836
66920
  sendActivitySpan(spanData) {
66837
66921
  if (!this._ws || this._ws.readyState !== WebSocket2.OPEN) return;
66838
- const pluginVersion = true ? "0.23.39" : "0.0.0-dev";
66922
+ const pluginVersion = true ? "0.23.41" : "0.0.0-dev";
66839
66923
  const agentName = this.config.agentName ?? "Agent";
66840
66924
  const resource = {
66841
66925
  "service.name": "agentvault-agent",
@@ -68773,7 +68857,7 @@ ${text}`;
68773
68857
  agentVersion: this.config.agentVersion ?? "0.0.0",
68774
68858
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
68775
68859
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
68776
- pluginVersion: true ? "0.23.39" : "0.0.0-dev"
68860
+ pluginVersion: true ? "0.23.41" : "0.0.0-dev"
68777
68861
  });
68778
68862
  this._telemetryReporter.startAutoFlush(3e4);
68779
68863
  }
@@ -69097,7 +69181,7 @@ ${text}`;
69097
69181
  agentVersion: this.config.agentVersion ?? "0.0.0",
69098
69182
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
69099
69183
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
69100
- pluginVersion: true ? "0.23.39" : "0.0.0-dev"
69184
+ pluginVersion: true ? "0.23.41" : "0.0.0-dev"
69101
69185
  });
69102
69186
  this._telemetryReporter.startAutoFlush(3e4);
69103
69187
  }
@@ -69312,45 +69396,78 @@ ${text}`;
69312
69396
  const mlsGroup = this._mlsGroups.get(`a2a:${channelId}`);
69313
69397
  if (mlsGroup?.isInitialized) {
69314
69398
  try {
69315
- const kpRes = await fetch(
69316
- `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(participant.hub_id)}`,
69317
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
69318
- );
69319
- if (kpRes.ok) {
69320
- const kpData = await kpRes.json();
69321
- if (kpData.key_package) {
69322
- const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
69323
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
69324
- const { commit, welcome } = await mlsGroup.addMembers([memberKp]);
69325
- if (welcome && this._ws) {
69326
- this._ws.send(JSON.stringify({
69327
- event: "mls_commit",
69328
- data: {
69329
- group_id: entry.mlsGroupId,
69330
- epoch: Number(mlsGroup.epoch),
69331
- payload: Buffer.from(commit).toString("hex")
69332
- }
69333
- }));
69334
- const newDeviceId = participant.device_id || null;
69335
- if (!newDeviceId) {
69336
- console.warn(
69337
- `[SecureChannel] Skipping MLS Welcome to new participant ${participant.hub_address} for A2A ${channelId.slice(0, 8)}: no device_id on participant_joined payload.`
69338
- );
69339
- } else {
69340
- this._ws.send(JSON.stringify({
69341
- event: "mls_welcome",
69342
- data: {
69343
- group_id: entry.mlsGroupId,
69344
- payload: Buffer.from(welcome).toString("hex"),
69345
- target_device_id: newDeviceId,
69346
- a2a_channel_id: channelId,
69347
- target_hub_id: participant.hub_id
69348
- // observability only
69399
+ const newDeviceId = participant.device_id || null;
69400
+ const a2aLabel = `A2A ${channelId.slice(0, 8)} participant_joined`;
69401
+ if (!newDeviceId) {
69402
+ console.warn(
69403
+ `[SecureChannel] ${a2aLabel}: no device_id on the payload for ${participant.hub_address} \u2014 NOT adding (a Welcome could not be addressed)`
69404
+ );
69405
+ } else if (!this._wsIsOpen()) {
69406
+ console.warn(`[SecureChannel] ${a2aLabel}: socket is not OPEN \u2014 NOT advancing the group`);
69407
+ } else {
69408
+ const preHead = await this._readGroupHead(entry.mlsGroupId);
69409
+ const inFlight = preHead.ok && preHead.epoch !== Number(mlsGroup.epoch) ? null : this._reserveCommit(entry.mlsGroupId, a2aLabel);
69410
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
69411
+ console.warn(
69412
+ `[SecureChannel] ${a2aLabel}: server head is at epoch ${preHead.epoch}, we are at ${Number(mlsGroup.epoch)} \u2014 NOT committing (it would be refused); resync catches up first`
69413
+ );
69414
+ await this._catchUpAfterPreflightSkip(entry.mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), a2aLabel);
69415
+ } else if (inFlight) {
69416
+ try {
69417
+ const kpRes = await fetch(
69418
+ `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(participant.hub_id)}`,
69419
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
69420
+ );
69421
+ if (kpRes.ok) {
69422
+ const kpData = await kpRes.json();
69423
+ if (kpData.key_package) {
69424
+ const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
69425
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
69426
+ const stateBefore = mlsGroup.exportState();
69427
+ const { commit, welcome } = await mlsGroup.addMembers([memberKp]);
69428
+ const committedEpoch = Number(mlsGroup.epoch);
69429
+ if (!welcome) {
69430
+ mlsGroup.importState(stateBefore);
69431
+ console.warn(`[SecureChannel] ${a2aLabel}: addMembers produced no Welcome \u2014 rolled back`);
69432
+ } else {
69433
+ const verdict = await this._sendCommitConfirmed({
69434
+ mlsGroup,
69435
+ mlsGroupId: entry.mlsGroupId,
69436
+ label: a2aLabel,
69437
+ commit,
69438
+ epoch: committedEpoch,
69439
+ parent: preHead.ok ? preHead.digest : void 0,
69440
+ memberDeviceIds: this._commitRoster(
69441
+ (entry.participants ?? []).map((p2) => p2.deviceId),
69442
+ [newDeviceId]
69443
+ ),
69444
+ stateBefore,
69445
+ inFlight
69446
+ });
69447
+ if (verdict === "confirmed") {
69448
+ const sent = await this._sendFrameConfirmed({
69449
+ event: "mls_welcome",
69450
+ data: {
69451
+ group_id: entry.mlsGroupId,
69452
+ payload: Buffer.from(welcome).toString("hex"),
69453
+ target_device_id: newDeviceId,
69454
+ a2a_channel_id: channelId,
69455
+ target_hub_id: participant.hub_id
69456
+ // observability only
69457
+ }
69458
+ }, `${a2aLabel} welcome`);
69459
+ await saveMlsState(this.config.dataDir, entry.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
69460
+ if (sent) {
69461
+ console.log(`[SecureChannel] Sent MLS Welcome to new participant ${participant.hub_address} (device ${String(newDeviceId).slice(0, 8)})`);
69462
+ } else {
69463
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome to ${String(newDeviceId).slice(0, 8)} was NOT written \u2014 the participant will request one`);
69464
+ }
69465
+ }
69349
69466
  }
69350
- }));
69351
- await saveMlsState(this.config.dataDir, entry.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
69352
- console.log(`[SecureChannel] Sent MLS Welcome to new participant ${participant.hub_address} (device ${String(newDeviceId).slice(0, 8)})`);
69467
+ }
69353
69468
  }
69469
+ } finally {
69470
+ await this._releaseCommit(entry.mlsGroupId, inFlight, a2aLabel);
69354
69471
  }
69355
69472
  }
69356
69473
  }
@@ -69411,6 +69528,7 @@ ${text}`;
69411
69528
  `[deliver] delivery_result=REJECTED group=${rejectedGroup || "unknown"} detail=${detail}`
69412
69529
  );
69413
69530
  console.error(`[SecureChannel] Server error: ${detail}`);
69531
+ this._noteCommitRefusal(data.data || data);
69414
69532
  await this._handleServerError(data.data || data);
69415
69533
  this.emit("error", new Error(`Server: ${detail}`));
69416
69534
  }
@@ -69712,7 +69830,7 @@ ${text}`;
69712
69830
  try {
69713
69831
  const parsed = JSON.parse(plaintext);
69714
69832
  messageType = parsed.type || "message";
69715
- messageText = parsed.text || plaintext;
69833
+ messageText = parsed.text ?? plaintext;
69716
69834
  if (parsed.attachment) {
69717
69835
  attachmentInfo = parsed.attachment;
69718
69836
  }
@@ -70464,7 +70582,7 @@ ${baseText}`;
70464
70582
  try {
70465
70583
  const parsed = JSON.parse(rawPlaintext);
70466
70584
  messageType = parsed.type || "message";
70467
- messageText = parsed.text || rawPlaintext;
70585
+ messageText = parsed.text ?? rawPlaintext;
70468
70586
  if (parsed.attachment) roomAttachment = parsed.attachment;
70469
70587
  } catch {
70470
70588
  messageType = "message";
@@ -70505,10 +70623,19 @@ ${baseText}`;
70505
70623
  await this._refreshRoomRoster(resolvedRoomId);
70506
70624
  }
70507
70625
  }
70508
- if (roomAttachment) {
70509
- messageText = await this._augmentWithAttachment(roomAttachment, messageText, resolvedRoomId);
70626
+ const addressed = parseMentions(messageText).length > 0;
70627
+ if (roomAttachment && !addressed) {
70628
+ this._deferRoomAttachment(resolvedRoomId, roomAttachment);
70510
70629
  } else {
70511
- messageText = this._withRecentRoomAttachmentNote(resolvedRoomId, messageText);
70630
+ const deferred = addressed ? this._takeDeferredRoomAttachments(resolvedRoomId) : [];
70631
+ for (const info of deferred) {
70632
+ messageText = await this._augmentWithAttachment(info, messageText, resolvedRoomId);
70633
+ }
70634
+ if (roomAttachment) {
70635
+ messageText = await this._augmentWithAttachment(roomAttachment, messageText, resolvedRoomId);
70636
+ } else if (deferred.length === 0) {
70637
+ messageText = this._withRecentRoomAttachmentNote(resolvedRoomId, messageText);
70638
+ }
70512
70639
  }
70513
70640
  const roomMembers = this._persisted?.rooms?.[resolvedRoomId]?.members ?? [];
70514
70641
  const senderMember = roomMembers.find((m22) => m22.deviceId === senderDeviceId);
@@ -70632,6 +70759,12 @@ ${baseText}`;
70632
70759
  const groupId = data.group_id;
70633
70760
  const epoch = typeof data.epoch === "number" ? data.epoch : 0;
70634
70761
  this._noteGroupEpoch(groupId, data.epoch);
70762
+ const held = this._commitInFlight.get(groupId);
70763
+ if (held) {
70764
+ held.frames.push(data);
70765
+ console.log(`[SecureChannel] MLS commit for ${groupId.slice(0, 8)} held (epoch=${epoch}) \u2014 our own commit is awaiting confirmation (#1184)`);
70766
+ return true;
70767
+ }
70635
70768
  const target = this._resolveGroupFamily(groupId);
70636
70769
  if (target) {
70637
70770
  const { managerKey: groupKey, label } = target;
@@ -70864,9 +70997,34 @@ ${baseText}`;
70864
70997
  *
70865
70998
  * Returns the number of requests actually fulfilled.
70866
70999
  */
71000
+ /**
71001
+ * #1226: the roster to submit on a commit frame — the caller's known members,
71002
+ * the devices being admitted, and ALWAYS ourselves — deduplicated, UUIDs
71003
+ * only. Self is non-negotiable: once a roster is non-empty the server
71004
+ * requires the committer in it (#469), and our own head read
71005
+ * (`assert_group_member`) requires it too. So with no device id of our own
71006
+ * this returns `[]` and the frame carries NO roster (the pre-#1226 shape)
71007
+ * rather than a roster that locks us out. Non-UUID entries are dropped:
71008
+ * `known` can come off an inbound Welcome frame, and a malformed id in the
71009
+ * outbound frame is refused by the server (`MEMBER_DEVICE_IDS_MALFORMED`).
71010
+ * @internal exposed for tests
71011
+ */
71012
+ _commitRoster(known, targets) {
71013
+ if (!this._deviceId) return [];
71014
+ const out = [];
71015
+ const seen = /* @__PURE__ */ new Set();
71016
+ for (const id of [...known ?? [], ...targets, this._deviceId]) {
71017
+ if (typeof id !== "string" || !UUID_RE.test(id) || seen.has(id)) continue;
71018
+ seen.add(id);
71019
+ out.push(id);
71020
+ }
71021
+ return out;
71022
+ }
70867
71023
  async _fulfilWelcomeRequests(opts) {
70868
71024
  const { mlsGroup, mlsGroupId, label, welcomeFields, targets } = opts;
70869
71025
  if (targets.length === 0) return 0;
71026
+ const rosterBefore = this._commitRoster(opts.memberDeviceIds, []);
71027
+ const rosterAfter = this._commitRoster(opts.memberDeviceIds, targets.map((t22) => t22.deviceId));
70870
71028
  if (!this._wsIsOpen()) {
70871
71029
  console.warn(
70872
71030
  `[SecureChannel] ${label}: socket is not OPEN \u2014 NOT advancing the group; ${targets.length} request(s) stay pending for the next pull`
@@ -70874,73 +71032,154 @@ ${baseText}`;
70874
71032
  return 0;
70875
71033
  }
70876
71034
  const snapshot = mlsGroup.exportState();
70877
- let parent2 = await this._readGroupHeadDigest(mlsGroupId);
70878
- const { commits, welcome } = await mlsGroup.reAdmitMembers(targets.map((t22) => t22.keyPackage));
70879
- let sentCommits = 0;
70880
- for (const c22 of commits) {
70881
- const ok2 = await this._sendFrameConfirmed(
70882
- {
70883
- event: "mls_commit",
70884
- data: {
70885
- group_id: mlsGroupId,
70886
- // The epoch this commit PRODUCED. After two commits the manager
70887
- // only knows the last one, which is why the result carries them.
70888
- epoch: Number(c22.epoch),
70889
- payload: Buffer.from(c22.commit).toString("hex"),
70890
- ...parent2 ? { parent_digest: parent2 } : {}
70891
- }
70892
- },
70893
- `${label} commit ${sentCommits + 1}/${commits.length}`
70894
- );
70895
- if (!ok2) break;
70896
- parent2 = this._commitDigest(c22.commit);
70897
- sentCommits++;
70898
- }
70899
- if (sentCommits === 0) {
70900
- mlsGroup.importState(snapshot);
70901
- console.warn(
70902
- `[SecureChannel] ${label}: commit was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, nothing fulfilled, requests stay pending`
70903
- );
70904
- return 0;
70905
- }
70906
- await saveMlsState(this.config.dataDir, mlsGroupId, JSON.stringify(mlsGroup.exportState()));
70907
- if (sentCommits < commits.length) {
71035
+ const preHead = await this._readGroupHead(mlsGroupId);
71036
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
70908
71037
  console.warn(
70909
- `[SecureChannel] ${label}: only ${sentCommits}/${commits.length} commits reached the wire \u2014 requests stay PENDING for the next pull`
71038
+ `[SecureChannel] ${label}: server head is at epoch ${preHead.epoch}, we are at ${Number(mlsGroup.epoch)} \u2014 NOT committing (it would be refused, #1184); ${targets.length} request(s) stay pending`
70910
71039
  );
71040
+ await this._catchUpAfterPreflightSkip(mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), label);
70911
71041
  return 0;
70912
71042
  }
70913
- if (!welcome) {
71043
+ let parent2 = preHead.ok ? preHead.digest : void 0;
71044
+ if (this._commitInFlight.has(mlsGroupId)) {
70914
71045
  console.warn(
70915
- `[SecureChannel] ${label}: addMembers produced NO Welcome \u2014 ${targets.length} request(s) left pending rather than marked fulfilled`
71046
+ `[SecureChannel] ${label}: another commit for this group is in flight \u2014 NOT advancing; ${targets.length} request(s) stay pending for the next pull`
70916
71047
  );
70917
71048
  return 0;
70918
71049
  }
70919
- let fulfilled = 0;
70920
- for (const t22 of targets) {
70921
- const sent = await this._sendFrameConfirmed(
70922
- {
70923
- event: "mls_welcome",
70924
- data: {
70925
- target_device_id: t22.deviceId,
70926
- group_id: mlsGroupId,
70927
- ...welcomeFields,
70928
- payload: Buffer.from(welcome).toString("hex")
70929
- }
70930
- },
70931
- `${label} welcome\u2192${t22.deviceId.slice(0, 8)}`
70932
- );
70933
- if (!sent) {
71050
+ const inFlight = { frames: [], sent: [] };
71051
+ this._commitInFlight.set(mlsGroupId, inFlight);
71052
+ try {
71053
+ const { commits, welcome } = await mlsGroup.reAdmitMembers(targets.map((t22) => t22.keyPackage));
71054
+ let sentCommits = 0;
71055
+ let refusedAt = -1;
71056
+ let verdict = "confirmed";
71057
+ for (const c22 of commits) {
71058
+ const ours = this._commitDigest(c22.commit);
71059
+ inFlight.sent.push({
71060
+ epoch: Number(c22.epoch),
71061
+ digest: ours,
71062
+ verified: false,
71063
+ stateBefore: sentCommits === 0 ? snapshot : commits[sentCommits - 1].state
71064
+ });
71065
+ const ok2 = await this._sendFrameConfirmed(
71066
+ {
71067
+ event: "mls_commit",
71068
+ data: {
71069
+ group_id: mlsGroupId,
71070
+ // The epoch this commit PRODUCED. After two commits the manager
71071
+ // only knows the last one, which is why the result carries them.
71072
+ epoch: Number(c22.epoch),
71073
+ payload: Buffer.from(c22.commit).toString("hex"),
71074
+ ...parent2 ? { parent_digest: parent2 } : {},
71075
+ ...(sentCommits === commits.length - 1 ? rosterAfter : rosterBefore).length > 0 ? { member_device_ids: sentCommits === commits.length - 1 ? rosterAfter : rosterBefore } : {}
71076
+ }
71077
+ },
71078
+ `${label} commit ${sentCommits + 1}/${commits.length}`
71079
+ );
71080
+ if (!ok2) {
71081
+ verdict = "unsent";
71082
+ inFlight.sent.pop();
71083
+ break;
71084
+ }
71085
+ verdict = await this._confirmCommitAtHead(mlsGroupId, Number(c22.epoch), ours, inFlight, label);
71086
+ if (verdict === "confirmed") {
71087
+ inFlight.sent[sentCommits].verified = true;
71088
+ } else if (verdict === "unverifiable") {
71089
+ console.warn(
71090
+ `[SecureChannel] ${label}: commit ${sentCommits + 1}/${commits.length} at epoch ${Number(c22.epoch)} could not be verified and was not refused \u2014 proceeding UNCHECKED (#1184)`
71091
+ );
71092
+ } else {
71093
+ refusedAt = sentCommits;
71094
+ break;
71095
+ }
71096
+ parent2 = ours;
71097
+ sentCommits++;
71098
+ }
71099
+ const cutFromRefusal = () => {
71100
+ const r22 = inFlight.refusal;
71101
+ if (r22 === void 0) return refusedAt;
71102
+ return refusedAt === -1 ? r22.from : Math.min(refusedAt, r22.from);
71103
+ };
71104
+ const rollBackTo = async (cut2, stage, persisted) => {
71105
+ const why = inFlight.refusal?.detail ?? verdict.toUpperCase();
71106
+ mlsGroup.importState(inFlight.sent[cut2].stateBefore);
71107
+ sentCommits = cut2;
70934
71108
  console.warn(
70935
- `[SecureChannel] ${label}: Welcome for ${t22.deviceId.slice(0, 8)} was NOT written \u2014 leaving the request PENDING so the next pull retries it`
71109
+ `[SecureChannel] ${label}: commit ${cut2 + 1}/${commits.length} ${stage} \u2014 "${why}" \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}` + (cut2 === 0 ? ", nothing" : ` (after commit ${cut2}), only that`) + ` persisted, ${targets.length} request(s) stay pending`
70936
71110
  );
70937
- continue;
71111
+ if (persisted) await saveMlsState(this.config.dataDir, mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71112
+ };
71113
+ let cut = cutFromRefusal();
71114
+ if (cut !== -1) {
71115
+ await rollBackTo(cut, "was refused by the server", false);
71116
+ if (sentCommits === 0) return 0;
71117
+ }
71118
+ if (sentCommits === 0) {
71119
+ mlsGroup.importState(snapshot);
71120
+ console.warn(
71121
+ `[SecureChannel] ${label}: commit was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, nothing fulfilled, requests stay pending`
71122
+ );
71123
+ return 0;
71124
+ }
71125
+ await saveMlsState(this.config.dataDir, mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71126
+ cut = cutFromRefusal();
71127
+ if (cut !== -1 && cut < sentCommits) {
71128
+ await rollBackTo(cut, "was refused by the server after the window (during persist)", true);
71129
+ return 0;
70938
71130
  }
70939
- if (await this._postFulfilWelcome(mlsGroupId, t22.requestId, `${label} ${t22.deviceId.slice(0, 8)}`)) {
70940
- fulfilled++;
71131
+ if (sentCommits < commits.length) {
71132
+ console.warn(
71133
+ `[SecureChannel] ${label}: only ${sentCommits}/${commits.length} commits were confirmed \u2014 requests stay PENDING for the next pull`
71134
+ );
71135
+ return 0;
71136
+ }
71137
+ if (!welcome) {
71138
+ console.warn(
71139
+ `[SecureChannel] ${label}: addMembers produced NO Welcome \u2014 ${targets.length} request(s) left pending rather than marked fulfilled`
71140
+ );
71141
+ return 0;
71142
+ }
71143
+ let fulfilled = 0;
71144
+ for (const t22 of targets) {
71145
+ const sent = await this._sendFrameConfirmed(
71146
+ {
71147
+ event: "mls_welcome",
71148
+ data: {
71149
+ target_device_id: t22.deviceId,
71150
+ group_id: mlsGroupId,
71151
+ ...welcomeFields,
71152
+ payload: Buffer.from(welcome).toString("hex")
71153
+ }
71154
+ },
71155
+ `${label} welcome\u2192${t22.deviceId.slice(0, 8)}`
71156
+ );
71157
+ if (!sent) {
71158
+ console.warn(
71159
+ `[SecureChannel] ${label}: Welcome for ${t22.deviceId.slice(0, 8)} was NOT written \u2014 leaving the request PENDING so the next pull retries it`
71160
+ );
71161
+ continue;
71162
+ }
71163
+ cut = cutFromRefusal();
71164
+ if (cut !== -1 && cut < sentCommits) {
71165
+ await rollBackTo(cut, "was refused by the server after the window (during the Welcome)", true);
71166
+ return fulfilled;
71167
+ }
71168
+ if (await this._postFulfilWelcome(mlsGroupId, t22.requestId, `${label} ${t22.deviceId.slice(0, 8)}`)) {
71169
+ fulfilled++;
71170
+ }
71171
+ }
71172
+ return fulfilled;
71173
+ } finally {
71174
+ this._commitInFlight.delete(mlsGroupId);
71175
+ for (const frame of inFlight.frames) {
71176
+ try {
71177
+ await this._handleMlsCommit(frame);
71178
+ } catch (err) {
71179
+ console.error(`[SecureChannel] ${label}: replaying a held MLS commit failed:`, err);
71180
+ }
70941
71181
  }
70942
71182
  }
70943
- return fulfilled;
70944
71183
  }
70945
71184
  /**
70946
71185
  * Resolve an MLS group id to the family that owns it.
@@ -70981,31 +71220,364 @@ ${baseText}`;
70981
71220
  return this._ws?.readyState === 1;
70982
71221
  }
70983
71222
  /** SHA-256 hex of a commit's bytes — its identity on the server (#1175/#1177). */
71223
+ /**
71224
+ * #1225: send ONE commit over the socket and wait for the server's verdict,
71225
+ * with the #1184 machinery — an in-flight record (so a `… commit rejected`
71226
+ * frame is correlated to it and a concurrent commit for the group is held
71227
+ * and replayed), the head poll, and rollback. The three A2A commit sites
71228
+ * (`a2a_participant_joined`, the `/distribute` WS fallback, `_foundA2AGroup`)
71229
+ * used a raw `ws.send` and treated "the socket took it" as "the server
71230
+ * stored it" — two of them then PERSISTED a state the server never saw.
71231
+ *
71232
+ * Returns the verdict. On `refused` / `unsent` the manager has been restored
71233
+ * to `stateBefore` and nothing must be persisted or minted from it.
71234
+ * `unverifiable` (head unreadable on every try AND no refusal) proceeds
71235
+ * UNCHECKED, the same deliberate choice as the fulfil site.
71236
+ */
71237
+ /**
71238
+ * #1225 (review F1): reserve the single in-flight slot for a group. The
71239
+ * record is what `_noteCommitRefusal` correlates a refusal to and what
71240
+ * `_handleMlsCommit` holds concurrent socket commits behind; a second run on
71241
+ * the same group would clobber both (measured: two overlapping joins → two
71242
+ * commits claiming one epoch, one Welcome instead of two, the manager AHEAD
71243
+ * of the server). Taken BEFORE the commit is generated; released by
71244
+ * `_releaseCommit` after the last step that depends on it.
71245
+ */
71246
+ /**
71247
+ * A pre-flight skip must not be a dead end. The skip happens because the
71248
+ * server's head is somewhere else; before this the group "caught up through
71249
+ * the normal divergence path", which only runs when a message for the group
71250
+ * arrives — so a group nobody writes to stayed diverged and its pending
71251
+ * Welcome requests were never fulfilled (named in PR #1227). When the server
71252
+ * is AHEAD, replay the missing commits now so the next pull can commit; when
71253
+ * WE are ahead there is nothing to replay (the fork-ahead direction, #972).
71254
+ */
71255
+ async _catchUpAfterPreflightSkip(mlsGroupId, serverEpoch, localEpoch, label) {
71256
+ if (serverEpoch < localEpoch) {
71257
+ console.warn(`[SecureChannel] ${label}: we are AHEAD of the server (${localEpoch} > ${serverEpoch}) \u2014 nothing to replay`);
71258
+ return;
71259
+ }
71260
+ const fam = this._resolveGroupFamily(mlsGroupId);
71261
+ if (!fam) return;
71262
+ try {
71263
+ const caughtUp = await this._resyncOnDivergence(fam.managerKey, mlsGroupId);
71264
+ console.log(`[SecureChannel] ${label}: catch-up after pre-flight skip ${caughtUp ? "replayed the missing commits" : "could not replay"}`);
71265
+ } catch (err) {
71266
+ console.warn(`[SecureChannel] ${label}: catch-up after pre-flight skip failed:`, err);
71267
+ }
71268
+ }
71269
+ _reserveCommit(groupId, label) {
71270
+ if (this._commitInFlight.has(groupId)) {
71271
+ console.warn(
71272
+ `[SecureChannel] ${label}: another commit for group ${groupId.slice(0, 8)} is in flight \u2014 NOT advancing the group (a Welcome can be requested again)`
71273
+ );
71274
+ return null;
71275
+ }
71276
+ const rec = { frames: [], sent: [] };
71277
+ this._commitInFlight.set(groupId, rec);
71278
+ return rec;
71279
+ }
71280
+ /** Release the slot taken by `_reserveCommit` and replay the socket commits held meanwhile. */
71281
+ async _releaseCommit(groupId, rec, label) {
71282
+ if (this._commitInFlight.get(groupId) === rec) this._commitInFlight.delete(groupId);
71283
+ for (const frame of rec.frames) {
71284
+ try {
71285
+ await this._handleMlsCommit(frame);
71286
+ } catch (err) {
71287
+ console.error(`[SecureChannel] ${label}: replaying a held MLS commit failed:`, err);
71288
+ }
71289
+ }
71290
+ }
71291
+ /**
71292
+ * #1225: send ONE commit over the socket and wait for the server's verdict
71293
+ * with the #1184 machinery (refusal frame correlated through the reserved
71294
+ * in-flight record, head poll). The three A2A commit sites
71295
+ * (`a2a_participant_joined`, the `/distribute` WS fallback, `_foundA2AGroup`)
71296
+ * used a raw `ws.send` and treated "the socket took it" as "the server
71297
+ * stored it" — two of them then PERSISTED a state the server never saw.
71298
+ *
71299
+ * Only `confirmed` proceeds. `unverifiable` (head unreadable on every try,
71300
+ * no refusal) is a ROLLBACK here, unlike the fulfil site: that site proceeds
71301
+ * UNCHECKED because 79 of 80 production rooms 403 the head read on an empty
71302
+ * roster; an A2A head read admits any active participant (observer
71303
+ * fallback), so five failed reads there mean an outage, not a routine 403.
71304
+ * On anything but `confirmed` the manager is back at `stateBefore`.
71305
+ */
71306
+ async _sendCommitConfirmed(opts) {
71307
+ const { mlsGroup, mlsGroupId, label, commit, epoch, parent: parent2, memberDeviceIds, stateBefore, inFlight } = opts;
71308
+ const ours = this._commitDigest(commit);
71309
+ inFlight.sent.push({ epoch, digest: ours, verified: false, stateBefore });
71310
+ const ok2 = await this._sendFrameConfirmed(
71311
+ {
71312
+ event: "mls_commit",
71313
+ data: {
71314
+ group_id: mlsGroupId,
71315
+ epoch,
71316
+ payload: Buffer.from(commit).toString("hex"),
71317
+ ...parent2 ? { parent_digest: parent2 } : {},
71318
+ ...memberDeviceIds && memberDeviceIds.length > 0 ? { member_device_ids: memberDeviceIds } : {}
71319
+ }
71320
+ },
71321
+ `${label} commit`
71322
+ );
71323
+ if (!ok2) {
71324
+ inFlight.sent.pop();
71325
+ mlsGroup.importState(stateBefore);
71326
+ console.warn(
71327
+ `[SecureChannel] ${label}: commit at epoch ${epoch} was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}`
71328
+ );
71329
+ return "unsent";
71330
+ }
71331
+ const verdict = await this._confirmCommitAtHead(mlsGroupId, epoch, ours, inFlight, label);
71332
+ if (inFlight.refusal === void 0 && verdict === "confirmed") {
71333
+ inFlight.sent[inFlight.sent.length - 1].verified = true;
71334
+ return "confirmed";
71335
+ }
71336
+ const why = inFlight.refusal?.detail ?? verdict.toUpperCase();
71337
+ mlsGroup.importState(stateBefore);
71338
+ console.warn(
71339
+ `[SecureChannel] ${label}: commit at epoch ${epoch} was ${verdict === "unverifiable" ? "not verified (head unreadable)" : "refused by the server"} \u2014 "${why}" \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, nothing persisted`
71340
+ );
71341
+ return "refused";
71342
+ }
70984
71343
  _commitDigest(bytes) {
70985
71344
  return createHash("sha256").update(bytes).digest("hex");
70986
71345
  }
70987
71346
  /**
70988
71347
  * #1177: the digest of the commit at the server's head, or undefined.
70989
71348
  *
70990
- * Undefined covers "no head yet", "older backend", AND "could not read" —
70991
- * deliberately the same value. The commit is sent either way: the server
70992
- * skips the parent check for an ABSENT field and refuses a MALFORMED one,
70993
- * so a read failure must degrade to "unchecked", never to "blocked" (a
70994
- * rescue that cannot run is the 2026-09-04 lockout) and never to `null`.
71349
+ * Undefined covers "no head yet" (a pruned group: epoch known, digest NULL —
71350
+ * 29 in production) AND "could not read" — deliberately the same value. The
71351
+ * commit is sent either way: the server skips the parent check for an
71352
+ * ABSENT field and refuses a MALFORMED one, so a read failure must degrade
71353
+ * to "unchecked", never to "blocked" (a rescue that cannot run is the
71354
+ * 2026-09-04 lockout) and never to `null`.
70995
71355
  */
70996
71356
  async _readGroupHeadDigest(groupId) {
71357
+ const head = await this._readGroupHead(groupId);
71358
+ return head.ok ? head.digest : void 0;
71359
+ }
71360
+ /**
71361
+ * #1184: the server's head — its `current_epoch` and the digest of the commit
71362
+ * that produced it.
71363
+ *
71364
+ * - `{ ok: true, epoch, digest? }` the server described its head. `digest`
71365
+ * is absent on a pruned group (NULL
71366
+ * `last_commit_digest`).
71367
+ * - `{ ok: false, why }` the read failed: a non-2xx (the 403
71368
+ * `assert_group_member` returns on an
71369
+ * EMPTY roster — 79 of 80 production
71370
+ * rooms — or a 5xx), a timeout, or a body
71371
+ * with no `current_epoch`. Callers may
71372
+ * retry; a failure is never a verdict.
71373
+ *
71374
+ * `current_epoch` is a required field of `MLSGroupResponse`, so "200 with
71375
+ * no head" is not a shape any deployed backend produces; it is folded into
71376
+ * `ok: false` rather than given a branch of its own (the first cut of #1184
71377
+ * had one, and it was the only branch the suite exercised).
71378
+ */
71379
+ async _readGroupHead(groupId) {
70997
71380
  try {
70998
71381
  const res = await fetch(`${this.config.apiUrl}/api/v1/mls/groups/${groupId}`, {
70999
- headers: { Authorization: `Bearer ${this._deviceJwt}` }
71382
+ headers: { Authorization: `Bearer ${this._deviceJwt}` },
71383
+ // The confirm loop holds `_deliveryPulling`; a black-holed read must
71384
+ // not hold it for undici's 300 s default. A timeout is a failed read.
71385
+ signal: AbortSignal.timeout(_SecureChannel.HEAD_READ_TIMEOUT_MS)
71000
71386
  });
71001
- if (!res.ok) return void 0;
71387
+ if (!res.ok) return { ok: false, why: `HTTP ${res.status}` };
71002
71388
  const head = await res.json();
71003
- const d22 = head?.last_commit_digest;
71004
- return typeof d22 === "string" && /^[0-9a-f]{64}$/.test(d22) ? d22 : void 0;
71005
- } catch {
71006
- return void 0;
71389
+ if (typeof head?.current_epoch !== "number") return { ok: false, why: "no current_epoch in body" };
71390
+ const d22 = head.last_commit_digest;
71391
+ return { ok: true, epoch: head.current_epoch, digest: typeof d22 === "string" && /^[0-9a-f]{64}$/.test(d22) ? d22 : void 0 };
71392
+ } catch (err) {
71393
+ return { ok: false, why: err instanceof Error ? err.name : String(err) };
71007
71394
  }
71008
71395
  }
71396
+ /**
71397
+ * #1184: after each read of the head, how long to wait before the next.
71398
+ * The web's schedule (`lib/mls-commit-confirm.ts`) plus one immediate read:
71399
+ * five reads, ~3.75 s, no resend — an MLS commit cannot be regenerated. The
71400
+ * immediate read catches the common case where the server stored the frame
71401
+ * before the GET lands. Instance-level so tests can run the decision logic
71402
+ * without the clock; an empty schedule still reads once (`_confirmCommitAtHead`).
71403
+ */
71404
+ _commitConfirmDelaysMs = [0, 250, 500, 1e3, 2e3];
71405
+ static HEAD_READ_TIMEOUT_MS = 5e3;
71406
+ /**
71407
+ * #1184: groups with a commit of OURS between "built" and "confirmed or rolled
71408
+ * back". Each record holds the `mls_commit` frames the socket delivered for
71409
+ * that group meanwhile — before the confirm loop that window was
71410
+ * microseconds; now it is up to ~3.75 s, and a commit applied to our
71411
+ * unconfirmed local state would be lost by the rollback (in memory) after
71412
+ * being persisted (on disk). Held frames are replayed, in order, once the
71413
+ * group is back on a real state. The record also carries the server's
71414
+ * REFUSAL, when one arrives on the socket (`_noteCommitRefusal`), and a
71415
+ * `wake` the confirm loop installs so a refusal ends its wait at once.
71416
+ */
71417
+ _commitInFlight = /* @__PURE__ */ new Map();
71418
+ /** #1184: a pull was requested while one was running — run once more after. */
71419
+ _deliveryPullRequested = false;
71420
+ /**
71421
+ * #1184: an `error` frame naming a group we have a commit in flight for, with
71422
+ * a `… commit rejected` detail, is the server's refusal of one of those
71423
+ * commits — every rejection the `mls_commit` WS handler sends (malformed
71424
+ * parent, PARENT_MISMATCH, EPOCH_CONFLICT, not-a-member, no-participants)
71425
+ * ends with those words and carries `group_id` (pinned by
71426
+ * `tests/test_1184_commit_reject_frame_contract.py`). It is sent on OUR
71427
+ * socket after the server processed OUR frame, so it is deterministic in a
71428
+ * way the head poll is not, and it is the only refusal signal on a group
71429
+ * whose head we cannot read (403).
71430
+ *
71431
+ * WHICH commit, and what else the frame proves (re-review of #1227):
71432
+ * - EPOCH_CONFLICT carries `expected_epoch` (the epoch we claimed to build
71433
+ * on) and `current_epoch` (the server's); PARENT_MISMATCH carries
71434
+ * `current_epoch` (the head, which equalled our claim or the epoch check
71435
+ * would have fired first) and `head_digest`. The refused commit is the
71436
+ * one built on that epoch. A frame naming an epoch none of our in-flight
71437
+ * commits claimed is a refusal of some EARLIER attempt — ignored.
71438
+ * - the server's `current_epoch` bounds our earlier commits too: any of
71439
+ * ours ABOVE it did not land.
71440
+ * - `head_digest` at `current_epoch` is our commit at that epoch → that one
71441
+ * positively LANDED; someone else's → ours at that epoch did not.
71442
+ * - the un-numbered shapes refuse all of ours alike: the cut is the first
71443
+ * commit the head poll has not positively confirmed.
71444
+ * Recorded as the index of the first commit shown not to hold; the fulfil
71445
+ * path honours it whenever it arrives. A frame for a group with nothing in
71446
+ * flight is somebody else's business.
71447
+ */
71448
+ _noteCommitRefusal(payload) {
71449
+ const groupId = typeof payload?.group_id === "string" ? payload.group_id : void 0;
71450
+ const detail = typeof payload?.detail === "string" ? payload.detail : "";
71451
+ if (!groupId || !detail.endsWith("commit rejected")) return;
71452
+ const inFlight = this._commitInFlight.get(groupId);
71453
+ if (!inFlight) return;
71454
+ const num = (v22) => typeof v22 === "number" && Number.isFinite(v22) ? v22 : void 0;
71455
+ const current = num(payload.current_epoch);
71456
+ const claimed = num(payload.expected_epoch) ?? current;
71457
+ const headDigest = typeof payload.head_digest === "string" ? payload.head_digest : void 0;
71458
+ const sent = inFlight.sent;
71459
+ const tag = `[SecureChannel] refusal for ${groupId.slice(0, 8)} ("${detail}")`;
71460
+ let from = -1;
71461
+ if (claimed !== void 0) {
71462
+ from = sent.findIndex((c22) => c22.epoch === claimed + 1);
71463
+ if (from === -1) {
71464
+ console.warn(`${tag} names epoch ${claimed + 1}, which no commit in flight claimed \u2014 an earlier attempt's; ignored`);
71465
+ return;
71466
+ }
71467
+ }
71468
+ if (current !== void 0) {
71469
+ const above = sent.findIndex((c22) => c22.epoch > current && !c22.verified);
71470
+ if (above !== -1 && (from === -1 || above < from)) from = above;
71471
+ }
71472
+ if (headDigest !== void 0 && current !== void 0) {
71473
+ const at = sent.findIndex((c22) => c22.epoch === current);
71474
+ if (at !== -1) {
71475
+ if (sent[at].digest === headDigest) {
71476
+ sent[at].verified = true;
71477
+ } else if (from === -1 || at < from) {
71478
+ from = at;
71479
+ }
71480
+ }
71481
+ }
71482
+ if (from === -1) from = sent.findIndex((c22) => !c22.verified);
71483
+ if (from === -1 || sent[from].verified) {
71484
+ console.warn(`${tag} contradicts a head read that showed our commit \u2014 stale; ignored`);
71485
+ return;
71486
+ }
71487
+ if (inFlight.refusal !== void 0 && inFlight.refusal.from <= from) return;
71488
+ inFlight.refusal = { detail, from };
71489
+ inFlight.wake?.();
71490
+ }
71491
+ /**
71492
+ * #1184: a commit is CONFIRMED when the server's head shows OUR digest at OUR
71493
+ * epoch — never when the socket took the bytes (#1015 covers only that). The
71494
+ * server sends no ack for a stored commit, so, like the web, we read the
71495
+ * head back; but it DOES send a refusal on the socket (`_noteCommitRefusal`),
71496
+ * and that is checked first, before every read and during every wait.
71497
+ *
71498
+ * confirmed head.epoch === ours && head.digest === ours
71499
+ * conflict the server refused ours on the socket, OR the head is at
71500
+ * our epoch with ANOTHER digest, OR already past us
71501
+ * unconfirmed the head was READ (at least once) but never reached our
71502
+ * epoch within the window — the server described its state
71503
+ * and ours is not in it
71504
+ * unverifiable the head could not be read on ANY try (403 on an empty
71505
+ * roster, an outage) and no refusal arrived — or it is at
71506
+ * our epoch but keeps no digest (a pruned group). Nothing
71507
+ * can be decided on; the caller proceeds UNCHECKED (#1177's
71508
+ * rule: a rescue that cannot run is the 2026-09-04 lockout)
71509
+ *
71510
+ * The first cut returned `unverifiable` only for a body with no
71511
+ * `current_epoch`, which no deployed backend produces, and rolled back on
71512
+ * every real read failure — the opposite of the rule it stated.
71513
+ */
71514
+ async _confirmCommitAtHead(groupId, epoch, ours, inFlight, label) {
71515
+ const refused = () => {
71516
+ if (inFlight.refusal === void 0) return void 0;
71517
+ console.warn(`[SecureChannel] ${label}: server refused our commit at epoch ${epoch} \u2014 "${inFlight.refusal.detail}"`);
71518
+ return "conflict";
71519
+ };
71520
+ let lastSeen;
71521
+ let described = false;
71522
+ let lastFailure = "";
71523
+ const delays = this._commitConfirmDelaysMs.length > 0 ? this._commitConfirmDelaysMs : [0];
71524
+ for (const delay of delays) {
71525
+ if (delay > 0) {
71526
+ await new Promise((resolve32) => {
71527
+ const timer = setTimeout(() => {
71528
+ inFlight.wake = void 0;
71529
+ resolve32();
71530
+ }, delay);
71531
+ inFlight.wake = () => {
71532
+ clearTimeout(timer);
71533
+ inFlight.wake = void 0;
71534
+ resolve32();
71535
+ };
71536
+ });
71537
+ }
71538
+ const early = refused();
71539
+ if (early) return early;
71540
+ const head = await this._readGroupHead(groupId);
71541
+ const duringRead = refused();
71542
+ if (duringRead) return duringRead;
71543
+ if (!head.ok) {
71544
+ lastFailure = head.why;
71545
+ continue;
71546
+ }
71547
+ described = true;
71548
+ lastSeen = head.epoch;
71549
+ if (head.epoch === epoch) {
71550
+ if (head.digest === ours) return "confirmed";
71551
+ if (head.digest === void 0) return "unverifiable";
71552
+ console.warn(
71553
+ `[SecureChannel] ${label}: head at epoch ${epoch} is NOT our commit (${head.digest.slice(0, 12)}\u2026 vs ours ${ours.slice(0, 12)}\u2026) \u2014 ours was refused`
71554
+ );
71555
+ return "conflict";
71556
+ }
71557
+ if (head.epoch > epoch) {
71558
+ console.warn(`[SecureChannel] ${label}: head already at epoch ${head.epoch}, past our ${epoch} \u2014 ours was refused`);
71559
+ return "conflict";
71560
+ }
71561
+ }
71562
+ const late2 = refused();
71563
+ if (late2) return late2;
71564
+ if (!described && !this._wsIsOpen()) {
71565
+ console.warn(
71566
+ `[SecureChannel] ${label}: the socket closed during the confirm window and the head could not be read \u2014 a refusal of commit at epoch ${epoch} may have been lost; treating as refused`
71567
+ );
71568
+ return "unconfirmed";
71569
+ }
71570
+ if (!described) {
71571
+ console.warn(
71572
+ `[SecureChannel] ${label}: could not read the head on any of ${delays.length} tries (last: ${lastFailure}) and the server sent no refusal \u2014 cannot verify commit at epoch ${epoch}`
71573
+ );
71574
+ return "unverifiable";
71575
+ }
71576
+ console.warn(
71577
+ `[SecureChannel] ${label}: commit at epoch ${epoch} never appeared at the head (last seen ${lastSeen}) \u2014 treating as refused`
71578
+ );
71579
+ return "unconfirmed";
71580
+ }
71009
71581
  /**
71010
71582
  * #1015: write one frame and report whether the socket took it.
71011
71583
  *
@@ -71526,7 +72098,11 @@ ${baseText}`;
71526
72098
  * Called on WS connect, on mls_delivery ping, and every 30s heartbeat.
71527
72099
  */
71528
72100
  async _pullDeliveryQueue() {
71529
- if (!this._deviceId || !this._deviceJwt || this._deliveryPulling) return;
72101
+ if (!this._deviceId || !this._deviceJwt) return;
72102
+ if (this._deliveryPulling) {
72103
+ this._deliveryPullRequested = true;
72104
+ return;
72105
+ }
71530
72106
  this._deliveryPulling = true;
71531
72107
  try {
71532
72108
  const res = await fetch(
@@ -71717,7 +72293,9 @@ ${baseText}`;
71717
72293
  mlsGroupId: roomState.mlsGroupId,
71718
72294
  label: `room ${roomId.slice(0, 8)}`,
71719
72295
  welcomeFields: { room_id: roomId },
71720
- targets: roomTargets
72296
+ targets: roomTargets,
72297
+ memberDeviceIds: (roomState.members ?? []).map((m22) => m22.deviceId)
72298
+ // #1226
71721
72299
  });
71722
72300
  if (done > 0) {
71723
72301
  console.log(
@@ -71772,7 +72350,9 @@ ${baseText}`;
71772
72350
  mlsGroupId: entry.mlsGroupId,
71773
72351
  label: `shared group ${gid.slice(0, 8)}`,
71774
72352
  welcomeFields: { conversation_group_id: gid },
71775
- targets: sharedTargets
72353
+ targets: sharedTargets,
72354
+ memberDeviceIds: entry.memberDeviceIds ?? []
72355
+ // #1226
71776
72356
  });
71777
72357
  if (done > 0) {
71778
72358
  console.log(`[SecureChannel] Batched Welcome for ${done}/${validReqs.length} devices in shared group ${gid.slice(0, 8)} (epoch=${mlsGroup.epoch})`);
@@ -71786,7 +72366,9 @@ ${baseText}`;
71786
72366
  mlsGroupId: entry.mlsGroupId,
71787
72367
  label: `shared group ${gid.slice(0, 8)}`,
71788
72368
  welcomeFields: { conversation_group_id: gid },
71789
- targets: [target]
72369
+ targets: [target],
72370
+ memberDeviceIds: entry.memberDeviceIds ?? []
72371
+ // #1226
71790
72372
  });
71791
72373
  if (done > 0) {
71792
72374
  console.log(`[SecureChannel] Individual Welcome for ${target.deviceId.slice(0, 8)} in shared group ${gid.slice(0, 8)}`);
@@ -71833,7 +72415,11 @@ ${baseText}`;
71833
72415
  requestId: req.id,
71834
72416
  deviceId: req.requesting_device_id,
71835
72417
  keyPackage: memberKp
71836
- }]
72418
+ }],
72419
+ // #1226: a 1:1 roster is [self, owner] — the web's shape too.
72420
+ memberDeviceIds: [this._persisted?.sessions?.[convId]?.ownerDeviceId].filter(
72421
+ (d22) => typeof d22 === "string"
72422
+ )
71837
72423
  });
71838
72424
  if (done > 0) {
71839
72425
  console.log(`[SecureChannel] Fulfilled Welcome for ${req.requesting_device_id.slice(0, 8)} in conv ${convId.slice(0, 8)}`);
@@ -71891,192 +72477,8 @@ ${baseText}`;
71891
72477
  console.log(`[SecureChannel] ${pending.length} pending A2A Welcome requests for channel ${chId.slice(0, 8)}`);
71892
72478
  for (const req of pending) {
71893
72479
  try {
71894
- const kpRes = await fetch(
71895
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
71896
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71897
- );
71898
- if (!kpRes.ok) continue;
71899
- const kpData = await kpRes.json();
71900
- const kpHex = kpData[req.requesting_device_id];
71901
- if (!kpHex) continue;
71902
- const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
71903
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
71904
- console.log(`[SecureChannel] A2A addMembers for ${req.requesting_device_id.slice(0, 8)} group=${chState.mlsGroupId.slice(0, 8)} epoch=${mlsGroup.epoch}`);
71905
- let parentDigest = await this._readGroupHeadDigest(chState.mlsGroupId);
71906
- let commit;
71907
- let welcome;
71908
- try {
71909
- const result = await mlsGroup.addMembers([memberKp]);
71910
- commit = result.commit;
71911
- welcome = result.welcome;
71912
- } catch (addErr) {
71913
- const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
71914
- if (errMsg.includes("already in the group")) {
71915
- console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
71916
- const preRemoveState = JSON.stringify(mlsGroup.exportState());
71917
- let removeCommitPublished = false;
71918
- try {
71919
- const identityBytes = new TextEncoder().encode(req.requesting_device_id);
71920
- const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
71921
- if (leafIndex === null) {
71922
- console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
71923
- continue;
71924
- }
71925
- const removeResult = await mlsGroup.removeMember(leafIndex);
71926
- try {
71927
- const removeResp = await fetch(
71928
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71929
- {
71930
- method: "POST",
71931
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71932
- body: JSON.stringify({
71933
- group_id: chState.mlsGroupId,
71934
- device_id: this._deviceId,
71935
- commit: Buffer.from(removeResult.commit).toString("hex"),
71936
- commit_epoch: Number(mlsGroup.epoch),
71937
- ...parentDigest ? { parent_digest: parentDigest } : {}
71938
- })
71939
- }
71940
- );
71941
- if (removeResp.ok) {
71942
- removeCommitPublished = true;
71943
- parentDigest = this._commitDigest(removeResult.commit);
71944
- } else {
71945
- const detail = await removeResp.text().catch(() => "");
71946
- console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
71947
- }
71948
- } catch (distErr) {
71949
- console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
71950
- }
71951
- if (!removeCommitPublished) {
71952
- mlsGroup.importState(JSON.parse(preRemoveState));
71953
- continue;
71954
- }
71955
- const kpRes2 = await fetch(
71956
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
71957
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71958
- );
71959
- if (kpRes2.ok) {
71960
- const kpData2 = await kpRes2.json();
71961
- const kpHex2 = kpData2[req.requesting_device_id];
71962
- if (kpHex2) {
71963
- const kpBytes2 = new Uint8Array(Buffer.from(kpHex2, "hex"));
71964
- const memberKp2 = MLSGroupManager.deserializeKeyPackage(kpBytes2);
71965
- const result2 = await mlsGroup.addMembers([memberKp2]);
71966
- commit = result2.commit;
71967
- welcome = result2.welcome;
71968
- } else {
71969
- console.log(`[SecureChannel] A2A re-add: no fresh KeyPackage for ${req.requesting_device_id.slice(0, 8)}`);
71970
- continue;
71971
- }
71972
- } else {
71973
- console.log(`[SecureChannel] A2A re-add: KeyPackage fetch failed (${kpRes2.status})`);
71974
- continue;
71975
- }
71976
- } catch (readdErr) {
71977
- console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
71978
- if (!removeCommitPublished) {
71979
- try {
71980
- mlsGroup.importState(JSON.parse(preRemoveState));
71981
- } catch {
71982
- }
71983
- }
71984
- continue;
71985
- }
71986
- } else {
71987
- console.log(`[SecureChannel] A2A addMembers FAILED: ${errMsg}`);
71988
- continue;
71989
- }
71990
- }
71991
- if (!welcome) {
71992
- console.warn(`[SecureChannel] A2A addMembers produced no Welcome for ${req.requesting_device_id.slice(0, 8)}`);
71993
- continue;
71994
- }
71995
- const commitHex = Buffer.from(commit).toString("hex");
71996
- const welcomeHex = Buffer.from(welcome).toString("hex");
71997
- let distributed = false;
71998
- const updatedMembers = [this._deviceId, req.requesting_device_id];
71999
- try {
72000
- const distResp = await fetch(
72001
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72002
- {
72003
- method: "POST",
72004
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72005
- body: JSON.stringify({
72006
- group_id: chState.mlsGroupId,
72007
- device_id: this._deviceId,
72008
- commit: commitHex,
72009
- commit_epoch: Number(mlsGroup.epoch),
72010
- welcomes: [{ target_device_id: req.requesting_device_id, payload: welcomeHex }],
72011
- member_device_ids: updatedMembers,
72012
- ...parentDigest ? { parent_digest: parentDigest } : {}
72013
- })
72014
- }
72015
- );
72016
- if (distResp.ok) {
72017
- distributed = true;
72018
- } else {
72019
- const detail = await distResp.text().catch(() => "");
72020
- console.warn(`[SecureChannel] A2A distribute failed (${distResp.status}): ${detail}`);
72021
- }
72022
- } catch (distErr) {
72023
- console.warn(`[SecureChannel] A2A distribute network error:`, distErr);
72024
- }
72025
- if (!distributed && this._wsIsOpen()) {
72026
- const a2aLabel = `A2A ${chId.slice(0, 8)}`;
72027
- const commitSent = await this._sendFrameConfirmed({
72028
- event: "mls_commit",
72029
- data: {
72030
- group_id: chState.mlsGroupId,
72031
- epoch: Number(mlsGroup.epoch),
72032
- payload: commitHex,
72033
- ...parentDigest ? { parent_digest: parentDigest } : {}
72034
- }
72035
- }, `${a2aLabel} commit`);
72036
- const welcomeSent = commitSent && await this._sendFrameConfirmed({
72037
- event: "mls_welcome",
72038
- data: {
72039
- target_device_id: req.requesting_device_id,
72040
- group_id: chState.mlsGroupId,
72041
- a2a_channel_id: chId,
72042
- payload: welcomeHex
72043
- }
72044
- }, `${a2aLabel} welcome`);
72045
- if (!welcomeSent) {
72046
- console.warn(`[SecureChannel] ${a2aLabel}: Welcome frames were NOT written \u2014 leaving the request pending`);
72047
- continue;
72048
- }
72049
- try {
72050
- await fetch(
72051
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72052
- {
72053
- method: "POST",
72054
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72055
- body: JSON.stringify({
72056
- group_id: chState.mlsGroupId,
72057
- device_id: this._deviceId,
72058
- commit_epoch: Number(mlsGroup.epoch),
72059
- member_device_ids: updatedMembers
72060
- })
72061
- }
72062
- );
72063
- } catch {
72064
- }
72065
- distributed = true;
72066
- }
72067
- if (!distributed) {
72068
- console.warn(`[SecureChannel] Cannot deliver Welcome \u2014 HTTP distribute and WS both unavailable`);
72069
- continue;
72070
- }
72071
- const a2aFulfilled = await this._postFulfilWelcome(
72072
- chState.mlsGroupId,
72073
- req.id,
72074
- `A2A ${chId.slice(0, 8)}`
72075
- );
72076
- await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
72077
- if (a2aFulfilled) {
72078
- console.log(`[SecureChannel] Fulfilled A2A Welcome for ${req.requesting_device_id.slice(0, 8)} in channel ${chId.slice(0, 8)}`);
72079
- }
72480
+ const next = await this._fulfilA2AWelcome(chId, chState, mlsGroup, req);
72481
+ if (next === "stop") break;
72080
72482
  } catch (fulfillErr) {
72081
72483
  console.log(`[SecureChannel] A2A Welcome fulfill failed: ${fulfillErr instanceof Error ? fulfillErr.message : String(fulfillErr)}`);
72082
72484
  }
@@ -72088,6 +72490,10 @@ ${baseText}`;
72088
72490
  console.warn("[SecureChannel] Delivery pull error:", err);
72089
72491
  } finally {
72090
72492
  this._deliveryPulling = false;
72493
+ if (this._deliveryPullRequested) {
72494
+ this._deliveryPullRequested = false;
72495
+ void this._pullDeliveryQueue().catch((err) => console.warn("[SecureChannel] Coalesced delivery pull error:", err));
72496
+ }
72091
72497
  }
72092
72498
  }
72093
72499
  /**
@@ -72171,7 +72577,7 @@ ${baseText}`;
72171
72577
  try {
72172
72578
  const parsed = JSON.parse(plaintext);
72173
72579
  messageType = parsed.type || "message";
72174
- messageText = parsed.text || plaintext;
72580
+ messageText = parsed.text ?? plaintext;
72175
72581
  } catch {
72176
72582
  messageType = "message";
72177
72583
  messageText = plaintext;
@@ -72343,6 +72749,227 @@ ${baseText}`;
72343
72749
  }
72344
72750
  }
72345
72751
  }
72752
+ /**
72753
+ * #1225: fulfil ONE pending A2A Welcome request — the `/distribute` path.
72754
+ * Extracted from the delivery pull so the in-flight slot (review F1) is held
72755
+ * for exactly this request and released on every exit. Returns "stop" when
72756
+ * nothing else on this channel can succeed this pull (review F2).
72757
+ */
72758
+ async _fulfilA2AWelcome(chId, chState, mlsGroup, req) {
72759
+ const a2aLabel = `A2A ${chId.slice(0, 8)}`;
72760
+ const preHead = await this._readGroupHead(chState.mlsGroupId);
72761
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
72762
+ console.warn(
72763
+ `[SecureChannel] ${a2aLabel}: server head is at epoch ${preHead.epoch}, we are at ${Number(mlsGroup.epoch)} \u2014 NOT committing (it would be refused); resync catches up first`
72764
+ );
72765
+ await this._catchUpAfterPreflightSkip(chState.mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), a2aLabel);
72766
+ return "stop";
72767
+ }
72768
+ const inFlight = this._reserveCommit(chState.mlsGroupId, a2aLabel);
72769
+ if (!inFlight) return "stop";
72770
+ try {
72771
+ const kpRes = await fetch(
72772
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
72773
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
72774
+ );
72775
+ if (!kpRes.ok) return "next";
72776
+ const kpData = await kpRes.json();
72777
+ const kpHex = kpData[req.requesting_device_id];
72778
+ if (!kpHex) return "next";
72779
+ const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
72780
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
72781
+ console.log(`[SecureChannel] A2A addMembers for ${req.requesting_device_id.slice(0, 8)} group=${chState.mlsGroupId.slice(0, 8)} epoch=${mlsGroup.epoch}`);
72782
+ let parentDigest = preHead.ok ? preHead.digest : void 0;
72783
+ let commit;
72784
+ let welcome;
72785
+ let preAddState = mlsGroup.exportState();
72786
+ try {
72787
+ const result = await mlsGroup.addMembers([memberKp]);
72788
+ commit = result.commit;
72789
+ welcome = result.welcome;
72790
+ } catch (addErr) {
72791
+ const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
72792
+ if (errMsg.includes("already in the group")) {
72793
+ console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
72794
+ const preRemoveState = JSON.stringify(mlsGroup.exportState());
72795
+ let removeCommitPublished = false;
72796
+ try {
72797
+ const identityBytes = new TextEncoder().encode(req.requesting_device_id);
72798
+ const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
72799
+ if (leafIndex === null) {
72800
+ console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
72801
+ return "next";
72802
+ }
72803
+ const removeResult = await mlsGroup.removeMember(leafIndex);
72804
+ try {
72805
+ const removeResp = await fetch(
72806
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72807
+ {
72808
+ method: "POST",
72809
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72810
+ body: JSON.stringify({
72811
+ group_id: chState.mlsGroupId,
72812
+ device_id: this._deviceId,
72813
+ commit: Buffer.from(removeResult.commit).toString("hex"),
72814
+ commit_epoch: Number(mlsGroup.epoch),
72815
+ expected_epoch: Number(mlsGroup.epoch) - 1,
72816
+ // #1225: exact-step, like the WS path
72817
+ ...parentDigest ? { parent_digest: parentDigest } : {}
72818
+ })
72819
+ }
72820
+ );
72821
+ if (removeResp.ok) {
72822
+ removeCommitPublished = true;
72823
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
72824
+ parentDigest = this._commitDigest(removeResult.commit);
72825
+ } else {
72826
+ const detail = await removeResp.text().catch(() => "");
72827
+ console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
72828
+ }
72829
+ } catch (distErr) {
72830
+ console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
72831
+ }
72832
+ if (!removeCommitPublished) {
72833
+ mlsGroup.importState(JSON.parse(preRemoveState));
72834
+ return "next";
72835
+ }
72836
+ const kpRes2 = await fetch(
72837
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
72838
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
72839
+ );
72840
+ if (kpRes2.ok) {
72841
+ const kpData2 = await kpRes2.json();
72842
+ const kpHex2 = kpData2[req.requesting_device_id];
72843
+ if (kpHex2) {
72844
+ const kpBytes2 = new Uint8Array(Buffer.from(kpHex2, "hex"));
72845
+ const memberKp2 = MLSGroupManager.deserializeKeyPackage(kpBytes2);
72846
+ preAddState = mlsGroup.exportState();
72847
+ const result2 = await mlsGroup.addMembers([memberKp2]);
72848
+ commit = result2.commit;
72849
+ welcome = result2.welcome;
72850
+ } else {
72851
+ console.log(`[SecureChannel] A2A re-add: no fresh KeyPackage for ${req.requesting_device_id.slice(0, 8)}`);
72852
+ return "next";
72853
+ }
72854
+ } else {
72855
+ console.log(`[SecureChannel] A2A re-add: KeyPackage fetch failed (${kpRes2.status})`);
72856
+ return "next";
72857
+ }
72858
+ } catch (readdErr) {
72859
+ console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
72860
+ if (!removeCommitPublished) {
72861
+ try {
72862
+ mlsGroup.importState(JSON.parse(preRemoveState));
72863
+ } catch {
72864
+ }
72865
+ }
72866
+ return "next";
72867
+ }
72868
+ } else {
72869
+ console.log(`[SecureChannel] A2A addMembers FAILED: ${errMsg}`);
72870
+ return "next";
72871
+ }
72872
+ }
72873
+ if (!welcome) {
72874
+ console.warn(`[SecureChannel] A2A addMembers produced no Welcome for ${req.requesting_device_id.slice(0, 8)}`);
72875
+ return "next";
72876
+ }
72877
+ const commitHex = Buffer.from(commit).toString("hex");
72878
+ const welcomeHex = Buffer.from(welcome).toString("hex");
72879
+ let distributed = false;
72880
+ let transportFailed = false;
72881
+ const updatedMembers = this._commitRoster([this._deviceId], [req.requesting_device_id]);
72882
+ try {
72883
+ const distResp = await fetch(
72884
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72885
+ {
72886
+ method: "POST",
72887
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72888
+ body: JSON.stringify({
72889
+ group_id: chState.mlsGroupId,
72890
+ device_id: this._deviceId,
72891
+ commit: commitHex,
72892
+ commit_epoch: Number(mlsGroup.epoch),
72893
+ welcomes: [{ target_device_id: req.requesting_device_id, payload: welcomeHex }],
72894
+ member_device_ids: updatedMembers,
72895
+ expected_epoch: Number(mlsGroup.epoch) - 1,
72896
+ // #1225: exact-step, like the WS path
72897
+ ...parentDigest ? { parent_digest: parentDigest } : {}
72898
+ })
72899
+ }
72900
+ );
72901
+ if (distResp.ok) {
72902
+ distributed = true;
72903
+ } else {
72904
+ const detail = await distResp.text().catch(() => "");
72905
+ console.warn(`[SecureChannel] A2A distribute failed (${distResp.status}): ${detail}`);
72906
+ if (distResp.status >= 500) {
72907
+ transportFailed = true;
72908
+ } else if (distResp.status === 409) {
72909
+ mlsGroup.importState(preAddState);
72910
+ console.warn(
72911
+ `[SecureChannel] ${a2aLabel}: add commit lost the race (409) \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, request stays pending`
72912
+ );
72913
+ return "next";
72914
+ } else {
72915
+ mlsGroup.importState(preAddState);
72916
+ console.error(
72917
+ `[SecureChannel] ${a2aLabel}: add commit refused with ${distResp.status} \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}; not retrying this channel this pull`
72918
+ );
72919
+ return "stop";
72920
+ }
72921
+ }
72922
+ } catch (distErr) {
72923
+ console.warn(`[SecureChannel] A2A distribute network error:`, distErr);
72924
+ transportFailed = true;
72925
+ }
72926
+ if (!distributed && transportFailed && this._wsIsOpen()) {
72927
+ const verdict = await this._sendCommitConfirmed({
72928
+ mlsGroup,
72929
+ mlsGroupId: chState.mlsGroupId,
72930
+ label: a2aLabel,
72931
+ commit,
72932
+ epoch: Number(mlsGroup.epoch),
72933
+ parent: parentDigest,
72934
+ memberDeviceIds: updatedMembers,
72935
+ stateBefore: preAddState,
72936
+ inFlight
72937
+ });
72938
+ if (verdict !== "confirmed") return "next";
72939
+ const welcomeSent = await this._sendFrameConfirmed({
72940
+ event: "mls_welcome",
72941
+ data: {
72942
+ target_device_id: req.requesting_device_id,
72943
+ group_id: chState.mlsGroupId,
72944
+ a2a_channel_id: chId,
72945
+ payload: welcomeHex
72946
+ }
72947
+ }, `${a2aLabel} welcome`);
72948
+ if (!welcomeSent) {
72949
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
72950
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome frame was NOT written \u2014 leaving the request pending`);
72951
+ return "next";
72952
+ }
72953
+ distributed = true;
72954
+ }
72955
+ if (!distributed) {
72956
+ console.warn(`[SecureChannel] Cannot deliver Welcome \u2014 HTTP distribute and WS both unavailable`);
72957
+ return "next";
72958
+ }
72959
+ const a2aFulfilled = await this._postFulfilWelcome(
72960
+ chState.mlsGroupId,
72961
+ req.id,
72962
+ `A2A ${chId.slice(0, 8)}`
72963
+ );
72964
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
72965
+ if (a2aFulfilled) {
72966
+ console.log(`[SecureChannel] Fulfilled A2A Welcome for ${req.requesting_device_id.slice(0, 8)} in channel ${chId.slice(0, 8)}`);
72967
+ }
72968
+ return "next";
72969
+ } finally {
72970
+ await this._releaseCommit(chState.mlsGroupId, inFlight, a2aLabel);
72971
+ }
72972
+ }
72346
72973
  /**
72347
72974
  * Found the MLS group for an A2A channel as the creator agent.
72348
72975
  * Calls /mls/a2a/{channelId}/init, creates the local MLS group, and sends
@@ -72385,48 +73012,77 @@ ${baseText}`;
72385
73012
  await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
72386
73013
  for (const p2 of participants) {
72387
73014
  if (p2.status !== "active" && p2.status !== "invited") continue;
73015
+ const a2aLabel = `A2A ${channelId.slice(0, 8)} found\u2192${p2.hubAddress}`;
72388
73016
  try {
72389
- const kpRes = await fetch(
72390
- `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(p2.hubId)}`,
72391
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
72392
- );
72393
- if (kpRes.ok) {
72394
- const kpData = await kpRes.json();
72395
- if (kpData.key_package) {
72396
- const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
72397
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
72398
- const { commit, welcome } = await mgr.addMembers([memberKp]);
72399
- if (welcome && this._ws) {
72400
- this._ws.send(JSON.stringify({
72401
- event: "mls_commit",
73017
+ if (!p2.deviceId) {
73018
+ console.warn(
73019
+ `[SecureChannel] ${a2aLabel}: no deviceId \u2014 NOT adding (a Welcome could not be addressed). Backend a2a_channel_approved payload may be missing device_id for this participant.`
73020
+ );
73021
+ continue;
73022
+ }
73023
+ if (!this._wsIsOpen()) {
73024
+ console.warn(`[SecureChannel] ${a2aLabel}: socket is not OPEN \u2014 NOT advancing the group`);
73025
+ continue;
73026
+ }
73027
+ const head = await this._readGroupHead(mlsData.group_id);
73028
+ if (head.ok && head.epoch !== Number(mgr.epoch)) {
73029
+ console.warn(`[SecureChannel] ${a2aLabel}: server head is at epoch ${head.epoch}, we are at ${Number(mgr.epoch)} \u2014 NOT committing`);
73030
+ await this._catchUpAfterPreflightSkip(mlsData.group_id, head.epoch, Number(mgr.epoch), a2aLabel);
73031
+ continue;
73032
+ }
73033
+ const inFlight = this._reserveCommit(mlsData.group_id, a2aLabel);
73034
+ if (!inFlight) continue;
73035
+ try {
73036
+ const kpRes = await fetch(
73037
+ `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(p2.hubId)}`,
73038
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
73039
+ );
73040
+ if (kpRes.ok) {
73041
+ const kpData = await kpRes.json();
73042
+ if (kpData.key_package) {
73043
+ const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
73044
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
73045
+ const stateBefore = mgr.exportState();
73046
+ const { commit, welcome } = await mgr.addMembers([memberKp]);
73047
+ const committedEpoch = Number(mgr.epoch);
73048
+ if (!welcome) {
73049
+ mgr.importState(stateBefore);
73050
+ console.warn(`[SecureChannel] ${a2aLabel}: addMembers produced no Welcome \u2014 rolled back`);
73051
+ continue;
73052
+ }
73053
+ const verdict = await this._sendCommitConfirmed({
73054
+ mlsGroup: mgr,
73055
+ mlsGroupId: mlsData.group_id,
73056
+ label: a2aLabel,
73057
+ commit,
73058
+ epoch: committedEpoch,
73059
+ parent: head.ok ? head.digest : void 0,
73060
+ memberDeviceIds: this._commitRoster(participants.map((q22) => q22.deviceId), [p2.deviceId]),
73061
+ stateBefore,
73062
+ inFlight
73063
+ });
73064
+ if (verdict !== "confirmed") continue;
73065
+ const sent = await this._sendFrameConfirmed({
73066
+ event: "mls_welcome",
72402
73067
  data: {
72403
73068
  group_id: mlsData.group_id,
72404
- epoch: Number(mgr.epoch),
72405
- payload: Buffer.from(commit).toString("hex")
73069
+ payload: Buffer.from(welcome).toString("hex"),
73070
+ target_device_id: p2.deviceId,
73071
+ a2a_channel_id: channelId,
73072
+ target_hub_id: p2.hubId
73073
+ // observability only — the backend ignores it
72406
73074
  }
72407
- }));
72408
- if (!p2.deviceId) {
72409
- console.warn(
72410
- `[SecureChannel] Skipping MLS Welcome to ${p2.hubAddress} for A2A ${channelId.slice(0, 8)}: no deviceId. Backend a2a_channel_approved payload may be missing device_id for this participant.`
72411
- );
72412
- } else {
72413
- this._ws.send(JSON.stringify({
72414
- event: "mls_welcome",
72415
- data: {
72416
- group_id: mlsData.group_id,
72417
- payload: Buffer.from(welcome).toString("hex"),
72418
- target_device_id: p2.deviceId,
72419
- a2a_channel_id: channelId,
72420
- // Kept for observability — backend ignores but it's
72421
- // useful in logs/wire captures to correlate to a hub.
72422
- target_hub_id: p2.hubId
72423
- }
72424
- }));
73075
+ }, `${a2aLabel} welcome`);
73076
+ await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
73077
+ if (sent) {
72425
73078
  console.log(`[SecureChannel] Sent MLS Welcome to ${p2.hubAddress} (device ${p2.deviceId.slice(0, 8)}) for A2A ${channelId.slice(0, 8)}`);
73079
+ } else {
73080
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome was NOT written \u2014 the participant will request one`);
72426
73081
  }
72427
73082
  }
72428
- await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
72429
73083
  }
73084
+ } finally {
73085
+ await this._releaseCommit(mlsData.group_id, inFlight, a2aLabel);
72430
73086
  }
72431
73087
  } catch (kpErr) {
72432
73088
  console.warn(`[SecureChannel] Failed to Welcome participant ${p2.hubAddress}:`, kpErr);
@@ -72520,7 +73176,7 @@ ${baseText}`;
72520
73176
  try {
72521
73177
  const parsed = JSON.parse(plaintext);
72522
73178
  messageType = parsed.type || "message";
72523
- messageText = parsed.text || plaintext;
73179
+ messageText = parsed.text ?? plaintext;
72524
73180
  } catch {
72525
73181
  messageType = "message";
72526
73182
  messageText = plaintext;
@@ -72805,7 +73461,7 @@ ${baseText}`;
72805
73461
  try {
72806
73462
  const parsed = JSON.parse(plaintext);
72807
73463
  messageType = parsed.type || "message";
72808
- messageText = parsed.text || plaintext;
73464
+ messageText = parsed.text ?? plaintext;
72809
73465
  } catch {
72810
73466
  messageType = "message";
72811
73467
  messageText = plaintext;
@@ -73405,58 +74061,6 @@ var init_gateway_send = __esm2({
73405
74061
  init_openclaw_compat();
73406
74062
  }
73407
74063
  });
73408
- function parseMentions(text) {
73409
- const mentions = [];
73410
- const re22 = new RegExp(MENTION_RE.source, MENTION_RE.flags);
73411
- let match;
73412
- while ((match = re22.exec(text)) !== null) {
73413
- mentions.push(match[1].toLowerCase());
73414
- }
73415
- return mentions;
73416
- }
73417
- function resolveOwn(mention, names) {
73418
- if (names.has(mention)) return mention;
73419
- const parts = mention.split("-");
73420
- for (let i2 = parts.length - 1; i2 > 0; i2--) {
73421
- const candidate = parts.slice(0, i2).join("-");
73422
- if (names.has(candidate)) return candidate;
73423
- }
73424
- return null;
73425
- }
73426
- function owesRoomReply(plaintext, agentName, accountId, senderIsAgent, roomDisplayName, ownDisplayName, selfResolved = true) {
73427
- const mentions = parseMentions(plaintext);
73428
- if (mentions.length === 0) return false;
73429
- const ownNames = ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName);
73430
- if (mentions.some((m22) => resolveOwn(m22, ownNames) !== null)) return true;
73431
- if (mentions.some((m22) => resolveOwn(m22, BROADCAST_NAMES) !== null)) {
73432
- return senderIsAgent !== true;
73433
- }
73434
- if (!selfResolved) return true;
73435
- return false;
73436
- }
73437
- function ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName) {
73438
- const names = /* @__PURE__ */ new Set();
73439
- const add4 = (n22) => {
73440
- if (!n22) return;
73441
- const lower = n22.toLowerCase();
73442
- names.add(lower);
73443
- names.add(lower.split(/[\s(]/)[0]);
73444
- };
73445
- add4(agentName);
73446
- add4(accountId);
73447
- add4(roomDisplayName);
73448
- add4(ownDisplayName);
73449
- return names;
73450
- }
73451
- var MENTION_RE;
73452
- var BROADCAST_NAMES;
73453
- var init_room_protocol = __esm2({
73454
- "src/room-protocol.ts"() {
73455
- "use strict";
73456
- MENTION_RE = /@([\w-]+)/gi;
73457
- BROADCAST_NAMES = /* @__PURE__ */ new Set(["all", "everyone"]);
73458
- }
73459
- });
73460
74064
  var init_llm_response_parser = __esm2({
73461
74065
  "src/llm-response-parser.ts"() {
73462
74066
  "use strict";
@@ -99550,7 +100154,7 @@ var init_index = __esm2({
99550
100154
  await init_skill_telemetry();
99551
100155
  await init_policy_enforcer();
99552
100156
  init_room_protocol();
99553
- VERSION = true ? "0.23.39" : "0.0.0-dev";
100157
+ VERSION = true ? "0.23.41" : "0.0.0-dev";
99554
100158
  }
99555
100159
  });
99556
100160
  await init_index();
@@ -135966,7 +136570,7 @@ async function main() {
135966
136570
  "[bridge] warning: passing the invite token on the command line is visible to other local users via 'ps'. Prefer: AV_INVITE_TOKEN=\u2026 npx @agentvault/claude-bridge"
135967
136571
  );
135968
136572
  }
135969
- logLine(`[bridge] version: ${true ? "0.8.12" : "dev"}`);
136573
+ logLine(`[bridge] version: ${true ? "0.8.14" : "dev"}`);
135970
136574
  logLine(`[bridge] data dir: ${cfg.dataDir} (${cfg.dataDirSource})`);
135971
136575
  logLine(`[bridge] workspace: ${cfg.workspaceDir} \xB7 permissions: ${cfg.permissionMode} \xB7 enclave dir fenced`);
135972
136576
  if (cfg.armRoom) {
@@ -135998,7 +136602,7 @@ async function main() {
135998
136602
  // its default would render "@agentvault/agentvault@0.7.x" — the wrong
135999
136603
  // package name attached to the bridge's version number, which is worse
136000
136604
  // than either alone.
136001
- clientVersion: `@agentvault/claude-bridge@${true ? "0.8.12" : "dev"}`
136605
+ clientVersion: `@agentvault/claude-bridge@${true ? "0.8.14" : "dev"}`
136002
136606
  });
136003
136607
  const agentSystemPrompt = cfg.systemPrompt ?? `You are ${cfg.agentName}, an AI agent on AgentVault. You talk with your owner in 1:1 direct messages and collaborate with other agents in shared rooms. That is your identity \u2014 introduce yourself by that name and do not claim to be any other agent. To speak, call the say tool. In a 1:1 with your owner, reply to what they say. In a room you see every message \u2014 call say only when you have something worth adding, and otherwise stay silent. Keep messages concise.`;
136004
136608
  const deviceJwt = () => {