@agentvault/claude-bridge 0.8.13 → 0.8.15

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/bridge.d.ts CHANGED
@@ -3,6 +3,9 @@ export interface RoomMessage {
3
3
  roomId: string;
4
4
  senderName: string;
5
5
  plaintext: string;
6
+ /** #1223 — the text the sender typed, before any attachment was folded into
7
+ * `plaintext`. The @ gate reads this; absent on emitters < 0.23.42. */
8
+ caption?: string;
6
9
  /** True when the sender is another agent (SecureChannel derives this from the
7
10
  * room roster). Used to decide reply expectation: a human/owner speaking in a
8
11
  * room always expects a reply; agent-authored traffic does not (the agent may
package/dist/index.js CHANGED
@@ -64664,11 +64664,11 @@ var init_mls_kp_pool = __esm2({
64664
64664
  }
64665
64665
  });
64666
64666
  function ownIdentity() {
64667
- const v22 = true ? "0.23.40" : FALLBACK;
64667
+ const v22 = true ? "0.23.42" : FALLBACK;
64668
64668
  return `${PACKAGE}@${v22}`;
64669
64669
  }
64670
64670
  function buildSha() {
64671
- const raw = true ? "dbac15d-dirty" : "";
64671
+ const raw = true ? "d9d53a0-dirty" : "";
64672
64672
  const cleaned = (raw ?? "").trim();
64673
64673
  return !cleaned || cleaned === "unknown" ? null : cleaned;
64674
64674
  }
@@ -65575,6 +65575,7 @@ var CREDENTIAL_MESSAGE_TYPES;
65575
65575
  var CATCHUP_MESSAGE_TYPES;
65576
65576
  var POLL_INTERVAL_MS;
65577
65577
  var RECONNECT_BASE_MS;
65578
+ var UUID_RE;
65578
65579
  var RECONNECT_MAX_MS;
65579
65580
  var PENDING_POLL_INTERVAL_MS;
65580
65581
  var OUTBOUND_DEDUPE_WINDOW_MS;
@@ -65622,6 +65623,7 @@ var init_channel = __esm2({
65622
65623
  ]);
65623
65624
  POLL_INTERVAL_MS = 6e3;
65624
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;
65625
65627
  RECONNECT_MAX_MS = 3e4;
65626
65628
  PENDING_POLL_INTERVAL_MS = 15e3;
65627
65629
  OUTBOUND_DEDUPE_WINDOW_MS = 3e3;
@@ -66917,7 +66919,7 @@ ${text}`;
66917
66919
  */
66918
66920
  sendActivitySpan(spanData) {
66919
66921
  if (!this._ws || this._ws.readyState !== WebSocket2.OPEN) return;
66920
- const pluginVersion = true ? "0.23.40" : "0.0.0-dev";
66922
+ const pluginVersion = true ? "0.23.42" : "0.0.0-dev";
66921
66923
  const agentName = this.config.agentName ?? "Agent";
66922
66924
  const resource = {
66923
66925
  "service.name": "agentvault-agent",
@@ -68855,7 +68857,7 @@ ${text}`;
68855
68857
  agentVersion: this.config.agentVersion ?? "0.0.0",
68856
68858
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
68857
68859
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
68858
- pluginVersion: true ? "0.23.40" : "0.0.0-dev"
68860
+ pluginVersion: true ? "0.23.42" : "0.0.0-dev"
68859
68861
  });
68860
68862
  this._telemetryReporter.startAutoFlush(3e4);
68861
68863
  }
@@ -69179,7 +69181,7 @@ ${text}`;
69179
69181
  agentVersion: this.config.agentVersion ?? "0.0.0",
69180
69182
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
69181
69183
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
69182
- pluginVersion: true ? "0.23.40" : "0.0.0-dev"
69184
+ pluginVersion: true ? "0.23.42" : "0.0.0-dev"
69183
69185
  });
69184
69186
  this._telemetryReporter.startAutoFlush(3e4);
69185
69187
  }
@@ -69394,45 +69396,78 @@ ${text}`;
69394
69396
  const mlsGroup = this._mlsGroups.get(`a2a:${channelId}`);
69395
69397
  if (mlsGroup?.isInitialized) {
69396
69398
  try {
69397
- const kpRes = await fetch(
69398
- `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(participant.hub_id)}`,
69399
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
69400
- );
69401
- if (kpRes.ok) {
69402
- const kpData = await kpRes.json();
69403
- if (kpData.key_package) {
69404
- const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
69405
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
69406
- const { commit, welcome } = await mlsGroup.addMembers([memberKp]);
69407
- if (welcome && this._ws) {
69408
- this._ws.send(JSON.stringify({
69409
- event: "mls_commit",
69410
- data: {
69411
- group_id: entry.mlsGroupId,
69412
- epoch: Number(mlsGroup.epoch),
69413
- payload: Buffer.from(commit).toString("hex")
69414
- }
69415
- }));
69416
- const newDeviceId = participant.device_id || null;
69417
- if (!newDeviceId) {
69418
- console.warn(
69419
- `[SecureChannel] Skipping MLS Welcome to new participant ${participant.hub_address} for A2A ${channelId.slice(0, 8)}: no device_id on participant_joined payload.`
69420
- );
69421
- } else {
69422
- this._ws.send(JSON.stringify({
69423
- event: "mls_welcome",
69424
- data: {
69425
- group_id: entry.mlsGroupId,
69426
- payload: Buffer.from(welcome).toString("hex"),
69427
- target_device_id: newDeviceId,
69428
- a2a_channel_id: channelId,
69429
- target_hub_id: participant.hub_id
69430
- // 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
+ }
69431
69466
  }
69432
- }));
69433
- await saveMlsState(this.config.dataDir, entry.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
69434
- console.log(`[SecureChannel] Sent MLS Welcome to new participant ${participant.hub_address} (device ${String(newDeviceId).slice(0, 8)})`);
69467
+ }
69435
69468
  }
69469
+ } finally {
69470
+ await this._releaseCommit(entry.mlsGroupId, inFlight, a2aLabel);
69436
69471
  }
69437
69472
  }
69438
69473
  }
@@ -69909,7 +69944,13 @@ ${messageText}`;
69909
69944
  messageType: msgData.message_type ?? "text",
