@agentvault/agentvault 0.23.73 → 0.23.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -24034,11 +24034,11 @@ var init_mls_kp_pool = __esm({
24034
24034
 
24035
24035
  // src/client-version.ts
24036
24036
  function ownIdentity() {
24037
- const v2 = true ? "0.23.73" : FALLBACK;
24037
+ const v2 = true ? "0.23.74" : FALLBACK;
24038
24038
  return `${PACKAGE}@${v2}`;
24039
24039
  }
24040
24040
  function buildSha() {
24041
- const raw = true ? "cb8786f" : "";
24041
+ const raw = true ? "91424d1" : "";
24042
24042
  const cleaned = (raw ?? "").trim();
24043
24043
  return !cleaned || cleaned === "unknown" ? null : cleaned;
24044
24044
  }
@@ -26570,6 +26570,28 @@ var init_welcome_kp_backoff = __esm({
26570
26570
  }
26571
26571
  });
26572
26572
 
26573
+ // ../crypto/dist/invisible-text.js
26574
+ function replaceInvisible(value, replacement) {
26575
+ 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);
26576
+ }
26577
+ function drawsNothing(value) {
26578
+ return value.replace(INVISIBLE2, "").split(BRAILLE_BLANK).join("").length === 0;
26579
+ }
26580
+ var ZWJ, DEFAULT_IGNORABLE, KEPT_IGNORABLE, OBJECT_REPLACEMENT, CONTROL, KEPT_CONTROL, INVISIBLE2, BRAILLE_BLANK;
26581
+ var init_invisible_text = __esm({
26582
+ "../crypto/dist/invisible-text.js"() {
26583
+ "use strict";
26584
+ ZWJ = 8205;
26585
+ DEFAULT_IGNORABLE = new RegExp("\\p{Default_Ignorable_Code_Point}", "gu");
26586
+ KEPT_IGNORABLE = /* @__PURE__ */ new Set([8204, ZWJ, 65039]);
26587
+ OBJECT_REPLACEMENT = new RegExp(String.fromCodePoint(65532), "g");
26588
+ CONTROL = new RegExp("\\p{Cc}", "gu");
26589
+ KEPT_CONTROL = /* @__PURE__ */ new Set([9, 10, 13]);
26590
+ INVISIBLE2 = /[\s\p{Cf}\p{Default_Ignorable_Code_Point}]/gu;
26591
+ BRAILLE_BLANK = String.fromCodePoint(10240);
26592
+ }
26593
+ });
26594
+
26573
26595
  // src/dm-group-pins.ts
26574
26596
  function isUuid(v2) {
26575
26597
  return typeof v2 === "string" && UUID_RE3.test(v2);
@@ -26709,8 +26731,8 @@ function drOwnerClaimNotice(label) {
26709
26731
  }
26710
26732
  function sanitizeDeviceLabel(name2) {
26711
26733
  if (typeof name2 !== "string") return null;
26712
- const clean8 = name2.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, " ").replace(/\s+/g, " ").trim();
26713
- if (clean8 === "") return null;
26734
+ const clean8 = replaceInvisible(name2, " ").replace(/\s+/g, " ").trim();
26735
+ if (clean8 === "" || drawsNothing(clean8)) return null;
26714
26736
  const points = Array.from(clean8);
26715
26737
  return points.length > 64 ? `${points.slice(0, 63).join("")}\u2026` : clean8;
26716
26738
  }
