@essentialai/cogent-bridge-bundled 3.23.5 → 3.23.7

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/cogent-bridge.mjs +502 -289
  2. package/package.json +1 -1
package/cogent-bridge.mjs CHANGED
@@ -1259,8 +1259,8 @@ var init_parseUtil = __esm({
1259
1259
  init_errors();
1260
1260
  init_en();
1261
1261
  makeIssue = (params) => {
1262
- const { data, path: path24, errorMaps, issueData } = params;
1263
- const fullPath = [...path24, ...issueData.path || []];
1262
+ const { data, path: path25, errorMaps, issueData } = params;
1263
+ const fullPath = [...path25, ...issueData.path || []];
1264
1264
  const fullIssue = {
1265
1265
  ...issueData,
1266
1266
  path: fullPath
@@ -1540,11 +1540,11 @@ var init_types = __esm({
1540
1540
  init_parseUtil();
1541
1541
  init_util();
1542
1542
  ParseInputLazyPath = class {
1543
- constructor(parent, value, path24, key) {
1543
+ constructor(parent, value, path25, key) {
1544
1544
  this._cachedPath = [];
1545
1545
  this.parent = parent;
1546
1546
  this.data = value;
1547
- this._path = path24;
1547
+ this._path = path25;
1548
1548
  this._key = key;
1549
1549
  }
1550
1550
  get path() {
@@ -4996,10 +4996,10 @@ function assignProp(target, prop, value) {
4996
4996
  configurable: true
4997
4997
  });
4998
4998
  }
4999
- function getElementAtPath(obj, path24) {
5000
- if (!path24)
4999
+ function getElementAtPath(obj, path25) {
5000
+ if (!path25)
5001
5001
  return obj;
5002
- return path24.reduce((acc, key) => acc?.[key], obj);
5002
+ return path25.reduce((acc, key) => acc?.[key], obj);
5003
5003
  }
5004
5004
  function promiseAllObject(promisesObj) {
5005
5005
  const keys = Object.keys(promisesObj);
@@ -5248,11 +5248,11 @@ function aborted(x, startIndex = 0) {
5248
5248
  }
5249
5249
  return false;
5250
5250
  }
5251
- function prefixIssues(path24, issues) {
5251
+ function prefixIssues(path25, issues) {
5252
5252
  return issues.map((iss) => {
5253
5253
  var _a;
5254
5254
  (_a = iss).path ?? (_a.path = []);
5255
- iss.path.unshift(path24);
5255
+ iss.path.unshift(path25);
5256
5256
  return iss;
5257
5257
  });
5258
5258
  }
@@ -17058,8 +17058,8 @@ var require_utils = __commonJS({
17058
17058
  }
17059
17059
  return ind;
17060
17060
  }
17061
- function removeDotSegments(path24) {
17062
- let input = path24;
17061
+ function removeDotSegments(path25) {
17062
+ let input = path25;
17063
17063
  const output = [];
17064
17064
  let nextSlash = -1;
17065
17065
  let len = 0;
@@ -17258,8 +17258,8 @@ var require_schemes = __commonJS({
17258
17258
  wsComponent.secure = void 0;
17259
17259
  }
17260
17260
  if (wsComponent.resourceName) {
17261
- const [path24, query] = wsComponent.resourceName.split("?");
17262
- wsComponent.path = path24 && path24 !== "/" ? path24 : void 0;
17261
+ const [path25, query] = wsComponent.resourceName.split("?");
17262
+ wsComponent.path = path25 && path25 !== "/" ? path25 : void 0;
17263
17263
  wsComponent.query = query;
17264
17264
  wsComponent.resourceName = void 0;
17265
17265
  }
@@ -20612,12 +20612,12 @@ var require_dist = __commonJS({
20612
20612
  throw new Error(`Unknown format "${name}"`);
20613
20613
  return f;
20614
20614
  };
20615
- function addFormats(ajv, list, fs22, exportName) {
20615
+ function addFormats(ajv, list, fs23, exportName) {
20616
20616
  var _a;
20617
20617
  var _b;
20618
20618
  (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
20619
20619
  for (const f of list)
20620
- ajv.addFormat(f, fs22[f]);
20620
+ ajv.addFormat(f, fs23[f]);
20621
20621
  }
20622
20622
  module.exports = exports = formatsPlugin;
20623
20623
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -21729,8 +21729,8 @@ var require_parseUtil = __commonJS({
21729
21729
  var errors_js_1 = require_errors2();
21730
21730
  var en_js_1 = __importDefault(require_en());
21731
21731
  var makeIssue2 = (params) => {
21732
- const { data, path: path24, errorMaps, issueData } = params;
21733
- const fullPath = [...path24, ...issueData.path || []];
21732
+ const { data, path: path25, errorMaps, issueData } = params;
21733
+ const fullPath = [...path25, ...issueData.path || []];
21734
21734
  const fullIssue = {
21735
21735
  ...issueData,
21736
21736
  path: fullPath
@@ -21884,11 +21884,11 @@ var require_types2 = __commonJS({
21884
21884
  var parseUtil_js_1 = require_parseUtil();
21885
21885
  var util_js_1 = require_util2();
21886
21886
  var ParseInputLazyPath2 = class {
21887
- constructor(parent, value, path24, key) {
21887
+ constructor(parent, value, path25, key) {
21888
21888
  this._cachedPath = [];
21889
21889
  this.parent = parent;
21890
21890
  this.data = value;
21891
- this._path = path24;
21891
+ this._path = path25;
21892
21892
  this._key = key;
21893
21893
  }
21894
21894
  get path() {
@@ -26389,8 +26389,8 @@ var init_stdio2 = __esm({
26389
26389
  // src/constants.ts
26390
26390
  import { createRequire } from "node:module";
26391
26391
  function resolveVersion() {
26392
- if ("3.23.5") {
26393
- return "3.23.5";
26392
+ if ("3.23.7") {
26393
+ return "3.23.7";
26394
26394
  }
26395
26395
  try {
26396
26396
  const require2 = createRequire(import.meta.url);
@@ -27826,7 +27826,7 @@ var init_http_backend = __esm({
27826
27826
  * in cloud mode we ignore it and use this.sessionId (the cloud session).
27827
27827
  */
27828
27828
  async registerPeer(peerId, _sessionId, cwd, label, clientVersion, mode, _channelSessionId, capabilities, workspaceId, threadId, peerSecret) {
27829
- const path24 = PATHS.peers.replace(":sessionId", this.sessionId);
27829
+ const path25 = PATHS.peers.replace(":sessionId", this.sessionId);
27830
27830
  const body = {
27831
27831
  peerId,
27832
27832
  cwd,
@@ -27857,7 +27857,7 @@ var init_http_backend = __esm({
27857
27857
  if (peerSecret !== void 0 && await relaySupports(this.http, "peer-ownership")) {
27858
27858
  body.peerSecret = peerSecret;
27859
27859
  }
27860
- return this.http.post(path24, body);
27860
+ return this.http.post(path25, body);
27861
27861
  }
27862
27862
  /**
27863
27863
  * Deregister a peer from the cloud session.
@@ -27869,9 +27869,9 @@ var init_http_backend = __esm({
27869
27869
  * local mail creds. A 404 (peer not found) resolves to `{ removed: false, ... }`, not a throw.
27870
27870
  */
27871
27871
  async deregisterPeer(peerId) {
27872
- const path24 = PATHS.peer.replace(":sessionId", this.sessionId).replace(":peerId", peerId);
27872
+ const path25 = PATHS.peer.replace(":sessionId", this.sessionId).replace(":peerId", peerId);
27873
27873
  try {
27874
- const headers = await this.http.delete(path24, {});
27874
+ const headers = await this.http.delete(path25, {});
27875
27875
  const mailboxDeprovisioned = headers.get(MAILBOX_DEPROVISIONED_HEADER) === "true";
27876
27876
  return { removed: true, mailboxDeprovisioned };
27877
27877
  } catch (err) {
@@ -27895,8 +27895,8 @@ var init_http_backend = __esm({
27895
27895
  * GET /api/sessions/:sessionId/peers
27896
27896
  */
27897
27897
  async listPeers() {
27898
- const path24 = PATHS.peers.replace(":sessionId", this.sessionId);
27899
- const result = await this.http.get(path24);
27898
+ const path25 = PATHS.peers.replace(":sessionId", this.sessionId);
27899
+ const result = await this.http.get(path25);
27900
27900
  return result.peers;
27901
27901
  }
27902
27902
  /**
@@ -27904,8 +27904,8 @@ var init_http_backend = __esm({
27904
27904
  * Calls the lightweight heartbeat endpoint on the cloud relay server.
27905
27905
  */
27906
27906
  async updateLastSeen(peerId) {
27907
- const path24 = PATHS.heartbeat.replace(":sessionId", this.sessionId);
27908
- await this.http.post(path24, { peerId });
27907
+ const path25 = PATHS.heartbeat.replace(":sessionId", this.sessionId);
27908
+ await this.http.post(path25, { peerId });
27909
27909
  }
27910
27910
  /**
27911
27911
  * Record a message in the cloud session.
@@ -27916,7 +27916,7 @@ var init_http_backend = __esm({
27916
27916
  * the input record to construct a full MessageRecord.
27917
27917
  */
27918
27918
  async recordMessage(record2) {
27919
- const path24 = PATHS.messages.replace(":sessionId", this.sessionId);
27919
+ const path25 = PATHS.messages.replace(":sessionId", this.sessionId);
27920
27920
  const body = {
27921
27921
  fromPeerId: record2.fromPeerId,
27922
27922
  toPeerId: record2.toPeerId,
@@ -27939,7 +27939,7 @@ var init_http_backend = __esm({
27939
27939
  if (record2.attachments && record2.attachments.length > 0) {
27940
27940
  body.attachments = record2.attachments;
27941
27941
  }
27942
- const resp = await this.http.post(path24, body);
27942
+ const resp = await this.http.post(path25, body);
27943
27943
  return {
27944
27944
  ...record2,
27945
27945
  id: resp.id,
@@ -27953,7 +27953,7 @@ var init_http_backend = __esm({
27953
27953
  * Supports optional peerId filter and limit (default 300).
27954
27954
  */
27955
27955
  async getHistory(peerId, limit, includeRelayEchoes, metadataOnly, dedupInferredEchoes) {
27956
- const path24 = PATHS.messages.replace(":sessionId", this.sessionId);
27956
+ const path25 = PATHS.messages.replace(":sessionId", this.sessionId);
27957
27957
  const query = {};
27958
27958
  if (peerId) {
27959
27959
  query.peerId = peerId;
@@ -27968,7 +27968,7 @@ var init_http_backend = __esm({
27968
27968
  if (dedupInferredEchoes) {
27969
27969
  query.dedupInferredEchoes = "true";
27970
27970
  }
27971
- const result = await this.http.get(path24, query);
27971
+ const result = await this.http.get(path25, query);
27972
27972
  return result.messages;
27973
27973
  }
27974
27974
  /**
@@ -27979,12 +27979,12 @@ var init_http_backend = __esm({
27979
27979
  * so that get-history shows the actual response (not null).
27980
27980
  */
27981
27981
  async updateMessageResponse(messageId, response, durationMs, pending) {
27982
- const path24 = PATHS.message.replace(":sessionId", this.sessionId).replace(":messageId", messageId);
27982
+ const path25 = PATHS.message.replace(":sessionId", this.sessionId).replace(":messageId", messageId);
27983
27983
  const body = { response, durationMs };
27984
27984
  if (pending === true) {
27985
27985
  body.pending = true;
27986
27986
  }
27987
- await this.http.patch(path24, body);
27987
+ await this.http.patch(path25, body);
27988
27988
  }
27989
27989
  /**
27990
27990
  * Validate a session.
@@ -28126,8 +28126,8 @@ var init_http_client = __esm({
28126
28126
  * Perform an authenticated GET request.
28127
28127
  * Appends query parameters to the URL if provided.
28128
28128
  */
28129
- async get(path24, query) {
28130
- const url = new URL(path24, this.baseUrl);
28129
+ async get(path25, query) {
28130
+ const url = new URL(path25, this.baseUrl);
28131
28131
  if (query) {
28132
28132
  for (const [k, v] of Object.entries(query)) {
28133
28133
  url.searchParams.set(k, v);
@@ -28142,8 +28142,8 @@ var init_http_client = __esm({
28142
28142
  /**
28143
28143
  * Perform an authenticated POST request with a JSON body.
28144
28144
  */
28145
- async post(path24, body) {
28146
- const url = new URL(path24, this.baseUrl);
28145
+ async post(path25, body) {
28146
+ const url = new URL(path25, this.baseUrl);
28147
28147
  const resp = await this.fetchWithTimeout(url, {
28148
28148
  method: "POST",
28149
28149
  headers: this.headers(),
@@ -28161,8 +28161,8 @@ var init_http_client = __esm({
28161
28161
  * Perform an authenticated PATCH request with a JSON body.
28162
28162
  * Used to update existing resources (e.g., message response fields).
28163
28163
  */
28164
- async patch(path24, body) {
28165
- const url = new URL(path24, this.baseUrl);
28164
+ async patch(path25, body) {
28165
+ const url = new URL(path25, this.baseUrl);
28166
28166
  const resp = await this.fetchWithTimeout(url, {
28167
28167
  method: "PATCH",
28168
28168
  headers: this.headers(),
@@ -28187,8 +28187,8 @@ var init_http_client = __esm({
28187
28187
  * "Malformed JSON in request body" 400 from cogent-server <=3.1.2 when
28188
28188
  * any client (including third-party tools) DELETEd a peer without a body.
28189
28189
  */
28190
- async delete(path24, body) {
28191
- const url = new URL(path24, this.baseUrl);
28190
+ async delete(path25, body) {
28191
+ const url = new URL(path25, this.baseUrl);
28192
28192
  const headers = {
28193
28193
  "Authorization": `Bearer ${this.token}`
28194
28194
  };
@@ -32393,14 +32393,14 @@ var init_ws_client = __esm({
32393
32393
  if (this.pollTimer) return;
32394
32394
  const poll = async () => {
32395
32395
  try {
32396
- const path24 = `/api/sessions/${this.opts.sessionId}/poll`;
32396
+ const path25 = `/api/sessions/${this.opts.sessionId}/poll`;
32397
32397
  const query = {
32398
32398
  peerId: this.opts.peerId
32399
32399
  };
32400
32400
  if (this.lastMessageId) {
32401
32401
  query.lastMessageId = this.lastMessageId;
32402
32402
  }
32403
- const result = await this.opts.http.get(path24, query);
32403
+ const result = await this.opts.http.get(path25, query);
32404
32404
  if (result.messages && result.messages.length > 0) {
32405
32405
  this.opts.onMessages(result.messages);
32406
32406
  this.lastMessageId = result.messages[result.messages.length - 1].id;
@@ -33741,6 +33741,162 @@ var init_wake_ownership = __esm({
33741
33741
  }
33742
33742
  });
33743
33743
 
33744
+ // src/services/stale-bridge-reaper.ts
33745
+ import { execFileSync as execFileSync2 } from "node:child_process";
33746
+ import fs18 from "node:fs";
33747
+ import path19 from "node:path";
33748
+ function isBridgeCommand(argv) {
33749
+ if (!argv) return false;
33750
+ if (/\.test\.|-test\.mjs|scripts\//.test(argv)) return false;
33751
+ return /\/bridge\/cogent-bridge\.mjs(\s|$)/.test(argv) || // plugin bundle (Claude + codex)
33752
+ /\/cogent-bridge(\s|$)/.test(argv) || // npx / global bin shim
33753
+ /@essentialai\/cogent-bridge(-bundled)?\/dist\/(cli|index)\.js(\s|$)/.test(argv);
33754
+ }
33755
+ function versionFromArgv(argv) {
33756
+ const m = argv.match(/\/cogent\/(\d+\.\d+\.\d+)\//);
33757
+ return m ? m[1] : null;
33758
+ }
33759
+ function listProcesses() {
33760
+ let out;
33761
+ try {
33762
+ out = execFileSync2("ps", ["-eo", "pid=,ppid=,lstart=,args="], {
33763
+ encoding: "utf-8",
33764
+ maxBuffer: 8 * 1024 * 1024,
33765
+ timeout: 1e4
33766
+ });
33767
+ } catch (err) {
33768
+ logger.debug(`stale-bridge-reaper: ps failed (${err.message})`);
33769
+ return [];
33770
+ }
33771
+ const procs = [];
33772
+ for (const line of out.split("\n")) {
33773
+ const m = line.match(/^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s+(.*)$/);
33774
+ if (!m) continue;
33775
+ const started = Date.parse(m[3]);
33776
+ procs.push({
33777
+ pid: Number(m[1]),
33778
+ ppid: Number(m[2]),
33779
+ startedAt: Number.isFinite(started) ? started : NaN,
33780
+ argv: m[4]
33781
+ });
33782
+ }
33783
+ return procs;
33784
+ }
33785
+ function processCwd(pid) {
33786
+ try {
33787
+ if (process.platform === "linux") {
33788
+ return path19.resolve(fs18.readlinkSync(`/proc/${pid}/cwd`));
33789
+ }
33790
+ if (process.platform === "darwin") {
33791
+ const out = execFileSync2("lsof", ["-a", "-d", "cwd", "-p", String(pid), "-Fn"], {
33792
+ encoding: "utf-8",
33793
+ timeout: 1e4,
33794
+ stdio: ["ignore", "pipe", "ignore"]
33795
+ });
33796
+ const line = out.split("\n").find((l) => l.startsWith("n"));
33797
+ return line ? path19.resolve(line.slice(1)) : null;
33798
+ }
33799
+ } catch {
33800
+ }
33801
+ return null;
33802
+ }
33803
+ function canonicalPath(p) {
33804
+ try {
33805
+ return fs18.realpathSync(path19.resolve(p));
33806
+ } catch {
33807
+ return path19.resolve(p);
33808
+ }
33809
+ }
33810
+ function ancestorsOf(pid, procs) {
33811
+ const byPid = new Map(procs.map((p) => [p.pid, p]));
33812
+ const seen = /* @__PURE__ */ new Set();
33813
+ let cur = byPid.get(pid)?.ppid;
33814
+ while (cur && cur > 1 && !seen.has(cur)) {
33815
+ seen.add(cur);
33816
+ cur = byPid.get(cur)?.ppid;
33817
+ }
33818
+ return seen;
33819
+ }
33820
+ function announcedPidsFor(cwd) {
33821
+ const pids = /* @__PURE__ */ new Set();
33822
+ try {
33823
+ const base = path19.dirname(bridgeDirFor(cwd, "x"));
33824
+ const prefix = path19.basename(bridgeDirFor(cwd, "x")).split(".")[0];
33825
+ for (const dir of fs18.readdirSync(base)) {
33826
+ if (!dir.startsWith(`${prefix}.`)) continue;
33827
+ const peerId = dir.slice(prefix.length + 1);
33828
+ for (const e of listLiveBridges(cwd, peerId)) pids.add(e.pid);
33829
+ }
33830
+ } catch {
33831
+ }
33832
+ return pids;
33833
+ }
33834
+ function findStaleBridges(cwd, procs = listProcesses(), opts = {}) {
33835
+ const selfPid = opts.selfPid ?? process.pid;
33836
+ const selfStartedAt = opts.selfStartedAt ?? Date.now() - Math.floor(process.uptime() * 1e3);
33837
+ const cwdOf = opts.cwdOf ?? processCwd;
33838
+ const announced = opts.announced ?? announcedPidsFor(cwd);
33839
+ const target = canonicalPath(cwd);
33840
+ const ancestors = ancestorsOf(selfPid, procs);
33841
+ const out = [];
33842
+ for (const p of procs) {
33843
+ if (p.pid === selfPid) continue;
33844
+ if (ancestors.has(p.pid)) continue;
33845
+ if (!isBridgeCommand(p.argv)) continue;
33846
+ if (announced.has(p.pid)) continue;
33847
+ if (!Number.isFinite(p.startedAt) || p.startedAt >= selfStartedAt) continue;
33848
+ const theirCwd = cwdOf(p.pid);
33849
+ if (!theirCwd || canonicalPath(theirCwd) !== target) continue;
33850
+ const ver = versionFromArgv(p.argv);
33851
+ out.push({
33852
+ proc: p,
33853
+ reason: `pid ${p.pid}${ver ? ` (plugin ${ver})` : ""} is a cogent bridge in this exact checkout, started ${new Date(p.startedAt).toISOString()} \u2014 before this process \u2014 and has not announced itself, so it predates self-supersession and would keep waking this session forever`
33854
+ });
33855
+ }
33856
+ return out;
33857
+ }
33858
+ function reaperEnabled(env = process.env) {
33859
+ const v = env.COGENT_REAP_STALE_BRIDGES;
33860
+ if (v === void 0 || v === "") return true;
33861
+ return !/^(0|false|no|off)$/i.test(v.trim());
33862
+ }
33863
+ function reapStaleBridges(cwd, opts = {}) {
33864
+ if (!reaperEnabled()) {
33865
+ logger.debug("stale-bridge-reaper: disabled by COGENT_REAP_STALE_BRIDGES");
33866
+ return [];
33867
+ }
33868
+ let candidates;
33869
+ try {
33870
+ candidates = findStaleBridges(cwd, listProcesses(), opts);
33871
+ } catch (err) {
33872
+ logger.warn(`stale-bridge-reaper: scan failed (${err.message}) \u2014 reaping nothing`);
33873
+ return [];
33874
+ }
33875
+ const reaped = [];
33876
+ for (const c2 of candidates) {
33877
+ logger.warn(`Cogent: terminating a stale bridge \u2014 ${c2.reason}`);
33878
+ try {
33879
+ process.kill(c2.proc.pid, "SIGTERM");
33880
+ reaped.push(c2);
33881
+ } catch (err) {
33882
+ logger.warn(`stale-bridge-reaper: could not signal pid ${c2.proc.pid}: ${err.message}`);
33883
+ }
33884
+ }
33885
+ if (reaped.length) {
33886
+ logger.warn(
33887
+ `Cogent: reaped ${reaped.length} stale bridge process(es) left behind by an earlier plugin version. They could not stand down on their own because they predate 3.23.4.`
33888
+ );
33889
+ }
33890
+ return reaped;
33891
+ }
33892
+ var init_stale_bridge_reaper = __esm({
33893
+ "src/services/stale-bridge-reaper.ts"() {
33894
+ "use strict";
33895
+ init_logger();
33896
+ init_wake_ownership();
33897
+ }
33898
+ });
33899
+
33744
33900
  // src/services/auto-relay.ts
33745
33901
  import { randomUUID as randomUUID2 } from "node:crypto";
33746
33902
  function buildStatusNotice(status, peerId, traceId) {
@@ -33883,6 +34039,7 @@ var init_auto_relay = __esm({
33883
34039
  init_wake_claim();
33884
34040
  init_wake_lock();
33885
34041
  init_wake_ownership();
34042
+ init_stale_bridge_reaper();
33886
34043
  init_constants();
33887
34044
  init_logger();
33888
34045
  init_npm_update_check();
@@ -33932,6 +34089,8 @@ var init_auto_relay = __esm({
33932
34089
  processing = false;
33933
34090
  /** Senders already told this bridge is superseded — one notice each, not one per message. */
33934
34091
  supersededNotified = /* @__PURE__ */ new Set();
34092
+ /** Reaping leftovers is a one-shot per process, not a per-registration action. */
34093
+ reapedStaleBridges = false;
33935
34094
  queue = [];
33936
34095
  // Message ids to be handled inject-only (full-group-chat awareness) rather than
33937
34096
  // full-wake+reply. Shares the `processing` lock + `queue` so an awareness inject
@@ -33980,6 +34139,14 @@ var init_auto_relay = __esm({
33980
34139
  );
33981
34140
  announceBridge(cwd, peerId, CLIENT_VERSION, getConfig().COGENT_ENDPOINT ?? "local");
33982
34141
  this.supersededNotified.clear();
34142
+ if (!this.reapedStaleBridges) {
34143
+ this.reapedStaleBridges = true;
34144
+ try {
34145
+ reapStaleBridges(cwd);
34146
+ } catch (err) {
34147
+ logger.debug(`stale-bridge reap skipped: ${err.message}`);
34148
+ }
34149
+ }
33983
34150
  }
33984
34151
  /**
33985
34152
  * Emit one content-free wake-trace line (ids/decisions/timings only — NEVER
@@ -35101,8 +35268,8 @@ __export(startup_exports, {
35101
35268
  triggerReRegistration: () => triggerReRegistration
35102
35269
  });
35103
35270
  import os14 from "node:os";
35104
- import path19 from "node:path";
35105
- import fs18 from "node:fs/promises";
35271
+ import path20 from "node:path";
35272
+ import fs19 from "node:fs/promises";
35106
35273
  import readline2 from "node:readline";
35107
35274
  import { execFile as execFile5 } from "node:child_process";
35108
35275
  import { promisify as promisify4 } from "node:util";
@@ -35120,7 +35287,7 @@ function bindInboxNotifier() {
35120
35287
  }
35121
35288
  async function loadPersistedConfig() {
35122
35289
  try {
35123
- const raw = await fs18.readFile(PERSIST_PATH, "utf-8");
35290
+ const raw = await fs19.readFile(PERSIST_PATH, "utf-8");
35124
35291
  return JSON.parse(raw);
35125
35292
  } catch {
35126
35293
  return {};
@@ -35128,7 +35295,7 @@ async function loadPersistedConfig() {
35128
35295
  }
35129
35296
  async function savePersistedConfig(config2) {
35130
35297
  try {
35131
- await fs18.writeFile(PERSIST_PATH, JSON.stringify(config2, null, 2) + "\n", "utf-8");
35298
+ await fs19.writeFile(PERSIST_PATH, JSON.stringify(config2, null, 2) + "\n", "utf-8");
35132
35299
  } catch (err) {
35133
35300
  const msg = err instanceof Error ? err.message : String(err);
35134
35301
  logger.warn(`Could not save config to ${PERSIST_PATH}: ${msg}`);
@@ -35163,11 +35330,11 @@ First run detected. Where should cogent-bridge store its data?
35163
35330
  });
35164
35331
  }
35165
35332
  async function validateStateDir(statePath) {
35166
- await fs18.mkdir(statePath, { recursive: true });
35167
- const testFile = path19.join(statePath, ".write-test");
35333
+ await fs19.mkdir(statePath, { recursive: true });
35334
+ const testFile = path20.join(statePath, ".write-test");
35168
35335
  try {
35169
- await fs18.writeFile(testFile, "test", "utf-8");
35170
- await fs18.unlink(testFile);
35336
+ await fs19.writeFile(testFile, "test", "utf-8");
35337
+ await fs19.unlink(testFile);
35171
35338
  } catch {
35172
35339
  throw new BridgeError(
35173
35340
  "STARTUP_FAILED" /* STARTUP_FAILED */,
@@ -35355,10 +35522,10 @@ async function runStartup() {
35355
35522
  if (envStatePath) {
35356
35523
  statePath = envStatePath;
35357
35524
  } else {
35358
- const defaultPath = path19.join(os14.homedir(), ".cogent");
35525
+ const defaultPath = path20.join(os14.homedir(), ".cogent");
35359
35526
  statePath = await firstRunPrompt(defaultPath);
35360
35527
  }
35361
- if (!envStatePath && statePath !== path19.join(os14.homedir(), ".cogent")) {
35528
+ if (!envStatePath && statePath !== path20.join(os14.homedir(), ".cogent")) {
35362
35529
  process.env.COGENT_STATE_PATH = statePath;
35363
35530
  } else if (!envStatePath) {
35364
35531
  process.env.COGENT_STATE_PATH = statePath;
@@ -35422,7 +35589,7 @@ async function runStartup() {
35422
35589
  }
35423
35590
  initLogger(
35424
35591
  config2.COGENT_LOG_LEVEL,
35425
- path19.join(config2.COGENT_STATE_PATH, "logs")
35592
+ path20.join(config2.COGENT_STATE_PATH, "logs")
35426
35593
  );
35427
35594
  if (isCloud && effectiveSessionId && effectiveToken) {
35428
35595
  cloudInbox = new MessageInbox();
@@ -35484,7 +35651,7 @@ var init_startup = __esm({
35484
35651
  init_auto_relay();
35485
35652
  UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
35486
35653
  execFileAsync3 = promisify4(execFile5);
35487
- PERSIST_PATH = path19.join(os14.homedir(), ".cogent-config.json");
35654
+ PERSIST_PATH = path20.join(os14.homedir(), ".cogent-config.json");
35488
35655
  legacyWarnEmitted = false;
35489
35656
  cloudWsClient = null;
35490
35657
  cloudInbox = null;
@@ -35499,12 +35666,12 @@ var init_startup = __esm({
35499
35666
 
35500
35667
  // src/cloud/mail-credential-store.ts
35501
35668
  import crypto9 from "node:crypto";
35502
- import fs19 from "node:fs/promises";
35503
- import path20 from "node:path";
35669
+ import fs20 from "node:fs/promises";
35670
+ import path21 from "node:path";
35504
35671
  import os15 from "node:os";
35505
35672
  function defaultMailCredentialPath(cwd = process.cwd()) {
35506
- const hash = crypto9.createHash("sha256").update(path20.resolve(cwd)).digest("hex").slice(0, 16);
35507
- return path20.join(os15.homedir(), ".cogent", "mail-credentials", `${hash}.json`);
35673
+ const hash = crypto9.createHash("sha256").update(path21.resolve(cwd)).digest("hex").slice(0, 16);
35674
+ return path21.join(os15.homedir(), ".cogent", "mail-credentials", `${hash}.json`);
35508
35675
  }
35509
35676
  function resolveMailCredentialPath(credentialPath) {
35510
35677
  if (credentialPath) return credentialPath;
@@ -35515,16 +35682,16 @@ function resolveMailCredentialPath(credentialPath) {
35515
35682
  async function loadMailCredentials(credentialPath) {
35516
35683
  const filePath = resolveMailCredentialPath(credentialPath);
35517
35684
  try {
35518
- return JSON.parse(await fs19.readFile(filePath, "utf-8"));
35685
+ return JSON.parse(await fs20.readFile(filePath, "utf-8"));
35519
35686
  } catch {
35520
35687
  return null;
35521
35688
  }
35522
35689
  }
35523
35690
  async function saveMailCredentials(creds, credentialPath) {
35524
35691
  const filePath = resolveMailCredentialPath(credentialPath);
35525
- await fs19.mkdir(path20.dirname(filePath), { recursive: true, mode: 448 });
35526
- await fs19.writeFile(filePath, JSON.stringify(creds, null, 2) + "\n", { encoding: "utf-8", mode: 384 });
35527
- await fs19.chmod(filePath, 384);
35692
+ await fs20.mkdir(path21.dirname(filePath), { recursive: true, mode: 448 });
35693
+ await fs20.writeFile(filePath, JSON.stringify(creds, null, 2) + "\n", { encoding: "utf-8", mode: 384 });
35694
+ await fs20.chmod(filePath, 384);
35528
35695
  }
35529
35696
  async function persistProvisionedMailbox(mailbox, credentialPath) {
35530
35697
  if (!mailbox?.address || !mailbox.password) return false;
@@ -35545,7 +35712,7 @@ async function persistProvisionedMailbox(mailbox, credentialPath) {
35545
35712
  async function clearMailCredentials(credentialPath) {
35546
35713
  const filePath = resolveMailCredentialPath(credentialPath);
35547
35714
  try {
35548
- await fs19.unlink(filePath);
35715
+ await fs20.unlink(filePath);
35549
35716
  } catch (err) {
35550
35717
  if (err.code !== "ENOENT") throw err;
35551
35718
  }
@@ -35694,19 +35861,60 @@ function registerRegisterPeerTool(server) {
35694
35861
  storedPeerSecret = void 0;
35695
35862
  }
35696
35863
  }
35697
- const peer = await backend.registerPeer(
35698
- peerId,
35699
- sessionId,
35700
- cwd,
35701
- label,
35702
- CLIENT_VERSION,
35703
- mode,
35704
- channelSessionId,
35705
- capabilities,
35706
- workspaceId,
35707
- threadId,
35708
- storedPeerSecret
35709
- );
35864
+ let peer;
35865
+ try {
35866
+ peer = await backend.registerPeer(
35867
+ peerId,
35868
+ sessionId,
35869
+ cwd,
35870
+ label,
35871
+ CLIENT_VERSION,
35872
+ mode,
35873
+ channelSessionId,
35874
+ capabilities,
35875
+ workspaceId,
35876
+ threadId,
35877
+ storedPeerSecret
35878
+ );
35879
+ } catch (regErr) {
35880
+ const msg = regErr instanceof Error ? regErr.message : String(regErr);
35881
+ let recovered;
35882
+ if (/PEER_NOT_YOURS/.test(msg) && isCloudMode()) {
35883
+ try {
35884
+ const creds = await loadCredentials();
35885
+ if (creds?.ownerToken && creds.ownerToken !== creds.token && creds.endpoint && creds.sessionId) {
35886
+ logger.warn(
35887
+ `register_peer: '${peerId}' is owned by an earlier token (its peerSecret was lost by a pre-3.23.5 re-join). Re-proving ownership with the stored owner token.`
35888
+ );
35889
+ const res = await fetch(`${creds.endpoint}/api/sessions/${creds.sessionId}/peers`, {
35890
+ method: "POST",
35891
+ headers: { "content-type": "application/json", authorization: `Bearer ${creds.ownerToken}` },
35892
+ body: JSON.stringify({
35893
+ peerId,
35894
+ cwd,
35895
+ label,
35896
+ type: "agent",
35897
+ clientVersion: CLIENT_VERSION,
35898
+ ...mode ? { mode } : {},
35899
+ ...capabilities ? { capabilities } : {}
35900
+ })
35901
+ });
35902
+ if (res.ok) {
35903
+ recovered = await res.json();
35904
+ const secret = recovered?.peerSecret;
35905
+ if (secret) {
35906
+ await saveCredentials({ ...creds, peerId, peerSecret: secret, savedAt: (/* @__PURE__ */ new Date()).toISOString() });
35907
+ logger.info(`register_peer: ownership reclaimed for '${peerId}'; a fresh peerSecret is stored.`);
35908
+ }
35909
+ }
35910
+ }
35911
+ } catch (recoverErr) {
35912
+ logger.debug(`register_peer: ownership recovery failed: ${recoverErr.message}`);
35913
+ }
35914
+ }
35915
+ if (!recovered) throw regErr;
35916
+ peer = recovered;
35917
+ }
35710
35918
  if (isCloudMode()) {
35711
35919
  try {
35712
35920
  const creds = await loadCredentials();
@@ -37223,7 +37431,12 @@ function registerJoinSessionTool(server) {
37223
37431
  if (prior && prior.endpoint === endpoint && prior.sessionId === data.sessionId) {
37224
37432
  carried = {
37225
37433
  ...prior.peerId ? { peerId: prior.peerId } : {},
37226
- ...prior.peerSecret ? { peerSecret: prior.peerSecret } : {}
37434
+ ...prior.peerSecret ? { peerSecret: prior.peerSecret } : {},
37435
+ // Keep the token that owns the peer. A re-join mints a NEW one, and ownership is
37436
+ // proven by the CREATING token (or its secret) — so overwriting this field is what
37437
+ // turned a lost peerSecret into a permanent lockout. Prefer an ownerToken we are
37438
+ // already carrying; only fall back to `prior.token` the first time.
37439
+ ...prior.ownerToken || prior.token ? { ownerToken: prior.ownerToken ?? prior.token } : {}
37227
37440
  };
37228
37441
  }
37229
37442
  } catch (err) {
@@ -37510,8 +37723,8 @@ var require_cookies = __commonJS({
37510
37723
  if (urlparts.hostname !== cookie.domain && (cookie.domain.charAt(0) !== "." || ("." + urlparts.hostname).substr(-cookie.domain.length) !== cookie.domain)) {
37511
37724
  return false;
37512
37725
  }
37513
- let path24 = this.getPath(urlparts.pathname);
37514
- if (path24.substr(0, cookie.path.length) !== cookie.path) {
37726
+ let path25 = this.getPath(urlparts.pathname);
37727
+ if (path25.substr(0, cookie.path.length) !== cookie.path) {
37515
37728
  return false;
37516
37729
  }
37517
37730
  if (cookie.secure && urlparts.protocol !== "https:") {
@@ -37571,16 +37784,16 @@ var require_cookies = __commonJS({
37571
37784
  * @returns {String} Normalized path
37572
37785
  */
37573
37786
  getPath(pathname) {
37574
- let path24 = (pathname || "/").split("/");
37575
- path24.pop();
37576
- path24 = path24.join("/").trim();
37577
- if (path24.charAt(0) !== "/") {
37578
- path24 = "/" + path24;
37787
+ let path25 = (pathname || "/").split("/");
37788
+ path25.pop();
37789
+ path25 = path25.join("/").trim();
37790
+ if (path25.charAt(0) !== "/") {
37791
+ path25 = "/" + path25;
37579
37792
  }
37580
- if (path24.substr(-1) !== "/") {
37581
- path24 += "/";
37793
+ if (path25.substr(-1) !== "/") {
37794
+ path25 += "/";
37582
37795
  }
37583
- return path24;
37796
+ return path25;
37584
37797
  }
37585
37798
  };
37586
37799
  module.exports = Cookies;
@@ -37881,7 +38094,7 @@ var require_shared = __commonJS({
37881
38094
  "use strict";
37882
38095
  var urllib = __require("url");
37883
38096
  var util2 = __require("util");
37884
- var fs22 = __require("fs");
38097
+ var fs23 = __require("fs");
37885
38098
  var nmfetch = require_fetch();
37886
38099
  var dns = __require("dns");
37887
38100
  var net = __require("net");
@@ -38267,7 +38480,7 @@ var require_shared = __commonJS({
38267
38480
  }
38268
38481
  return callback(null, parsedDataUri.data);
38269
38482
  } else if (content.path) {
38270
- return resolveStream(fs22.createReadStream(content.path), callback);
38483
+ return resolveStream(fs23.createReadStream(content.path), callback);
38271
38484
  }
38272
38485
  }
38273
38486
  if (typeof data[key].content === "string" && !["utf8", "usascii", "ascii"].includes(encoding)) {
@@ -38391,7 +38604,7 @@ var require_shared = __commonJS({
38391
38604
  var require_mime_types = __commonJS({
38392
38605
  "node_modules/nodemailer/lib/mime-funcs/mime-types.js"(exports, module) {
38393
38606
  "use strict";
38394
- var path24 = __require("path");
38607
+ var path25 = __require("path");
38395
38608
  var defaultMimeType = "application/octet-stream";
38396
38609
  var defaultExtension = "bin";
38397
38610
  var mimeTypes = /* @__PURE__ */ new Map([
@@ -40449,7 +40662,7 @@ var require_mime_types = __commonJS({
40449
40662
  if (!filename) {
40450
40663
  return defaultMimeType;
40451
40664
  }
40452
- let parsed = path24.parse(filename);
40665
+ let parsed = path25.parse(filename);
40453
40666
  let extension = (parsed.ext.substr(1) || parsed.name || "").split("?").shift().trim().toLowerCase();
40454
40667
  let value = defaultMimeType;
40455
40668
  if (extensions.has(extension)) {
@@ -41851,7 +42064,7 @@ var require_mime_node = __commonJS({
41851
42064
  "node_modules/nodemailer/lib/mime-node/index.js"(exports, module) {
41852
42065
  "use strict";
41853
42066
  var crypto12 = __require("crypto");
41854
- var fs22 = __require("fs");
42067
+ var fs23 = __require("fs");
41855
42068
  var punycode = require_punycode();
41856
42069
  var PassThrough = __require("stream").PassThrough;
41857
42070
  var shared = require_shared();
@@ -42566,7 +42779,7 @@ var require_mime_node = __commonJS({
42566
42779
  setImmediate(() => contentStream.emit("error", new Error("File access rejected for " + content.path)));
42567
42780
  return contentStream;
42568
42781
  }
42569
- return fs22.createReadStream(content.path);
42782
+ return fs23.createReadStream(content.path);
42570
42783
  } else if (content && typeof content.href === "string") {
42571
42784
  if (this.disableUrlAccess) {
42572
42785
  contentStream = new PassThrough();
@@ -43587,8 +43800,8 @@ var require_dkim = __commonJS({
43587
43800
  var RelaxedBody = require_relaxed_body();
43588
43801
  var sign = require_sign();
43589
43802
  var PassThrough = __require("stream").PassThrough;
43590
- var fs22 = __require("fs");
43591
- var path24 = __require("path");
43803
+ var fs23 = __require("fs");
43804
+ var path25 = __require("path");
43592
43805
  var crypto12 = __require("crypto");
43593
43806
  var DKIM_ALGO = "sha256";
43594
43807
  var MAX_MESSAGE_SIZE = 128 * 1024;
@@ -43602,7 +43815,7 @@ var require_dkim = __commonJS({
43602
43815
  this.chunks = [];
43603
43816
  this.chunklen = 0;
43604
43817
  this.readPos = 0;
43605
- this.cachePath = this.cacheDir ? path24.join(this.cacheDir, "message." + Date.now() + "-" + crypto12.randomBytes(14).toString("hex")) : false;
43818
+ this.cachePath = this.cacheDir ? path25.join(this.cacheDir, "message." + Date.now() + "-" + crypto12.randomBytes(14).toString("hex")) : false;
43606
43819
  this.cache = false;
43607
43820
  this.headers = false;
43608
43821
  this.bodyHash = false;
@@ -43622,10 +43835,10 @@ var require_dkim = __commonJS({
43622
43835
  if (!this.cache || !this.cachePath) {
43623
43836
  return;
43624
43837
  }
43625
- fs22.unlink(this.cachePath, () => false);
43838
+ fs23.unlink(this.cachePath, () => false);
43626
43839
  }
43627
43840
  createReadCache() {
43628
- this.cache = fs22.createReadStream(this.cachePath);
43841
+ this.cache = fs23.createReadStream(this.cachePath);
43629
43842
  this.cache.once("error", (err) => {
43630
43843
  this.cleanup();
43631
43844
  this.output.emit("error", err);
@@ -43681,7 +43894,7 @@ var require_dkim = __commonJS({
43681
43894
  }
43682
43895
  createWriteCache() {
43683
43896
  this.output.usingCache = true;
43684
- this.cache = fs22.createWriteStream(this.cachePath);
43897
+ this.cache = fs23.createWriteStream(this.cachePath);
43685
43898
  this.cache.once("error", (err) => {
43686
43899
  this.cleanup();
43687
43900
  this.relaxedBody.unpipe(this.cache);
@@ -48570,13 +48783,13 @@ var require_nodemailer = __commonJS({
48570
48783
  });
48571
48784
 
48572
48785
  // src/mail/mail-sender.ts
48573
- import fs20 from "node:fs/promises";
48574
- import path21 from "node:path";
48786
+ import fs21 from "node:fs/promises";
48787
+ import path22 from "node:path";
48575
48788
  async function buildAndSendMail(sender, creds, params) {
48576
48789
  const attachments = [];
48577
48790
  for (const p of params.attachmentPaths ?? []) {
48578
- const content = await fs20.readFile(p);
48579
- attachments.push({ filename: path21.basename(p), content });
48791
+ const content = await fs21.readFile(p);
48792
+ attachments.push({ filename: path22.basename(p), content });
48580
48793
  }
48581
48794
  const { messageId } = await sender.send({
48582
48795
  from: creds.address,
@@ -48965,8 +49178,8 @@ var require_req = __commonJS({
48965
49178
  if (req.originalUrl) {
48966
49179
  _req.url = req.originalUrl;
48967
49180
  } else {
48968
- const path24 = req.path;
48969
- _req.url = typeof path24 === "string" ? path24 : req.url ? req.url.path || req.url : void 0;
49181
+ const path25 = req.path;
49182
+ _req.url = typeof path25 === "string" ? path25 : req.url ? req.url.path || req.url : void 0;
48970
49183
  }
48971
49184
  if (req.query) {
48972
49185
  _req.query = req.query;
@@ -49131,14 +49344,14 @@ var require_redact = __commonJS({
49131
49344
  }
49132
49345
  return obj;
49133
49346
  }
49134
- function parsePath(path24) {
49347
+ function parsePath(path25) {
49135
49348
  const parts = [];
49136
49349
  let current = "";
49137
49350
  let inBrackets = false;
49138
49351
  let inQuotes = false;
49139
49352
  let quoteChar = "";
49140
- for (let i = 0; i < path24.length; i++) {
49141
- const char = path24[i];
49353
+ for (let i = 0; i < path25.length; i++) {
49354
+ const char = path25[i];
49142
49355
  if (!inBrackets && char === ".") {
49143
49356
  if (current) {
49144
49357
  parts.push(current);
@@ -49269,10 +49482,10 @@ var require_redact = __commonJS({
49269
49482
  return current;
49270
49483
  }
49271
49484
  function redactPaths(obj, paths, censor, remove = false) {
49272
- for (const path24 of paths) {
49273
- const parts = parsePath(path24);
49485
+ for (const path25 of paths) {
49486
+ const parts = parsePath(path25);
49274
49487
  if (parts.includes("*")) {
49275
- redactWildcardPath(obj, parts, censor, path24, remove);
49488
+ redactWildcardPath(obj, parts, censor, path25, remove);
49276
49489
  } else {
49277
49490
  if (remove) {
49278
49491
  removeKey(obj, parts);
@@ -49357,8 +49570,8 @@ var require_redact = __commonJS({
49357
49570
  }
49358
49571
  } else {
49359
49572
  if (afterWildcard.includes("*")) {
49360
- const wrappedCensor = typeof censor === "function" ? (value, path24) => {
49361
- const fullPath = [...pathArray.slice(0, pathLength), ...path24];
49573
+ const wrappedCensor = typeof censor === "function" ? (value, path25) => {
49574
+ const fullPath = [...pathArray.slice(0, pathLength), ...path25];
49362
49575
  return censor(value, fullPath);
49363
49576
  } : censor;
49364
49577
  redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove);
@@ -49393,8 +49606,8 @@ var require_redact = __commonJS({
49393
49606
  return null;
49394
49607
  }
49395
49608
  const pathStructure = /* @__PURE__ */ new Map();
49396
- for (const path24 of pathsToClone) {
49397
- const parts = parsePath(path24);
49609
+ for (const path25 of pathsToClone) {
49610
+ const parts = parsePath(path25);
49398
49611
  let current = pathStructure;
49399
49612
  for (let i = 0; i < parts.length; i++) {
49400
49613
  const part = parts[i];
@@ -49446,24 +49659,24 @@ var require_redact = __commonJS({
49446
49659
  }
49447
49660
  return cloneSelectively(obj, pathStructure);
49448
49661
  }
49449
- function validatePath(path24) {
49450
- if (typeof path24 !== "string") {
49662
+ function validatePath(path25) {
49663
+ if (typeof path25 !== "string") {
49451
49664
  throw new Error("Paths must be (non-empty) strings");
49452
49665
  }
49453
- if (path24 === "") {
49666
+ if (path25 === "") {
49454
49667
  throw new Error("Invalid redaction path ()");
49455
49668
  }
49456
- if (path24.includes("..")) {
49457
- throw new Error(`Invalid redaction path (${path24})`);
49669
+ if (path25.includes("..")) {
49670
+ throw new Error(`Invalid redaction path (${path25})`);
49458
49671
  }
49459
- if (path24.includes(",")) {
49460
- throw new Error(`Invalid redaction path (${path24})`);
49672
+ if (path25.includes(",")) {
49673
+ throw new Error(`Invalid redaction path (${path25})`);
49461
49674
  }
49462
49675
  let bracketCount = 0;
49463
49676
  let inQuotes = false;
49464
49677
  let quoteChar = "";
49465
- for (let i = 0; i < path24.length; i++) {
49466
- const char = path24[i];
49678
+ for (let i = 0; i < path25.length; i++) {
49679
+ const char = path25[i];
49467
49680
  if ((char === '"' || char === "'") && bracketCount > 0) {
49468
49681
  if (!inQuotes) {
49469
49682
  inQuotes = true;
@@ -49477,20 +49690,20 @@ var require_redact = __commonJS({
49477
49690
  } else if (char === "]" && !inQuotes) {
49478
49691
  bracketCount--;
49479
49692
  if (bracketCount < 0) {
49480
- throw new Error(`Invalid redaction path (${path24})`);
49693
+ throw new Error(`Invalid redaction path (${path25})`);
49481
49694
  }
49482
49695
  }
49483
49696
  }
49484
49697
  if (bracketCount !== 0) {
49485
- throw new Error(`Invalid redaction path (${path24})`);
49698
+ throw new Error(`Invalid redaction path (${path25})`);
49486
49699
  }
49487
49700
  }
49488
49701
  function validatePaths(paths) {
49489
49702
  if (!Array.isArray(paths)) {
49490
49703
  throw new TypeError("paths must be an array");
49491
49704
  }
49492
- for (const path24 of paths) {
49493
- validatePath(path24);
49705
+ for (const path25 of paths) {
49706
+ validatePath(path25);
49494
49707
  }
49495
49708
  }
49496
49709
  function slowRedact(options = {}) {
@@ -49658,8 +49871,8 @@ var require_redaction = __commonJS({
49658
49871
  if (shape[k] === null) {
49659
49872
  o[k] = (value) => topCensor(value, [k]);
49660
49873
  } else {
49661
- const wrappedCensor = typeof censor === "function" ? (value, path24) => {
49662
- return censor(value, [k, ...path24]);
49874
+ const wrappedCensor = typeof censor === "function" ? (value, path25) => {
49875
+ return censor(value, [k, ...path25]);
49663
49876
  } : censor;
49664
49877
  o[k] = Redact({
49665
49878
  paths: shape[k],
@@ -49877,10 +50090,10 @@ var require_atomic_sleep = __commonJS({
49877
50090
  var require_sonic_boom = __commonJS({
49878
50091
  "node_modules/sonic-boom/index.js"(exports, module) {
49879
50092
  "use strict";
49880
- var fs22 = __require("fs");
50093
+ var fs23 = __require("fs");
49881
50094
  var EventEmitter = __require("events");
49882
50095
  var inherits = __require("util").inherits;
49883
- var path24 = __require("path");
50096
+ var path25 = __require("path");
49884
50097
  var sleep4 = require_atomic_sleep();
49885
50098
  var assert2 = __require("assert");
49886
50099
  var BUSY_WRITE_TIMEOUT = 100;
@@ -49934,20 +50147,20 @@ var require_sonic_boom = __commonJS({
49934
50147
  const mode = sonic.mode;
49935
50148
  if (sonic.sync) {
49936
50149
  try {
49937
- if (sonic.mkdir) fs22.mkdirSync(path24.dirname(file), { recursive: true });
49938
- const fd = fs22.openSync(file, flags, mode);
50150
+ if (sonic.mkdir) fs23.mkdirSync(path25.dirname(file), { recursive: true });
50151
+ const fd = fs23.openSync(file, flags, mode);
49939
50152
  fileOpened(null, fd);
49940
50153
  } catch (err) {
49941
50154
  fileOpened(err);
49942
50155
  throw err;
49943
50156
  }
49944
50157
  } else if (sonic.mkdir) {
49945
- fs22.mkdir(path24.dirname(file), { recursive: true }, (err) => {
50158
+ fs23.mkdir(path25.dirname(file), { recursive: true }, (err) => {
49946
50159
  if (err) return fileOpened(err);
49947
- fs22.open(file, flags, mode, fileOpened);
50160
+ fs23.open(file, flags, mode, fileOpened);
49948
50161
  });
49949
50162
  } else {
49950
- fs22.open(file, flags, mode, fileOpened);
50163
+ fs23.open(file, flags, mode, fileOpened);
49951
50164
  }
49952
50165
  }
49953
50166
  function SonicBoom(opts) {
@@ -49988,8 +50201,8 @@ var require_sonic_boom = __commonJS({
49988
50201
  this.flush = flushBuffer;
49989
50202
  this.flushSync = flushBufferSync;
49990
50203
  this._actualWrite = actualWriteBuffer;
49991
- fsWriteSync = () => fs22.writeSync(this.fd, this._writingBuf);
49992
- fsWrite = () => fs22.write(this.fd, this._writingBuf, this.release);
50204
+ fsWriteSync = () => fs23.writeSync(this.fd, this._writingBuf);
50205
+ fsWrite = () => fs23.write(this.fd, this._writingBuf, this.release);
49993
50206
  } else if (contentMode === void 0 || contentMode === kContentModeUtf8) {
49994
50207
  this._writingBuf = "";
49995
50208
  this.write = write;
@@ -49998,15 +50211,15 @@ var require_sonic_boom = __commonJS({
49998
50211
  this._actualWrite = actualWrite;
49999
50212
  fsWriteSync = () => {
50000
50213
  if (Buffer.isBuffer(this._writingBuf)) {
50001
- return fs22.writeSync(this.fd, this._writingBuf);
50214
+ return fs23.writeSync(this.fd, this._writingBuf);
50002
50215
  }
50003
- return fs22.writeSync(this.fd, this._writingBuf, "utf8");
50216
+ return fs23.writeSync(this.fd, this._writingBuf, "utf8");
50004
50217
  };
50005
50218
  fsWrite = () => {
50006
50219
  if (Buffer.isBuffer(this._writingBuf)) {
50007
- return fs22.write(this.fd, this._writingBuf, this.release);
50220
+ return fs23.write(this.fd, this._writingBuf, this.release);
50008
50221
  }
50009
- return fs22.write(this.fd, this._writingBuf, "utf8", this.release);
50222
+ return fs23.write(this.fd, this._writingBuf, "utf8", this.release);
50010
50223
  };
50011
50224
  } else {
50012
50225
  throw new Error(`SonicBoom supports "${kContentModeUtf8}" and "${kContentModeBuffer}", but passed ${contentMode}`);
@@ -50063,7 +50276,7 @@ var require_sonic_boom = __commonJS({
50063
50276
  }
50064
50277
  }
50065
50278
  if (this._fsync) {
50066
- fs22.fsyncSync(this.fd);
50279
+ fs23.fsyncSync(this.fd);
50067
50280
  }
50068
50281
  const len = this._len;
50069
50282
  if (this._reopening) {
@@ -50177,7 +50390,7 @@ var require_sonic_boom = __commonJS({
50177
50390
  const onDrain = () => {
50178
50391
  if (!this._fsync) {
50179
50392
  try {
50180
- fs22.fsync(this.fd, (err) => {
50393
+ fs23.fsync(this.fd, (err) => {
50181
50394
  this._flushPending = false;
50182
50395
  cb(err);
50183
50396
  });
@@ -50279,7 +50492,7 @@ var require_sonic_boom = __commonJS({
50279
50492
  const fd = this.fd;
50280
50493
  this.once("ready", () => {
50281
50494
  if (fd !== this.fd) {
50282
- fs22.close(fd, (err) => {
50495
+ fs23.close(fd, (err) => {
50283
50496
  if (err) {
50284
50497
  return this.emit("error", err);
50285
50498
  }
@@ -50328,7 +50541,7 @@ var require_sonic_boom = __commonJS({
50328
50541
  buf = this._bufs[0];
50329
50542
  }
50330
50543
  try {
50331
- const n = Buffer.isBuffer(buf) ? fs22.writeSync(this.fd, buf) : fs22.writeSync(this.fd, buf, "utf8");
50544
+ const n = Buffer.isBuffer(buf) ? fs23.writeSync(this.fd, buf) : fs23.writeSync(this.fd, buf, "utf8");
50332
50545
  const releasedBufObj = releaseWritingBuf(buf, this._len, n);
50333
50546
  buf = releasedBufObj.writingBuf;
50334
50547
  this._len = releasedBufObj.len;
@@ -50344,7 +50557,7 @@ var require_sonic_boom = __commonJS({
50344
50557
  }
50345
50558
  }
50346
50559
  try {
50347
- fs22.fsyncSync(this.fd);
50560
+ fs23.fsyncSync(this.fd);
50348
50561
  } catch {
50349
50562
  }
50350
50563
  }
@@ -50365,7 +50578,7 @@ var require_sonic_boom = __commonJS({
50365
50578
  buf = mergeBuf(this._bufs[0], this._lens[0]);
50366
50579
  }
50367
50580
  try {
50368
- const n = fs22.writeSync(this.fd, buf);
50581
+ const n = fs23.writeSync(this.fd, buf);
50369
50582
  buf = buf.subarray(n);
50370
50583
  this._len = Math.max(this._len - n, 0);
50371
50584
  if (buf.length <= 0) {
@@ -50393,13 +50606,13 @@ var require_sonic_boom = __commonJS({
50393
50606
  this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || "";
50394
50607
  if (this.sync) {
50395
50608
  try {
50396
- const written = Buffer.isBuffer(this._writingBuf) ? fs22.writeSync(this.fd, this._writingBuf) : fs22.writeSync(this.fd, this._writingBuf, "utf8");
50609
+ const written = Buffer.isBuffer(this._writingBuf) ? fs23.writeSync(this.fd, this._writingBuf) : fs23.writeSync(this.fd, this._writingBuf, "utf8");
50397
50610
  release(null, written);
50398
50611
  } catch (err) {
50399
50612
  release(err);
50400
50613
  }
50401
50614
  } else {
50402
- fs22.write(this.fd, this._writingBuf, release);
50615
+ fs23.write(this.fd, this._writingBuf, release);
50403
50616
  }
50404
50617
  }
50405
50618
  function actualWriteBuffer() {
@@ -50408,7 +50621,7 @@ var require_sonic_boom = __commonJS({
50408
50621
  this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift());
50409
50622
  if (this.sync) {
50410
50623
  try {
50411
- const written = fs22.writeSync(this.fd, this._writingBuf);
50624
+ const written = fs23.writeSync(this.fd, this._writingBuf);
50412
50625
  release(null, written);
50413
50626
  } catch (err) {
50414
50627
  release(err);
@@ -50417,7 +50630,7 @@ var require_sonic_boom = __commonJS({
50417
50630
  if (kCopyBuffer) {
50418
50631
  this._writingBuf = Buffer.from(this._writingBuf);
50419
50632
  }
50420
- fs22.write(this.fd, this._writingBuf, release);
50633
+ fs23.write(this.fd, this._writingBuf, release);
50421
50634
  }
50422
50635
  }
50423
50636
  function actualClose(sonic) {
@@ -50433,12 +50646,12 @@ var require_sonic_boom = __commonJS({
50433
50646
  sonic._lens = [];
50434
50647
  assert2(typeof sonic.fd === "number", `sonic.fd must be a number, got ${typeof sonic.fd}`);
50435
50648
  try {
50436
- fs22.fsync(sonic.fd, closeWrapped);
50649
+ fs23.fsync(sonic.fd, closeWrapped);
50437
50650
  } catch {
50438
50651
  }
50439
50652
  function closeWrapped() {
50440
50653
  if (sonic.fd !== 1 && sonic.fd !== 2) {
50441
- fs22.close(sonic.fd, done);
50654
+ fs23.close(sonic.fd, done);
50442
50655
  } else {
50443
50656
  done();
50444
50657
  }
@@ -51274,15 +51487,15 @@ var require_transport = __commonJS({
51274
51487
  if (!unquoted) {
51275
51488
  return false;
51276
51489
  }
51277
- let path24 = unquoted;
51278
- if (path24.startsWith("file://")) {
51490
+ let path25 = unquoted;
51491
+ if (path25.startsWith("file://")) {
51279
51492
  try {
51280
- path24 = fileURLToPath(path24);
51493
+ path25 = fileURLToPath(path25);
51281
51494
  } catch {
51282
51495
  return false;
51283
51496
  }
51284
51497
  }
51285
- return isAbsolute(path24) && !existsSync(path24);
51498
+ return isAbsolute(path25) && !existsSync(path25);
51286
51499
  }
51287
51500
  function stripQuotes(value) {
51288
51501
  const first = value[0];
@@ -85349,15 +85562,15 @@ var require_tools2 = __commonJS({
85349
85562
  * @param {String} path - Mailbox path to encode
85350
85563
  * @returns {String} Encoded mailbox path
85351
85564
  */
85352
- encodePath(connection, path24) {
85353
- path24 = (path24 || "").toString();
85354
- if (!connection.enabled.has("UTF8=ACCEPT") && !tools.isRev2Active(connection) && /[&\x00-\x08\x0b-\x0c\x0e-\x1f\u0080-\uffff]/.test(path24)) {
85565
+ encodePath(connection, path25) {
85566
+ path25 = (path25 || "").toString();
85567
+ if (!connection.enabled.has("UTF8=ACCEPT") && !tools.isRev2Active(connection) && /[&\x00-\x08\x0b-\x0c\x0e-\x1f\u0080-\uffff]/.test(path25)) {
85355
85568
  try {
85356
- path24 = iconv.encode(path24, "utf-7-imap").toString();
85569
+ path25 = iconv.encode(path25, "utf-7-imap").toString();
85357
85570
  } catch {
85358
85571
  }
85359
85572
  }
85360
- return path24;
85573
+ return path25;
85361
85574
  },
85362
85575
  /**
85363
85576
  * Decodes a mailbox path from modified UTF-7 if the server does not support UTF8=ACCEPT.
@@ -85366,15 +85579,15 @@ var require_tools2 = __commonJS({
85366
85579
  * @param {String} path - Mailbox path to decode
85367
85580
  * @returns {String} Decoded mailbox path
85368
85581
  */
85369
- decodePath(connection, path24) {
85370
- path24 = (path24 || "").toString();
85371
- if (!connection.enabled.has("UTF8=ACCEPT") && !tools.isRev2Active(connection) && /[&]/.test(path24)) {
85582
+ decodePath(connection, path25) {
85583
+ path25 = (path25 || "").toString();
85584
+ if (!connection.enabled.has("UTF8=ACCEPT") && !tools.isRev2Active(connection) && /[&]/.test(path25)) {
85372
85585
  try {
85373
- path24 = iconv.decode(Buffer.from(path24), "utf-7-imap").toString();
85586
+ path25 = iconv.decode(Buffer.from(path25), "utf-7-imap").toString();
85374
85587
  } catch {
85375
85588
  }
85376
85589
  }
85377
- return path24;
85590
+ return path25;
85378
85591
  },
85379
85592
  /**
85380
85593
  * Normalizes a mailbox path by joining array segments with the namespace delimiter,
@@ -85385,17 +85598,17 @@ var require_tools2 = __commonJS({
85385
85598
  * @param {Boolean} [skipNamespace] - If true, skips prepending the namespace prefix
85386
85599
  * @returns {String} Normalized mailbox path
85387
85600
  */
85388
- normalizePath(connection, path24, skipNamespace) {
85389
- if (Array.isArray(path24)) {
85390
- path24 = path24.join(connection.namespace && connection.namespace.delimiter || "");
85601
+ normalizePath(connection, path25, skipNamespace) {
85602
+ if (Array.isArray(path25)) {
85603
+ path25 = path25.join(connection.namespace && connection.namespace.delimiter || "");
85391
85604
  }
85392
- if (path24.toUpperCase() === "INBOX") {
85605
+ if (path25.toUpperCase() === "INBOX") {
85393
85606
  return "INBOX";
85394
85607
  }
85395
- if (!skipNamespace && connection.namespace && connection.namespace.prefix && !path24.startsWith(connection.namespace.prefix)) {
85396
- path24 = connection.namespace.prefix + path24;
85608
+ if (!skipNamespace && connection.namespace && connection.namespace.prefix && !path25.startsWith(connection.namespace.prefix)) {
85609
+ path25 = connection.namespace.prefix + path25;
85397
85610
  }
85398
- return path24;
85611
+ return path25;
85399
85612
  },
85400
85613
  /**
85401
85614
  * Compares two mailbox paths for equality after normalization.
@@ -85726,14 +85939,14 @@ var require_tools2 = __commonJS({
85726
85939
  }
85727
85940
  }
85728
85941
  if (map.emailId || map.uid) {
85729
- let path24 = mailbox.path;
85730
- if (/[\u0080-\uffff]/.test(path24)) {
85942
+ let path25 = mailbox.path;
85943
+ if (/[\u0080-\uffff]/.test(path25)) {
85731
85944
  try {
85732
- path24 = iconv.encode(path24, "utf-7-imap").toString();
85945
+ path25 = iconv.encode(path25, "utf-7-imap").toString();
85733
85946
  } catch {
85734
85947
  }
85735
85948
  }
85736
- map.id = map.emailId || createHash2("md5").update([path24, mailbox.uidValidity?.toString() || "", map.uid.toString()].join(":")).digest("hex");
85949
+ map.id = map.emailId || createHash2("md5").update([path25, mailbox.uidValidity?.toString() || "", map.uid.toString()].join(":")).digest("hex");
85737
85950
  }
85738
85951
  if (map.flags) {
85739
85952
  let flagColor = tools.getFlagColor(map.flags);
@@ -85908,16 +86121,16 @@ var require_tools2 = __commonJS({
85908
86121
  * @returns {Object} Parsed body structure tree with part numbers, types, parameters, and child nodes
85909
86122
  */
85910
86123
  parseBodystructure(entry) {
85911
- let walk = (node, path24) => {
85912
- path24 = path24 || [];
86124
+ let walk = (node, path25) => {
86125
+ path25 = path25 || [];
85913
86126
  let curNode = {}, i = 0, part = 0;
85914
- if (path24.length) {
85915
- curNode.part = path24.join(".");
86127
+ if (path25.length) {
86128
+ curNode.part = path25.join(".");
85916
86129
  }
85917
86130
  if (Array.isArray(node[0])) {
85918
86131
  curNode.childNodes = [];
85919
86132
  while (Array.isArray(node[i])) {
85920
- curNode.childNodes.push(walk(node[i], path24.concat(++part)));
86133
+ curNode.childNodes.push(walk(node[i], path25.concat(++part)));
85921
86134
  i++;
85922
86135
  }
85923
86136
  curNode.type = "multipart/" + ((node[i++] || {}).value || "").toString().toLowerCase();
@@ -85960,7 +86173,7 @@ var require_tools2 = __commonJS({
85960
86173
  // the encapsulated message shares the part number with its wrapper.
85961
86174
  // Distinction is via suffixes: path.MIME = wrapper headers,
85962
86175
  // path.HEADER = encapsulated message headers.
85963
- walk(node[i], path24)
86176
+ walk(node[i], path25)
85964
86177
  ];
85965
86178
  }
85966
86179
  i++;
@@ -87922,14 +88135,14 @@ var require_select = __commonJS({
87922
88135
  // update into a silent no-op for the rest of the session.
87923
88136
  permanentflags: { key: "permanentFlags", parse: (value) => Array.isArray(value) && new Set(value) }
87924
88137
  });
87925
- module.exports = async (connection, path24, options) => {
88138
+ module.exports = async (connection, path25, options) => {
87926
88139
  if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
87927
88140
  return;
87928
88141
  }
87929
88142
  options = options || {};
87930
- path24 = normalizePath(connection, path24);
87931
- if (!connection.folders.has(path24)) {
87932
- let folders = await connection.run("LIST", "", path24);
88143
+ path25 = normalizePath(connection, path25);
88144
+ if (!connection.folders.has(path25)) {
88145
+ let folders = await connection.run("LIST", "", path25);
87933
88146
  if (!folders) {
87934
88147
  throw new Error("Failed to fetch folders");
87935
88148
  }
@@ -87937,10 +88150,10 @@ var require_select = __commonJS({
87937
88150
  connection.folders.set(folder.path, folder);
87938
88151
  });
87939
88152
  }
87940
- let folderListData = connection.folders.has(path24) ? connection.folders.get(path24) : false;
88153
+ let folderListData = connection.folders.has(path25) ? connection.folders.get(path25) : false;
87941
88154
  let response;
87942
88155
  try {
87943
- let map = { path: path24 };
88156
+ let map = { path: path25 };
87944
88157
  if (folderListData) {
87945
88158
  ["delimiter", "specialUse", "subscribed", "listed"].forEach((key) => {
87946
88159
  if (folderListData[key]) {
@@ -87959,7 +88172,7 @@ var require_select = __commonJS({
87959
88172
  ]);
87960
88173
  map.qresync = true;
87961
88174
  }
87962
- let encodedPath = encodePath(connection, path24);
88175
+ let encodedPath = encodePath(connection, path25);
87963
88176
  let selectCommand = {
87964
88177
  command: !options.readOnly ? "SELECT" : "EXAMINE",
87965
88178
  /* c8 ignore next */
@@ -88019,12 +88232,12 @@ var require_select = __commonJS({
88019
88232
  // since the client's last known state. Only received when QRESYNC was requested.
88020
88233
  // A dummy mailbox object is passed because the mailbox isn't officially open yet.
88021
88234
  VANISHED: async (untagged) => {
88022
- await connection.untaggedVanished(untagged, { path: path24, uidNext: false, uidValidity: false });
88235
+ await connection.untaggedVanished(untagged, { path: path25, uidNext: false, uidValidity: false });
88023
88236
  },
88024
88237
  // Untagged FETCH during SELECT/EXAMINE: only occurs with QRESYNC, delivering
88025
88238
  // updated flags for messages that changed since the client's last modseq.
88026
88239
  FETCH: async (untagged) => {
88027
- await connection.untaggedFetch(untagged, { path: path24, uidNext: false, uidValidity: false });
88240
+ await connection.untaggedFetch(untagged, { path: path25, uidNext: false, uidValidity: false });
88028
88241
  }
88029
88242
  }
88030
88243
  });
@@ -88038,13 +88251,13 @@ var require_select = __commonJS({
88038
88251
  }
88039
88252
  let currentMailbox = connection.mailbox;
88040
88253
  connection.mailbox = false;
88041
- if (currentMailbox && currentMailbox.path !== path24) {
88254
+ if (currentMailbox && currentMailbox.path !== path25) {
88042
88255
  connection.emit("mailboxClose", currentMailbox);
88043
88256
  }
88044
88257
  connection.mailbox = map;
88045
88258
  connection.currentSelectCommand = selectCommand;
88046
88259
  connection.state = connection.states.SELECTED;
88047
- if (!currentMailbox || currentMailbox.path !== path24) {
88260
+ if (!currentMailbox || currentMailbox.path !== path25) {
88048
88261
  connection.emit("mailboxOpen", connection.mailbox);
88049
88262
  }
88050
88263
  response.next();
@@ -88259,17 +88472,17 @@ var require_create = __commonJS({
88259
88472
  "node_modules/imapflow/lib/commands/create.js"(exports, module) {
88260
88473
  "use strict";
88261
88474
  var { encodePath, normalizePath, getStatusCode, enhanceCommandError } = require_tools2();
88262
- module.exports = async (connection, path24) => {
88475
+ module.exports = async (connection, path25) => {
88263
88476
  if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
88264
88477
  return;
88265
88478
  }
88266
- path24 = normalizePath(connection, path24);
88479
+ path25 = normalizePath(connection, path25);
88267
88480
  let response;
88268
88481
  try {
88269
88482
  let map = {
88270
- path: path24
88483
+ path: path25
88271
88484
  };
88272
- response = await connection.exec("CREATE", [{ type: "ATOM", value: encodePath(connection, path24) }]);
88485
+ response = await connection.exec("CREATE", [{ type: "ATOM", value: encodePath(connection, path25) }]);
88273
88486
  let section = response.response.attributes && response.response.attributes[0] && response.response.attributes[0].section && response.response.attributes[0].section.length ? response.response.attributes[0].section : false;
88274
88487
  if (section) {
88275
88488
  let key;
@@ -88295,13 +88508,13 @@ var require_create = __commonJS({
88295
88508
  }
88296
88509
  map.created = true;
88297
88510
  response.next();
88298
- await connection.run("SUBSCRIBE", path24);
88511
+ await connection.run("SUBSCRIBE", path25);
88299
88512
  return map;
88300
88513
  } catch (err) {
88301
88514
  let errorCode = getStatusCode(err.response);
88302
88515
  if (errorCode === "ALREADYEXISTS") {
88303
88516
  return {
88304
- path: path24,
88517
+ path: path25,
88305
88518
  created: false
88306
88519
  };
88307
88520
  }
@@ -88318,20 +88531,20 @@ var require_delete = __commonJS({
88318
88531
  "node_modules/imapflow/lib/commands/delete.js"(exports, module) {
88319
88532
  "use strict";
88320
88533
  var { encodePath, normalizePath, enhanceCommandError } = require_tools2();
88321
- module.exports = async (connection, path24) => {
88534
+ module.exports = async (connection, path25) => {
88322
88535
  if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
88323
88536
  return;
88324
88537
  }
88325
- path24 = normalizePath(connection, path24);
88326
- if (connection.state === connection.states.SELECTED && connection.mailbox.path === path24) {
88538
+ path25 = normalizePath(connection, path25);
88539
+ if (connection.state === connection.states.SELECTED && connection.mailbox.path === path25) {
88327
88540
  await connection.run("CLOSE");
88328
88541
  }
88329
88542
  let response;
88330
88543
  try {
88331
88544
  let map = {
88332
- path: path24
88545
+ path: path25
88333
88546
  };
88334
- response = await connection.exec("DELETE", [{ type: "ATOM", value: encodePath(connection, path24) }]);
88547
+ response = await connection.exec("DELETE", [{ type: "ATOM", value: encodePath(connection, path25) }]);
88335
88548
  response.next();
88336
88549
  return map;
88337
88550
  } catch (err) {
@@ -88348,23 +88561,23 @@ var require_rename = __commonJS({
88348
88561
  "node_modules/imapflow/lib/commands/rename.js"(exports, module) {
88349
88562
  "use strict";
88350
88563
  var { encodePath, normalizePath, enhanceCommandError } = require_tools2();
88351
- module.exports = async (connection, path24, newPath) => {
88564
+ module.exports = async (connection, path25, newPath) => {
88352
88565
  if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
88353
88566
  return;
88354
88567
  }
88355
- path24 = normalizePath(connection, path24);
88568
+ path25 = normalizePath(connection, path25);
88356
88569
  newPath = normalizePath(connection, newPath);
88357
- if (connection.state === connection.states.SELECTED && connection.mailbox.path === path24) {
88570
+ if (connection.state === connection.states.SELECTED && connection.mailbox.path === path25) {
88358
88571
  await connection.run("CLOSE");
88359
88572
  }
88360
88573
  let response;
88361
88574
  try {
88362
88575
  let map = {
88363
- path: path24,
88576
+ path: path25,
88364
88577
  newPath
88365
88578
  };
88366
88579
  response = await connection.exec("RENAME", [
88367
- { type: "ATOM", value: encodePath(connection, path24) },
88580
+ { type: "ATOM", value: encodePath(connection, path25) },
88368
88581
  { type: "ATOM", value: encodePath(connection, newPath) }
88369
88582
  ]);
88370
88583
  response.next();
@@ -88411,14 +88624,14 @@ var require_subscribe = __commonJS({
88411
88624
  "node_modules/imapflow/lib/commands/subscribe.js"(exports, module) {
88412
88625
  "use strict";
88413
88626
  var { encodePath, normalizePath, enhanceCommandError } = require_tools2();
88414
- module.exports = async (connection, path24) => {
88627
+ module.exports = async (connection, path25) => {
88415
88628
  if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
88416
88629
  return;
88417
88630
  }
88418
- path24 = normalizePath(connection, path24);
88631
+ path25 = normalizePath(connection, path25);
88419
88632
  let response;
88420
88633
  try {
88421
- response = await connection.exec("SUBSCRIBE", [{ type: "ATOM", value: encodePath(connection, path24) }]);
88634
+ response = await connection.exec("SUBSCRIBE", [{ type: "ATOM", value: encodePath(connection, path25) }]);
88422
88635
  response.next();
88423
88636
  return true;
88424
88637
  } catch (err) {
@@ -88435,14 +88648,14 @@ var require_unsubscribe = __commonJS({
88435
88648
  "node_modules/imapflow/lib/commands/unsubscribe.js"(exports, module) {
88436
88649
  "use strict";
88437
88650
  var { encodePath, normalizePath, enhanceCommandError } = require_tools2();
88438
- module.exports = async (connection, path24) => {
88651
+ module.exports = async (connection, path25) => {
88439
88652
  if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
88440
88653
  return;
88441
88654
  }
88442
- path24 = normalizePath(connection, path24);
88655
+ path25 = normalizePath(connection, path25);
88443
88656
  let response;
88444
88657
  try {
88445
- response = await connection.exec("UNSUBSCRIBE", [{ type: "ATOM", value: encodePath(connection, path24) }]);
88658
+ response = await connection.exec("UNSUBSCRIBE", [{ type: "ATOM", value: encodePath(connection, path25) }]);
88446
88659
  response.next();
88447
88660
  return true;
88448
88661
  } catch (err) {
@@ -89248,11 +89461,11 @@ var require_status = __commonJS({
89248
89461
  var { encodePath, normalizePath, buildStatusQueryAttributes, isRev2Active } = require_tools2();
89249
89462
  var { parseStatusList } = require_status_fields();
89250
89463
  var MAILBOX_UPDATERS = {
89251
- messages: (value, connection, path24) => {
89464
+ messages: (value, connection, path25) => {
89252
89465
  let prevCount = connection.mailbox.exists;
89253
89466
  if (prevCount !== value) {
89254
89467
  connection.mailbox.exists = value;
89255
- connection.emit("exists", { path: path24, count: value, prevCount });
89468
+ connection.emit("exists", { path: path25, count: value, prevCount });
89256
89469
  }
89257
89470
  },
89258
89471
  uidNext: (value, connection) => {
@@ -89262,28 +89475,28 @@ var require_status = __commonJS({
89262
89475
  connection.mailbox.highestModseq = value;
89263
89476
  }
89264
89477
  };
89265
- module.exports = async (connection, path24, query) => {
89266
- if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state) || !path24) {
89478
+ module.exports = async (connection, path25, query) => {
89479
+ if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state) || !path25) {
89267
89480
  return false;
89268
89481
  }
89269
- path24 = normalizePath(connection, path24);
89270
- let encodedPath = encodePath(connection, path24);
89482
+ path25 = normalizePath(connection, path25);
89483
+ let encodedPath = encodePath(connection, path25);
89271
89484
  let attributes = [{ type: encodedPath.indexOf("&") >= 0 ? "STRING" : "ATOM", value: encodedPath }];
89272
89485
  let queryAttributes = buildStatusQueryAttributes(connection, query);
89273
89486
  let syntheticRecent = query && query.recent && isRev2Active(connection);
89274
89487
  if (!queryAttributes.length) {
89275
- return syntheticRecent ? { path: path24, recent: 0 } : false;
89488
+ return syntheticRecent ? { path: path25, recent: 0 } : false;
89276
89489
  }
89277
89490
  attributes.push(queryAttributes);
89278
89491
  let response;
89279
89492
  try {
89280
- let map = { path: path24 };
89493
+ let map = { path: path25 };
89281
89494
  response = await connection.exec("STATUS", attributes, {
89282
89495
  untagged: {
89283
89496
  // STATUS response: * STATUS <mailbox> (<key> <value> <key> <value> ...)
89284
89497
  // Parsed as alternating key-value pairs (i % 2 pattern).
89285
89498
  STATUS: async (untagged) => {
89286
- let updateCurrent = connection.state === connection.states.SELECTED && path24 === connection.mailbox.path;
89499
+ let updateCurrent = connection.state === connection.states.SELECTED && path25 === connection.mailbox.path;
89287
89500
  let list = untagged.attributes && Array.isArray(untagged.attributes[1]) ? untagged.attributes[1] : false;
89288
89501
  if (!list) {
89289
89502
  return;
@@ -89291,7 +89504,7 @@ var require_status = __commonJS({
89291
89504
  parseStatusList(list, (key, value) => {
89292
89505
  map[key] = value;
89293
89506
  if (updateCurrent && MAILBOX_UPDATERS[key]) {
89294
- MAILBOX_UPDATERS[key](value, connection, path24);
89507
+ MAILBOX_UPDATERS[key](value, connection, path25);
89295
89508
  }
89296
89509
  });
89297
89510
  }
@@ -89304,9 +89517,9 @@ var require_status = __commonJS({
89304
89517
  return map;
89305
89518
  } catch (err) {
89306
89519
  if (err.responseStatus === "NO") {
89307
- let folders = await connection.run("LIST", "", path24, { listOnly: true });
89520
+ let folders = await connection.run("LIST", "", path25, { listOnly: true });
89308
89521
  if (folders && !folders.length) {
89309
- let error2 = new Error(`Mailbox doesn't exist: ${path24}`);
89522
+ let error2 = new Error(`Mailbox doesn't exist: ${path25}`);
89310
89523
  error2.code = "NotFound";
89311
89524
  error2.response = err;
89312
89525
  throw error2;
@@ -89453,15 +89666,15 @@ var require_quota = __commonJS({
89453
89666
  "node_modules/imapflow/lib/commands/quota.js"(exports, module) {
89454
89667
  "use strict";
89455
89668
  var { encodePath, normalizePath, enhanceCommandError, parseUintValue, isUnsafeKey } = require_tools2();
89456
- module.exports = async (connection, path24) => {
89457
- if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state) || !path24) {
89669
+ module.exports = async (connection, path25) => {
89670
+ if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state) || !path25) {
89458
89671
  return;
89459
89672
  }
89460
89673
  if (!connection.capabilities.has("QUOTA")) {
89461
89674
  return false;
89462
89675
  }
89463
- path24 = normalizePath(connection, path24);
89464
- let map = { path: path24 };
89676
+ path25 = normalizePath(connection, path25);
89677
+ let map = { path: path25 };
89465
89678
  let processQuotaResponse = (untagged) => {
89466
89679
  let attributes = untagged.attributes && untagged.attributes[1];
89467
89680
  if (!attributes || !attributes.length) {
@@ -89501,7 +89714,7 @@ var require_quota = __commonJS({
89501
89714
  let quotaFound = false;
89502
89715
  let response;
89503
89716
  try {
89504
- response = await connection.exec("GETQUOTAROOT", [{ type: "ATOM", value: encodePath(connection, path24) }], {
89717
+ response = await connection.exec("GETQUOTAROOT", [{ type: "ATOM", value: encodePath(connection, path25) }], {
89505
89718
  untagged: {
89506
89719
  // QUOTAROOT response tells us which quota root applies to this mailbox.
89507
89720
  // A mailbox may have zero or one quota root.
@@ -89644,15 +89857,15 @@ var require_idle = __commonJS({
89644
89857
  }
89645
89858
  }
89646
89859
  async function pollOnce2(connection, session) {
89647
- let path24 = connection.mailbox && connection.mailbox.path;
89860
+ let path25 = connection.mailbox && connection.mailbox.path;
89648
89861
  switch (connection.missingIdleCommand) {
89649
89862
  case "SELECT":
89650
89863
  connection.log.debug({ src: "c", msg: `Running SELECT to detect changes in folder`, cid: connection.id });
89651
- await connection.runInternal("SELECT", path24, { readOnly: session.selectCommand.command === "EXAMINE" });
89864
+ await connection.runInternal("SELECT", path25, { readOnly: session.selectCommand.command === "EXAMINE" });
89652
89865
  break;
89653
89866
  case "STATUS": {
89654
89867
  connection.log.debug({ src: "c", msg: `Running STATUS to detect changes in folder`, cid: connection.id });
89655
- let status = await connection.runInternal("STATUS", path24, {
89868
+ let status = await connection.runInternal("STATUS", path25, {
89656
89869
  messages: true,
89657
89870
  uidNext: true,
89658
89871
  uidValidity: true,
@@ -91339,12 +91552,12 @@ var require_imap_flow = __commonJS({
91339
91552
  this.emit("flags", updateEvent);
91340
91553
  }
91341
91554
  }
91342
- async ensureSelectedMailbox(path24) {
91343
- if (!path24) {
91555
+ async ensureSelectedMailbox(path25) {
91556
+ if (!path25) {
91344
91557
  return false;
91345
91558
  }
91346
- if (!this.mailbox || !comparePaths(this, this.mailbox.path, path24)) {
91347
- return await this.mailboxOpen(path24);
91559
+ if (!this.mailbox || !comparePaths(this, this.mailbox.path, path25)) {
91560
+ return await this.mailboxOpen(path25);
91348
91561
  }
91349
91562
  return true;
91350
91563
  }
@@ -91759,9 +91972,9 @@ var require_imap_flow = __commonJS({
91759
91972
  * let quota = await client.getQuota();
91760
91973
  * console.log(quota.storage.used, quota.storage.limit)
91761
91974
  */
91762
- async getQuota(path24) {
91763
- path24 = path24 || "INBOX";
91764
- return await this.run("QUOTA", path24);
91975
+ async getQuota(path25) {
91976
+ path25 = path25 || "INBOX";
91977
+ return await this.run("QUOTA", path25);
91765
91978
  }
91766
91979
  /**
91767
91980
  * @typedef {Object} ListResponse
@@ -91871,8 +92084,8 @@ var require_imap_flow = __commonJS({
91871
92084
  * console.log(info.path);
91872
92085
  * // "INBOX.parent.child" // assumes "INBOX." as namespace prefix and "." as delimiter
91873
92086
  */
91874
- async mailboxCreate(path24) {
91875
- return await this.run("CREATE", path24);
92087
+ async mailboxCreate(path25) {
92088
+ return await this.run("CREATE", path25);
91876
92089
  }
91877
92090
  /**
91878
92091
  * @typedef {Object} MailboxRenameResponse
@@ -91893,8 +92106,8 @@ var require_imap_flow = __commonJS({
91893
92106
  * console.log(info.newPath);
91894
92107
  * // "INBOX.Important stuff ❗️" // assumes "INBOX." as namespace prefix
91895
92108
  */
91896
- async mailboxRename(path24, newPath) {
91897
- return await this.run("RENAME", path24, newPath);
92109
+ async mailboxRename(path25, newPath) {
92110
+ return await this.run("RENAME", path25, newPath);
91898
92111
  }
91899
92112
  /**
91900
92113
  * @typedef {Object} MailboxDeleteResponse
@@ -91913,8 +92126,8 @@ var require_imap_flow = __commonJS({
91913
92126
  * console.log(info.path);
91914
92127
  * // "INBOX.Important stuff ❗️" // assumes "INBOX." as namespace prefix
91915
92128
  */
91916
- async mailboxDelete(path24) {
91917
- return await this.run("DELETE", path24);
92129
+ async mailboxDelete(path25) {
92130
+ return await this.run("DELETE", path25);
91918
92131
  }
91919
92132
  /**
91920
92133
  * Subscribes to a mailbox
@@ -91925,8 +92138,8 @@ var require_imap_flow = __commonJS({
91925
92138
  * @example
91926
92139
  * await client.mailboxSubscribe('Important stuff ❗️');
91927
92140
  */
91928
- async mailboxSubscribe(path24) {
91929
- return await this.run("SUBSCRIBE", path24);
92141
+ async mailboxSubscribe(path25) {
92142
+ return await this.run("SUBSCRIBE", path25);
91930
92143
  }
91931
92144
  /**
91932
92145
  * Unsubscribes from a mailbox
@@ -91937,8 +92150,8 @@ var require_imap_flow = __commonJS({
91937
92150
  * @example
91938
92151
  * await client.mailboxUnsubscribe('Important stuff ❗️');
91939
92152
  */
91940
- async mailboxUnsubscribe(path24) {
91941
- return await this.run("UNSUBSCRIBE", path24);
92153
+ async mailboxUnsubscribe(path25) {
92154
+ return await this.run("UNSUBSCRIBE", path25);
91942
92155
  }
91943
92156
  /**
91944
92157
  * Opens a mailbox to access messages. You can perform message operations only against an opened mailbox.
@@ -91956,8 +92169,8 @@ var require_imap_flow = __commonJS({
91956
92169
  * console.log(mailbox.exists);
91957
92170
  * // 125
91958
92171
  */
91959
- async mailboxOpen(path24, options) {
91960
- return await this.run("SELECT", path24, options);
92172
+ async mailboxOpen(path25, options) {
92173
+ return await this.run("SELECT", path25, options);
91961
92174
  }
91962
92175
  /**
91963
92176
  * Closes a previously opened mailbox
@@ -92004,8 +92217,8 @@ var require_imap_flow = __commonJS({
92004
92217
  * console.log(status.unseen);
92005
92218
  * // 123
92006
92219
  */
92007
- async status(path24, query) {
92008
- return await this.run("STATUS", path24, query);
92220
+ async status(path25, query) {
92221
+ return await this.run("STATUS", path25, query);
92009
92222
  }
92010
92223
  /**
92011
92224
  * Starts listening for new or deleted messages from the currently opened mailbox. Only required if {@link ImapFlow#disableAutoIdle} is set to `true`
@@ -92259,8 +92472,8 @@ var require_imap_flow = __commonJS({
92259
92472
  * @example
92260
92473
  * await client.append('INBOX', rawMessageBuffer, ['\\Seen'], new Date(2000, 1, 1));
92261
92474
  */
92262
- async append(path24, content, flags, idate) {
92263
- return await this.run("APPEND", path24, content, flags, idate) || false;
92475
+ async append(path25, content, flags, idate) {
92476
+ return await this.run("APPEND", path25, content, flags, idate) || false;
92264
92477
  }
92265
92478
  /**
92266
92479
  * @typedef {Object} CopyResponseObject
@@ -93104,7 +93317,7 @@ var require_imap_flow = __commonJS({
93104
93317
  await new Promise((resolve2) => setImmediate(resolve2));
93105
93318
  }
93106
93319
  const lock = this.locks.shift();
93107
- const { resolve, reject, path: path24, options, lockId } = lock;
93320
+ const { resolve, reject, path: path25, options, lockId } = lock;
93108
93321
  if (lock.acquireTimer) {
93109
93322
  clearTimeout(lock.acquireTimer);
93110
93323
  lock.acquireTimer = null;
@@ -93120,7 +93333,7 @@ var require_imap_flow = __commonJS({
93120
93333
  this.log.warn({
93121
93334
  msg: "Mailbox lock held for a long time",
93122
93335
  lockId: lock.lockId,
93123
- path: path24,
93336
+ path: path25,
93124
93337
  heldFor: Date.now() - lock.heldAt,
93125
93338
  /* c8 ignore next */
93126
93339
  // the held-lock-warning diagnostic with a description set is a timing-dependent log detail
@@ -93156,52 +93369,52 @@ var require_imap_flow = __commonJS({
93156
93369
  }
93157
93370
  };
93158
93371
  if (!this.usable || !this.socket || this.socket.destroyed) {
93159
- this.log.trace({ msg: "Failed to acquire mailbox lock", path: path24, lockId, idling: this.idling });
93372
+ this.log.trace({ msg: "Failed to acquire mailbox lock", path: path25, lockId, idling: this.idling });
93160
93373
  let error2 = new Error("Connection not available");
93161
93374
  error2.code = "NoConnection";
93162
93375
  reject(error2);
93163
93376
  continue;
93164
93377
  }
93165
- if (this.mailbox && this.mailbox.path === path24 && !!this.mailbox.readOnly === !!options.readOnly) {
93378
+ if (this.mailbox && this.mailbox.path === path25 && !!this.mailbox.readOnly === !!options.readOnly) {
93166
93379
  this.log.trace({
93167
93380
  msg: "Mailbox lock acquired [existing]",
93168
- path: path24,
93381
+ path: path25,
93169
93382
  lockId,
93170
93383
  idling: this.idling,
93171
93384
  ...options.description && { description: options.description }
93172
93385
  });
93173
93386
  this.currentLock = lock;
93174
93387
  armHeldTimer();
93175
- resolve({ path: path24, release });
93388
+ resolve({ path: path25, release });
93176
93389
  break;
93177
93390
  }
93178
93391
  try {
93179
- await this.mailboxOpen(path24, options);
93392
+ await this.mailboxOpen(path25, options);
93180
93393
  this.log.trace({
93181
93394
  msg: "Mailbox lock acquired [selected]",
93182
- path: path24,
93395
+ path: path25,
93183
93396
  lockId,
93184
93397
  idling: this.idling,
93185
93398
  ...options.description && { description: options.description }
93186
93399
  });
93187
93400
  this.currentLock = lock;
93188
93401
  armHeldTimer();
93189
- resolve({ path: path24, release });
93402
+ resolve({ path: path25, release });
93190
93403
  break;
93191
93404
  } catch (err) {
93192
93405
  if (err.responseStatus === "NO") {
93193
93406
  try {
93194
- let folders = await this.run("LIST", "", path24, { listOnly: true });
93407
+ let folders = await this.run("LIST", "", path25, { listOnly: true });
93195
93408
  if (!folders || !folders.length) {
93196
93409
  err.mailboxMissing = true;
93197
93410
  }
93198
93411
  } catch (E) {
93199
- this.log.trace({ msg: "Failed to verify failed mailbox", path: path24, err: E });
93412
+ this.log.trace({ msg: "Failed to verify failed mailbox", path: path25, err: E });
93200
93413
  }
93201
93414
  }
93202
93415
  this.log.trace({
93203
93416
  msg: "Failed to acquire mailbox lock",
93204
- path: path24,
93417
+ path: path25,
93205
93418
  lockId,
93206
93419
  idling: this.idling,
93207
93420
  ...options.description && { description: options.description },
@@ -93240,13 +93453,13 @@ var require_imap_flow = __commonJS({
93240
93453
  * lock.release();
93241
93454
  * }
93242
93455
  */
93243
- getMailboxLock(path24, options) {
93456
+ getMailboxLock(path25, options) {
93244
93457
  options = options || {};
93245
- path24 = normalizePath(this, path24);
93458
+ path25 = normalizePath(this, path25);
93246
93459
  let lockId = ++this.lockCounter;
93247
93460
  this.log.trace({
93248
93461
  msg: "Requesting lock",
93249
- path: path24,
93462
+ path: path25,
93250
93463
  lockId,
93251
93464
  ...options.description && { description: options.description },
93252
93465
  activeLock: this.currentLock ? {
@@ -93255,7 +93468,7 @@ var require_imap_flow = __commonJS({
93255
93468
  } : null
93256
93469
  });
93257
93470
  let lockPromise = new Promise((resolve, reject) => {
93258
- let lockEntry = { resolve, reject, path: path24, options, lockId };
93471
+ let lockEntry = { resolve, reject, path: path25, options, lockId };
93259
93472
  this.locks.push(lockEntry);
93260
93473
  if (Number(options.acquireTimeout) > 0) {
93261
93474
  lockEntry.acquireTimer = setTimeout(() => {
@@ -93344,16 +93557,16 @@ var require_imap_flow = __commonJS({
93344
93557
  });
93345
93558
 
93346
93559
  // src/mail/mail-fetcher.ts
93347
- import fs21 from "node:fs/promises";
93348
- import path22 from "node:path";
93560
+ import fs22 from "node:fs/promises";
93561
+ import path23 from "node:path";
93349
93562
  async function saveAttachments(attachments, downloadDir) {
93350
93563
  if (attachments.length === 0) return [];
93351
- await fs21.mkdir(downloadDir, { recursive: true });
93564
+ await fs22.mkdir(downloadDir, { recursive: true });
93352
93565
  const saved = [];
93353
93566
  for (const a of attachments) {
93354
- const name = path22.basename(a.filename) || "attachment";
93355
- const savedPath = path22.join(downloadDir, name);
93356
- await fs21.writeFile(savedPath, a.content);
93567
+ const name = path23.basename(a.filename) || "attachment";
93568
+ const savedPath = path23.join(downloadDir, name);
93569
+ await fs22.writeFile(savedPath, a.content);
93357
93570
  saved.push({ filename: name, savedPath, size: a.content.length });
93358
93571
  }
93359
93572
  return saved;
@@ -93484,7 +93697,7 @@ var init_mail_fetcher = __esm({
93484
93697
 
93485
93698
  // src/tools/fetch-mail.ts
93486
93699
  import os16 from "node:os";
93487
- import path23 from "node:path";
93700
+ import path24 from "node:path";
93488
93701
  function registerFetchMailTool(server, deps = {}) {
93489
93702
  const makeFetcher = deps.fetcherFactory ?? ((creds) => new ImapflowMailFetcher(creds));
93490
93703
  server.registerTool(
@@ -93546,7 +93759,7 @@ var init_fetch_mail = __esm({
93546
93759
  init_mail_fetcher();
93547
93760
  init_auth_error();
93548
93761
  init_validate();
93549
- DEFAULT_DOWNLOAD_DIR = path23.join(os16.homedir(), ".cogent", "mail-downloads");
93762
+ DEFAULT_DOWNLOAD_DIR = path24.join(os16.homedir(), ".cogent", "mail-downloads");
93550
93763
  }
93551
93764
  });
93552
93765