@agentvault/agentvault 0.23.40 → 0.23.41

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/cli.js CHANGED
@@ -63285,11 +63285,11 @@ var init_mls_kp_pool = __esm({
63285
63285
 
63286
63286
  // src/client-version.ts
63287
63287
  function ownIdentity() {
63288
- const v2 = true ? "0.23.40" : FALLBACK;
63288
+ const v2 = true ? "0.23.41" : FALLBACK;
63289
63289
  return `${PACKAGE}@${v2}`;
63290
63290
  }
63291
63291
  function buildSha() {
63292
- const raw = true ? "dbac15d-dirty" : "";
63292
+ const raw = true ? "916d6c5-dirty" : "";
63293
63293
  const cleaned = (raw ?? "").trim();
63294
63294
  return !cleaned || cleaned === "unknown" ? null : cleaned;
63295
63295
  }
@@ -64218,7 +64218,7 @@ function _isSelfHubAddress(ownHubAddress, target) {
64218
64218
  const tgt = (target ?? "").trim().toLowerCase();
64219
64219
  return own.length > 0 && own === tgt;
64220
64220
  }
64221
- var ROOM_AGENT_TYPES, CREDENTIAL_MESSAGE_TYPES, CATCHUP_MESSAGE_TYPES, POLL_INTERVAL_MS, RECONNECT_BASE_MS, RECONNECT_MAX_MS, PENDING_POLL_INTERVAL_MS, OUTBOUND_DEDUPE_WINDOW_MS, OUTBOUND_DEDUPE_MAX_SUPPRESS_MS, OUTBOUND_DEDUPE_MAX, OUTBOUND_DEDUPE_TYPES, RETRY_CANDIDATE_TTL_MS, RETRY_CANDIDATE_MAX, ROOM_FULFIL_COOLDOWN_MS, SecureChannel;
64221
+ var ROOM_AGENT_TYPES, CREDENTIAL_MESSAGE_TYPES, CATCHUP_MESSAGE_TYPES, POLL_INTERVAL_MS, RECONNECT_BASE_MS, UUID_RE, RECONNECT_MAX_MS, PENDING_POLL_INTERVAL_MS, OUTBOUND_DEDUPE_WINDOW_MS, OUTBOUND_DEDUPE_MAX_SUPPRESS_MS, OUTBOUND_DEDUPE_MAX, OUTBOUND_DEDUPE_TYPES, RETRY_CANDIDATE_TTL_MS, RETRY_CANDIDATE_MAX, ROOM_FULFIL_COOLDOWN_MS, SecureChannel;
64222
64222
  var init_channel = __esm({
64223
64223
  async "src/channel.ts"() {
64224
64224
  "use strict";
@@ -64256,6 +64256,7 @@ var init_channel = __esm({
64256
64256
  ]);
64257
64257
  POLL_INTERVAL_MS = 6e3;
64258
64258
  RECONNECT_BASE_MS = 1e3;
64259
+ UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
64259
64260
  RECONNECT_MAX_MS = 3e4;
64260
64261
  PENDING_POLL_INTERVAL_MS = 15e3;
64261
64262
  OUTBOUND_DEDUPE_WINDOW_MS = 3e3;
@@ -65551,7 +65552,7 @@ ${text}`;
65551
65552
  */
65552
65553
  sendActivitySpan(spanData) {
65553
65554
  if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return;
65554
- const pluginVersion = true ? "0.23.40" : "0.0.0-dev";
65555
+ const pluginVersion = true ? "0.23.41" : "0.0.0-dev";
65555
65556
  const agentName = this.config.agentName ?? "Agent";
65556
65557
  const resource = {
65557
65558
  "service.name": "agentvault-agent",
@@ -67489,7 +67490,7 @@ ${text}`;
67489
67490
  agentVersion: this.config.agentVersion ?? "0.0.0",
67490
67491
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
67491
67492
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
67492
- pluginVersion: true ? "0.23.40" : "0.0.0-dev"
67493
+ pluginVersion: true ? "0.23.41" : "0.0.0-dev"
67493
67494
  });
67494
67495
  this._telemetryReporter.startAutoFlush(3e4);
67495
67496
  }
@@ -67813,7 +67814,7 @@ ${text}`;
67813
67814
  agentVersion: this.config.agentVersion ?? "0.0.0",
67814
67815
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
67815
67816
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
67816
- pluginVersion: true ? "0.23.40" : "0.0.0-dev"
67817
+ pluginVersion: true ? "0.23.41" : "0.0.0-dev"
67817
67818
  });
67818
67819
  this._telemetryReporter.startAutoFlush(3e4);
67819
67820
  }
@@ -68028,45 +68029,78 @@ ${text}`;
68028
68029
  const mlsGroup = this._mlsGroups.get(`a2a:${channelId}`);
68029
68030
  if (mlsGroup?.isInitialized) {
68030
68031
  try {
68031
- const kpRes = await fetch(
68032
- `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(participant.hub_id)}`,
68033
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
68034
- );
68035
- if (kpRes.ok) {
68036
- const kpData = await kpRes.json();
68037
- if (kpData.key_package) {
68038
- const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
68039
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
68040
- const { commit, welcome } = await mlsGroup.addMembers([memberKp]);
68041
- if (welcome && this._ws) {
68042
- this._ws.send(JSON.stringify({
68043
- event: "mls_commit",
68044
- data: {
68045
- group_id: entry.mlsGroupId,
68046
- epoch: Number(mlsGroup.epoch),
68047
- payload: Buffer.from(commit).toString("hex")
68048
- }
68049
- }));
68050
- const newDeviceId = participant.device_id || null;
68051
- if (!newDeviceId) {
68052
- console.warn(
68053
- `[SecureChannel] Skipping MLS Welcome to new participant ${participant.hub_address} for A2A ${channelId.slice(0, 8)}: no device_id on participant_joined payload.`
68054
- );
68055
- } else {
68056
- this._ws.send(JSON.stringify({
68057
- event: "mls_welcome",
68058
- data: {
68059
- group_id: entry.mlsGroupId,
68060
- payload: Buffer.from(welcome).toString("hex"),
68061
- target_device_id: newDeviceId,
68062
- a2a_channel_id: channelId,
68063
- target_hub_id: participant.hub_id
68064
- // observability only
68032
+ const newDeviceId = participant.device_id || null;
68033
+ const a2aLabel = `A2A ${channelId.slice(0, 8)} participant_joined`;
68034
+ if (!newDeviceId) {
68035
+ console.warn(
68036
+ `[SecureChannel] ${a2aLabel}: no device_id on the payload for ${participant.hub_address} \u2014 NOT adding (a Welcome could not be addressed)`
68037
+ );
68038
+ } else if (!this._wsIsOpen()) {
68039
+ console.warn(`[SecureChannel] ${a2aLabel}: socket is not OPEN \u2014 NOT advancing the group`);
68040
+ } else {
68041
+ const preHead = await this._readGroupHead(entry.mlsGroupId);
68042
+ const inFlight = preHead.ok && preHead.epoch !== Number(mlsGroup.epoch) ? null : this._reserveCommit(entry.mlsGroupId, a2aLabel);
68043
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
68044
+ console.warn(
68045
+ `[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`
68046
+ );
68047
+ await this._catchUpAfterPreflightSkip(entry.mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), a2aLabel);
68048
+ } else if (inFlight) {
68049
+ try {
68050
+ const kpRes = await fetch(
68051
+ `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(participant.hub_id)}`,
68052
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
68053
+ );
68054
+ if (kpRes.ok) {
68055
+ const kpData = await kpRes.json();
68056
+ if (kpData.key_package) {
68057
+ const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
68058
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
68059
+ const stateBefore = mlsGroup.exportState();
68060
+ const { commit, welcome } = await mlsGroup.addMembers([memberKp]);
68061
+ const committedEpoch = Number(mlsGroup.epoch);
68062
+ if (!welcome) {
68063
+ mlsGroup.importState(stateBefore);
68064
+ console.warn(`[SecureChannel] ${a2aLabel}: addMembers produced no Welcome \u2014 rolled back`);
68065
+ } else {
68066
+ const verdict = await this._sendCommitConfirmed({
68067
+ mlsGroup,
68068
+ mlsGroupId: entry.mlsGroupId,
68069
+ label: a2aLabel,
68070
+ commit,
68071
+ epoch: committedEpoch,
68072
+ parent: preHead.ok ? preHead.digest : void 0,
68073
+ memberDeviceIds: this._commitRoster(
68074
+ (entry.participants ?? []).map((p2) => p2.deviceId),
68075
+ [newDeviceId]
68076
+ ),
68077
+ stateBefore,
68078
+ inFlight
68079
+ });
68080
+ if (verdict === "confirmed") {
68081
+ const sent = await this._sendFrameConfirmed({
68082
+ event: "mls_welcome",
68083
+ data: {
68084
+ group_id: entry.mlsGroupId,
68085
+ payload: Buffer.from(welcome).toString("hex"),
68086
+ target_device_id: newDeviceId,
68087
+ a2a_channel_id: channelId,
68088
+ target_hub_id: participant.hub_id
68089
+ // observability only
68090
+ }
68091
+ }, `${a2aLabel} welcome`);
68092
+ await saveMlsState(this.config.dataDir, entry.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
68093
+ if (sent) {
68094
+ console.log(`[SecureChannel] Sent MLS Welcome to new participant ${participant.hub_address} (device ${String(newDeviceId).slice(0, 8)})`);
68095
+ } else {
68096
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome to ${String(newDeviceId).slice(0, 8)} was NOT written \u2014 the participant will request one`);
68097
+ }
68098
+ }
68065
68099
  }
68066
- }));
68067
- await saveMlsState(this.config.dataDir, entry.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
68068
- console.log(`[SecureChannel] Sent MLS Welcome to new participant ${participant.hub_address} (device ${String(newDeviceId).slice(0, 8)})`);
68100
+ }
68069
68101
  }
68102
+ } finally {
68103
+ await this._releaseCommit(entry.mlsGroupId, inFlight, a2aLabel);
68070
68104
  }
68071
68105
  }
68072
68106
  }
@@ -69596,9 +69630,34 @@ ${baseText}`;
69596
69630
  *
69597
69631
  * Returns the number of requests actually fulfilled.
69598
69632
  */
69633
+ /**
69634
+ * #1226: the roster to submit on a commit frame — the caller's known members,
69635
+ * the devices being admitted, and ALWAYS ourselves — deduplicated, UUIDs
69636
+ * only. Self is non-negotiable: once a roster is non-empty the server
69637
+ * requires the committer in it (#469), and our own head read
69638
+ * (`assert_group_member`) requires it too. So with no device id of our own
69639
+ * this returns `[]` and the frame carries NO roster (the pre-#1226 shape)
69640
+ * rather than a roster that locks us out. Non-UUID entries are dropped:
69641
+ * `known` can come off an inbound Welcome frame, and a malformed id in the
69642
+ * outbound frame is refused by the server (`MEMBER_DEVICE_IDS_MALFORMED`).
69643
+ * @internal exposed for tests
69644
+ */
69645
+ _commitRoster(known, targets) {
69646
+ if (!this._deviceId) return [];
69647
+ const out = [];
69648
+ const seen = /* @__PURE__ */ new Set();
69649
+ for (const id of [...known ?? [], ...targets, this._deviceId]) {
69650
+ if (typeof id !== "string" || !UUID_RE.test(id) || seen.has(id)) continue;
69651
+ seen.add(id);
69652
+ out.push(id);
69653
+ }
69654
+ return out;
69655
+ }
69599
69656
  async _fulfilWelcomeRequests(opts) {
69600
69657
  const { mlsGroup, mlsGroupId, label, welcomeFields, targets } = opts;
69601
69658
  if (targets.length === 0) return 0;
69659
+ const rosterBefore = this._commitRoster(opts.memberDeviceIds, []);
69660
+ const rosterAfter = this._commitRoster(opts.memberDeviceIds, targets.map((t2) => t2.deviceId));
69602
69661
  if (!this._wsIsOpen()) {
69603
69662
  console.warn(
69604
69663
  `[SecureChannel] ${label}: socket is not OPEN \u2014 NOT advancing the group; ${targets.length} request(s) stay pending for the next pull`
@@ -69611,9 +69670,16 @@ ${baseText}`;
69611
69670
  console.warn(
69612
69671
  `[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`
69613
69672
  );
69673
+ await this._catchUpAfterPreflightSkip(mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), label);
69614
69674
  return 0;
69615
69675
  }
69616
69676
  let parent2 = preHead.ok ? preHead.digest : void 0;
69677
+ if (this._commitInFlight.has(mlsGroupId)) {
69678
+ console.warn(
69679
+ `[SecureChannel] ${label}: another commit for this group is in flight \u2014 NOT advancing; ${targets.length} request(s) stay pending for the next pull`
69680
+ );
69681
+ return 0;
69682
+ }
69617
69683
  const inFlight = { frames: [], sent: [] };
69618
69684
  this._commitInFlight.set(mlsGroupId, inFlight);
69619
69685
  try {
@@ -69638,7 +69704,8 @@ ${baseText}`;
69638
69704
  // only knows the last one, which is why the result carries them.
69639
69705
  epoch: Number(c2.epoch),
69640
69706
  payload: Buffer.from(c2.commit).toString("hex"),
69641
- ...parent2 ? { parent_digest: parent2 } : {}
69707
+ ...parent2 ? { parent_digest: parent2 } : {},
69708
+ ...(sentCommits === commits.length - 1 ? rosterAfter : rosterBefore).length > 0 ? { member_device_ids: sentCommits === commits.length - 1 ? rosterAfter : rosterBefore } : {}
69642
69709
  }
69643
69710
  },
69644
69711
  `${label} commit ${sentCommits + 1}/${commits.length}`
@@ -69786,6 +69853,126 @@ ${baseText}`;
69786
69853
  return this._ws?.readyState === 1;
69787
69854
  }
69788
69855
  /** SHA-256 hex of a commit's bytes — its identity on the server (#1175/#1177). */
69856
+ /**
69857
+ * #1225: send ONE commit over the socket and wait for the server's verdict,
69858
+ * with the #1184 machinery — an in-flight record (so a `… commit rejected`
69859
+ * frame is correlated to it and a concurrent commit for the group is held
69860
+ * and replayed), the head poll, and rollback. The three A2A commit sites
69861
+ * (`a2a_participant_joined`, the `/distribute` WS fallback, `_foundA2AGroup`)
69862
+ * used a raw `ws.send` and treated "the socket took it" as "the server
69863
+ * stored it" — two of them then PERSISTED a state the server never saw.
69864
+ *
69865
+ * Returns the verdict. On `refused` / `unsent` the manager has been restored
69866
+ * to `stateBefore` and nothing must be persisted or minted from it.
69867
+ * `unverifiable` (head unreadable on every try AND no refusal) proceeds
69868
+ * UNCHECKED, the same deliberate choice as the fulfil site.
69869
+ */
69870
+ /**
69871
+ * #1225 (review F1): reserve the single in-flight slot for a group. The
69872
+ * record is what `_noteCommitRefusal` correlates a refusal to and what
69873
+ * `_handleMlsCommit` holds concurrent socket commits behind; a second run on
69874
+ * the same group would clobber both (measured: two overlapping joins → two
69875
+ * commits claiming one epoch, one Welcome instead of two, the manager AHEAD
69876
+ * of the server). Taken BEFORE the commit is generated; released by
69877
+ * `_releaseCommit` after the last step that depends on it.
69878
+ */
69879
+ /**
69880
+ * A pre-flight skip must not be a dead end. The skip happens because the
69881
+ * server's head is somewhere else; before this the group "caught up through
69882
+ * the normal divergence path", which only runs when a message for the group
69883
+ * arrives — so a group nobody writes to stayed diverged and its pending
69884
+ * Welcome requests were never fulfilled (named in PR #1227). When the server
69885
+ * is AHEAD, replay the missing commits now so the next pull can commit; when
69886
+ * WE are ahead there is nothing to replay (the fork-ahead direction, #972).
69887
+ */
69888
+ async _catchUpAfterPreflightSkip(mlsGroupId, serverEpoch, localEpoch, label) {
69889
+ if (serverEpoch < localEpoch) {
69890
+ console.warn(`[SecureChannel] ${label}: we are AHEAD of the server (${localEpoch} > ${serverEpoch}) \u2014 nothing to replay`);
69891
+ return;
69892
+ }
69893
+ const fam = this._resolveGroupFamily(mlsGroupId);
69894
+ if (!fam) return;
69895
+ try {
69896
+ const caughtUp = await this._resyncOnDivergence(fam.managerKey, mlsGroupId);
69897
+ console.log(`[SecureChannel] ${label}: catch-up after pre-flight skip ${caughtUp ? "replayed the missing commits" : "could not replay"}`);
69898
+ } catch (err) {
69899
+ console.warn(`[SecureChannel] ${label}: catch-up after pre-flight skip failed:`, err);
69900
+ }
69901
+ }
69902
+ _reserveCommit(groupId, label) {
69903
+ if (this._commitInFlight.has(groupId)) {
69904
+ console.warn(
69905
+ `[SecureChannel] ${label}: another commit for group ${groupId.slice(0, 8)} is in flight \u2014 NOT advancing the group (a Welcome can be requested again)`
69906
+ );
69907
+ return null;
69908
+ }
69909
+ const rec = { frames: [], sent: [] };
69910
+ this._commitInFlight.set(groupId, rec);
69911
+ return rec;
69912
+ }
69913
+ /** Release the slot taken by `_reserveCommit` and replay the socket commits held meanwhile. */
69914
+ async _releaseCommit(groupId, rec, label) {
69915
+ if (this._commitInFlight.get(groupId) === rec) this._commitInFlight.delete(groupId);
69916
+ for (const frame of rec.frames) {
69917
+ try {
69918
+ await this._handleMlsCommit(frame);
69919
+ } catch (err) {
69920
+ console.error(`[SecureChannel] ${label}: replaying a held MLS commit failed:`, err);
69921
+ }
69922
+ }
69923
+ }
69924
+ /**
69925
+ * #1225: send ONE commit over the socket and wait for the server's verdict
69926
+ * with the #1184 machinery (refusal frame correlated through the reserved
69927
+ * in-flight record, head poll). The three A2A commit sites
69928
+ * (`a2a_participant_joined`, the `/distribute` WS fallback, `_foundA2AGroup`)
69929
+ * used a raw `ws.send` and treated "the socket took it" as "the server
69930
+ * stored it" — two of them then PERSISTED a state the server never saw.
69931
+ *
69932
+ * Only `confirmed` proceeds. `unverifiable` (head unreadable on every try,
69933
+ * no refusal) is a ROLLBACK here, unlike the fulfil site: that site proceeds
69934
+ * UNCHECKED because 79 of 80 production rooms 403 the head read on an empty
69935
+ * roster; an A2A head read admits any active participant (observer
69936
+ * fallback), so five failed reads there mean an outage, not a routine 403.
69937
+ * On anything but `confirmed` the manager is back at `stateBefore`.
69938
+ */
69939
+ async _sendCommitConfirmed(opts) {
69940
+ const { mlsGroup, mlsGroupId, label, commit, epoch, parent: parent2, memberDeviceIds, stateBefore, inFlight } = opts;
69941
+ const ours = this._commitDigest(commit);
69942
+ inFlight.sent.push({ epoch, digest: ours, verified: false, stateBefore });
69943
+ const ok = await this._sendFrameConfirmed(
69944
+ {
69945
+ event: "mls_commit",
69946
+ data: {
69947
+ group_id: mlsGroupId,
69948
+ epoch,
69949
+ payload: Buffer.from(commit).toString("hex"),
69950
+ ...parent2 ? { parent_digest: parent2 } : {},
69951
+ ...memberDeviceIds && memberDeviceIds.length > 0 ? { member_device_ids: memberDeviceIds } : {}
69952
+ }
69953
+ },
69954
+ `${label} commit`
69955
+ );
69956
+ if (!ok) {
69957
+ inFlight.sent.pop();
69958
+ mlsGroup.importState(stateBefore);
69959
+ console.warn(
69960
+ `[SecureChannel] ${label}: commit at epoch ${epoch} was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}`
69961
+ );
69962
+ return "unsent";
69963
+ }
69964
+ const verdict = await this._confirmCommitAtHead(mlsGroupId, epoch, ours, inFlight, label);
69965
+ if (inFlight.refusal === void 0 && verdict === "confirmed") {
69966
+ inFlight.sent[inFlight.sent.length - 1].verified = true;
69967
+ return "confirmed";
69968
+ }
69969
+ const why = inFlight.refusal?.detail ?? verdict.toUpperCase();
69970
+ mlsGroup.importState(stateBefore);
69971
+ console.warn(
69972
+ `[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`
69973
+ );
69974
+ return "refused";
69975
+ }
69789
69976
  _commitDigest(bytes) {
69790
69977
  return createHash("sha256").update(bytes).digest("hex");
69791
69978
  }
@@ -70739,7 +70926,9 @@ ${baseText}`;
70739
70926
  mlsGroupId: roomState.mlsGroupId,
70740
70927
  label: `room ${roomId.slice(0, 8)}`,
70741
70928
  welcomeFields: { room_id: roomId },
70742
- targets: roomTargets
70929
+ targets: roomTargets,
70930
+ memberDeviceIds: (roomState.members ?? []).map((m2) => m2.deviceId)
70931
+ // #1226
70743
70932
  });
70744
70933
  if (done > 0) {
70745
70934
  console.log(
@@ -70794,7 +70983,9 @@ ${baseText}`;
70794
70983
  mlsGroupId: entry.mlsGroupId,
70795
70984
  label: `shared group ${gid.slice(0, 8)}`,
70796
70985
  welcomeFields: { conversation_group_id: gid },
70797
- targets: sharedTargets
70986
+ targets: sharedTargets,
70987
+ memberDeviceIds: entry.memberDeviceIds ?? []
70988
+ // #1226
70798
70989
  });
70799
70990
  if (done > 0) {
70800
70991
  console.log(`[SecureChannel] Batched Welcome for ${done}/${validReqs.length} devices in shared group ${gid.slice(0, 8)} (epoch=${mlsGroup.epoch})`);
@@ -70808,7 +70999,9 @@ ${baseText}`;
70808
70999
  mlsGroupId: entry.mlsGroupId,
70809
71000
  label: `shared group ${gid.slice(0, 8)}`,
70810
71001
  welcomeFields: { conversation_group_id: gid },
70811
- targets: [target]
71002
+ targets: [target],
71003
+ memberDeviceIds: entry.memberDeviceIds ?? []
71004
+ // #1226
70812
71005
  });
70813
71006
  if (done > 0) {
70814
71007
  console.log(`[SecureChannel] Individual Welcome for ${target.deviceId.slice(0, 8)} in shared group ${gid.slice(0, 8)}`);
@@ -70855,7 +71048,11 @@ ${baseText}`;
70855
71048
  requestId: req.id,
70856
71049
  deviceId: req.requesting_device_id,
70857
71050
  keyPackage: memberKp
70858
- }]
71051
+ }],
71052
+ // #1226: a 1:1 roster is [self, owner] — the web's shape too.
71053
+ memberDeviceIds: [this._persisted?.sessions?.[convId]?.ownerDeviceId].filter(
71054
+ (d2) => typeof d2 === "string"
71055
+ )
70859
71056
  });
70860
71057
  if (done > 0) {
70861
71058
  console.log(`[SecureChannel] Fulfilled Welcome for ${req.requesting_device_id.slice(0, 8)} in conv ${convId.slice(0, 8)}`);
@@ -70913,192 +71110,8 @@ ${baseText}`;
70913
71110
  console.log(`[SecureChannel] ${pending.length} pending A2A Welcome requests for channel ${chId.slice(0, 8)}`);
70914
71111
  for (const req of pending) {
70915
71112
  try {
70916
- const kpRes = await fetch(
70917
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
70918
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
70919
- );
70920
- if (!kpRes.ok) continue;
70921
- const kpData = await kpRes.json();
70922
- const kpHex = kpData[req.requesting_device_id];
70923
- if (!kpHex) continue;
70924
- const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
70925
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
70926
- console.log(`[SecureChannel] A2A addMembers for ${req.requesting_device_id.slice(0, 8)} group=${chState.mlsGroupId.slice(0, 8)} epoch=${mlsGroup.epoch}`);
70927
- let parentDigest = await this._readGroupHeadDigest(chState.mlsGroupId);
70928
- let commit;
70929
- let welcome;
70930
- try {
70931
- const result = await mlsGroup.addMembers([memberKp]);
70932
- commit = result.commit;
70933
- welcome = result.welcome;
70934
- } catch (addErr) {
70935
- const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
70936
- if (errMsg.includes("already in the group")) {
70937
- console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
70938
- const preRemoveState = JSON.stringify(mlsGroup.exportState());
70939
- let removeCommitPublished = false;
70940
- try {
70941
- const identityBytes = new TextEncoder().encode(req.requesting_device_id);
70942
- const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
70943
- if (leafIndex === null) {
70944
- console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
70945
- continue;
70946
- }
70947
- const removeResult = await mlsGroup.removeMember(leafIndex);
70948
- try {
70949
- const removeResp = await fetch(
70950
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
70951
- {
70952
- method: "POST",
70953
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
70954
- body: JSON.stringify({
70955
- group_id: chState.mlsGroupId,
70956
- device_id: this._deviceId,
70957
- commit: Buffer.from(removeResult.commit).toString("hex"),
70958
- commit_epoch: Number(mlsGroup.epoch),
70959
- ...parentDigest ? { parent_digest: parentDigest } : {}
70960
- })
70961
- }
70962
- );
70963
- if (removeResp.ok) {
70964
- removeCommitPublished = true;
70965
- parentDigest = this._commitDigest(removeResult.commit);
70966
- } else {
70967
- const detail = await removeResp.text().catch(() => "");
70968
- console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
70969
- }
70970
- } catch (distErr) {
70971
- console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
70972
- }
70973
- if (!removeCommitPublished) {
70974
- mlsGroup.importState(JSON.parse(preRemoveState));
70975
- continue;
70976
- }
70977
- const kpRes2 = await fetch(
70978
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
70979
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
70980
- );
70981
- if (kpRes2.ok) {
70982
- const kpData2 = await kpRes2.json();
70983
- const kpHex2 = kpData2[req.requesting_device_id];
70984
- if (kpHex2) {
70985
- const kpBytes2 = new Uint8Array(Buffer.from(kpHex2, "hex"));
70986
- const memberKp2 = MLSGroupManager.deserializeKeyPackage(kpBytes2);
70987
- const result2 = await mlsGroup.addMembers([memberKp2]);
70988
- commit = result2.commit;
70989
- welcome = result2.welcome;
70990
- } else {
70991
- console.log(`[SecureChannel] A2A re-add: no fresh KeyPackage for ${req.requesting_device_id.slice(0, 8)}`);
70992
- continue;
70993
- }
70994
- } else {
70995
- console.log(`[SecureChannel] A2A re-add: KeyPackage fetch failed (${kpRes2.status})`);
70996
- continue;
70997
- }
70998
- } catch (readdErr) {
70999
- console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
71000
- if (!removeCommitPublished) {
71001
- try {
71002
- mlsGroup.importState(JSON.parse(preRemoveState));
71003
- } catch {
71004
- }
71005
- }
71006
- continue;
71007
- }
71008
- } else {
71009
- console.log(`[SecureChannel] A2A addMembers FAILED: ${errMsg}`);
71010
- continue;
71011
- }
71012
- }
71013
- if (!welcome) {
71014
- console.warn(`[SecureChannel] A2A addMembers produced no Welcome for ${req.requesting_device_id.slice(0, 8)}`);
71015
- continue;
71016
- }
71017
- const commitHex = Buffer.from(commit).toString("hex");
71018
- const welcomeHex = Buffer.from(welcome).toString("hex");
71019
- let distributed = false;
71020
- const updatedMembers = [this._deviceId, req.requesting_device_id];
71021
- try {
71022
- const distResp = await fetch(
71023
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71024
- {
71025
- method: "POST",
71026
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71027
- body: JSON.stringify({
71028
- group_id: chState.mlsGroupId,
71029
- device_id: this._deviceId,
71030
- commit: commitHex,
71031
- commit_epoch: Number(mlsGroup.epoch),
71032
- welcomes: [{ target_device_id: req.requesting_device_id, payload: welcomeHex }],
71033
- member_device_ids: updatedMembers,
71034
- ...parentDigest ? { parent_digest: parentDigest } : {}
71035
- })
71036
- }
71037
- );
71038
- if (distResp.ok) {
71039
- distributed = true;
71040
- } else {
71041
- const detail = await distResp.text().catch(() => "");
71042
- console.warn(`[SecureChannel] A2A distribute failed (${distResp.status}): ${detail}`);
71043
- }
71044
- } catch (distErr) {
71045
- console.warn(`[SecureChannel] A2A distribute network error:`, distErr);
71046
- }
71047
- if (!distributed && this._wsIsOpen()) {
71048
- const a2aLabel = `A2A ${chId.slice(0, 8)}`;
71049
- const commitSent = await this._sendFrameConfirmed({
71050
- event: "mls_commit",
71051
- data: {
71052
- group_id: chState.mlsGroupId,
71053
- epoch: Number(mlsGroup.epoch),
71054
- payload: commitHex,
71055
- ...parentDigest ? { parent_digest: parentDigest } : {}
71056
- }
71057
- }, `${a2aLabel} commit`);
71058
- const welcomeSent = commitSent && await this._sendFrameConfirmed({
71059
- event: "mls_welcome",
71060
- data: {
71061
- target_device_id: req.requesting_device_id,
71062
- group_id: chState.mlsGroupId,
71063
- a2a_channel_id: chId,
71064
- payload: welcomeHex
71065
- }
71066
- }, `${a2aLabel} welcome`);
71067
- if (!welcomeSent) {
71068
- console.warn(`[SecureChannel] ${a2aLabel}: Welcome frames were NOT written \u2014 leaving the request pending`);
71069
- continue;
71070
- }
71071
- try {
71072
- await fetch(
71073
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71074
- {
71075
- method: "POST",
71076
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71077
- body: JSON.stringify({
71078
- group_id: chState.mlsGroupId,
71079
- device_id: this._deviceId,
71080
- commit_epoch: Number(mlsGroup.epoch),
71081
- member_device_ids: updatedMembers
71082
- })
71083
- }
71084
- );
71085
- } catch {
71086
- }
71087
- distributed = true;
71088
- }
71089
- if (!distributed) {
71090
- console.warn(`[SecureChannel] Cannot deliver Welcome \u2014 HTTP distribute and WS both unavailable`);
71091
- continue;
71092
- }
71093
- const a2aFulfilled = await this._postFulfilWelcome(
71094
- chState.mlsGroupId,
71095
- req.id,
71096
- `A2A ${chId.slice(0, 8)}`
71097
- );
71098
- await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71099
- if (a2aFulfilled) {
71100
- console.log(`[SecureChannel] Fulfilled A2A Welcome for ${req.requesting_device_id.slice(0, 8)} in channel ${chId.slice(0, 8)}`);
71101
- }
71113
+ const next = await this._fulfilA2AWelcome(chId, chState, mlsGroup, req);
71114
+ if (next === "stop") break;
71102
71115
  } catch (fulfillErr) {
71103
71116
  console.log(`[SecureChannel] A2A Welcome fulfill failed: ${fulfillErr instanceof Error ? fulfillErr.message : String(fulfillErr)}`);
71104
71117
  }
@@ -71369,6 +71382,227 @@ ${baseText}`;
71369
71382
  }
71370
71383
  }
71371
71384
  }
71385
+ /**
71386
+ * #1225: fulfil ONE pending A2A Welcome request — the `/distribute` path.
71387
+ * Extracted from the delivery pull so the in-flight slot (review F1) is held
71388
+ * for exactly this request and released on every exit. Returns "stop" when
71389
+ * nothing else on this channel can succeed this pull (review F2).
71390
+ */
71391
+ async _fulfilA2AWelcome(chId, chState, mlsGroup, req) {
71392
+ const a2aLabel = `A2A ${chId.slice(0, 8)}`;
71393
+ const preHead = await this._readGroupHead(chState.mlsGroupId);
71394
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
71395
+ console.warn(
71396
+ `[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`
71397
+ );
71398
+ await this._catchUpAfterPreflightSkip(chState.mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), a2aLabel);
71399
+ return "stop";
71400
+ }
71401
+ const inFlight = this._reserveCommit(chState.mlsGroupId, a2aLabel);
71402
+ if (!inFlight) return "stop";
71403
+ try {
71404
+ const kpRes = await fetch(
71405
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
71406
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71407
+ );
71408
+ if (!kpRes.ok) return "next";
71409
+ const kpData = await kpRes.json();
71410
+ const kpHex = kpData[req.requesting_device_id];
71411
+ if (!kpHex) return "next";
71412
+ const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
71413
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
71414
+ console.log(`[SecureChannel] A2A addMembers for ${req.requesting_device_id.slice(0, 8)} group=${chState.mlsGroupId.slice(0, 8)} epoch=${mlsGroup.epoch}`);
71415
+ let parentDigest = preHead.ok ? preHead.digest : void 0;
71416
+ let commit;
71417
+ let welcome;
71418
+ let preAddState = mlsGroup.exportState();
71419
+ try {
71420
+ const result = await mlsGroup.addMembers([memberKp]);
71421
+ commit = result.commit;
71422
+ welcome = result.welcome;
71423
+ } catch (addErr) {
71424
+ const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
71425
+ if (errMsg.includes("already in the group")) {
71426
+ console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
71427
+ const preRemoveState = JSON.stringify(mlsGroup.exportState());
71428
+ let removeCommitPublished = false;
71429
+ try {
71430
+ const identityBytes = new TextEncoder().encode(req.requesting_device_id);
71431
+ const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
71432
+ if (leafIndex === null) {
71433
+ console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
71434
+ return "next";
71435
+ }
71436
+ const removeResult = await mlsGroup.removeMember(leafIndex);
71437
+ try {
71438
+ const removeResp = await fetch(
71439
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71440
+ {
71441
+ method: "POST",
71442
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71443
+ body: JSON.stringify({
71444
+ group_id: chState.mlsGroupId,
71445
+ device_id: this._deviceId,
71446
+ commit: Buffer.from(removeResult.commit).toString("hex"),
71447
+ commit_epoch: Number(mlsGroup.epoch),
71448
+ expected_epoch: Number(mlsGroup.epoch) - 1,
71449
+ // #1225: exact-step, like the WS path
71450
+ ...parentDigest ? { parent_digest: parentDigest } : {}
71451
+ })
71452
+ }
71453
+ );
71454
+ if (removeResp.ok) {
71455
+ removeCommitPublished = true;
71456
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71457
+ parentDigest = this._commitDigest(removeResult.commit);
71458
+ } else {
71459
+ const detail = await removeResp.text().catch(() => "");
71460
+ console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
71461
+ }
71462
+ } catch (distErr) {
71463
+ console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
71464
+ }
71465
+ if (!removeCommitPublished) {
71466
+ mlsGroup.importState(JSON.parse(preRemoveState));
71467
+ return "next";
71468
+ }
71469
+ const kpRes2 = await fetch(
71470
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
71471
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71472
+ );
71473
+ if (kpRes2.ok) {
71474
+ const kpData2 = await kpRes2.json();
71475
+ const kpHex2 = kpData2[req.requesting_device_id];
71476
+ if (kpHex2) {
71477
+ const kpBytes2 = new Uint8Array(Buffer.from(kpHex2, "hex"));
71478
+ const memberKp2 = MLSGroupManager.deserializeKeyPackage(kpBytes2);
71479
+ preAddState = mlsGroup.exportState();
71480
+ const result2 = await mlsGroup.addMembers([memberKp2]);
71481
+ commit = result2.commit;
71482
+ welcome = result2.welcome;
71483
+ } else {
71484
+ console.log(`[SecureChannel] A2A re-add: no fresh KeyPackage for ${req.requesting_device_id.slice(0, 8)}`);
71485
+ return "next";
71486
+ }
71487
+ } else {
71488
+ console.log(`[SecureChannel] A2A re-add: KeyPackage fetch failed (${kpRes2.status})`);
71489
+ return "next";
71490
+ }
71491
+ } catch (readdErr) {
71492
+ console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
71493
+ if (!removeCommitPublished) {
71494
+ try {
71495
+ mlsGroup.importState(JSON.parse(preRemoveState));
71496
+ } catch {
71497
+ }
71498
+ }
71499
+ return "next";
71500
+ }
71501
+ } else {
71502
+ console.log(`[SecureChannel] A2A addMembers FAILED: ${errMsg}`);
71503
+ return "next";
71504
+ }
71505
+ }
71506
+ if (!welcome) {
71507
+ console.warn(`[SecureChannel] A2A addMembers produced no Welcome for ${req.requesting_device_id.slice(0, 8)}`);
71508
+ return "next";
71509
+ }
71510
+ const commitHex = Buffer.from(commit).toString("hex");
71511
+ const welcomeHex = Buffer.from(welcome).toString("hex");
71512
+ let distributed = false;
71513
+ let transportFailed = false;
71514
+ const updatedMembers = this._commitRoster([this._deviceId], [req.requesting_device_id]);
71515
+ try {
71516
+ const distResp = await fetch(
71517
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71518
+ {
71519
+ method: "POST",
71520
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71521
+ body: JSON.stringify({
71522
+ group_id: chState.mlsGroupId,
71523
+ device_id: this._deviceId,
71524
+ commit: commitHex,
71525
+ commit_epoch: Number(mlsGroup.epoch),
71526
+ welcomes: [{ target_device_id: req.requesting_device_id, payload: welcomeHex }],
71527
+ member_device_ids: updatedMembers,
71528
+ expected_epoch: Number(mlsGroup.epoch) - 1,
71529
+ // #1225: exact-step, like the WS path
71530
+ ...parentDigest ? { parent_digest: parentDigest } : {}
71531
+ })
71532
+ }
71533
+ );
71534
+ if (distResp.ok) {
71535
+ distributed = true;
71536
+ } else {
71537
+ const detail = await distResp.text().catch(() => "");
71538
+ console.warn(`[SecureChannel] A2A distribute failed (${distResp.status}): ${detail}`);
71539
+ if (distResp.status >= 500) {
71540
+ transportFailed = true;
71541
+ } else if (distResp.status === 409) {
71542
+ mlsGroup.importState(preAddState);
71543
+ console.warn(
71544
+ `[SecureChannel] ${a2aLabel}: add commit lost the race (409) \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, request stays pending`
71545
+ );
71546
+ return "next";
71547
+ } else {
71548
+ mlsGroup.importState(preAddState);
71549
+ console.error(
71550
+ `[SecureChannel] ${a2aLabel}: add commit refused with ${distResp.status} \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}; not retrying this channel this pull`
71551
+ );
71552
+ return "stop";
71553
+ }
71554
+ }
71555
+ } catch (distErr) {
71556
+ console.warn(`[SecureChannel] A2A distribute network error:`, distErr);
71557
+ transportFailed = true;
71558
+ }
71559
+ if (!distributed && transportFailed && this._wsIsOpen()) {
71560
+ const verdict = await this._sendCommitConfirmed({
71561
+ mlsGroup,
71562
+ mlsGroupId: chState.mlsGroupId,
71563
+ label: a2aLabel,
71564
+ commit,
71565
+ epoch: Number(mlsGroup.epoch),
71566
+ parent: parentDigest,
71567
+ memberDeviceIds: updatedMembers,
71568
+ stateBefore: preAddState,
71569
+ inFlight
71570
+ });
71571
+ if (verdict !== "confirmed") return "next";
71572
+ const welcomeSent = await this._sendFrameConfirmed({
71573
+ event: "mls_welcome",
71574
+ data: {
71575
+ target_device_id: req.requesting_device_id,
71576
+ group_id: chState.mlsGroupId,
71577
+ a2a_channel_id: chId,
71578
+ payload: welcomeHex
71579
+ }
71580
+ }, `${a2aLabel} welcome`);
71581
+ if (!welcomeSent) {
71582
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71583
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome frame was NOT written \u2014 leaving the request pending`);
71584
+ return "next";
71585
+ }
71586
+ distributed = true;
71587
+ }
71588
+ if (!distributed) {
71589
+ console.warn(`[SecureChannel] Cannot deliver Welcome \u2014 HTTP distribute and WS both unavailable`);
71590
+ return "next";
71591
+ }
71592
+ const a2aFulfilled = await this._postFulfilWelcome(
71593
+ chState.mlsGroupId,
71594
+ req.id,
71595
+ `A2A ${chId.slice(0, 8)}`
71596
+ );
71597
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71598
+ if (a2aFulfilled) {
71599
+ console.log(`[SecureChannel] Fulfilled A2A Welcome for ${req.requesting_device_id.slice(0, 8)} in channel ${chId.slice(0, 8)}`);
71600
+ }
71601
+ return "next";
71602
+ } finally {
71603
+ await this._releaseCommit(chState.mlsGroupId, inFlight, a2aLabel);
71604
+ }
71605
+ }
71372
71606
  /**
71373
71607
  * Found the MLS group for an A2A channel as the creator agent.
71374
71608
  * Calls /mls/a2a/{channelId}/init, creates the local MLS group, and sends
@@ -71411,48 +71645,77 @@ ${baseText}`;
71411
71645
  await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
71412
71646
  for (const p2 of participants) {
71413
71647
  if (p2.status !== "active" && p2.status !== "invited") continue;
71648
+ const a2aLabel = `A2A ${channelId.slice(0, 8)} found\u2192${p2.hubAddress}`;
71414
71649
  try {
71415
- const kpRes = await fetch(
71416
- `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(p2.hubId)}`,
71417
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71418
- );
71419
- if (kpRes.ok) {
71420
- const kpData = await kpRes.json();
71421
- if (kpData.key_package) {
71422
- const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
71423
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
71424
- const { commit, welcome } = await mgr.addMembers([memberKp]);
71425
- if (welcome && this._ws) {
71426
- this._ws.send(JSON.stringify({
71427
- event: "mls_commit",
71650
+ if (!p2.deviceId) {
71651
+ console.warn(
71652
+ `[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.`
71653
+ );
71654
+ continue;
71655
+ }
71656
+ if (!this._wsIsOpen()) {
71657
+ console.warn(`[SecureChannel] ${a2aLabel}: socket is not OPEN \u2014 NOT advancing the group`);
71658
+ continue;
71659
+ }
71660
+ const head = await this._readGroupHead(mlsData.group_id);
71661
+ if (head.ok && head.epoch !== Number(mgr.epoch)) {
71662
+ console.warn(`[SecureChannel] ${a2aLabel}: server head is at epoch ${head.epoch}, we are at ${Number(mgr.epoch)} \u2014 NOT committing`);
71663
+ await this._catchUpAfterPreflightSkip(mlsData.group_id, head.epoch, Number(mgr.epoch), a2aLabel);
71664
+ continue;
71665
+ }
71666
+ const inFlight = this._reserveCommit(mlsData.group_id, a2aLabel);
71667
+ if (!inFlight) continue;
71668
+ try {
71669
+ const kpRes = await fetch(
71670
+ `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(p2.hubId)}`,
71671
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71672
+ );
71673
+ if (kpRes.ok) {
71674
+ const kpData = await kpRes.json();
71675
+ if (kpData.key_package) {
71676
+ const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
71677
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
71678
+ const stateBefore = mgr.exportState();
71679
+ const { commit, welcome } = await mgr.addMembers([memberKp]);
71680
+ const committedEpoch = Number(mgr.epoch);
71681
+ if (!welcome) {
71682
+ mgr.importState(stateBefore);
71683
+ console.warn(`[SecureChannel] ${a2aLabel}: addMembers produced no Welcome \u2014 rolled back`);
71684
+ continue;
71685
+ }
71686
+ const verdict = await this._sendCommitConfirmed({
71687
+ mlsGroup: mgr,
71688
+ mlsGroupId: mlsData.group_id,
71689
+ label: a2aLabel,
71690
+ commit,
71691
+ epoch: committedEpoch,
71692
+ parent: head.ok ? head.digest : void 0,
71693
+ memberDeviceIds: this._commitRoster(participants.map((q2) => q2.deviceId), [p2.deviceId]),
71694
+ stateBefore,
71695
+ inFlight
71696
+ });
71697
+ if (verdict !== "confirmed") continue;
71698
+ const sent = await this._sendFrameConfirmed({
71699
+ event: "mls_welcome",
71428
71700
  data: {
71429
71701
  group_id: mlsData.group_id,
71430
- epoch: Number(mgr.epoch),
71431
- payload: Buffer.from(commit).toString("hex")
71702
+ payload: Buffer.from(welcome).toString("hex"),
71703
+ target_device_id: p2.deviceId,
71704
+ a2a_channel_id: channelId,
71705
+ target_hub_id: p2.hubId
71706
+ // observability only — the backend ignores it
71432
71707
  }
71433
- }));
71434
- if (!p2.deviceId) {
71435
- console.warn(
71436
- `[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.`
71437
- );
71438
- } else {
71439
- this._ws.send(JSON.stringify({
71440
- event: "mls_welcome",
71441
- data: {
71442
- group_id: mlsData.group_id,
71443
- payload: Buffer.from(welcome).toString("hex"),
71444
- target_device_id: p2.deviceId,
71445
- a2a_channel_id: channelId,
71446
- // Kept for observability — backend ignores but it's
71447
- // useful in logs/wire captures to correlate to a hub.
71448
- target_hub_id: p2.hubId
71449
- }
71450
- }));
71708
+ }, `${a2aLabel} welcome`);
71709
+ await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
71710
+ if (sent) {
71451
71711
  console.log(`[SecureChannel] Sent MLS Welcome to ${p2.hubAddress} (device ${p2.deviceId.slice(0, 8)}) for A2A ${channelId.slice(0, 8)}`);
71712
+ } else {
71713
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome was NOT written \u2014 the participant will request one`);
71452
71714
  }
71453
71715
  }
71454
- await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
71455
71716
  }
71717
+ } finally {
71718
+ await this._releaseCommit(mlsData.group_id, inFlight, a2aLabel);
71456
71719
  }
71457
71720
  } catch (kpErr) {
71458
71721
  console.warn(`[SecureChannel] Failed to Welcome participant ${p2.hubAddress}:`, kpErr);
@@ -92943,7 +93206,7 @@ var init_index = __esm({
92943
93206
  await init_skill_telemetry();
92944
93207
  await init_policy_enforcer();
92945
93208
  init_room_protocol();
92946
- VERSION = true ? "0.23.40" : "0.0.0-dev";
93209
+ VERSION = true ? "0.23.41" : "0.0.0-dev";
92947
93210
  }
92948
93211
  });
92949
93212
 
@@ -93040,9 +93303,9 @@ function describeSdkCapabilities(results) {
93040
93303
  function describeBuildIdentity() {
93041
93304
  const name2 = "Build identity";
93042
93305
  try {
93043
- const raw = true ? "dbac15d-dirty" : "";
93306
+ const raw = true ? "916d6c5-dirty" : "";
93044
93307
  const sha = (raw ?? "").trim();
93045
- const at = true ? "2026-09-08T13:56:50.510Z".trim() : "";
93308
+ const at = true ? "2026-09-08T15:20:36.385Z".trim() : "";
93046
93309
  const built = at ? ` built ${at}` : "";
93047
93310
  if (!sha || sha === "unknown") {
93048
93311
  return {