@@ -26719,6 +26741,7 @@ var init_dm_group_pins = __esm({
26719
26741
  "src/dm-group-pins.ts"() {
26720
26742
  "use strict";
26721
26743
  init_mls_sender_binding();
26744
+ init_invisible_text();
26722
26745
  UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
26723
26746
  CANONICAL_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
26724
26747
  WELCOME_ROUTING_FIELDS = [
@@ -29687,6 +29710,60 @@ function anySignal(signals) {
29687
29710
  }
29688
29711
  return c2.signal;
29689
29712
  }
29713
+ function textCutEnd(value, budget) {
29714
+ const Segmenter = Intl.Segmenter;
29715
+ if (typeof Segmenter === "function") {
29716
+ const segmenter = new Segmenter(
29717
+ void 0,
29718
+ { granularity: "grapheme" }
29719
+ );
29720
+ let end2 = 0;
29721
+ for (const { segment, index } of segmenter.segment(value.slice(0, budget + 64))) {
29722
+ if (index + segment.length > budget) break;
29723
+ end2 = index + segment.length;
29724
+ }
29725
+ return end2;
29726
+ }
29727
+ let end = budget;
29728
+ const last = value.charCodeAt(end - 1);
29729
+ if (last >= 55296 && last <= 56319) end -= 1;
29730
+ for (; ; ) {
29731
+ const before = end;
29732
+ while (end > 0 && value.charCodeAt(end - 1) === 8205) end -= 1;
29733
+ let regional = 0;
29734
+ for (let i2 = end; i2 >= 2; i2 -= 2) {
29735
+ const c2 = value.codePointAt(i2 - 2);
29736
+ if (c2 < 127462 || c2 > 127487) break;
29737
+ regional++;
29738
+ }
29739
+ if (regional % 2 === 1) end -= 2;
29740
+ if (end === before) return end;
29741
+ }
29742
+ }
29743
+ function capTextPart(value, max) {
29744
+ if (value.length <= max) return value;
29745
+ return `${value.slice(0, textCutEnd(value, max - 1))}\u2026`;
29746
+ }
29747
+ function statusAlertTextLine(alert) {
29748
+ const severity = STATUS_ALERT_SEVERITIES.has(alert.severity) ? String(alert.severity) : "info";
29749
+ const title = capTextPart(String(alert.title), STATUS_ALERT_TEXT_LIMITS.title);
29750
+ const message = capTextPart(String(alert.message), STATUS_ALERT_TEXT_LIMITS.message);
29751
+ return `[${severity.toUpperCase()}] ${title}: ${message}`;
29752
+ }
29753
+ function statusAlertEnvelope(alert, timestamp) {
29754
+ const envelope = {
29755
+ type: "status_alert",
29756
+ title: alert.title,
29757
+ message: alert.message,
29758
+ severity: alert.severity,
29759
+ timestamp
29760
+ };
29761
+ if (alert.detail !== void 0) envelope.detail = alert.detail;
29762
+ if (alert.detailFormat !== void 0) envelope.detail_format = alert.detailFormat;
29763
+ if (alert.category !== void 0) envelope.category = alert.category;
29764
+ envelope.text = statusAlertTextLine(alert);
29765
+ return envelope;
29766
+ }
29690
29767
  function outboundDedupeKey(resolved, content, options) {
29691
29768
  if (!OUTBOUND_DEDUPE_TYPES.has(content.type)) return null;
29692
29769
  const base = [resolved.kind, resolved.id ?? "owner", options?.conversationId ?? "", options?.topicId ?? ""];
@@ -29827,7 +29904,7 @@ function historyErrorReason(error2) {
29827
29904
  }
29828
29905
  return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? `${name2} (status ${status})` : name2;
29829
29906
  }
29830
- 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;
29907
+ 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;
29831
29908
  var init_channel = __esm({
29832
29909
  "src/channel.ts"() {
29833
29910
  "use strict";
@@ -29879,6 +29956,8 @@ var init_channel = __esm({
29879
29956
  "decision_response",
29880
29957
  "artifact_share"
29881
29958
  ]);
29959
+ STATUS_ALERT_TEXT_LIMITS = { title: 120, message: 2e3 };
29960
+ STATUS_ALERT_SEVERITIES = /* @__PURE__ */ new Set(["info", "warning", "error", "critical"]);
29882
29961
  CREDENTIAL_MESSAGE_TYPES = /* @__PURE__ */ new Set([
29883
29962
  "credential_grant",
29884
29963
  "credential_revoke",
@@ -30064,6 +30143,56 @@ var init_channel = __esm({
30064
30143
  /** #1094: never let one slow report hold up the rest. */
30065
30144
  static _KEY_PROOF_FETCH_TIMEOUT_MS = 1e4;
30066
30145
  _keyProofTimer = null;
30146
+ /**
30147
+ * #1889: a group the server refuses a proof for — 404 "MLS group not found",
30148
+ * or 403 "Not a member of this group" outside the join grace — is not asked
30149
+ * again for this long (Hermes's #1543 window). A Welcome into the group, or a
30150
+ * `room_joined` for its room, ends the pause at once.
30151
+ */
30152
+ static _KEY_PROOF_PAUSE_MS = 24 * 60 * 60 * 1e3;
30153
+ /**
30154
+ * #1889 review: a 403 pauses for ONE hour, not a day. A live member whose
30155
+ * roster entry lags still answers 403, and a paused proof reads as `stale`
30156
+ * to the lockout detector, which then cannot repair it on epoch_behind. An
30157
+ * hour bounds that while still cutting a dead room's 144 posts a day to 24.
30158
+ */
30159
+ static _KEY_PROOF_403_PAUSE_MS = 60 * 60 * 1e3;
30160
+ /** When this process started: the join grace also covers a join made just before a restart. */
30161
+ _processStartedAt = Date.now();
30162
+ /**
30163
+ * #1889 review: one room's state is changed by one task at a time. The
30164
+ * reconcile's drop, `joinRoom` and a room Welcome's install all run under
30165
+ * the room's lock, so a re-admit can never be deleted half-way through.
30166
+ */
30167
+ _roomLocks = /* @__PURE__ */ new Map();
30168
+ /**
30169
+ * #1889 review: `POST /mls/rooms/{id}/init` runs while `joinRoom` holds the
30170
+ * room's lock, and a delivery-queue Welcome for that room waits on the lock
30171
+ * (the pull is serial). Without a bound, a hung init stalled every group's
30172
+ * delivery for Node's 300 s default. It is the only network call made under
30173
+ * a room lock. Static and writable so a test can shorten it.
30174
+ */
30175
+ static ROOM_INIT_FETCH_TIMEOUT_MS = 1e4;
30176
+ /**
30177
+ * #1889 / #1542: right after a join the server roster can lag this device,
30178
+ * and that lag answers 403 too. Inside this window a 403 pauses nothing: a
30179
+ * paused proof would read as never_proved.
30180
+ */
30181
+ static _KEY_PROOF_JOIN_GRACE_MS = 30 * 60 * 1e3;
30182
+ /** The backend's detail for a device outside the roster (mls.py report_key_proof). */
30183
+ static KEY_PROOF_NOT_A_MEMBER_DETAIL = "Not a member of this group";
30184
+ /** #1889: group id -> ms until which its key proofs are paused. */
30185
+ _keyProofPausedUntil = /* @__PURE__ */ new Map();
30186
+ /** #1889: group id -> ms this device last joined it from a Welcome. */
30187
+ _mlsGroupJoinedAt = /* @__PURE__ */ new Map();
30188
+ /**
30189
+ * #1889: room id -> how many times `joinRoom` ran for it. A room reconcile
30190
+ * prunes nothing whose count moved while its GET was in flight: the
30191
+ * response predates that (re)join.
30192
+ */
30193
+ _roomJoinGen = /* @__PURE__ */ new Map();
30194
+ /** #1889: the room reconcile in flight, so overlapping asks share one GET. */
30195
+ _roomReconcileInFlight = null;
30067
30196
  _a2aReconcileTimer = null;
30068
30197
  _deliveryPulling = false;
30069
30198
  _drDeliveryPulling = false;
@@ -33235,7 +33364,7 @@ ${text}`,
33235
33364
  */
33236
33365
  sendActivitySpan(spanData) {
33237
33366
  if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return;
33238
- const pluginVersion = true ? "0.23.73" : "0.0.0-dev";
33367
+ const pluginVersion = true ? "0.23.74" : "0.0.0-dev";
33239
33368
  const agentName = this.config.agentName ?? "Agent";
33240
33369
  const resource = {
33241
33370
  "service.name": "agentvault-agent",
@@ -33546,10 +33675,19 @@ ${text}`,
33546
33675
  * Encryption is handled by MLS group operations, not per-member DR sessions.
33547
33676
  */
33548
33677
  async joinRoom(roomData) {
33678
+ if (!this._persisted) {
33679
+ throw new Error("Channel not initialized");
33680
+ }
33681
+ this._roomJoinGen.set(roomData.roomId, (this._roomJoinGen.get(roomData.roomId) ?? 0) + 1);
33682
+ return this._withRoomLock(roomData.roomId, () => this._joinRoomLocked(roomData));
33683
+ }
33684
+ async _joinRoomLocked(roomData) {
33549
33685
  if (!this._persisted) {
33550
33686
  throw new Error("Channel not initialized");
33551
33687
  }
33552
33688
  this._roomRosterRefreshed.delete(roomData.roomId);
33689
+ const priorGroup = this._persisted?.rooms?.[roomData.roomId]?.mlsGroupId;
33690
+ if (priorGroup) this._keyProofPausedUntil.delete(priorGroup);
33553
33691
  this._applyRoomAudience(roomData.roomId, roomData.audience);
33554
33692
  await libsodium_wrappers_default.ready;
33555
33693
  const myDeviceId = this._deviceId;
@@ -33605,7 +33743,11 @@ ${text}`,
33605
33743
  },
33606
33744
  body: JSON.stringify({
33607
33745
  member_device_ids: roomData.members.map((m2) => m2.deviceId)
33608
- })
33746
+ }),
33747
+ // #1889 review: bounded, because this runs under the room lock. A
33748
+ // timeout lands in the catch below: no group id is stored, so the
33749
+ // next room_joined (or the owner's Welcome) still completes the room.
33750
+ signal: AbortSignal.timeout(_SecureChannel.ROOM_INIT_FETCH_TIMEOUT_MS)
33609
33751
  });
33610
33752
  if (initRes.ok) {
33611
33753
  const groupData = await initRes.json();
@@ -33749,10 +33891,41 @@ ${text}`,
33749
33891
  * Fail-safe: a failed fetch / non-ok / non-array response prunes NOTHING, so a
33750
33892
  * transient error can never over-prune a live room.
33751
33893
  */
33752
- async _reconcileRoomsWithServer() {
33894
+ /** Run `fn` holding room `roomId`'s lock (FIFO). */
33895
+ async _withRoomLock(roomId, fn) {
33896
+ const prev = this._roomLocks.get(roomId) ?? Promise.resolve();
33897
+ let release;
33898
+ const mine = new Promise((resolve8) => {
33899
+ release = resolve8;
33900
+ });
33901
+ const tail = prev.then(() => mine);
33902
+ this._roomLocks.set(roomId, tail);
33903
+ await prev;
33904
+ try {
33905
+ return await fn();
33906
+ } finally {
33907
+ release();
33908
+ if (this._roomLocks.get(roomId) === tail) this._roomLocks.delete(roomId);
33909
+ }
33910
+ }
33911
+ _reconcileRoomsWithServer() {
33912
+ if (this._roomReconcileInFlight) return this._roomReconcileInFlight;
33913
+ const run = this._reconcileRoomsOnce().finally(() => {
33914
+ this._roomReconcileInFlight = null;
33915
+ });
33916
+ this._roomReconcileInFlight = run;
33917
+ return run;
33918
+ }
33919
+ async _reconcileRoomsOnce() {
33753
33920
  const local = this._persisted?.rooms;
33754
33921
  if (!local || Object.keys(local).length === 0) return;
33755
33922
  if (!this._deviceJwt) return;
33923
+ const before = new Map(
33924
+ Object.keys(local).map((rid) => [
33925
+ rid,
33926
+ { mgr: this._mlsGroups.get(rid), gen: this._roomJoinGen.get(rid) ?? 0 }
33927
+ ])
33928
+ );
33756
33929
  let activeIds;
33757
33930
  try {
33758
33931
  const res = await fetch(`${this.config.apiUrl}/api/v1/rooms`, {
@@ -33761,38 +33934,59 @@ ${text}`,
33761
33934
  if (!res.ok) return;
33762
33935
  const list = await res.json();
33763
33936
  if (!Array.isArray(list)) return;
33764
- activeIds = new Set(
33765
- list.map((r2) => r2?.id).filter((id) => !!id)
33766
- );
33937
+ if (!list.every((r2) => !!r2 && typeof r2 === "object" && typeof r2.id === "string" && r2.id)) {
33938
+ console.warn("[SecureChannel] room reconcile skipped: malformed item in GET /rooms (pruning nothing)");
33939
+ return;
33940
+ }
33941
+ activeIds = new Set(list.map((r2) => r2.id));
33767
33942
  } catch (err) {
33768
33943
  console.warn(
33769
33944
  `[SecureChannel] room reconcile skipped (fetch failed, pruning nothing): ${err instanceof Error ? err.message : String(err)}`
33770
33945
  );
33771
33946
  return;
33772
33947
  }
33773
- const stale = Object.keys(local).filter((rid) => !activeIds.has(rid));
33948
+ for (const rid of activeIds) {
33949
+ const gid = local[rid]?.mlsGroupId;
33950
+ if (gid) this._keyProofPausedUntil.delete(gid);
33951
+ }
33952
+ const stale = Object.keys(local).filter((rid) => {
33953
+ if (activeIds.has(rid)) return false;
33954
+ const snap = before.get(rid);
33955
+ if (!snap) return false;
33956
+ return this._mlsGroups.get(rid) === snap.mgr && (this._roomJoinGen.get(rid) ?? 0) === snap.gen;
33957
+ });
33774
33958
  if (stale.length === 0) return;
33959
+ const pruned = [];
33775
33960
  for (const rid of stale) {
33776
- const room = local[rid];
33777
- if (room?.mlsGroupId) {
33778
- try {
33779
- await deleteMlsState(this.config.dataDir, room.mlsGroupId);
33780
- } catch {
33961
+ await this._withRoomLock(rid, async () => {
33962
+ const snap = before.get(rid);
33963
+ const room = local[rid];
33964
+ if (!snap || !room) return;
33965
+ if (this._mlsGroups.get(rid) !== snap.mgr || (this._roomJoinGen.get(rid) ?? 0) !== snap.gen) return;
33966
+ this._mlsGroups.delete(rid);
33967
+ for (const convId of room.conversationIds ?? []) {
33968
+ this._sessions.delete(convId);
33969
+ if (this._persisted?.sessions) delete this._persisted.sessions[convId];
33970
+ }
33971
+ delete local[rid];
33972
+ pruned.push(rid);
33973
+ if (room.mlsGroupId) {
33974
+ this._keyProofPausedUntil.delete(room.mlsGroupId);
33975
+ this._mlsGroupJoinedAt.delete(room.mlsGroupId);
33976
+ try {
33977
+ await deleteMlsState(this.config.dataDir, room.mlsGroupId);
33978
+ } catch {
33979
+ }
33781
33980
  }
33782
- }
33783
- this._mlsGroups.delete(rid);
33784
- for (const convId of room?.conversationIds ?? []) {
33785
- this._sessions.delete(convId);
33786
- if (this._persisted?.sessions) delete this._persisted.sessions[convId];
33787
- }
33788
- delete local[rid];
33789
- this._retireRoomFolder(rid);
33981
+ this._retireRoomFolder(rid);
33982
+ });
33790
33983
  }
33984
+ if (pruned.length === 0) return;
33791
33985
  await this._persistState();
33792
33986
  console.log(
33793
- `[SecureChannel] Room reconcile: pruned ${stale.length} disbanded/left room(s) from local state (${stale.map((r2) => r2.slice(0, 8)).join(", ")})`
33987
+ `[SecureChannel] Room reconcile: pruned ${pruned.length} disbanded/left room(s) from local state (${pruned.map((r2) => r2.slice(0, 8)).join(", ")})`
33794
33988
  );
33795
- this.emit("rooms_reconciled", { pruned: stale });
33989
+ this.emit("rooms_reconciled", { pruned });
33796
33990
  }
33797
33991
  /**
33798
33992
  * #629 — quarantine MLS state for groups this device is no longer in.
@@ -34257,19 +34451,8 @@ ${text}`,
34257
34451
  }
34258
34452
  async sendStatusAlert(alert, routing) {
34259
34453
  const priority = alert.severity === "error" || alert.severity === "critical" ? "high" : "normal";
34260
- const envelope = {
34261
- type: "status_alert",
34262
- title: alert.title,
34263
- message: alert.message,
34264
- severity: alert.severity,
34265
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
34266
- };
34267
- if (alert.detail !== void 0) envelope.detail = alert.detail;
34268
- if (alert.detailFormat !== void 0) envelope.detail_format = alert.detailFormat;
34269
- if (alert.category !== void 0) envelope.category = alert.category;
34270
- envelope.text = `[${String(alert.severity).toUpperCase()}] ${alert.title}: ${alert.message}`;
34271
34454
  await this.send(
34272
- JSON.stringify(envelope),
34455
+ JSON.stringify(statusAlertEnvelope(alert, (/* @__PURE__ */ new Date()).toISOString())),
34273
34456
  {
34274
34457
  conversationId: routing?.conversationId,
34275
34458
  audience: routing?.audience,
@@ -34486,16 +34669,7 @@ ${text}`,
34486
34669
  decisionId = await this.sendDecisionRequest(content.request, ownerRouting);
34487
34670
  } else if (content.type === "status_alert") {
34488
34671
  if (resolved.kind === "room") {
34489
- const envelope = {
34490
- title: content.alert.title,
34491
- message: content.alert.message,
34492
- severity: content.alert.severity,
34493
- timestamp: ts
34494
- };
34495
- if (content.alert.detail !== void 0) envelope.detail = content.alert.detail;
34496
- if (content.alert.detailFormat !== void 0) envelope.detail_format = content.alert.detailFormat;
34497
- if (content.alert.category !== void 0) envelope.category = content.alert.category;
34498
- await this.sendToRoom(resolved.id, JSON.stringify(envelope), {
34672
+ await this.sendToRoom(resolved.id, JSON.stringify(statusAlertEnvelope(content.alert, ts)), {
34499
34673
  messageType: "status_alert",
34500
34674
  priority: content.alert.severity === "error" || content.alert.severity === "critical" ? "high" : "normal",
34501
34675
  metadata: { severity: content.alert.severity }
@@ -39586,13 +39760,17 @@ ${baseText}`;
39586
39760
  const jwt = this._deviceJwt;
39587
39761
  if (!deviceId || !jwt) return;
39588
39762
  const best = /* @__PURE__ */ new Map();
39589
- for (const mgr of this._mlsGroups.values()) {
39763
+ const roomGroups = /* @__PURE__ */ new Set();
39764
+ const now = Date.now();
39765
+ for (const [key, mgr] of this._mlsGroups.entries()) {
39590
39766
  try {
39591
39767
  if (!mgr.isInitialized) continue;
39592
39768
  const epoch = Number(mgr.epoch);
39593
39769
  if (epoch <= 0) continue;
39594
39770
  const groupId = _SecureChannel._mlsGroupIdString(mgr.groupId);
39595
39771
  if (!groupId) continue;
39772
+ if (now < (this._keyProofPausedUntil.get(groupId) ?? 0)) continue;
39773
+ if (this._persisted?.rooms?.[key]) roomGroups.add(groupId);
39596
39774
  const prev = best.get(groupId);
39597
39775
  if (prev && epoch <= prev.epoch) continue;
39598
39776
  best.set(groupId, { epoch, authenticator: Buffer.from(mgr.epochAuthenticator).toString("hex") });
@@ -39600,6 +39778,7 @@ ${baseText}`;
39600
39778
  continue;
39601
39779
  }
39602
39780
  }
39781
+ let askRooms = false;
39603
39782
  for (const [groupId, { epoch, authenticator }] of best) {
39604
39783
  try {
39605
39784
  const res = await fetch(`${this.config.apiUrl}/api/v1/mls/groups/${groupId}/key-proof`, {
@@ -39608,11 +39787,34 @@ ${baseText}`;
39608
39787
  body: JSON.stringify({ device_id: deviceId, epoch, authenticator }),
39609
39788
  signal: AbortSignal.timeout(_SecureChannel._KEY_PROOF_FETCH_TIMEOUT_MS)
39610
39789
  });
39611
- if (!res.ok) console.debug(`[key-proof] ${groupId.slice(0, 8)}: HTTP ${res.status}`);
39790
+ if (res.ok) continue;
39791
+ const detail = res.status === 403 ? await this._errorDetail(res) : null;
39792
+ if (res.status === 404 || detail === _SecureChannel.KEY_PROOF_NOT_A_MEMBER_DETAIL) {
39793
+ if (roomGroups.has(groupId)) askRooms = true;
39794
+ const graceFrom = Math.max(this._mlsGroupJoinedAt.get(groupId) ?? 0, this._processStartedAt);
39795
+ if (res.status === 403 && Date.now() - graceFrom < _SecureChannel._KEY_PROOF_JOIN_GRACE_MS) {
39796
+ console.debug(`[key-proof] ${groupId.slice(0, 8)}: HTTP 403 within the join grace (roster lag)`);
39797
+ continue;
39798
+ }
39799
+ const pauseMs = res.status === 404 ? _SecureChannel._KEY_PROOF_PAUSE_MS : _SecureChannel._KEY_PROOF_403_PAUSE_MS;
39800
+ this._keyProofPausedUntil.set(groupId, Date.now() + pauseMs);
39801
+ console.log(
39802
+ `[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)`
39803
+ );
39804
+ continue;
39805
+ }
39806
+ console.debug(`[key-proof] ${groupId.slice(0, 8)}: HTTP ${res.status}`);
39612
39807
  } catch (err) {
39613
39808
  console.debug(`[key-proof] ${groupId.slice(0, 8)}: report failed (non-critical):`, err);
39614
39809
  }
39615
39810
  }
39811
+ if (askRooms) {
39812
+ try {
39813
+ await this._reconcileRoomsWithServer();
39814
+ } catch (err) {
39815
+ console.warn(`[key-proof] room reconcile after a refusal failed (ignored): ${err instanceof Error ? err.message : String(err)}`);
39816
+ }
39817
+ }
39616
39818
  }
39617
39819
  /**
39618
39820
  * The wire MLS group id as a UUID string, or null. Every founder today —
@@ -39905,18 +40107,16 @@ ${baseText}`;
39905
40107
  * limiter (per-conversation and global caps). The plaintext carries
39906
40108
  * `type: "status_alert"`, so no agent in the room treats it as a turn
39907
40109
  * (`status_alert` is not in ROOM_AGENT_TYPES). Fire-and-forget; never throws.
40110
+ * #1867: built by `statusAlertEnvelope`, like every other plugin alert, so
40111
+ * it carries the `text` line a room tab older than #1860 shows.
39908
40112
  */
39909
40113
  _sendRoomSecurityNotice(noticeKey, roomId, title, text) {
39910
40114
  try {
39911
40115
  if (!this._securityNoticeLimiter.allow(noticeKey)) return;
39912
- const envelope = JSON.stringify({
39913
- type: "status_alert",
39914
- title,
39915
- message: text(),
39916
- severity: "warning",
39917
- category: "security",
39918
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
39919
- });
40116
+ const envelope = JSON.stringify(statusAlertEnvelope(
40117
+ { title, message: text(), severity: "warning", category: "security" },
40118
+ (/* @__PURE__ */ new Date()).toISOString()
40119
+ ));
39920
40120
  Promise.resolve().then(() => this.sendToRoom(roomId, envelope, { messageType: "status_alert" })).catch((err) => {
39921
40121
  console.warn(`[SecureChannel] #1800 security notice for room ${logId(roomId)} was not sent:`, err);
39922
40122
  });
@@ -39949,7 +40149,7 @@ ${baseText}`;
39949
40149
  agentVersion: this.config.agentVersion ?? "0.0.0",
39950
40150
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
39951
40151
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
39952
- pluginVersion: true ? "0.23.73" : "0.0.0-dev"
40152
+ pluginVersion: true ? "0.23.74" : "0.0.0-dev"
39953
40153
  });
39954
40154
  this._telemetryReporter.startAutoFlush(3e4);
39955
40155
  }
@@ -40148,6 +40348,10 @@ ${baseText}`;
40148
40348
  return;
40149
40349
  }
40150
40350
  const mgr = joined.mgr;
40351
+ if (groupId) {
40352
+ this._keyProofPausedUntil.delete(groupId);
40353
+ this._mlsGroupJoinedAt.set(groupId, Date.now());
40354
+ }
40151
40355
  this._removeKpFromPool(joined.kp);
40152
40356
  void this._ensureKpPoolPublished().catch((err) => {
40153
40357
  console.warn("[SecureChannel] KeyPackage pool replenish after join failed:", err);
@@ -40211,34 +40415,8 @@ ${baseText}`;
40211
40415
  return;
40212
40416
  }
40213
40417
  const welcomeRoomId = data.room_id;
40214
- for (const [roomId, room] of Object.entries(this._persisted?.rooms ?? {})) {
40215
- if (room.mlsGroupId === groupId || roomId === welcomeRoomId) {
40216
- room.mlsGroupId = groupId;
40217
- this._mlsGroups.set(roomId, mgr);
40218
- this._invalidateRoomAudienceForGroup(groupId);
40219
- await saveMlsState(this.config.dataDir, groupId, JSON.stringify(mgr.exportState()));
40220
- await this._persistState();
40221
- await this._applyBufferedMlsCommits(groupId, mgr);
40222
- console.log(`[SecureChannel] Joined MLS group for room ${roomId.slice(0, 8)} via Welcome (epoch=${mgr.epoch})`);
40223
- this._pendingMlsKpBundle = void 0;
40224
- await releaseA2ASyncLock(this.config.dataDir, `room-kp-${groupId}`).catch(() => {
40225
- });
40226
- return;
40227
- }
40228
- }
40229
- if (welcomeRoomId && this._persisted) {
40230
- await this._registerRoomFromWelcome(
40231
- welcomeRoomId,
40232
- groupId,
40233
- mgr,
40234
- data.room_name
40235
- );
40236
- this._pendingMlsKpBundle = void 0;
40237
- await releaseA2ASyncLock(this.config.dataDir, `room-kp-${groupId}`).catch(() => {
40238
- });
40239
- console.log(
40240
- `[SecureChannel] Registered room ${welcomeRoomId.slice(0, 8)} from unmatched Welcome (epoch=${mgr.epoch})`
40241
- );
40418
+ const lockRoom = typeof welcomeRoomId === "string" && welcomeRoomId ? welcomeRoomId : Object.entries(this._persisted?.rooms ?? {}).find(([, r2]) => r2.mlsGroupId === groupId)?.[0];
40419
+ if (lockRoom && await this._withRoomLock(lockRoom, () => this._installRoomWelcome(groupId, mgr, data))) {
40242
40420
  return;
40243
40421
  }
40244
40422
  const a2aChannelId = data.a2a_channel_id;
@@ -40297,6 +40475,45 @@ ${baseText}`;
40297
40475
  throw err;
40298
40476
  }
40299
40477
  }
40478
+ /**
40479
+ * The room half of `_handleMlsWelcome`: install `mgr` for the room this
40480
+ * Welcome names (by group or by room id), or register the room from the
40481
+ * Welcome. True when handled. Caller holds the room's lock (#1889 review).
40482
+ */
40483
+ async _installRoomWelcome(groupId, mgr, data) {
40484
+ const welcomeRoomId = data.room_id;
40485
+ for (const [roomId, room] of Object.entries(this._persisted?.rooms ?? {})) {
40486
+ if (room.mlsGroupId === groupId || roomId === welcomeRoomId) {
40487
+ room.mlsGroupId = groupId;
40488
+ this._mlsGroups.set(roomId, mgr);
40489
+ this._invalidateRoomAudienceForGroup(groupId);
40490
+ await saveMlsState(this.config.dataDir, groupId, JSON.stringify(mgr.exportState()));
40491
+ await this._persistState();
40492
+ await this._applyBufferedMlsCommits(groupId, mgr);
40493
+ console.log(`[SecureChannel] Joined MLS group for room ${roomId.slice(0, 8)} via Welcome (epoch=${mgr.epoch})`);
40494
+ this._pendingMlsKpBundle = void 0;
40495
+ await releaseA2ASyncLock(this.config.dataDir, `room-kp-${groupId}`).catch(() => {
40496
+ });
40497
+ return true;
40498
+ }
40499
+ }
40500
+ if (welcomeRoomId && this._persisted) {
40501
+ await this._registerRoomFromWelcome(
40502
+ welcomeRoomId,
40503
+ groupId,
40504
+ mgr,
40505
+ data.room_name
40506
+ );
40507
+ this._pendingMlsKpBundle = void 0;
40508
+ await releaseA2ASyncLock(this.config.dataDir, `room-kp-${groupId}`).catch(() => {
40509
+ });
40510
+ console.log(
40511
+ `[SecureChannel] Registered room ${welcomeRoomId.slice(0, 8)} from unmatched Welcome (epoch=${mgr.epoch})`
40512
+ );
40513
+ return true;
40514
+ }
40515
+ return false;
40516
+ }
40300
40517
  /**
40301
40518
  * Self-bootstrap a room entry + MLS group mapping from a Welcome whose room is
40302
40519
  * not yet persisted. Happens when we were added to an EXISTING room and the
@@ -59514,6 +59731,18 @@ var init_policy_enforcer = __esm({
59514
59731
  }
59515
59732
  });
59516
59733
 
59734
+ // src/shell-word.ts
59735
+ var NEEDS_ESCAPE;
59736
+ var init_shell_word = __esm({
59737
+ "src/shell-word.ts"() {
59738
+ "use strict";
59739
+ NEEDS_ESCAPE = new RegExp(
59740
+ `[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}\\p{Default_Ignorable_Code_Point}${String.fromCodePoint(65532)}${String.fromCodePoint(10240)}]`,
59741
+ "u"
59742
+ );
59743
+ }
59744
+ });
59745
+
59517
59746
  // src/index.ts
59518
59747
  var VERSION;
59519
59748
  var init_index = __esm({
@@ -59545,7 +59774,8 @@ var init_index = __esm({
59545
59774
  init_room_protocol();
59546
59775
  init_tool_telemetry();
59547
59776
  init_turn_failure();
59548
- VERSION = true ? "0.23.73" : "0.0.0-dev";
59777
+ init_shell_word();
59778
+ VERSION = true ? "0.23.74" : "0.0.0-dev";
59549
59779
  }
59550
59780
  });
59551
59781
 
@@ -59642,9 +59872,9 @@ function describeSdkCapabilities(results) {
59642
59872
  function describeBuildIdentity() {
59643
59873
  const name2 = "Build identity";
59644
59874
  try {
59645
- const raw = true ? "cb8786f" : "";
59875
+ const raw = true ? "91424d1" : "";
59646
59876
  const sha = (raw ?? "").trim();
59647
- const at2 = true ? "2026-11-24T14:45:30.852Z".trim() : "";
59877
+ const at2 = true ? "2026-11-28T15:49:17.098Z".trim() : "";
59648
59878
  const built = at2 ? ` built ${at2}` : "";
59649
59879
  if (!sha || sha === "unknown") {
59650
59880
  return {
@@ -60172,10 +60402,12 @@ var init_doctor = __esm({
60172
60402
  // src/create-agent.ts
60173
60403
  var create_agent_exports = {};
60174
60404
  __export(create_agent_exports, {
60405
+ CREATE_NAME_ERROR: () => CREATE_NAME_ERROR,
60175
60406
  _checkAltFrameworkName: () => _checkAltFrameworkName,
60176
60407
  findNextPort: () => findNextPort,
60177
60408
  generateWorkspaceFiles: () => generateWorkspaceFiles,
60178
60409
  openclawHome: () => openclawHome,
60410
+ pickCreateAgentName: () => pickCreateAgentName,
60179
60411
  readOpenClawConfig: () => readOpenClawConfig,
60180
60412
  runCreateCommand: () => runCreateCommand
60181
60413
  });
@@ -60183,6 +60415,19 @@ import { execFileSync as execFileSync2 } from "node:child_process";
60183
60415
  import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync6, writeFileSync as writeFileSync2, copyFileSync } from "node:fs";
60184
60416
  import { join as join12 } from "node:path";
60185
60417
  import { createInterface as createInterface3 } from "node:readline";
60418
+ function pickCreateAgentName(args2) {
60419
+ let name2;
60420
+ for (const arg of args2) {
60421
+ if (arg.startsWith("-")) {
60422
+ const flag = /^--([A-Za-z][\w-]*)(?:=[\s\S]*)?$/.exec(arg);
60423
+ if (flag && CREATE_FLAGS.has(flag[1])) continue;
60424
+ return { error: CREATE_NAME_ERROR };
60425
+ }
60426
+ if (name2 === void 0) name2 = arg;
60427
+ }
60428
+ if (name2 !== void 0 && !/^[A-Za-z0-9]/.test(name2)) return { error: CREATE_NAME_ERROR };
60429
+ return { name: name2 };
60430
+ }
60186
60431
  function _checkAltFrameworkName(name2) {
60187
60432
  const lower = name2.toLowerCase().trim();
60188
60433
  if (!lower) return null;
@@ -60283,6 +60528,7 @@ _(Empty \u2014 ${name2} starts with a clean memory. Update as the agent learns.)
60283
60528
  }
60284
60529
  async function runCreateCommand(options) {
60285
60530
  const { name: name2, token: token2, apiUrl: apiUrl2, force } = options;
60531
+ if (!/^[A-Za-z0-9]/.test(name2)) throw new Error(CREATE_NAME_ERROR);
60286
60532
  const home = openclawHome();
60287
60533
  const configPath = join12(home, "openclaw.json");
60288
60534
  const workspaceDir = join12(home, `workspace-${name2}`);
@@ -60588,15 +60834,31 @@ Skills are injected at runtime \u2014 no need to list them here.
60588
60834
  3. Approve the agent in the AgentVault app
60589
60835
  `);
60590
60836
  }
60591
- var ALT_FRAMEWORK_HINTS;
60837
+ var CREATE_NAME_ERROR, CREATE_FLAGS, ALT_FRAMEWORK_HINTS;
60592
60838
  var init_create_agent = __esm({
60593
60839
  "src/create-agent.ts"() {
60594
60840
  "use strict";
60595
60841
  init_setup();
60842
+ CREATE_NAME_ERROR = "Agent name must start with a letter (a-z) or a number";
60843
+ CREATE_FLAGS = /* @__PURE__ */ new Set([
60844
+ "token",
60845
+ "port",
60846
+ "api-url",
60847
+ "force",
60848
+ "data-dir",
60849
+ "account-id",
60850
+ "name",
60851
+ "webhook-url",
60852
+ "no-notifications"
60853
+ ]);
60596
60854
  ALT_FRAMEWORK_HINTS = {
60597
60855
  hermes: {
60598
60856
  name: "Hermes",
60599
- install: "pip install agentvault-hermes && agentvault-hermes setup --token=<paste-the-token>"
60857
+ install: (
60858
+ // [mls] is required (without it setup fails: no mls_rs_uniffi); quoted
60859
+ // so zsh does not treat the brackets as a glob.
60860
+ 'pip install "agentvault-hermes-plugin[mls]" && agentvault-hermes setup --token=<paste-the-token>'
60861
+ )
60600
60862
  },
60601
60863
  nemo: {
60602
60864
  name: "NVIDIA NeMo",
@@ -61425,7 +61687,13 @@ After setup, restart OpenClaw \u2014 messages will flow automatically.
61425
61687
  process.exit(0);
61426
61688
  }
61427
61689
  if (subcommand === "create") {
61428
- const agentName = args.slice(1).find((a2) => !a2.startsWith("--"));
61690
+ const { pickCreateAgentName: pickCreateAgentName2 } = await Promise.resolve().then(() => (init_create_agent(), create_agent_exports));
61691
+ const picked = pickCreateAgentName2(args.slice(commandIndex + 1));
61692
+ if ("error" in picked) {
61693
+ console.error(` Error: ${picked.error}`);
61694
+ process.exit(1);
61695
+ }
61696
+ const agentName = picked.name;
61429
61697
  if (!agentName || !token) {
61430
61698
  console.error(`
61431
61699
  AgentVault Create Agent