@agentvault/claude-bridge 0.8.3 → 0.8.5

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.
Files changed (2) hide show
  1. package/dist/index.js +213 -10
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -64011,6 +64011,8 @@ var init_mls_group = __esm2({
64011
64011
  continue;
64012
64012
  seenIdentities.push(identity);
64013
64013
  const leaf = this.memberLeafIndex(identity);
64014
+ if (leaf !== null && leaf === this.ownLeafIndex())
64015
+ continue;
64014
64016
  if (leaf !== null)
64015
64017
  leavesToRemove.push(leaf);
64016
64018
  }
@@ -64066,6 +64068,20 @@ var init_mls_group = __esm2({
64066
64068
  * then re-adds it with a fresh KeyPackage so it gets a Welcome at the
64067
64069
  * current epoch it can actually apply.
64068
64070
  */
64071
+ /**
64072
+ * The leaf index THIS manager occupies — the leaf whose private key it holds.
64073
+ *
64074
+ * Read from `privatePath.leafIndex`, which is the same value ts-mls uses to
64075
+ * decide whether a commit removes its own committer, so a caller checking
64076
+ * against this cannot disagree with the library about who "we" are.
64077
+ *
64078
+ * Exists so a fulfiller can tell a request from ANOTHER device apart from one
64079
+ * from itself (#1147) without any "who am I" plumbing: the manager already
64080
+ * knows, and a guard that reads it here cannot be forgotten by a call site.
64081
+ */
64082
+ ownLeafIndex() {
64083
+ return this._requireState().privatePath.leafIndex;
64084
+ }
64069
64085
  memberLeafIndex(identity) {
64070
64086
  const s22 = this._requireState();
64071
64087
  const tree = s22.ratchetTree;
@@ -64596,11 +64612,11 @@ var init_mls_kp_pool = __esm2({
64596
64612
  }
64597
64613
  });
64598
64614
  function ownIdentity() {
64599
- const v22 = true ? "0.23.30" : FALLBACK;
64615
+ const v22 = true ? "0.23.32" : FALLBACK;
64600
64616
  return `${PACKAGE}@${v22}`;
64601
64617
  }
64602
64618
  function buildSha() {
64603
- const raw = true ? "1fff5d6" : "";
64619
+ const raw = true ? "564f8b1-dirty" : "";
64604
64620
  const cleaned = (raw ?? "").trim();
64605
64621
  return !cleaned || cleaned === "unknown" ? null : cleaned;
64606
64622
  }
@@ -66348,6 +66364,118 @@ var init_channel = __esm2({
66348
66364
  * Encrypt and send a message to ALL owner devices (fanout).
66349
66365
  * Each session gets the same plaintext encrypted independently.
66350
66366
  */
66367
+ /**
66368
+ * #952 — sends held because MLS is expected for this conversation but the
66369
+ * group is not joined yet.
66370
+ *
66371
+ * ⚠️ IN MEMORY ONLY. These entries hold PLAINTEXT. `_persisted` is written to
66372
+ * disk, and the product's entire premise is that plaintext does not rest
66373
+ * where it does not have to; a crash losing a held greeting is the correct
66374
+ * trade. This is why the existing `outboundQueue` could not be reused — that
66375
+ * one is persisted, and holds already-DR-encrypted bytes, which is exactly
66376
+ * the encryption we are trying not to perform yet.
66377
+ */
66378
+ _mlsHold = /* @__PURE__ */ new Map();
66379
+ /** How long a send waits for the Welcome. The two measured bursts were each
66380
+ * confined to a single minute, with the group already existing server-side
66381
+ * in the same second, so this is generous rather than tight. */
66382
+ static MLS_HOLD_MS = 3e4;
66383
+ /** Bound on held sends per group — see `_holdForMls`. */
66384
+ static MLS_HOLD_MAX = 50;
66385
+ /**
66386
+ * Should this 1:1 send wait for MLS rather than go out over Double Ratchet?
66387
+ *
66388
+ * The discriminator exists at the moment of the bug: `_sessionGroupIds`
66389
+ * already carries the conversation's group id — the server told us the group
66390
+ * exists — while `_mlsGroups` has no usable manager for it. Group expected,
66391
+ * group not ready.
66392
+ *
66393
+ * The negative case is load-bearing. A conversation with NO group id is
66394
+ * legitimately Double Ratchet, and holding it would break owner-to-agent
66395
+ * messaging outright, which is far worse than the bug this fixes. "Present"
66396
+ * is also not "ready": a manager parked at epoch 0 has not joined (#1092),
66397
+ * and reading presence as readiness is how #991 shipped.
66398
+ */
66399
+ _shouldHoldForMls(convGroupId, mlsGroup, mlsGroupId) {
66400
+ if (!convGroupId) return false;
66401
+ const ready = Boolean(mlsGroup?.isInitialized) && Boolean(mlsGroupId) && Number(mlsGroup?.epoch) > 0;
66402
+ return !ready;
66403
+ }
66404
+ /** Park a send until the Welcome lands, or until the hold expires. */
66405
+ _holdForMls(convGroupId, convId, plaintext, options) {
66406
+ let entry = this._mlsHold.get(convGroupId);
66407
+ if (!entry) {
66408
+ const timer = setTimeout(() => {
66409
+ void this._releaseHeldOverDr(convGroupId);
66410
+ }, _SecureChannel.MLS_HOLD_MS);
66411
+ timer.unref?.();
66412
+ entry = { items: [], timer };
66413
+ this._mlsHold.set(convGroupId, entry);
66414
+ }
66415
+ if (entry.items.length >= _SecureChannel.MLS_HOLD_MAX) {
66416
+ entry.items.shift();
66417
+ console.warn(
66418
+ `[SecureChannel] MLS hold full for group ${convGroupId.slice(0, 8)} \u2014 dropped the oldest held message`
66419
+ );
66420
+ }
66421
+ entry.items.push({ convId, plaintext, options });
66422
+ console.log(
66423
+ `[SecureChannel] Holding send for group ${convGroupId.slice(0, 8)} until its Welcome lands (held=${entry.items.length})`
66424
+ );
66425
+ }
66426
+ _takeHold(convGroupId) {
66427
+ const entry = this._mlsHold.get(convGroupId);
66428
+ if (!entry) return null;
66429
+ clearTimeout(entry.timer);
66430
+ this._mlsHold.delete(convGroupId);
66431
+ return entry;
66432
+ }
66433
+ /** Re-drive one held send through the normal path, now that MLS is ready. */
66434
+ async _resendHeld(item) {
66435
+ await this.send(item.plaintext, {
66436
+ ...item.options ?? {},
66437
+ conversationId: item.convId,
66438
+ bypassMlsHold: true
66439
+ });
66440
+ }
66441
+ /** The Welcome landed — release everything held for this group, in order. */
66442
+ async _flushMlsHold(convGroupId) {
66443
+ const entry = this._takeHold(convGroupId);
66444
+ if (!entry) return;
66445
+ console.log(
66446
+ `[SecureChannel] Welcome landed for group ${convGroupId.slice(0, 8)} \u2014 releasing ${entry.items.length} held message(s) over MLS`
66447
+ );
66448
+ for (const item of entry.items) {
66449
+ try {
66450
+ await this._resendHeld(item);
66451
+ } catch (err) {
66452
+ console.warn("[SecureChannel] Held message failed to send after Welcome:", err);
66453
+ }
66454
+ }
66455
+ }
66456
+ /**
66457
+ * The hold expired. Send over Double Ratchet exactly as before.
66458
+ *
66459
+ * This is deliberately NOT a drop. #853 and #831 are Welcomes that never
66460
+ * arrive; under those an unbounded hold turns a lost minute into an agent
66461
+ * that never speaks again. The hold removes the race — it must not invent a
66462
+ * new failure mode. The warning is the part that is new: today the loss is
66463
+ * silent.
66464
+ */
66465
+ async _releaseHeldOverDr(convGroupId) {
66466
+ const entry = this._takeHold(convGroupId);
66467
+ if (!entry) return;
66468
+ console.warn(
66469
+ `[SecureChannel] No Welcome for group ${convGroupId.slice(0, 8)} within ${_SecureChannel.MLS_HOLD_MS}ms \u2014 releasing ${entry.items.length} message(s) over Double Ratchet. The recipient may not hold a ratchet with this device, in which case they are undeliverable (#952).`
66470
+ );
66471
+ for (const item of entry.items) {
66472
+ try {
66473
+ await this._resendHeld(item);
66474
+ } catch (err) {
66475
+ console.warn("[SecureChannel] Held message failed on Double Ratchet release:", err);
66476
+ }
66477
+ }
66478
+ }
66351
66479
  async send(plaintext, options) {
66352
66480
  if (isAbstention(plaintext)) return;
66353
66481
  if (this._state === "error" || this._state === "idle") {
@@ -66509,6 +66637,10 @@ var init_channel = __esm2({
66509
66637
  );
66510
66638
  addressedMlsGroupIds.push(mlsGroupId);
66511
66639
  if (convGroupId) sentSharedGroupIds.add(convGroupId);
66640
+ } else if (!options?.bypassMlsHold && this._shouldHoldForMls(convGroupId, mlsGroup, mlsGroupId)) {
66641
+ this._holdForMls(convGroupId, convId, plaintext, options);
66642
+ sentCount++;
66643
+ continue;
66512
66644
  } else {
66513
66645
  const encrypted = session.ratchet.encrypt(plaintext);
66514
66646
  const transport = encryptedMessageToTransport(encrypted);
@@ -66678,7 +66810,7 @@ var init_channel = __esm2({
66678
66810
  */
66679
66811
  sendActivitySpan(spanData) {
66680
66812
  if (!this._ws || this._ws.readyState !== WebSocket2.OPEN) return;
66681
- const pluginVersion = true ? "0.23.30" : "0.0.0-dev";
66813
+ const pluginVersion = true ? "0.23.32" : "0.0.0-dev";
66682
66814
  const agentName = this.config.agentName ?? "Agent";
66683
66815
  const resource = {
66684
66816
  "service.name": "agentvault-agent",
@@ -68616,7 +68748,7 @@ var init_channel = __esm2({
68616
68748
  agentVersion: this.config.agentVersion ?? "0.0.0",
68617
68749
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
68618
68750
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
68619
- pluginVersion: true ? "0.23.30" : "0.0.0-dev"
68751
+ pluginVersion: true ? "0.23.32" : "0.0.0-dev"
68620
68752
  });
68621
68753
  this._telemetryReporter.startAutoFlush(3e4);
68622
68754
  }
@@ -68940,7 +69072,7 @@ var init_channel = __esm2({
68940
69072
  agentVersion: this.config.agentVersion ?? "0.0.0",
68941
69073
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
68942
69074
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
68943
- pluginVersion: true ? "0.23.30" : "0.0.0-dev"
69075
+ pluginVersion: true ? "0.23.32" : "0.0.0-dev"
68944
69076
  });
68945
69077
  this._telemetryReporter.startAutoFlush(3e4);
68946
69078
  }
@@ -69356,11 +69488,13 @@ var init_channel = __esm2({
69356
69488
  let text = plaintext;
69357
69489
  let messageType = "text";
69358
69490
  let topicId = data.topic_id;
69491
+ let mlsAttachment = null;
69359
69492
  try {
69360
69493
  const parsed = JSON.parse(plaintext);
69361
69494
  text = parsed.text ?? plaintext;
69362
69495
  messageType = parsed.type ?? "text";
69363
69496
  topicId = parsed.topicId ?? topicId;
69497
+ if (parsed.attachment) mlsAttachment = parsed.attachment;
69364
69498
  } catch {
69365
69499
  }
69366
69500
  if (messageType === "history_catchup_request") {
@@ -69427,6 +69561,9 @@ var init_channel = __esm2({
69427
69561
  console.log(`[SecureChannel] Session ${convId.slice(0, 8)} activated via MLS message`);
69428
69562
  }
69429
69563
  }
69564
+ if (mlsAttachment) {
69565
+ text = await this._augmentWithAttachment(mlsAttachment, text);
69566
+ }
69430
69567
  const metadata = {
69431
69568
  messageId: data.message_id ?? `mls_${Date.now()}`,
69432
69569
  conversationId: convId ?? this._primaryConversationId,
@@ -69676,10 +69813,70 @@ ${messageText}`;
69676
69813
  * Download an encrypted attachment blob, decrypt it, verify integrity,
69677
69814
  * and save the plaintext file to disk.
69678
69815
  */
69816
+ /** Where an attachment may be written — always directly inside `attachDir` (#1143).
69817
+ *
69818
+ * The filename arrives INSIDE the envelope and is chosen by whoever sent the
69819
+ * message. `join(attachDir, info.filename)` resolves `..` normally, so
69820
+ * `../../agentvault.json` wrote over the device credential store. Only the
69821
+ * final path component is honoured, and anything that is not a usable name
69822
+ * falls back to a fixed one.
69823
+ */
69824
+ _safeAttachmentPath(attachDir, filename) {
69825
+ const raw = String(filename ?? "");
69826
+ const last = raw.split(/[\\/]/).pop() ?? "";
69827
+ const cleaned = last.replace(/\0/g, "").trim();
69828
+ const safe = cleaned === "" || cleaned === "." || cleaned === ".." ? "attachment.bin" : cleaned;
69829
+ return join4(attachDir, safe);
69830
+ }
69831
+ /** Download an attachment and fold it into the text the agent sees (#1139).
69832
+ *
69833
+ * Extracted so the MLS receive path can use it too. It used to live inline in
69834
+ * `_handleIncomingMessage`, which meant attachments worked on the Double
69835
+ * Ratchet path ONLY — and hermes drops DR by design (`secure_channel.py:594`,
69836
+ * "DR fallback is logged-and-dropped"), so no single transport could serve
69837
+ * both client families. That is why an attachment reached ohtani and never
69838
+ * reached smartcoder2 on 2026-08-31.
69839
+ *
69840
+ * Returns the text unchanged when there is no attachment or the fetch fails —
69841
+ * but a failure is LOGGED and announced in the text, never silent.
69842
+ */
69843
+ async _augmentWithAttachment(attachmentInfo, baseText) {
69844
+ if (!attachmentInfo) return baseText;
69845
+ try {
69846
+ const { filePath, decrypted } = await this._downloadAndDecryptAttachment(attachmentInfo);
69847
+ const mime = String(attachmentInfo.mime ?? "application/octet-stream");
69848
+ const name = String(attachmentInfo.filename ?? "attachment");
69849
+ const textMimes = ["text/", "application/json", "application/xml", "application/csv"];
69850
+ if (textMimes.some((m22) => mime.startsWith(m22))) {
69851
+ const content = new TextDecoder().decode(decrypted);
69852
+ return `[Attachment: ${name} (${mime}) saved to ${filePath}]
69853
+ ---
69854
+ ${content}
69855
+ ---
69856
+
69857
+ ${baseText}`;
69858
+ }
69859
+ if (mime.startsWith("image/")) {
69860
+ return `[Image attachment: ${name} saved to ${filePath}]
69861
+ Use your Read tool to view this image file.
69862
+
69863
+ ${baseText}`;
69864
+ }
69865
+ return `[Attachment: ${name} saved to ${filePath}]
69866
+
69867
+ ${baseText}`;
69868
+ } catch (err) {
69869
+ console.error("[SecureChannel] Failed to download attachment:", err);
69870
+ return `[Attachment: ${String(attachmentInfo.filename ?? "file")} was sent but could not be retrieved: ${err}]
69871
+
69872
+ ${baseText}`;
69873
+ }
69874
+ }
69679
69875
  async _downloadAndDecryptAttachment(info) {
69680
69876
  const attachDir = join4(this.config.dataDir, "attachments");
69681
69877
  await mkdir3(attachDir, { recursive: true });
69682
- const url22 = `${this.config.apiUrl}${info.blobUrl}`;
69878
+ const sep3 = info.blobUrl.includes("?") ? "&" : "?";
69879
+ const url22 = `${this.config.apiUrl}${info.blobUrl}${sep3}device_id=${encodeURIComponent(this._deviceId ?? "")}`;
69683
69880
  const res = await fetch(url22, {
69684
69881
  headers: { Authorization: `Bearer ${this._deviceJwt}` }
69685
69882
  });
@@ -69695,7 +69892,7 @@ ${messageText}`;
69695
69892
  const fileKey = base64ToBytes(info.fileKey);
69696
69893
  const fileNonce = base64ToBytes(info.fileNonce);
69697
69894
  const decrypted = decryptFile(encryptedData, fileKey, fileNonce);
69698
- const filePath = join4(attachDir, info.filename);
69895
+ const filePath = this._safeAttachmentPath(attachDir, info.filename);
69699
69896
  await writeFile3(filePath, decrypted);
69700
69897
  console.log(`[SecureChannel] Attachment saved: ${filePath} (${decrypted.length} bytes)`);
69701
69898
  return { filePath, decrypted };
@@ -70231,10 +70428,12 @@ ${messageText}`;
70231
70428
  const rawPlaintext = new TextDecoder().decode(result.plaintext);
70232
70429
  let messageText;
70233
70430
  let messageType;
70431
+ let roomAttachment = null;
70234
70432
  try {
70235
70433
  const parsed = JSON.parse(rawPlaintext);
70236
70434
  messageType = parsed.type || "message";
70237
70435
  messageText = parsed.text || rawPlaintext;
70436
+ if (parsed.attachment) roomAttachment = parsed.attachment;
70238
70437
  } catch {
70239
70438
  messageType = "message";
70240
70439
  messageText = rawPlaintext;
@@ -70274,6 +70473,9 @@ ${messageText}`;
70274
70473
  await this._refreshRoomRoster(resolvedRoomId);
70275
70474
  }
70276
70475
  }
70476
+ if (roomAttachment) {
70477
+ messageText = await this._augmentWithAttachment(roomAttachment, messageText);
70478
+ }
70277
70479
  const roomMembers = this._persisted?.rooms?.[resolvedRoomId]?.members ?? [];
70278
70480
  const senderMember = roomMembers.find((m22) => m22.deviceId === senderDeviceId);
70279
70481
  const senderIsAgent = senderMember?.entityType === "agent";
@@ -71116,6 +71318,7 @@ ${messageText}`;
71116
71318
  await this._persistState();
71117
71319
  }
71118
71320
  console.log(`[SecureChannel] Joined shared 1:1 MLS group for group ${conversationGroupId.slice(0, 8)} via Welcome (epoch=${mgr.epoch})`);
71321
+ await this._flushMlsHold(conversationGroupId);
71119
71322
  return;
71120
71323
  }
71121
71324
  if (conversationId) {
@@ -99229,7 +99432,7 @@ var init_index = __esm2({
99229
99432
  await init_skill_telemetry();
99230
99433
  await init_policy_enforcer();
99231
99434
  init_room_protocol();
99232
- VERSION = true ? "0.23.30" : "0.0.0-dev";
99435
+ VERSION = true ? "0.23.32" : "0.0.0-dev";
99233
99436
  }
99234
99437
  });
99235
99438
  await init_index();
@@ -135633,7 +135836,7 @@ async function main() {
135633
135836
  "[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"
135634
135837
  );
135635
135838
  }
135636
- logLine(`[bridge] version: ${true ? "0.8.3" : "dev"}`);
135839
+ logLine(`[bridge] version: ${true ? "0.8.5" : "dev"}`);
135637
135840
  logLine(`[bridge] data dir: ${cfg.dataDir} (${cfg.dataDirSource})`);
135638
135841
  logLine(`[bridge] workspace: ${cfg.workspaceDir} \xB7 permissions: ${cfg.permissionMode} \xB7 enclave dir fenced`);
135639
135842
  if (cfg.armRoom) {
@@ -135665,7 +135868,7 @@ async function main() {
135665
135868
  // its default would render "@agentvault/agentvault@0.7.x" — the wrong
135666
135869
  // package name attached to the bridge's version number, which is worse
135667
135870
  // than either alone.
135668
- clientVersion: `@agentvault/claude-bridge@${true ? "0.8.3" : "dev"}`
135871
+ clientVersion: `@agentvault/claude-bridge@${true ? "0.8.5" : "dev"}`
135669
135872
  });
135670
135873
  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.`;
135671
135874
  const deviceJwt = () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/claude-bridge",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
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",