@agentvault/claude-bridge 0.8.12 → 0.8.13

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
@@ -211,6 +211,23 @@ export declare function pollApprovalsOnce(arming: ArmingState, dataDir: string,
211
211
  * unmarked turn already reads as a DM, which is what the model assumes.
212
212
  */
213
213
  export declare function roomTurnPrefix(roomId: string, senderName: string, roomName?: string): string;
214
+ /**
215
+ * Does this agent owe a reply to this room message? (#1107)
216
+ *
217
+ * This bridge used to answer with `e.senderIsAgent === false` — "reply to any
218
+ * human". That was a THIRD implementation of the room reply rule, alongside the
219
+ * OpenClaw plugin and hermes, and #1107 shipped to the other two only. Under the
220
+ * old rule this agent would still have answered every un-mentioned message while
221
+ * wren, cortina, smartcode and smartcoder2 stayed quiet: the cascade, half-fixed,
222
+ * in the half most likely to be read as "the protocol doesn't work".
223
+ *
224
+ * Now it defers to the ONE shared implementation exported by
225
+ * `@agentvault/agentvault`. The message is still pushed into the session either
226
+ * way — the agent reads the whole room and only the reply obligation changes.
227
+ */
228
+ export declare function _makeOwesReply(agentName: string | undefined, channel: {
229
+ ownDisplayName?: string;
230
+ }, log: (msg: string) => void): (e: RoomMessage) => boolean;
214
231
  export declare function wireBridge(channel: RoomChannel, session: RoomSession, target: ActiveTarget, opts?: {
215
232
  /**
216
233
  * #1107: this agent's own name, used to recognise its own @mention. Threaded
package/dist/index.js CHANGED
@@ -1122,6 +1122,58 @@ var init_mls_commit_classify = __esm2({
1122
1122
  "use strict";
1123
1123
  }
1124
1124
  });
1125
+ function parseMentions(text) {
1126
+ const mentions = [];
1127
+ const re22 = new RegExp(MENTION_RE.source, MENTION_RE.flags);
1128
+ let match;
1129
+ while ((match = re22.exec(text)) !== null) {
1130
+ mentions.push(match[1].toLowerCase());
1131
+ }
1132
+ return mentions;
1133
+ }
1134
+ function resolveOwn(mention, names) {
1135
+ if (names.has(mention)) return mention;
1136
+ const parts = mention.split("-");
1137
+ for (let i2 = parts.length - 1; i2 > 0; i2--) {
1138
+ const candidate = parts.slice(0, i2).join("-");
1139
+ if (names.has(candidate)) return candidate;
1140
+ }
1141
+ return null;
1142
+ }
1143
+ function owesRoomReply(plaintext, agentName, accountId, senderIsAgent, roomDisplayName, ownDisplayName, selfResolved = true) {
1144
+ const mentions = parseMentions(plaintext);
1145
+ if (mentions.length === 0) return false;
1146
+ const ownNames = ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName);
1147
+ if (mentions.some((m22) => resolveOwn(m22, ownNames) !== null)) return true;
1148
+ if (mentions.some((m22) => resolveOwn(m22, BROADCAST_NAMES) !== null)) {
1149
+ return senderIsAgent !== true;
1150
+ }
1151
+ if (!selfResolved) return true;
1152
+ return false;
1153
+ }
1154
+ function ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName) {
1155
+ const names = /* @__PURE__ */ new Set();
1156
+ const add4 = (n22) => {
1157
+ if (!n22) return;
1158
+ const lower = n22.toLowerCase();
1159
+ names.add(lower);
1160
+ names.add(lower.split(/[\s(]/)[0]);
1161
+ };
1162
+ add4(agentName);
1163
+ add4(accountId);
1164
+ add4(roomDisplayName);
1165
+ add4(ownDisplayName);
1166
+ return names;
1167
+ }
1168
+ var MENTION_RE;
1169
+ var BROADCAST_NAMES;
1170
+ var init_room_protocol = __esm2({
1171
+ "src/room-protocol.ts"() {
1172
+ "use strict";
1173
+ MENTION_RE = /@([\w-]+)/gi;
1174
+ BROADCAST_NAMES = /* @__PURE__ */ new Set(["all", "everyone"]);
1175
+ }
1176
+ });
1125
1177
  var __filename;
1126
1178
  var __dirname;
1127
1179
  var url2;
@@ -64024,10 +64076,10 @@ var init_mls_group = __esm2({
64024
64076
  const commits = [];
64025
64077
  if (leavesToRemove.length > 0) {
64026
64078
  const { commit } = await this.removeMembers(leavesToRemove);
64027
- commits.push({ commit, epoch: this.epoch });
64079
+ commits.push({ commit, epoch: this.epoch, state: this.exportState() });
64028
64080
  }
64029
64081
  const added = await this.addMembers(toAdd);
64030
- commits.push({ commit: added.commit, epoch: this.epoch });
64082
+ commits.push({ commit: added.commit, epoch: this.epoch, state: this.exportState() });
64031
64083
  return { commits, welcome: added.welcome };
64032
64084
  }
64033
64085
  async removeMembers(memberIndices) {
@@ -64612,11 +64664,11 @@ var init_mls_kp_pool = __esm2({
64612
64664
  }
64613
64665
  });
64614
64666
  function ownIdentity() {
64615
- const v22 = true ? "0.23.39" : FALLBACK;
64667
+ const v22 = true ? "0.23.40" : FALLBACK;
64616
64668
  return `${PACKAGE}@${v22}`;
64617
64669
  }
64618
64670
  function buildSha() {
64619
- const raw = true ? "9982fc8-dirty" : "";
64671
+ const raw = true ? "dbac15d-dirty" : "";
64620
64672
  const cleaned = (raw ?? "").trim();
64621
64673
  return !cleaned || cleaned === "unknown" ? null : cleaned;
64622
64674
  }
@@ -65538,6 +65590,7 @@ var init_channel = __esm2({
65538
65590
  "use strict";
65539
65591
  init_abstention();
65540
65592
  init_mls_commit_classify();
65593
+ init_room_protocol();
65541
65594
  await init_libsodium_wrappers();
65542
65595
  await init_dist();
65543
65596
  await init_dist();
@@ -65740,6 +65793,35 @@ var init_channel = __esm2({
65740
65793
 
65741
65794
  ${text}`;
65742
65795
  }
65796
+ /**
65797
+ * #1161: room attachments whose caption addressed nobody, NOT yet fetched.
65798
+ * The reply gate lives in every consumer of `room_message` (openclaw-entry
65799
+ * and the three native bridges), but its first clause is shared and needs no
65800
+ * identity: a caption with no mention token owes nobody a reply (#1107), so
65801
+ * nobody needs the file yet. Kept per room, newest last, and fetched on the
65802
+ * room's next ADDRESSED turn — the owner attaches, then asks (#1159/#1181).
65803
+ * Hermes does the same (`_defer_room_attachment`).
65804
+ */
65805
+ _deferredRoomAttachments = /* @__PURE__ */ new Map();
65806
+ static DEFERRED_ROOM_ATTACHMENT_MAX = 5;
65807
+ static DEFERRED_ROOM_ATTACHMENT_MS = 60 * 60 * 1e3;
65808
+ _deferRoomAttachment(roomId, info) {
65809
+ const list = this._deferredRoomAttachments.get(roomId) ?? [];
65810
+ list.push({ info, at: Date.now() });
65811
+ while (list.length > _SecureChannel.DEFERRED_ROOM_ATTACHMENT_MAX) list.shift();
65812
+ this._deferredRoomAttachments.set(roomId, list);
65813
+ console.log(
65814
+ `[SecureChannel] room ${roomId.slice(0, 8)}: attachment ${String(info?.filename ?? "file")} deferred \u2014 caption addresses nobody, fetch on the next @-addressed turn (#1161)`
65815
+ );
65816
+ }
65817
+ /** Drain the room's deferred attachments that are still fresh (oldest first). */
65818
+ _takeDeferredRoomAttachments(roomId) {
65819
+ const list = this._deferredRoomAttachments.get(roomId);
65820
+ if (!list?.length) return [];
65821
+ this._deferredRoomAttachments.delete(roomId);
65822
+ const cutoff = Date.now() - _SecureChannel.DEFERRED_ROOM_ATTACHMENT_MS;
65823
+ return list.filter((d22) => d22.at >= cutoff).map((d22) => d22.info);
65824
+ }
65743
65825
  /** In-flight roster-refresh promises (per room) — dedup concurrent refreshes. */
65744
65826
  _roomRosterRefreshInFlight = /* @__PURE__ */ new Map();
65745
65827
  /** Dedup buffer for A2A message IDs (prevents double-delivery via direct + Redis) */
@@ -66835,7 +66917,7 @@ ${text}`;
66835
66917
  */
66836
66918
  sendActivitySpan(spanData) {
66837
66919
  if (!this._ws || this._ws.readyState !== WebSocket2.OPEN) return;
66838
- const pluginVersion = true ? "0.23.39" : "0.0.0-dev";
66920
+ const pluginVersion = true ? "0.23.40" : "0.0.0-dev";
66839
66921
  const agentName = this.config.agentName ?? "Agent";
66840
66922
  const resource = {
66841
66923
  "service.name": "agentvault-agent",
@@ -68773,7 +68855,7 @@ ${text}`;
68773
68855
  agentVersion: this.config.agentVersion ?? "0.0.0",
68774
68856
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
68775
68857
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
68776
- pluginVersion: true ? "0.23.39" : "0.0.0-dev"
68858
+ pluginVersion: true ? "0.23.40" : "0.0.0-dev"
68777
68859
  });
68778
68860
  this._telemetryReporter.startAutoFlush(3e4);
68779
68861
  }
@@ -69097,7 +69179,7 @@ ${text}`;
69097
69179
  agentVersion: this.config.agentVersion ?? "0.0.0",
69098
69180
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
69099
69181
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
69100
- pluginVersion: true ? "0.23.39" : "0.0.0-dev"
69182
+ pluginVersion: true ? "0.23.40" : "0.0.0-dev"
69101
69183
  });
69102
69184
  this._telemetryReporter.startAutoFlush(3e4);
69103
69185
  }
@@ -69411,6 +69493,7 @@ ${text}`;
69411
69493
  `[deliver] delivery_result=REJECTED group=${rejectedGroup || "unknown"} detail=${detail}`
69412
69494
  );
69413
69495
  console.error(`[SecureChannel] Server error: ${detail}`);
69496
+ this._noteCommitRefusal(data.data || data);
69414
69497
  await this._handleServerError(data.data || data);
69415
69498
  this.emit("error", new Error(`Server: ${detail}`));
69416
69499
  }
@@ -69712,7 +69795,7 @@ ${text}`;
69712
69795
  try {
69713
69796
  const parsed = JSON.parse(plaintext);
69714
69797
  messageType = parsed.type || "message";
69715
- messageText = parsed.text || plaintext;
69798
+ messageText = parsed.text ?? plaintext;
69716
69799
  if (parsed.attachment) {
69717
69800
  attachmentInfo = parsed.attachment;
69718
69801
  }
@@ -70464,7 +70547,7 @@ ${baseText}`;
70464
70547
  try {
70465
70548
  const parsed = JSON.parse(rawPlaintext);
70466
70549
  messageType = parsed.type || "message";
70467
- messageText = parsed.text || rawPlaintext;
70550
+ messageText = parsed.text ?? rawPlaintext;
70468
70551
  if (parsed.attachment) roomAttachment = parsed.attachment;
70469
70552
  } catch {
70470
70553
  messageType = "message";
@@ -70505,10 +70588,19 @@ ${baseText}`;
70505
70588
  await this._refreshRoomRoster(resolvedRoomId);
70506
70589
  }
70507
70590
  }
70508
- if (roomAttachment) {
70509
- messageText = await this._augmentWithAttachment(roomAttachment, messageText, resolvedRoomId);
70591
+ const addressed = parseMentions(messageText).length > 0;
70592
+ if (roomAttachment && !addressed) {
70593
+ this._deferRoomAttachment(resolvedRoomId, roomAttachment);
70510
70594
  } else {
70511
- messageText = this._withRecentRoomAttachmentNote(resolvedRoomId, messageText);
70595
+ const deferred = addressed ? this._takeDeferredRoomAttachments(resolvedRoomId) : [];
70596
+ for (const info of deferred) {
70597
+ messageText = await this._augmentWithAttachment(info, messageText, resolvedRoomId);
70598
+ }
70599
+ if (roomAttachment) {
70600
+ messageText = await this._augmentWithAttachment(roomAttachment, messageText, resolvedRoomId);
70601
+ } else if (deferred.length === 0) {
70602
+ messageText = this._withRecentRoomAttachmentNote(resolvedRoomId, messageText);
70603
+ }
70512
70604
  }
70513
70605
  const roomMembers = this._persisted?.rooms?.[resolvedRoomId]?.members ?? [];
70514
70606
  const senderMember = roomMembers.find((m22) => m22.deviceId === senderDeviceId);
@@ -70632,6 +70724,12 @@ ${baseText}`;
70632
70724
  const groupId = data.group_id;
70633
70725
  const epoch = typeof data.epoch === "number" ? data.epoch : 0;
70634
70726
  this._noteGroupEpoch(groupId, data.epoch);
70727
+ const held = this._commitInFlight.get(groupId);
70728
+ if (held) {
70729
+ held.frames.push(data);
70730
+ console.log(`[SecureChannel] MLS commit for ${groupId.slice(0, 8)} held (epoch=${epoch}) \u2014 our own commit is awaiting confirmation (#1184)`);
70731
+ return true;
70732
+ }
70635
70733
  const target = this._resolveGroupFamily(groupId);
70636
70734
  if (target) {
70637
70735
  const { managerKey: groupKey, label } = target;
@@ -70874,73 +70972,146 @@ ${baseText}`;
70874
70972
  return 0;
70875
70973
  }
70876
70974
  const snapshot = mlsGroup.exportState();
70877
- let parent2 = await this._readGroupHeadDigest(mlsGroupId);
70878
- const { commits, welcome } = await mlsGroup.reAdmitMembers(targets.map((t22) => t22.keyPackage));
70879
- let sentCommits = 0;
70880
- for (const c22 of commits) {
70881
- const ok2 = await this._sendFrameConfirmed(
70882
- {
70883
- event: "mls_commit",
70884
- data: {
70885
- group_id: mlsGroupId,
70886
- // The epoch this commit PRODUCED. After two commits the manager
70887
- // only knows the last one, which is why the result carries them.
70888
- epoch: Number(c22.epoch),
70889
- payload: Buffer.from(c22.commit).toString("hex"),
70890
- ...parent2 ? { parent_digest: parent2 } : {}
70891
- }
70892
- },
70893
- `${label} commit ${sentCommits + 1}/${commits.length}`
70894
- );
70895
- if (!ok2) break;
70896
- parent2 = this._commitDigest(c22.commit);
70897
- sentCommits++;
70898
- }
70899
- if (sentCommits === 0) {
70900
- mlsGroup.importState(snapshot);
70901
- console.warn(
70902
- `[SecureChannel] ${label}: commit was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, nothing fulfilled, requests stay pending`
70903
- );
70904
- return 0;
70905
- }
70906
- await saveMlsState(this.config.dataDir, mlsGroupId, JSON.stringify(mlsGroup.exportState()));
70907
- if (sentCommits < commits.length) {
70908
- console.warn(
70909
- `[SecureChannel] ${label}: only ${sentCommits}/${commits.length} commits reached the wire \u2014 requests stay PENDING for the next pull`
70910
- );
70911
- return 0;
70912
- }
70913
- if (!welcome) {
70975
+ const preHead = await this._readGroupHead(mlsGroupId);
70976
+ if (preHead.ok && preHead.epoch !== Number(mlsGroup.epoch)) {
70914
70977
  console.warn(
70915
- `[SecureChannel] ${label}: addMembers produced NO Welcome \u2014 ${targets.length} request(s) left pending rather than marked fulfilled`
70978
+ `[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`
70916
70979
  );
70917
70980
  return 0;
70918
70981
  }
70919
- let fulfilled = 0;
70920
- for (const t22 of targets) {
70921
- const sent = await this._sendFrameConfirmed(
70922
- {
70923
- event: "mls_welcome",
70924
- data: {
70925
- target_device_id: t22.deviceId,
70926
- group_id: mlsGroupId,
70927
- ...welcomeFields,
70928
- payload: Buffer.from(welcome).toString("hex")
70929
- }
70930
- },
70931
- `${label} welcome\u2192${t22.deviceId.slice(0, 8)}`
70932
- );
70933
- if (!sent) {
70982
+ let parent2 = preHead.ok ? preHead.digest : void 0;
70983
+ const inFlight = { frames: [], sent: [] };
70984
+ this._commitInFlight.set(mlsGroupId, inFlight);
70985
+ try {
70986
+ const { commits, welcome } = await mlsGroup.reAdmitMembers(targets.map((t22) => t22.keyPackage));
70987
+ let sentCommits = 0;
70988
+ let refusedAt = -1;
70989
+ let verdict = "confirmed";
70990
+ for (const c22 of commits) {
70991
+ const ours = this._commitDigest(c22.commit);
70992
+ inFlight.sent.push({
70993
+ epoch: Number(c22.epoch),
70994
+ digest: ours,
70995
+ verified: false,
70996
+ stateBefore: sentCommits === 0 ? snapshot : commits[sentCommits - 1].state
70997
+ });
70998
+ const ok2 = await this._sendFrameConfirmed(
70999
+ {
71000
+ event: "mls_commit",
71001
+ data: {
71002
+ group_id: mlsGroupId,
71003
+ // The epoch this commit PRODUCED. After two commits the manager
71004
+ // only knows the last one, which is why the result carries them.
71005
+ epoch: Number(c22.epoch),
71006
+ payload: Buffer.from(c22.commit).toString("hex"),
71007
+ ...parent2 ? { parent_digest: parent2 } : {}
71008
+ }
71009
+ },
71010
+ `${label} commit ${sentCommits + 1}/${commits.length}`
71011
+ );
71012
+ if (!ok2) {
71013
+ verdict = "unsent";
71014
+ inFlight.sent.pop();
71015
+ break;
71016
+ }
71017
+ verdict = await this._confirmCommitAtHead(mlsGroupId, Number(c22.epoch), ours, inFlight, label);
71018
+ if (verdict === "confirmed") {
71019
+ inFlight.sent[sentCommits].verified = true;
71020
+ } else if (verdict === "unverifiable") {
71021
+ console.warn(
71022
+ `[SecureChannel] ${label}: commit ${sentCommits + 1}/${commits.length} at epoch ${Number(c22.epoch)} could not be verified and was not refused \u2014 proceeding UNCHECKED (#1184)`
71023
+ );
71024
+ } else {
71025
+ refusedAt = sentCommits;
71026
+ break;
71027
+ }
71028
+ parent2 = ours;
71029
+ sentCommits++;
71030
+ }
71031
+ const cutFromRefusal = () => {
71032
+ const r22 = inFlight.refusal;
71033
+ if (r22 === void 0) return refusedAt;
71034
+ return refusedAt === -1 ? r22.from : Math.min(refusedAt, r22.from);
71035
+ };
71036
+ const rollBackTo = async (cut2, stage, persisted) => {
71037
+ const why = inFlight.refusal?.detail ?? verdict.toUpperCase();
71038
+ mlsGroup.importState(inFlight.sent[cut2].stateBefore);
71039
+ sentCommits = cut2;
70934
71040
  console.warn(
70935
- `[SecureChannel] ${label}: Welcome for ${t22.deviceId.slice(0, 8)} was NOT written \u2014 leaving the request PENDING so the next pull retries it`
71041
+ `[SecureChannel] ${label}: commit ${cut2 + 1}/${commits.length} ${stage} \u2014 "${why}" \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}` + (cut2 === 0 ? ", nothing" : ` (after commit ${cut2}), only that`) + ` persisted, ${targets.length} request(s) stay pending`
70936
71042
  );
70937
- continue;
71043
+ if (persisted) await saveMlsState(this.config.dataDir, mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71044
+ };
71045
+ let cut = cutFromRefusal();
71046
+ if (cut !== -1) {
71047
+ await rollBackTo(cut, "was refused by the server", false);
71048
+ if (sentCommits === 0) return 0;
70938
71049
  }
70939
- if (await this._postFulfilWelcome(mlsGroupId, t22.requestId, `${label} ${t22.deviceId.slice(0, 8)}`)) {
70940
- fulfilled++;
71050
+ if (sentCommits === 0) {
71051
+ mlsGroup.importState(snapshot);
71052
+ console.warn(
71053
+ `[SecureChannel] ${label}: commit was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, nothing fulfilled, requests stay pending`
71054
+ );
71055
+ return 0;
71056
+ }
71057
+ await saveMlsState(this.config.dataDir, mlsGroupId, JSON.stringify(mlsGroup.exportState()));
71058
+ cut = cutFromRefusal();
71059
+ if (cut !== -1 && cut < sentCommits) {
71060
+ await rollBackTo(cut, "was refused by the server after the window (during persist)", true);
71061
+ return 0;
71062
+ }
71063
+ if (sentCommits < commits.length) {
71064
+ console.warn(
71065
+ `[SecureChannel] ${label}: only ${sentCommits}/${commits.length} commits were confirmed \u2014 requests stay PENDING for the next pull`
71066
+ );
71067
+ return 0;
71068
+ }
71069
+ if (!welcome) {
71070
+ console.warn(
71071
+ `[SecureChannel] ${label}: addMembers produced NO Welcome \u2014 ${targets.length} request(s) left pending rather than marked fulfilled`
71072
+ );
71073
+ return 0;
71074
+ }
71075
+ let fulfilled = 0;
71076
+ for (const t22 of targets) {
71077
+ const sent = await this._sendFrameConfirmed(
71078
+ {
71079
+ event: "mls_welcome",
71080
+ data: {
71081
+ target_device_id: t22.deviceId,
71082
+ group_id: mlsGroupId,
71083
+ ...welcomeFields,
71084
+ payload: Buffer.from(welcome).toString("hex")
71085
+ }
71086
+ },
71087
+ `${label} welcome\u2192${t22.deviceId.slice(0, 8)}`
71088
+ );
71089
+ if (!sent) {
71090
+ console.warn(
71091
+ `[SecureChannel] ${label}: Welcome for ${t22.deviceId.slice(0, 8)} was NOT written \u2014 leaving the request PENDING so the next pull retries it`
71092
+ );
71093
+ continue;
71094
+ }
71095
+ cut = cutFromRefusal();
71096
+ if (cut !== -1 && cut < sentCommits) {
71097
+ await rollBackTo(cut, "was refused by the server after the window (during the Welcome)", true);
71098
+ return fulfilled;
71099
+ }
71100
+ if (await this._postFulfilWelcome(mlsGroupId, t22.requestId, `${label} ${t22.deviceId.slice(0, 8)}`)) {
71101
+ fulfilled++;
71102
+ }
71103
+ }
71104
+ return fulfilled;
71105
+ } finally {
71106
+ this._commitInFlight.delete(mlsGroupId);
71107
+ for (const frame of inFlight.frames) {
71108
+ try {
71109
+ await this._handleMlsCommit(frame);
71110
+ } catch (err) {
71111
+ console.error(`[SecureChannel] ${label}: replaying a held MLS commit failed:`, err);
71112
+ }
70941
71113
  }
70942
71114
  }
70943
- return fulfilled;
70944
71115
  }
70945
71116
  /**
70946
71117
  * Resolve an MLS group id to the family that owns it.
@@ -70987,24 +71158,237 @@ ${baseText}`;
70987
71158
  /**
70988
71159
  * #1177: the digest of the commit at the server's head, or undefined.
70989
71160
  *
70990
- * Undefined covers "no head yet", "older backend", AND "could not read" —
70991
- * deliberately the same value. The commit is sent either way: the server
70992
- * skips the parent check for an ABSENT field and refuses a MALFORMED one,
70993
- * so a read failure must degrade to "unchecked", never to "blocked" (a
70994
- * rescue that cannot run is the 2026-09-04 lockout) and never to `null`.
71161
+ * Undefined covers "no head yet" (a pruned group: epoch known, digest NULL —
71162
+ * 29 in production) AND "could not read" — deliberately the same value. The
71163
+ * commit is sent either way: the server skips the parent check for an
71164
+ * ABSENT field and refuses a MALFORMED one, so a read failure must degrade
71165
+ * to "unchecked", never to "blocked" (a rescue that cannot run is the
71166
+ * 2026-09-04 lockout) and never to `null`.
70995
71167
  */
70996
71168
  async _readGroupHeadDigest(groupId) {
71169
+ const head = await this._readGroupHead(groupId);
71170
+ return head.ok ? head.digest : void 0;
71171
+ }
71172
+ /**
71173
+ * #1184: the server's head — its `current_epoch` and the digest of the commit
71174
+ * that produced it.
71175
+ *
71176
+ * - `{ ok: true, epoch, digest? }` the server described its head. `digest`
71177
+ * is absent on a pruned group (NULL
71178
+ * `last_commit_digest`).
71179
+ * - `{ ok: false, why }` the read failed: a non-2xx (the 403
71180
+ * `assert_group_member` returns on an
71181
+ * EMPTY roster — 79 of 80 production
71182
+ * rooms — or a 5xx), a timeout, or a body
71183
+ * with no `current_epoch`. Callers may
71184
+ * retry; a failure is never a verdict.
71185
+ *
71186
+ * `current_epoch` is a required field of `MLSGroupResponse`, so "200 with
71187
+ * no head" is not a shape any deployed backend produces; it is folded into
71188
+ * `ok: false` rather than given a branch of its own (the first cut of #1184
71189
+ * had one, and it was the only branch the suite exercised).
71190
+ */
71191
+ async _readGroupHead(groupId) {
70997
71192
  try {
70998
71193
  const res = await fetch(`${this.config.apiUrl}/api/v1/mls/groups/${groupId}`, {
70999
- headers: { Authorization: `Bearer ${this._deviceJwt}` }
71194
+ headers: { Authorization: `Bearer ${this._deviceJwt}` },
71195
+ // The confirm loop holds `_deliveryPulling`; a black-holed read must
71196
+ // not hold it for undici's 300 s default. A timeout is a failed read.
71197
+ signal: AbortSignal.timeout(_SecureChannel.HEAD_READ_TIMEOUT_MS)
71000
71198
  });
71001
- if (!res.ok) return void 0;
71199
+ if (!res.ok) return { ok: false, why: `HTTP ${res.status}` };
71002
71200
  const head = await res.json();
71003
- const d22 = head?.last_commit_digest;
71004
- return typeof d22 === "string" && /^[0-9a-f]{64}$/.test(d22) ? d22 : void 0;
71005
- } catch {
71006
- return void 0;
71201
+ if (typeof head?.current_epoch !== "number") return { ok: false, why: "no current_epoch in body" };
71202
+ const d22 = head.last_commit_digest;
71203
+ return { ok: true, epoch: head.current_epoch, digest: typeof d22 === "string" && /^[0-9a-f]{64}$/.test(d22) ? d22 : void 0 };
71204
+ } catch (err) {
71205
+ return { ok: false, why: err instanceof Error ? err.name : String(err) };
71206
+ }
71207
+ }
71208
+ /**
71209
+ * #1184: after each read of the head, how long to wait before the next.
71210
+ * The web's schedule (`lib/mls-commit-confirm.ts`) plus one immediate read:
71211
+ * five reads, ~3.75 s, no resend — an MLS commit cannot be regenerated. The
71212
+ * immediate read catches the common case where the server stored the frame
71213
+ * before the GET lands. Instance-level so tests can run the decision logic
71214
+ * without the clock; an empty schedule still reads once (`_confirmCommitAtHead`).
71215
+ */
71216
+ _commitConfirmDelaysMs = [0, 250, 500, 1e3, 2e3];
71217
+ static HEAD_READ_TIMEOUT_MS = 5e3;
71218
+ /**
71219
+ * #1184: groups with a commit of OURS between "built" and "confirmed or rolled
71220
+ * back". Each record holds the `mls_commit` frames the socket delivered for
71221
+ * that group meanwhile — before the confirm loop that window was
71222
+ * microseconds; now it is up to ~3.75 s, and a commit applied to our
71223
+ * unconfirmed local state would be lost by the rollback (in memory) after
71224
+ * being persisted (on disk). Held frames are replayed, in order, once the
71225
+ * group is back on a real state. The record also carries the server's
71226
+ * REFUSAL, when one arrives on the socket (`_noteCommitRefusal`), and a
71227
+ * `wake` the confirm loop installs so a refusal ends its wait at once.
71228
+ */
71229
+ _commitInFlight = /* @__PURE__ */ new Map();
71230
+ /** #1184: a pull was requested while one was running — run once more after. */
71231
+ _deliveryPullRequested = false;
71232
+ /**
71233
+ * #1184: an `error` frame naming a group we have a commit in flight for, with
71234
+ * a `… commit rejected` detail, is the server's refusal of one of those
71235
+ * commits — every rejection the `mls_commit` WS handler sends (malformed
71236
+ * parent, PARENT_MISMATCH, EPOCH_CONFLICT, not-a-member, no-participants)
71237
+ * ends with those words and carries `group_id` (pinned by
71238
+ * `tests/test_1184_commit_reject_frame_contract.py`). It is sent on OUR
71239
+ * socket after the server processed OUR frame, so it is deterministic in a
71240
+ * way the head poll is not, and it is the only refusal signal on a group
71241
+ * whose head we cannot read (403).
71242
+ *
71243
+ * WHICH commit, and what else the frame proves (re-review of #1227):
71244
+ * - EPOCH_CONFLICT carries `expected_epoch` (the epoch we claimed to build
71245
+ * on) and `current_epoch` (the server's); PARENT_MISMATCH carries
71246
+ * `current_epoch` (the head, which equalled our claim or the epoch check
71247
+ * would have fired first) and `head_digest`. The refused commit is the
71248
+ * one built on that epoch. A frame naming an epoch none of our in-flight
71249
+ * commits claimed is a refusal of some EARLIER attempt — ignored.
71250
+ * - the server's `current_epoch` bounds our earlier commits too: any of
71251
+ * ours ABOVE it did not land.
71252
+ * - `head_digest` at `current_epoch` is our commit at that epoch → that one
71253
+ * positively LANDED; someone else's → ours at that epoch did not.
71254
+ * - the un-numbered shapes refuse all of ours alike: the cut is the first
71255
+ * commit the head poll has not positively confirmed.
71256
+ * Recorded as the index of the first commit shown not to hold; the fulfil
71257
+ * path honours it whenever it arrives. A frame for a group with nothing in
71258
+ * flight is somebody else's business.
71259
+ */
71260
+ _noteCommitRefusal(payload) {
71261
+ const groupId = typeof payload?.group_id === "string" ? payload.group_id : void 0;
71262
+ const detail = typeof payload?.detail === "string" ? payload.detail : "";
71263
+ if (!groupId || !detail.endsWith("commit rejected")) return;
71264
+ const inFlight = this._commitInFlight.get(groupId);
71265
+ if (!inFlight) return;
71266
+ const num = (v22) => typeof v22 === "number" && Number.isFinite(v22) ? v22 : void 0;
71267
+ const current = num(payload.current_epoch);
71268
+ const claimed = num(payload.expected_epoch) ?? current;
71269
+ const headDigest = typeof payload.head_digest === "string" ? payload.head_digest : void 0;
71270
+ const sent = inFlight.sent;
71271
+ const tag = `[SecureChannel] refusal for ${groupId.slice(0, 8)} ("${detail}")`;
71272
+ let from = -1;
71273
+ if (claimed !== void 0) {
71274
+ from = sent.findIndex((c22) => c22.epoch === claimed + 1);
71275
+ if (from === -1) {
71276
+ console.warn(`${tag} names epoch ${claimed + 1}, which no commit in flight claimed \u2014 an earlier attempt's; ignored`);
71277
+ return;
71278
+ }
71279
+ }
71280
+ if (current !== void 0) {
71281
+ const above = sent.findIndex((c22) => c22.epoch > current && !c22.verified);
71282
+ if (above !== -1 && (from === -1 || above < from)) from = above;
71283
+ }
71284
+ if (headDigest !== void 0 && current !== void 0) {
71285
+ const at = sent.findIndex((c22) => c22.epoch === current);
71286
+ if (at !== -1) {
71287
+ if (sent[at].digest === headDigest) {
71288
+ sent[at].verified = true;
71289
+ } else if (from === -1 || at < from) {
71290
+ from = at;
71291
+ }
71292
+ }
71293
+ }
71294
+ if (from === -1) from = sent.findIndex((c22) => !c22.verified);
71295
+ if (from === -1 || sent[from].verified) {
71296
+ console.warn(`${tag} contradicts a head read that showed our commit \u2014 stale; ignored`);
71297
+ return;
71298
+ }
71299
+ if (inFlight.refusal !== void 0 && inFlight.refusal.from <= from) return;
71300
+ inFlight.refusal = { detail, from };
71301
+ inFlight.wake?.();
71302
+ }
71303
+ /**
71304
+ * #1184: a commit is CONFIRMED when the server's head shows OUR digest at OUR
71305
+ * epoch — never when the socket took the bytes (#1015 covers only that). The
71306
+ * server sends no ack for a stored commit, so, like the web, we read the
71307
+ * head back; but it DOES send a refusal on the socket (`_noteCommitRefusal`),
71308
+ * and that is checked first, before every read and during every wait.
71309
+ *
71310
+ * confirmed head.epoch === ours && head.digest === ours
71311
+ * conflict the server refused ours on the socket, OR the head is at
71312
+ * our epoch with ANOTHER digest, OR already past us
71313
+ * unconfirmed the head was READ (at least once) but never reached our
71314
+ * epoch within the window — the server described its state
71315
+ * and ours is not in it
71316
+ * unverifiable the head could not be read on ANY try (403 on an empty
71317
+ * roster, an outage) and no refusal arrived — or it is at
71318
+ * our epoch but keeps no digest (a pruned group). Nothing
71319
+ * can be decided on; the caller proceeds UNCHECKED (#1177's
71320
+ * rule: a rescue that cannot run is the 2026-09-04 lockout)
71321
+ *
71322
+ * The first cut returned `unverifiable` only for a body with no
71323
+ * `current_epoch`, which no deployed backend produces, and rolled back on
71324
+ * every real read failure — the opposite of the rule it stated.
71325
+ */
71326
+ async _confirmCommitAtHead(groupId, epoch, ours, inFlight, label) {
71327
+ const refused = () => {
71328
+ if (inFlight.refusal === void 0) return void 0;
71329
+ console.warn(`[SecureChannel] ${label}: server refused our commit at epoch ${epoch} \u2014 "${inFlight.refusal.detail}"`);
71330
+ return "conflict";
71331
+ };
71332
+ let lastSeen;
71333
+ let described = false;
71334
+ let lastFailure = "";
71335
+ const delays = this._commitConfirmDelaysMs.length > 0 ? this._commitConfirmDelaysMs : [0];
71336
+ for (const delay of delays) {
71337
+ if (delay > 0) {
71338
+ await new Promise((resolve32) => {
71339
+ const timer = setTimeout(() => {
71340
+ inFlight.wake = void 0;
71341
+ resolve32();
71342
+ }, delay);
71343
+ inFlight.wake = () => {
71344
+ clearTimeout(timer);
71345
+ inFlight.wake = void 0;
71346
+ resolve32();
71347
+ };
71348
+ });
71349
+ }
71350
+ const early = refused();
71351
+ if (early) return early;
71352
+ const head = await this._readGroupHead(groupId);
71353
+ const duringRead = refused();
71354
+ if (duringRead) return duringRead;
71355
+ if (!head.ok) {
71356
+ lastFailure = head.why;
71357
+ continue;
71358
+ }
71359
+ described = true;
71360
+ lastSeen = head.epoch;
71361
+ if (head.epoch === epoch) {
71362
+ if (head.digest === ours) return "confirmed";
71363
+ if (head.digest === void 0) return "unverifiable";
71364
+ console.warn(
71365
+ `[SecureChannel] ${label}: head at epoch ${epoch} is NOT our commit (${head.digest.slice(0, 12)}\u2026 vs ours ${ours.slice(0, 12)}\u2026) \u2014 ours was refused`
71366
+ );
71367
+ return "conflict";
71368
+ }
71369
+ if (head.epoch > epoch) {
71370
+ console.warn(`[SecureChannel] ${label}: head already at epoch ${head.epoch}, past our ${epoch} \u2014 ours was refused`);
71371
+ return "conflict";
71372
+ }
71373
+ }
71374
+ const late2 = refused();
71375
+ if (late2) return late2;
71376
+ if (!described && !this._wsIsOpen()) {
71377
+ console.warn(
71378
+ `[SecureChannel] ${label}: the socket closed during the confirm window and the head could not be read \u2014 a refusal of commit at epoch ${epoch} may have been lost; treating as refused`
71379
+ );
71380
+ return "unconfirmed";
71381
+ }
71382
+ if (!described) {
71383
+ console.warn(
71384
+ `[SecureChannel] ${label}: could not read the head on any of ${delays.length} tries (last: ${lastFailure}) and the server sent no refusal \u2014 cannot verify commit at epoch ${epoch}`
71385
+ );
71386
+ return "unverifiable";
71007
71387
  }
71388
+ console.warn(
71389
+ `[SecureChannel] ${label}: commit at epoch ${epoch} never appeared at the head (last seen ${lastSeen}) \u2014 treating as refused`
71390
+ );
71391
+ return "unconfirmed";
71008
71392
  }
71009
71393
  /**
71010
71394
  * #1015: write one frame and report whether the socket took it.
@@ -71526,7 +71910,11 @@ ${baseText}`;
71526
71910
  * Called on WS connect, on mls_delivery ping, and every 30s heartbeat.
71527
71911
  */
71528
71912
  async _pullDeliveryQueue() {
71529
- if (!this._deviceId || !this._deviceJwt || this._deliveryPulling) return;
71913
+ if (!this._deviceId || !this._deviceJwt) return;
71914
+ if (this._deliveryPulling) {
71915
+ this._deliveryPullRequested = true;
71916
+ return;
71917
+ }
71530
71918
  this._deliveryPulling = true;
71531
71919
  try {
71532
71920
  const res = await fetch(
@@ -72088,6 +72476,10 @@ ${baseText}`;
72088
72476
  console.warn("[SecureChannel] Delivery pull error:", err);
72089
72477
  } finally {
72090
72478
  this._deliveryPulling = false;
72479
+ if (this._deliveryPullRequested) {
72480
+ this._deliveryPullRequested = false;
72481
+ void this._pullDeliveryQueue().catch((err) => console.warn("[SecureChannel] Coalesced delivery pull error:", err));
72482
+ }
72091
72483
  }
72092
72484
  }
72093
72485
  /**
@@ -72171,7 +72563,7 @@ ${baseText}`;
72171
72563
  try {
72172
72564
  const parsed = JSON.parse(plaintext);
72173
72565
  messageType = parsed.type || "message";
72174
- messageText = parsed.text || plaintext;
72566
+ messageText = parsed.text ?? plaintext;
72175
72567
  } catch {
72176
72568
  messageType = "message";
72177
72569
  messageText = plaintext;
@@ -72520,7 +72912,7 @@ ${baseText}`;
72520
72912
  try {
72521
72913
  const parsed = JSON.parse(plaintext);
72522
72914
  messageType = parsed.type || "message";
72523
- messageText = parsed.text || plaintext;
72915
+ messageText = parsed.text ?? plaintext;
72524
72916
  } catch {
72525
72917
  messageType = "message";
72526
72918
  messageText = plaintext;
@@ -72805,7 +73197,7 @@ ${baseText}`;
72805
73197
  try {
72806
73198
  const parsed = JSON.parse(plaintext);
72807
73199
  messageType = parsed.type || "message";
72808
- messageText = parsed.text || plaintext;
73200
+ messageText = parsed.text ?? plaintext;
72809
73201
  } catch {
72810
73202
  messageType = "message";
72811
73203
  messageText = plaintext;
@@ -73405,58 +73797,6 @@ var init_gateway_send = __esm2({
73405
73797
  init_openclaw_compat();
73406
73798
  }
73407
73799
  });
73408
- function parseMentions(text) {
73409
- const mentions = [];
73410
- const re22 = new RegExp(MENTION_RE.source, MENTION_RE.flags);
73411
- let match;
73412
- while ((match = re22.exec(text)) !== null) {
73413
- mentions.push(match[1].toLowerCase());
73414
- }
73415
- return mentions;
73416
- }
73417
- function resolveOwn(mention, names) {
73418
- if (names.has(mention)) return mention;
73419
- const parts = mention.split("-");
73420
- for (let i2 = parts.length - 1; i2 > 0; i2--) {
73421
- const candidate = parts.slice(0, i2).join("-");
73422
- if (names.has(candidate)) return candidate;
73423
- }
73424
- return null;
73425
- }
73426
- function owesRoomReply(plaintext, agentName, accountId, senderIsAgent, roomDisplayName, ownDisplayName, selfResolved = true) {
73427
- const mentions = parseMentions(plaintext);
73428
- if (mentions.length === 0) return false;
73429
- const ownNames = ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName);
73430
- if (mentions.some((m22) => resolveOwn(m22, ownNames) !== null)) return true;
73431
- if (mentions.some((m22) => resolveOwn(m22, BROADCAST_NAMES) !== null)) {
73432
- return senderIsAgent !== true;
73433
- }
73434
- if (!selfResolved) return true;
73435
- return false;
73436
- }
73437
- function ownRoomNames(agentName, accountId, roomDisplayName, ownDisplayName) {
73438
- const names = /* @__PURE__ */ new Set();
73439
- const add4 = (n22) => {
73440
- if (!n22) return;
73441
- const lower = n22.toLowerCase();
73442
- names.add(lower);
73443
- names.add(lower.split(/[\s(]/)[0]);
73444
- };
73445
- add4(agentName);
73446
- add4(accountId);
73447
- add4(roomDisplayName);
73448
- add4(ownDisplayName);
73449
- return names;
73450
- }
73451
- var MENTION_RE;
73452
- var BROADCAST_NAMES;
73453
- var init_room_protocol = __esm2({
73454
- "src/room-protocol.ts"() {
73455
- "use strict";
73456
- MENTION_RE = /@([\w-]+)/gi;
73457
- BROADCAST_NAMES = /* @__PURE__ */ new Set(["all", "everyone"]);
73458
- }
73459
- });
73460
73800
  var init_llm_response_parser = __esm2({
73461
73801
  "src/llm-response-parser.ts"() {
73462
73802
  "use strict";
@@ -99550,7 +99890,7 @@ var init_index = __esm2({
99550
99890
  await init_skill_telemetry();
99551
99891
  await init_policy_enforcer();
99552
99892
  init_room_protocol();
99553
- VERSION = true ? "0.23.39" : "0.0.0-dev";
99893
+ VERSION = true ? "0.23.40" : "0.0.0-dev";
99554
99894
  }
99555
99895
  });
99556
99896
  await init_index();
@@ -135966,7 +136306,7 @@ async function main() {
135966
136306
  "[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"
135967
136307
  );
135968
136308
  }
135969
- logLine(`[bridge] version: ${true ? "0.8.12" : "dev"}`);
136309
+ logLine(`[bridge] version: ${true ? "0.8.13" : "dev"}`);
135970
136310
  logLine(`[bridge] data dir: ${cfg.dataDir} (${cfg.dataDirSource})`);
135971
136311
  logLine(`[bridge] workspace: ${cfg.workspaceDir} \xB7 permissions: ${cfg.permissionMode} \xB7 enclave dir fenced`);
135972
136312
  if (cfg.armRoom) {
@@ -135998,7 +136338,7 @@ async function main() {
135998
136338
  // its default would render "@agentvault/agentvault@0.7.x" — the wrong
135999
136339
  // package name attached to the bridge's version number, which is worse
136000
136340
  // than either alone.
136001
- clientVersion: `@agentvault/claude-bridge@${true ? "0.8.12" : "dev"}`
136341
+ clientVersion: `@agentvault/claude-bridge@${true ? "0.8.13" : "dev"}`
136002
136342
  });
136003
136343
  const agentSystemPrompt = cfg.systemPrompt ?? `You are ${cfg.agentName}, an AI agent on AgentVault. You talk with your owner in 1:1 direct messages and collaborate with other agents in shared rooms. That is your identity \u2014 introduce yourself by that name and do not claim to be any other agent. To speak, call the say tool. In a 1:1 with your owner, reply to what they say. In a room you see every message \u2014 call say only when you have something worth adding, and otherwise stay silent. Keep messages concise.`;
136004
136344
  const deviceJwt = () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/claude-bridge",
3
- "version": "0.8.12",
3
+ "version": "0.8.13",
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",