@agentvault/claude-bridge 0.8.13 → 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.
Files changed (2) hide show
  1. package/dist/index.js +534 -270
  2. package/package.json +1 -1
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.41" : FALLBACK;
64668
64668
  return `${PACKAGE}@${v22}`;
64669
64669
  }
64670
64670
  function buildSha() {
64671
- const raw = true ? "dbac15d-dirty" : "";
64671
+ const raw = true ? "916d6c5-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.41" : "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.41" : "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.41" : "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
  }
@@ -70962,9 +70997,34 @@ ${baseText}`;
70962
70997
  *
70963
70998
  * Returns the number of requests actually fulfilled.
70964
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
+ }
70965
71023
  async _fulfilWelcomeRequests(opts) {
70966
71024
  const { mlsGroup, mlsGroupId, label, welcomeFields, targets } = opts;
70967
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));
70968
71028
  if (!this._wsIsOpen()) {
70969
71029
  console.warn(
70970
71030
  `[SecureChannel] ${label}: socket is not OPEN \u2014 NOT advancing the group; ${targets.length} request(s) stay pending for the next pull`
@@ -70977,9 +71037,16 @@ ${baseText}`;
70977
71037
  console.warn(
70978
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`
70979
71039
  );
71040
+ await this._catchUpAfterPreflightSkip(mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), label);
70980
71041
  return 0;
70981
71042
  }
70982
71043
  let parent2 = preHead.ok ? preHead.digest : void 0;
71044
+ if (this._commitInFlight.has(mlsGroupId)) {
71045
+ console.warn(
71046
+ `[SecureChannel] ${label}: another commit for this group is in flight \u2014 NOT advancing; ${targets.length} request(s) stay pending for the next pull`
71047
+ );
71048
+ return 0;
71049
+ }
70983
71050
  const inFlight = { frames: [], sent: [] };
70984
71051
  this._commitInFlight.set(mlsGroupId, inFlight);
70985
71052
  try {
@@ -71004,7 +71071,8 @@ ${baseText}`;
71004
71071
  // only knows the last one, which is why the result carries them.
71005
71072
  epoch: Number(c22.epoch),
71006
71073
  payload: Buffer.from(c22.commit).toString("hex"),
71007
- ...parent2 ? { parent_digest: parent2 } : {}
71074
+ ...parent2 ? { parent_digest: parent2 } : {},
71075
+ ...(sentCommits === commits.length - 1 ? rosterAfter : rosterBefore).length > 0 ? { member_device_ids: sentCommits === commits.length - 1 ? rosterAfter : rosterBefore } : {}
71008
71076
  }
71009
71077
  },
71010
71078
  `${label} commit ${sentCommits + 1}/${commits.length}`
@@ -71152,6 +71220,126 @@ ${baseText}`;
71152
71220
  return this._ws?.readyState === 1;
71153
71221
  }
71154
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
+ }
71155
71343
  _commitDigest(bytes) {
71156
71344
  return createHash("sha256").update(bytes).digest("hex");
71157
71345
  }
@@ -72105,7 +72293,9 @@ ${baseText}`;
72105
72293
  mlsGroupId: roomState.mlsGroupId,
72106
72294
  label: `room ${roomId.slice(0, 8)}`,
72107
72295
  welcomeFields: { room_id: roomId },
72108
- targets: roomTargets
72296
+ targets: roomTargets,
72297
+ memberDeviceIds: (roomState.members ?? []).map((m22) => m22.deviceId)
72298
+ // #1226
72109
72299
  });
72110
72300
  if (done > 0) {
72111
72301
  console.log(
@@ -72160,7 +72350,9 @@ ${baseText}`;
72160
72350
  mlsGroupId: entry.mlsGroupId,
72161
72351
  label: `shared group ${gid.slice(0, 8)}`,
72162
72352
  welcomeFields: { conversation_group_id: gid },
72163
- targets: sharedTargets
72353
+ targets: sharedTargets,
72354
+ memberDeviceIds: entry.memberDeviceIds ?? []
72355
+ // #1226
72164
72356
  });
72165
72357
  if (done > 0) {
72166
72358
  console.log(`[SecureChannel] Batched Welcome for ${done}/${validReqs.length} devices in shared group ${gid.slice(0, 8)} (epoch=${mlsGroup.epoch})`);
@@ -72174,7 +72366,9 @@ ${baseText}`;
72174
72366
  mlsGroupId: entry.mlsGroupId,
72175
72367
  label: `shared group ${gid.slice(0, 8)}`,
72176
72368
  welcomeFields: { conversation_group_id: gid },
72177
- targets: [target]
72369
+ targets: [target],
72370
+ memberDeviceIds: entry.memberDeviceIds ?? []
72371
+ // #1226
72178
72372
  });
