@agentvault/agentvault 0.23.73 → 0.23.75

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
@@ -349,7 +349,7 @@ var init_room_protocol = __esm({
349
349
  MENTION_RE = /@([\w-]+)/gi;
350
350
  BROADCAST_NAMES = /* @__PURE__ */ new Set(["all", "everyone"]);
351
351
  PRIVATE_ROOM_TURN_NOTE = "(private room: just you and your person \u2014 every message here is for you; answer it)";
352
- GENERIC_AGENT_NAMES = /* @__PURE__ */ new Set(["default", "agent", "assistant", "bot", "main"]);
352
+ GENERIC_AGENT_NAMES = /* @__PURE__ */ new Set(["default", "agent", "assistant", "bot", "main", "unnamed", "unnamed agent"]);
353
353
  }
354
354
  });
355
355
 
@@ -24115,11 +24115,11 @@ var init_mls_kp_pool = __esm({
24115
24115
 
24116
24116
  // src/client-version.ts
24117
24117
  function ownIdentity() {
24118
- const v2 = true ? "0.23.73" : FALLBACK;
24118
+ const v2 = true ? "0.23.75" : FALLBACK;
24119
24119
  return `${PACKAGE}@${v2}`;
24120
24120
  }
24121
24121
  function buildSha() {
24122
- const raw = true ? "cb8786f" : "";
24122
+ const raw = true ? "c389222" : "";
24123
24123
  const cleaned = (raw ?? "").trim();
24124
24124
  return !cleaned || cleaned === "unknown" ? null : cleaned;
24125
24125
  }
@@ -26737,6 +26737,28 @@ var init_welcome_kp_backoff = __esm({
26737
26737
  }
26738
26738
  });
26739
26739
 
26740
+ // ../crypto/dist/invisible-text.js
26741
+ function replaceInvisible(value, replacement) {
26742
+ return value.replace(DEFAULT_IGNORABLE, (ch) => KEPT_IGNORABLE.has(ch.codePointAt(0)) ? ch : replacement).replace(OBJECT_REPLACEMENT, replacement).replace(CONTROL, (ch) => KEPT_CONTROL.has(ch.codePointAt(0)) ? ch : replacement);
26743
+ }
26744
+ function drawsNothing(value) {
26745
+ return value.replace(INVISIBLE2, "").split(BRAILLE_BLANK).join("").length === 0;
26746
+ }
26747
+ var ZWJ, DEFAULT_IGNORABLE, KEPT_IGNORABLE, OBJECT_REPLACEMENT, CONTROL, KEPT_CONTROL, INVISIBLE2, BRAILLE_BLANK;
26748
+ var init_invisible_text = __esm({
26749
+ "../crypto/dist/invisible-text.js"() {
26750
+ "use strict";
26751
+ ZWJ = 8205;
26752
+ DEFAULT_IGNORABLE = new RegExp("\\p{Default_Ignorable_Code_Point}", "gu");
26753
+ KEPT_IGNORABLE = /* @__PURE__ */ new Set([8204, ZWJ, 65039]);
26754
+ OBJECT_REPLACEMENT = new RegExp(String.fromCodePoint(65532), "g");
26755
+ CONTROL = new RegExp("\\p{Cc}", "gu");
26756
+ KEPT_CONTROL = /* @__PURE__ */ new Set([9, 10, 13]);
26757
+ INVISIBLE2 = /[\s\p{Cf}\p{Default_Ignorable_Code_Point}]/gu;
26758
+ BRAILLE_BLANK = String.fromCodePoint(10240);
26759
+ }
26760
+ });
26761
+
26740
26762
  // src/dm-group-pins.ts
26741
26763
  function isUuid(v2) {
26742
26764
  return typeof v2 === "string" && UUID_RE3.test(v2);
@@ -26876,8 +26898,8 @@ function drOwnerClaimNotice(label) {
26876
26898
  }
26877
26899
  function sanitizeDeviceLabel(name) {
26878
26900
  if (typeof name !== "string") return null;
26879
- const clean8 = name.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, " ").replace(/\s+/g, " ").trim();
26880
- if (clean8 === "") return null;
26901
+ const clean8 = replaceInvisible(name, " ").replace(/\s+/g, " ").trim();
26902
+ if (clean8 === "" || drawsNothing(clean8)) return null;
26881
26903
  const points = Array.from(clean8);
26882
26904
  return points.length > 64 ? `${points.slice(0, 63).join("")}\u2026` : clean8;
26883
26905
  }
@@ -26886,6 +26908,7 @@ var init_dm_group_pins = __esm({
26886
26908
  "src/dm-group-pins.ts"() {
26887
26909
  "use strict";
26888
26910
  init_mls_sender_binding();
26911
+ init_invisible_text();
26889
26912
  UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
26890
26913
  CANONICAL_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
26891
26914
  WELCOME_ROUTING_FIELDS = [
@@ -29880,6 +29903,60 @@ function anySignal(signals) {
29880
29903
  }
29881
29904
  return c2.signal;
29882
29905
  }
29906
+ function textCutEnd(value, budget) {
29907
+ const Segmenter = Intl.Segmenter;
29908
+ if (typeof Segmenter === "function") {
29909
+ const segmenter = new Segmenter(
29910
+ void 0,
29911
+ { granularity: "grapheme" }
29912
+ );
29913
+ let end2 = 0;
29914
+ for (const { segment, index } of segmenter.segment(value.slice(0, budget + 64))) {
29915
+ if (index + segment.length > budget) break;
29916
+ end2 = index + segment.length;
29917
+ }
29918
+ return end2;
29919
+ }
29920
+ let end = budget;
29921
+ const last = value.charCodeAt(end - 1);
29922
+ if (last >= 55296 && last <= 56319) end -= 1;
29923
+ for (; ; ) {
29924
+ const before = end;
29925
+ while (end > 0 && value.charCodeAt(end - 1) === 8205) end -= 1;
29926
+ let regional = 0;
29927
+ for (let i2 = end; i2 >= 2; i2 -= 2) {
29928
+ const c2 = value.codePointAt(i2 - 2);
29929
+ if (c2 < 127462 || c2 > 127487) break;
29930
+ regional++;
29931
+ }
29932
+ if (regional % 2 === 1) end -= 2;
29933
+ if (end === before) return end;
29934
+ }
29935
+ }
29936
+ function capTextPart(value, max) {
29937
+ if (value.length <= max) return value;
29938
+ return `${value.slice(0, textCutEnd(value, max - 1))}\u2026`;
29939
+ }
29940
+ function statusAlertTextLine(alert) {
29941
+ const severity = STATUS_ALERT_SEVERITIES.has(alert.severity) ? String(alert.severity) : "info";
29942
+ const title = capTextPart(String(alert.title), STATUS_ALERT_TEXT_LIMITS.title);
29943
+ const message = capTextPart(String(alert.message), STATUS_ALERT_TEXT_LIMITS.message);
29944
+ return `[${severity.toUpperCase()}] ${title}: ${message}`;
29945
+ }
29946
+ function statusAlertEnvelope(alert, timestamp) {
29947
+ const envelope = {
29948
+ type: "status_alert",
29949
+ title: alert.title,
29950
+ message: alert.message,
29951
+ severity: alert.severity,
29952
+ timestamp
29953
+ };
29954
+ if (alert.detail !== void 0) envelope.detail = alert.detail;
29955
+ if (alert.detailFormat !== void 0) envelope.detail_format = alert.detailFormat;
29956
+ if (alert.category !== void 0) envelope.category = alert.category;
29957
+ envelope.text = statusAlertTextLine(alert);
29958
+ return envelope;
29959
+ }
29883
29960
  function outboundDedupeKey(resolved, content, options) {
29884
29961
  if (!OUTBOUND_DEDUPE_TYPES.has(content.type)) return null;
29885
29962
  const base = [resolved.kind, resolved.id ?? "owner", options?.conversationId ?? "", options?.topicId ?? ""];
@@ -30020,7 +30097,7 @@ function historyErrorReason(error2) {
30020
30097
  }
30021
30098
  return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? `${name} (status ${status})` : name;
30022
30099
  }
30023
- var ROOM_AGENT_TYPES, CREDENTIAL_MESSAGE_TYPES, CATCHUP_MESSAGE_TYPES, ROOM_PROTOCOL_TYPES, POLL_INTERVAL_MS, RECONNECT_BASE_MS, UUID_RE5, KpIdentityRefused, RECONNECT_MAX_MS, PENDING_POLL_INTERVAL_MS, PENDING_POLL_SILENCE_MS, HISTORY_RESTORE_TIMEOUT_MS2, ROOM_ROSTER_REFRESH_TIMEOUT_MS, ROOM_ROSTER_OWNER_MAX_AGE_MS, TimedSet, HISTORY_UPLOAD_TIMEOUT_MS, CANONICAL_TIMESTAMP_RE, OUTBOUND_DEDUPE_WINDOW_MS, OUTBOUND_DEDUPE_MAX_SUPPRESS_MS, OUTBOUND_DEDUPE_MAX, OUTBOUND_DEDUPE_TYPES, RETRY_CANDIDATE_TTL_MS, RETRY_CANDIDATE_MAX, _turnConversation, _turnTokenStore, _drTurnStore, PERSON_INVOLVED_WINDOW_MS, ATTESTED_INBOUND_MAX, UNMAPPED_RECONCILE_COOLDOWN_MS, TOPIC_ID_RE, ROOM_FULFIL_COOLDOWN_MS, SecureChannel;
30100
+ var ROOM_AGENT_TYPES, STATUS_ALERT_TEXT_LIMITS, STATUS_ALERT_SEVERITIES, CREDENTIAL_MESSAGE_TYPES, CATCHUP_MESSAGE_TYPES, ROOM_PROTOCOL_TYPES, POLL_INTERVAL_MS, RECONNECT_BASE_MS, UUID_RE5, KpIdentityRefused, RECONNECT_MAX_MS, PENDING_POLL_INTERVAL_MS, PENDING_POLL_SILENCE_MS, HISTORY_RESTORE_TIMEOUT_MS2, ROOM_ROSTER_REFRESH_TIMEOUT_MS, ROOM_ROSTER_OWNER_MAX_AGE_MS, TimedSet, HISTORY_UPLOAD_TIMEOUT_MS, CANONICAL_TIMESTAMP_RE, OUTBOUND_DEDUPE_WINDOW_MS, OUTBOUND_DEDUPE_MAX_SUPPRESS_MS, OUTBOUND_DEDUPE_MAX, OUTBOUND_DEDUPE_TYPES, RETRY_CANDIDATE_TTL_MS, RETRY_CANDIDATE_MAX, _turnConversation, _turnTokenStore, _drTurnStore, PERSON_INVOLVED_WINDOW_MS, ATTESTED_INBOUND_MAX, UNMAPPED_RECONCILE_COOLDOWN_MS, TOPIC_ID_RE, ROOM_FULFIL_COOLDOWN_MS, SecureChannel;
30024
30101
  var init_channel = __esm({
30025
30102
  "src/channel.ts"() {
30026
30103
  "use strict";
@@ -30072,6 +30149,8 @@ var init_channel = __esm({
30072
30149
  "decision_response",
30073
30150
  "artifact_share"
30074
30151
  ]);
30152
+ STATUS_ALERT_TEXT_LIMITS = { title: 120, message: 2e3 };
30153
+ STATUS_ALERT_SEVERITIES = /* @__PURE__ */ new Set(["info", "warning", "error", "critical"]);
30075
30154
  CREDENTIAL_MESSAGE_TYPES = /* @__PURE__ */ new Set([
30076
30155
  "credential_grant",
30077
30156
  "credential_revoke",
@@ -30257,6 +30336,56 @@ var init_channel = __esm({
30257
30336
  /** #1094: never let one slow report hold up the rest. */
30258
30337
  static _KEY_PROOF_FETCH_TIMEOUT_MS = 1e4;
30259
30338
  _keyProofTimer = null;
30339
+ /**
30340
+ * #1889: a group the server refuses a proof for — 404 "MLS group not found",
30341
+ * or 403 "Not a member of this group" outside the join grace — is not asked
30342
+ * again for this long (Hermes's #1543 window). A Welcome into the group, or a
30343
+ * `room_joined` for its room, ends the pause at once.
30344
+ */
30345
+ static _KEY_PROOF_PAUSE_MS = 24 * 60 * 60 * 1e3;
30346
+ /**
30347
+ * #1889 review: a 403 pauses for ONE hour, not a day. A live member whose
30348
+ * roster entry lags still answers 403, and a paused proof reads as `stale`
30349
+ * to the lockout detector, which then cannot repair it on epoch_behind. An
30350
+ * hour bounds that while still cutting a dead room's 144 posts a day to 24.
30351
+ */
30352
+ static _KEY_PROOF_403_PAUSE_MS = 60 * 60 * 1e3;
30353
+ /** When this process started: the join grace also covers a join made just before a restart. */
30354
+ _processStartedAt = Date.now();
30355
+ /**
30356
+ * #1889 review: one room's state is changed by one task at a time. The
30357
+ * reconcile's drop, `joinRoom` and a room Welcome's install all run under
30358
+ * the room's lock, so a re-admit can never be deleted half-way through.
30359
+ */
30360
+ _roomLocks = /* @__PURE__ */ new Map();
30361
+ /**
30362
+ * #1889 review: `POST /mls/rooms/{id}/init` runs while `joinRoom` holds the
30363
+ * room's lock, and a delivery-queue Welcome for that room waits on the lock
30364
+ * (the pull is serial). Without a bound, a hung init stalled every group's
30365
+ * delivery for Node's 300 s default. It is the only network call made under
30366
+ * a room lock. Static and writable so a test can shorten it.
30367
+ */
30368
+ static ROOM_INIT_FETCH_TIMEOUT_MS = 1e4;
30369
+ /**
30370
+ * #1889 / #1542: right after a join the server roster can lag this device,
30371
+ * and that lag answers 403 too. Inside this window a 403 pauses nothing: a
30372
+ * paused proof would read as never_proved.
30373
+ */
30374
+ static _KEY_PROOF_JOIN_GRACE_MS = 30 * 60 * 1e3;
30375
+ /** The backend's detail for a device outside the roster (mls.py report_key_proof). */
30376
+ static KEY_PROOF_NOT_A_MEMBER_DETAIL = "Not a member of this group";
30377
+ /** #1889: group id -> ms until which its key proofs are paused. */
30378
+ _keyProofPausedUntil = /* @__PURE__ */ new Map();
30379
+ /** #1889: group id -> ms this device last joined it from a Welcome. */
30380
+ _mlsGroupJoinedAt = /* @__PURE__ */ new Map();
30381
+ /**
30382
+ * #1889: room id -> how many times `joinRoom` ran for it. A room reconcile
30383
+ * prunes nothing whose count moved while its GET was in flight: the
30384
+ * response predates that (re)join.
30385
+ */
30386
+ _roomJoinGen = /* @__PURE__ */ new Map();
30387
+ /** #1889: the room reconcile in flight, so overlapping asks share one GET. */
30388
+ _roomReconcileInFlight = null;
30260
30389
  _a2aReconcileTimer = null;
30261
30390
  _deliveryPulling = false;
30262
30391
  _drDeliveryPulling = false;
@@ -33428,7 +33557,7 @@ ${text}`,
33428
33557
  */
33429
33558
  sendActivitySpan(spanData) {
33430
33559
  if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return;
33431
- const pluginVersion = true ? "0.23.73" : "0.0.0-dev";
33560
+ const pluginVersion = true ? "0.23.75" : "0.0.0-dev";
33432
33561
  const agentName = this.config.agentName ?? "Agent";
33433
33562
  const resource = {
33434
33563
  "service.name": "agentvault-agent",
@@ -33739,10 +33868,19 @@ ${text}`,
33739
33868
  * Encryption is handled by MLS group operations, not per-member DR sessions.
33740
33869
  */
33741
33870
  async joinRoom(roomData) {
33871
+ if (!this._persisted) {
33872
+ throw new Error("Channel not initialized");
33873
+ }
33874
+ this._roomJoinGen.set(roomData.roomId, (this._roomJoinGen.get(roomData.roomId) ?? 0) + 1);
33875
+ return this._withRoomLock(roomData.roomId, () => this._joinRoomLocked(roomData));
33876
+ }
33877
+ async _joinRoomLocked(roomData) {
33742
33878
  if (!this._persisted) {
33743
33879
  throw new Error("Channel not initialized");
33744
33880
  }
33745
33881
  this._roomRosterRefreshed.delete(roomData.roomId);
33882
+ const priorGroup = this._persisted?.rooms?.[roomData.roomId]?.mlsGroupId;
33883
+ if (priorGroup) this._keyProofPausedUntil.delete(priorGroup);
33746
33884
  this._applyRoomAudience(roomData.roomId, roomData.audience);
33747
33885
  await libsodium_wrappers_default.ready;
33748
33886
  const myDeviceId = this._deviceId;
@@ -33798,7 +33936,11 @@ ${text}`,
33798
33936
  },
33799
33937
  body: JSON.stringify({
33800
33938
  member_device_ids: roomData.members.map((m2) => m2.deviceId)
33801
- })
33939
+ }),
33940
+ // #1889 review: bounded, because this runs under the room lock. A
33941
+ // timeout lands in the catch below: no group id is stored, so the
33942
+ // next room_joined (or the owner's Welcome) still completes the room.
33943
+ signal: AbortSignal.timeout(_SecureChannel.ROOM_INIT_FETCH_TIMEOUT_MS)
33802
33944
  });
33803
33945
  if (initRes.ok) {
33804
33946
  const groupData = await initRes.json();
@@ -33942,10 +34084,41 @@ ${text}`,
33942
34084
  * Fail-safe: a failed fetch / non-ok / non-array response prunes NOTHING, so a
33943
34085
  * transient error can never over-prune a live room.
33944
34086
  */
33945
- async _reconcileRoomsWithServer() {
34087
+ /** Run `fn` holding room `roomId`'s lock (FIFO). */
34088
+ async _withRoomLock(roomId, fn) {
34089
+ const prev = this._roomLocks.get(roomId) ?? Promise.resolve();
34090
+ let release;
34091
+ const mine = new Promise((resolve7) => {
34092
+ release = resolve7;
34093
+ });
34094
+ const tail = prev.then(() => mine);
34095
+ this._roomLocks.set(roomId, tail);
34096
+ await prev;
34097
+ try {
34098
+ return await fn();
34099
+ } finally {
34100
+ release();
34101
+ if (this._roomLocks.get(roomId) === tail) this._roomLocks.delete(roomId);
34102
+ }
34103
+ }
34104
+ _reconcileRoomsWithServer() {
34105
+ if (this._roomReconcileInFlight) return this._roomReconcileInFlight;
34106
+ const run = this._reconcileRoomsOnce().finally(() => {
34107
+ this._roomReconcileInFlight = null;
34108
+ });
34109
+ this._roomReconcileInFlight = run;
34110
+ return run;
34111
+ }
34112
+ async _reconcileRoomsOnce() {
33946
34113
  const local = this._persisted?.rooms;
33947
34114
  if (!local || Object.keys(local).length === 0) return;
33948
34115
  if (!this._deviceJwt) return;
34116
+ const before = new Map(
34117
+ Object.keys(local).map((rid) => [
34118
+ rid,
34119
+ { mgr: this._mlsGroups.get(rid), gen: this._roomJoinGen.get(rid) ?? 0 }
34120
+ ])
34121
+ );
33949
34122
  let activeIds;
33950
34123
  try {
33951
34124
  const res = await fetch(`${this.config.apiUrl}/api/v1/rooms`, {
@@ -33954,38 +34127,59 @@ ${text}`,
33954
34127
  if (!res.ok) return;
33955
34128
  const list = await res.json();
33956
34129
  if (!Array.isArray(list)) return;
33957
- activeIds = new Set(
33958
- list.map((r2) => r2?.id).filter((id) => !!id)
33959
- );
34130
+ if (!list.every((r2) => !!r2 && typeof r2 === "object" && typeof r2.id === "string" && r2.id)) {
34131
+ console.warn("[SecureChannel] room reconcile skipped: malformed item in GET /rooms (pruning nothing)");
34132
+ return;
34133
+ }
34134
+ activeIds = new Set(list.map((r2) => r2.id));
33960
34135
  } catch (err) {
33961
34136
  console.warn(
33962
34137
  `[SecureChannel] room reconcile skipped (fetch failed, pruning nothing): ${err instanceof Error ? err.message : String(err)}`
33963
34138
  );
33964
34139
  return;
33965
34140
  }
33966
- const stale = Object.keys(local).filter((rid) => !activeIds.has(rid));
34141
+ for (const rid of activeIds) {
34142
+ const gid = local[rid]?.mlsGroupId;
34143
+ if (gid) this._keyProofPausedUntil.delete(gid);
34144
+ }
34145
+ const stale = Object.keys(local).filter((rid) => {
34146
+ if (activeIds.has(rid)) return false;
34147
+ const snap = before.get(rid);
34148
+ if (!snap) return false;
34149
+ return this._mlsGroups.get(rid) === snap.mgr && (this._roomJoinGen.get(rid) ?? 0) === snap.gen;
34150
+ });
33967
34151
  if (stale.length === 0) return;
34152
+ const pruned = [];
33968
34153
  for (const rid of stale) {
33969
- const room = local[rid];
33970
- if (room?.mlsGroupId) {
33971
- try {
33972
- await deleteMlsState(this.config.dataDir, room.mlsGroupId);
33973
- } catch {
34154
+ await this._withRoomLock(rid, async () => {
34155
+ const snap = before.get(rid);
34156
+ const room = local[rid];
34157
+ if (!snap || !room) return;
34158
+ if (this._mlsGroups.get(rid) !== snap.mgr || (this._roomJoinGen.get(rid) ?? 0) !== snap.gen) return;
34159
+ this._mlsGroups.delete(rid);
34160
+ for (const convId of room.conversationIds ?? []) {
34161
+ this._sessions.delete(convId);
34162
+ if (this._persisted?.sessions) delete this._persisted.sessions[convId];
33974
34163
  }
33975
- }
33976
- this._mlsGroups.delete(rid);
33977
- for (const convId of room?.conversationIds ?? []) {
33978
- this._sessions.delete(convId);
33979
- if (this._persisted?.sessions) delete this._persisted.sessions[convId];
33980
- }
33981
- delete local[rid];
33982
- this._retireRoomFolder(rid);
34164
+ delete local[rid];
34165
+ pruned.push(rid);
34166
+ if (room.mlsGroupId) {
34167
+ this._keyProofPausedUntil.delete(room.mlsGroupId);
34168
+ this._mlsGroupJoinedAt.delete(room.mlsGroupId);
34169
+ try {
34170
+ await deleteMlsState(this.config.dataDir, room.mlsGroupId);
34171
+ } catch {
34172
+ }
34173
+ }
34174
+ this._retireRoomFolder(rid);
34175
+ });
33983
34176
  }
34177
+ if (pruned.length === 0) return;
33984
34178
  await this._persistState();
33985
34179
  console.log(
33986
- `[SecureChannel] Room reconcile: pruned ${stale.length} disbanded/left room(s) from local state (${stale.map((r2) => r2.slice(0, 8)).join(", ")})`
34180
+ `[SecureChannel] Room reconcile: pruned ${pruned.length} disbanded/left room(s) from local state (${pruned.map((r2) => r2.slice(0, 8)).join(", ")})`
33987
34181
  );
33988
- this.emit("rooms_reconciled", { pruned: stale });
34182
+ this.emit("rooms_reconciled", { pruned });
33989
34183
  }
33990
34184
  /**
33991
34185
  * #629 — quarantine MLS state for groups this device is no longer in.
@@ -34450,19 +34644,8 @@ ${text}`,
34450
34644
  }
34451
34645
  async sendStatusAlert(alert, routing) {
34452
34646
  const priority = alert.severity === "error" || alert.severity === "critical" ? "high" : "normal";
34453
- const envelope = {
34454
- type: "status_alert",
34455
- title: alert.title,
34456
- message: alert.message,
34457
- severity: alert.severity,
34458
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
34459
- };
34460
- if (alert.detail !== void 0) envelope.detail = alert.detail;
34461
- if (alert.detailFormat !== void 0) envelope.detail_format = alert.detailFormat;
34462
- if (alert.category !== void 0) envelope.category = alert.category;
34463
- envelope.text = `[${String(alert.severity).toUpperCase()}] ${alert.title}: ${alert.message}`;
34464
34647
  await this.send(
34465
- JSON.stringify(envelope),
34648
+ JSON.stringify(statusAlertEnvelope(alert, (/* @__PURE__ */ new Date()).toISOString())),
34466
34649
  {
34467
34650
  conversationId: routing?.conversationId,
34468
34651
  audience: routing?.audience,
@@ -34679,16 +34862,7 @@ ${text}`,
34679
34862
  decisionId = await this.sendDecisionRequest(content.request, ownerRouting);
34680
34863
  } else if (content.type === "status_alert") {
34681
34864
  if (resolved.kind === "room") {
34682
- const envelope = {
34683
- title: content.alert.title,
34684
- message: content.alert.message,
34685
- severity: content.alert.severity,
34686
- timestamp: ts
34687
- };
34688
- if (content.alert.detail !== void 0) envelope.detail = content.alert.detail;
34689
- if (content.alert.detailFormat !== void 0) envelope.detail_format = content.alert.detailFormat;
34690
- if (content.alert.category !== void 0) envelope.category = content.alert.category;
34691
- await this.sendToRoom(resolved.id, JSON.stringify(envelope), {
34865
+ await this.sendToRoom(resolved.id, JSON.stringify(statusAlertEnvelope(content.alert, ts)), {
34692
34866
  messageType: "status_alert",
34693
34867
  priority: content.alert.severity === "error" || content.alert.severity === "critical" ? "high" : "normal",
34694
34868
  metadata: { severity: content.alert.severity }
@@ -39779,13 +39953,17 @@ ${baseText}`;
39779
39953
  const jwt = this._deviceJwt;
39780
39954
  if (!deviceId || !jwt) return;
39781
39955
  const best = /* @__PURE__ */ new Map();
39782
- for (const mgr of this._mlsGroups.values()) {
39956
+ const roomGroups = /* @__PURE__ */ new Set();
39957
+ const now = Date.now();
39958
+ for (const [key, mgr] of this._mlsGroups.entries()) {
39783
39959
  try {
39784
39960
  if (!mgr.isInitialized) continue;
39785
39961
  const epoch = Number(mgr.epoch);
39786
39962
  if (epoch <= 0) continue;
39787
39963
  const groupId = _SecureChannel._mlsGroupIdString(mgr.groupId);
39788
39964
  if (!groupId) continue;
39965
+ if (now < (this._keyProofPausedUntil.get(groupId) ?? 0)) continue;
39966
+ if (this._persisted?.rooms?.[key]) roomGroups.add(groupId);
39789
39967
  const prev = best.get(groupId);
39790
39968
  if (prev && epoch <= prev.epoch) continue;
39791
39969
  best.set(groupId, { epoch, authenticator: Buffer.from(mgr.epochAuthenticator).toString("hex") });
@@ -39793,6 +39971,7 @@ ${baseText}`;
39793
39971
  continue;
39794
39972
  }
39795
39973
  }
39974
+ let askRooms = false;
39796
39975
  for (const [groupId, { epoch, authenticator }] of best) {
39797
39976
  try {
39798
39977
  const res = await fetch(`${this.config.apiUrl}/api/v1/mls/groups/${groupId}/key-proof`, {
@@ -39801,11 +39980,34 @@ ${baseText}`;
39801
39980
  body: JSON.stringify({ device_id: deviceId, epoch, authenticator }),
39802
39981
  signal: AbortSignal.timeout(_SecureChannel._KEY_PROOF_FETCH_TIMEOUT_MS)
39803
39982
  });
39804
- if (!res.ok) console.debug(`[key-proof] ${groupId.slice(0, 8)}: HTTP ${res.status}`);
39983
+ if (res.ok) continue;
39984
+ const detail = res.status === 403 ? await this._errorDetail(res) : null;
39985
+ if (res.status === 404 || detail === _SecureChannel.KEY_PROOF_NOT_A_MEMBER_DETAIL) {
39986
+ if (roomGroups.has(groupId)) askRooms = true;
39987
+ const graceFrom = Math.max(this._mlsGroupJoinedAt.get(groupId) ?? 0, this._processStartedAt);
39988
+ if (res.status === 403 && Date.now() - graceFrom < _SecureChannel._KEY_PROOF_JOIN_GRACE_MS) {
39989
+ console.debug(`[key-proof] ${groupId.slice(0, 8)}: HTTP 403 within the join grace (roster lag)`);
39990
+ continue;
39991
+ }
39992
+ const pauseMs = res.status === 404 ? _SecureChannel._KEY_PROOF_PAUSE_MS : _SecureChannel._KEY_PROOF_403_PAUSE_MS;
39993
+ this._keyProofPausedUntil.set(groupId, Date.now() + pauseMs);
39994
+ console.log(
39995
+ `[key-proof] ${groupId.slice(0, 8)}: HTTP ${res.status} (${res.status === 404 ? "group gone" : "not a member"}) \u2014 pausing its proofs for ${pauseMs / 36e5}h (#1889)`
39996
+ );
39997
+ continue;
39998
+ }
39999
+ console.debug(`[key-proof] ${groupId.slice(0, 8)}: HTTP ${res.status}`);
39805
40000
  } catch (err) {
39806
40001
  console.debug(`[key-proof] ${groupId.slice(0, 8)}: report failed (non-critical):`, err);
39807
40002
  }
39808
40003
  }
40004
+ if (askRooms) {
40005
+ try {
40006
+ await this._reconcileRoomsWithServer();
40007
+ } catch (err) {
40008
+ console.warn(`[key-proof] room reconcile after a refusal failed (ignored): ${err instanceof Error ? err.message : String(err)}`);
40009
+ }
40010
+ }
39809
40011
  }
39810
40012
  /**
39811
40013
  * The wire MLS group id as a UUID string, or null. Every founder today —
@@ -40098,18 +40300,16 @@ ${baseText}`;
40098
40300
  * limiter (per-conversation and global caps). The plaintext carries
40099
40301
  * `type: "status_alert"`, so no agent in the room treats it as a turn
40100
40302
  * (`status_alert` is not in ROOM_AGENT_TYPES). Fire-and-forget; never throws.
40303
+ * #1867: built by `statusAlertEnvelope`, like every other plugin alert, so
40304
+ * it carries the `text` line a room tab older than #1860 shows.
40101
40305
  */
40102
40306
  _sendRoomSecurityNotice(noticeKey, roomId, title, text) {
40103
40307
  try {
40104
40308
  if (!this._securityNoticeLimiter.allow(noticeKey)) return;
40105
- const envelope = JSON.stringify({
40106
- type: "status_alert",
40107
- title,
40108
- message: text(),
40109
- severity: "warning",
40110
- category: "security",
40111
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
40112
- });
40309
+ const envelope = JSON.stringify(statusAlertEnvelope(
40310
+ { title, message: text(), severity: "warning", category: "security" },
40311
+ (/* @__PURE__ */ new Date()).toISOString()
40312
+ ));
40113
40313
  Promise.resolve().then(() => this.sendToRoom(roomId, envelope, { messageType: "status_alert" })).catch((err) => {
40114
40314
  console.warn(`[SecureChannel] #1800 security notice for room ${logId(roomId)} was not sent:`, err);
40115
40315
  });
@@ -40142,7 +40342,7 @@ ${baseText}`;
40142
40342
  agentVersion: this.config.agentVersion ?? "0.0.0",
40143
40343
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
40144
40344
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
40145
- pluginVersion: true ? "0.23.73" : "0.0.0-dev"
40345
+ pluginVersion: true ? "0.23.75" : "0.0.0-dev"
40146
40346
  });
40147
40347
  this._telemetryReporter.startAutoFlush(3e4);
40148
40348
  }
@@ -40341,6 +40541,10 @@ ${baseText}`;
40341
40541
  return;
40342
40542
  }
40343
40543
  const mgr = joined.mgr;
40544
+ if (groupId) {
40545
+ this._keyProofPausedUntil.delete(groupId);
40546
+ this._mlsGroupJoinedAt.set(groupId, Date.now());
40547
+ }
40344
40548
  this._removeKpFromPool(joined.kp);
40345
40549
  void this._ensureKpPoolPublished().catch((err) => {
40346
40550
  console.warn("[SecureChannel] KeyPackage pool replenish after join failed:", err);
@@ -40404,34 +40608,8 @@ ${baseText}`;
40404
40608
  return;
40405
40609
  }
40406
40610
  const welcomeRoomId = data.room_id;
40407
- for (const [roomId, room] of Object.entries(this._persisted?.rooms ?? {})) {
40408
- if (room.mlsGroupId === groupId || roomId === welcomeRoomId) {
40409
- room.mlsGroupId = groupId;
40410
- this._mlsGroups.set(roomId, mgr);
40411
- this._invalidateRoomAudienceForGroup(groupId);
40412
- await saveMlsState(this.config.dataDir, groupId, JSON.stringify(mgr.exportState()));
40413
- await this._persistState();
40414
- await this._applyBufferedMlsCommits(groupId, mgr);
40415
- console.log(`[SecureChannel] Joined MLS group for room ${roomId.slice(0, 8)} via Welcome (epoch=${mgr.epoch})`);
40416
- this._pendingMlsKpBundle = void 0;
40417
- await releaseA2ASyncLock(this.config.dataDir, `room-kp-${groupId}`).catch(() => {
40418
- });
40419
- return;
40420
- }
40421
- }
40422
- if (welcomeRoomId && this._persisted) {
40423
- await this._registerRoomFromWelcome(
40424
- welcomeRoomId,
40425
- groupId,
40426
- mgr,
40427
- data.room_name
40428
- );
40429
- this._pendingMlsKpBundle = void 0;
40430
- await releaseA2ASyncLock(this.config.dataDir, `room-kp-${groupId}`).catch(() => {
40431
- });
40432
- console.log(
40433
- `[SecureChannel] Registered room ${welcomeRoomId.slice(0, 8)} from unmatched Welcome (epoch=${mgr.epoch})`
40434
- );
40611
+ const lockRoom = typeof welcomeRoomId === "string" && welcomeRoomId ? welcomeRoomId : Object.entries(this._persisted?.rooms ?? {}).find(([, r2]) => r2.mlsGroupId === groupId)?.[0];
40612
+ if (lockRoom && await this._withRoomLock(lockRoom, () => this._installRoomWelcome(groupId, mgr, data))) {
40435
40613
  return;
40436
40614
  }
40437
40615
  const a2aChannelId = data.a2a_channel_id;
@@ -40490,6 +40668,45 @@ ${baseText}`;
40490
40668
  throw err;
40491
40669
  }
40492
40670
  }
40671
+ /**
40672
+ * The room half of `_handleMlsWelcome`: install `mgr` for the room this
40673
+ * Welcome names (by group or by room id), or register the room from the
40674
+ * Welcome. True when handled. Caller holds the room's lock (#1889 review).
40675
+ */
40676
+ async _installRoomWelcome(groupId, mgr, data) {
40677
+ const welcomeRoomId = data.room_id;
40678
+ for (const [roomId, room] of Object.entries(this._persisted?.rooms ?? {})) {
40679
+ if (room.mlsGroupId === groupId || roomId === welcomeRoomId) {
40680
+ room.mlsGroupId = groupId;
40681
+ this._mlsGroups.set(roomId, mgr);
40682
+ this._invalidateRoomAudienceForGroup(groupId);
40683
+ await saveMlsState(this.config.dataDir, groupId, JSON.stringify(mgr.exportState()));
40684
+ await this._persistState();
40685
+ await this._applyBufferedMlsCommits(groupId, mgr);
40686
+ console.log(`[SecureChannel] Joined MLS group for room ${roomId.slice(0, 8)} via Welcome (epoch=${mgr.epoch})`);
40687
+ this._pendingMlsKpBundle = void 0;
40688
+ await releaseA2ASyncLock(this.config.dataDir, `room-kp-${groupId}`).catch(() => {
40689
+ });
40690
+ return true;
40691
+ }
40692
+ }
40693
+ if (welcomeRoomId && this._persisted) {
40694
+ await this._registerRoomFromWelcome(
40695
+ welcomeRoomId,
40696
+ groupId,
40697
+ mgr,
40698
+ data.room_name
40699
+ );
40700
+ this._pendingMlsKpBundle = void 0;
40701
+ await releaseA2ASyncLock(this.config.dataDir, `room-kp-${groupId}`).catch(() => {
40702
+ });
40703
+ console.log(
40704
+ `[SecureChannel] Registered room ${welcomeRoomId.slice(0, 8)} from unmatched Welcome (epoch=${mgr.epoch})`
40705
+ );
40706
+ return true;
40707
+ }
40708
+ return false;
40709
+ }
40493
40710
  /**
40494
40711
  * Self-bootstrap a room entry + MLS group mapping from a Welcome whose room is
40495
40712
  * not yet persisted. Happens when we were added to an EXISTING room and the
@@ -43075,12 +43292,15 @@ function getActiveChannel(accountId = "default") {
43075
43292
  async function _handleInbound(params) {
43076
43293
  const { plaintext, metadata, channel, account, cfg, fileTurn } = params;
43077
43294
  const core = _ocRuntime;
43078
- if (metadata.roomId && metadata.senderBinding !== "bound") {
43079
- const ownDisplayName = channel.ownDisplayName ?? "";
43295
+ if (metadata.roomId) {
43080
43296
  const agentName = account.agentName ?? "";
43081
- const selfResolved = !!ownDisplayName || !!agentName && agentName.toLowerCase() !== "default";
43082
- if (!owesRoomReply(metadata.caption ?? plaintext, agentName, account.accountId ?? "", true, void 0, ownDisplayName, selfResolved, metadata.roomAudience, metadata.senderBinding)) {
43083
- console.log(`[AgentVault] room message from an unverified sender not addressed to this agent \u2014 not dispatched (#1855) room=${String(metadata.roomId).slice(0, 8)}`);
43297
+ const roomSelfName = _roomSelfName(channel, metadata.roomId);
43298
+ const ownDisplayName = channel.ownDisplayName ?? "";
43299
+ const selfResolved = !!ownDisplayName || !!roomSelfName && roomSelfName !== agentName || !!agentName && agentName.toLowerCase() !== "default";
43300
+ const gateText = metadata.caption ?? plaintext;
43301
+ const gateSenderIsAgent = metadata.senderBinding === "bound" ? metadata.senderIsAgent : true;
43302
+ if (!owesRoomReply(gateText, agentName, account.accountId ?? "", gateSenderIsAgent, roomSelfName || agentName, ownDisplayName, selfResolved, metadata.roomAudience, metadata.senderBinding)) {
43303
+ console.log(`[AgentVault] room message read, not answered \u2014 no @mention for this agent (#1107/#1859) room=${String(metadata.roomId).slice(0, 8)}`);
43084
43304
  return;
43085
43305
  }
43086
43306
  }
@@ -43109,9 +43329,16 @@ async function _handleInbound(params) {
43109
43329
  replyHost = { ...limitRoots !== void 0 ? { limitRoots } : {}, ...sandboxed ? { sandboxed: true } : {} };
43110
43330
  }
43111
43331
  noteTurnSandbox(fileTurn?.token, replyHost.sandboxed === true);
43112
- const modelBody = fileSendOn ? `${neutralizeForeignLine(plaintext)}
43332
+ const currentBody = neutralizeForeignLine(plaintext);
43333
+ const roomHistory = metadata.roomId ? _roomHistoryBlock(channel, metadata.roomId) : "";
43334
+ const contextBody = roomHistory ? `[Recent room conversation]
43335
+ ${roomHistory}
43336
+
43337
+ [Current message]
43338
+ ${currentBody}` : currentBody;
43339
+ const modelBody = fileSendOn ? `${contextBody}
43113
43340
 
43114
- ${openclawFileLines(channel, fileTarget, { roomsAllowed: false })}` : neutralizeForeignLine(plaintext);
43341
+ ${openclawFileLines(channel, fileTarget, { roomsAllowed: false })}` : contextBody;
43115
43342
  const body = core.channel.reply.formatAgentEnvelope({
43116
43343
  channel: "AgentVault",
43117
43344
  from: identity.name,
@@ -43193,6 +43420,27 @@ ${openclawFileLines(channel, fileTarget, { roomsAllowed: false })}` : neutralize
43193
43420
  const result = await trackedRun;
43194
43421
  await _legacyTurnRuns.afterDispatch(channel, runKey, fileTurn, result, trackedRun);
43195
43422
  }
43423
+ function _roomSelfName(channel, roomId) {
43424
+ try {
43425
+ const room = channel.getRooms().find((r2) => r2.roomId === roomId);
43426
+ const self2 = room?.members?.find((m2) => m2.deviceId === channel.deviceId);
43427
+ return typeof self2?.displayName === "string" ? self2.displayName : "";
43428
+ } catch {
43429
+ return "";
43430
+ }
43431
+ }
43432
+ function _roomHistoryBlock(channel, roomId) {
43433
+ const prior = channel.getRoomHistory(roomId, 20).slice(0, -1);
43434
+ return prior.map((h2) => {
43435
+ if (h2.sender === "agent") {
43436
+ const files = Array.isArray(h2.files) && h2.files.length > 0 ? `
43437
+ ${renderHistoryFiles(h2.files)}` : "";
43438
+ return `[You]: ${h2.text}${files}`;
43439
+ }
43440
+ const who = h2.sender === "unverified" ? "Unverified sender" : "Room Member";
43441
+ return `[${who}]: ${neutralizeForeignLine(String(h2.text ?? ""))}`;
43442
+ }).join("\n");
43443
+ }
43196
43444
  var _ocRuntime, _channels, _legacyTurnRuns, agentVaultPlugin;
43197
43445
  var init_openclaw_plugin = __esm({
43198
43446
  "src/openclaw-plugin.ts"() {
@@ -70520,6 +70768,41 @@ var init_policy_enforcer = __esm({
70520
70768
  }
70521
70769
  });
70522
70770
 
70771
+ // src/shell-word.ts
70772
+ function utf8Escapes(ch) {
70773
+ const cp = ch.codePointAt(0);
70774
+ const bytes = cp < 128 ? [cp] : cp < 2048 ? [192 | cp >> 6, 128 | cp & 63] : cp < 65536 ? [224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63] : [240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63];
70775
+ return bytes.map((b2) => `\\x${b2.toString(16).padStart(2, "0")}`).join("");
70776
+ }
70777
+ function shellWord(value) {
70778
+ if (BARE.test(value)) return value;
70779
+ if (value === "") return "''";
70780
+ if (NEEDS_ESCAPE.test(value)) {
70781
+ let body = "";
70782
+ let afterEscape = false;
70783
+ for (const ch of value) {
70784
+ const literal2 = LITERAL_IN_ANSI_C.test(ch) && !(afterEscape && HEX.test(ch));
70785
+ body += literal2 ? ch : utf8Escapes(ch);
70786
+ afterEscape = !literal2;
70787
+ }
70788
+ return `$'${body}'`;
70789
+ }
70790
+ return value.split(/(['\\])/).filter((part) => part !== "").map((part) => part === "'" || part === "\\" ? `\\${part}` : `'${part}'`).join("");
70791
+ }
70792
+ var BARE, NEEDS_ESCAPE, LITERAL_IN_ANSI_C, HEX;
70793
+ var init_shell_word = __esm({
70794
+ "src/shell-word.ts"() {
70795
+ "use strict";
70796
+ BARE = /^[A-Za-z0-9_./:@+-]+$/;
70797
+ NEEDS_ESCAPE = new RegExp(
70798
+ `[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}\\p{Default_Ignorable_Code_Point}${String.fromCodePoint(65532)}${String.fromCodePoint(10240)}]`,
70799
+ "u"
70800
+ );
70801
+ LITERAL_IN_ANSI_C = /^[A-Za-z0-9]$/;
70802
+ HEX = /^[0-9A-Fa-f]$/;
70803
+ }
70804
+ });
70805
+
70523
70806
  // src/index.ts
70524
70807
  var VERSION;
70525
70808
  var init_index = __esm({
@@ -70550,7 +70833,8 @@ var init_index = __esm({
70550
70833
  init_room_protocol();
70551
70834
  init_tool_telemetry();
70552
70835
  init_turn_failure();
70553
- VERSION = true ? "0.23.73" : "0.0.0-dev";
70836
+ init_shell_word();
70837
+ VERSION = true ? "0.23.75" : "0.0.0-dev";
70554
70838
  }
70555
70839
  });
70556
70840
  init_index();
@@ -70637,6 +70921,7 @@ export {
70637
70921
  sendToRoom,
70638
70922
  sendToTarget,
70639
70923
  setOcRuntime,
70924
+ shellWord,
70640
70925
  stagingLineFor,
70641
70926
  stripCaptionMentions,
70642
70927
  stripMentions,