@agentvault/grok-bridge 0.4.4 → 0.4.6

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
@@ -64004,6 +64004,8 @@ var init_mls_group = __esm2({
64004
64004
  continue;
64005
64005
  seenIdentities.push(identity);
64006
64006
  const leaf = this.memberLeafIndex(identity);
64007
+ if (leaf !== null && leaf === this.ownLeafIndex())
64008
+ continue;
64007
64009
  if (leaf !== null)
64008
64010
  leavesToRemove.push(leaf);
64009
64011
  }
@@ -64059,6 +64061,20 @@ var init_mls_group = __esm2({
64059
64061
  * then re-adds it with a fresh KeyPackage so it gets a Welcome at the
64060
64062
  * current epoch it can actually apply.
64061
64063
  */
64064
+ /**
64065
+ * The leaf index THIS manager occupies — the leaf whose private key it holds.
64066
+ *
64067
+ * Read from `privatePath.leafIndex`, which is the same value ts-mls uses to
64068
+ * decide whether a commit removes its own committer, so a caller checking
64069
+ * against this cannot disagree with the library about who "we" are.
64070
+ *
64071
+ * Exists so a fulfiller can tell a request from ANOTHER device apart from one
64072
+ * from itself (#1147) without any "who am I" plumbing: the manager already
64073
+ * knows, and a guard that reads it here cannot be forgotten by a call site.
64074
+ */
64075
+ ownLeafIndex() {
64076
+ return this._requireState().privatePath.leafIndex;
64077
+ }
64062
64078
  memberLeafIndex(identity) {
64063
64079
  const s2 = this._requireState();
64064
64080
  const tree = s2.ratchetTree;
@@ -64589,11 +64605,11 @@ var init_mls_kp_pool = __esm2({
64589
64605
  }
64590
64606
  });
64591
64607
  function ownIdentity() {
64592
- const v2 = true ? "0.23.31" : FALLBACK;
64608
+ const v2 = true ? "0.23.33" : FALLBACK;
64593
64609
  return `${PACKAGE}@${v2}`;
64594
64610
  }
64595
64611
  function buildSha() {
64596
- const raw = true ? "3e1243a-dirty" : "";
64612
+ const raw = true ? "7b91f2f-dirty" : "";
64597
64613
  const cleaned = (raw ?? "").trim();
64598
64614
  return !cleaned || cleaned === "unknown" ? null : cleaned;
64599
64615
  }
@@ -65508,6 +65524,7 @@ var OUTBOUND_DEDUPE_MAX;
65508
65524
  var OUTBOUND_DEDUPE_TYPES;
65509
65525
  var RETRY_CANDIDATE_TTL_MS;
65510
65526
  var RETRY_CANDIDATE_MAX;
65527
+ var ROOM_FULFIL_COOLDOWN_MS;
65511
65528
  var SecureChannel;
65512
65529
  var init_channel = __esm2({
65513
65530
  async "src/channel.ts"() {
@@ -65553,6 +65570,7 @@ var init_channel = __esm2({
65553
65570
  OUTBOUND_DEDUPE_TYPES = /* @__PURE__ */ new Set(["text", "status_alert", "artifact", "attachment"]);
65554
65571
  RETRY_CANDIDATE_TTL_MS = 6e4;
65555
65572
  RETRY_CANDIDATE_MAX = 32;
65573
+ ROOM_FULFIL_COOLDOWN_MS = 6e4;
65556
65574
  SecureChannel = class _SecureChannel extends EventEmitter {
65557
65575
  constructor(config2) {
65558
65576
  super();
@@ -65622,6 +65640,8 @@ var init_channel = __esm2({
65622
65640
  _drDeliveryPulling = false;
65623
65641
  /** MLS group managers per room/conversation (roomId or conv:conversationId or 1to1-group:groupId -> MLSGroupManager) */
65624
65642
  _mlsGroups = /* @__PURE__ */ new Map();
65643
+ /** `${mlsGroupId}:${deviceId}` -> last re-admit ms (#1171). */
65644
+ _roomFulfilCooldown = /* @__PURE__ */ new Map();
65625
65645
  /** Maps conversationId -> conversation_group_id for shared 1:1 MLS groups */
65626
65646
  _sessionGroupIds = /* @__PURE__ */ new Map();
65627
65647
  /** Consecutive MLS decrypt failure count per group key for epoch recovery. */
@@ -66787,7 +66807,7 @@ var init_channel = __esm2({
66787
66807
  */
66788
66808
  sendActivitySpan(spanData) {
66789
66809
  if (!this._ws || this._ws.readyState !== WebSocket.OPEN) return;
66790
- const pluginVersion = true ? "0.23.31" : "0.0.0-dev";
66810
+ const pluginVersion = true ? "0.23.33" : "0.0.0-dev";
66791
66811
  const agentName = this.config.agentName ?? "Agent";
66792
66812
  const resource = {
66793
66813
  "service.name": "agentvault-agent",
@@ -68725,7 +68745,7 @@ var init_channel = __esm2({
68725
68745
  agentVersion: this.config.agentVersion ?? "0.0.0",
68726
68746
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
68727
68747
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
68728
- pluginVersion: true ? "0.23.31" : "0.0.0-dev"
68748
+ pluginVersion: true ? "0.23.33" : "0.0.0-dev"
68729
68749
  });
68730
68750
  this._telemetryReporter.startAutoFlush(3e4);
68731
68751
  }
@@ -69049,7 +69069,7 @@ var init_channel = __esm2({
69049
69069
  agentVersion: this.config.agentVersion ?? "0.0.0",
69050
69070
  // __AV_VERSION__ is injected by esbuild from package.json at build time.
69051
69071
  // Falls back to "0.0.0-dev" in non-bundled contexts (tests).
69052
- pluginVersion: true ? "0.23.31" : "0.0.0-dev"
69072
+ pluginVersion: true ? "0.23.33" : "0.0.0-dev"
69053
69073
  });
69054
69074
  this._telemetryReporter.startAutoFlush(3e4);
69055
69075
  }
@@ -69852,7 +69872,8 @@ ${baseText}`;
69852
69872
  async _downloadAndDecryptAttachment(info) {
69853
69873
  const attachDir = join4(this.config.dataDir, "attachments");
69854
69874
  await mkdir3(attachDir, { recursive: true });
69855
- const url22 = `${this.config.apiUrl}${info.blobUrl}`;
69875
+ const sep2 = info.blobUrl.includes("?") ? "&" : "?";
69876
+ const url22 = `${this.config.apiUrl}${info.blobUrl}${sep2}device_id=${encodeURIComponent(this._deviceId ?? "")}`;
69856
69877
  const res = await fetch(url22, {
69857
69878
  headers: { Authorization: `Bearer ${this._deviceJwt}` }
69858
69879
  });
@@ -70404,10 +70425,12 @@ ${baseText}`;
70404
70425
  const rawPlaintext = new TextDecoder().decode(result.plaintext);
70405
70426
  let messageText;
70406
70427
  let messageType;
70428
+ let roomAttachment = null;
70407
70429
  try {
70408
70430
  const parsed = JSON.parse(rawPlaintext);
70409
70431
  messageType = parsed.type || "message";
70410
70432
  messageText = parsed.text || rawPlaintext;
70433
+ if (parsed.attachment) roomAttachment = parsed.attachment;
70411
70434
  } catch {
70412
70435
  messageType = "message";
70413
70436
  messageText = rawPlaintext;
@@ -70447,6 +70470,9 @@ ${baseText}`;
70447
70470
  await this._refreshRoomRoster(resolvedRoomId);
70448
70471
  }
70449
70472
  }
70473
+ if (roomAttachment) {
70474
+ messageText = await this._augmentWithAttachment(roomAttachment, messageText);
70475
+ }
70450
70476
  const roomMembers = this._persisted?.rooms?.[resolvedRoomId]?.members ?? [];
70451
70477
  const senderMember = roomMembers.find((m2) => m2.deviceId === senderDeviceId);
70452
70478
  const senderIsAgent = senderMember?.entityType === "agent";
@@ -70732,13 +70758,7 @@ ${baseText}`;
70732
70758
  console.warn(`[SecureChannel] MLS epoch recovery for ${groupKey} (${mlsGroupId.slice(0, 8)})`);
70733
70759
  this._mlsGroups.delete(groupKey);
70734
70760
  this._mlsDecryptFailCounts.delete(groupKey);
70735
- try {
70736
- const { unlink: unlink2 } = await import("fs/promises");
70737
- const path2 = `${this.config.dataDir}/.mls-state/${mlsGroupId}.json`;
70738
- await unlink2(path2).catch(() => {
70739
- });
70740
- } catch {
70741
- }
70761
+ await deleteMlsState(this.config.dataDir, mlsGroupId);
70742
70762
  try {
70743
70763
  const mgr = new MLSGroupManager();
70744
70764
  const identity = new TextEncoder().encode(this._deviceId);
@@ -70813,19 +70833,26 @@ ${baseText}`;
70813
70833
  return 0;
70814
70834
  }
70815
70835
  const snapshot = mlsGroup.exportState();
70816
- const { commit, welcome } = await mlsGroup.addMembers(targets.map((t2) => t2.keyPackage));
70817
- const commitSent = await this._sendFrameConfirmed(
70818
- {
70819
- event: "mls_commit",
70820
- data: {
70821
- group_id: mlsGroupId,
70822
- epoch: Number(mlsGroup.epoch),
70823
- payload: Buffer.from(commit).toString("hex")
70824
- }
70825
- },
70826
- `${label} commit`
70827
- );
70828
- if (!commitSent) {
70836
+ const { commits, welcome } = await mlsGroup.reAdmitMembers(targets.map((t2) => t2.keyPackage));
70837
+ let sentCommits = 0;
70838
+ for (const c2 of commits) {
70839
+ const ok = await this._sendFrameConfirmed(
70840
+ {
70841
+ event: "mls_commit",
70842
+ data: {
70843
+ group_id: mlsGroupId,
70844
+ // The epoch this commit PRODUCED. After two commits the manager
70845
+ // only knows the last one, which is why the result carries them.
70846
+ epoch: Number(c2.epoch),
70847
+ payload: Buffer.from(c2.commit).toString("hex")
70848
+ }
70849
+ },
70850
+ `${label} commit ${sentCommits + 1}/${commits.length}`
70851
+ );
70852
+ if (!ok) break;
70853
+ sentCommits++;
70854
+ }
70855
+ if (sentCommits === 0) {
70829
70856
  mlsGroup.importState(snapshot);
70830
70857
  console.warn(
70831
70858
  `[SecureChannel] ${label}: commit was NOT written \u2014 rolled back to epoch ${Number(mlsGroup.epoch)}, nothing fulfilled, requests stay pending`
@@ -70833,6 +70860,12 @@ ${baseText}`;
70833
70860
  return 0;
70834
70861
  }
70835
70862
  await saveMlsState(this.config.dataDir, mlsGroupId, JSON.stringify(mlsGroup.exportState()));
70863
+ if (sentCommits < commits.length) {
70864
+ console.warn(
70865
+ `[SecureChannel] ${label}: only ${sentCommits}/${commits.length} commits reached the wire \u2014 requests stay PENDING for the next pull`
70866
+ );
70867
+ return 0;
70868
+ }
70836
70869
  if (!welcome) {
70837
70870
  console.warn(
70838
70871
  `[SecureChannel] ${label}: addMembers produced NO Welcome \u2014 ${targets.length} request(s) left pending rather than marked fulfilled`
@@ -71561,38 +71594,63 @@ ${baseText}`;
71561
71594
  { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71562
71595
  );
71563
71596
  if (!pendingRes.ok) continue;
71564
- const pending = await pendingRes.json();
71597
+ let pending = await pendingRes.json();
71565
71598
  if (pending.length === 0) continue;
71566
71599
  console.log(`[SecureChannel] ${pending.length} pending Welcome requests for room ${roomId.slice(0, 8)}`);
71600
+ const nowMs = Date.now();
71601
+ const fresh = pending.filter((r2) => {
71602
+ const key = `${roomState.mlsGroupId}:${r2.requesting_device_id}`;
71603
+ const last = this._roomFulfilCooldown.get(key) ?? 0;
71604
+ if (nowMs - last < ROOM_FULFIL_COOLDOWN_MS) {
71605
+ console.log(
71606
+ `[SecureChannel] skipping ${r2.requesting_device_id.slice(0, 8)} in room ${roomId.slice(0, 8)} \u2014 re-admitted ${Math.round((nowMs - last) / 1e3)}s ago`
71607
+ );
71608
+ return false;
71609
+ }
71610
+ return true;
71611
+ });
71612
+ if (fresh.length === 0) continue;
71613
+ for (const r2 of fresh) {
71614
+ this._roomFulfilCooldown.set(`${roomState.mlsGroupId}:${r2.requesting_device_id}`, nowMs);
71615
+ }
71616
+ pending = fresh;
71617
+ const deviceIds = pending.map((r2) => r2.requesting_device_id);
71618
+ const kpRes = await fetch(
71619
+ `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${deviceIds.join(",")}`,
71620
+ { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71621
+ );
71622
+ if (!kpRes.ok) continue;
71623
+ const kpData = await kpRes.json();
71624
+ const roomTargets = [];
71567
71625
  for (const req of pending) {
71568
- try {
71569
- const kpRes = await fetch(
71570
- `${this.config.apiUrl}/api/v1/mls/key-packages/batch?device_ids=${req.requesting_device_id}`,
71571
- { headers: { Authorization: `Bearer ${this._deviceJwt}` } }
71626
+ const kpHex = kpData[req.requesting_device_id];
71627
+ if (!kpHex) {
71628
+ console.warn(`[SecureChannel] No KeyPackage for ${req.requesting_device_id.slice(0, 8)}, skipping`);
71629
+ continue;
71630
+ }
71631
+ const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
71632
+ roomTargets.push({
71633
+ requestId: req.id,
71634
+ deviceId: req.requesting_device_id,
71635
+ keyPackage: MLSGroupManager.deserializeKeyPackage(kpBytes)
71636
+ });
71637
+ }
71638
+ if (roomTargets.length === 0) continue;
71639
+ try {
71640
+ const done = await this._fulfilWelcomeRequests({
71641
+ mlsGroup,
71642
+ mlsGroupId: roomState.mlsGroupId,
71643
+ label: `room ${roomId.slice(0, 8)}`,
71644
+ welcomeFields: { room_id: roomId },
71645
+ targets: roomTargets
71646
+ });
71647
+ if (done > 0) {
71648
+ console.log(
71649
+ `[SecureChannel] Batched Welcome for ${done}/${roomTargets.length} device(s) in room ${roomId.slice(0, 8)} (epoch=${mlsGroup.epoch})`
71572
71650
  );
71573
- if (!kpRes.ok) continue;
71574
- const kpData = await kpRes.json();
71575
- const kpHex = kpData[req.requesting_device_id];
71576
- if (!kpHex) continue;
71577
- const kpBytes = new Uint8Array(Buffer.from(kpHex, "hex"));
71578
- const memberKp = MLSGroupManager.deserializeKeyPackage(kpBytes);
71579
- const done = await this._fulfilWelcomeRequests({
71580
- mlsGroup,
71581
- mlsGroupId: roomState.mlsGroupId,
71582
- label: `room ${roomId.slice(0, 8)}`,
71583
- welcomeFields: { room_id: roomId },
71584
- targets: [{
71585
- requestId: req.id,
71586
- deviceId: req.requesting_device_id,
71587
- keyPackage: memberKp
71588
- }]
71589
- });
71590
- if (done > 0) {
71591
- console.log(`[SecureChannel] Fulfilled Welcome for ${req.requesting_device_id.slice(0, 8)} in room ${roomId.slice(0, 8)}`);
71592
- }
71593
- } catch (fulfillErr) {
71594
- console.warn(`[SecureChannel] Welcome fulfill failed for ${req.requesting_device_id.slice(0, 8)}:`, fulfillErr);
71595
71651
  }
71652
+ } catch (fulfillErr) {
71653
+ console.warn(`[SecureChannel] Batched Welcome failed for room ${roomId.slice(0, 8)}:`, fulfillErr);
71596
71654
  }
71597
71655
  } catch {
71598
71656
  }
@@ -99403,7 +99461,7 @@ var init_index = __esm2({
99403
99461
  await init_skill_telemetry();
99404
99462
  await init_policy_enforcer();
99405
99463
  init_room_protocol();
99406
- VERSION = true ? "0.23.31" : "0.0.0-dev";
99464
+ VERSION = true ? "0.23.33" : "0.0.0-dev";
99407
99465
  }
99408
99466
  });
99409
99467
  await init_index();
@@ -100329,7 +100387,7 @@ async function main() {
100329
100387
  const info = parseInfoFlags(process.argv.slice(2));
100330
100388
  if (info.showVersion || info.showHelp) {
100331
100389
  const version2 = buildClientVersion2(
100332
- true ? "0.4.4" : void 0
100390
+ true ? "0.4.6" : void 0
100333
100391
  );
100334
100392
  if (info.showVersion) printLine(version2);
100335
100393
  if (info.showHelp) {
@@ -100382,7 +100440,7 @@ async function main() {
100382
100440
  agentName: cfg.agentName,
100383
100441
  platform: "node",
100384
100442
  clientVersion: buildClientVersion2(
100385
- true ? "0.4.4" : void 0
100443
+ true ? "0.4.6" : void 0
100386
100444
  )
100387
100445
  });
100388
100446
  channelRef = channel;
@@ -0,0 +1,57 @@
1
+ import { type BridgeConfig } from "../config.js";
2
+ import type { ReapResult } from "../reap.js";
3
+ import { type ServiceBackend } from "./backend.js";
4
+ export interface InstallOnReadyDeps {
5
+ entrypoint: string;
6
+ env: NodeJS.ProcessEnv;
7
+ backend?: ServiceBackend;
8
+ hasCreds?: (dataDir: string) => boolean;
9
+ /** Contents of the installed launcher, or undefined when none is installed. */
10
+ readLauncher?: (path: string) => string | undefined;
11
+ fenceAuthExists?: (fenceHome: string) => boolean;
12
+ /** Resolves when no turn is in flight (GrokSession.idle). See rule 2. */
13
+ waitForIdle?: () => Promise<void>;
14
+ /** Bound on that wait. The terminal coming back is the product promise, so a
15
+ * wedged turn must never hold the customer's shell open. */
16
+ idleTimeoutMs?: number;
17
+ /** The ONE teardown (src/reap.ts). Must complete before launchctl runs. */
18
+ reap: () => Promise<ReapResult>;
19
+ exit: (code: number) => void;
20
+ log: (msg: string) => void;
21
+ }
22
+ interface ReadyChannel {
23
+ on(ev: "ready", cb: () => void): unknown;
24
+ }
25
+ /**
26
+ * One-paste install: enrol in the foreground, hand off to the supervisor, exit —
27
+ * so the customer's terminal comes back and the agent survives a reboot.
28
+ *
29
+ * Four rules this module exists to enforce.
30
+ *
31
+ * 1. REFUSE BEFORE REAPING. Everything that can say no does so before anything is
32
+ * torn down. Refusing afterwards leaves the customer with an approved device,
33
+ * a spent invite token, and no running process — strictly worse than never
34
+ * having guarded at all.
35
+ *
36
+ * 2. REAP COMPLETELY, THEN BOOTSTRAP. `LaunchdBackend.install` runs bootout →
37
+ * poll-until-gone → bootstrap → kickstart synchronously, so the service is
38
+ * live the instant install returns. A partial teardown means two ACP sessions
39
+ * and two WebSockets on one device. `reap()` reports failure rather than
40
+ * swallowing it, and a failed reap is a refusal.
41
+ *
42
+ * 3. COMPARE, DON'T DETECT. `status().loaded` means only that a plist with this
43
+ * label exists. The old `install` subcommand never guarded its entrypoint
44
+ * (subcommand.ts), so a customer can hold a LOADED plist baked against a
45
+ * pruned npx cache; restarting that repairs nothing and reports success.
46
+ * Restart only when a service is loaded AND its baked entrypoint is the one we
47
+ * would install. Compare the ENTRYPOINT, never the whole launcher script —
48
+ * that embeds the install-time PATH and is volatile across shells.
49
+ *
50
+ * 4. VERIFY BEFORE CLAIMING. `backend.install` returns void, and launchd's
51
+ * implementation runs `kickstart` regardless of every `bootstrap` exit code.
52
+ * This log line is the customer's only feedback, so it comes after a
53
+ * `status()` that returned loaded:true.
54
+ */
55
+ export declare function installOnReady(channel: ReadyChannel, cfg: BridgeConfig, deps: InstallOnReadyDeps): void;
56
+ export {};
57
+ //# sourceMappingURL=install-on-ready.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"install-on-ready.d.ts","sourceRoot":"","sources":["../../src/service/install-on-ready.ts"],"names":[],"mappings":"AAEA,OAAO,EAA4C,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAC3F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAG7C,OAAO,EAAiB,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAElE,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;IACvB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC;IACxC,+EAA+E;IAC/E,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IACpD,eAAe,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC;IACjD,yEAAyE;IACzE,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAClC;iEAC6D;IAC7D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2EAA2E;IAC3E,IAAI,EAAE,MAAM,OAAO,CAAC,UAAU,CAAC,CAAC;IAChC,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7B,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CAC5B;AAMD,UAAU,YAAY;IACpB,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC;CAC1C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,YAAY,EACrB,GAAG,EAAE,YAAY,EACjB,IAAI,EAAE,kBAAkB,GACvB,IAAI,CAgHN"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentvault/grok-bridge",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "type": "module",
5
5
  "description": "AgentVault Grok Bridge — daemon bridging a Grok agent into E2E-encrypted AgentVault direct messages and rooms.",
6
6
  "main": "dist/index.js",