69910
69945
  priority: msgData.priority ?? "normal",
69911
69946
  envelopeVersion: msgData.envelope_version ?? "1.0.0",
69912
- roomId
69947
+ roomId,
69948
+ // #1223 — the pre-fold text. This DR `message` path also sets `roomId`
69949
+ // and folds an attachment into `emitText`, so without this a room
69950
+ // message that reaches the gate here would fall back to the folded
69951
+ // text (the same bug the MLS room path fixes). `messageText` is the
69952
+ // envelope text before the fold; `emitText` is the folded copy.
69953
+ caption: messageText
69913
69954
  };
69914
69955
  this.emit("message", emitText, metadata);
69915
69956
  Promise.resolve(this.config.onMessage?.(emitText, metadata)).catch((err) => {
@@ -70588,6 +70629,7 @@ ${baseText}`;
70588
70629
  await this._refreshRoomRoster(resolvedRoomId);
70589
70630
  }
70590
70631
  }
70632
+ const caption = messageText;
70591
70633
  const addressed = parseMentions(messageText).length > 0;
70592
70634
  if (roomAttachment && !addressed) {
70593
70635
  this._deferRoomAttachment(resolvedRoomId, roomAttachment);
@@ -70614,7 +70656,8 @@ ${baseText}`;
70614
70656
  senderDeviceId,
70615
70657
  senderIsAgent,
70616
70658
  senderName: senderMember?.displayName || "unknown",
70617
- roomName: this._persisted?.rooms?.[resolvedRoomId]?.name
70659
+ roomName: this._persisted?.rooms?.[resolvedRoomId]?.name,
70660
+ caption
70618
70661
  };
70619
70662
  const senderLabel = senderMember?.displayName || "someone";
70620
70663
  this._appendHistory("owner", messageText, `room:${resolvedRoomId}`);
@@ -70623,6 +70666,9 @@ ${baseText}`;
70623
70666
  senderDeviceId,
70624
70667
  senderName: senderLabel,
70625
70668
  plaintext: messageText,
70669
+ // #1223 — what the sender typed, before the attachment fold. The
70670
+ // bridges gate on this (falling back to `plaintext` when absent).
70671
+ caption,
70626
70672
  messageType,
70627
70673
  timestamp: data.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
70628
70674
  // Native bridge (claude-room-bridge) consumes this to decide reply
@@ -70962,9 +71008,34 @@ ${baseText}`;
70962
71008
  *
70963
71009
  * Returns the number of requests actually fulfilled.
70964
71010
  */
71011
+ /**
71012
+ * #1226: the roster to submit on a commit frame — the caller's known members,
71013
+ * the devices being admitted, and ALWAYS ourselves — deduplicated, UUIDs
71014
+ * only. Self is non-negotiable: once a roster is non-empty the server
71015
+ * requires the committer in it (#469), and our own head read
71016
+ * (`assert_group_member`) requires it too. So with no device id of our own
71017
+ * this returns `[]` and the frame carries NO roster (the pre-#1226 shape)
71018
+ * rather than a roster that locks us out. Non-UUID entries are dropped:
71019
+ * `known` can come off an inbound Welcome frame, and a malformed id in the
71020
+ * outbound frame is refused by the server (`MEMBER_DEVICE_IDS_MALFORMED`).
71021
+ * @internal exposed for tests
71022
+ */
71023
+ _commitRoster(known, targets) {
71024
+ if (!this._deviceId) return [];
71025
+ const out = [];
71026
+ const seen = /* @__PURE__ */ new Set();
71027
+ for (const id of [...known ?? [], ...targets, this._deviceId]) {
71028
+ if (typeof id !== "string" || !UUID_RE.test(id) || seen.has(id)) continue;
71029
+ seen.add(id);
71030
+ out.push(id);
71031
+ }
71032
+ return out;
71033
+ }
70965
71034
  async _fulfilWelcomeRequests(opts) {
70966
71035
  const { mlsGroup, mlsGroupId, label, welcomeFields, targets } = opts;
70967
71036
  if (targets.length === 0) return 0;
71037
+ const rosterBefore = this._commitRoster(opts.memberDeviceIds, []);
71038
+ const rosterAfter = this._commitRoster(opts.memberDeviceIds, targets.map((t22) => t22.deviceId));
70968
71039
  if (!this._wsIsOpen()) {
70969
71040
  console.warn(
70970
71041
  `[SecureChannel] ${label}: socket is not OPEN \u2014 NOT advancing the group; ${targets.length} request(s) stay pending for the next pull`
@@ -70977,9 +71048,16 @@ ${baseText}`;
70977
71048
  console.warn(
70978
71049
  `[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`
70979
71050
  );
71051
+ await this._catchUpAfterPreflightSkip(mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), label);
70980
71052
  return 0;
70981
71053
  }
70982
71054
  let parent2 = preHead.ok ? preHead.digest : void 0;
71055
+ if (this._commitInFlight.has(mlsGroupId)) {
71056
+ console.warn(
71057
+ `[SecureChannel] ${label}: another commit for this group is in flight \u2014 NOT advancing; ${targets.length} request(s) stay pending for the next pull`
71058
+ );
71059
+ return 0;
71060
+ }
70983
71061
  const inFlight = { frames: [], sent: [] };
70984
71062
  this._commitInFlight.set(mlsGroupId, inFlight);
70985
71063
  try {
@@ -71004,7 +71082,8 @@ ${baseText}`;
71004
71082
  // only knows the last one, which is why the result carries them.
71005
71083
  epoch: Number(c22.epoch),
71006
71084
  payload: Buffer.from(c22.commit).toString("hex"),
71007
- ...parent2 ? { parent_digest: parent2 } : {}
71085
+ ...parent2 ? { parent_digest: parent2 } : {},
71086
+ ...(sentCommits === commits.length - 1 ? rosterAfter : rosterBefore).length > 0 ? { member_device_ids: sentCommits === commits.length - 1 ? rosterAfter : rosterBefore } : {}
71008
71087
  }
71009
71088
  },
71010
71089
  `${label} commit ${sentCommits + 1}/${commits.length}`
@@ -71152,6 +71231,126 @@ ${baseText}`;
71152
71231
  return this._ws?.readyState === 1;
71153
71232
  }
71154
71233
  /** SHA-256 hex of a commit's bytes — its identity on the server (#1175/#1177). */
71234
+ /**
71235
+ * #1225: send ONE commit over the socket and wait for the server's verdict,
71236
+ * with the #1184 machinery — an in-flight record (so a `… commit rejected`
71237
+ * frame is correlated to it and a concurrent commit for the group is held
71238
+ * and replayed), the head poll, and rollback. The three A2A commit sites
71239
+ * (`a2a_participant_joined`, the `/distribute` WS fallback, `_foundA2AGroup`)
71240
+ * used a raw `ws.send` and treated "the socket took it" as "the server
71241
+ * stored it" — two of them then PERSISTED a state the server never saw.
71242
+ *
71243
+ * Returns the verdict. On `refused` / `unsent` the manager has been restored
71244
+ * to `stateBefore` and nothing must be persisted or minted from it.
71245
+ * `unverifiable` (head unreadable on every try AND no refusal) proceeds
71246
+ * UNCHECKED, the same deliberate choice as the fulfil site.
71247
+ */
71248
+ /**
71249
+ * #1225 (review F1): reserve the single in-flight slot for a group. The
71250
+ * record is what `_noteCommitRefusal` correlates a refusal to and what
71251
+ * `_handleMlsCommit` holds concurrent socket commits behind; a second run on
71252
+ * the same group would clobber both (measured: two overlapping joins → two
71253
+ * commits claiming one epoch, one Welcome instead of two, the manager AHEAD
71254
+ * of the server). Taken BEFORE the commit is generated; released by
71255
+ * `_releaseCommit` after the last step that depends on it.
71256
+ */
71257
+ /**
71258
+ * A pre-flight skip must not be a dead end. The skip happens because the
71259
+ * server's head is somewhere else; before this the group "caught up through
71260
+ * the normal divergence path", which only runs when a message for the group
71261
+ * arrives — so a group nobody writes to stayed diverged and its pending
71262
+ * Welcome requests were never fulfilled (named in PR #1227). When the server
71263
+ * is AHEAD, replay the missing commits now so the next pull can commit; when
71264
+ * WE are ahead there is nothing to replay (the fork-ahead direction, #972).
71265
+ */
71266
+ async _catchUpAfterPreflightSkip(mlsGroupId, serverEpoch, localEpoch, label) {
71267
+ if (serverEpoch < localEpoch) {
71268
+ console.warn(`[SecureChannel] ${label}: we are AHEAD of the server (${localEpoch} > ${serverEpoch}) \u2014 nothing to replay`);
71269
+ return;
71270
+ }
71271
+ const fam = this._resolveGroupFamily(mlsGroupId);
71272
+ if (!fam) return;
71273
+ try {
71274
+ const caughtUp = await this._resyncOnDivergence(fam.managerKey, mlsGroupId);
71275
+ console.log(`[SecureChannel] ${label}: catch-up after pre-flight skip ${caughtUp ? "replayed the missing commits" : "could not replay"}`);
71276
+ } catch (err) {
71277
+ console.warn(`[SecureChannel] ${label}: catch-up after pre-flight skip failed:`, err);
71278
+ }
71279
+ }
71280
+ _reserveCommit(groupId, label) {
71281
+ if (this._commitInFlight.has(groupId)) {
71282
+ console.warn(
71283
+ `[SecureChannel] ${label}: another commit for group ${groupId.slice(0, 8)} is in flight \u2014 NOT advancing the group (a Welcome can be requested again)`
71284
+ );
71285
+ return null;
71286
+ }
71287
+ const rec = { frames: [], sent: [] };
71288
+ this._commitInFlight.set(groupId, rec);
71289
+ return rec;
71290
+ }
71291
+ /** Release the slot taken by `_reserveCommit` and replay the socket commits held meanwhile. */
71292
+ async _releaseCommit(groupId, rec, label) {
71293
+ if (this._commitInFlight.get(groupId) === rec) this._commitInFlight.delete(groupId);
71294
+ for (const frame of rec.frames) {
71295
+ try {
71296
+ await this._handleMlsCommit(frame);
71297
+ } catch (err) {
71298
+ console.error(`[SecureChannel] ${label}: replaying a held MLS commit failed:`, err);
71299
+ }
71300
+ }
71301
+ }
71302
+ /**
71303
+ * #1225: send ONE commit over the socket and wait for the server's verdict
71304
+ * with the #1184 machinery (refusal frame correlated through the reserved
71305
+ * in-flight record, head poll). The three A2A commit sites
71306
+ * (`a2a_participant_joined`, the `/distribute` WS fallback, `_foundA2AGroup`)
71307
+ * used a raw `ws.send` and treated "the socket took it" as "the server
71308
+ * stored it" — two of them then PERSISTED a state the server never saw.
71309
+ *
71310
+ * Only `confirmed` proceeds. `unverifiable` (head unreadable on every try,
71311
+ * no refusal) is a ROLLBACK here, unlike the fulfil site: that site proceeds
71312
+ * UNCHECKED because 79 of 80 production rooms 403 the head read on an empty
71313
+ * roster; an A2A head read admits any active participant (observer
71314
+ * fallback), so five failed reads there mean an outage, not a routine 403.
71315
+ * On anything but `confirmed` the manager is back at `stateBefore`.
71316
+ */
71317
+ async _sendCommitConfirmed(opts) {
71318
+ const { mlsGroup, mlsGroupId, label, commit, epoch, parent: parent2, memberDeviceIds, stateBefore, inFlight } = opts;
71319
+ const ours = this._commitDigest(commit);
71320
+ inFlight.sent.push({ epoch, digest: ours, verified: false, stateBefore });
71321
+ const ok2 = await this._sendFrameConfirmed(
71322
+ {
71323
+ event: "mls_commit",
71324
+ data: {
71325
+ group_id: mlsGroupId,
71326
+ epoch,
71327
+ payload: Buffer.from(commit).toString("hex"),
71328
+ ...parent2 ? { parent_digest: parent2 } : {},
71329
+ ...memberDeviceIds && memberDeviceIds.length > 0 ? { member_device_ids: memberDeviceIds } : {}
71330
+ }
71331
+ },
71332
+ `${label} commit`
71333
+ );
71334
+ if (!ok2) {
71335
+ inFlight.sent.pop();
71336
+ mlsGroup.importState(stateBefore);
71337
+ console.warn(
71338
+ `[SecureChannel] ${label}: commit at epoch ${epoch} was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}`
71339
+ );
71340
+ return "unsent";
71341
+ }
71342
+ const verdict = await this._confirmCommitAtHead(mlsGroupId, epoch, ours, inFlight, label);
71343
+ if (inFlight.refusal === void 0 && verdict === "confirmed") {
71344
+ inFlight.sent[inFlight.sent.length - 1].verified = true;
71345
+ return "confirmed";
71346
+ }
71347
+ const why = inFlight.refusal?.detail ?? verdict.toUpperCase();
71348
+ mlsGroup.importState(stateBefore);
71349
+ console.warn(
71350
+ `[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`
71351
+ );
71352
+ return "refused";
71353
+ }
71155
71354
  _commitDigest(bytes) {
71156
71355
  return createHash("sha256").update(bytes).digest("hex");
71157
71356
  }
@@ -72105,7 +72304,9 @@ ${baseText}`;
72105
72304
  mlsGroupId: roomState.mlsGroupId,
72106
72305
  label: `room ${roomId.slice(0, 8)}`,
72107
72306
  welcomeFields: { room_id: roomId },
72108
- targets: roomTargets
72307
+ targets: roomTargets,
72308
+ memberDeviceIds: (roomState.members ?? []).map((m22) => m22.deviceId)
72309
+ // #1226
72109
72310
  });
72110
72311
  if (done > 0) {
72111
72312
  console.log(
@@ -72160,7 +72361,9 @@ ${baseText}`;
72160
72361
  mlsGroupId: entry.mlsGroupId,
72161
72362
  label: `shared group ${gid.slice(0, 8)}`,
72162
72363
  welcomeFields: { conversation_group_id: gid },
72163
- targets: sharedTargets
72364
+ targets: sharedTargets,
72365
+ memberDeviceIds: entry.memberDeviceIds ?? []
72366
+ // #1226
72164
72367
  });
72165
72368
  if (done > 0) {
72166
72369
  console.log(`[SecureChannel] Batched Welcome for ${done}/${validReqs.length} devices in shared group ${gid.slice(0, 8)} (epoch=${mlsGroup.epoch})`);
@@ -72174,7 +72377,9 @@ ${baseText}`;
72174
72377
  mlsGroupId: entry.mlsGroupId,
72175
72378
  label: `shared group ${gid.slice(0, 8)}`,
72176
72379
  welcomeFields: { conversation_group_id: gid },
72177
- targets: [target]
72380
+ targets: [target],
72381
+ memberDeviceIds: entry.memberDeviceIds ?? []
72382
+ // #1226
72178
72383
  });
72179
72384
  if (done > 0) {
72180
72385
  console.log(`[SecureChannel] Individual Welcome for ${target.deviceId.slice(0, 8)} in shared group ${gid.slice(0, 8)}`);
@@ -72221,7 +72426,11 @@ ${baseText}`;
72221
72426
  requestId: req.id,
72222
72427
  deviceId: req.requesting_device_id,
72223
72428
  keyPackage: memberKp
72224
- }]
72429
+ }],
72430
+ // #1226: a 1:1 roster is [self, owner] — the web's shape too.
72431
+ memberDeviceIds: [this._persisted?.sessions?.[convId]?.ownerDeviceId].filter(
72432
+ (d22) => typeof d22 === "string"
72433
+ )
72225
72434
  });
72226
72435
  if (done > 0) {
72227
72436
  console.log(`[SecureChannel] Fulfilled Welcome for ${req.requesting_device_id.slice(0, 8)} in conv ${convId.slice(0, 8)}`);
@@ -72279,192 +72488,8 @@ ${baseText}`;
72279
72488
  console.log(`[SecureChannel] ${pending.length} pending A2A Welcome requests for channel ${chId.slice(0, 8)}`);
72280
72489
  for (const req of pending) {
72281
72490
  try {
72282
- const kpRes = await fetch(
72283
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
72284
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
72285
- );
72286
- if (!kpRes.ok) continue;
72287
- const kpData = await kpRes.json();
72288
- const kpHex = kpData[req.requesting_device_id];
72289
- if (!kpHex) continue;
72290
- const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
72291
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
72292
- console.log(`[SecureChannel] A2A addMembers for ${req.requesting_device_id.slice(0, 8)} group=${chState.mlsGroupId.slice(0, 8)} epoch=${mlsGroup.epoch}`);
72293
- let parentDigest = await this._readGroupHeadDigest(chState.mlsGroupId);
72294
- let commit;
72295
- let welcome;
72296
- try {
72297
- const result = await mlsGroup.addMembers([memberKp]);
72298
- commit = result.commit;
72299
- welcome = result.welcome;
72300
- } catch (addErr) {
72301
- const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
72302
- if (errMsg.includes("already in the group")) {
72303
- console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
72304
- const preRemoveState = JSON.stringify(mlsGroup.exportState());
72305
- let removeCommitPublished = false;
72306
- try {
72307
- const identityBytes = new TextEncoder().encode(req.requesting_device_id);
72308
- const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
72309
- if (leafIndex === null) {
72310
- console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
72311
- continue;
72312
- }
72313
- const removeResult = await mlsGroup.removeMember(leafIndex);
72314
- try {
72315
- const removeResp = await fetch(
72316
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72317
- {
72318
- method: "POST",
72319
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72320
- body: JSON.stringify({
72321
- group_id: chState.mlsGroupId,
72322
- device_id: this._deviceId,
72323
- commit: Buffer.from(removeResult.commit).toString("hex"),
72324
- commit_epoch: Number(mlsGroup.epoch),
72325
- ...parentDigest ? { parent_digest: parentDigest } : {}
72326
- })
72327
- }
72328
- );
72329
- if (removeResp.ok) {
72330
- removeCommitPublished = true;
72331
- parentDigest = this._commitDigest(removeResult.commit);
72332
- } else {
72333
- const detail = await removeResp.text().catch(() => "");
72334
- console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
72335
- }
72336
- } catch (distErr) {
72337
- console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
72338
- }
72339
- if (!removeCommitPublished) {
72340
- mlsGroup.importState(JSON.parse(preRemoveState));
72341
- continue;
72342
- }
72343
- const kpRes2 = await fetch(
72344
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
72345
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
72346
- );
72347
- if (kpRes2.ok) {
72348
- const kpData2 = await kpRes2.json();
72349
- const kpHex2 = kpData2[req.requesting_device_id];
72350
- if (kpHex2) {
72351
- const kpBytes2 = new Uint8Array(Buffer.from(kpHex2, "hex"));
72352
- const memberKp2 = MLSGroupManager.deserializeKeyPackage(kpBytes2);
72353
- const result2 = await mlsGroup.addMembers([memberKp2]);
72354
- commit = result2.commit;
72355
- welcome = result2.welcome;
72356
- } else {
72357
- console.log(`[SecureChannel] A2A re-add: no fresh KeyPackage for ${req.requesting_device_id.slice(0, 8)}`);
72358
- continue;
72359
- }
72360
- } else {
72361
- console.log(`[SecureChannel] A2A re-add: KeyPackage fetch failed (${kpRes2.status})`);
72362
- continue;
72363
- }
72364
- } catch (readdErr) {
72365
- console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
72366
- if (!removeCommitPublished) {
72367
- try {
72368
- mlsGroup.importState(JSON.parse(preRemoveState));
72369
- } catch {
72370
- }
72371
- }
72372
- continue;
72373
- }
72374
- } else {
72375
- console.log(`[SecureChannel] A2A addMembers FAILED: ${errMsg}`);
72376
- continue;
72377
- }
72378
- }
72379
- if (!welcome) {
72380
- console.warn(`[SecureChannel] A2A addMembers produced no Welcome for ${req.requesting_device_id.slice(0, 8)}`);
72381
- continue;
72382
- }
72383
- const commitHex = Buffer.from(commit).toString("hex");
72384
- const welcomeHex = Buffer.from(welcome).toString("hex");
72385
- let distributed = false;
72386
- const updatedMembers = [this._deviceId, req.requesting_device_id];
72387
- try {
72388
- const distResp = await fetch(
72389
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72390
- {
72391
- method: "POST",
72392
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72393
- body: JSON.stringify({
72394
- group_id: chState.mlsGroupId,
72395
- device_id: this._deviceId,
72396
- commit: commitHex,
72397
- commit_epoch: Number(mlsGroup.epoch),
72398
- welcomes: [{ target_device_id: req.requesting_device_id, payload: welcomeHex }],
72399
- member_device_ids: updatedMembers,
72400
- ...parentDigest ? { parent_digest: parentDigest } : {}
72401
- })
72402
- }
72403
- );
72404
- if (distResp.ok) {
72405
- distributed = true;
72406
- } else {
72407
- const detail = await distResp.text().catch(() => "");
72408
- console.warn(`[SecureChannel] A2A distribute failed (${distResp.status}): ${detail}`);
72409
- }
72410
- } catch (distErr) {
72411
- console.warn(`[SecureChannel] A2A distribute network error:`, distErr);
72412
- }
72413
- if (!distributed && this._wsIsOpen()) {
72414
- const a2aLabel = `A2A ${chId.slice(0, 8)}`;
72415
- const commitSent = await this._sendFrameConfirmed({
72416
- event: "mls_commit",
72417
- data: {
72418
- group_id: chState.mlsGroupId,
72419
- epoch: Number(mlsGroup.epoch),
72420
- payload: commitHex,
72421
- ...parentDigest ? { parent_digest: parentDigest } : {}
72422
- }
72423
- }, `${a2aLabel} commit`);
72424
- const welcomeSent = commitSent && await this._sendFrameConfirmed({
72425
- event: "mls_welcome",
72426
- data: {
72427
- target_device_id: req.requesting_device_id,
72428
- group_id: chState.mlsGroupId,
72429
- a2a_channel_id: chId,
72430
- payload: welcomeHex
72431
- }
72432
- }, `${a2aLabel} welcome`);
72433
- if (!welcomeSent) {
72434
- console.warn(`[SecureChannel] ${a2aLabel}: Welcome frames were NOT written \u2014 leaving the request pending`);
72435
- continue;
72436
- }
72437
- try {
72438
- await fetch(
72439
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72440
- {
72441
- method: "POST",
72442
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72443
- body: JSON.stringify({
72444
- group_id: chState.mlsGroupId,
72445
- device_id: this._deviceId,
72446
- commit_epoch: Number(mlsGroup.epoch),
72447
- member_device_ids: updatedMembers
72448
- })
72449
- }
72450
- );
72451
- } catch {
72452
- }
72453
- distributed = true;
72454
- }
72455
- if (!distributed) {
72456
- console.warn(`[SecureChannel] Cannot deliver Welcome \u2014 HTTP distribute and WS both unavailable`);
72457
- continue;
72458
- }
72459
- const a2aFulfilled = await this._postFulfilWelcome(
72460
- chState.mlsGroupId,
72461
- req.id,
72462
- `A2A ${chId.slice(0, 8)}`
72463
- );
72464
- await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
72465
- if (a2aFulfilled) {
72466
- console.log(`[SecureChannel] Fulfilled A2A Welcome for ${req.requesting_device_id.slice(0, 8)} in channel ${chId.slice(0, 8)}`);
72467
- }
72491
+ const next = await this._fulfilA2AWelcome(chId, chState, mlsGroup, req);
72492
+ if (next === "stop") break;
72468
72493
  } catch (fulfillErr) {
72469
72494
  console.log(`[SecureChannel] A2A Welcome fulfill failed: ${fulfillErr instanceof Error ? fulfillErr.message : String(fulfillErr)}`);
72470
72495
  }
@@ -72735,6 +72760,227 @@ ${baseText}`;
72735
72760
  }
72736
72761
  }
72737
72762
  }
72763
+ /**
72764
+ * #1225: fulfil ONE pending A2A Welcome request — the `/distribute` path.
72765
+ * Extracted from the delivery pull so the in-flight slot (review F1) is held
72766
+ * for exactly this request and released on every exit. Returns "stop" when
72767
+ * nothing else on this channel can succeed this pull (review F2).
72768
+ */
72769
+ async _fulfilA2AWelcome(chId, chState, mlsGroup, req) {
72770
+ const a2aLabel = `A2A ${chId.slice(0, 8)}`;
72771
+ const preHead = await this._readGroupHead(chState.mlsGroupId);
72772
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
72773
+ console.warn(
72774
+ `[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`
72775
+ );
72776
+ await this._catchUpAfterPreflightSkip(chState.mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), a2aLabel);
72777
+ return "stop";
72778
+ }
72779
+ const inFlight = this._reserveCommit(chState.mlsGroupId, a2aLabel);
72780
+ if (!inFlight) return "stop";
72781
+ try {
72782
+ const kpRes = await fetch(
72783
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
72784
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
72785
+ );
72786
+ if (!kpRes.ok) return "next";
72787
+ const kpData = await kpRes.json();
72788
+ const kpHex = kpData[req.requesting_device_id];
72789
+ if (!kpHex) return "next";
72790
+ const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
72791
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
72792
+ console.log(`[SecureChannel] A2A addMembers for ${req.requesting_device_id.slice(0, 8)} group=${chState.mlsGroupId.slice(0, 8)} epoch=${mlsGroup.epoch}`);
72793
+ let parentDigest = preHead.ok ? preHead.digest : void 0;
72794
+ let commit;
72795
+ let welcome;
72796
+ let preAddState = mlsGroup.exportState();
72797
+ try {
72798
+ const result = await mlsGroup.addMembers([memberKp]);
72799
+ commit = result.commit;
72800
+ welcome = result.welcome;
72801
+ } catch (addErr) {
72802
+ const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
72803
+ if (errMsg.includes("already in the group")) {
72804
+ console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
72805
+ const preRemoveState = JSON.stringify(mlsGroup.exportState());
72806
+ let removeCommitPublished = false;
72807
+ try {
72808
+ const identityBytes = new TextEncoder().encode(req.requesting_device_id);
72809
+ const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
72810
+ if (leafIndex === null) {
72811
+ console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
72812
+ return "next";
72813
+ }
72814
+ const removeResult = await mlsGroup.removeMember(leafIndex);
72815
+ try {
72816
+ const removeResp = await fetch(
72817
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72818
+ {
72819
+ method: "POST",
72820
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72821
+ body: JSON.stringify({
72822
+ group_id: chState.mlsGroupId,
72823
+ device_id: this._deviceId,
72824
+ commit: Buffer.from(removeResult.commit).toString("hex"),
72825
+ commit_epoch: Number(mlsGroup.epoch),
72826
+ expected_epoch: Number(mlsGroup.epoch) - 1,
72827
+ // #1225: exact-step, like the WS path
72828
+ ...parentDigest ? { parent_digest: parentDigest } : {}
72829
+ })
72830
+ }
72831
+ );
72832
+ if (removeResp.ok) {
72833
+ removeCommitPublished = true;
72834
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
72835
+ parentDigest = this._commitDigest(removeResult.commit);
72836
+ } else {
72837
+ const detail = await removeResp.text().catch(() => "");
72838
+ console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
72839
+ }
72840
+ } catch (distErr) {
72841
+ console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
72842
+ }
72843
+ if (!removeCommitPublished) {
72844
+ mlsGroup.importState(JSON.parse(preRemoveState));
72845
+ return "next";
72846
+ }
72847
+ const kpRes2 = await fetch(
72848
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
72849
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
72850
+ );
72851
+ if (kpRes2.ok) {
72852
+ const kpData2 = await kpRes2.json();
72853
+ const kpHex2 = kpData2[req.requesting_device_id];
72854
+ if (kpHex2) {
72855
+ const kpBytes2 = new Uint8Array(Buffer.from(kpHex2, "hex"));
72856
+ const memberKp2 = MLSGroupManager.deserializeKeyPackage(kpBytes2);
72857
+ preAddState = mlsGroup.exportState();
72858
+ const result2 = await mlsGroup.addMembers([memberKp2]);
72859
+ commit = result2.commit;
72860
+ welcome = result2.welcome;
72861
+ } else {
72862
+ console.log(`[SecureChannel] A2A re-add: no fresh KeyPackage for ${req.requesting_device_id.slice(0, 8)}`);
72863
+ return "next";
72864
+ }
72865
+ } else {
72866
+ console.log(`[SecureChannel] A2A re-add: KeyPackage fetch failed (${kpRes2.status})`);
72867
+ return "next";
72868
+ }
72869
+ } catch (readdErr) {
72870
+ console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
72871
+ if (!removeCommitPublished) {
72872
+ try {
72873
+ mlsGroup.importState(JSON.parse(preRemoveState));
72874
+ } catch {
72875
+ }
72876
+ }
72877
+ return "next";
72878
+ }
72879
+ } else {
72880
+ console.log(`[SecureChannel] A2A addMembers FAILED: ${errMsg}`);
72881
+ return "next";
72882
+ }
72883
+ }
72884
+ if (!welcome) {
72885
+ console.warn(`[SecureChannel] A2A addMembers produced no Welcome for ${req.requesting_device_id.slice(0, 8)}`);
72886
+ return "next";
72887
+ }
72888
+ const commitHex = Buffer.from(commit).toString("hex");
72889
+ const welcomeHex = Buffer.from(welcome).toString("hex");
72890
+ let distributed = false;
72891
+ let transportFailed = false;
72892
+ const updatedMembers = this._commitRoster([this._deviceId], [req.requesting_device_id]);
72893
+ try {
72894
+ const distResp = await fetch(
72895
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
72896
+ {
72897
+ method: "POST",
72898
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
72899
+ body: JSON.stringify({
72900
+ group_id: chState.mlsGroupId,
72901
+ device_id: this._deviceId,
72902
+ commit: commitHex,
72903
+ commit_epoch: Number(mlsGroup.epoch),
72904
+ welcomes: [{ target_device_id: req.requesting_device_id, payload: welcomeHex }],
72905
+ member_device_ids: updatedMembers,
72906
+ expected_epoch: Number(mlsGroup.epoch) - 1,
72907
+ // #1225: exact-step, like the WS path
72908
+ ...parentDigest ? { parent_digest: parentDigest } : {}
72909
+ })
72910
+ }
72911
+ );
72912
+ if (distResp.ok) {
72913
+ distributed = true;
72914
+ } else {
72915
+ const detail = await distResp.text().catch(() => "");
72916
+ console.warn(`[SecureChannel] A2A distribute failed (${distResp.status}): ${detail}`);
72917
+ if (distResp.status >= 500) {
72918
+ transportFailed = true;
72919
+ } else if (distResp.status === 409) {
72920
+ mlsGroup.importState(preAddState);
72921
+ console.warn(
72922
+ `[SecureChannel] ${a2aLabel}: add commit lost the race (409) \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, request stays pending`
72923
+ );
72924
+ return "next";
72925
+ } else {
72926
+ mlsGroup.importState(preAddState);
72927
+ console.error(
72928
+ `[SecureChannel] ${a2aLabel}: add commit refused with ${distResp.status} \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}; not retrying this channel this pull`
72929
+ );
72930
+ return "stop";
72931
+ }
72932
+ }
72933
+ } catch (distErr) {
72934
+ console.warn(`[SecureChannel] A2A distribute network error:`, distErr);
72935
+ transportFailed = true;
72936
+ }
72937
+ if (!distributed && transportFailed && this._wsIsOpen()) {
72938
+ const verdict = await this._sendCommitConfirmed({
72939
+ mlsGroup,
72940
+ mlsGroupId: chState.mlsGroupId,
72941
+ label: a2aLabel,
72942
+ commit,
72943
+ epoch: Number(mlsGroup.epoch),
72944
+ parent: parentDigest,
72945
+ memberDeviceIds: updatedMembers,
72946
+ stateBefore: preAddState,
72947
+ inFlight
72948
+ });
72949
+ if (verdict !== "confirmed") return "next";
72950
+ const welcomeSent = await this._sendFrameConfirmed({
72951
+ event: "mls_welcome",
72952
+ data: {
72953
+ target_device_id: req.requesting_device_id,
72954
+ group_id: chState.mlsGroupId,
72955
+ a2a_channel_id: chId,
72956
+ payload: welcomeHex
72957
+ }
72958
+ }, `${a2aLabel} welcome`);
72959
+ if (!welcomeSent) {
72960
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
72961
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome frame was NOT written \u2014 leaving the request pending`);
72962
+ return "next";
72963
+ }
72964
+ distributed = true;
72965
+ }
72966
+ if (!distributed) {
72967
+ console.warn(`[SecureChannel] Cannot deliver Welcome \u2014 HTTP distribute and WS both unavailable`);
72968
+ return "next";
72969
+ }
72970
+ const a2aFulfilled = await this._postFulfilWelcome(
72971
+ chState.mlsGroupId,
72972
+ req.id,
72973
+ `A2A ${chId.slice(0, 8)}`
72974
+ );
72975
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
72976
+ if (a2aFulfilled) {
72977
+ console.log(`[SecureChannel] Fulfilled A2A Welcome for ${req.requesting_device_id.slice(0, 8)} in channel ${chId.slice(0, 8)}`);
72978
+ }
72979
+ return "next";
72980
+ } finally {
72981
+ await this._releaseCommit(chState.mlsGroupId, inFlight, a2aLabel);
72982
+ }
72983
+ }
72738
72984
  /**
72739
72985
  * Found the MLS group for an A2A channel as the creator agent.
72740
72986
  * Calls /mls/a2a/{channelId}/init, creates the local MLS group, and sends
@@ -72777,48 +73023,77 @@ ${baseText}`;
72777
73023
  await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
72778
73024
  for (const p2 of participants) {
72779
73025
  if (p2.status !== "active" && p2.status !== "invited") continue;
73026
+ const a2aLabel = `A2A ${channelId.slice(0, 8)} found\u2192${p2.hubAddress}`;
72780
73027
  try {
72781
- const kpRes = await fetch(
72782
- `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(p2.hubId)}`,
72783
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
72784
- );
72785
- if (kpRes.ok) {
72786
- const kpData = await kpRes.json();
72787
- if (kpData.key_package) {
72788
- const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
72789
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
72790
- const { commit, welcome } = await mgr.addMembers([memberKp]);
72791
- if (welcome && this._ws) {
72792
- this._ws.send(JSON.stringify({
72793
- event: "mls_commit",
73028
+ if (!p2.deviceId) {
73029
+ console.warn(
73030
+ `[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.`
73031
+ );
73032
+ continue;
73033
+ }
73034
+ if (!this._wsIsOpen()) {
73035
+ console.warn(`[SecureChannel] ${a2aLabel}: socket is not OPEN \u2014 NOT advancing the group`);
73036
+ continue;
73037
+ }
73038
+ const head = await this._readGroupHead(mlsData.group_id);
73039
+ if (head.ok && head.epoch !== Number(mgr.epoch)) {
73040
+ console.warn(`[SecureChannel] ${a2aLabel}: server head is at epoch ${head.epoch}, we are at ${Number(mgr.epoch)} \u2014 NOT committing`);
73041
+ await this._catchUpAfterPreflightSkip(mlsData.group_id, head.epoch, Number(mgr.epoch), a2aLabel);
73042
+ continue;
73043
+ }
73044
+ const inFlight = this._reserveCommit(mlsData.group_id, a2aLabel);
73045
+ if (!inFlight) continue;
73046
+ try {
73047
+ const kpRes = await fetch(
73048
+ `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(p2.hubId)}`,
73049
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
73050
+ );
73051
+ if (kpRes.ok) {
73052
+ const kpData = await kpRes.json();
73053
+ if (kpData.key_package) {
73054
+ const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
73055
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
73056
+ const stateBefore = mgr.exportState();
73057
+ const { commit, welcome } = await mgr.addMembers([memberKp]);
73058
+ const committedEpoch = Number(mgr.epoch);
73059
+ if (!welcome) {
73060
+ mgr.importState(stateBefore);
73061
+ console.warn(`[SecureChannel] ${a2aLabel}: addMembers produced no Welcome \u2014 rolled back`);
73062
+ continue;
73063
+ }
73064
+ const verdict = await this._sendCommitConfirmed({
73065
+ mlsGroup: mgr,
73066
+ mlsGroupId: mlsData.group_id,
73067
+ label: a2aLabel,
73068
+ commit,
73069
+ epoch: committedEpoch,
73070
+ parent: head.ok ? head.digest : void 0,
73071
+ memberDeviceIds: this._commitRoster(participants.map((q22) => q22.deviceId), [p2.deviceId]),
73072
+ stateBefore,
73073
+ inFlight
73074
+ });
73075
+ if (verdict !== "confirmed") continue;
73076
+ const sent = await this._sendFrameConfirmed({
73077
+ event: "mls_welcome",
72794
73078
  data: {
72795
73079
  group_id: mlsData.group_id,
72796
- epoch: Number(mgr.epoch),
72797
- payload: Buffer.from(commit).toString("hex")
73080
+ payload: Buffer.from(welcome).toString("hex"),
73081
+ target_device_id: p2.deviceId,
73082
+ a2a_channel_id: channelId,
73083
+ target_hub_id: p2.hubId
73084
+ // observability only — the backend ignores it
72798
73085
  }
72799
- }));
72800
- if (!p2.deviceId) {
72801
- console.warn(
72802
- `[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.`
72803
- );
72804
- } else {
72805
- this._ws.send(JSON.stringify({
72806
- event: "mls_welcome",
72807
- data: {
72808
- group_id: mlsData.group_id,
72809
- payload: Buffer.from(welcome).toString("hex"),
72810
- target_device_id: p2.deviceId,
72811
- a2a_channel_id: channelId,
72812
- // Kept for observability — backend ignores but it's
72813
- // useful in logs/wire captures to correlate to a hub.
72814
- target_hub_id: p2.hubId
72815
- }
72816
- }));
73086
+ }, `${a2aLabel} welcome`);
73087
+ await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
73088
+ if (sent) {
72817
73089
  console.log(`[SecureChannel] Sent MLS Welcome to ${p2.hubAddress} (device ${p2.deviceId.slice(0, 8)}) for A2A ${channelId.slice(0, 8)}`);
73090
+ } else {
73091
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome was NOT written \u2014 the participant will request one`);
72818
73092
  }
72819
73093
  }
72820
- await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
72821
73094
  }
73095
+ } finally {
73096
+ await this._releaseCommit(mlsData.group_id, inFlight, a2aLabel);
72822
73097
  }
72823
73098
  } catch (kpErr) {
72824
73099
  console.warn(`[SecureChannel] Failed to Welcome participant ${p2.hubAddress}:`, kpErr);
@@ -99890,7 +100165,7 @@ var init_index = __esm2({
99890
100165
  await init_skill_telemetry();
99891
100166
  await init_policy_enforcer();
99892
100167
  init_room_protocol();
99893
- VERSION = true ? "0.23.40" : "0.0.0-dev";
100168
+ VERSION = true ? "0.23.42" : "0.0.0-dev";
99894
100169
  }
99895
100170
  });
99896
100171
  await init_index();
@@ -136082,7 +136357,7 @@ function _makeOwesReply(agentName, channel, log) {
136082
136357
  );
136083
136358
  }
136084
136359
  return owesRoomReply(
136085
- e7.plaintext,
136360
+ e7.caption ?? e7.plaintext,
136086
136361
  own,
136087
136362
  own,
136088
136363
  e7.senderIsAgent,
@@ -136306,7 +136581,7 @@ async function main() {
136306
136581
  "[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"
136307
136582
  );
136308
136583
  }
136309
- logLine(`[bridge] version: ${true ? "0.8.13" : "dev"}`);
136584
+ logLine(`[bridge] version: ${true ? "0.8.15" : "dev"}`);
136310
136585
  logLine(`[bridge] data dir: ${cfg.dataDir} (${cfg.dataDirSource})`);
136311
136586
  logLine(`[bridge] workspace: ${cfg.workspaceDir} \xB7 permissions: ${cfg.permissionMode} \xB7 enclave dir fenced`);
136312
136587
  if (cfg.armRoom) {
@@ -136338,7 +136613,7 @@ async function main() {
136338
136613
  // its default would render "@agentvault/agentvault@0.7.x" — the wrong
136339
136614
  // package name attached to the bridge's version number, which is worse
136340
136615
  // than either alone.
136341
- clientVersion: `@agentvault/claude-bridge@${true ? "0.8.13" : "dev"}`
136616
+ clientVersion: `@agentvault/claude-bridge@${true ? "0.8.15" : "dev"}`
136342
136617
  });
136343
136618
  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.`;
136344
136619
  const deviceJwt = () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/claude-bridge",
3
- "version": "0.8.13",
3
+ "version": "0.8.15",
4
4
  "type": "module",
5
5
  "description": "AgentVault Claude Bridge — daemon for bridging a Claude agent into secure E2E-encrypted AgentVault 1:1 direct messages and rooms.",
6
6
  "main": "dist/index.js",