@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/index.js CHANGED
@@ -63328,11 +63328,11 @@ var init_mls_kp_pool = __esm({
63328
63328
 
63329
63329
  // src/client-version.ts
63330
63330
  function ownIdentity() {
63331
- const v2 = true ? "0.23.40" : FALLBACK;
63331
+ const v2 = true ? "0.23.41" : FALLBACK;
63332
63332
  return `${PACKAGE}@${v2}`;
63333
63333
  }
63334
63334
  function buildSha() {
63335
- const raw = true ? "dbac15d-dirty" : "";
63335
+ const raw = true ? "916d6c5-dirty" : "";
63336
63336
  const cleaned = (raw ?? "").trim();
63337
63337
  return !cleaned || cleaned === "unknown" ? null : cleaned;
63338
63338
  }
@@ -64261,7 +64261,7 @@ function _isSelfHubAddress(ownHubAddress, target) {
64261
64261
  const tgt = (target ?? "").trim().toLowerCase();
64262
64262
  return own.length > 0 && own === tgt;
64263
64263
  }
64264
- 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;
64264
+ 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;
64265
64265
  var init_channel = __esm({
64266
64266
  async "src/channel.ts"() {
64267
64267
  "use strict";
@@ -64299,6 +64299,7 @@ var init_channel = __esm({
64299
64299
  ]);
64300
64300
  POLL_INTERVAL_MS = 6e3;
64301
64301
  RECONNECT_BASE_MS = 1e3;
64302
+ UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
64302
64303
  RECONNECT_MAX_MS = 3e4;
64303
64304
  PENDING_POLL_INTERVAL_MS = 15e3;
64304
64305
  OUTBOUND_DEDUPE_WINDOW_MS = 3e3;
@@ -65594,7 +65595,7 @@ ${text}`;
65594
65595
  */
65595
65596
  sendActivitySpan(spanData) {
65596
65597
  if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return;
65597
- const pluginVersion = true ? "0.23.40" : "0.0.0-dev";
65598
+ const pluginVersion = true ? "0.23.41" : "0.0.0-dev";
65598
65599
  const agentName = this.config.agentName ?? "Agent";
65599
65600
  const resource = {
65600
65601
  "service.name": "agentvault-agent",
@@ -67532,7 +67533,7 @@ ${text}`;
67532
67533
  agentVersion: this.config.agentVersion ?? "0.0.0",
67533
67534
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
67534
67535
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
67535
- pluginVersion: true ? "0.23.40" : "0.0.0-dev"
67536
+ pluginVersion: true ? "0.23.41" : "0.0.0-dev"
67536
67537
  });
67537
67538
  this._telemetryReporter.startAutoFlush(3e4);
67538
67539
  }
@@ -67856,7 +67857,7 @@ ${text}`;
67856
67857
  agentVersion: this.config.agentVersion ?? "0.0.0",
67857
67858
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
67858
67859
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
67859
- pluginVersion: true ? "0.23.40" : "0.0.0-dev"
67860
+ pluginVersion: true ? "0.23.41" : "0.0.0-dev"
67860
67861
  });
67861
67862
  this._telemetryReporter.startAutoFlush(3e4);
67862
67863
  }
@@ -68071,45 +68072,78 @@ ${text}`;
68071
68072
  const mlsGroup = this._mlsGroups.get(`a2a:${channelId}`);
68072
68073
  if (mlsGroup?.isInitialized) {
68073
68074
  try {
68074
- const kpRes = await fetch(
68075
- `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(participant.hub_id)}`,
68076
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
68077
- );
68078
- if (kpRes.ok) {
68079
- const kpData = await kpRes.json();
68080
- if (kpData.key_package) {
68081
- const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
68082
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
68083
- const { commit, welcome } = await mlsGroup.addMembers([memberKp]);
68084
- if (welcome && this._ws) {
68085
- this._ws.send(JSON.stringify({
68086
- event: "mls_commit",
68087
- data: {
68088
- group_id: entry.mlsGroupId,
68089
- epoch: Number(mlsGroup.epoch),
68090
- payload: Buffer.from(commit).toString("hex")
68091
- }
68092
- }));
68093
- const newDeviceId = participant.device_id || null;
68094
- if (!newDeviceId) {
68095
- console.warn(
68096
- `[SecureChannel] Skipping MLS Welcome to new participant ${participant.hub_address} for A2A ${channelId.slice(0, 8)}: no device_id on participant_joined payload.`
68097
- );
68098
- } else {
68099
- this._ws.send(JSON.stringify({
68100
- event: "mls_welcome",
68101
- data: {
68102
- group_id: entry.mlsGroupId,
68103
- payload: Buffer.from(welcome).toString("hex"),
68104
- target_device_id: newDeviceId,
68105
- a2a_channel_id: channelId,
68106
- target_hub_id: participant.hub_id
68107
- // observability only
68075
+ const newDeviceId = participant.device_id || null;
68076
+ const a2aLabel = `A2A ${channelId.slice(0, 8)} participant_joined`;
68077
+ if (!newDeviceId) {
68078
+ console.warn(
68079
+ `[SecureChannel] ${a2aLabel}: no device_id on the payload for ${participant.hub_address} \u2014 NOT adding (a Welcome could not be addressed)`
68080
+ );
68081
+ } else if (!this._wsIsOpen()) {
68082
+ console.warn(`[SecureChannel] ${a2aLabel}: socket is not OPEN \u2014 NOT advancing the group`);
68083
+ } else {
68084
+ const preHead = await this._readGroupHead(entry.mlsGroupId);
68085
+ const inFlight = preHead.ok && preHead.epoch !== Number(mlsGroup.epoch) ? null : this._reserveCommit(entry.mlsGroupId, a2aLabel);
68086
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
68087
+ console.warn(
68088
+ `[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`
68089
+ );
68090
+ await this._catchUpAfterPreflightSkip(entry.mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), a2aLabel);
68091
+ } else if (inFlight) {
68092
+ try {
68093
+ const kpRes = await fetch(
68094
+ `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(participant.hub_id)}`,
68095
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
68096
+ );
68097
+ if (kpRes.ok) {
68098
+ const kpData = await kpRes.json();
68099
+ if (kpData.key_package) {
68100
+ const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
68101
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
68102
+ const stateBefore = mlsGroup.exportState();
68103
+ const { commit, welcome } = await mlsGroup.addMembers([memberKp]);
68104
+ const committedEpoch = Number(mlsGroup.epoch);
68105
+ if (!welcome) {
68106
+ mlsGroup.importState(stateBefore);
68107
+ console.warn(`[SecureChannel] ${a2aLabel}: addMembers produced no Welcome \u2014 rolled back`);
68108
+ } else {
68109
+ const verdict = await this._sendCommitConfirmed({
68110
+ mlsGroup,
68111
+ mlsGroupId: entry.mlsGroupId,
68112
+ label: a2aLabel,
68113
+ commit,
68114
+ epoch: committedEpoch,
68115
+ parent: preHead.ok ? preHead.digest : void 0,
68116
+ memberDeviceIds: this._commitRoster(
68117
+ (entry.participants ?? []).map((p2) => p2.deviceId),
68118
+ [newDeviceId]
68119
+ ),
68120
+ stateBefore,
68121
+ inFlight
68122
+ });
68123
+ if (verdict === "confirmed") {
68124
+ const sent = await this._sendFrameConfirmed({
68125
+ event: "mls_welcome",
68126
+ data: {
68127
+ group_id: entry.mlsGroupId,
68128
+ payload: Buffer.from(welcome).toString("hex"),
68129
+ target_device_id: newDeviceId,
68130
+ a2a_channel_id: channelId,
68131
+ target_hub_id: participant.hub_id
68132
+ // observability only
68133
+ }
68134
+ }, `${a2aLabel} welcome`);
68135
+ await saveMlsState(this.config.dataDir, entry.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
68136
+ if (sent) {
68137
+ console.log(`[SecureChannel] Sent MLS Welcome to new participant ${participant.hub_address} (device ${String(newDeviceId).slice(0, 8)})`);
68138
+ } else {
68139
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome to ${String(newDeviceId).slice(0, 8)} was NOT written \u2014 the participant will request one`);
68140
+ }
68141
+ }
68108
68142
  }
68109
- }));
68110
- await saveMlsState(this.config.dataDir, entry.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
68111
- console.log(`[SecureChannel] Sent MLS Welcome to new participant ${participant.hub_address} (device ${String(newDeviceId).slice(0, 8)})`);
68143
+ }
68112
68144
  }
68145
+ } finally {
68146
+ await this._releaseCommit(entry.mlsGroupId, inFlight, a2aLabel);
68113
68147
  }
68114
68148
  }
68115
68149
  }
@@ -69639,9 +69673,34 @@ ${baseText}`;
69639
69673
  *
69640
69674
  * Returns the number of requests actually fulfilled.
69641
69675
  */
69676
+ /**
69677
+ * #1226: the roster to submit on a commit frame — the caller's known members,
69678
+ * the devices being admitted, and ALWAYS ourselves — deduplicated, UUIDs
69679
+ * only. Self is non-negotiable: once a roster is non-empty the server
69680
+ * requires the committer in it (#469), and our own head read
69681
+ * (`assert_group_member`) requires it too. So with no device id of our own
69682
+ * this returns `[]` and the frame carries NO roster (the pre-#1226 shape)
69683
+ * rather than a roster that locks us out. Non-UUID entries are dropped:
69684
+ * `known` can come off an inbound Welcome frame, and a malformed id in the
69685
+ * outbound frame is refused by the server (`MEMBER_DEVICE_IDS_MALFORMED`).
69686
+ * @internal exposed for tests
69687
+ */
69688
+ _commitRoster(known, targets) {
69689
+ if (!this._deviceId) return [];
69690
+ const out = [];
69691
+ const seen = /* @__PURE__ */ new Set();
69692
+ for (const id of [...known ?? [], ...targets, this._deviceId]) {
69693
+ if (typeof id !== "string" || !UUID_RE.test(id) || seen.has(id)) continue;
69694
+ seen.add(id);
69695
+ out.push(id);
69696
+ }
69697
+ return out;
69698
+ }
69642
69699
  async _fulfilWelcomeRequests(opts) {
69643
69700
  const { mlsGroup, mlsGroupId, label, welcomeFields, targets } = opts;
69644
69701
  if (targets.length === 0) return 0;
69702
+ const rosterBefore = this._commitRoster(opts.memberDeviceIds, []);
69703
+ const rosterAfter = this._commitRoster(opts.memberDeviceIds, targets.map((t2) => t2.deviceId));
69645
69704
  if (!this._wsIsOpen()) {
69646
69705
  console.warn(
69647
69706
  `[SecureChannel] ${label}: socket is not OPEN \u2014 NOT advancing the group; ${targets.length} request(s) stay pending for the next pull`
@@ -69654,9 +69713,16 @@ ${baseText}`;
69654
69713
  console.warn(
69655
69714
  `[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`
69656
69715
  );
69716
+ await this._catchUpAfterPreflightSkip(mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), label);
69657
69717
  return 0;
69658
69718
  }
69659
69719
  let parent2 = preHead.ok ? preHead.digest : void 0;
69720
+ if (this._commitInFlight.has(mlsGroupId)) {
69721
+ console.warn(
69722
+ `[SecureChannel] ${label}: another commit for this group is in flight \u2014 NOT advancing; ${targets.length} request(s) stay pending for the next pull`
69723
+ );
69724
+ return 0;
69725
+ }
69660
69726
  const inFlight = { frames: [], sent: [] };
69661
69727
  this._commitInFlight.set(mlsGroupId, inFlight);
69662
69728
  try {
@@ -69681,7 +69747,8 @@ ${baseText}`;
69681
69747
  // only knows the last one, which is why the result carries them.
69682
69748
  epoch: Number(c2.epoch),
69683
69749
  payload: Buffer.from(c2.commit).toString("hex"),
69684
- ...parent2 ? { parent_digest: parent2 } : {}
69750
+ ...parent2 ? { parent_digest: parent2 } : {},
69751
+ ...(sentCommits === commits.length - 1 ? rosterAfter : rosterBefore).length > 0 ? { member_device_ids: sentCommits === commits.length - 1 ? rosterAfter : rosterBefore } : {}
69685
69752
  }
69686
69753
  },
69687
69754
  `${label} commit ${sentCommits + 1}/${commits.length}`
@@ -69829,6 +69896,126 @@ ${baseText}`;
69829
69896
  return this._ws?.readyState === 1;
69830
69897
  }
69831
69898
  /** SHA-256 hex of a commit's bytes — its identity on the server (#1175/#1177). */
69899
+ /**
69900
+ * #1225: send ONE commit over the socket and wait for the server's verdict,
69901
+ * with the #1184 machinery — an in-flight record (so a `… commit rejected`
69902
+ * frame is correlated to it and a concurrent commit for the group is held
69903
+ * and replayed), the head poll, and rollback. The three A2A commit sites
69904
+ * (`a2a_participant_joined`, the `/distribute` WS fallback, `_foundA2AGroup`)
69905
+ * used a raw `ws.send` and treated "the socket took it" as "the server
69906
+ * stored it" — two of them then PERSISTED a state the server never saw.
69907
+ *
69908
+ * Returns the verdict. On `refused` / `unsent` the manager has been restored
69909
+ * to `stateBefore` and nothing must be persisted or minted from it.
69910
+ * `unverifiable` (head unreadable on every try AND no refusal) proceeds
69911
+ * UNCHECKED, the same deliberate choice as the fulfil site.
69912
+ */
69913
+ /**
69914
+ * #1225 (review F1): reserve the single in-flight slot for a group. The
69915
+ * record is what `_noteCommitRefusal` correlates a refusal to and what
69916
+ * `_handleMlsCommit` holds concurrent socket commits behind; a second run on
69917
+ * the same group would clobber both (measured: two overlapping joins → two
69918
+ * commits claiming one epoch, one Welcome instead of two, the manager AHEAD
69919
+ * of the server). Taken BEFORE the commit is generated; released by
69920
+ * `_releaseCommit` after the last step that depends on it.
69921
+ */
69922
+ /**
69923
+ * A pre-flight skip must not be a dead end. The skip happens because the
69924
+ * server's head is somewhere else; before this the group "caught up through
69925
+ * the normal divergence path", which only runs when a message for the group
69926
+ * arrives — so a group nobody writes to stayed diverged and its pending
69927
+ * Welcome requests were never fulfilled (named in PR #1227). When the server
69928
+ * is AHEAD, replay the missing commits now so the next pull can commit; when
69929
+ * WE are ahead there is nothing to replay (the fork-ahead direction, #972).
69930
+ */
69931
+ async _catchUpAfterPreflightSkip(mlsGroupId, serverEpoch, localEpoch, label) {
69932
+ if (serverEpoch < localEpoch) {
69933
+ console.warn(`[SecureChannel] ${label}: we are AHEAD of the server (${localEpoch} > ${serverEpoch}) \u2014 nothing to replay`);
69934
+ return;
69935
+ }
69936
+ const fam = this._resolveGroupFamily(mlsGroupId);
69937
+ if (!fam) return;
69938
+ try {
69939
+ const caughtUp = await this._resyncOnDivergence(fam.managerKey, mlsGroupId);
69940
+ console.log(`[SecureChannel] ${label}: catch-up after pre-flight skip ${caughtUp ? "replayed the missing commits" : "could not replay"}`);
69941
+ } catch (err) {
69942
+ console.warn(`[SecureChannel] ${label}: catch-up after pre-flight skip failed:`, err);
69943
+ }
69944
+ }
69945
+ _reserveCommit(groupId, label) {
69946
+ if (this._commitInFlight.has(groupId)) {
69947
+ console.warn(
69948
+ `[SecureChannel] ${label}: another commit for group ${groupId.slice(0, 8)} is in flight \u2014 NOT advancing the group (a Welcome can be requested again)`
69949
+ );
69950
+ return null;
69951
+ }
69952
+ const rec = { frames: [], sent: [] };
69953
+ this._commitInFlight.set(groupId, rec);
69954
+ return rec;
69955
+ }
69956
+ /** Release the slot taken by `_reserveCommit` and replay the socket commits held meanwhile. */
69957
+ async _releaseCommit(groupId, rec, label) {
69958
+ if (this._commitInFlight.get(groupId) === rec) this._commitInFlight.delete(groupId);
69959
+ for (const frame of rec.frames) {
69960
+ try {
69961
+ await this._handleMlsCommit(frame);
69962
+ } catch (err) {
69963
+ console.error(`[SecureChannel] ${label}: replaying a held MLS commit failed:`, err);
69964
+ }
69965
+ }
69966
+ }
69967
+ /**
69968
+ * #1225: send ONE commit over the socket and wait for the server's verdict
69969
+ * with the #1184 machinery (refusal frame correlated through the reserved
69970
+ * in-flight record, head poll). The three A2A commit sites
69971
+ * (`a2a_participant_joined`, the `/distribute` WS fallback, `_foundA2AGroup`)
69972
+ * used a raw `ws.send` and treated "the socket took it" as "the server
69973
+ * stored it" — two of them then PERSISTED a state the server never saw.
69974
+ *
69975
+ * Only `confirmed` proceeds. `unverifiable` (head unreadable on every try,
69976
+ * no refusal) is a ROLLBACK here, unlike the fulfil site: that site proceeds
69977
+ * UNCHECKED because 79 of 80 production rooms 403 the head read on an empty
69978
+ * roster; an A2A head read admits any active participant (observer
69979
+ * fallback), so five failed reads there mean an outage, not a routine 403.
69980
+ * On anything but `confirmed` the manager is back at `stateBefore`.
69981
+ */
69982
+ async _sendCommitConfirmed(opts) {
69983
+ const { mlsGroup, mlsGroupId, label, commit, epoch, parent: parent2, memberDeviceIds, stateBefore, inFlight } = opts;
69984
+ const ours = this._commitDigest(commit);
69985
+ inFlight.sent.push({ epoch, digest: ours, verified: false, stateBefore });
69986
+ const ok = await this._sendFrameConfirmed(
69987
+ {
69988
+ event: "mls_commit",
69989
+ data: {
69990
+ group_id: mlsGroupId,
69991
+ epoch,
69992
+ payload: Buffer.from(commit).toString("hex"),
69993
+ ...parent2 ? { parent_digest: parent2 } : {},
69994
+ ...memberDeviceIds && memberDeviceIds.length > 0 ? { member_device_ids: memberDeviceIds } : {}
69995
+ }
69996
+ },
69997
+ `${label} commit`
69998
+ );
69999
+ if (!ok) {
70000
+ inFlight.sent.pop();
70001
+ mlsGroup.importState(stateBefore);
70002
+ console.warn(
70003
+ `[SecureChannel] ${label}: commit at epoch ${epoch} was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}`
70004
+ );
70005
+ return "unsent";
70006
+ }
70007
+ const verdict = await this._confirmCommitAtHead(mlsGroupId, epoch, ours, inFlight, label);
70008
+ if (inFlight.refusal === void 0 && verdict === "confirmed") {
70009
+ inFlight.sent[inFlight.sent.length - 1].verified = true;
70010
+ return "confirmed";
70011
+ }
70012
+ const why = inFlight.refusal?.detail ?? verdict.toUpperCase();
70013
+ mlsGroup.importState(stateBefore);
70014
+ console.warn(
70015
+ `[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`
70016
+ );
70017
+ return "refused";
70018
+ }
69832
70019
  _commitDigest(bytes) {
69833
70020
  return createHash("sha256").update(bytes).digest("hex");
69834
70021
  }
@@ -70782,7 +70969,9 @@ ${baseText}`;
70782
70969
  mlsGroupId: roomState.mlsGroupId,
70783
70970
  label: `room ${roomId.slice(0, 8)}`,
70784
70971
  welcomeFields: { room_id: roomId },
70785
- targets: roomTargets
70972
+ targets: roomTargets,
70973
+ memberDeviceIds: (roomState.members ?? []).map((m2) => m2.deviceId)
70974
+ // #1226
70786
70975
  });
70787
70976
  if (done > 0) {
70788
70977
  console.log(
@@ -70837,7 +71026,9 @@ ${baseText}`;
70837
71026
  mlsGroupId: entry.mlsGroupId,
70838
71027
  label: `shared group ${gid.slice(0, 8)}`,
70839
71028
  welcomeFields: { conversation_group_id: gid },
70840
- targets: sharedTargets
71029
+ targets: sharedTargets,
71030
+ memberDeviceIds: entry.memberDeviceIds ?? []
71031
+ // #1226
70841
71032
  });
70842
71033
  if (done > 0) {
70843
71034
  console.log(`[SecureChannel] Batched Welcome for ${done}/${validReqs.length} devices in shared group ${gid.slice(0, 8)} (epoch=${mlsGroup.epoch})`);
@@ -70851,7 +71042,9 @@ ${baseText}`;
70851
71042
  mlsGroupId: entry.mlsGroupId,
70852
71043
  label: `shared group ${gid.slice(0, 8)}`,
70853
71044
  welcomeFields: { conversation_group_id: gid },
70854
- targets: [target]
71045
+ targets: [target],
71046
+ memberDeviceIds: entry.memberDeviceIds ?? []
71047
+ // #1226
70855
71048
  });
70856
71049
  if (done > 0) {
70857
71050
  console.log(`[SecureChannel] Individual Welcome for ${target.deviceId.slice(0, 8)} in shared group ${gid.slice(0, 8)}`);
@@ -70898,7 +71091,11 @@ ${baseText}`;
70898
71091
  requestId: req.id,
70899
71092
  deviceId: req.requesting_device_id,
70900
71093
  keyPackage: memberKp
70901
- }]
71094
+ }],
71095
+ // #1226: a 1:1 roster is [self, owner] — the web's shape too.
71096
+ memberDeviceIds: [this._persisted?.sessions?.[convId]?.ownerDeviceId].filter(
71097
+ (d2) => typeof d2 === "string"
71098
+ )
70902
71099
  });
70903
71100
  if (done > 0) {
70904
71101
  console.log(`[SecureChannel] Fulfilled Welcome for ${req.requesting_device_id.slice(0, 8)} in conv ${convId.slice(0, 8)}`);
@@ -70956,192 +71153,8 @@ ${baseText}`;
70956
71153
  console.log(`[SecureChannel] ${pending.length} pending A2A Welcome requests for channel ${chId.slice(0, 8)}`);
70957
71154
  for (const req of pending) {
70958
71155
  try {
70959
- const kpRes = await fetch(
70960
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
70961
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
70962
- );
70963
- if (!kpRes.ok) continue;
70964
- const kpData = await kpRes.json();
70965
- const kpHex = kpData[req.requesting_device_id];
70966
- if (!kpHex) continue;
70967
- const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
70968
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
70969
- console.log(`[SecureChannel] A2A addMembers for ${req.requesting_device_id.slice(0, 8)} group=${chState.mlsGroupId.slice(0, 8)} epoch=${mlsGroup.epoch}`);
70970
- let parentDigest = await this._readGroupHeadDigest(chState.mlsGroupId);
70971
- let commit;
70972
- let welcome;
70973
- try {
70974
- const result = await mlsGroup.addMembers([memberKp]);
70975
- commit = result.commit;
70976
- welcome = result.welcome;
70977
- } catch (addErr) {
70978
- const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
70979
- if (errMsg.includes("already in the group")) {
70980
- console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
70981
- const preRemoveState = JSON.stringify(mlsGroup.exportState());
70982
- let removeCommitPublished = false;
70983
- try {
70984
- const identityBytes = new TextEncoder().encode(req.requesting_device_id);
70985
- const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
70986
- if (leafIndex === null) {
70987
- console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
70988
- continue;
70989
- }
70990
- const removeResult = await mlsGroup.removeMember(leafIndex);
70991
- try {
70992
- const removeResp = await fetch(
70993
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
70994
- {
70995
- method: "POST",
70996
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
70997
- body: JSON.stringify({
70998
- group_id: chState.mlsGroupId,
70999
- device_id: this._deviceId,
71000
- commit: Buffer.from(removeResult.commit).toString("hex"),
71001
- commit_epoch: Number(mlsGroup.epoch),
71002
- ...parentDigest ? { parent_digest: parentDigest } : {}
71003
- })
71004
- }
71005
- );
71006
- if (removeResp.ok) {
71007
- removeCommitPublished = true;
71008
- parentDigest = this._commitDigest(removeResult.commit);
71009
- } else {
71010
- const detail = await removeResp.text().catch(() => "");
71011
- console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
71012
- }
71013
- } catch (distErr) {
71014
- console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
71015
- }
71016
- if (!removeCommitPublished) {
71017
- mlsGroup.importState(JSON.parse(preRemoveState));
71018
- continue;
71019
- }
71020
- const kpRes2 = await fetch(
71021
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
71022
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71023
- );
71024
- if (kpRes2.ok) {
71025
- const kpData2 = await kpRes2.json();
71026
- const kpHex2 = kpData2[req.requesting_device_id];
71027
- if (kpHex2) {
71028
- const kpBytes2 = new Uint8Array(Buffer.from(kpHex2, "hex"));
71029
- const memberKp2 = MLSGroupManager.deserializeKeyPackage(kpBytes2);
71030
- const result2 = await mlsGroup.addMembers([memberKp2]);
71031
- commit = result2.commit;
71032
- welcome = result2.welcome;
71033
- } else {
71034
- console.log(`[SecureChannel] A2A re-add: no fresh KeyPackage for ${req.requesting_device_id.slice(0, 8)}`);
71035
- continue;
71036
- }
71037
- } else {
71038
- console.log(`[SecureChannel] A2A re-add: KeyPackage fetch failed (${kpRes2.status})`);
71039
- continue;
71040
- }
71041
- } catch (readdErr) {
71042
- console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
71043
- if (!removeCommitPublished) {
71044
- try {
71045
- mlsGroup.importState(JSON.parse(preRemoveState));
71046
- } catch {
71047
- }
71048
- }
71049
- continue;
71050
- }
71051
- } else {
71052
- console.log(`[SecureChannel] A2A addMembers FAILED: ${errMsg}`);
71053
- continue;
71054
- }
71055
- }
71056
- if (!welcome) {
71057
- console.warn(`[SecureChannel] A2A addMembers produced no Welcome for ${req.requesting_device_id.slice(0, 8)}`);
71058
- continue;
71059
- }
71060
- const commitHex = Buffer.from(commit).toString("hex");
71061
- const welcomeHex = Buffer.from(welcome).toString("hex");
71062
- let distributed = false;
71063
- const updatedMembers = [this._deviceId, req.requesting_device_id];
71064
- try {
71065
- const distResp = await fetch(
71066
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71067
- {
71068
- method: "POST",
71069
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71070
- body: JSON.stringify({
71071
- group_id: chState.mlsGroupId,
71072
- device_id: this._deviceId,
71073
- commit: commitHex,
71074
- commit_epoch: Number(mlsGroup.epoch),
71075
- welcomes: [{ target_device_id: req.requesting_device_id, payload: welcomeHex }],
71076
- member_device_ids: updatedMembers,
71077
- ...parentDigest ? { parent_digest: parentDigest } : {}
71078
- })
71079
- }
71080
- );
71081
- if (distResp.ok) {
71082
- distributed = true;
71083
- } else {
71084
- const detail = await distResp.text().catch(() => "");
71085
- console.warn(`[SecureChannel] A2A distribute failed (${distResp.status}): ${detail}`);
71086
- }
71087
- } catch (distErr) {
71088
- console.warn(`[SecureChannel] A2A distribute network error:`, distErr);
71089
- }
71090
- if (!distributed && this._wsIsOpen()) {
71091
- const a2aLabel = `A2A ${chId.slice(0, 8)}`;
71092
- const commitSent = await this._sendFrameConfirmed({
71093
- event: "mls_commit",
71094
- data: {
71095
- group_id: chState.mlsGroupId,
71096
- epoch: Number(mlsGroup.epoch),
71097
- payload: commitHex,
71098
- ...parentDigest ? { parent_digest: parentDigest } : {}
71099
- }
71100
- }, `${a2aLabel} commit`);
71101
- const welcomeSent = commitSent && await this._sendFrameConfirmed({
71102
- event: "mls_welcome",
71103
- data: {
71104
- target_device_id: req.requesting_device_id,
71105
- group_id: chState.mlsGroupId,
71106
- a2a_channel_id: chId,
71107
- payload: welcomeHex
71108
- }
71109
- }, `${a2aLabel} welcome`);
71110
- if (!welcomeSent) {
71111
- console.warn(`[SecureChannel] ${a2aLabel}: Welcome frames were NOT written \u2014 leaving the request pending`);
71112
- continue;
71113
- }
71114
- try {
71115
- await fetch(
71116
- `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71117
- {
71118
- method: "POST",
71119
- headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71120
- body: JSON.stringify({
71121
- group_id: chState.mlsGroupId,
71122
- device_id: this._deviceId,
71123
- commit_epoch: Number(mlsGroup.epoch),
71124
- member_device_ids: updatedMembers
71125
- })
71126
- }
71127
- );
71128
- } catch {
71129
- }
71130
- distributed = true;
71131
- }
71132
- if (!distributed) {
71133
- console.warn(`[SecureChannel] Cannot deliver Welcome \u2014 HTTP distribute and WS both unavailable`);
71134
- continue;
71135
- }
71136
- const a2aFulfilled = await this._postFulfilWelcome(
71137
- chState.mlsGroupId,
71138
- req.id,
71139
- `A2A ${chId.slice(0, 8)}`
71140
- );
71141
- await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71142
- if (a2aFulfilled) {
71143
- console.log(`[SecureChannel] Fulfilled A2A Welcome for ${req.requesting_device_id.slice(0, 8)} in channel ${chId.slice(0, 8)}`);
71144
- }
71156
+ const next = await this._fulfilA2AWelcome(chId, chState, mlsGroup, req);
71157
+ if (next === "stop") break;
71145
71158
  } catch (fulfillErr) {
71146
71159
  console.log(`[SecureChannel] A2A Welcome fulfill failed: ${fulfillErr instanceof Error ? fulfillErr.message : String(fulfillErr)}`);
71147
71160
  }
@@ -71412,6 +71425,227 @@ ${baseText}`;
71412
71425
  }
71413
71426
  }
71414
71427
  }
71428
+ /**
71429
+ * #1225: fulfil ONE pending A2A Welcome request — the `/distribute` path.
71430
+ * Extracted from the delivery pull so the in-flight slot (review F1) is held
71431
+ * for exactly this request and released on every exit. Returns "stop" when
71432
+ * nothing else on this channel can succeed this pull (review F2).
71433
+ */
71434
+ async _fulfilA2AWelcome(chId, chState, mlsGroup, req) {
71435
+ const a2aLabel = `A2A ${chId.slice(0, 8)}`;
71436
+ const preHead = await this._readGroupHead(chState.mlsGroupId);
71437
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
71438
+ console.warn(
71439
+ `[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`
71440
+ );
71441
+ await this._catchUpAfterPreflightSkip(chState.mlsGroupId, preHead.epoch, Number(mlsGroup.epoch), a2aLabel);
71442
+ return "stop";
71443
+ }
71444
+ const inFlight = this._reserveCommit(chState.mlsGroupId, a2aLabel);
71445
+ if (!inFlight) return "stop";
71446
+ try {
71447
+ const kpRes = await fetch(
71448
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
71449
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71450
+ );
71451
+ if (!kpRes.ok) return "next";
71452
+ const kpData = await kpRes.json();
71453
+ const kpHex = kpData[req.requesting_device_id];
71454
+ if (!kpHex) return "next";
71455
+ const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
71456
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
71457
+ console.log(`[SecureChannel] A2A addMembers for ${req.requesting_device_id.slice(0, 8)} group=${chState.mlsGroupId.slice(0, 8)} epoch=${mlsGroup.epoch}`);
71458
+ let parentDigest = preHead.ok ? preHead.digest : void 0;
71459
+ let commit;
71460
+ let welcome;
71461
+ let preAddState = mlsGroup.exportState();
71462
+ try {
71463
+ const result = await mlsGroup.addMembers([memberKp]);
71464
+ commit = result.commit;
71465
+ welcome = result.welcome;
71466
+ } catch (addErr) {
71467
+ const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
71468
+ if (errMsg.includes("already in the group")) {
71469
+ console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
71470
+ const preRemoveState = JSON.stringify(mlsGroup.exportState());
71471
+ let removeCommitPublished = false;
71472
+ try {
71473
+ const identityBytes = new TextEncoder().encode(req.requesting_device_id);
71474
+ const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
71475
+ if (leafIndex === null) {
71476
+ console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
71477
+ return "next";
71478
+ }
71479
+ const removeResult = await mlsGroup.removeMember(leafIndex);
71480
+ try {
71481
+ const removeResp = await fetch(
71482
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71483
+ {
71484
+ method: "POST",
71485
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71486
+ body: JSON.stringify({
71487
+ group_id: chState.mlsGroupId,
71488
+ device_id: this._deviceId,
71489
+ commit: Buffer.from(removeResult.commit).toString("hex"),
71490
+ commit_epoch: Number(mlsGroup.epoch),
71491
+ expected_epoch: Number(mlsGroup.epoch) - 1,
71492
+ // #1225: exact-step, like the WS path
71493
+ ...parentDigest ? { parent_digest: parentDigest } : {}
71494
+ })
71495
+ }
71496
+ );
71497
+ if (removeResp.ok) {
71498
+ removeCommitPublished = true;
71499
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71500
+ parentDigest = this._commitDigest(removeResult.commit);
71501
+ } else {
71502
+ const detail = await removeResp.text().catch(() => "");
71503
+ console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
71504
+ }
71505
+ } catch (distErr) {
71506
+ console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
71507
+ }
71508
+ if (!removeCommitPublished) {
71509
+ mlsGroup.importState(JSON.parse(preRemoveState));
71510
+ return "next";
71511
+ }
71512
+ const kpRes2 = await fetch(
71513
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
71514
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71515
+ );
71516
+ if (kpRes2.ok) {
71517
+ const kpData2 = await kpRes2.json();
71518
+ const kpHex2 = kpData2[req.requesting_device_id];
71519
+ if (kpHex2) {
71520
+ const kpBytes2 = new Uint8Array(Buffer.from(kpHex2, "hex"));
71521
+ const memberKp2 = MLSGroupManager.deserializeKeyPackage(kpBytes2);
71522
+ preAddState = mlsGroup.exportState();
71523
+ const result2 = await mlsGroup.addMembers([memberKp2]);
71524
+ commit = result2.commit;
71525
+ welcome = result2.welcome;
71526
+ } else {
71527
+ console.log(`[SecureChannel] A2A re-add: no fresh KeyPackage for ${req.requesting_device_id.slice(0, 8)}`);
71528
+ return "next";
71529
+ }
71530
+ } else {
71531
+ console.log(`[SecureChannel] A2A re-add: KeyPackage fetch failed (${kpRes2.status})`);
71532
+ return "next";
71533
+ }
71534
+ } catch (readdErr) {
71535
+ console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
71536
+ if (!removeCommitPublished) {
71537
+ try {
71538
+ mlsGroup.importState(JSON.parse(preRemoveState));
71539
+ } catch {
71540
+ }
71541
+ }
71542
+ return "next";
71543
+ }
71544
+ } else {
71545
+ console.log(`[SecureChannel] A2A addMembers FAILED: ${errMsg}`);
71546
+ return "next";
71547
+ }
71548
+ }
71549
+ if (!welcome) {
71550
+ console.warn(`[SecureChannel] A2A addMembers produced no Welcome for ${req.requesting_device_id.slice(0, 8)}`);
71551
+ return "next";
71552
+ }
71553
+ const commitHex = Buffer.from(commit).toString("hex");
71554
+ const welcomeHex = Buffer.from(welcome).toString("hex");
71555
+ let distributed = false;
71556
+ let transportFailed = false;
71557
+ const updatedMembers = this._commitRoster([this._deviceId], [req.requesting_device_id]);
71558
+ try {
71559
+ const distResp = await fetch(
71560
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
71561
+ {
71562
+ method: "POST",
71563
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
71564
+ body: JSON.stringify({
71565
+ group_id: chState.mlsGroupId,
71566
+ device_id: this._deviceId,
71567
+ commit: commitHex,
71568
+ commit_epoch: Number(mlsGroup.epoch),
71569
+ welcomes: [{ target_device_id: req.requesting_device_id, payload: welcomeHex }],
71570
+ member_device_ids: updatedMembers,
71571
+ expected_epoch: Number(mlsGroup.epoch) - 1,
71572
+ // #1225: exact-step, like the WS path
71573
+ ...parentDigest ? { parent_digest: parentDigest } : {}
71574
+ })
71575
+ }
71576
+ );
71577
+ if (distResp.ok) {
71578
+ distributed = true;
71579
+ } else {
71580
+ const detail = await distResp.text().catch(() => "");
71581
+ console.warn(`[SecureChannel] A2A distribute failed (${distResp.status}): ${detail}`);
71582
+ if (distResp.status >= 500) {
71583
+ transportFailed = true;
71584
+ } else if (distResp.status === 409) {
71585
+ mlsGroup.importState(preAddState);
71586
+ console.warn(
71587
+ `[SecureChannel] ${a2aLabel}: add commit lost the race (409) \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, request stays pending`
71588
+ );
71589
+ return "next";
71590
+ } else {
71591
+ mlsGroup.importState(preAddState);
71592
+ console.error(
71593
+ `[SecureChannel] ${a2aLabel}: add commit refused with ${distResp.status} \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}; not retrying this channel this pull`
71594
+ );
71595
+ return "stop";
71596
+ }
71597
+ }
71598
+ } catch (distErr) {
71599
+ console.warn(`[SecureChannel] A2A distribute network error:`, distErr);
71600
+ transportFailed = true;
71601
+ }
71602
+ if (!distributed && transportFailed && this._wsIsOpen()) {
71603
+ const verdict = await this._sendCommitConfirmed({
71604
+ mlsGroup,
71605
+ mlsGroupId: chState.mlsGroupId,
71606
+ label: a2aLabel,
71607
+ commit,
71608
+ epoch: Number(mlsGroup.epoch),
71609
+ parent: parentDigest,
71610
+ memberDeviceIds: updatedMembers,
71611
+ stateBefore: preAddState,
71612
+ inFlight
71613
+ });
71614
+ if (verdict !== "confirmed") return "next";
71615
+ const welcomeSent = await this._sendFrameConfirmed({
71616
+ event: "mls_welcome",
71617
+ data: {
71618
+ target_device_id: req.requesting_device_id,
71619
+ group_id: chState.mlsGroupId,
71620
+ a2a_channel_id: chId,
71621
+ payload: welcomeHex
71622
+ }
71623
+ }, `${a2aLabel} welcome`);
71624
+ if (!welcomeSent) {
71625
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71626
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome frame was NOT written \u2014 leaving the request pending`);
71627
+ return "next";
71628
+ }
71629
+ distributed = true;
71630
+ }
71631
+ if (!distributed) {
71632
+ console.warn(`[SecureChannel] Cannot deliver Welcome \u2014 HTTP distribute and WS both unavailable`);
71633
+ return "next";
71634
+ }
71635
+ const a2aFulfilled = await this._postFulfilWelcome(
71636
+ chState.mlsGroupId,
71637
+ req.id,
71638
+ `A2A ${chId.slice(0, 8)}`
71639
+ );
71640
+ await saveMlsState(this.config.dataDir, chState.mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71641
+ if (a2aFulfilled) {
71642
+ console.log(`[SecureChannel] Fulfilled A2A Welcome for ${req.requesting_device_id.slice(0, 8)} in channel ${chId.slice(0, 8)}`);
71643
+ }
71644
+ return "next";
71645
+ } finally {
71646
+ await this._releaseCommit(chState.mlsGroupId, inFlight, a2aLabel);
71647
+ }
71648
+ }
71415
71649
  /**
71416
71650
  * Found the MLS group for an A2A channel as the creator agent.
71417
71651
  * Calls /mls/a2a/{channelId}/init, creates the local MLS group, and sends
@@ -71454,48 +71688,77 @@ ${baseText}`;
71454
71688
  await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
71455
71689
  for (const p2 of participants) {
71456
71690
  if (p2.status !== "active" && p2.status !== "invited") continue;
71691
+ const a2aLabel = `A2A ${channelId.slice(0, 8)} found\u2192${p2.hubAddress}`;
71457
71692
  try {
71458
- const kpRes = await fetch(
71459
- `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(p2.hubId)}`,
71460
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71461
- );
71462
- if (kpRes.ok) {
71463
- const kpData = await kpRes.json();
71464
- if (kpData.key_package) {
71465
- const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
71466
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
71467
- const { commit, welcome } = await mgr.addMembers([memberKp]);
71468
- if (welcome && this._ws) {
71469
- this._ws.send(JSON.stringify({
71470
- event: "mls_commit",
71693
+ if (!p2.deviceId) {
71694
+ console.warn(
71695
+ `[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.`
71696
+ );
71697
+ continue;
71698
+ }
71699
+ if (!this._wsIsOpen()) {
71700
+ console.warn(`[SecureChannel] ${a2aLabel}: socket is not OPEN \u2014 NOT advancing the group`);
71701
+ continue;
71702
+ }
71703
+ const head = await this._readGroupHead(mlsData.group_id);
71704
+ if (head.ok && head.epoch !== Number(mgr.epoch)) {
71705
+ console.warn(`[SecureChannel] ${a2aLabel}: server head is at epoch ${head.epoch}, we are at ${Number(mgr.epoch)} \u2014 NOT committing`);
71706
+ await this._catchUpAfterPreflightSkip(mlsData.group_id, head.epoch, Number(mgr.epoch), a2aLabel);
71707
+ continue;
71708
+ }
71709
+ const inFlight = this._reserveCommit(mlsData.group_id, a2aLabel);
71710
+ if (!inFlight) continue;
71711
+ try {
71712
+ const kpRes = await fetch(
71713
+ `${this.config.apiUrl}/api/v1/mls/key-packages?hub_id=${encodeURIComponent(p2.hubId)}`,
71714
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71715
+ );
71716
+ if (kpRes.ok) {
71717
+ const kpData = await kpRes.json();
71718
+ if (kpData.key_package) {
71719
+ const kpBytes = new Uint8Array(Buffer.from(kpData.key_package, "hex"));
71720
+ const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
71721
+ const stateBefore = mgr.exportState();
71722
+ const { commit, welcome } = await mgr.addMembers([memberKp]);
71723
+ const committedEpoch = Number(mgr.epoch);
71724
+ if (!welcome) {
71725
+ mgr.importState(stateBefore);
71726
+ console.warn(`[SecureChannel] ${a2aLabel}: addMembers produced no Welcome \u2014 rolled back`);
71727
+ continue;
71728
+ }
71729
+ const verdict = await this._sendCommitConfirmed({
71730
+ mlsGroup: mgr,
71731
+ mlsGroupId: mlsData.group_id,
71732
+ label: a2aLabel,
71733
+ commit,
71734
+ epoch: committedEpoch,
71735
+ parent: head.ok ? head.digest : void 0,
71736
+ memberDeviceIds: this._commitRoster(participants.map((q2) => q2.deviceId), [p2.deviceId]),
71737
+ stateBefore,
71738
+ inFlight
71739
+ });
71740
+ if (verdict !== "confirmed") continue;
71741
+ const sent = await this._sendFrameConfirmed({
71742
+ event: "mls_welcome",
71471
71743
  data: {
71472
71744
  group_id: mlsData.group_id,
71473
- epoch: Number(mgr.epoch),
71474
- payload: Buffer.from(commit).toString("hex")
71745
+ payload: Buffer.from(welcome).toString("hex"),
71746
+ target_device_id: p2.deviceId,
71747
+ a2a_channel_id: channelId,
71748
+ target_hub_id: p2.hubId
71749
+ // observability only — the backend ignores it
71475
71750
  }
71476
- }));
71477
- if (!p2.deviceId) {
71478
- console.warn(
71479
- `[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.`
71480
- );
71481
- } else {
71482
- this._ws.send(JSON.stringify({
71483
- event: "mls_welcome",
71484
- data: {
71485
- group_id: mlsData.group_id,
71486
- payload: Buffer.from(welcome).toString("hex"),
71487
- target_device_id: p2.deviceId,
71488
- a2a_channel_id: channelId,
71489
- // Kept for observability — backend ignores but it's
71490
- // useful in logs/wire captures to correlate to a hub.
71491
- target_hub_id: p2.hubId
71492
- }
71493
- }));
71751
+ }, `${a2aLabel} welcome`);
71752
+ await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
71753
+ if (sent) {
71494
71754
  console.log(`[SecureChannel] Sent MLS Welcome to ${p2.hubAddress} (device ${p2.deviceId.slice(0, 8)}) for A2A ${channelId.slice(0, 8)}`);
71755
+ } else {
71756
+ console.warn(`[SecureChannel] ${a2aLabel}: Welcome was NOT written \u2014 the participant will request one`);
71495
71757
  }
71496
71758
  }
71497
- await saveMlsState(this.config.dataDir, mlsData.group_id, JSON.stringify(mgr.exportState()));
71498
71759
  }
71760
+ } finally {
71761
+ await this._releaseCommit(mlsData.group_id, inFlight, a2aLabel);
71499
71762
  }
71500
71763
  } catch (kpErr) {
71501
71764
  console.warn(`[SecureChannel] Failed to Welcome participant ${p2.hubAddress}:`, kpErr);
@@ -99007,7 +99270,7 @@ var init_index = __esm({
99007
99270
  await init_skill_telemetry();
99008
99271
  await init_policy_enforcer();
99009
99272
  init_room_protocol();
99010
- VERSION = true ? "0.23.40" : "0.0.0-dev";
99273
+ VERSION = true ? "0.23.41" : "0.0.0-dev";
99011
99274
  }
99012
99275
  });
99013
99276
  await init_index();