@agentvault/claude-bridge 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bridge.d.ts CHANGED
@@ -43,6 +43,10 @@ export interface RoomHushed {
43
43
  }
44
44
  export interface RoomChannel {
45
45
  on(ev: "room_message", cb: (e: RoomMessage) => void): unknown;
46
+ on(ev: "room_joined", cb: (e: {
47
+ roomId: string;
48
+ name?: string;
49
+ }) => void): unknown;
46
50
  on(ev: "message", cb: (text: string, metadata: MessageMeta) => void): unknown;
47
51
  on(ev: "room_hushed", cb: (e: RoomHushed) => void): unknown;
48
52
  on(ev: "error", cb: (err: unknown) => void): unknown;
@@ -175,6 +179,26 @@ export declare function attachLifecycle(channel: LifecycleChannel, opts?: {
175
179
  * dropped (it usually means a mis-timed or duplicate approval).
176
180
  */
177
181
  export declare function pollApprovalsOnce(arming: ArmingState, dataDir: string, onArmed: () => void, log?: (msg: string) => void): void;
182
+ /**
183
+ * How a ROOM turn is announced to the model (#366 / #499 Facet A).
184
+ *
185
+ * Reproduced live 2026-07-29: asked "what room are you in?" *in* a room, the
186
+ * agent answered "This is our 1:1 DM, so no room name to report." Everything
187
+ * beneath the model was correct — the bridge logged `inbound from chris in
188
+ * c6a2734d` then `said to room c6a2734d`, and the message is recorded against
189
+ * room "New Test" in the database. The turn was simply pushed as
190
+ * `[chris]: <text>`, which carries no channel context whatsoever, so the model
191
+ * had nothing to distinguish a room from a DM and defaulted to DM.
192
+ *
193
+ * The room NAME is best-effort (learned from `room_joined`), but the fact that
194
+ * this is a room is not: when the name is unknown we still say "room" and fall
195
+ * back to a short id. Getting "which room" wrong is a cosmetic answer; getting
196
+ * "am I in a room" wrong changes how the agent addresses everyone in it.
197
+ *
198
+ * A 1:1 DM is deliberately left unlabelled — that path is not broken, and an
199
+ * unmarked turn already reads as a DM, which is what the model assumes.
200
+ */
201
+ export declare function roomTurnPrefix(roomId: string, senderName: string, roomName?: string): string;
178
202
  export declare function wireBridge(channel: RoomChannel, session: RoomSession, target: ActiveTarget, opts?: {
179
203
  roomFilter?: string;
180
204
  armRoom?: boolean;
package/dist/index.js CHANGED
@@ -63525,6 +63525,34 @@ var init_owner_sync = __esm2({
63525
63525
  NONCE_BYTES2 = 24;
63526
63526
  }
63527
63527
  });
63528
+ function seqOf(m22) {
63529
+ if (m22.seq === void 0 || m22.seq === null || m22.seq === "")
63530
+ return null;
63531
+ const n22 = Number(m22.seq);
63532
+ return Number.isFinite(n22) ? n22 : null;
63533
+ }
63534
+ function createdAtOf(m22) {
63535
+ const t22 = new Date(m22.created_at ?? 0).getTime();
63536
+ return Number.isFinite(t22) ? t22 : 0;
63537
+ }
63538
+ function orderDeliveryBatch(messages) {
63539
+ return [...messages].sort((a2, b22) => {
63540
+ const aWelcome = a2.message_type === "welcome";
63541
+ const bWelcome = b22.message_type === "welcome";
63542
+ if (aWelcome !== bWelcome)
63543
+ return aWelcome ? -1 : 1;
63544
+ const as2 = seqOf(a2);
63545
+ const bs2 = seqOf(b22);
63546
+ if (as2 !== null && bs2 !== null && as2 !== bs2)
63547
+ return as2 - bs2;
63548
+ return createdAtOf(a2) - createdAtOf(b22);
63549
+ });
63550
+ }
63551
+ var init_mls_delivery_order = __esm2({
63552
+ "../crypto/dist/mls-delivery-order.js"() {
63553
+ "use strict";
63554
+ }
63555
+ });
63528
63556
  var dist_exports = {};
63529
63557
  __export2(dist_exports, {
63530
63558
  AV_CREDENTIAL_CONTEXT: () => AV_CREDENTIAL_CONTEXT,
@@ -63595,6 +63623,7 @@ __export2(dist_exports, {
63595
63623
  issueCredential: () => issueCredential,
63596
63624
  multibaseToPublicKey: () => multibaseToPublicKey,
63597
63625
  normalizeBackupCode: () => normalizeBackupCode,
63626
+ orderDeliveryBatch: () => orderDeliveryBatch,
63598
63627
  parseTraceparent: () => parseTraceparent,
63599
63628
  performX3DH: () => performX3DH,
63600
63629
  presentCredentials: () => presentCredentials,
@@ -63632,6 +63661,7 @@ var init_dist = __esm2({
63632
63661
  await init_approval();
63633
63662
  init_mls_group();
63634
63663
  await init_owner_sync();
63664
+ init_mls_delivery_order();
63635
63665
  }
63636
63666
  });
63637
63667
  function syncLockPath(dataDir, channelId) {
@@ -64592,6 +64622,7 @@ var init_channel = __esm2({
64592
64622
  "use strict";
64593
64623
  await init_libsodium_wrappers();
64594
64624
  await init_dist();
64625
+ await init_dist();
64595
64626
  init_mls_state();
64596
64627
  await init_mls_kp_pool();
64597
64628
  init_credential_store();
@@ -64679,6 +64710,10 @@ var init_channel = __esm2({
64679
64710
  _sessionGroupIds = /* @__PURE__ */ new Map();
64680
64711
  /** Consecutive MLS decrypt failure count per group key for epoch recovery. */
64681
64712
  _mlsDecryptFailCounts = /* @__PURE__ */ new Map();
64713
+ /** #474: per-group consecutive processCommit failures. Mirrors the decrypt
64714
+ * counter above — a commit that fails is divergence, and divergence must
64715
+ * self-heal rather than be logged and dropped. */
64716
+ _mlsCommitFailCounts = /* @__PURE__ */ new Map();
64682
64717
  static MAX_MLS_DECRYPT_FAILS = 3;
64683
64718
  /** Cached MLS KeyPackage bundle for this device (regenerated on each connect). */
64684
64719
  _mlsKeyPackage = null;
@@ -65559,7 +65594,7 @@ var init_channel = __esm2({
65559
65594
  */
65560
65595
  sendActivitySpan(spanData) {
65561
65596
  if (!this._ws || this._ws.readyState !== WebSocket2.OPEN) return;
65562
- const pluginVersion = true ? "0.23.11" : "0.0.0-dev";
65597
+ const pluginVersion = true ? "0.23.13" : "0.0.0-dev";
65563
65598
  const agentName = this.config.agentName ?? "Agent";
65564
65599
  const resource = {
65565
65600
  "service.name": "agentvault-agent",
@@ -67298,7 +67333,7 @@ var init_channel = __esm2({
67298
67333
  agentVersion: this.config.agentVersion ?? "0.0.0",
67299
67334
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
67300
67335
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
67301
- pluginVersion: true ? "0.23.11" : "0.0.0-dev"
67336
+ pluginVersion: true ? "0.23.13" : "0.0.0-dev"
67302
67337
  });
67303
67338
  this._telemetryReporter.startAutoFlush(3e4);
67304
67339
  }
@@ -67616,7 +67651,7 @@ var init_channel = __esm2({
67616
67651
  agentVersion: this.config.agentVersion ?? "0.0.0",
67617
67652
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
67618
67653
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
67619
- pluginVersion: true ? "0.23.11" : "0.0.0-dev"
67654
+ pluginVersion: true ? "0.23.13" : "0.0.0-dev"
67620
67655
  });
67621
67656
  this._telemetryReporter.startAutoFlush(3e4);
67622
67657
  }
@@ -69012,14 +69047,9 @@ ${messageText}`;
69012
69047
  await saveMlsState(this.config.dataDir, groupId, JSON.stringify(mlsGroup.exportState()));
69013
69048
  console.log(`[SecureChannel] MLS commit processed for room ${roomId.slice(0, 8)} (epoch=${mlsGroup.epoch})`);
69014
69049
  } catch (err) {
69015
- const isOldEpoch = err?.message?.includes("epoch") || err?.message?.includes("old") || err?.message?.includes("Validation");
69016
- if (isOldEpoch) {
69017
- console.log(`[SecureChannel] Discarding old-epoch commit for room ${roomId.slice(0, 8)}`);
69018
- } else {
69019
- console.error(`[SecureChannel] MLS commit failed for room ${roomId.slice(0, 8)}:`, err);
69020
- throw err;
69021
- }
69050
+ await this._onCommitFailure(roomId, groupId, err, `room ${roomId.slice(0, 8)}`);
69022
69051
  }
69052
+ this._mlsCommitFailCounts.delete(roomId);
69023
69053
  } else {
69024
69054
  this._bufferMlsCommit(groupId, epoch, data);
69025
69055
  console.log(`[SecureChannel] Buffered MLS commit for room ${roomId.slice(0, 8)} (epoch=${epoch}, group not initialized)`);
@@ -69037,14 +69067,9 @@ ${messageText}`;
69037
69067
  await saveMlsState(this.config.dataDir, groupId, JSON.stringify(mlsGroup.exportState()));
69038
69068
  console.log(`[SecureChannel] MLS commit processed for A2A ${chId.slice(0, 8)} (epoch=${mlsGroup.epoch})`);
69039
69069
  } catch (err) {
69040
- const isOldEpoch = err?.message?.includes("epoch") || err?.message?.includes("old") || err?.message?.includes("Validation");
69041
- if (isOldEpoch) {
69042
- console.log(`[SecureChannel] Discarding old-epoch commit for A2A ${chId.slice(0, 8)}`);
69043
- } else {
69044
- console.error(`[SecureChannel] MLS commit failed for A2A ${chId.slice(0, 8)}:`, err);
69045
- throw err;
69046
- }
69070
+ await this._onCommitFailure(`a2a:${chId}`, groupId, err, `A2A ${chId.slice(0, 8)}`);
69047
69071
  }
69072
+ this._mlsCommitFailCounts.delete(`a2a:${chId}`);
69048
69073
  } else {
69049
69074
  this._bufferMlsCommit(groupId, epoch, data);
69050
69075
  console.log(`[SecureChannel] Buffered MLS commit for A2A ${chId.slice(0, 8)} (epoch=${epoch}, group not initialized)`);
@@ -69101,6 +69126,52 @@ ${messageText}`;
69101
69126
  * sends us one. Deduped to a 30s window per group so a burst of undecryptable
69102
69127
  * rows doesn't spam request-welcome. Fire-and-forget.
69103
69128
  */
69129
+ /**
69130
+ * #474 — a failed `processCommit` is DIVERGENCE, and divergence must
69131
+ * self-heal. It previously did neither: the room stayed broken forever.
69132
+ *
69133
+ * Two swallow paths existed, and only the second was ever reported:
69134
+ *
69135
+ * 1. `isOldEpoch` substring-matched the error text for "epoch" / "old" /
69136
+ * "Validation" and discarded deliberately. `ValidationError: Desired gen
69137
+ * in the past` contains "Validation", so the LOUDEST production failure
69138
+ * was filed as benign — 1,439 occurrences on one agent, all thrown away
69139
+ * by a string match.
69140
+ * 2. Everything else re-threw to the WS dispatcher, which logs and drops.
69141
+ *
69142
+ * Result: ~1,600 commit failures across 13 rooms and ZERO resyncs. Classifying
69143
+ * divergence by grepping an error message is the root of it — error text is
69144
+ * not a protocol, and the one case that must never be silent was the one that
69145
+ * happened to contain the magic word.
69146
+ *
69147
+ * So: no classification. COUNT, and after MAX_MLS_DECRYPT_FAILS consecutive
69148
+ * failures run the same ladder the decrypt path has used since #440 — replay
69149
+ * the missed commits via /sync, and fall back to re-join only if that cannot
69150
+ * catch up. Counting rather than resyncing on first failure matters: a
69151
+ * genuinely stale commit is normal, and resyncing on each one would have
69152
+ * fired ~1,600 Welcome requests.
69153
+ *
69154
+ * Never re-throws. The caller's only handler logs and drops, so throwing here
69155
+ * is indistinguishable from swallowing — it just moves the swallow one frame up.
69156
+ */
69157
+ async _onCommitFailure(groupKey, mlsGroupId, err, label) {
69158
+ const count = (this._mlsCommitFailCounts.get(groupKey) ?? 0) + 1;
69159
+ this._mlsCommitFailCounts.set(groupKey, count);
69160
+ console.error(
69161
+ `[SecureChannel] MLS commit failed (${count}/${_SecureChannel.MAX_MLS_DECRYPT_FAILS}) for ${label}:`,
69162
+ err
69163
+ );
69164
+ if (count < _SecureChannel.MAX_MLS_DECRYPT_FAILS) return;
69165
+ console.warn(`[SecureChannel] MLS commit resync triggered for ${label} \u2014 ${count} consecutive failures`);
69166
+ try {
69167
+ if (!await this._resyncOnDivergence(groupKey, mlsGroupId)) {
69168
+ await this._triggerMlsEpochRecovery(groupKey, mlsGroupId);
69169
+ }
69170
+ this._mlsCommitFailCounts.delete(groupKey);
69171
+ } catch (recoverErr) {
69172
+ console.error(`[SecureChannel] MLS commit resync FAILED for ${label}:`, recoverErr);
69173
+ }
69174
+ }
69104
69175
  async _requestWelcomeSelfHeal(groupId) {
69105
69176
  const now = Date.now();
69106
69177
  const last = this._welcomeSelfHealInflight.get(groupId) ?? 0;
@@ -69498,16 +69569,10 @@ ${messageText}`;
69498
69569
  console.warn(`[SecureChannel] Delivery pull failed: ${res.status}`);
69499
69570
  return;
69500
69571
  }
69501
- const { messages } = await res.json();
69572
+ let { messages } = await res.json();
69502
69573
  const hasMessages = messages && messages.length > 0;
69503
69574
  if (hasMessages) {
69504
- const order = { welcome: 0, commit: 1, application: 2 };
69505
- messages.sort((a2, b22) => {
69506
- const ao = order[a2.message_type] ?? 2;
69507
- const bo = order[b22.message_type] ?? 2;
69508
- if (ao !== bo) return ao - bo;
69509
- return new Date(a2.created_at).getTime() - new Date(b22.created_at).getTime();
69510
- });
69575
+ messages = orderDeliveryBatch(messages);
69511
69576
  const ackedIds = [];
69512
69577
  const nackedIds = [];
69513
69578
  for (const msg of messages) {
@@ -69902,9 +69967,43 @@ ${messageText}`;
69902
69967
  const errMsg = addErr instanceof Error ? addErr.message : String(addErr);
69903
69968
  if (errMsg.includes("already in the group")) {
69904
69969
  console.log(`[SecureChannel] A2A member already in group \u2014 removing and re-adding ${req.requesting_device_id.slice(0, 8)}`);
69970
+ const preRemoveState = JSON.stringify(mlsGroup.exportState());
69971
+ let removeCommitPublished = false;
69905
69972
  try {
69906
69973
  const identityBytes = new TextEncoder().encode(req.requesting_device_id);
69907
- await mlsGroup.removeMember(identityBytes);
69974
+ const leafIndex = mlsGroup.memberLeafIndex(identityBytes);
69975
+ if (leafIndex === null) {
69976
+ console.log(`[SecureChannel] A2A re-add: no leaf index for ${req.requesting_device_id.slice(0, 8)} \u2014 cannot remove`);
69977
+ continue;
69978
+ }
69979
+ const removeResult = await mlsGroup.removeMember(leafIndex);
69980
+ try {
69981
+ const removeResp = await fetch(
69982
+ `${this.config.apiUrl}/api/v1/mls/groups/${chState.mlsGroupId}/distribute`,
69983
+ {
69984
+ method: "POST",
69985
+ headers: { Authorization: `Bearer ${this._deviceJwt}`, "Content-Type": "application/json" },
69986
+ body: JSON.stringify({
69987
+ group_id: chState.mlsGroupId,
69988
+ device_id: this._deviceId,
69989
+ commit: Buffer.from(removeResult.commit).toString("hex"),
69990
+ commit_epoch: Number(mlsGroup.epoch)
69991
+ })
69992
+ }
69993
+ );
69994
+ if (removeResp.ok) {
69995
+ removeCommitPublished = true;
69996
+ } else {
69997
+ const detail = await removeResp.text().catch(() => "");
69998
+ console.warn(`[SecureChannel] A2A remove-commit distribute failed (${removeResp.status}): ${detail}`);
69999
+ }
70000
+ } catch (distErr) {
70001
+ console.warn(`[SecureChannel] A2A remove-commit distribute network error:`, distErr);
70002
+ }
70003
+ if (!removeCommitPublished) {
70004
+ mlsGroup.importState(JSON.parse(preRemoveState));
70005
+ continue;
70006
+ }
69908
70007
  const kpRes2 = await fetch(
69909
70008
  `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
69910
70009
  { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
@@ -69928,6 +70027,12 @@ ${messageText}`;
69928
70027
  }
69929
70028
  } catch (readdErr) {
69930
70029
  console.log(`[SecureChannel] A2A remove+re-add FAILED: ${readdErr instanceof Error ? readdErr.message : String(readdErr)}`);
70030
+ if (!removeCommitPublished) {
70031
+ try {
70032
+ mlsGroup.importState(JSON.parse(preRemoveState));
70033
+ } catch {
70034
+ }
70035
+ }
69931
70036
  continue;
69932
70037
  }
69933
70038
  } else {
@@ -97395,7 +97500,7 @@ var init_index = __esm2({
97395
97500
  init_skill_invoker();
97396
97501
  await init_skill_telemetry();
97397
97502
  await init_policy_enforcer();
97398
- VERSION = true ? "0.23.11" : "0.0.0-dev";
97503
+ VERSION = true ? "0.23.13" : "0.0.0-dev";
97399
97504
  }
97400
97505
  });
97401
97506
  await init_index();
@@ -133452,6 +133557,10 @@ function pollApprovalsOnce(arming, dataDir, onArmed, log = () => {
133452
133557
  }
133453
133558
  }
133454
133559
  }
133560
+ function roomTurnPrefix(roomId, senderName, roomName) {
133561
+ const room = roomName ? `"${roomName}"` : roomId.slice(0, 8);
133562
+ return `[room ${room} | ${senderName}]`;
133563
+ }
133455
133564
  function wireBridge(channel, session, target, opts = {}) {
133456
133565
  const log = opts.log ?? (() => {
133457
133566
  });
@@ -133486,6 +133595,10 @@ function wireBridge(channel, session, target, opts = {}) {
133486
133595
  );
133487
133596
  });
133488
133597
  let warnedMissingSenderIsAgent = false;
133598
+ const roomNames = /* @__PURE__ */ new Map();
133599
+ channel.on("room_joined", (e7) => {
133600
+ if (e7?.roomId && e7.name) roomNames.set(e7.roomId, e7.name);
133601
+ });
133489
133602
  channel.on("room_message", (e7) => {
133490
133603
  if (typeof e7.senderIsAgent !== "boolean" && !warnedMissingSenderIsAgent) {
133491
133604
  warnedMissingSenderIsAgent = true;
@@ -133500,7 +133613,7 @@ function wireBridge(channel, session, target, opts = {}) {
133500
133613
  }
133501
133614
  log(`inbound from ${e7.senderName} in ${e7.roomId.slice(0, 8)}`);
133502
133615
  target.setRoom(e7.roomId);
133503
- session.push(`[${e7.senderName}]: ${e7.plaintext}`, target.snapshotReply(channel, log), {
133616
+ session.push(`${roomTurnPrefix(e7.roomId, e7.senderName, roomNames.get(e7.roomId))}: ${e7.plaintext}`, target.snapshotReply(channel, log), {
133504
133617
  autoReplyOnText: false,
133505
133618
  replyExpected: e7.senderIsAgent === false,
133506
133619
  armed: () => arming.isArmed(e7.roomId)
@@ -133651,7 +133764,7 @@ async function main() {
133651
133764
  "[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"
133652
133765
  );
133653
133766
  }
133654
- console.error(`[bridge] version: ${true ? "0.7.1" : "dev"}`);
133767
+ console.error(`[bridge] version: ${true ? "0.7.3" : "dev"}`);
133655
133768
  console.error(`[bridge] data dir: ${cfg.dataDir} (${cfg.dataDirSource})`);
133656
133769
  console.error(`[bridge] workspace: ${cfg.workspaceDir} \xB7 permissions: ${cfg.permissionMode} \xB7 enclave dir fenced`);
133657
133770
  if (cfg.armRoom) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/claude-bridge",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
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",