72179
72373
  if (done > 0) {
72180
72374
  console.log(`[SecureChannel] Individual Welcome for ${target.deviceId.slice(0, 8)} in shared group ${gid.slice(0, 8)}`);
@@ -72221,7 +72415,11 @@ ${baseText}`;
72221
72415
  requestId: req.id,
72222
72416
  deviceId: req.requesting_device_id,
72223
72417
  keyPackage: memberKp
72224
- }]
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
+ )
72225
72423
  });
72226
72424
  if (done > 0) {
72227
72425
  console.log(`[SecureChannel] Fulfilled Welcome for ${req.requesting_device_id.slice(0, 8)} in conv ${convId.slice(0, 8)}`);
@@ -72279,192 +72477,8 @@ ${baseText}`;
72279
72477
  console.log(`[SecureChannel] ${pending.length} pending A2A Welcome requests for channel ${chId.slice(0, 8)}`);
72280
72478
  for (const req of pending) {
72281
72479
  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
- }
72480
+ const next = await this._fulfilA2AWelcome(chId, chState, mlsGroup, req);
72481
+ if (next === "stop") break;
72468
72482
  } catch (fulfillErr) {
72469
72483
  console.log(`[SecureChannel] A2A Welcome fulfill failed: ${fulfillErr instanceof Error ? fulfillErr.message : String(fulfillErr)}`);
72470
72484
  }
@@ -72735,6 +72749,227 @@ ${baseText}`;
72735
72749
  }
72736
72750
  }
72737
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
+ }
72738
72973
  /**
72739
72974
  * Found the MLS group for an A2A channel as the creator agent.
72740
72975
  * Calls /mls/a2a/{channelId}/init, creates the local MLS group, and sends
@@ -72777,48 +73012,77 @@ ${baseText}`;
72777
73012
  await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
72778
73013
  for (const p2 of participants) {
72779
73014
  if (p2.status !== "active" && p2.status !== "invited") continue;
73015
+ const a2aLabel = `A2A ${channelId.slice(0, 8)} found\u2192${p2.hubAddress}`;
72780
73016
  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",
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",
72794
73067
  data: {
72795
73068
  group_id: mlsData.group_id,
72796
- epoch: Number(mgr.epoch),
72797
- 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
72798
73074
  }
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
- }));
73075
+ }, `${a2aLabel} welcome`);
73076
+ await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
73077
+ if (sent) {
72817
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`);
72818
73081
  }
72819
73082
  }
72820
- await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
72821
73083
  }
73084
+ } finally {
73085
+ await this._releaseCommit(mlsData.group_id, inFlight, a2aLabel);
72822
73086
  }
72823
73087
  } catch (kpErr) {
72824
73088
  console.warn(`[SecureChannel] Failed to Welcome participant ${p2.hubAddress}:`, kpErr);
@@ -99890,7 +100154,7 @@ var init_index = __esm2({
99890
100154
  await init_skill_telemetry();
99891
100155
  await init_policy_enforcer();
99892
100156
  init_room_protocol();
99893
- VERSION = true ? "0.23.40" : "0.0.0-dev";
100157
+ VERSION = true ? "0.23.41" : "0.0.0-dev";
99894
100158
  }
99895
100159
  });
99896
100160
  await init_index();
@@ -136306,7 +136570,7 @@ async function main() {
136306
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"
136307
136571
  );
136308
136572
  }
136309
- logLine(`[bridge] version: ${true ? "0.8.13" : "dev"}`);
136573
+ logLine(`[bridge] version: ${true ? "0.8.14" : "dev"}`);
136310
136574
  logLine(`[bridge] data dir: ${cfg.dataDir} (${cfg.dataDirSource})`);
136311
136575
  logLine(`[bridge] workspace: ${cfg.workspaceDir} \xB7 permissions: ${cfg.permissionMode} \xB7 enclave dir fenced`);
136312
136576
  if (cfg.armRoom) {
@@ -136338,7 +136602,7 @@ async function main() {
136338
136602
  // its default would render "@agentvault/agentvault@0.7.x" — the wrong
136339
136603
  // package name attached to the bridge's version number, which is worse
136340
136604
  // than either alone.
136341
- clientVersion: `@agentvault/claude-bridge@${true ? "0.8.13" : "dev"}`
136605
+ clientVersion: `@agentvault/claude-bridge@${true ? "0.8.14" : "dev"}`
136342
136606
  });
136343
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.`;
136344
136608
  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.14",
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",