@rubytech/create-maxy 1.0.644 → 1.0.646

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.
@@ -67,13 +67,13 @@ var compose = (middleware, onError, onNotFound) => {
67
67
  if (handler) {
68
68
  try {
69
69
  res = await handler(context, () => dispatch(i + 1));
70
- } catch (err2) {
71
- if (err2 instanceof Error && onError) {
72
- context.error = err2;
73
- res = await onError(err2, context);
70
+ } catch (err) {
71
+ if (err instanceof Error && onError) {
72
+ context.error = err;
73
+ res = await onError(err, context);
74
74
  isError = true;
75
75
  } else {
76
- throw err2;
76
+ throw err;
77
77
  }
78
78
  }
79
79
  } else {
@@ -1100,12 +1100,12 @@ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1100
1100
  var notFoundHandler = (c) => {
1101
1101
  return c.text("404 Not Found", 404);
1102
1102
  };
1103
- var errorHandler = (err2, c) => {
1104
- if ("getResponse" in err2) {
1105
- const res = err2.getResponse();
1103
+ var errorHandler = (err, c) => {
1104
+ if ("getResponse" in err) {
1105
+ const res = err.getResponse();
1106
1106
  return c.newResponse(res.body, res);
1107
1107
  }
1108
- console.error(err2);
1108
+ console.error(err);
1109
1109
  return c.text("Internal Server Error", 500);
1110
1110
  };
1111
1111
  var Hono = class _Hono {
@@ -1356,11 +1356,11 @@ var Hono = class _Hono {
1356
1356
  this.router.add(method, path2, [handler, r]);
1357
1357
  this.routes.push(r);
1358
1358
  }
1359
- #handleError(err2, c) {
1360
- if (err2 instanceof Error) {
1361
- return this.errorHandler(err2, c);
1359
+ #handleError(err, c) {
1360
+ if (err instanceof Error) {
1361
+ return this.errorHandler(err, c);
1362
1362
  }
1363
- throw err2;
1363
+ throw err;
1364
1364
  }
1365
1365
  #dispatch(request, executionCtx, env, method) {
1366
1366
  if (method === "HEAD") {
@@ -1381,12 +1381,12 @@ var Hono = class _Hono {
1381
1381
  res = matchResult[0][0][0][0](c, async () => {
1382
1382
  c.res = await this.#notFoundHandler(c);
1383
1383
  });
1384
- } catch (err2) {
1385
- return this.#handleError(err2, c);
1384
+ } catch (err) {
1385
+ return this.#handleError(err, c);
1386
1386
  }
1387
1387
  return res instanceof Promise ? res.then(
1388
1388
  (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
1389
- ).catch((err2) => this.#handleError(err2, c)) : res ?? this.#notFoundHandler(c);
1389
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
1390
1390
  }
1391
1391
  const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1392
1392
  return (async () => {
@@ -1398,8 +1398,8 @@ var Hono = class _Hono {
1398
1398
  );
1399
1399
  }
1400
1400
  return context.res;
1401
- } catch (err2) {
1402
- return this.#handleError(err2, c);
1401
+ } catch (err) {
1402
+ return this.#handleError(err, c);
1403
1403
  }
1404
1404
  })();
1405
1405
  }
@@ -2430,16 +2430,16 @@ var handleFetchError = (e) => new Response(null, {
2430
2430
  status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
2431
2431
  });
2432
2432
  var handleResponseError = (e, outgoing) => {
2433
- const err2 = e instanceof Error ? e : new Error("unknown error", { cause: e });
2434
- if (err2.code === "ERR_STREAM_PREMATURE_CLOSE") {
2433
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
2434
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
2435
2435
  console.info("The user aborted a request.");
2436
2436
  } else {
2437
2437
  console.error(e);
2438
2438
  if (!outgoing.headersSent) {
2439
2439
  outgoing.writeHead(500, { "Content-Type": "text/plain" });
2440
2440
  }
2441
- outgoing.end(`Error: ${err2.message}`);
2442
- outgoing.destroy(err2);
2441
+ outgoing.end(`Error: ${err.message}`);
2442
+ outgoing.destroy(err);
2443
2443
  }
2444
2444
  };
2445
2445
  var flushHeaders = (outgoing) => {
@@ -2496,8 +2496,8 @@ var responseViaResponseObject = async (res, outgoing, options = {}) => {
2496
2496
  if (options.errorHandler) {
2497
2497
  try {
2498
2498
  res = await res;
2499
- } catch (err2) {
2500
- const errRes = await options.errorHandler(err2);
2499
+ } catch (err) {
2500
+ const errRes = await options.errorHandler(err);
2501
2501
  if (!errRes) {
2502
2502
  return;
2503
2503
  }
@@ -2768,8 +2768,8 @@ var createStreamBody = (stream) => {
2768
2768
  stream.on("data", (chunk) => {
2769
2769
  controller.enqueue(chunk);
2770
2770
  });
2771
- stream.on("error", (err2) => {
2772
- controller.error(err2);
2771
+ stream.on("error", (err) => {
2772
+ controller.error(err);
2773
2773
  });
2774
2774
  stream.on("end", () => {
2775
2775
  controller.close();
@@ -2930,8 +2930,8 @@ var CLAUDE_CREDENTIALS_FILE = resolve(homedir(), ".claude", ".credentials.json")
2930
2930
  var VNC_LOG_FILE = resolve2(LOG_DIR, "vnc-boot.log");
2931
2931
  try {
2932
2932
  mkdirSync(LOG_DIR, { recursive: true });
2933
- } catch (err2) {
2934
- console.error(`[vnc-log-fail] mkdir ${LOG_DIR} failed: ${err2.message}`);
2933
+ } catch (err) {
2934
+ console.error(`[vnc-log-fail] mkdir ${LOG_DIR} failed: ${err.message}`);
2935
2935
  }
2936
2936
  function vncLog(phase, fields = {}) {
2937
2937
  const ts = (/* @__PURE__ */ new Date()).toISOString();
@@ -2941,8 +2941,8 @@ function vncLog(phase, fields = {}) {
2941
2941
  `;
2942
2942
  try {
2943
2943
  appendFileSync(VNC_LOG_FILE, line);
2944
- } catch (err2) {
2945
- console.error(`[vnc-log-fail] ${err2.message} \u2014 dropped: ${line.slice(0, 300).trim()}`);
2944
+ } catch (err) {
2945
+ console.error(`[vnc-log-fail] ${err.message} \u2014 dropped: ${line.slice(0, 300).trim()}`);
2946
2946
  }
2947
2947
  }
2948
2948
  var corrCounter = 0;
@@ -2983,8 +2983,8 @@ var SCRYPT_P = 1;
2983
2983
  var SCRYPT_KEYLEN = 64;
2984
2984
  function scryptAsync(password, salt) {
2985
2985
  return new Promise((resolve33, reject) => {
2986
- scrypt(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P }, (err2, key) => {
2987
- if (err2) reject(err2);
2986
+ scrypt(password, salt, SCRYPT_KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P }, (err, key) => {
2987
+ if (err) reject(err);
2988
2988
  else resolve33(key);
2989
2989
  });
2990
2990
  });
@@ -3595,11 +3595,11 @@ function attachVncWsProxy(server, opts) {
3595
3595
  upstreamHost,
3596
3596
  upstreamPort
3597
3597
  });
3598
- } catch (err2) {
3598
+ } catch (err) {
3599
3599
  vncLog("ws-upgrade", {
3600
3600
  decision: "rejected",
3601
3601
  reason: "handler-exception",
3602
- err: err2.message
3602
+ err: err.message
3603
3603
  });
3604
3604
  clientSocket.destroy();
3605
3605
  }
@@ -3754,12 +3754,12 @@ function handleUpgrade(req, clientSocket, head, opts) {
3754
3754
  upstream.once("close", (hadError) => {
3755
3755
  finish("upstream", hadError ? "error" : "normal");
3756
3756
  });
3757
- clientSocket.once("error", (err2) => {
3758
- vncLog("proxy-error", { corrId, side: "client", err: err2.message });
3757
+ clientSocket.once("error", (err) => {
3758
+ vncLog("proxy-error", { corrId, side: "client", err: err.message });
3759
3759
  finish("client", "error");
3760
3760
  });
3761
- upstream.once("error", (err2) => {
3762
- vncLog("proxy-error", { corrId, side: "upstream", err: err2.message });
3761
+ upstream.once("error", (err) => {
3762
+ vncLog("proxy-error", { corrId, side: "upstream", err: err.message });
3763
3763
  finish("upstream", "error");
3764
3764
  });
3765
3765
  });
@@ -3774,12 +3774,12 @@ function handleUpgrade(req, clientSocket, head, opts) {
3774
3774
  writeStatusAndDestroy(clientSocket, 504, "Gateway Timeout");
3775
3775
  upstream.destroy();
3776
3776
  });
3777
- upstream.once("error", (err2) => {
3777
+ upstream.once("error", (err) => {
3778
3778
  if (proxyOpened) return;
3779
3779
  vncLog("proxy-error", {
3780
3780
  corrId,
3781
3781
  side: "upstream-connect",
3782
- err: err2.message
3782
+ err: err.message
3783
3783
  });
3784
3784
  writeStatusAndDestroy(clientSocket, 502, "Bad Gateway");
3785
3785
  upstream.destroy();
@@ -3888,8 +3888,8 @@ function attachGraphHttpRoutes(app2) {
3888
3888
  statusText: upstream.statusText,
3889
3889
  headers: resHeaders
3890
3890
  });
3891
- } catch (err2) {
3892
- const msg = err2 instanceof Error ? err2.message : String(err2);
3891
+ } catch (err) {
3892
+ const msg = err instanceof Error ? err.message : String(err);
3893
3893
  console.error(`[graph-proxy] upstream fetch failed for ${upstreamUrl}: ${msg}`);
3894
3894
  return c.text(`Graph proxy upstream unreachable: ${msg}`, 502);
3895
3895
  }
@@ -3973,13 +3973,13 @@ function attachGraphWsProxy(server, opts) {
3973
3973
  writeStatusAndDestroy2(clientSocket, 504, "Gateway Timeout");
3974
3974
  upstream.destroy();
3975
3975
  });
3976
- upstream.once("error", (err2) => {
3977
- console.error(`[graph-proxy] ws upstream error: ${err2.message}`);
3976
+ upstream.once("error", (err) => {
3977
+ console.error(`[graph-proxy] ws upstream error: ${err.message}`);
3978
3978
  writeStatusAndDestroy2(clientSocket, 502, "Bad Gateway");
3979
3979
  upstream.destroy();
3980
3980
  });
3981
- } catch (err2) {
3982
- console.error(`[graph-proxy] upgrade handler exception: ${err2.message}`);
3981
+ } catch (err) {
3982
+ console.error(`[graph-proxy] upgrade handler exception: ${err.message}`);
3983
3983
  clientSocket.destroy();
3984
3984
  }
3985
3985
  });
@@ -4103,8 +4103,8 @@ function writeOAuthCredentials(tokens) {
4103
4103
  };
4104
4104
  writeFileSync2(CLAUDE_CREDENTIALS_FILE, JSON.stringify(fileData, null, 2), "utf-8");
4105
4105
  return newExpiresAt;
4106
- } catch (err2) {
4107
- console.error(`[claude-auth] credential write failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4106
+ } catch (err) {
4107
+ console.error(`[claude-auth] credential write failed: ${err instanceof Error ? err.message : String(err)}`);
4108
4108
  return null;
4109
4109
  }
4110
4110
  }
@@ -4153,8 +4153,8 @@ async function doRefresh() {
4153
4153
  client_id: CLIENT_ID
4154
4154
  })
4155
4155
  });
4156
- } catch (err2) {
4157
- console.error(`[auth-refresh] network error: ${err2 instanceof Error ? err2.message : String(err2)}`);
4156
+ } catch (err) {
4157
+ console.error(`[auth-refresh] network error: ${err instanceof Error ? err.message : String(err)}`);
4158
4158
  return { status: "expired", expiresAt: creds.expiresAt };
4159
4159
  }
4160
4160
  if (res.status === 429) {
@@ -4252,13 +4252,13 @@ function resolveKeyFilePath() {
4252
4252
  );
4253
4253
  }
4254
4254
  configDirName2 = brand.configDir;
4255
- } catch (err2) {
4256
- if (err2 instanceof SyntaxError) {
4255
+ } catch (err) {
4256
+ if (err instanceof SyntaxError) {
4257
4257
  throw new Error(
4258
- `brand.json at ${brandPath3} is not valid JSON: ${err2.message}`
4258
+ `brand.json at ${brandPath3} is not valid JSON: ${err.message}`
4259
4259
  );
4260
4260
  }
4261
- throw err2;
4261
+ throw err;
4262
4262
  }
4263
4263
  }
4264
4264
  cachedKeyFilePath = resolve3(homedir2(), configDirName2, ".anthropic-api-key");
@@ -4272,8 +4272,8 @@ function readKey() {
4272
4272
  let keyFilePath2;
4273
4273
  try {
4274
4274
  keyFilePath2 = resolveKeyFilePath();
4275
- } catch (err2) {
4276
- const msg = err2 instanceof Error ? err2.message : String(err2);
4275
+ } catch (err) {
4276
+ const msg = err instanceof Error ? err.message : String(err);
4277
4277
  console.error(`[anthropic-key] path resolution failed: ${msg}`);
4278
4278
  return null;
4279
4279
  }
@@ -4291,14 +4291,14 @@ function readKey() {
4291
4291
  return null;
4292
4292
  }
4293
4293
  return raw2;
4294
- } catch (err2) {
4295
- const code = err2 instanceof Error && "code" in err2 ? err2.code : void 0;
4294
+ } catch (err) {
4295
+ const code = err instanceof Error && "code" in err ? err.code : void 0;
4296
4296
  if (code === "ENOENT") {
4297
4297
  console.error(
4298
4298
  `[anthropic-key] no key available (env var unset, file not found: ${keyFilePath2})`
4299
4299
  );
4300
4300
  } else {
4301
- const msg = err2 instanceof Error ? err2.message : String(err2);
4301
+ const msg = err instanceof Error ? err.message : String(err);
4302
4302
  console.error(
4303
4303
  `[anthropic-key] failed to read key file ${keyFilePath2}: ${msg}`
4304
4304
  );
@@ -4367,9 +4367,9 @@ async function validateKey(key) {
4367
4367
  status: "error",
4368
4368
  message: `Could not verify API key. Anthropic returned ${res.status}. This may be a temporary outage \u2014 try again later.`
4369
4369
  };
4370
- } catch (err2) {
4370
+ } catch (err) {
4371
4371
  const latency = Date.now() - start;
4372
- const msg = err2 instanceof Error ? err2.message : String(err2);
4372
+ const msg = err instanceof Error ? err.message : String(err);
4373
4373
  console.error(
4374
4374
  `[anthropic-key] validate: error (network failure, ${latency}ms): ${msg}`
4375
4375
  );
@@ -4492,8 +4492,8 @@ function discoverNativeDisplay() {
4492
4492
  display: sessionDisplay
4493
4493
  });
4494
4494
  return info;
4495
- } catch (err2) {
4496
- vncLog("native-display-discovery", { action: "fallback", reason: "error", err: err2.message });
4495
+ } catch (err) {
4496
+ vncLog("native-display-discovery", { action: "fallback", reason: "error", err: err.message });
4497
4497
  return fallback;
4498
4498
  }
4499
4499
  }
@@ -4536,13 +4536,13 @@ async function ensureVnc() {
4536
4536
  vncLog("ensure-vnc", { action: "restart", reason: "x-down" });
4537
4537
  try {
4538
4538
  execFileSync("bash", [VNC_SCRIPT, "start"], { timeout: 2e4 });
4539
- } catch (err2) {
4540
- vncLog("ensure-vnc", { action: "restart-failed", err: err2.message });
4539
+ } catch (err) {
4540
+ vncLog("ensure-vnc", { action: "restart-failed", err: err.message });
4541
4541
  return false;
4542
4542
  }
4543
- const ok2 = await waitForPort(5900, 12e3);
4544
- vncLog("ensure-vnc", { action: "restart-complete", x_port_5900: ok2 });
4545
- return ok2;
4543
+ const ok = await waitForPort(5900, 12e3);
4544
+ vncLog("ensure-vnc", { action: "restart-complete", x_port_5900: ok });
4545
+ return ok;
4546
4546
  }
4547
4547
  async function ensureCdp(transport = "vnc") {
4548
4548
  const targetSentinel = transport === "native" ? "native" : ":99";
@@ -4593,8 +4593,8 @@ async function ensureCdp(transport = "vnc") {
4593
4593
  vncLog("ensure-cdp", { action: `restart-${vncCommand}`, reason: "cdp-dead", transport });
4594
4594
  try {
4595
4595
  execFileSync("bash", [VNC_SCRIPT, vncCommand], { timeout: 2e4 });
4596
- } catch (err2) {
4597
- vncLog("ensure-cdp", { action: "restart-chrome-failed", transport, err: err2.message });
4596
+ } catch (err) {
4597
+ vncLog("ensure-cdp", { action: "restart-chrome-failed", transport, err: err.message });
4598
4598
  return false;
4599
4599
  }
4600
4600
  const cdpOk = await waitForPort(9222, 12e3);
@@ -4807,8 +4807,8 @@ async function ensureConversation(accountId, agentType, sessionKey, visitorId, a
4807
4807
  console.error(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} conversation attributed: conversationId=${id.slice(0, 8)}\u2026 userId=${userId ?? "none"} ${agentType}/${accountId.slice(0, 8)}\u2026`);
4808
4808
  }
4809
4809
  return id ?? null;
4810
- } catch (err2) {
4811
- console.error(`[persist] ensureConversation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4810
+ } catch (err) {
4811
+ console.error(`[persist] ensureConversation failed: ${err instanceof Error ? err.message : String(err)}`);
4812
4812
  return null;
4813
4813
  } finally {
4814
4814
  await session.close();
@@ -4834,8 +4834,8 @@ async function findRecentConversation(visitorId, accountId, agentSlug, maxAgeHou
4834
4834
  if (!conversationId) return null;
4835
4835
  console.log(`[persist] found recent conversation ${conversationId.slice(0, 8)}\u2026 for visitor ${visitorId.slice(0, 8)}\u2026`);
4836
4836
  return { conversationId, sessionKey };
4837
- } catch (err2) {
4838
- console.error(`[persist] findRecentConversation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4837
+ } catch (err) {
4838
+ console.error(`[persist] findRecentConversation failed: ${err instanceof Error ? err.message : String(err)}`);
4839
4839
  return null;
4840
4840
  } finally {
4841
4841
  await session.close();
@@ -4857,8 +4857,8 @@ async function findGroupBySlug(groupSlug, accountId) {
4857
4857
  groupName: record.get("groupName"),
4858
4858
  agentSlug: record.get("agentSlug")
4859
4859
  };
4860
- } catch (err2) {
4861
- console.error(`[group] findGroupBySlug failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4860
+ } catch (err) {
4861
+ console.error(`[group] findGroupBySlug failed: ${err instanceof Error ? err.message : String(err)}`);
4862
4862
  return null;
4863
4863
  } finally {
4864
4864
  await session.close();
@@ -4880,8 +4880,8 @@ async function getGroupParticipants(conversationId) {
4880
4880
  joinedAt: String(r.get("joinedAt")),
4881
4881
  visitorId: r.get("visitorId")
4882
4882
  }));
4883
- } catch (err2) {
4884
- console.error(`[group] getGroupParticipants failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4883
+ } catch (err) {
4884
+ console.error(`[group] getGroupParticipants failed: ${err instanceof Error ? err.message : String(err)}`);
4885
4885
  return [];
4886
4886
  } finally {
4887
4887
  await session.close();
@@ -4898,8 +4898,8 @@ async function checkGroupMembership(conversationId, visitorId) {
4898
4898
  { conversationId, visitorId }
4899
4899
  );
4900
4900
  return result.records[0]?.get("displayName") ?? null;
4901
- } catch (err2) {
4902
- console.error(`[group] checkGroupMembership failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4901
+ } catch (err) {
4902
+ console.error(`[group] checkGroupMembership failed: ${err instanceof Error ? err.message : String(err)}`);
4903
4903
  return null;
4904
4904
  } finally {
4905
4905
  await session.close();
@@ -4929,8 +4929,8 @@ async function bindVisitorToGroup(conversationId, visitorId, personEmail, person
4929
4929
  console.error(`[group] auth-denied id=${conversationId.slice(0, 8)}\u2026 visitor=${visitorId.slice(0, 8)}\u2026`);
4930
4930
  }
4931
4931
  return name ? { displayName: name } : null;
4932
- } catch (err2) {
4933
- console.error(`[group] bindVisitorToGroup failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4932
+ } catch (err) {
4933
+ console.error(`[group] bindVisitorToGroup failed: ${err instanceof Error ? err.message : String(err)}`);
4934
4934
  return null;
4935
4935
  } finally {
4936
4936
  await session.close();
@@ -4958,8 +4958,8 @@ async function getMessagesSince(conversationId, since, limit = 100) {
4958
4958
  senderVisitorId: r.get("senderVisitorId"),
4959
4959
  createdAt: String(r.get("createdAt"))
4960
4960
  }));
4961
- } catch (err2) {
4962
- console.error(`[group] getMessagesSince failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4961
+ } catch (err) {
4962
+ console.error(`[group] getMessagesSince failed: ${err instanceof Error ? err.message : String(err)}`);
4963
4963
  return [];
4964
4964
  } finally {
4965
4965
  await session.close();
@@ -4980,8 +4980,8 @@ async function getGroupMessagesForContext(conversationId, limit = 50) {
4980
4980
  content: r.get("content"),
4981
4981
  senderName: r.get("senderName")
4982
4982
  }));
4983
- } catch (err2) {
4984
- console.error(`[group] getGroupMessagesForContext failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
4983
+ } catch (err) {
4984
+ console.error(`[group] getGroupMessagesForContext failed: ${err instanceof Error ? err.message : String(err)}`);
4985
4985
  return [];
4986
4986
  } finally {
4987
4987
  await session.close();
@@ -5008,8 +5008,8 @@ async function backfillNullUserIdConversations(userId) {
5008
5008
  console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: no orphaned admin conversations found`);
5009
5009
  }
5010
5010
  return typeof updated === "number" ? updated : 0;
5011
- } catch (err2) {
5012
- console.error(`[session] backfillNullUserIdConversations failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5011
+ } catch (err) {
5012
+ console.error(`[session] backfillNullUserIdConversations failed: ${err instanceof Error ? err.message : String(err)}`);
5013
5013
  return 0;
5014
5014
  } finally {
5015
5015
  await session.close();
@@ -5039,8 +5039,8 @@ async function createNewAdminConversation(userId, accountId, sessionKey) {
5039
5039
  cacheConversationId(sessionKey, conversationId);
5040
5040
  console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} conversation created: conversationId=${conversationId.slice(0, 8)}\u2026 userId=${userId} accountId=${accountId.slice(0, 8)}\u2026`);
5041
5041
  return conversationId;
5042
- } catch (err2) {
5043
- console.error(`[session] createNewAdminConversation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5042
+ } catch (err) {
5043
+ console.error(`[session] createNewAdminConversation failed: ${err instanceof Error ? err.message : String(err)}`);
5044
5044
  return null;
5045
5045
  } finally {
5046
5046
  await session.close();
@@ -5085,8 +5085,8 @@ async function fetchBranding(accountId) {
5085
5085
  if (faviconUrl) branding.faviconUrl = faviconUrl;
5086
5086
  console.error(`[branding] resolved for accountId=${accountId.slice(0, 8)}\u2026: primary=${branding.primaryColor ?? "\u2013"} logo=${branding.logoUrl ? "yes" : "no"}`);
5087
5087
  return branding;
5088
- } catch (err2) {
5089
- console.error(`[branding] fetchBranding failed for accountId=${accountId.slice(0, 8)}\u2026: ${err2 instanceof Error ? err2.message : String(err2)}`);
5088
+ } catch (err) {
5089
+ console.error(`[branding] fetchBranding failed for accountId=${accountId.slice(0, 8)}\u2026: ${err instanceof Error ? err.message : String(err)}`);
5090
5090
  return null;
5091
5091
  } finally {
5092
5092
  await session.close();
@@ -5140,8 +5140,8 @@ async function persistToolCall(record) {
5140
5140
  }
5141
5141
  );
5142
5142
  console.error(`[persist] tool-call persisted: name=${record.toolName} conversation=${record.conversationId.slice(0, 8)}\u2026${record.approvalState ? ` approval=${record.approvalState}` : ""}`);
5143
- } catch (err2) {
5144
- console.error(`[persist] tool-call write failed: name=${record.toolName} error=${err2 instanceof Error ? err2.message : String(err2)}`);
5143
+ } catch (err) {
5144
+ console.error(`[persist] tool-call write failed: name=${record.toolName} error=${err instanceof Error ? err.message : String(err)}`);
5145
5145
  } finally {
5146
5146
  await session.close();
5147
5147
  }
@@ -5152,8 +5152,8 @@ async function persistMessage(conversationId, role, content, accountId, tokens,
5152
5152
  let embedding = null;
5153
5153
  try {
5154
5154
  embedding = await embed(content);
5155
- } catch (err2) {
5156
- console.error(`[persist] Embedding failed, storing without: ${err2 instanceof Error ? err2.message : String(err2)}`);
5155
+ } catch (err) {
5156
+ console.error(`[persist] Embedding failed, storing without: ${err instanceof Error ? err.message : String(err)}`);
5157
5157
  }
5158
5158
  const session = getSession();
5159
5159
  try {
@@ -5193,8 +5193,8 @@ async function persistMessage(conversationId, role, content, accountId, tokens,
5193
5193
  );
5194
5194
  console.error(`[persist] ${(/* @__PURE__ */ new Date()).toISOString()} conversationId=${conversationId.slice(0, 8)}\u2026 role=${role} len=${content.length}${sender ? ` sender=${sender.displayName}` : ""}`);
5195
5195
  return messageId;
5196
- } catch (err2) {
5197
- console.error(`[persist] Neo4j write failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5196
+ } catch (err) {
5197
+ console.error(`[persist] Neo4j write failed: ${err instanceof Error ? err.message : String(err)}`);
5198
5198
  return null;
5199
5199
  } finally {
5200
5200
  await session.close();
@@ -5216,8 +5216,8 @@ async function getRecentMessages(conversationId, limit = 50) {
5216
5216
  content: r.get("content"),
5217
5217
  createdAt: String(r.get("createdAt"))
5218
5218
  }));
5219
- } catch (err2) {
5220
- console.error(`[persist] getRecentMessages failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5219
+ } catch (err) {
5220
+ console.error(`[persist] getRecentMessages failed: ${err instanceof Error ? err.message : String(err)}`);
5221
5221
  return [];
5222
5222
  } finally {
5223
5223
  await session.close();
@@ -5232,8 +5232,8 @@ async function verifyConversationOwnership(conversationId, accountId) {
5232
5232
  { conversationId, accountId }
5233
5233
  );
5234
5234
  return result.records.length > 0;
5235
- } catch (err2) {
5236
- console.error(`[persist] verifyConversationOwnership failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5235
+ } catch (err) {
5236
+ console.error(`[persist] verifyConversationOwnership failed: ${err instanceof Error ? err.message : String(err)}`);
5237
5237
  return false;
5238
5238
  } finally {
5239
5239
  await session.close();
@@ -5249,8 +5249,8 @@ async function verifyAndGetConversationUpdatedAt(conversationId, accountId) {
5249
5249
  );
5250
5250
  const record = result.records[0];
5251
5251
  return record ? record.get("updatedAt") : null;
5252
- } catch (err2) {
5253
- console.error(`[persist] verifyAndGetConversationUpdatedAt failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5252
+ } catch (err) {
5253
+ console.error(`[persist] verifyAndGetConversationUpdatedAt failed: ${err instanceof Error ? err.message : String(err)}`);
5254
5254
  return null;
5255
5255
  } finally {
5256
5256
  await session.close();
@@ -5281,8 +5281,8 @@ async function searchMessages(accountId, queryEmbedding, limit = 10) {
5281
5281
  createdAt: String(r.get("createdAt")),
5282
5282
  score: typeof r.get("score") === "number" ? r.get("score") : Number(r.get("score"))
5283
5283
  }));
5284
- } catch (err2) {
5285
- console.error(`[persist] searchMessages failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5284
+ } catch (err) {
5285
+ console.error(`[persist] searchMessages failed: ${err instanceof Error ? err.message : String(err)}`);
5286
5286
  return [];
5287
5287
  } finally {
5288
5288
  await session.close();
@@ -5305,8 +5305,8 @@ async function listAdminSessions(accountId, userId, limit = 20) {
5305
5305
  name: r.get("name"),
5306
5306
  updatedAt: String(r.get("updatedAt"))
5307
5307
  }));
5308
- } catch (err2) {
5309
- console.error(`[persist] listAdminSessions failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5308
+ } catch (err) {
5309
+ console.error(`[persist] listAdminSessions failed: ${err instanceof Error ? err.message : String(err)}`);
5310
5310
  return [];
5311
5311
  } finally {
5312
5312
  await session.close();
@@ -5326,8 +5326,8 @@ async function deleteConversation(conversationId) {
5326
5326
  const count = typeof deleted === "object" && deleted !== null ? Number(deleted) : Number(deleted ?? 0);
5327
5327
  console.error(`[persist] deleteConversation ${conversationId.slice(0, 8)}\u2026: ${count > 0 ? "deleted" : "not found"}`);
5328
5328
  return count > 0;
5329
- } catch (err2) {
5330
- console.error(`[persist] deleteConversation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5329
+ } catch (err) {
5330
+ console.error(`[persist] deleteConversation failed: ${err instanceof Error ? err.message : String(err)}`);
5331
5331
  return false;
5332
5332
  } finally {
5333
5333
  await session.close();
@@ -5394,9 +5394,9 @@ ${userContent}`;
5394
5394
  console.error("[persist] autoLabel: haiku subprocess timed out");
5395
5395
  resolve33(null);
5396
5396
  }, SESSION_LABEL_TIMEOUT_MS);
5397
- proc.on("error", (err2) => {
5397
+ proc.on("error", (err) => {
5398
5398
  clearTimeout(timer);
5399
- console.error(`[persist] autoLabel: subprocess error \u2014 ${err2.message}`);
5399
+ console.error(`[persist] autoLabel: subprocess error \u2014 ${err.message}`);
5400
5400
  resolve33(null);
5401
5401
  });
5402
5402
  proc.on("close", (code) => {
@@ -5459,8 +5459,8 @@ async function autoLabelSession(conversationId, userMessage) {
5459
5459
  let embedding = null;
5460
5460
  try {
5461
5461
  embedding = await embed(fullLabel);
5462
- } catch (err2) {
5463
- console.error(`[persist] Conversation embedding failed, labelling without: ${err2 instanceof Error ? err2.message : String(err2)}`);
5462
+ } catch (err) {
5463
+ console.error(`[persist] Conversation embedding failed, labelling without: ${err instanceof Error ? err.message : String(err)}`);
5464
5464
  }
5465
5465
  const session = getSession();
5466
5466
  try {
@@ -5481,13 +5481,13 @@ async function autoLabelSession(conversationId, userMessage) {
5481
5481
  console.error(`[persist] Auto-labeled session ${conversationId.slice(0, 8)}\u2026: "${fullLabel}"${embedding ? " (embedded)" : ""}`);
5482
5482
  labelAccumulator.delete(conversationId);
5483
5483
  }
5484
- } catch (err2) {
5485
- console.error(`[persist] autoLabelSession failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5484
+ } catch (err) {
5485
+ console.error(`[persist] autoLabelSession failed: ${err instanceof Error ? err.message : String(err)}`);
5486
5486
  } finally {
5487
5487
  await session.close();
5488
5488
  }
5489
- } catch (err2) {
5490
- console.error(`[persist] autoLabel: unexpected error \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
5489
+ } catch (err) {
5490
+ console.error(`[persist] autoLabel: unexpected error \u2014 ${err instanceof Error ? err.message : String(err)}`);
5491
5491
  } finally {
5492
5492
  const currentEntry = labelAccumulator.get(conversationId);
5493
5493
  if (currentEntry) currentEntry.pending = false;
@@ -5497,8 +5497,8 @@ async function renameConversation(conversationId, label) {
5497
5497
  let embedding = null;
5498
5498
  try {
5499
5499
  embedding = await embed(label);
5500
- } catch (err2) {
5501
- console.error(`[persist] manual-label: embedding failed, persisting without: ${err2 instanceof Error ? err2.message : String(err2)}`);
5500
+ } catch (err) {
5501
+ console.error(`[persist] manual-label: embedding failed, persisting without: ${err instanceof Error ? err.message : String(err)}`);
5502
5502
  }
5503
5503
  const session = getSession();
5504
5504
  try {
@@ -5537,8 +5537,8 @@ async function getUserTimezone(accountId, userId) {
5537
5537
  if (result.records.length === 0) return null;
5538
5538
  const tz = result.records[0].get("timezone");
5539
5539
  return tz && tz.trim().length > 0 ? tz : null;
5540
- } catch (err2) {
5541
- console.error(`[datetime] getUserTimezone failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5540
+ } catch (err) {
5541
+ console.error(`[datetime] getUserTimezone failed: ${err instanceof Error ? err.message : String(err)}`);
5542
5542
  return null;
5543
5543
  } finally {
5544
5544
  await session.close();
@@ -5634,8 +5634,8 @@ async function loadUserProfile(accountId, userId) {
5634
5634
  `[profile] loaded for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 preferences=${preferences.length} (decay: ${decayCount} updated)`
5635
5635
  );
5636
5636
  return summary;
5637
- } catch (err2) {
5638
- console.error(`[profile] loadUserProfile failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5637
+ } catch (err) {
5638
+ console.error(`[profile] loadUserProfile failed: ${err instanceof Error ? err.message : String(err)}`);
5639
5639
  return null;
5640
5640
  } finally {
5641
5641
  await session.close();
@@ -5720,9 +5720,9 @@ function readRecentToolFailures(accountId, conversationId) {
5720
5720
  } finally {
5721
5721
  closeSync(fd);
5722
5722
  }
5723
- } catch (err2) {
5723
+ } catch (err) {
5724
5724
  console.error(
5725
- `[session-context] recent-tool-failures read failed: ${err2 instanceof Error ? err2.message : String(err2)}`
5725
+ `[session-context] recent-tool-failures read failed: ${err instanceof Error ? err.message : String(err)}`
5726
5726
  );
5727
5727
  return [];
5728
5728
  }
@@ -5916,8 +5916,8 @@ ${failureLines.map((l) => `- ${l.trim()}`).join("\n")}`);
5916
5916
  return `<previous-context>
5917
5917
  ${sections.join("\n\n")}
5918
5918
  </previous-context>`;
5919
- } catch (err2) {
5920
- console.error(`[session-context] loadSessionContext failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5919
+ } catch (err) {
5920
+ console.error(`[session-context] loadSessionContext failed: ${err instanceof Error ? err.message : String(err)}`);
5921
5921
  return null;
5922
5922
  } finally {
5923
5923
  await session.close();
@@ -5959,9 +5959,9 @@ async function consumeStep7FlagUI(session, accountId) {
5959
5959
  );
5960
5960
  try {
5961
5961
  rmSync(flagPath);
5962
- } catch (err2) {
5962
+ } catch (err) {
5963
5963
  console.error(
5964
- `[onboarding-flag-consumed] warn: failed to delete ${flagPath}: ${err2 instanceof Error ? err2.message : String(err2)}`
5964
+ `[onboarding-flag-consumed] warn: failed to delete ${flagPath}: ${err instanceof Error ? err.message : String(err)}`
5965
5965
  );
5966
5966
  }
5967
5967
  return true;
@@ -5984,8 +5984,8 @@ async function loadOnboardingStep(accountId) {
5984
5984
  return raw2.toNumber();
5985
5985
  }
5986
5986
  return 0;
5987
- } catch (err2) {
5988
- console.error(`[onboarding-inject] loadOnboardingStep failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
5987
+ } catch (err) {
5988
+ console.error(`[onboarding-inject] loadOnboardingStep failed: ${err instanceof Error ? err.message : String(err)}`);
5989
5989
  return null;
5990
5990
  } finally {
5991
5991
  await session.close();
@@ -6155,8 +6155,8 @@ async function writeReflectionPreferences(accountId, userId, conversationId, upd
6155
6155
  }
6156
6156
  console.error(`[profile-reflection] Wrote ${written}/${updates.length} preference updates for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026`);
6157
6157
  return written;
6158
- } catch (err2) {
6159
- console.error(`[profile-reflection] writeReflectionPreferences failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
6158
+ } catch (err) {
6159
+ console.error(`[profile-reflection] writeReflectionPreferences failed: ${err instanceof Error ? err.message : String(err)}`);
6160
6160
  return written;
6161
6161
  } finally {
6162
6162
  await session.close();
@@ -6192,12 +6192,12 @@ async function searchKnowledgeFulltext(accountId, query, limit) {
6192
6192
  score
6193
6193
  };
6194
6194
  });
6195
- } catch (err2) {
6196
- const msg = err2 instanceof Error ? err2.message : String(err2);
6195
+ } catch (err) {
6196
+ const msg = err instanceof Error ? err.message : String(err);
6197
6197
  if (msg.includes("index") || msg.includes("fulltext") || msg.includes("not found")) {
6198
6198
  return [];
6199
6199
  }
6200
- throw err2;
6200
+ throw err;
6201
6201
  } finally {
6202
6202
  await session.close();
6203
6203
  }
@@ -6336,12 +6336,12 @@ ${message.slice(0, CLASSIFIER_MSG_CAP)}`
6336
6336
  `${TAG} done duration_ms=${durationMs} input_tokens=${inputTokens} output_tokens=${outputTokens} commitments=${commitments.length} confidences=[${commitments.map((c) => c.confidence.toFixed(2)).join(",")}]`
6337
6337
  );
6338
6338
  return commitments;
6339
- } catch (err2) {
6339
+ } catch (err) {
6340
6340
  const durationMs = Date.now() - startMs;
6341
- if (err2 instanceof Error && err2.name === "AbortError") {
6341
+ if (err instanceof Error && err.name === "AbortError") {
6342
6342
  console.error(`${TAG} failed error=timeout duration_ms=${durationMs}`);
6343
6343
  } else {
6344
- const reason = err2 instanceof Error ? err2.message : String(err2);
6344
+ const reason = err instanceof Error ? err.message : String(err);
6345
6345
  console.error(`${TAG} failed error=${reason} duration_ms=${durationMs}`);
6346
6346
  }
6347
6347
  return [];
@@ -6414,10 +6414,10 @@ async function probeDns(host, family) {
6414
6414
  if (timer) clearTimeout(timer);
6415
6415
  const ms = Date.now() - start;
6416
6416
  return `${label}=${result.address} ${label}_ms=${ms}`;
6417
- } catch (err2) {
6417
+ } catch (err) {
6418
6418
  if (timer) clearTimeout(timer);
6419
6419
  const ms = Date.now() - start;
6420
- const msg = err2 instanceof Error ? err2.message : String(err2);
6420
+ const msg = err instanceof Error ? err.message : String(err);
6421
6421
  return `${label}=err ${label}_err=${quoteDiag(msg.slice(0, 60))} ${label}_ms=${ms}`;
6422
6422
  }
6423
6423
  }
@@ -6440,9 +6440,9 @@ async function probeTcp(host, port2) {
6440
6440
  clearTimeout(timer);
6441
6441
  finish(`tcp=ok tcp_ms=${Date.now() - start}`);
6442
6442
  });
6443
- sock.once("error", (err2) => {
6443
+ sock.once("error", (err) => {
6444
6444
  clearTimeout(timer);
6445
- const msg = err2 instanceof Error ? err2.message : String(err2);
6445
+ const msg = err instanceof Error ? err.message : String(err);
6446
6446
  finish(`tcp=err tcp_err=${quoteDiag(msg.slice(0, 60))} tcp_ms=${Date.now() - start}`);
6447
6447
  });
6448
6448
  });
@@ -6455,9 +6455,9 @@ async function probeHttp(url) {
6455
6455
  const res = await fetch(url, { method: "HEAD", redirect: "manual", signal: controller.signal });
6456
6456
  clearTimeout(timer);
6457
6457
  return `http_status=${res.status} http_ms=${Date.now() - start}`;
6458
- } catch (err2) {
6458
+ } catch (err) {
6459
6459
  clearTimeout(timer);
6460
- const msg = err2 instanceof Error ? err2.message : String(err2);
6460
+ const msg = err instanceof Error ? err.message : String(err);
6461
6461
  return `http_status=err http_err=${quoteDiag(msg.slice(0, 60))} http_ms=${Date.now() - start}`;
6462
6462
  }
6463
6463
  }
@@ -6539,8 +6539,8 @@ function sigtermFlushStreamLogs(reason, source) {
6539
6539
  `;
6540
6540
  try {
6541
6541
  appendFileSync2(entry.path, line);
6542
- } catch (err2) {
6543
- const msg = err2 instanceof Error ? err2.message : String(err2);
6542
+ } catch (err) {
6543
+ const msg = err instanceof Error ? err.message : String(err);
6544
6544
  console.error(`[server-sigterm-flush-err] path=${entry.path} reason=${msg}`);
6545
6545
  }
6546
6546
  }
@@ -6550,8 +6550,8 @@ function purgeOldLogs(logDir, prefix) {
6550
6550
  let entries;
6551
6551
  try {
6552
6552
  entries = readdirSync2(logDir);
6553
- } catch (err2) {
6554
- const msg = err2 instanceof Error ? err2.message : String(err2);
6553
+ } catch (err) {
6554
+ const msg = err instanceof Error ? err.message : String(err);
6555
6555
  console.error(`[log-purge-err] readdir dir=${logDir} prefix=${prefix} reason=${msg}`);
6556
6556
  return;
6557
6557
  }
@@ -6560,8 +6560,8 @@ function purgeOldLogs(logDir, prefix) {
6560
6560
  const filePath = resolve6(logDir, file);
6561
6561
  try {
6562
6562
  if (statSync3(filePath).mtimeMs < cutoff) unlinkSync2(filePath);
6563
- } catch (err2) {
6564
- const msg = err2 instanceof Error ? err2.message : String(err2);
6563
+ } catch (err) {
6564
+ const msg = err instanceof Error ? err.message : String(err);
6565
6565
  console.error(`[log-purge-err] file=${file} reason=${msg}`);
6566
6566
  }
6567
6567
  }
@@ -6617,8 +6617,8 @@ function sampleProcState(pid) {
6617
6617
  let openFds2 = 0;
6618
6618
  try {
6619
6619
  openFds2 = readdirSync2(fdDir).length;
6620
- } catch (err2) {
6621
- const msg = err2 instanceof Error ? err2.message : String(err2);
6620
+ } catch (err) {
6621
+ const msg = err instanceof Error ? err.message : String(err);
6622
6622
  return `proc_err=${JSON.stringify(msg.slice(0, 60))}`;
6623
6623
  }
6624
6624
  let established2 = 0;
@@ -6670,8 +6670,8 @@ function sampleProcState(pid) {
6670
6670
  }
6671
6671
  }
6672
6672
  return `open_fds=${openFds} socket_count=${sockets} tcp_established=${established} tcp_connecting=${connecting} rss_mb=unknown`;
6673
- } catch (err2) {
6674
- const msg = err2 instanceof Error ? err2.message : String(err2);
6673
+ } catch (err) {
6674
+ const msg = err instanceof Error ? err.message : String(err);
6675
6675
  return `proc_err=${JSON.stringify(msg.slice(0, 60))}`;
6676
6676
  }
6677
6677
  }
@@ -6764,8 +6764,8 @@ function resolveDefaultAgentSlug(accountDir) {
6764
6764
  let config;
6765
6765
  try {
6766
6766
  config = JSON.parse(readFileSync7(configPath2, "utf-8"));
6767
- } catch (err2) {
6768
- console.error("[agent-resolve] failed to read account.json:", err2);
6767
+ } catch (err) {
6768
+ console.error("[agent-resolve] failed to read account.json:", err);
6769
6769
  return null;
6770
6770
  }
6771
6771
  if (!config.defaultAgent) {
@@ -6964,8 +6964,8 @@ function autoDeliverPremiumPlugins(purchasedPlugins) {
6964
6964
  let bundleRaw;
6965
6965
  try {
6966
6966
  bundleRaw = readFileSync7(bundlePath, "utf-8");
6967
- } catch (err2) {
6968
- console.log(`${TAG18} ${pluginName}: cannot read BUNDLE.md \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
6967
+ } catch (err) {
6968
+ console.log(`${TAG18} ${pluginName}: cannot read BUNDLE.md \u2014 ${err instanceof Error ? err.message : String(err)}`);
6969
6969
  continue;
6970
6970
  }
6971
6971
  const fmMatch = bundleRaw.match(/^---\n([\s\S]*?)\n---/);
@@ -7007,8 +7007,8 @@ function autoDeliverPremiumPlugins(purchasedPlugins) {
7007
7007
  try {
7008
7008
  cpSync(source, target, { recursive: true });
7009
7009
  delivered++;
7010
- } catch (err2) {
7011
- console.log(`${TAG18} ${pluginName}/${sub}: copy failed \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
7010
+ } catch (err) {
7011
+ console.log(`${TAG18} ${pluginName}/${sub}: copy failed \u2014 ${err instanceof Error ? err.message : String(err)}`);
7012
7012
  }
7013
7013
  }
7014
7014
  console.log(`${TAG18} ${pluginName} (bundle): ${delivered} delivered, ${skipped} already present`);
@@ -7021,8 +7021,8 @@ function autoDeliverPremiumPlugins(purchasedPlugins) {
7021
7021
  try {
7022
7022
  cpSync(stagingDir, target, { recursive: true });
7023
7023
  console.log(`${TAG18} ${pluginName} (standalone): delivered`);
7024
- } catch (err2) {
7025
- console.log(`${TAG18} ${pluginName}: copy failed \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
7024
+ } catch (err) {
7025
+ console.log(`${TAG18} ${pluginName}: copy failed \u2014 ${err instanceof Error ? err.message : String(err)}`);
7026
7026
  }
7027
7027
  }
7028
7028
  }
@@ -7062,8 +7062,8 @@ function migratePluginRenames(accountDir, config) {
7062
7062
  writeFileSync5(configPath2, JSON.stringify(parsed, null, 2) + "\n");
7063
7063
  config.enabledPlugins = migrated;
7064
7064
  console.log(`${TAG18} account.json updated (${migrated.length} plugins)`);
7065
- } catch (err2) {
7066
- console.error(`${TAG18} failed to update account.json \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
7065
+ } catch (err) {
7066
+ console.error(`${TAG18} failed to update account.json \u2014 ${err instanceof Error ? err.message : String(err)}`);
7067
7067
  }
7068
7068
  const pluginsDir = resolve6(PLATFORM_ROOT4, "plugins");
7069
7069
  for (const oldName of Object.keys(PLUGIN_RENAMES)) {
@@ -7072,8 +7072,8 @@ function migratePluginRenames(accountDir, config) {
7072
7072
  try {
7073
7073
  rmSync2(orphan, { recursive: true });
7074
7074
  console.log(`${TAG18} removed orphan: ${oldName}`);
7075
- } catch (err2) {
7076
- console.log(`${TAG18} orphan removal failed: ${oldName} \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
7075
+ } catch (err) {
7076
+ console.log(`${TAG18} orphan removal failed: ${oldName} \u2014 ${err instanceof Error ? err.message : String(err)}`);
7077
7077
  }
7078
7078
  }
7079
7079
  }
@@ -7109,8 +7109,8 @@ function autoDeliverBundleAgents(accountDir, purchasedPlugins) {
7109
7109
  const source = resolve6(bundleAgentsDir, filename);
7110
7110
  try {
7111
7111
  cpSync(source, target);
7112
- } catch (err2) {
7113
- console.log(`${TAG18} copy failed: ${filename} \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
7112
+ } catch (err) {
7113
+ console.log(`${TAG18} copy failed: ${filename} \u2014 ${err instanceof Error ? err.message : String(err)}`);
7114
7114
  continue;
7115
7115
  }
7116
7116
  try {
@@ -7140,8 +7140,8 @@ function autoDeliverBundleAgents(accountDir, purchasedPlugins) {
7140
7140
  try {
7141
7141
  writeFileSync5(agentsmdPath, agentsmd);
7142
7142
  console.log(`${TAG18} AGENTS.md updated (${delivered} agents added)`);
7143
- } catch (err2) {
7144
- console.error(`${TAG18} AGENTS.md update failed \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
7143
+ } catch (err) {
7144
+ console.error(`${TAG18} AGENTS.md update failed \u2014 ${err instanceof Error ? err.message : String(err)}`);
7145
7145
  }
7146
7146
  }
7147
7147
  }
@@ -7297,8 +7297,8 @@ function loadEmbeddedPlugins(agentType, selectedPlugins, enabledPlugins) {
7297
7297
  let raw2;
7298
7298
  try {
7299
7299
  raw2 = readFileSync7(pluginPath, "utf-8");
7300
- } catch (err2) {
7301
- console.warn(`[plugins] ${dir}: failed to read PLUGIN.md for ${agentType} embed: ${String(err2)}`);
7300
+ } catch (err) {
7301
+ console.warn(`[plugins] ${dir}: failed to read PLUGIN.md for ${agentType} embed: ${String(err)}`);
7302
7302
  continue;
7303
7303
  }
7304
7304
  const body = raw2.replace(/^---\n[\s\S]*?\n---\n*/, "").trim();
@@ -7391,7 +7391,7 @@ function fetchMcpToolsList(pluginDir) {
7391
7391
  proc.stderr.on("data", (chunk) => {
7392
7392
  stderrBuf += chunk.toString();
7393
7393
  });
7394
- proc.on("error", (err2) => settle([], `spawn error: ${err2.message}`));
7394
+ proc.on("error", (err) => settle([], `spawn error: ${err.message}`));
7395
7395
  proc.on("close", (code) => {
7396
7396
  if (!settled) settle([], `process exited with code ${code}`);
7397
7397
  });
@@ -8362,7 +8362,7 @@ async function fetchMemoryContext(accountId, query, sessionKey, options) {
8362
8362
  proc.stderr.on("data", (chunk) => {
8363
8363
  stderrBuf += chunk.toString();
8364
8364
  });
8365
- proc.on("error", (err2) => settle(null, `spawn error: ${err2.message}`));
8365
+ proc.on("error", (err) => settle(null, `spawn error: ${err.message}`));
8366
8366
  proc.on("close", (code) => {
8367
8367
  if (!settled) settle(null, `process exited with code ${code}`);
8368
8368
  });
@@ -8526,11 +8526,11 @@ ${truncatedResponse}` : "No response text was generated.",
8526
8526
  streamLog.write(`[${isoTs()}] [context-overflow-recovery] summary=fallback reason=haiku-empty
8527
8527
  `);
8528
8528
  return basicTemplate;
8529
- } catch (err2) {
8530
- const reason = err2 instanceof Error ? err2.message : String(err2);
8529
+ } catch (err) {
8530
+ const reason = err instanceof Error ? err.message : String(err);
8531
8531
  streamLog.write(`[${isoTs()}] [context-overflow-recovery] summary=fallback reason=${reason}
8532
8532
  `);
8533
- if (!(err2 instanceof Error && (err2.name === "AbortError" || reason.includes("ECONNREFUSED") || reason.includes("ENOTFOUND")))) {
8533
+ if (!(err instanceof Error && (err.name === "AbortError" || reason.includes("ECONNREFUSED") || reason.includes("ENOTFOUND")))) {
8534
8534
  console.error(`[context-overflow-recovery] Haiku summary failed: ${reason}`);
8535
8535
  }
8536
8536
  return basicTemplate;
@@ -8640,9 +8640,9 @@ Extract preference updates as JSON array.`
8640
8640
  console.error(`[profile-reflection] Extracted ${sanitized.length} preference updates via Haiku (${updates.length - sanitized.length} filtered)`);
8641
8641
  const convId = sessionStore.get(sessionKey)?.conversationId;
8642
8642
  return await writeReflectionPreferences(accountId, userId, convId, sanitized);
8643
- } catch (err2) {
8644
- const reason = err2 instanceof Error ? err2.message : String(err2);
8645
- if (err2 instanceof Error && err2.name === "AbortError") {
8643
+ } catch (err) {
8644
+ const reason = err instanceof Error ? err.message : String(err);
8645
+ if (err instanceof Error && err.name === "AbortError") {
8646
8646
  console.error(`[profile-reflection] Haiku call timed out after ${REFLECTION_TIMEOUT_MS}ms`);
8647
8647
  } else {
8648
8648
  console.error(`[profile-reflection] Haiku call failed: ${reason}`);
@@ -8750,8 +8750,8 @@ async function* runCompactionTurn(accountDir, accountId, systemPrompt, resumeSes
8750
8750
  `);
8751
8751
  streamLog.write(`[${isoTs()}] [compaction-start] resumeSessionId=${resumeSessionId}
8752
8752
  `);
8753
- proc.on("error", (err2) => {
8754
- if (!streamLog.destroyed && !streamLog.writableEnded) streamLog.write(`[${isoTs()}] [compaction-spawn-error] ${err2.message}
8753
+ proc.on("error", (err) => {
8754
+ if (!streamLog.destroyed && !streamLog.writableEnded) streamLog.write(`[${isoTs()}] [compaction-spawn-error] ${err.message}
8755
8755
  `);
8756
8756
  });
8757
8757
  yield "Summarising session...";
@@ -8884,8 +8884,8 @@ async function* parseClaudeStream(proc, streamLog, adminModel, conversationId, a
8884
8884
  streamLog.write(`[${isoTs()}] [tool-wait-diag]${convIdTag} name=${info.name} tool_use_id=${toolUseId} elapsed=${elapsedSec}s ${diag}
8885
8885
  `);
8886
8886
  }
8887
- }).catch((err2) => {
8888
- const msg = err2 instanceof Error ? err2.message : String(err2);
8887
+ }).catch((err) => {
8888
+ const msg = err instanceof Error ? err.message : String(err);
8889
8889
  if (!streamLog.destroyed && !streamLog.writableEnded) {
8890
8890
  streamLog.write(`[${isoTs()}] [tool-wait-diag]${convIdTag} name=${info.name} tool_use_id=${toolUseId} elapsed=${elapsedSec}s diag_err=${JSON.stringify(msg.slice(0, 80))}
8891
8891
  `);
@@ -9187,9 +9187,9 @@ async function* parseClaudeStream(proc, streamLog, adminModel, conversationId, a
9187
9187
  streamLog.write(`[${isoTs()}] [tool-failure-diag]${convIdTag} name=${name} ${diag}
9188
9188
  `);
9189
9189
  }
9190
- } catch (err2) {
9190
+ } catch (err) {
9191
9191
  if (!streamLog.destroyed) {
9192
- const msg2 = err2 instanceof Error ? err2.message : String(err2);
9192
+ const msg2 = err instanceof Error ? err.message : String(err);
9193
9193
  streamLog.write(`[${isoTs()}] [tool-failure-diag]${convIdTag} name=${name} diag_err=${JSON.stringify(msg2.slice(0, 80))}
9194
9194
  `);
9195
9195
  }
@@ -9681,8 +9681,8 @@ async function* invokeAdminAgent(message, systemPrompt, accountDir, accountId, a
9681
9681
  `);
9682
9682
  if (sessionKey) activeProcesses.delete(sessionKey);
9683
9683
  });
9684
- proc.on("error", (err2) => {
9685
- if (!streamLog.destroyed && !streamLog.writableEnded) streamLog.write(`[${isoTs()}] [spawn-error] ${err2.message}
9684
+ proc.on("error", (err) => {
9685
+ if (!streamLog.destroyed && !streamLog.writableEnded) streamLog.write(`[${isoTs()}] [spawn-error] ${err.message}
9686
9686
  `);
9687
9687
  });
9688
9688
  let currentAgentSessionId;
@@ -9756,8 +9756,8 @@ async function* invokeAdminAgent(message, systemPrompt, accountDir, accountId, a
9756
9756
  const reflectionUserId = getUserIdForSession(sessionKey);
9757
9757
  if (reflectionUserId) {
9758
9758
  const profileForReflection = await loadUserProfile(accountId, reflectionUserId);
9759
- reflectOnSessionProfile(accountId, reflectionUserId, sessionKey, profileForReflection).catch((err2) => {
9760
- console.error(`[profile-reflection] Unhandled error: ${err2 instanceof Error ? err2.message : String(err2)}`);
9759
+ reflectOnSessionProfile(accountId, reflectionUserId, sessionKey, profileForReflection).catch((err) => {
9760
+ console.error(`[profile-reflection] Unhandled error: ${err instanceof Error ? err.message : String(err)}`);
9761
9761
  });
9762
9762
  }
9763
9763
  clearAgentSessionId(sessionKey, "compaction-complete");
@@ -9786,8 +9786,8 @@ async function* invokeAdminAgent(message, systemPrompt, accountDir, accountId, a
9786
9786
  (step.value.summary ? step.value.summary + "\n\n" : "") + "Recovered conversation context:\n" + contextPairs
9787
9787
  );
9788
9788
  }
9789
- } catch (err2) {
9790
- console.error(`[persist] Context re-seeding failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
9789
+ } catch (err) {
9790
+ console.error(`[persist] Context re-seeding failed: ${err instanceof Error ? err.message : String(err)}`);
9791
9791
  }
9792
9792
  }
9793
9793
  }
@@ -9799,8 +9799,8 @@ async function* invokeAdminAgent(message, systemPrompt, accountDir, accountId, a
9799
9799
  yield { type: "status", message: step.value };
9800
9800
  step = await compactionIter.next();
9801
9801
  }
9802
- } catch (err2) {
9803
- const msg = err2 instanceof Error ? err2.message : String(err2);
9802
+ } catch (err) {
9803
+ const msg = err instanceof Error ? err.message : String(err);
9804
9804
  streamLog.write(`[${isoTs()}] [session-reset] compaction failed: ${msg}
9805
9805
  `);
9806
9806
  yield { type: "status", message: "Compaction failed \u2014 resetting anyway." };
@@ -9921,8 +9921,8 @@ async function* invokeManagedAdminAgent(message, systemPrompt, accountDir, accou
9921
9921
  }
9922
9922
  const pendingTrimmed = consumePendingTrimmedMessages(sessionKey);
9923
9923
  if (pendingTrimmed && pendingTrimmed.length > 0) {
9924
- const ok2 = await compactTrimmedMessages(accountId, pendingTrimmed);
9925
- if (!ok2) {
9924
+ const ok = await compactTrimmedMessages(accountId, pendingTrimmed);
9925
+ if (!ok) {
9926
9926
  storePendingTrimmedMessages(sessionKey, pendingTrimmed);
9927
9927
  }
9928
9928
  }
@@ -9946,8 +9946,8 @@ async function* invokeManagedAdminAgent(message, systemPrompt, accountDir, accou
9946
9946
  const trimmed = trimHistory(sessionKey, historyBudget);
9947
9947
  if (trimmed.length > 0) {
9948
9948
  yield { type: "status", message: "Archiving older messages..." };
9949
- const ok2 = await compactTrimmedMessages(accountId, trimmed);
9950
- if (!ok2) {
9949
+ const ok = await compactTrimmedMessages(accountId, trimmed);
9950
+ if (!ok) {
9951
9951
  storePendingTrimmedMessages(sessionKey, trimmed);
9952
9952
  }
9953
9953
  }
@@ -10017,8 +10017,8 @@ async function* invokeManagedAdminAgent(message, systemPrompt, accountDir, accou
10017
10017
  `);
10018
10018
  if (sessionKey) activeProcesses.delete(sessionKey);
10019
10019
  });
10020
- proc.on("error", (err2) => {
10021
- if (!streamLog.destroyed && !streamLog.writableEnded) streamLog.write(`[${isoTs()}] [spawn-error] ${err2.message}
10020
+ proc.on("error", (err) => {
10021
+ if (!streamLog.destroyed && !streamLog.writableEnded) streamLog.write(`[${isoTs()}] [spawn-error] ${err.message}
10022
10022
  `);
10023
10023
  });
10024
10024
  let responseText = "";
@@ -10088,8 +10088,8 @@ async function* invokeManagedAdminAgent(message, systemPrompt, accountDir, accou
10088
10088
  yield { type: "status", message: step.value };
10089
10089
  step = await compactionIter.next();
10090
10090
  }
10091
- } catch (err2) {
10092
- const msg = err2 instanceof Error ? err2.message : String(err2);
10091
+ } catch (err) {
10092
+ const msg = err instanceof Error ? err.message : String(err);
10093
10093
  streamLog.write(`[${isoTs()}] [session-reset] compaction failed: ${msg}
10094
10094
  `);
10095
10095
  yield { type: "status", message: "Compaction failed \u2014 resetting anyway." };
@@ -10244,8 +10244,8 @@ async function* invokePublicAgent(message, systemPrompt, accountId, accountDir,
10244
10244
  if (sessionKey) {
10245
10245
  const pendingTrimmed = consumePendingTrimmedMessages(sessionKey);
10246
10246
  if (pendingTrimmed && pendingTrimmed.length > 0) {
10247
- const ok2 = await compactTrimmedMessages(accountId, pendingTrimmed);
10248
- if (!ok2) {
10247
+ const ok = await compactTrimmedMessages(accountId, pendingTrimmed);
10248
+ if (!ok) {
10249
10249
  storePendingTrimmedMessages(sessionKey, pendingTrimmed);
10250
10250
  }
10251
10251
  }
@@ -10256,8 +10256,8 @@ async function* invokePublicAgent(message, systemPrompt, accountId, accountDir,
10256
10256
  const trimmed = trimHistory(sessionKey, historyBudget);
10257
10257
  if (trimmed.length > 0) {
10258
10258
  yield { type: "status", message: "Archiving older messages..." };
10259
- const ok2 = await compactTrimmedMessages(accountId, trimmed);
10260
- if (!ok2) {
10259
+ const ok = await compactTrimmedMessages(accountId, trimmed);
10260
+ if (!ok) {
10261
10261
  storePendingTrimmedMessages(sessionKey, trimmed);
10262
10262
  }
10263
10263
  }
@@ -10502,12 +10502,12 @@ async function* compactSession(sessionKey) {
10502
10502
  const history = getMessageHistory(sessionKey);
10503
10503
  if (history.length === 0) return { ok: true };
10504
10504
  yield "Saving to memory...";
10505
- const ok2 = await compactTrimmedMessages(account.accountId, history);
10506
- if (ok2) {
10505
+ const ok = await compactTrimmedMessages(account.accountId, history);
10506
+ if (ok) {
10507
10507
  if (session) session.messageHistory = [];
10508
10508
  }
10509
10509
  yield "Closing session...";
10510
- return { ok: ok2 };
10510
+ return { ok };
10511
10511
  }
10512
10512
  const currentSessionId = getAgentSessionId(sessionKey);
10513
10513
  if (!currentSessionId) return { ok: false, reason: "no-session" };
@@ -10533,8 +10533,8 @@ ${EXPLANATORY_STYLE_INSTRUCTIONS}` : baseSystemPrompt;
10533
10533
  const compactUserId = getUserIdForSession(sessionKey);
10534
10534
  if (compactAgentType === "admin" && compactUserId) {
10535
10535
  const currentProfile = await loadUserProfile(account.accountId, compactUserId);
10536
- reflectOnSessionProfile(account.accountId, compactUserId, sessionKey, currentProfile).catch((err2) => {
10537
- console.error(`[profile-reflection] Unhandled error: ${err2 instanceof Error ? err2.message : String(err2)}`);
10536
+ reflectOnSessionProfile(account.accountId, compactUserId, sessionKey, currentProfile).catch((err) => {
10537
+ console.error(`[profile-reflection] Unhandled error: ${err instanceof Error ? err.message : String(err)}`);
10538
10538
  });
10539
10539
  }
10540
10540
  clearAgentSessionId(sessionKey, "session-compact-complete");
@@ -10625,8 +10625,8 @@ ${sessionContext}`;
10625
10625
  let skillContent = "";
10626
10626
  try {
10627
10627
  skillContent = readFileSync7(skillPath, "utf-8");
10628
- } catch (err2) {
10629
- console.error(`[onboarding-inject] accountId=${accountId.slice(0, 8)}\u2026 error=skill-read-failed path=${skillPath} reason=${err2 instanceof Error ? err2.message : String(err2)}`);
10628
+ } catch (err) {
10629
+ console.error(`[onboarding-inject] accountId=${accountId.slice(0, 8)}\u2026 error=skill-read-failed path=${skillPath} reason=${err instanceof Error ? err.message : String(err)}`);
10630
10630
  }
10631
10631
  const skillBytes = Buffer.byteLength(skillContent, "utf-8");
10632
10632
  if (skillContent.length > 0) {
@@ -10680,8 +10680,8 @@ ${manifest}`;
10680
10680
  baseSystemPrompt += `
10681
10681
 
10682
10682
  ${graphRef}`;
10683
- } catch (err2) {
10684
- console.error(`[graph-primitives] reference missing at ${graphRefPath} \u2014 admin session will have no Cypher cookbook: ${err2 instanceof Error ? err2.message : String(err2)}`);
10683
+ } catch (err) {
10684
+ console.error(`[graph-primitives] reference missing at ${graphRefPath} \u2014 admin session will have no Cypher cookbook: ${err instanceof Error ? err.message : String(err)}`);
10685
10685
  }
10686
10686
  }
10687
10687
  if (agentConfig?.budget) {
@@ -10765,8 +10765,8 @@ ${gwParts.join("\n")}`;
10765
10765
  if (sessionKey) {
10766
10766
  try {
10767
10767
  await ensureConversation(accountId, agentType, sessionKey, void 0, void 0, sessionUserId);
10768
- } catch (err2) {
10769
- console.error(`[persist] ensureConversation failed in invokeAgent: ${err2 instanceof Error ? err2.message : String(err2)}`);
10768
+ } catch (err) {
10769
+ console.error(`[persist] ensureConversation failed in invokeAgent: ${err instanceof Error ? err.message : String(err)}`);
10770
10770
  }
10771
10771
  }
10772
10772
  if (agentType !== "public") {
@@ -10780,8 +10780,8 @@ ${gwParts.join("\n")}`;
10780
10780
  const classifyStartMs = Date.now();
10781
10781
  const [adminClassification, commitments] = await Promise.all([
10782
10782
  needsTopicCheck ? classifyMemoryQuery(message, history) : Promise.resolve(QUERY_CLASSIFIER_FALLBACK),
10783
- classifyCommitments(message, history).catch((err2) => {
10784
- console.error(`[commitment-classifier] unexpected error: ${err2 instanceof Error ? err2.message : String(err2)}`);
10783
+ classifyCommitments(message, history).catch((err) => {
10784
+ console.error(`[commitment-classifier] unexpected error: ${err instanceof Error ? err.message : String(err)}`);
10785
10785
  return [];
10786
10786
  })
10787
10787
  ]);
@@ -10811,8 +10811,8 @@ ${block}`;
10811
10811
  }
10812
10812
  console.log(`[commitment-offer] sessionKey=${sk}\u2026 count=${commitments.filter((c) => c.confidence >= COMMITMENT_CONFIDENCE_THRESHOLD).length} summaries=${commitments.filter((c) => c.confidence >= COMMITMENT_CONFIDENCE_THRESHOLD).map((c) => JSON.stringify(c.what)).join(",")}`);
10813
10813
  }
10814
- } catch (err2) {
10815
- console.error(`[commitment-classifier] block error: ${err2 instanceof Error ? err2.message : String(err2)}`);
10814
+ } catch (err) {
10815
+ console.error(`[commitment-classifier] block error: ${err instanceof Error ? err.message : String(err)}`);
10816
10816
  }
10817
10817
  }
10818
10818
  if (agentType === "public") {
@@ -11285,8 +11285,8 @@ function loadRules(configDir2) {
11285
11285
  let parsed;
11286
11286
  try {
11287
11287
  parsed = JSON.parse(raw2);
11288
- } catch (err2) {
11289
- throw new Error(`rules file ${path2} is not valid JSON: ${err2 instanceof Error ? err2.message : String(err2)}`);
11288
+ } catch (err) {
11289
+ throw new Error(`rules file ${path2} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
11290
11290
  }
11291
11291
  return validateRulesFile(parsed, path2);
11292
11292
  }
@@ -11375,8 +11375,8 @@ function validateRule(input, label, seenIds) {
11375
11375
  if (pattern.length > 0) {
11376
11376
  try {
11377
11377
  new RegExp(pattern);
11378
- } catch (err2) {
11379
- throw new Error(`${label}: pattern is not a valid regex: ${err2 instanceof Error ? err2.message : String(err2)}`);
11378
+ } catch (err) {
11379
+ throw new Error(`${label}: pattern is not a valid regex: ${err instanceof Error ? err.message : String(err)}`);
11380
11380
  }
11381
11381
  }
11382
11382
  const thresholdCount = r.thresholdCount;
@@ -11407,8 +11407,8 @@ function validateRule(input, label, seenIds) {
11407
11407
  if (r.followupPattern.length > 0) {
11408
11408
  try {
11409
11409
  new RegExp(r.followupPattern);
11410
- } catch (err2) {
11411
- throw new Error(`${label}: followupPattern is not a valid regex: ${err2 instanceof Error ? err2.message : String(err2)}`);
11410
+ } catch (err) {
11411
+ throw new Error(`${label}: followupPattern is not a valid regex: ${err instanceof Error ? err.message : String(err)}`);
11412
11412
  }
11413
11413
  }
11414
11414
  rule.followupPattern = r.followupPattern;
@@ -11466,8 +11466,8 @@ function loadTailState(configDir2) {
11466
11466
  }
11467
11467
  }
11468
11468
  return clean;
11469
- } catch (err2) {
11470
- console.error(`[review] tail state corrupt at ${path2}, starting fresh: ${err2 instanceof Error ? err2.message : String(err2)}`);
11469
+ } catch (err) {
11470
+ console.error(`[review] tail state corrupt at ${path2}, starting fresh: ${err instanceof Error ? err.message : String(err)}`);
11471
11471
  return {};
11472
11472
  }
11473
11473
  }
@@ -11643,8 +11643,8 @@ function reviewLog(configDir2, event) {
11643
11643
  ).toISOString()} [review] ${JSON.stringify(event)}
11644
11644
  `;
11645
11645
  appendFileSync3(path2, line, "utf-8");
11646
- } catch (err2) {
11647
- console.error(`[review] failed to write review log at ${path2}: ${err2 instanceof Error ? err2.message : String(err2)}`);
11646
+ } catch (err) {
11647
+ console.error(`[review] failed to write review log at ${path2}: ${err instanceof Error ? err.message : String(err)}`);
11648
11648
  }
11649
11649
  }
11650
11650
  async function ensureReviewAlertIndex() {
@@ -11757,8 +11757,8 @@ function queueAlert(configDir2, accountId, match2) {
11757
11757
  mkdirSync7(dirname4(path2), { recursive: true });
11758
11758
  const line = JSON.stringify({ accountId, match: match2 }) + "\n";
11759
11759
  appendFileSync3(path2, line, "utf-8");
11760
- } catch (err2) {
11761
- console.error(`[review] failed to queue alert at ${path2}: ${err2 instanceof Error ? err2.message : String(err2)}`);
11760
+ } catch (err) {
11761
+ console.error(`[review] failed to queue alert at ${path2}: ${err instanceof Error ? err.message : String(err)}`);
11762
11762
  }
11763
11763
  }
11764
11764
  async function drainPendingAlerts(configDir2) {
@@ -11810,13 +11810,13 @@ async function bootDetector() {
11810
11810
  let rulesFile;
11811
11811
  try {
11812
11812
  rulesFile = loadRules(configDir2);
11813
- } catch (err2) {
11813
+ } catch (err) {
11814
11814
  reviewLog(configDir2, {
11815
11815
  event: "boot-failed",
11816
11816
  reason: "rules-invalid",
11817
- error: err2 instanceof Error ? err2.message : String(err2)
11817
+ error: err instanceof Error ? err.message : String(err)
11818
11818
  });
11819
- console.error(`[review] boot: rules file invalid \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
11819
+ console.error(`[review] boot: rules file invalid \u2014 ${err instanceof Error ? err.message : String(err)}`);
11820
11820
  return null;
11821
11821
  }
11822
11822
  if (addMissingDefaultRules(rulesFile)) {
@@ -11832,22 +11832,22 @@ async function bootDetector() {
11832
11832
  try {
11833
11833
  await ensureReviewAlertIndex();
11834
11834
  reviewLog(configDir2, { event: "neo4j-index-ensured" });
11835
- } catch (err2) {
11835
+ } catch (err) {
11836
11836
  reviewLog(configDir2, {
11837
11837
  event: "neo4j-index-failed",
11838
- error: err2 instanceof Error ? err2.message : String(err2)
11838
+ error: err instanceof Error ? err.message : String(err)
11839
11839
  });
11840
- console.error(`[review] boot: ensureReviewAlertIndex failed (continuing): ${err2 instanceof Error ? err2.message : String(err2)}`);
11840
+ console.error(`[review] boot: ensureReviewAlertIndex failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
11841
11841
  }
11842
11842
  try {
11843
11843
  await ensureReviewDigestSchedule(accountId);
11844
11844
  reviewLog(configDir2, { event: "digest-schedule-ensured" });
11845
- } catch (err2) {
11845
+ } catch (err) {
11846
11846
  reviewLog(configDir2, {
11847
11847
  event: "digest-schedule-failed",
11848
- error: err2 instanceof Error ? err2.message : String(err2)
11848
+ error: err instanceof Error ? err.message : String(err)
11849
11849
  });
11850
- console.error(`[review] boot: ensureReviewDigestSchedule failed (continuing): ${err2 instanceof Error ? err2.message : String(err2)}`);
11850
+ console.error(`[review] boot: ensureReviewDigestSchedule failed (continuing): ${err instanceof Error ? err.message : String(err)}`);
11851
11851
  }
11852
11852
  const tailState = loadTailState(configDir2);
11853
11853
  const logDir = accountLogDir(accountDir);
@@ -12104,13 +12104,13 @@ async function runScanCycle(runtime) {
12104
12104
  rulesLoaded: runtime.rulesFile.rules.length,
12105
12105
  mtime: new Date(currentMtime).toISOString()
12106
12106
  });
12107
- } catch (err2) {
12107
+ } catch (err) {
12108
12108
  reviewLog(runtime.configDir, {
12109
12109
  event: "rules-reload-failed",
12110
- error: err2 instanceof Error ? err2.message : String(err2)
12110
+ error: err instanceof Error ? err.message : String(err)
12111
12111
  });
12112
12112
  runtime.snapshot.state = "degraded";
12113
- runtime.snapshot.lastError = err2 instanceof Error ? err2.message : String(err2);
12113
+ runtime.snapshot.lastError = err instanceof Error ? err.message : String(err);
12114
12114
  }
12115
12115
  }
12116
12116
  const logDir = accountLogDir(runtime.accountDir);
@@ -12237,12 +12237,12 @@ async function runScanCycle(runtime) {
12237
12237
  try {
12238
12238
  await upsertReviewAlert(runtime.accountId, match2);
12239
12239
  reviewLog(runtime.configDir, { event: "alert-persisted", ruleId: match2.ruleId });
12240
- } catch (err2) {
12240
+ } catch (err) {
12241
12241
  queueAlert(runtime.configDir, runtime.accountId, match2);
12242
12242
  reviewLog(runtime.configDir, {
12243
12243
  event: "alert-queued",
12244
12244
  ruleId: match2.ruleId,
12245
- error: err2 instanceof Error ? err2.message : String(err2)
12245
+ error: err instanceof Error ? err.message : String(err)
12246
12246
  });
12247
12247
  }
12248
12248
  }
@@ -12255,18 +12255,18 @@ async function runScanCycle(runtime) {
12255
12255
  remaining: drain.remaining
12256
12256
  });
12257
12257
  }
12258
- } catch (err2) {
12258
+ } catch (err) {
12259
12259
  reviewLog(runtime.configDir, {
12260
12260
  event: "queue-drain-failed",
12261
- error: err2 instanceof Error ? err2.message : String(err2)
12261
+ error: err instanceof Error ? err.message : String(err)
12262
12262
  });
12263
12263
  }
12264
12264
  try {
12265
12265
  runtime.snapshot.activeAlerts = await countActiveReviewAlerts(runtime.accountId);
12266
- } catch (err2) {
12266
+ } catch (err) {
12267
12267
  reviewLog(runtime.configDir, {
12268
12268
  event: "active-alerts-count-failed",
12269
- error: err2 instanceof Error ? err2.message : String(err2)
12269
+ error: err instanceof Error ? err.message : String(err)
12270
12270
  });
12271
12271
  }
12272
12272
  saveTailState(runtime.configDir, runtime.tailState);
@@ -12285,12 +12285,12 @@ async function runScanCycle(runtime) {
12285
12285
  matches: matches.length,
12286
12286
  durationMs: cycleDuration
12287
12287
  });
12288
- } catch (err2) {
12288
+ } catch (err) {
12289
12289
  runtime.snapshot.state = "degraded";
12290
- runtime.snapshot.lastError = err2 instanceof Error ? err2.message : String(err2);
12290
+ runtime.snapshot.lastError = err instanceof Error ? err.message : String(err);
12291
12291
  reviewLog(runtime.configDir, {
12292
12292
  event: "cycle-failed",
12293
- error: err2 instanceof Error ? err2.message : String(err2)
12293
+ error: err instanceof Error ? err.message : String(err)
12294
12294
  });
12295
12295
  }
12296
12296
  }
@@ -12333,16 +12333,16 @@ async function startReviewDetector() {
12333
12333
  activeRuntime = await bootDetector();
12334
12334
  if (!activeRuntime) return;
12335
12335
  stopFn = startScanLoop(activeRuntime);
12336
- } catch (err2) {
12337
- console.error(`[review] detector start failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
12336
+ } catch (err) {
12337
+ console.error(`[review] detector start failed: ${err instanceof Error ? err.message : String(err)}`);
12338
12338
  }
12339
12339
  }
12340
12340
  async function shutdownReviewDetector() {
12341
12341
  if (!stopFn) return;
12342
12342
  try {
12343
12343
  await stopFn();
12344
- } catch (err2) {
12345
- console.error(`[review] detector shutdown error: ${err2 instanceof Error ? err2.message : String(err2)}`);
12344
+ } catch (err) {
12345
+ console.error(`[review] detector shutdown error: ${err instanceof Error ? err.message : String(err)}`);
12346
12346
  }
12347
12347
  stopFn = null;
12348
12348
  activeRuntime = null;
@@ -12447,8 +12447,8 @@ function reloadManagerConfig(accountDir) {
12447
12447
  const config = readConfig(accountDir);
12448
12448
  reloadConfig(config);
12449
12449
  console.error(`${TAG2} reloaded manager config`);
12450
- } catch (err2) {
12451
- console.error(`${TAG2} manager config reload failed: ${String(err2)}`);
12450
+ } catch (err) {
12451
+ console.error(`${TAG2} manager config reload failed: ${String(err)}`);
12452
12452
  }
12453
12453
  }
12454
12454
  var E164_PATTERN = /^\+\d{7,15}$/;
@@ -12509,8 +12509,8 @@ function persistAfterPairing(accountDir, accountId, selfPhone) {
12509
12509
  console.error(`${TAG2} persisted after pairing account=${accountId} phone=${selfPhone ?? "null"}`);
12510
12510
  reloadManagerConfig(accountDir);
12511
12511
  return { ok: true };
12512
- } catch (err2) {
12513
- const msg = err2 instanceof Error ? err2.message : String(err2);
12512
+ } catch (err) {
12513
+ const msg = err instanceof Error ? err.message : String(err);
12514
12514
  console.error(`${TAG2} persist failed account=${accountId}: ${msg}`);
12515
12515
  return { ok: false, error: msg };
12516
12516
  }
@@ -12545,8 +12545,8 @@ function addAdminPhone(accountDir, phone) {
12545
12545
  console.error(`${TAG2} added admin phone=${normalized}`);
12546
12546
  reloadManagerConfig(accountDir);
12547
12547
  return { ok: true, message: `Added ${normalized} as admin phone. Messages from this number will route to the admin agent.` };
12548
- } catch (err2) {
12549
- const msg = err2 instanceof Error ? err2.message : String(err2);
12548
+ } catch (err) {
12549
+ const msg = err instanceof Error ? err.message : String(err);
12550
12550
  console.error(`${TAG2} addAdminPhone failed: ${msg}`);
12551
12551
  return { ok: false, error: msg };
12552
12552
  }
@@ -12579,8 +12579,8 @@ function removeAdminPhone(accountDir, phone) {
12579
12579
  console.error(`${TAG2} removed admin phone=${normalized}`);
12580
12580
  reloadManagerConfig(accountDir);
12581
12581
  return { ok: true, message: `Removed ${normalized} from admin phones. Messages from this number will now route to the public agent.` };
12582
- } catch (err2) {
12583
- const msg = err2 instanceof Error ? err2.message : String(err2);
12582
+ } catch (err) {
12583
+ const msg = err instanceof Error ? err.message : String(err);
12584
12584
  console.error(`${TAG2} removeAdminPhone failed: ${msg}`);
12585
12585
  return { ok: false, error: msg };
12586
12586
  }
@@ -12631,8 +12631,8 @@ function setPublicAgent(accountDir, slug) {
12631
12631
  console.error(`${TAG2} publicAgent set to ${trimmed}`);
12632
12632
  reloadManagerConfig(accountDir);
12633
12633
  return { ok: true, message: `Public agent set to "${trimmed}". WhatsApp messages from non-admin phones will be handled by this agent.` };
12634
- } catch (err2) {
12635
- const msg = err2 instanceof Error ? err2.message : String(err2);
12634
+ } catch (err) {
12635
+ const msg = err instanceof Error ? err.message : String(err);
12636
12636
  console.error(`${TAG2} setPublicAgent failed: ${msg}`);
12637
12637
  return { ok: false, error: msg };
12638
12638
  }
@@ -12677,8 +12677,8 @@ function updateConfig(accountDir, fields) {
12677
12677
  console.error(`${TAG2} updated fields=[${fieldNames.join(",")}]`);
12678
12678
  reloadManagerConfig(accountDir);
12679
12679
  return { ok: true, message: `Updated WhatsApp config: ${fieldNames.join(", ")}.` };
12680
- } catch (err2) {
12681
- const msg = err2 instanceof Error ? err2.message : String(err2);
12680
+ } catch (err) {
12681
+ const msg = err instanceof Error ? err.message : String(err);
12682
12682
  console.error(`${TAG2} updateConfig failed: ${msg}`);
12683
12683
  return { ok: false, error: msg };
12684
12684
  }
@@ -12738,8 +12738,8 @@ async function authExists(authDir) {
12738
12738
  const raw2 = await fs.readFile(credsPath, "utf-8");
12739
12739
  JSON.parse(raw2);
12740
12740
  return true;
12741
- } catch (err2) {
12742
- console.warn(`${TAG3} credential validation failed path=${credsPath}: ${String(err2)}`);
12741
+ } catch (err) {
12742
+ console.warn(`${TAG3} credential validation failed path=${credsPath}: ${String(err)}`);
12743
12743
  return false;
12744
12744
  }
12745
12745
  }
@@ -12767,8 +12767,8 @@ function maybeRestoreCredsFromBackup(authDir) {
12767
12767
  JSON.parse(backupRaw);
12768
12768
  fsSync.copyFileSync(backupPath, credsPath);
12769
12769
  console.error(`${TAG3} restored corrupted creds.json from backup in ${authDir}`);
12770
- } catch (err2) {
12771
- console.warn(`${TAG3} credential restore failed authDir=${authDir}: ${String(err2)}`);
12770
+ } catch (err) {
12771
+ console.warn(`${TAG3} credential restore failed authDir=${authDir}: ${String(err)}`);
12772
12772
  }
12773
12773
  }
12774
12774
  function readSelfId(authDir) {
@@ -12784,8 +12784,8 @@ function readSelfId(authDir) {
12784
12784
  if (match2) e164 = match2[1];
12785
12785
  }
12786
12786
  return { e164, jid };
12787
- } catch (err2) {
12788
- console.warn(`${TAG3} readSelfId failed authDir=${authDir}: ${String(err2)}`);
12787
+ } catch (err) {
12788
+ console.warn(`${TAG3} readSelfId failed authDir=${authDir}: ${String(err)}`);
12789
12789
  return { e164: null, jid: null };
12790
12790
  }
12791
12791
  }
@@ -12846,8 +12846,8 @@ function serializeArg(arg) {
12846
12846
  if (typeof arg === "string") return arg;
12847
12847
  try {
12848
12848
  return inspect(arg, INSPECT_OPTS);
12849
- } catch (err2) {
12850
- return `[inspect-failed: ${String(err2)}]`;
12849
+ } catch (err) {
12850
+ return `[inspect-failed: ${String(err)}]`;
12851
12851
  }
12852
12852
  }
12853
12853
  function bindingsToPrefix(bindings) {
@@ -12917,12 +12917,12 @@ async function safeSaveCreds(authDir, saveCreds) {
12917
12917
  try {
12918
12918
  JSON.parse(raw2);
12919
12919
  fsSync2.copyFileSync(credsPath, backupPath);
12920
- } catch (err2) {
12921
- console.warn(`${TAG4} backup pre-copy failed (parse or write) authDir=${authDir}: ${String(err2)}`);
12920
+ } catch (err) {
12921
+ console.warn(`${TAG4} backup pre-copy failed (parse or write) authDir=${authDir}: ${String(err)}`);
12922
12922
  }
12923
12923
  }
12924
- } catch (err2) {
12925
- console.warn(`${TAG4} backup preparation failed authDir=${authDir}: ${String(err2)}`);
12924
+ } catch (err) {
12925
+ console.warn(`${TAG4} backup preparation failed authDir=${authDir}: ${String(err)}`);
12926
12926
  }
12927
12927
  try {
12928
12928
  await Promise.resolve(saveCreds());
@@ -12937,13 +12937,13 @@ async function safeSaveCreds(authDir, saveCreds) {
12937
12937
  } catch (statErr) {
12938
12938
  console.error(`${TAG4} creds NOT found on disk after save path=${credsPath}: ${String(statErr)}`);
12939
12939
  }
12940
- } catch (err2) {
12941
- console.error(`${TAG4} failed saving creds to ${authDir}: ${String(err2)}`);
12940
+ } catch (err) {
12941
+ console.error(`${TAG4} failed saving creds to ${authDir}: ${String(err)}`);
12942
12942
  }
12943
12943
  }
12944
12944
  function enqueueSaveCreds(authDir, saveCreds) {
12945
- credsSaveQueue = credsSaveQueue.then(() => safeSaveCreds(authDir, saveCreds)).catch((err2) => {
12946
- console.error(`${TAG4} creds save queue error: ${String(err2)}`);
12945
+ credsSaveQueue = credsSaveQueue.then(() => safeSaveCreds(authDir, saveCreds)).catch((err) => {
12946
+ console.error(`${TAG4} creds save queue error: ${String(err)}`);
12947
12947
  });
12948
12948
  }
12949
12949
  async function createWaSocket(opts) {
@@ -13002,13 +13002,13 @@ async function createWaSocket(opts) {
13002
13002
  console.error(`${TAG4} connected`);
13003
13003
  }
13004
13004
  onConnectionUpdate?.(update);
13005
- } catch (err2) {
13006
- console.error(`${TAG4} connection.update handler error: ${String(err2)}`);
13005
+ } catch (err) {
13006
+ console.error(`${TAG4} connection.update handler error: ${String(err)}`);
13007
13007
  }
13008
13008
  });
13009
13009
  if (sock.ws && typeof sock.ws.on === "function") {
13010
- sock.ws.on("error", (err2) => {
13011
- console.error(`${TAG4} WebSocket error: ${String(err2)}`);
13010
+ sock.ws.on("error", (err) => {
13011
+ console.error(`${TAG4} WebSocket error: ${String(err)}`);
13012
13012
  });
13013
13013
  }
13014
13014
  return sock;
@@ -13028,21 +13028,21 @@ async function waitForConnection(sock) {
13028
13028
  sock.ev.on("connection.update", handler);
13029
13029
  });
13030
13030
  }
13031
- function getStatusCode(err2) {
13032
- return err2?.error?.output?.statusCode ?? err2?.output?.statusCode ?? err2?.status;
13031
+ function getStatusCode(err) {
13032
+ return err?.error?.output?.statusCode ?? err?.output?.statusCode ?? err?.status;
13033
13033
  }
13034
- function formatError(err2) {
13035
- if (err2 instanceof Error) return err2.message;
13036
- if (typeof err2 === "string") return err2;
13037
- if (!err2 || typeof err2 !== "object") return String(err2);
13038
- const boom = extractBoomDetails(err2) ?? extractBoomDetails(err2?.error) ?? extractBoomDetails(err2?.lastDisconnect?.error);
13039
- const status = boom?.statusCode ?? getStatusCode(err2);
13040
- const code = err2?.code;
13034
+ function formatError(err) {
13035
+ if (err instanceof Error) return err.message;
13036
+ if (typeof err === "string") return err;
13037
+ if (!err || typeof err !== "object") return String(err);
13038
+ const boom = extractBoomDetails(err) ?? extractBoomDetails(err?.error) ?? extractBoomDetails(err?.lastDisconnect?.error);
13039
+ const status = boom?.statusCode ?? getStatusCode(err);
13040
+ const code = err?.code;
13041
13041
  const codeText = typeof code === "string" || typeof code === "number" ? String(code) : void 0;
13042
13042
  const messageCandidates = [
13043
13043
  boom?.message,
13044
- typeof err2?.message === "string" ? err2.message : void 0,
13045
- typeof err2?.error?.message === "string" ? err2.error.message : void 0
13044
+ typeof err?.message === "string" ? err.message : void 0,
13045
+ typeof err?.error?.message === "string" ? err.error.message : void 0
13046
13046
  ].filter((v) => Boolean(v?.trim()));
13047
13047
  const message = messageCandidates[0];
13048
13048
  const pieces = [];
@@ -13050,11 +13050,11 @@ function formatError(err2) {
13050
13050
  if (boom?.error) pieces.push(boom.error);
13051
13051
  if (message) pieces.push(message);
13052
13052
  if (codeText) pieces.push(`code=${codeText}`);
13053
- return pieces.length > 0 ? pieces.join(" ") : String(err2);
13053
+ return pieces.length > 0 ? pieces.join(" ") : String(err);
13054
13054
  }
13055
- function extractBoomDetails(err2) {
13056
- if (!err2 || typeof err2 !== "object") return null;
13057
- const output = err2?.output;
13055
+ function extractBoomDetails(err) {
13056
+ if (!err || typeof err !== "object") return null;
13057
+ const output = err?.output;
13058
13058
  if (!output || typeof output !== "object") return null;
13059
13059
  const payload = output.payload;
13060
13060
  const statusCode = typeof output.statusCode === "number" ? output.statusCode : typeof payload?.statusCode === "number" ? payload.statusCode : void 0;
@@ -13078,9 +13078,9 @@ function computeReconnectNextState(input) {
13078
13078
  }
13079
13079
  return { action: "retry", nextAttempts, reason: "short-lived" };
13080
13080
  }
13081
- function classifyDisconnect(err2) {
13082
- const statusCode = getStatusCode(err2);
13083
- const message = formatError(err2);
13081
+ function classifyDisconnect(err) {
13082
+ const statusCode = getStatusCode(err);
13083
+ const message = formatError(err);
13084
13084
  if (statusCode === DisconnectReason2.loggedOut) {
13085
13085
  return {
13086
13086
  kind: "loggedOut",
@@ -13122,14 +13122,14 @@ var INSPECT_OPTS2 = {
13122
13122
  compact: true,
13123
13123
  maxArrayLength: 50
13124
13124
  };
13125
- function formatErr(err2) {
13126
- if (err2 instanceof Error) {
13127
- const base = `${err2.name}: ${err2.message}`;
13128
- const inspected = inspect2(err2, INSPECT_OPTS2);
13125
+ function formatErr(err) {
13126
+ if (err instanceof Error) {
13127
+ const base = `${err.name}: ${err.message}`;
13128
+ const inspected = inspect2(err, INSPECT_OPTS2);
13129
13129
  return `${base}
13130
13130
  ${inspected}`;
13131
13131
  }
13132
- return inspect2(err2, INSPECT_OPTS2);
13132
+ return inspect2(err, INSPECT_OPTS2);
13133
13133
  }
13134
13134
  function withTimeout(label, promise, timeoutMs) {
13135
13135
  return new Promise((resolve33, reject) => {
@@ -13141,9 +13141,9 @@ function withTimeout(label, promise, timeoutMs) {
13141
13141
  clearTimeout(timer);
13142
13142
  resolve33(value);
13143
13143
  },
13144
- (err2) => {
13144
+ (err) => {
13145
13145
  clearTimeout(timer);
13146
- reject(err2);
13146
+ reject(err);
13147
13147
  }
13148
13148
  );
13149
13149
  });
@@ -13184,8 +13184,8 @@ async function runInitQueries(sock, ctx) {
13184
13184
  console.error(
13185
13185
  `${TAG5} fetchBlocklist ok account=${ctx.accountId} count=${count}`
13186
13186
  );
13187
- } catch (err2) {
13188
- const formatted = formatErr(err2);
13187
+ } catch (err) {
13188
+ const formatted = formatErr(err);
13189
13189
  result.errors.blocklist = formatted;
13190
13190
  console.error(
13191
13191
  `${TAG5} fetchBlocklist FAILED account=${ctx.accountId}: ${formatted}`
@@ -13211,8 +13211,8 @@ async function runInitQueries(sock, ctx) {
13211
13211
  console.error(
13212
13212
  `${TAG5} fetchPrivacySettings ok account=${ctx.accountId} keys=${settings ? Object.keys(settings).join(",") : ""}`
13213
13213
  );
13214
- } catch (err2) {
13215
- const formatted = formatErr(err2);
13214
+ } catch (err) {
13215
+ const formatted = formatErr(err);
13216
13216
  result.errors.privacySettings = formatted;
13217
13217
  console.error(
13218
13218
  `${TAG5} fetchPrivacySettings FAILED account=${ctx.accountId}: ${formatted}`
@@ -13286,8 +13286,8 @@ async function resolveJidToE164(jid, lidMapping) {
13286
13286
  return phone;
13287
13287
  }
13288
13288
  }
13289
- } catch (err2) {
13290
- console.error(`[whatsapp:normalize] LID mapping failed jid=${jid}: ${String(err2)}`);
13289
+ } catch (err) {
13290
+ console.error(`[whatsapp:normalize] LID mapping failed jid=${jid}: ${String(err)}`);
13291
13291
  }
13292
13292
  }
13293
13293
  const lidMatch = jid.match(WHATSAPP_LID_RE);
@@ -13540,8 +13540,8 @@ function recordActivity(event) {
13540
13540
  console.error(
13541
13541
  `${TAG6} channel-activity: direction=${direction} account=${accountId} jid=${jid}` + (messageType ? ` type=${messageType}` : "")
13542
13542
  );
13543
- } catch (err2) {
13544
- console.error(`${TAG6} recording failed: ${String(err2)}`);
13543
+ } catch (err) {
13544
+ console.error(`${TAG6} recording failed: ${String(err)}`);
13545
13545
  }
13546
13546
  }
13547
13547
  function getChannelActivity(accountId) {
@@ -13580,9 +13580,9 @@ async function sendTextMessage(sock, to, text, opts) {
13580
13580
  recordActivity({ accountId: opts.accountId, direction: "outbound", jid, messageType: "text" });
13581
13581
  }
13582
13582
  return { success: true, messageId: messageId ?? void 0 };
13583
- } catch (err2) {
13584
- console.error(`${TAG7} send failed to=${to}: ${String(err2)}`);
13585
- return { success: false, error: String(err2) };
13583
+ } catch (err) {
13584
+ console.error(`${TAG7} send failed to=${to}: ${String(err)}`);
13585
+ return { success: false, error: String(err) };
13586
13586
  }
13587
13587
  }
13588
13588
  async function sendReadReceipt(sock, chatJid, messageIds, participant) {
@@ -13642,9 +13642,9 @@ async function sendMediaMessage(sock, to, media, opts) {
13642
13642
  recordActivity({ accountId: opts.accountId, direction: "outbound", jid, messageType: media.type });
13643
13643
  }
13644
13644
  return { success: true, messageId: messageId ?? void 0 };
13645
- } catch (err2) {
13646
- console.error(`${TAG7} send media failed to=${to}: ${String(err2)}`);
13647
- return { success: false, error: String(err2) };
13645
+ } catch (err) {
13646
+ console.error(`${TAG7} send media failed to=${to}: ${String(err)}`);
13647
+ return { success: false, error: String(err) };
13648
13648
  }
13649
13649
  }
13650
13650
 
@@ -13746,8 +13746,8 @@ async function downloadInboundMedia(msg, sock, opts) {
13746
13746
  mimetype: mimetype ?? "application/octet-stream",
13747
13747
  size: buffer.length
13748
13748
  };
13749
- } catch (err2) {
13750
- console.error(`${TAG8} media download failed type=${mimetype ?? "unknown"} error=${String(err2)}`);
13749
+ } catch (err) {
13750
+ console.error(`${TAG8} media download failed type=${mimetype ?? "unknown"} error=${String(err)}`);
13751
13751
  return void 0;
13752
13752
  }
13753
13753
  }
@@ -13789,8 +13789,8 @@ function createInboundDebouncer(opts) {
13789
13789
  if (result && typeof result.catch === "function") {
13790
13790
  result.catch(onError);
13791
13791
  }
13792
- } catch (err2) {
13793
- onError(err2);
13792
+ } catch (err) {
13793
+ onError(err);
13794
13794
  }
13795
13795
  }
13796
13796
  async function flush() {
@@ -13805,8 +13805,8 @@ function createInboundDebouncer(opts) {
13805
13805
  if (result && typeof result.catch === "function") {
13806
13806
  result.catch(onError);
13807
13807
  }
13808
- } catch (err2) {
13809
- onError(err2);
13808
+ } catch (err) {
13809
+ onError(err);
13810
13810
  }
13811
13811
  return;
13812
13812
  }
@@ -13817,8 +13817,8 @@ function createInboundDebouncer(opts) {
13817
13817
  if (result && typeof result.catch === "function") {
13818
13818
  result.catch(onError);
13819
13819
  }
13820
- } catch (err2) {
13821
- onError(err2);
13820
+ } catch (err) {
13821
+ onError(err);
13822
13822
  }
13823
13823
  return;
13824
13824
  }
@@ -13932,9 +13932,9 @@ async function isBusinessOpen(accountId) {
13932
13932
  } finally {
13933
13933
  await session.close();
13934
13934
  }
13935
- } catch (err2) {
13935
+ } catch (err) {
13936
13936
  console.error(
13937
- `${TAG10} [${accountId}] business hours check failed, treating as open: ${err2 instanceof Error ? err2.message : String(err2)}`
13937
+ `${TAG10} [${accountId}] business hours check failed, treating as open: ${err instanceof Error ? err.message : String(err)}`
13938
13938
  );
13939
13939
  return { open: true, reason: "hours check failed (treating as open)" };
13940
13940
  }
@@ -14012,8 +14012,8 @@ async function transcribe(audioPath, mimetype) {
14012
14012
  // overwrite without prompting
14013
14013
  wavPath
14014
14014
  ], { timeout: 3e4 });
14015
- } catch (err2) {
14016
- const reason = err2 instanceof Error ? err2.message : String(err2);
14015
+ } catch (err) {
14016
+ const reason = err instanceof Error ? err.message : String(err);
14017
14017
  console.error(`${TAG11} failed: ffmpeg conversion error=${reason}`);
14018
14018
  return void 0;
14019
14019
  }
@@ -14042,9 +14042,9 @@ async function transcribe(audioPath, mimetype) {
14042
14042
  `${TAG11} done provider=whisper-local duration_ms=${durationMs} words=${words} lang=${language}`
14043
14043
  );
14044
14044
  return { text, language, durationMs };
14045
- } catch (err2) {
14045
+ } catch (err) {
14046
14046
  const durationMs = Date.now() - startMs;
14047
- const reason = err2 instanceof Error ? err2.message : String(err2);
14047
+ const reason = err instanceof Error ? err.message : String(err);
14048
14048
  console.error(`${TAG11} failed provider=whisper-local duration_ms=${durationMs} error=${reason}`);
14049
14049
  return void 0;
14050
14050
  } finally {
@@ -14099,8 +14099,8 @@ async function init(opts) {
14099
14099
  console.error(`${TAG12} skipping disabled account=${accountId}`);
14100
14100
  continue;
14101
14101
  }
14102
- startConnection(accountId).catch((err2) => {
14103
- console.error(`${TAG12} failed to auto-start account=${accountId}: ${formatError(err2)}`);
14102
+ startConnection(accountId).catch((err) => {
14103
+ console.error(`${TAG12} failed to auto-start account=${accountId}: ${formatError(err)}`);
14104
14104
  });
14105
14105
  }
14106
14106
  }
@@ -14144,8 +14144,8 @@ async function stopConnection(accountId) {
14144
14144
  conn.sock.ev.removeAllListeners("connection.update");
14145
14145
  conn.sock.ev.removeAllListeners("creds.update");
14146
14146
  conn.sock.ws?.close?.();
14147
- } catch (err2) {
14148
- console.warn(`${TAG12} socket cleanup error during stop account=${accountId}: ${String(err2)}`);
14147
+ } catch (err) {
14148
+ console.warn(`${TAG12} socket cleanup error during stop account=${accountId}: ${String(err)}`);
14149
14149
  }
14150
14150
  }
14151
14151
  connections.delete(accountId);
@@ -14191,8 +14191,8 @@ async function registerLoginSocket(accountId, sock, authDir) {
14191
14191
  try {
14192
14192
  await sock.sendPresenceUpdate("available");
14193
14193
  console.error(`${TAG12} presence set to available account=${accountId}`);
14194
- } catch (err2) {
14195
- console.error(`${TAG12} presence update failed account=${accountId}: ${String(err2)}`);
14194
+ } catch (err) {
14195
+ console.error(`${TAG12} presence update failed account=${accountId}: ${String(err)}`);
14196
14196
  }
14197
14197
  await runInitQueries(sock, {
14198
14198
  accountId,
@@ -14243,8 +14243,8 @@ function loadConfig(accountConfig) {
14243
14243
  whatsAppConfig = {};
14244
14244
  }
14245
14245
  }
14246
- } catch (err2) {
14247
- console.error(`${TAG12} config load error: ${String(err2)}`);
14246
+ } catch (err) {
14247
+ console.error(`${TAG12} config load error: ${String(err)}`);
14248
14248
  whatsAppConfig = {};
14249
14249
  }
14250
14250
  }
@@ -14275,8 +14275,8 @@ async function connectWithReconnect(conn) {
14275
14275
  try {
14276
14276
  await sock.sendPresenceUpdate("available");
14277
14277
  console.error(`${TAG12} presence set to available account=${conn.accountId}`);
14278
- } catch (err2) {
14279
- console.error(`${TAG12} presence update failed account=${conn.accountId}: ${String(err2)}`);
14278
+ } catch (err) {
14279
+ console.error(`${TAG12} presence update failed account=${conn.accountId}: ${String(err)}`);
14280
14280
  }
14281
14281
  await runInitQueries(sock, {
14282
14282
  accountId: conn.accountId,
@@ -14294,14 +14294,14 @@ async function connectWithReconnect(conn) {
14294
14294
  uptimeMs = Date.now() - connectedAt;
14295
14295
  conn.connected = false;
14296
14296
  conn.sock = null;
14297
- } catch (err2) {
14297
+ } catch (err) {
14298
14298
  conn.connected = false;
14299
14299
  conn.sock = null;
14300
- cycleError = err2;
14300
+ cycleError = err;
14301
14301
  if (connectedAt) {
14302
14302
  uptimeMs = Date.now() - connectedAt;
14303
14303
  }
14304
- const classification = classifyDisconnect(err2);
14304
+ const classification = classifyDisconnect(err);
14305
14305
  conn.lastError = classification.message;
14306
14306
  console.error(`${TAG12} disconnect account=${conn.accountId}: ${classification.kind} \u2014 ${classification.message}`);
14307
14307
  if (!classification.shouldRetry) {
@@ -14374,8 +14374,8 @@ function watchForDisconnect(conn) {
14374
14374
  console.error(`${TAG12} socket disconnected for account=${conn.accountId}`);
14375
14375
  conn.connected = false;
14376
14376
  conn.sock = null;
14377
- connectWithReconnect(conn).catch((err2) => {
14378
- console.error(`${TAG12} reconnection failed for account=${conn.accountId}: ${formatError(err2)}`);
14377
+ connectWithReconnect(conn).catch((err) => {
14378
+ console.error(`${TAG12} reconnection failed for account=${conn.accountId}: ${formatError(err)}`);
14379
14379
  });
14380
14380
  }
14381
14381
  });
@@ -14402,9 +14402,9 @@ async function getGroupMeta(conn, jid) {
14402
14402
  `${TAG12} group metadata cached for ${jid}: "${meta.subject}", ${participants.length} participants, expires in ${GROUP_META_TTL}ms account=${conn.accountId}`
14403
14403
  );
14404
14404
  return entry;
14405
- } catch (err2) {
14405
+ } catch (err) {
14406
14406
  console.error(
14407
- `${TAG12} group metadata fetch failed for ${jid}: ${err2 instanceof Error ? err2.message : String(err2)}, caching empty entry for ${GROUP_META_TTL}ms account=${conn.accountId}`
14407
+ `${TAG12} group metadata fetch failed for ${jid}: ${err instanceof Error ? err.message : String(err)}, caching empty entry for ${GROUP_META_TTL}ms account=${conn.accountId}`
14408
14408
  );
14409
14409
  const emptyEntry = { expires: Date.now() + GROUP_META_TTL };
14410
14410
  conn.groupMetaCache.set(jid, emptyEntry);
@@ -14440,8 +14440,8 @@ function monitorInbound(conn) {
14440
14440
  mediaType: mediaEntry?.mediaType ?? last.mediaType
14441
14441
  });
14442
14442
  },
14443
- onError: (err2) => {
14444
- console.error(`${TAG12} debounce flush error account=${conn.accountId}: ${String(err2)}`);
14443
+ onError: (err) => {
14444
+ console.error(`${TAG12} debounce flush error account=${conn.accountId}: ${String(err)}`);
14445
14445
  }
14446
14446
  });
14447
14447
  sock.ev.on("messages.upsert", async (upsert) => {
@@ -14493,8 +14493,8 @@ function monitorInbound(conn) {
14493
14493
  continue;
14494
14494
  }
14495
14495
  await handleInboundMessage(conn, msg);
14496
- } catch (err2) {
14497
- console.error(`${TAG12} inbound handler error account=${conn.accountId}: ${String(err2)}`);
14496
+ } catch (err) {
14497
+ console.error(`${TAG12} inbound handler error account=${conn.accountId}: ${String(err)}`);
14498
14498
  }
14499
14499
  }
14500
14500
  });
@@ -14647,9 +14647,9 @@ async function handleInboundMessage(conn, msg) {
14647
14647
  try {
14648
14648
  await reply(afterHoursMessage);
14649
14649
  console.error(`${TAG12} [${conn.accountId}] after-hours auto-reply sent to ${remoteJid}`);
14650
- } catch (err2) {
14650
+ } catch (err) {
14651
14651
  console.error(
14652
- `${TAG12} [${conn.accountId}] after-hours auto-reply failed: ${err2 instanceof Error ? err2.message : String(err2)}`
14652
+ `${TAG12} [${conn.accountId}] after-hours auto-reply failed: ${err instanceof Error ? err.message : String(err)}`
14653
14653
  );
14654
14654
  }
14655
14655
  }
@@ -14706,8 +14706,8 @@ async function GET(req, remoteAddress) {
14706
14706
  pinConfigured = Array.isArray(users) && users.length > 0;
14707
14707
  }
14708
14708
  }
14709
- } catch (err2) {
14710
- console.error(`[health] users.json corrupt \u2014 reporting pin_configured=false: ${err2 instanceof Error ? err2.message : String(err2)}`);
14709
+ } catch (err) {
14710
+ console.error(`[health] users.json corrupt \u2014 reporting pin_configured=false: ${err instanceof Error ? err.message : String(err)}`);
14711
14711
  }
14712
14712
  let authHealth;
14713
14713
  try {
@@ -14741,8 +14741,8 @@ async function GET(req, remoteAddress) {
14741
14741
  lastError: a.lastError ?? null,
14742
14742
  sessionStuckReason: a.sessionStuckReason ?? null
14743
14743
  }));
14744
- } catch (err2) {
14745
- console.error(`[health] failed to read WhatsApp status: ${err2 instanceof Error ? err2.message : String(err2)}`);
14744
+ } catch (err) {
14745
+ console.error(`[health] failed to read WhatsApp status: ${err instanceof Error ? err.message : String(err)}`);
14746
14746
  }
14747
14747
  const whatsappAnyConnected = whatsappAccounts.some((a) => a.connected);
14748
14748
  const whatsappAnyStuck = whatsappAccounts.some((a) => Boolean(a.sessionStuckReason));
@@ -14793,8 +14793,8 @@ async function POST(req) {
14793
14793
  let body;
14794
14794
  try {
14795
14795
  body = await req.json();
14796
- } catch (err2) {
14797
- console.error("[session] failed to parse request body:", err2);
14796
+ } catch (err) {
14797
+ console.error("[session] failed to parse request body:", err);
14798
14798
  return Response.json({ error: "Invalid request" }, { status: 400 });
14799
14799
  }
14800
14800
  if (!body.session_id || typeof body.session_id !== "string") {
@@ -15046,8 +15046,8 @@ function writeBrandingCache(accountId, agentSlug, branding) {
15046
15046
  const cacheDir = resolve12(MAXY_DIR, "branding-cache", accountId);
15047
15047
  mkdirSync8(cacheDir, { recursive: true });
15048
15048
  writeFileSync10(resolve12(cacheDir, `${agentSlug}.json`), JSON.stringify(branding), "utf-8");
15049
- } catch (err2) {
15050
- console.error(`[branding] cache write failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
15049
+ } catch (err) {
15050
+ console.error(`[branding] cache write failed: ${err instanceof Error ? err.message : String(err)}`);
15051
15051
  }
15052
15052
  }
15053
15053
  function parseVisitorCookie(cookieHeader) {
@@ -15083,20 +15083,20 @@ var VISITOR_ERROR_MESSAGES = {
15083
15083
  claude_overloaded: "I'm not available right now. Please try again shortly.",
15084
15084
  agent_error: "I'm not available right now. Please try again later."
15085
15085
  };
15086
- function classifyAgentError(err2) {
15087
- const msg = err2 instanceof Error ? err2.message : String(err2);
15086
+ function classifyAgentError(err) {
15087
+ const msg = err instanceof Error ? err.message : String(err);
15088
15088
  if (/\b(401|authentication_error|OAuth token has expired)\b/i.test(msg)) return "auth_expired";
15089
15089
  if (/credit balance|billing|purchase credits/i.test(msg)) return "billing";
15090
15090
  if (/\b(500|api_error|internal server error)\b/i.test(msg)) return "claude_down";
15091
15091
  if (/\b(529|overloaded)\b/i.test(msg)) return "claude_overloaded";
15092
15092
  return "agent_error";
15093
15093
  }
15094
- function friendlyAgentError(err2, agentType = "admin") {
15095
- const code = classifyAgentError(err2);
15094
+ function friendlyAgentError(err, agentType = "admin") {
15095
+ const code = classifyAgentError(err);
15096
15096
  if (agentType === "public") return VISITOR_ERROR_MESSAGES[code];
15097
15097
  const base = ADMIN_ERROR_MESSAGES[code];
15098
15098
  if (code === "agent_error") {
15099
- const raw2 = err2 instanceof Error ? err2.message : String(err2);
15099
+ const raw2 = err instanceof Error ? err.message : String(err);
15100
15100
  return `${base}
15101
15101
 
15102
15102
  ${raw2}`;
@@ -15256,8 +15256,8 @@ async function transcribeVoiceNote(file, source) {
15256
15256
  tempPath = join8(tempDir, `recording${ext}`);
15257
15257
  const buffer = Buffer.from(await file.arrayBuffer());
15258
15258
  await writeFile3(tempPath, buffer);
15259
- } catch (err2) {
15260
- const reason = err2 instanceof Error ? err2.message : String(err2);
15259
+ } catch (err) {
15260
+ const reason = err instanceof Error ? err.message : String(err);
15261
15261
  console.error(`${TAG13} failed source=${source} error=temp-file-write: ${reason}`);
15262
15262
  return { ok: false, error: "Could not process voice note" };
15263
15263
  }
@@ -15280,9 +15280,9 @@ async function transcribeVoiceNote(file, source) {
15280
15280
  ok: true,
15281
15281
  result: { text: rawText, durationMs: elapsed, words }
15282
15282
  };
15283
- } catch (err2) {
15283
+ } catch (err) {
15284
15284
  const elapsed = Date.now() - startMs;
15285
- const reason = err2 instanceof Error ? err2.message : String(err2);
15285
+ const reason = err instanceof Error ? err.message : String(err);
15286
15286
  console.error(
15287
15287
  `${TAG13} failed source=${source} error=${reason} duration_ms=${elapsed}`
15288
15288
  );
@@ -15530,10 +15530,10 @@ async function processInbound(rawText, channel) {
15530
15530
  );
15531
15531
  }
15532
15532
  return result;
15533
- } catch (err2) {
15533
+ } catch (err) {
15534
15534
  const latencyMs = Date.now() - startMs;
15535
- const reason = err2 instanceof Error ? err2.message : String(err2);
15536
- const errorType = err2 instanceof Error && err2.name === "AbortError" ? "timeout" : "api-error";
15535
+ const reason = err instanceof Error ? err.message : String(err);
15536
+ const errorType = err instanceof Error && err.name === "AbortError" ? "timeout" : "api-error";
15537
15537
  console.warn(
15538
15538
  `${TAG14} fallthrough channel=${channel} reason=${errorType}: ${reason} latency_ms=${latencyMs}`
15539
15539
  );
@@ -15618,9 +15618,9 @@ async function POST2(req) {
15618
15618
  `File "${file.name}" exceeds the 20 MB limit (${(file.size / 1024 / 1024).toFixed(1)} MB).`
15619
15619
  );
15620
15620
  }
15621
- } catch (err2) {
15621
+ } catch (err) {
15622
15622
  return new Response(
15623
- JSON.stringify({ error: err2 instanceof Error ? err2.message : "Invalid file" }),
15623
+ JSON.stringify({ error: err instanceof Error ? err.message : "Invalid file" }),
15624
15624
  { status: 422, headers: { "Content-Type": "application/json" } }
15625
15625
  );
15626
15626
  }
@@ -15759,22 +15759,22 @@ async function POST2(req) {
15759
15759
  controller.enqueue(encoder.encode("data: [DONE]\n\n"));
15760
15760
  }
15761
15761
  }
15762
- } catch (err2) {
15763
- const rawMessage = err2 instanceof Error ? err2.message : String(err2);
15762
+ } catch (err) {
15763
+ const rawMessage = err instanceof Error ? err.message : String(err);
15764
15764
  const ts = (/* @__PURE__ */ new Date()).toISOString().slice(11, 23);
15765
- const controllerClosed = err2 instanceof TypeError && /Controller is already closed/i.test(rawMessage);
15765
+ const controllerClosed = err instanceof TypeError && /Controller is already closed/i.test(rawMessage);
15766
15766
  if (controllerClosed) {
15767
15767
  sseLog.write(`[${ts}] [${sk}] ${agentName}: DISCONNECT [client_disconnect] ${rawMessage}
15768
15768
  `);
15769
15769
  } else {
15770
- const category = classifyAgentError(err2);
15770
+ const category = classifyAgentError(err);
15771
15771
  sseLog.write(`[${ts}] [${sk}] ${agentName}: ERROR [${category}] ${rawMessage}
15772
15772
  `);
15773
15773
  sseLog.write(`[${ts}] [${sk}] ${agentName}: ${JSON.stringify({ type: "done", subtype: "error", error: rawMessage, error_category: category })}
15774
15774
  `);
15775
15775
  try {
15776
15776
  controller.enqueue(
15777
- encoder.encode(`data: ${JSON.stringify({ error: friendlyAgentError(err2, local ? "admin" : "public") })}
15777
+ encoder.encode(`data: ${JSON.stringify({ error: friendlyAgentError(err, local ? "admin" : "public") })}
15778
15778
 
15779
15779
  `)
15780
15780
  );
@@ -16186,8 +16186,8 @@ async function POST3(req) {
16186
16186
  status: result.status
16187
16187
  }
16188
16188
  });
16189
- } catch (err2) {
16190
- console.error(`[access-gate] verify-token ip=${clientIp} agent=${agentSlug} error=${err2 instanceof Error ? err2.message : String(err2)}`);
16189
+ } catch (err) {
16190
+ console.error(`[access-gate] verify-token ip=${clientIp} agent=${agentSlug} error=${err instanceof Error ? err.message : String(err)}`);
16191
16191
  return Response.json({ error: "Internal server error" }, { status: 500 });
16192
16192
  }
16193
16193
  }
@@ -16280,8 +16280,8 @@ async function POST4(req) {
16280
16280
  status: grant.status
16281
16281
  }
16282
16282
  });
16283
- } catch (err2) {
16284
- console.error(`[access-gate] verify-otp ip=${clientIp} agent=${agentSlug} error=${err2 instanceof Error ? err2.message : String(err2)}`);
16283
+ } catch (err) {
16284
+ console.error(`[access-gate] verify-otp ip=${clientIp} agent=${agentSlug} error=${err instanceof Error ? err.message : String(err)}`);
16285
16285
  return Response.json({ error: "Internal server error" }, { status: 500 });
16286
16286
  }
16287
16287
  }
@@ -16324,8 +16324,8 @@ async function POST5(req) {
16324
16324
  completeGrantSetup(session_key);
16325
16325
  console.error(`[access-gate] create-credentials agent=${grant.grantContactValue ? "redacted" : "unknown"} result=success`);
16326
16326
  return Response.json({ session_key });
16327
- } catch (err2) {
16328
- console.error(`[access-gate] create-credentials error=${err2 instanceof Error ? err2.message : String(err2)}`);
16327
+ } catch (err) {
16328
+ console.error(`[access-gate] create-credentials error=${err instanceof Error ? err.message : String(err)}`);
16329
16329
  return Response.json({ error: "Internal server error" }, { status: 500 });
16330
16330
  }
16331
16331
  }
@@ -16410,8 +16410,8 @@ async function POST6(req) {
16410
16410
  session_key: sessionKey,
16411
16411
  agent_id: agentSlug
16412
16412
  });
16413
- } catch (err2) {
16414
- console.error(`[access-gate] login ip=${clientIp} agent=${agentSlug} error=${err2 instanceof Error ? err2.message : String(err2)}`);
16413
+ } catch (err) {
16414
+ console.error(`[access-gate] login ip=${clientIp} agent=${agentSlug} error=${err instanceof Error ? err.message : String(err)}`);
16415
16415
  return Response.json({ error: "Internal server error" }, { status: 500 });
16416
16416
  }
16417
16417
  }
@@ -16442,13 +16442,13 @@ function readBrevoApiKey() {
16442
16442
  throw new Error(`Brevo API key file is empty: ${BREVO_API_KEY_FILE}`);
16443
16443
  }
16444
16444
  return key;
16445
- } catch (err2) {
16446
- if (err2.code === "ENOENT") {
16445
+ } catch (err) {
16446
+ if (err.code === "ENOENT") {
16447
16447
  throw new Error(
16448
16448
  `Brevo API key not configured. Expected at ${BREVO_API_KEY_FILE}. Set up SMS via the admin agent: "set up SMS" \u2192 provide your Brevo API key.`
16449
16449
  );
16450
16450
  }
16451
- throw err2;
16451
+ throw err;
16452
16452
  }
16453
16453
  }
16454
16454
  function hasBrevoApiKey() {
@@ -16458,10 +16458,10 @@ async function sendSms(recipient, content, opts) {
16458
16458
  let apiKey;
16459
16459
  try {
16460
16460
  apiKey = readBrevoApiKey();
16461
- } catch (err2) {
16461
+ } catch (err) {
16462
16462
  return {
16463
16463
  success: false,
16464
- error: err2 instanceof Error ? err2.message : "Failed to read Brevo API key"
16464
+ error: err instanceof Error ? err.message : "Failed to read Brevo API key"
16465
16465
  };
16466
16466
  }
16467
16467
  const finalContent = opts?.aiGenerated ? `${content} [AI-generated]` : content;
@@ -16505,13 +16505,13 @@ async function sendSms(recipient, content, opts) {
16505
16505
  error = `Brevo API error (HTTP ${statusCode})`;
16506
16506
  }
16507
16507
  return { success: false, error, statusCode };
16508
- } catch (err2) {
16509
- if (err2 instanceof DOMException && err2.name === "AbortError") {
16508
+ } catch (err) {
16509
+ if (err instanceof DOMException && err.name === "AbortError") {
16510
16510
  return { success: false, error: "Brevo API request timed out (10s)" };
16511
16511
  }
16512
16512
  return {
16513
16513
  success: false,
16514
- error: `SMS delivery failed: ${err2 instanceof Error ? err2.message : String(err2)}`
16514
+ error: `SMS delivery failed: ${err instanceof Error ? err.message : String(err)}`
16515
16515
  };
16516
16516
  } finally {
16517
16517
  clearTimeout(timeout);
@@ -16582,8 +16582,8 @@ async function POST7(req) {
16582
16582
  console.error(`[access-gate] forgot-password ip=${clientIp} agent=${agentSlug} contact=${maskContact(contact)} result=token_generated`);
16583
16583
  }
16584
16584
  return Response.json(GENERIC_RESPONSE);
16585
- } catch (err2) {
16586
- console.error(`[access-gate] forgot-password ip=${clientIp} agent=${agentSlug} error=${err2 instanceof Error ? err2.message : String(err2)}`);
16585
+ } catch (err) {
16586
+ console.error(`[access-gate] forgot-password ip=${clientIp} agent=${agentSlug} error=${err instanceof Error ? err.message : String(err)}`);
16587
16587
  return Response.json(GENERIC_RESPONSE);
16588
16588
  }
16589
16589
  }
@@ -16640,8 +16640,8 @@ async function POST8(req, remoteAddress) {
16640
16640
  messageId: smsResult.messageId,
16641
16641
  grantId: grant.grantId
16642
16642
  });
16643
- } catch (err2) {
16644
- console.error(`[access-gate] send-otp agent=${agentSlug} phone=${maskContact(phone)} error=${err2 instanceof Error ? err2.message : String(err2)}`);
16643
+ } catch (err) {
16644
+ console.error(`[access-gate] send-otp agent=${agentSlug} phone=${maskContact(phone)} error=${err instanceof Error ? err.message : String(err)}`);
16645
16645
  return Response.json({ error: "Internal server error" }, { status: 500 });
16646
16646
  }
16647
16647
  }
@@ -16727,9 +16727,9 @@ async function handleInbound(params) {
16727
16727
  if (agentType === "public" && responseText) {
16728
16728
  responseText += "\n\n\u2014 This message was generated by AI";
16729
16729
  }
16730
- } catch (err2) {
16730
+ } catch (err) {
16731
16731
  console.error(
16732
- `${TAG15} agent-error: chatId=${chatId} senderId=${senderId} error=${err2 instanceof Error ? err2.message : String(err2)}`
16732
+ `${TAG15} agent-error: chatId=${chatId} senderId=${senderId} error=${err instanceof Error ? err.message : String(err)}`
16733
16733
  );
16734
16734
  responseText = "I'm having trouble right now. Please try again in a moment.";
16735
16735
  }
@@ -16750,9 +16750,9 @@ async function handleInbound(params) {
16750
16750
  `${TAG15} send-error: chatId=${chatId} error=${data.description ?? "unknown"}`
16751
16751
  );
16752
16752
  }
16753
- } catch (err2) {
16753
+ } catch (err) {
16754
16754
  console.error(
16755
- `${TAG15} send-error: chatId=${chatId} error=${err2 instanceof Error ? err2.message : String(err2)}`
16755
+ `${TAG15} send-error: chatId=${chatId} error=${err instanceof Error ? err.message : String(err)}`
16756
16756
  );
16757
16757
  }
16758
16758
  }
@@ -16819,8 +16819,8 @@ async function POST9(req) {
16819
16819
  method: "POST",
16820
16820
  headers: { "Content-Type": "application/json" },
16821
16821
  body: JSON.stringify({ callback_query_id: callbackId })
16822
- }).catch((err2) => {
16823
- console.error(`${TAG15} callback-ack-error: ${err2 instanceof Error ? err2.message : String(err2)}`);
16822
+ }).catch((err) => {
16823
+ console.error(`${TAG15} callback-ack-error: ${err instanceof Error ? err.message : String(err)}`);
16824
16824
  });
16825
16825
  }
16826
16826
  handleInbound({
@@ -16831,9 +16831,9 @@ async function POST9(req) {
16831
16831
  botToken,
16832
16832
  accountId: account.accountId,
16833
16833
  agentType: accessResult.agentType
16834
- }).catch((err2) => {
16834
+ }).catch((err) => {
16835
16835
  console.error(
16836
- `${TAG15} unhandled-error: chatId=${chatId} senderId=${senderId} error=${err2 instanceof Error ? err2.message : String(err2)}`
16836
+ `${TAG15} unhandled-error: chatId=${chatId} senderId=${senderId} error=${err instanceof Error ? err.message : String(err)}`
16837
16837
  );
16838
16838
  });
16839
16839
  return Response.json({ ok: true });
@@ -16850,8 +16850,8 @@ var activeLogins = /* @__PURE__ */ new Map();
16850
16850
  function closeSocket(sock) {
16851
16851
  try {
16852
16852
  sock.ws?.close?.();
16853
- } catch (err2) {
16854
- console.warn(`${TAG16} socket close error during cleanup: ${String(err2)}`);
16853
+ } catch (err) {
16854
+ console.warn(`${TAG16} socket close error during cleanup: ${String(err)}`);
16855
16855
  }
16856
16856
  }
16857
16857
  function resetActiveLogin(accountId) {
@@ -16877,20 +16877,20 @@ async function loginConnectionLoop(accountId, login) {
16877
16877
  console.error(`${TAG16} loginConnectionLoop: connected account=${accountId} attempt=${attempt}`);
16878
16878
  }
16879
16879
  return;
16880
- } catch (err2) {
16880
+ } catch (err) {
16881
16881
  const current = activeLogins.get(accountId);
16882
16882
  if (current?.id !== login.id) return;
16883
- const classification = classifyDisconnect(err2);
16883
+ const classification = classifyDisconnect(err);
16884
16884
  if (!classification.shouldRetry || attempt >= LOGIN_MAX_RECONNECTS) {
16885
16885
  if (attempt >= LOGIN_MAX_RECONNECTS) {
16886
16886
  console.error(
16887
16887
  `${TAG16} login reconnect attempts exhausted (${attempt}/${LOGIN_MAX_RECONNECTS}) \u2014 surfacing error to agent`
16888
16888
  );
16889
- current.error = `Login failed after ${attempt} reconnect attempts: ${formatError(err2)}`;
16889
+ current.error = `Login failed after ${attempt} reconnect attempts: ${formatError(err)}`;
16890
16890
  } else {
16891
- current.error = formatError(err2);
16891
+ current.error = formatError(err);
16892
16892
  }
16893
- current.errorStatus = getStatusCode(err2);
16893
+ current.errorStatus = getStatusCode(err);
16894
16894
  return;
16895
16895
  }
16896
16896
  attempt++;
@@ -16974,10 +16974,10 @@ async function startLogin(opts) {
16974
16974
  resolveQr?.(qr2);
16975
16975
  }
16976
16976
  });
16977
- } catch (err2) {
16977
+ } catch (err) {
16978
16978
  clearTimeout(qrTimer);
16979
16979
  resetActiveLogin(accountId);
16980
- return { message: `Failed to start WhatsApp login: ${String(err2)}` };
16980
+ return { message: `Failed to start WhatsApp login: ${String(err)}` };
16981
16981
  }
16982
16982
  const login = {
16983
16983
  accountId,
@@ -16989,20 +16989,20 @@ async function startLogin(opts) {
16989
16989
  };
16990
16990
  activeLogins.set(accountId, login);
16991
16991
  if (pendingQr && !login.qr) login.qr = pendingQr;
16992
- loginConnectionLoop(accountId, login).catch((err2) => {
16993
- console.error(`${TAG16} loginConnectionLoop unexpected error: ${String(err2)}`);
16992
+ loginConnectionLoop(accountId, login).catch((err) => {
16993
+ console.error(`${TAG16} loginConnectionLoop unexpected error: ${String(err)}`);
16994
16994
  const current = activeLogins.get(accountId);
16995
16995
  if (current?.id === login.id) {
16996
- current.error = `Unexpected login error: ${String(err2)}`;
16996
+ current.error = `Unexpected login error: ${String(err)}`;
16997
16997
  }
16998
16998
  });
16999
16999
  let qr;
17000
17000
  try {
17001
17001
  qr = await qrPromise;
17002
- } catch (err2) {
17002
+ } catch (err) {
17003
17003
  clearTimeout(qrTimer);
17004
17004
  resetActiveLogin(accountId);
17005
- return { message: `Failed to get QR: ${String(err2)}` };
17005
+ return { message: `Failed to get QR: ${String(err)}` };
17006
17006
  }
17007
17007
  login.qrDataUrl = `qr:${qr}`;
17008
17008
  return {
@@ -17074,9 +17074,9 @@ async function POST10(req) {
17074
17074
  const result = await startLogin({ accountId, authDir, force });
17075
17075
  console.error(`[whatsapp:api] login/start result account=${accountId} hasQr=${!!result.qrRaw}${result.selfPhone ? ` phone=${result.selfPhone}` : ""}`);
17076
17076
  return Response.json(result);
17077
- } catch (err2) {
17078
- console.error(`[whatsapp:api] login/start error: ${String(err2)}`);
17079
- return Response.json({ error: String(err2) }, { status: 500 });
17077
+ } catch (err) {
17078
+ console.error(`[whatsapp:api] login/start error: ${String(err)}`);
17079
+ return Response.json({ error: String(err) }, { status: 500 });
17080
17080
  }
17081
17081
  }
17082
17082
 
@@ -17116,9 +17116,9 @@ async function POST11(req) {
17116
17116
  selfPhone: result.selfPhone,
17117
17117
  configPersisted
17118
17118
  });
17119
- } catch (err2) {
17120
- console.error(`[whatsapp:api] login/wait error: ${String(err2)}`);
17121
- return Response.json({ error: String(err2) }, { status: 500 });
17119
+ } catch (err) {
17120
+ console.error(`[whatsapp:api] login/wait error: ${String(err)}`);
17121
+ return Response.json({ error: String(err) }, { status: 500 });
17122
17122
  }
17123
17123
  }
17124
17124
 
@@ -17129,9 +17129,9 @@ async function GET2(_req) {
17129
17129
  const summary = status.map((a) => `${a.accountId}:${a.connected ? "up" : "down"}`).join(", ");
17130
17130
  console.error(`[whatsapp:api] status accounts=${status.length} [${summary}]`);
17131
17131
  return Response.json({ accounts: status });
17132
- } catch (err2) {
17133
- console.error(`[whatsapp:api] status error: ${String(err2)}`);
17134
- return Response.json({ error: String(err2) }, { status: 500 });
17132
+ } catch (err) {
17133
+ console.error(`[whatsapp:api] status error: ${String(err)}`);
17134
+ return Response.json({ error: String(err) }, { status: 500 });
17135
17135
  }
17136
17136
  }
17137
17137
 
@@ -17142,9 +17142,9 @@ async function POST12(req) {
17142
17142
  const accountId = validateAccountId(body.accountId);
17143
17143
  await stopConnection(accountId);
17144
17144
  return Response.json({ disconnected: true, accountId });
17145
- } catch (err2) {
17146
- console.error(`[whatsapp:api] disconnect error: ${String(err2)}`);
17147
- return Response.json({ error: String(err2) }, { status: 500 });
17145
+ } catch (err) {
17146
+ console.error(`[whatsapp:api] disconnect error: ${String(err)}`);
17147
+ return Response.json({ error: String(err) }, { status: 500 });
17148
17148
  }
17149
17149
  }
17150
17150
 
@@ -17155,9 +17155,9 @@ async function POST13(req) {
17155
17155
  const accountId = validateAccountId(body.accountId);
17156
17156
  await startConnection(accountId);
17157
17157
  return Response.json({ reconnecting: true, accountId });
17158
- } catch (err2) {
17159
- console.error(`[whatsapp:api] reconnect error: ${String(err2)}`);
17160
- return Response.json({ error: String(err2) }, { status: 500 });
17158
+ } catch (err) {
17159
+ console.error(`[whatsapp:api] reconnect error: ${String(err)}`);
17160
+ return Response.json({ error: String(err) }, { status: 500 });
17161
17161
  }
17162
17162
  }
17163
17163
 
@@ -17179,9 +17179,9 @@ async function POST14(req) {
17179
17179
  }
17180
17180
  const result = await sendTextMessage(sock, to, text, { accountId });
17181
17181
  return Response.json(result);
17182
- } catch (err2) {
17183
- console.error(`[whatsapp:api] send error: ${String(err2)}`);
17184
- return Response.json({ error: String(err2) }, { status: 500 });
17182
+ } catch (err) {
17183
+ console.error(`[whatsapp:api] send error: ${String(err)}`);
17184
+ return Response.json({ error: String(err) }, { status: 500 });
17185
17185
  }
17186
17186
  }
17187
17187
 
@@ -17348,8 +17348,8 @@ async function POST15(req) {
17348
17348
  console.error(`[whatsapp:api] config action=list-public-agents error="failed to parse config.json for agent ${entry.name}" \u2014 skipping`);
17349
17349
  }
17350
17350
  }
17351
- } catch (err2) {
17352
- console.error(`[whatsapp:api] config action=list-public-agents error="failed to scan agents directory: ${String(err2)}"`);
17351
+ } catch (err) {
17352
+ console.error(`[whatsapp:api] config action=list-public-agents error="failed to scan agents directory: ${String(err)}"`);
17353
17353
  }
17354
17354
  }
17355
17355
  console.error(`[whatsapp:api] config action=list-public-agents count=${agents.length}`);
@@ -17376,9 +17376,9 @@ async function POST15(req) {
17376
17376
  }));
17377
17377
  console.error(`[whatsapp:api] config action=list-groups count=${groups.length} accountId=${groupAccountId}`);
17378
17378
  return Response.json({ ok: true, groups });
17379
- } catch (err2) {
17380
- console.error(`[whatsapp:api] config action=list-groups error="${String(err2)}" accountId=${groupAccountId}`);
17381
- return Response.json({ ok: false, error: `Failed to fetch groups: ${String(err2)}` });
17379
+ } catch (err) {
17380
+ console.error(`[whatsapp:api] config action=list-groups error="${String(err)}" accountId=${groupAccountId}`);
17381
+ return Response.json({ ok: false, error: `Failed to fetch groups: ${String(err)}` });
17382
17382
  }
17383
17383
  }
17384
17384
  case "update-config": {
@@ -17401,9 +17401,9 @@ async function POST15(req) {
17401
17401
  { status: 400 }
17402
17402
  );
17403
17403
  }
17404
- } catch (err2) {
17405
- console.error(`[whatsapp:api] config error: ${String(err2)}`);
17406
- return Response.json({ ok: false, error: String(err2) }, { status: 500 });
17404
+ } catch (err) {
17405
+ console.error(`[whatsapp:api] config error: ${String(err)}`);
17406
+ return Response.json({ ok: false, error: String(err) }, { status: 500 });
17407
17407
  }
17408
17408
  }
17409
17409
 
@@ -17437,14 +17437,14 @@ async function POST16(req) {
17437
17437
  console.error(`${TAG17} send-document REJECTED path=${sanitised} reason=outside_account_directory`);
17438
17438
  return Response.json({ error: "Access denied: file is outside the account directory" }, { status: 403 });
17439
17439
  }
17440
- } catch (err2) {
17441
- const code = err2.code;
17440
+ } catch (err) {
17441
+ const code = err.code;
17442
17442
  if (code === "ENOENT") {
17443
17443
  console.error(`${TAG17} send-document ENOENT path=${filePath}`);
17444
17444
  return Response.json({ error: `File not found: ${filePath}` }, { status: 404 });
17445
17445
  }
17446
- console.error(`${TAG17} send-document path error: ${String(err2)}`);
17447
- return Response.json({ error: String(err2) }, { status: 500 });
17446
+ console.error(`${TAG17} send-document path error: ${String(err)}`);
17447
+ return Response.json({ error: String(err) }, { status: 500 });
17448
17448
  }
17449
17449
  const fileStat = await stat3(resolvedPath);
17450
17450
  if (fileStat.size > MAX_FILE_SIZE_BYTES) {
@@ -17474,9 +17474,9 @@ async function POST16(req) {
17474
17474
  `${TAG17} send-document to=${to} size=${fileStat.size} mime=${mimetype} ok=${result.success}` + (result.messageId ? ` id=${result.messageId}` : "")
17475
17475
  );
17476
17476
  return Response.json(result);
17477
- } catch (err2) {
17478
- console.error(`${TAG17} send-document error: ${String(err2)}`);
17479
- return Response.json({ error: String(err2) }, { status: 500 });
17477
+ } catch (err) {
17478
+ console.error(`${TAG17} send-document error: ${String(err)}`);
17479
+ return Response.json({ error: String(err) }, { status: 500 });
17480
17480
  }
17481
17481
  }
17482
17482
 
@@ -17491,9 +17491,9 @@ async function GET3(req) {
17491
17491
  `[whatsapp:api] activity accounts=${result.accounts.length} total=${total} recentEvents=${result.recentEvents.length}` + (accountId ? ` filter=${accountId}` : "")
17492
17492
  );
17493
17493
  return Response.json(result);
17494
- } catch (err2) {
17495
- console.error(`[whatsapp:api] activity error: ${String(err2)}`);
17496
- return Response.json({ error: String(err2) }, { status: 500 });
17494
+ } catch (err) {
17495
+ console.error(`[whatsapp:api] activity error: ${String(err)}`);
17496
+ return Response.json({ error: String(err) }, { status: 500 });
17497
17497
  }
17498
17498
  }
17499
17499
 
@@ -17518,9 +17518,9 @@ async function GET4(req) {
17518
17518
  `[whatsapp:api] conversations account=${accountId} count=${conversations.length}`
17519
17519
  );
17520
17520
  return Response.json({ conversations });
17521
- } catch (err2) {
17522
- console.error(`[whatsapp:api] conversations error: ${String(err2)}`);
17523
- return Response.json({ error: String(err2) }, { status: 500 });
17521
+ } catch (err) {
17522
+ console.error(`[whatsapp:api] conversations error: ${String(err)}`);
17523
+ return Response.json({ error: String(err) }, { status: 500 });
17524
17524
  }
17525
17525
  }
17526
17526
 
@@ -17541,9 +17541,9 @@ async function GET5(req) {
17541
17541
  `[whatsapp:api] messages account=${accountId} jid=${jid} limit=${effectiveLimit ?? "all"} returned=${messages.length}`
17542
17542
  );
17543
17543
  return Response.json({ messages });
17544
- } catch (err2) {
17545
- console.error(`[whatsapp:api] messages error: ${String(err2)}`);
17546
- return Response.json({ error: String(err2) }, { status: 500 });
17544
+ } catch (err) {
17545
+ console.error(`[whatsapp:api] messages error: ${String(err)}`);
17546
+ return Response.json({ error: String(err) }, { status: 500 });
17547
17547
  }
17548
17548
  }
17549
17549
 
@@ -17588,9 +17588,9 @@ async function GET6(req) {
17588
17588
  `[whatsapp:api] group-info jid=${jid} subject="${meta.subject}" participants=${meta.participants.length} account=${accountId}`
17589
17589
  );
17590
17590
  return Response.json(result);
17591
- } catch (err2) {
17592
- console.error(`[whatsapp:api] group-info error="${String(err2)}" jid=${jid} account=${accountId}`);
17593
- return Response.json({ error: `Failed to fetch group info: ${String(err2)}` }, { status: 500 });
17591
+ } catch (err) {
17592
+ console.error(`[whatsapp:api] group-info error="${String(err)}" jid=${jid} account=${accountId}`);
17593
+ return Response.json({ error: `Failed to fetch group info: ${String(err)}` }, { status: 500 });
17594
17594
  }
17595
17595
  }
17596
17596
 
@@ -17636,8 +17636,8 @@ async function GET7(req) {
17636
17636
  })),
17637
17637
  hasMore: messages.length >= POLL_LIMIT
17638
17638
  });
17639
- } catch (err2) {
17640
- console.error(`[group] poll failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
17639
+ } catch (err) {
17640
+ console.error(`[group] poll failed: ${err instanceof Error ? err.message : String(err)}`);
17641
17641
  return Response.json({ error: "Failed to fetch messages" }, { status: 503 });
17642
17642
  }
17643
17643
  }
@@ -17663,8 +17663,8 @@ async function POST17(req) {
17663
17663
  sizeBytes: attachment.sizeBytes,
17664
17664
  mimeType: attachment.mimeType
17665
17665
  });
17666
- } catch (err2) {
17667
- const message = err2 instanceof Error ? err2.message : String(err2);
17666
+ } catch (err) {
17667
+ const message = err instanceof Error ? err.message : String(err);
17668
17668
  console.error(`[admin:file-attach] error: ${message}`);
17669
17669
  return Response.json({ error: message }, { status: 500 });
17670
17670
  }
@@ -17774,8 +17774,8 @@ async function POST19(req) {
17774
17774
  let existingUsers = null;
17775
17775
  try {
17776
17776
  existingUsers = readUsersFile();
17777
- } catch (err2) {
17778
- console.error(`[set-pin] users.json corrupt: ${err2 instanceof Error ? err2.message : String(err2)}`);
17777
+ } catch (err) {
17778
+ console.error(`[set-pin] users.json corrupt: ${err instanceof Error ? err.message : String(err)}`);
17779
17779
  return Response.json({ error: "User configuration is corrupt." }, { status: 400 });
17780
17780
  }
17781
17781
  if (existingUsers !== null && existingUsers.length > 0) {
@@ -17811,8 +17811,8 @@ async function POST19(req) {
17811
17811
  writeFileSync13(`${account.accountDir}/account.json`, JSON.stringify(config, null, 2) + "\n");
17812
17812
  console.log(`[set-pin] added userId=${userId.slice(0, 8)}\u2026 to account.json admins`);
17813
17813
  }
17814
- } catch (err2) {
17815
- console.error(`[set-pin] failed to update account.json admins: ${err2 instanceof Error ? err2.message : String(err2)}`);
17814
+ } catch (err) {
17815
+ console.error(`[set-pin] failed to update account.json admins: ${err instanceof Error ? err.message : String(err)}`);
17816
17816
  }
17817
17817
  }
17818
17818
  return Response.json({ ok: true });
@@ -17821,8 +17821,8 @@ async function DELETE(req) {
17821
17821
  let users = null;
17822
17822
  try {
17823
17823
  users = readUsersFile();
17824
- } catch (err2) {
17825
- console.error(`[set-pin] users.json corrupt on DELETE: ${err2 instanceof Error ? err2.message : String(err2)}`);
17824
+ } catch (err) {
17825
+ console.error(`[set-pin] users.json corrupt on DELETE: ${err instanceof Error ? err.message : String(err)}`);
17826
17826
  return Response.json({ error: "User configuration is corrupt." }, { status: 400 });
17827
17827
  }
17828
17828
  if (users === null || users.length === 0) {
@@ -17871,8 +17871,8 @@ async function POST20() {
17871
17871
  try {
17872
17872
  const brand = JSON.parse(readFileSync18(brandPath3, "utf-8"));
17873
17873
  if (brand.productName) agentName = brand.productName;
17874
- } catch (err2) {
17875
- console.error(`[onboarding-skip] brand.json read failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
17874
+ } catch (err) {
17875
+ console.error(`[onboarding-skip] brand.json read failed: ${err instanceof Error ? err.message : String(err)}`);
17876
17876
  }
17877
17877
  }
17878
17878
  const soulPath = resolve18(accountDir, "agents", "admin", "SOUL.md");
@@ -17881,8 +17881,8 @@ async function POST20() {
17881
17881
  writeFileSync14(soulPath, `You are ${agentName}, an AI operations manager.
17882
17882
  `);
17883
17883
  console.log(`[onboarding-skip] wrote SOUL.md: ${soulPath}`);
17884
- } catch (err2) {
17885
- console.error(`[onboarding-skip] SOUL.md write failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
17884
+ } catch (err) {
17885
+ console.error(`[onboarding-skip] SOUL.md write failed: ${err instanceof Error ? err.message : String(err)}`);
17886
17886
  return Response.json({ error: "Failed to write default personality." }, { status: 500 });
17887
17887
  }
17888
17888
  const session = getSession();
@@ -17905,8 +17905,8 @@ async function POST20() {
17905
17905
  { accountId, now }
17906
17906
  );
17907
17907
  console.log(`[onboarding-skip] accountId=${accountId.slice(0, 8)}\u2026 currentStep=6 skipped=true`);
17908
- } catch (err2) {
17909
- console.error(`[onboarding-skip] Neo4j update failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
17908
+ } catch (err) {
17909
+ console.error(`[onboarding-skip] Neo4j update failed: ${err instanceof Error ? err.message : String(err)}`);
17910
17910
  return Response.json({ error: "Failed to update onboarding state." }, { status: 500 });
17911
17911
  } finally {
17912
17912
  await session.close();
@@ -17940,8 +17940,8 @@ async function POST21(req) {
17940
17940
  let users = null;
17941
17941
  try {
17942
17942
  users = readUsersFile2();
17943
- } catch (err2) {
17944
- console.error(`[session] users.json corrupt: ${err2 instanceof Error ? err2.message : String(err2)}`);
17943
+ } catch (err) {
17944
+ console.error(`[session] users.json corrupt: ${err instanceof Error ? err.message : String(err)}`);
17945
17945
  return Response.json(
17946
17946
  { error: "User configuration is corrupt. Re-run the seed script." },
17947
17947
  { status: 503 }
@@ -17998,8 +17998,8 @@ async function createAdminSession(accountId, thinkingView, userId, userName) {
17998
17998
  try {
17999
17999
  const step = await loadOnboardingStep(accountId);
18000
18000
  onboardingComplete = step === null || step >= 8;
18001
- } catch (err2) {
18002
- console.error(`[session] onboarding query failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
18001
+ } catch (err) {
18002
+ console.error(`[session] onboarding query failed: ${err instanceof Error ? err.message : String(err)}`);
18003
18003
  }
18004
18004
  let businessName;
18005
18005
  try {
@@ -18091,8 +18091,8 @@ function startScriptStreamTailer(opts) {
18091
18091
  });
18092
18092
  stream.on("error", rej);
18093
18093
  });
18094
- } catch (err2) {
18095
- if (onError) onError(err2 instanceof Error ? err2 : new Error(String(err2)));
18094
+ } catch (err) {
18095
+ if (onError) onError(err instanceof Error ? err : new Error(String(err)));
18096
18096
  } finally {
18097
18097
  pendingRead = false;
18098
18098
  }
@@ -18239,8 +18239,8 @@ async function POST22(req) {
18239
18239
  `File "${file.name}" exceeds the 20 MB limit (${(file.size / 1024 / 1024).toFixed(1)} MB).`
18240
18240
  );
18241
18241
  }
18242
- } catch (err2) {
18243
- return chatReject(422, err2 instanceof Error ? err2.message : "Invalid file", session_key);
18242
+ } catch (err) {
18243
+ return chatReject(422, err instanceof Error ? err.message : "Invalid file", session_key);
18244
18244
  }
18245
18245
  }
18246
18246
  const accountId = getAccountIdForSession(session_key);
@@ -18251,8 +18251,8 @@ async function POST22(req) {
18251
18251
  try {
18252
18252
  const stored = await storeAttachment(accountId, file);
18253
18253
  storedAttachments.push(stored);
18254
- } catch (err2) {
18255
- return chatReject(422, err2 instanceof Error ? err2.message : "File storage failed", session_key);
18254
+ } catch (err) {
18255
+ return chatReject(422, err instanceof Error ? err.message : "File storage failed", session_key);
18256
18256
  }
18257
18257
  }
18258
18258
  } else {
@@ -18373,8 +18373,8 @@ async function POST22(req) {
18373
18373
  controllerOpen = false;
18374
18374
  }
18375
18375
  },
18376
- onError: (err2) => {
18377
- console.error(`[script-stream-tailer] ${streamLogPath}: ${err2.message}`);
18376
+ onError: (err) => {
18377
+ console.error(`[script-stream-tailer] ${streamLogPath}: ${err.message}`);
18378
18378
  }
18379
18379
  });
18380
18380
  }
@@ -18394,16 +18394,16 @@ async function POST22(req) {
18394
18394
 
18395
18395
  `));
18396
18396
  }
18397
- } catch (err2) {
18398
- const rawMessage = err2 instanceof Error ? err2.message : String(err2);
18397
+ } catch (err) {
18398
+ const rawMessage = err instanceof Error ? err.message : String(err);
18399
18399
  const ts = (/* @__PURE__ */ new Date()).toISOString().slice(11, 23);
18400
- const controllerClosed = err2 instanceof TypeError && /Controller is already closed/i.test(rawMessage);
18400
+ const controllerClosed = err instanceof TypeError && /Controller is already closed/i.test(rawMessage);
18401
18401
  if (controllerClosed) {
18402
18402
  sseLog.write(`[${ts}] [${sk}] admin: DISCONNECT [client_disconnect] ${rawMessage}
18403
18403
  `);
18404
18404
  } else {
18405
- const category = classifyAgentError(err2);
18406
- const errEvent = JSON.stringify({ type: "text", content: friendlyAgentError(err2) });
18405
+ const category = classifyAgentError(err);
18406
+ const errEvent = JSON.stringify({ type: "text", content: friendlyAgentError(err) });
18407
18407
  const doneEvent = JSON.stringify({ type: "done", subtype: "error", error: rawMessage, error_category: category });
18408
18408
  sseLog.write(`[${ts}] [${sk}] admin: ERROR [${category}] ${rawMessage}
18409
18409
  `);
@@ -18514,8 +18514,8 @@ async function GET9(request) {
18514
18514
  const headers = { "Content-Type": "text/plain; charset=utf-8" };
18515
18515
  if (download) headers["Content-Disposition"] = `attachment; filename="${safe}"`;
18516
18516
  return new Response(content, { headers });
18517
- } catch (err2) {
18518
- const reason = err2 instanceof Error ? err2.message : String(err2);
18517
+ } catch (err) {
18518
+ const reason = err instanceof Error ? err.message : String(err);
18519
18519
  console.debug(`[admin/logs] miss dir=${dir} name=${safe} reason=${reason}`);
18520
18520
  }
18521
18521
  }
@@ -18556,8 +18556,8 @@ async function GET9(request) {
18556
18556
  const headers = { "Content-Type": "text/plain; charset=utf-8" };
18557
18557
  if (download) headers["Content-Disposition"] = `attachment; filename="${fileName}"`;
18558
18558
  return new Response(content, { headers });
18559
- } catch (err2) {
18560
- const reason = err2 instanceof Error ? err2.message : String(err2);
18559
+ } catch (err) {
18560
+ const reason = err instanceof Error ? err.message : String(err);
18561
18561
  console.debug(`[admin/logs] miss dir=${dir} name=${fileName} reason=${reason}`);
18562
18562
  }
18563
18563
  }
@@ -18571,8 +18571,8 @@ async function GET9(request) {
18571
18571
  let files;
18572
18572
  try {
18573
18573
  files = readdirSync5(dir).filter((f) => f.endsWith(".log"));
18574
- } catch (err2) {
18575
- const reason = err2 instanceof Error ? err2.message : String(err2);
18574
+ } catch (err) {
18575
+ const reason = err instanceof Error ? err.message : String(err);
18576
18576
  console.warn(`[admin/logs] readdir-fail dir=${dir} reason=${reason}`);
18577
18577
  continue;
18578
18578
  }
@@ -18582,8 +18582,8 @@ async function GET9(request) {
18582
18582
  const content = readFileSync20(resolve20(dir, name));
18583
18583
  const tail = content.length > TAIL_BYTES ? content.subarray(content.length - TAIL_BYTES).toString("utf-8") : content.toString("utf-8");
18584
18584
  logs[name] = tail.trim() || "(empty)";
18585
- } catch (err2) {
18586
- const reason = err2 instanceof Error ? err2.message : String(err2);
18585
+ } catch (err) {
18586
+ const reason = err instanceof Error ? err.message : String(err);
18587
18587
  console.debug(`[admin/logs] read-fail name=${name} reason=${reason}`);
18588
18588
  logs[name] = `(unreadable: ${reason})`;
18589
18589
  }
@@ -18693,8 +18693,8 @@ async function PATCH(req) {
18693
18693
  writeFileSync15(configPath2, JSON.stringify(config, null, 2) + "\n", "utf-8");
18694
18694
  console.error(`[account-update] contextMode=${contextMode}`);
18695
18695
  return Response.json({ ok: true, contextMode });
18696
- } catch (err2) {
18697
- console.error(`[account-update] failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
18696
+ } catch (err) {
18697
+ console.error(`[account-update] failed: ${err instanceof Error ? err.message : String(err)}`);
18698
18698
  return Response.json({ error: "Failed to update account" }, { status: 500 });
18699
18699
  }
18700
18700
  }
@@ -18730,8 +18730,8 @@ async function GET12() {
18730
18730
  console.error(`[admin/agents] failed to parse config.json for agent "${entry.name}" \u2014 skipping`);
18731
18731
  }
18732
18732
  }
18733
- } catch (err2) {
18734
- console.error(`[admin/agents] failed to scan agents directory: ${err2}`);
18733
+ } catch (err) {
18734
+ console.error(`[admin/agents] failed to scan agents directory: ${err}`);
18735
18735
  return Response.json({ agents: [] });
18736
18736
  }
18737
18737
  return Response.json({ agents });
@@ -18760,8 +18760,8 @@ async function DELETE2(_req, { params }) {
18760
18760
  rmSync3(agentDir, { recursive: true, force: true });
18761
18761
  console.log(`[admin/agents] deleted agent "${slug}"`);
18762
18762
  return Response.json({ ok: true });
18763
- } catch (err2) {
18764
- console.error(`[admin/agents] failed to delete agent "${slug}": ${err2}`);
18763
+ } catch (err) {
18764
+ console.error(`[admin/agents] failed to delete agent "${slug}": ${err}`);
18765
18765
  return Response.json({ error: "Failed to delete agent" }, { status: 500 });
18766
18766
  }
18767
18767
  }
@@ -18829,8 +18829,8 @@ function rotateIfNeeded() {
18829
18829
  const stats = statSync9(CLIENT_ERRORS_LOG);
18830
18830
  if (stats.size < MAX_LOG_SIZE) return;
18831
18831
  renameSync4(CLIENT_ERRORS_LOG, CLIENT_ERRORS_LOG + ".1");
18832
- } catch (err2) {
18833
- console.error(`[client-error] log rotation failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
18832
+ } catch (err) {
18833
+ console.error(`[client-error] log rotation failed: ${err instanceof Error ? err.message : String(err)}`);
18834
18834
  }
18835
18835
  }
18836
18836
  async function POST24(req, remoteAddress) {
@@ -18896,8 +18896,8 @@ async function POST24(req, remoteAddress) {
18896
18896
  status: typeof body.status === "number" ? body.status : void 0
18897
18897
  };
18898
18898
  appendFileSync4(CLIENT_ERRORS_LOG, JSON.stringify(payload) + "\n", "utf-8");
18899
- } catch (err2) {
18900
- console.error(`[client-error] append failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
18899
+ } catch (err) {
18900
+ console.error(`[client-error] append failed: ${err instanceof Error ? err.message : String(err)}`);
18901
18901
  }
18902
18902
  errorTimestamps.push(Date.now());
18903
18903
  return Response.json({ ok: true });
@@ -18942,8 +18942,8 @@ async function fetchLatest() {
18942
18942
  return null;
18943
18943
  }
18944
18944
  return version;
18945
- } catch (err2) {
18946
- console.error(`[admin/version] npm registry fetch failed: ${err2}`);
18945
+ } catch (err) {
18946
+ console.error(`[admin/version] npm registry fetch failed: ${err}`);
18947
18947
  return null;
18948
18948
  }
18949
18949
  }
@@ -19028,15 +19028,15 @@ async function POST25(req) {
19028
19028
  const installerScope = `upgrade-${upgradeHostname}`;
19029
19029
  try {
19030
19030
  writeFileSync16(LOCK_FILE, String(Date.now()));
19031
- } catch (err2) {
19032
- console.error("[admin/version/upgrade] failed to write lock file:", err2);
19031
+ } catch (err) {
19032
+ console.error("[admin/version/upgrade] failed to write lock file:", err);
19033
19033
  }
19034
19034
  try {
19035
19035
  writeFileSync16(LOG_FILE, "");
19036
- } catch (err2) {
19037
- console.error("[admin/version/upgrade] failed to truncate upgrade log:", err2);
19036
+ } catch (err) {
19037
+ console.error("[admin/version/upgrade] failed to truncate upgrade log:", err);
19038
19038
  return Response.json(
19039
- { ok: false, error: err2 instanceof Error ? err2.message : "failed to prepare upgrade log" },
19039
+ { ok: false, error: err instanceof Error ? err.message : "failed to prepare upgrade log" },
19040
19040
  { status: 500 }
19041
19041
  );
19042
19042
  }
@@ -19060,10 +19060,10 @@ async function POST25(req) {
19060
19060
  closeSync5(logFd);
19061
19061
  console.log(`[admin/version/upgrade] spawned upgrade process (pid ${child.pid} scope ${installerScope})`);
19062
19062
  return Response.json({ ok: true, started: true });
19063
- } catch (err2) {
19064
- console.error("[admin/version/upgrade] failed to spawn upgrade process:", err2);
19063
+ } catch (err) {
19064
+ console.error("[admin/version/upgrade] failed to spawn upgrade process:", err);
19065
19065
  return Response.json(
19066
- { ok: false, error: err2 instanceof Error ? err2.message : "failed to start upgrade" },
19066
+ { ok: false, error: err instanceof Error ? err.message : "failed to start upgrade" },
19067
19067
  { status: 500 }
19068
19068
  );
19069
19069
  }
@@ -19151,8 +19151,8 @@ async function GET15(req) {
19151
19151
  try {
19152
19152
  const sessions = await listAdminSessions(accountId, userId, 20);
19153
19153
  return Response.json({ sessions });
19154
- } catch (err2) {
19155
- console.error(`[sessions-list] Failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
19154
+ } catch (err) {
19155
+ console.error(`[sessions-list] Failed: ${err instanceof Error ? err.message : String(err)}`);
19156
19156
  return Response.json({ error: "Failed to fetch sessions" }, { status: 500 });
19157
19157
  }
19158
19158
  }
@@ -19210,8 +19210,8 @@ async function DELETE3(req, { params }) {
19210
19210
  try {
19211
19211
  await deleteConversation(conversationId);
19212
19212
  return Response.json({ ok: true });
19213
- } catch (err2) {
19214
- console.error(`[sessions-delete] Failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
19213
+ } catch (err) {
19214
+ console.error(`[sessions-delete] Failed: ${err instanceof Error ? err.message : String(err)}`);
19215
19215
  return Response.json({ error: "Failed to delete session" }, { status: 500 });
19216
19216
  }
19217
19217
  }
@@ -19238,8 +19238,8 @@ async function GET16(req, { params }) {
19238
19238
  try {
19239
19239
  const messages = await getRecentMessages(conversationId, 50);
19240
19240
  return Response.json({ messages });
19241
- } catch (err2) {
19242
- console.error(`[sessions-messages] Failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
19241
+ } catch (err) {
19242
+ console.error(`[sessions-messages] Failed: ${err instanceof Error ? err.message : String(err)}`);
19243
19243
  return Response.json({ error: "Failed to fetch messages" }, { status: 500 });
19244
19244
  }
19245
19245
  }
@@ -19274,8 +19274,8 @@ async function POST27(req, { params }) {
19274
19274
  seedSessionHistory(sessionKey, messages);
19275
19275
  estimatedTokens = messages.reduce((sum, m) => sum + Math.ceil(m.content.length / 4), 0);
19276
19276
  }
19277
- } catch (err2) {
19278
- console.error(`[session-resume] ${(/* @__PURE__ */ new Date()).toISOString()} getRecentMessages failed: conversationId=${conversationId.slice(0, 8)}\u2026 error=${err2 instanceof Error ? err2.message : String(err2)}`);
19277
+ } catch (err) {
19278
+ console.error(`[session-resume] ${(/* @__PURE__ */ new Date()).toISOString()} getRecentMessages failed: conversationId=${conversationId.slice(0, 8)}\u2026 error=${err instanceof Error ? err.message : String(err)}`);
19279
19279
  return Response.json({ error: "Failed to load conversation messages" }, { status: 500 });
19280
19280
  }
19281
19281
  const age = formatAge(updatedAt);
@@ -19335,8 +19335,8 @@ async function POST28(req, { params }) {
19335
19335
  console.error(`[admin] manual-label: haiku failed for ${conversationId} \u2014 null response`);
19336
19336
  }
19337
19337
  return Response.json({ label });
19338
- } catch (err2) {
19339
- console.error(`[admin] manual-label: haiku failed for ${conversationId} \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
19338
+ } catch (err) {
19339
+ console.error(`[admin] manual-label: haiku failed for ${conversationId} \u2014 ${err instanceof Error ? err.message : String(err)}`);
19340
19340
  return Response.json({ label: null });
19341
19341
  }
19342
19342
  }
@@ -19373,8 +19373,8 @@ async function PUT(req, { params }) {
19373
19373
  try {
19374
19374
  await renameConversation(conversationId, label);
19375
19375
  return Response.json({ ok: true });
19376
- } catch (err2) {
19377
- console.error(`[persist] manual-label: failed to rename ${conversationId} \u2014 ${err2 instanceof Error ? err2.message : String(err2)}`);
19376
+ } catch (err) {
19377
+ console.error(`[persist] manual-label: failed to rename ${conversationId} \u2014 ${err instanceof Error ? err.message : String(err)}`);
19378
19378
  return Response.json({ error: "Failed to rename session" }, { status: 500 });
19379
19379
  }
19380
19380
  }
@@ -19394,10 +19394,10 @@ async function POST29(req, remoteAddress) {
19394
19394
  return Response.json({ ok: false, error: "Chrome failed to start" }, { status: 502 });
19395
19395
  }
19396
19396
  return Response.json({ ok: true, transport });
19397
- } catch (err2) {
19398
- console.error("[admin/browser/launch] Failed to start browser:", err2);
19397
+ } catch (err) {
19398
+ console.error("[admin/browser/launch] Failed to start browser:", err);
19399
19399
  return Response.json(
19400
- { ok: false, error: err2 instanceof Error ? err2.message : "Unknown error" },
19400
+ { ok: false, error: err instanceof Error ? err.message : "Unknown error" },
19401
19401
  { status: 500 }
19402
19402
  );
19403
19403
  }
@@ -19416,12 +19416,12 @@ async function cdpNavigateNewTab(url, opts = {}) {
19416
19416
  method: "PUT",
19417
19417
  signal: AbortSignal.timeout(timeoutMs)
19418
19418
  });
19419
- } catch (err2) {
19420
- const msg = err2 instanceof Error ? err2.message : String(err2);
19419
+ } catch (err) {
19420
+ const msg = err instanceof Error ? err.message : String(err);
19421
19421
  if (msg.includes("ECONNREFUSED") || msg.includes("fetch failed") || msg.includes("ENOTFOUND")) {
19422
19422
  return { result: "cdp-unreachable", detail: msg };
19423
19423
  }
19424
- if (err2 instanceof Error && err2.name === "TimeoutError") {
19424
+ if (err instanceof Error && err.name === "TimeoutError") {
19425
19425
  return { result: "timeout", detail: msg };
19426
19426
  }
19427
19427
  return { result: "error", detail: msg };
@@ -19436,8 +19436,8 @@ async function cdpNavigateNewTab(url, opts = {}) {
19436
19436
  let target;
19437
19437
  try {
19438
19438
  target = await res.json();
19439
- } catch (err2) {
19440
- const msg = err2 instanceof Error ? err2.message : String(err2);
19439
+ } catch (err) {
19440
+ const msg = err instanceof Error ? err.message : String(err);
19441
19441
  return { result: "error", detail: `CDP /json/new response not JSON: ${msg}` };
19442
19442
  }
19443
19443
  return { result: "ok", targetId: target?.id };
@@ -19449,8 +19449,8 @@ async function POST30(req, remoteAddress) {
19449
19449
  let body;
19450
19450
  try {
19451
19451
  body = await req.json();
19452
- } catch (err2) {
19453
- const detail = err2 instanceof Error ? err2.message : String(err2);
19452
+ } catch (err) {
19453
+ const detail = err instanceof Error ? err.message : String(err);
19454
19454
  console.error(`${TAG18} reject reason=body-not-json detail=${detail} browser=fallback navigateResult=error`);
19455
19455
  return Response.json(
19456
19456
  { ok: false, navigateResult: "error", browser: "fallback", detail: "Request body was not valid JSON" },
@@ -19544,8 +19544,8 @@ async function POST31(req) {
19544
19544
  let body;
19545
19545
  try {
19546
19546
  body = await req.json();
19547
- } catch (err2) {
19548
- const detail = err2 instanceof Error ? err2.message : String(err2);
19547
+ } catch (err) {
19548
+ const detail = err instanceof Error ? err.message : String(err);
19549
19549
  console.error(`${TAG18} reject reason=body-not-json detail=${detail}`);
19550
19550
  return Response.json({ ok: false, detail: "Request body was not valid JSON" }, { status: 400 });
19551
19551
  }
@@ -19615,20 +19615,6 @@ function addAliasDomain(hostname2) {
19615
19615
 
19616
19616
  // app/api/admin/cloudflare/setup/route.ts
19617
19617
  var SCRIPT_TIMEOUT_MS = 10 * 60 * 1e3;
19618
- function log(line) {
19619
- console.log(`[cloudflare-setup] ${line}`);
19620
- }
19621
- function logErr(line) {
19622
- console.error(`[cloudflare-setup] ${line}`);
19623
- }
19624
- function err(field, message, output) {
19625
- logErr(`phase=error field=${field} reason="${message.slice(0, 160).replace(/"/g, "'")}"`);
19626
- const body = { ok: false, field, message, output };
19627
- return Response.json(body, { status: 200 });
19628
- }
19629
- function ok(result) {
19630
- return Response.json(result, { status: 200 });
19631
- }
19632
19618
  function loadBrandInfo() {
19633
19619
  const platformRoot3 = process.env.MAXY_PLATFORM_ROOT ?? resolve29(process.cwd(), "..");
19634
19620
  const brandPath3 = resolve29(platformRoot3, "config", "brand.json");
@@ -19684,10 +19670,14 @@ function validateBody(body) {
19684
19670
  }
19685
19671
  return null;
19686
19672
  }
19687
- function runScript(scriptPath, args) {
19673
+ function runScript(scriptPath, args, streamLogPath, log) {
19688
19674
  return new Promise((resolveP) => {
19689
19675
  const child = childProcess.spawn(scriptPath, args, {
19690
- env: { ...process.env },
19676
+ // STREAM_LOG_PATH (Task 581) enables setup-tunnel.sh's shared
19677
+ // _stream-log.sh helpers to tee phase lines + subprocess output into
19678
+ // the per-conversation stream log — same file the admin chat tailer
19679
+ // already reads for live in-turn rendering of agent events.
19680
+ env: { ...process.env, STREAM_LOG_PATH: streamLogPath },
19691
19681
  stdio: ["ignore", "pipe", "pipe"]
19692
19682
  });
19693
19683
  log(`phase=script-spawn pid=${child.pid ?? "unknown"} args="${args.join(" ")}"`);
@@ -19721,11 +19711,48 @@ ${e.message}`, timedOut: false });
19721
19711
  }
19722
19712
  async function POST32(req) {
19723
19713
  const started = Date.now();
19714
+ let correlationId;
19715
+ let sessionKeyTail;
19716
+ let streamLogPath;
19717
+ function tag() {
19718
+ if (!correlationId) return "";
19719
+ return ` conversationId=${correlationId} session_key=${sessionKeyTail ?? "unknown"}`;
19720
+ }
19721
+ function log(line) {
19722
+ console.log(`[cloudflare-setup] ${line}${tag()}`);
19723
+ }
19724
+ function logErr(line) {
19725
+ console.error(`[cloudflare-setup] ${line}${tag()}`);
19726
+ }
19727
+ function err(field, message, output) {
19728
+ logErr(`phase=error field=${field} reason="${message.slice(0, 160).replace(/"/g, "'")}"`);
19729
+ const body2 = {
19730
+ ok: false,
19731
+ field,
19732
+ message,
19733
+ output,
19734
+ correlationId,
19735
+ streamLogPath
19736
+ };
19737
+ return Response.json(body2, { status: 200 });
19738
+ }
19739
+ function ok(result2) {
19740
+ return Response.json(result2, { status: 200 });
19741
+ }
19724
19742
  const body = await parseBody2(req);
19725
19743
  if (!body) return err("request", "Invalid JSON body");
19726
19744
  if (!validateSession(body.session_key, "admin")) {
19727
19745
  return err("request", "Invalid or expired admin session");
19728
19746
  }
19747
+ const accountId = getAccountIdForSession(body.session_key);
19748
+ correlationId = getConversationIdForSession(body.session_key);
19749
+ sessionKeyTail = body.session_key.slice(-8);
19750
+ if (!accountId) {
19751
+ return err("request", "No account bound to session \u2014 refresh chat.");
19752
+ }
19753
+ if (!correlationId) {
19754
+ return err("request", "No active conversation for session \u2014 refresh chat.");
19755
+ }
19729
19756
  const invalid = validateBody(body);
19730
19757
  if (invalid) return err(invalid.field, invalid.message);
19731
19758
  const adminFqdn = `${body.adminLabel}.${body.adminDomain}`;
@@ -19746,11 +19773,13 @@ async function POST32(req) {
19746
19773
  } catch (e) {
19747
19774
  return err("script", `Server misconfigured: ${e instanceof Error ? e.message : String(e)}`);
19748
19775
  }
19776
+ streamLogPath = streamLogPathFor(accountId, correlationId).streamLogPath;
19777
+ log(`phase=stream-log-resolved path=${streamLogPath}`);
19749
19778
  const scriptPath = resolve29(homedir4(), "setup-tunnel.sh");
19750
19779
  const args = [brand.hostname, String(port2), adminFqdn];
19751
19780
  if (publicFqdn) args.push(publicFqdn);
19752
19781
  if (apex) args.push(apex);
19753
- const result = await runScript(scriptPath, args);
19782
+ const result = await runScript(scriptPath, args, streamLogPath, log);
19754
19783
  const combined = `${result.stdout}${result.stderr ? `
19755
19784
  ---
19756
19785
  ${result.stderr}` : ""}`;
@@ -19804,8 +19833,8 @@ async function POST33(req) {
19804
19833
  const body = await req.json();
19805
19834
  if (typeof body?.installed === "string") installed = body.installed;
19806
19835
  if (typeof body?.latest === "string") latest = body.latest;
19807
- } catch (err2) {
19808
- console.error(`[admin/version] alert-surfaced body parse failed: ${err2}`);
19836
+ } catch (err) {
19837
+ console.error(`[admin/version] alert-surfaced body parse failed: ${err}`);
19809
19838
  }
19810
19839
  console.log(`[admin/version] alert-surfaced installed=${installed} latest=${latest ?? "null"}`);
19811
19840
  return Response.json({ ok: true });
@@ -19826,18 +19855,18 @@ function resolveDataPath(raw2) {
19826
19855
  let dataRootReal;
19827
19856
  try {
19828
19857
  dataRootReal = realpathSync3(DATA_ROOT);
19829
- } catch (err2) {
19858
+ } catch (err) {
19830
19859
  return {
19831
19860
  ok: false,
19832
19861
  status: 500,
19833
- error: `DATA_ROOT not accessible: ${err2 instanceof Error ? err2.message : String(err2)}`
19862
+ error: `DATA_ROOT not accessible: ${err instanceof Error ? err.message : String(err)}`
19834
19863
  };
19835
19864
  }
19836
19865
  let resolvedReal;
19837
19866
  try {
19838
19867
  resolvedReal = realpathSync3(absolute);
19839
- } catch (err2) {
19840
- const code = err2.code;
19868
+ } catch (err) {
19869
+ const code = err.code;
19841
19870
  if (code === "ENOENT") {
19842
19871
  if (absolute !== dataRootReal && !absolute.startsWith(dataRootReal + sep)) {
19843
19872
  return { ok: false, status: 403, error: "Path escapes DATA_ROOT", resolved: absolute };
@@ -19847,7 +19876,7 @@ function resolveDataPath(raw2) {
19847
19876
  return {
19848
19877
  ok: false,
19849
19878
  status: 500,
19850
- error: err2 instanceof Error ? err2.message : String(err2)
19879
+ error: err instanceof Error ? err.message : String(err)
19851
19880
  };
19852
19881
  }
19853
19882
  if (resolvedReal !== dataRootReal && !resolvedReal.startsWith(dataRootReal + sep)) {
@@ -19948,13 +19977,13 @@ async function GET17(req) {
19948
19977
  });
19949
19978
  console.error(`[data] file-list path="${relPath}" entries=${entries.length}`);
19950
19979
  return Response.json({ path: relPath, entries });
19951
- } catch (err2) {
19952
- const code = err2.code;
19980
+ } catch (err) {
19981
+ const code = err.code;
19953
19982
  if (code === "ENOENT") {
19954
19983
  console.error(`[data] file-list not-found path="${relPath}"`);
19955
19984
  return Response.json({ error: "Not found" }, { status: 404 });
19956
19985
  }
19957
- const message = err2 instanceof Error ? err2.message : String(err2);
19986
+ const message = err instanceof Error ? err.message : String(err);
19958
19987
  console.error(`[data] file-list error path="${relPath}" err="${message}"`);
19959
19988
  return Response.json({ error: message }, { status: 500 });
19960
19989
  }
@@ -20013,13 +20042,13 @@ async function GET18(req) {
20013
20042
  "Cache-Control": "no-store"
20014
20043
  }
20015
20044
  });
20016
- } catch (err2) {
20017
- const code = err2.code;
20045
+ } catch (err) {
20046
+ const code = err.code;
20018
20047
  if (code === "ENOENT") {
20019
20048
  console.error(`[data] file-download not-found path="${relPath}"`);
20020
20049
  return Response.json({ error: "Not found" }, { status: 404 });
20021
20050
  }
20022
- const message = err2 instanceof Error ? err2.message : String(err2);
20051
+ const message = err instanceof Error ? err.message : String(err);
20023
20052
  console.error(`[data] file-download error path="${relPath}" err="${message}"`);
20024
20053
  return Response.json({ error: message }, { status: 500 });
20025
20054
  }
@@ -20033,8 +20062,8 @@ async function POST34(req) {
20033
20062
  let formData;
20034
20063
  try {
20035
20064
  formData = await req.formData();
20036
- } catch (err2) {
20037
- const message = err2 instanceof Error ? err2.message : String(err2);
20065
+ } catch (err) {
20066
+ const message = err instanceof Error ? err.message : String(err);
20038
20067
  return Response.json({ error: `Invalid multipart body: ${message}` }, { status: 400 });
20039
20068
  }
20040
20069
  const sessionKey = formData.get("session_key") ?? "";
@@ -20081,8 +20110,8 @@ async function POST34(req) {
20081
20110
  }
20082
20111
  const buffer = Buffer.from(await file.arrayBuffer());
20083
20112
  await writeFile4(destPath, buffer);
20084
- } catch (err2) {
20085
- const message = err2 instanceof Error ? err2.message : String(err2);
20113
+ } catch (err) {
20114
+ const message = err instanceof Error ? err.message : String(err);
20086
20115
  console.error(`[data] file-upload error filename="${safeName}" err="${message}"`);
20087
20116
  return Response.json({ error: message }, { status: 500 });
20088
20117
  }
@@ -20128,9 +20157,9 @@ async function GET19(req) {
20128
20157
  const elapsed = Date.now() - started;
20129
20158
  console.error(`[data] graph-search query="${q}" results=${results.length} ms=${elapsed}`);
20130
20159
  return Response.json({ results, elapsedMs: elapsed });
20131
- } catch (err2) {
20160
+ } catch (err) {
20132
20161
  const elapsed = Date.now() - started;
20133
- const message = err2 instanceof Error ? err2.message : String(err2);
20162
+ const message = err instanceof Error ? err.message : String(err);
20134
20163
  console.error(`[data] graph-search neo4j-unreachable query="${q}" ms=${elapsed} err="${message}"`);
20135
20164
  return Response.json({ error: `Graph search unavailable: ${message}` }, { status: 503 });
20136
20165
  }
@@ -20150,8 +20179,8 @@ if (BRAND_JSON_PATH && existsSync29(BRAND_JSON_PATH)) {
20150
20179
  try {
20151
20180
  const parsed = JSON.parse(readFileSync29(BRAND_JSON_PATH, "utf-8"));
20152
20181
  BRAND = { ...BRAND, ...parsed };
20153
- } catch (err2) {
20154
- console.error(`[brand] Failed to parse brand.json: ${err2.message}`);
20182
+ } catch (err) {
20183
+ console.error(`[brand] Failed to parse brand.json: ${err.message}`);
20155
20184
  process.exit(1);
20156
20185
  }
20157
20186
  }
@@ -20177,8 +20206,8 @@ function loadAliasDomains() {
20177
20206
  return null;
20178
20207
  }
20179
20208
  return new Set(parsed.filter((h) => typeof h === "string"));
20180
- } catch (err2) {
20181
- console.error(`[alias-domains] failed to read alias-domains.json: ${err2}`);
20209
+ } catch (err) {
20210
+ console.error(`[alias-domains] failed to read alias-domains.json: ${err}`);
20182
20211
  return null;
20183
20212
  }
20184
20213
  }
@@ -20358,8 +20387,8 @@ app.post("/__remote-auth/change-password", async (c) => {
20358
20387
  clearRateLimit(clientIp);
20359
20388
  console.error(`[remote-auth] password changed ip=${clientIp}`);
20360
20389
  return c.html(renderLoginPage({ ...resolveRemoteAuthOpts(), success: "Password changed successfully. Sign in with your new password.", redirect }), 200);
20361
- } catch (err2) {
20362
- console.error(`[remote-auth] change-password save failed: ${err2}`);
20390
+ } catch (err) {
20391
+ console.error(`[remote-auth] change-password save failed: ${err}`);
20363
20392
  return c.html(renderLoginPage({ ...resolveRemoteAuthOpts(), mode: "change", changeError: "Failed to save password", redirect }), 200);
20364
20393
  }
20365
20394
  });
@@ -20403,8 +20432,8 @@ app.post("/__remote-auth/set-initial-password", async (c) => {
20403
20432
  ) ?? "unknown";
20404
20433
  console.error(`[remote-auth] initial password set ip=${clientIp}`);
20405
20434
  return c.html(renderLoginPage({ ...resolveRemoteAuthOpts(), mode: "success" }), 200);
20406
- } catch (err2) {
20407
- console.error(`[remote-auth] initial password save failed: ${err2}`);
20435
+ } catch (err) {
20436
+ console.error(`[remote-auth] initial password save failed: ${err}`);
20408
20437
  return c.html(renderLoginPage({ ...resolveRemoteAuthOpts(), mode: "setup", setupError: "Failed to save password. Please try again." }), 200);
20409
20438
  }
20410
20439
  });
@@ -20436,8 +20465,8 @@ app.post("/api/remote-auth/set-password", async (c) => {
20436
20465
  await setRemotePassword(body.password);
20437
20466
  console.error("[remote-auth] password set");
20438
20467
  return Response.json({ ok: true });
20439
- } catch (err2) {
20440
- console.error(`[remote-auth] set-password failed: ${err2}`);
20468
+ } catch (err) {
20469
+ console.error(`[remote-auth] set-password failed: ${err}`);
20441
20470
  return Response.json({ error: "Failed to save password" }, { status: 500 });
20442
20471
  }
20443
20472
  });
@@ -20890,8 +20919,8 @@ try {
20890
20919
  }
20891
20920
  const summary = registered.map((r) => `${r.method} ${r.path}`).join(", ") || "(none)";
20892
20921
  console.log(`[route-shadow] static-paths-matching-slug-pattern count=${registered.length} routes=${summary}`);
20893
- } catch (err2) {
20894
- console.error(`[route-shadow] introspection unavailable: ${err2 instanceof Error ? err2.message : String(err2)}`);
20922
+ } catch (err) {
20923
+ console.error(`[route-shadow] introspection unavailable: ${err instanceof Error ? err.message : String(err)}`);
20895
20924
  }
20896
20925
  (async () => {
20897
20926
  try {
@@ -20901,15 +20930,15 @@ try {
20901
20930
  userId = users[0]?.userId ?? "";
20902
20931
  }
20903
20932
  await backfillNullUserIdConversations(userId);
20904
- } catch (err2) {
20905
- console.error(`[session] backfill startup failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
20933
+ } catch (err) {
20934
+ console.error(`[session] backfill startup failed: ${err instanceof Error ? err.message : String(err)}`);
20906
20935
  }
20907
20936
  })();
20908
20937
  (async () => {
20909
20938
  try {
20910
20939
  await startReviewDetector();
20911
- } catch (err2) {
20912
- console.error(`[review] startReviewDetector rejected: ${err2 instanceof Error ? err2.message : String(err2)}`);
20940
+ } catch (err) {
20941
+ console.error(`[review] startReviewDetector rejected: ${err instanceof Error ? err.message : String(err)}`);
20913
20942
  }
20914
20943
  })();
20915
20944
  var configDirForWhatsApp = basename8(MAXY_DIR) || ".maxy";
@@ -21015,8 +21044,8 @@ init({
21015
21044
  }
21016
21045
  await msg.reply(responseText);
21017
21046
  }
21018
- } catch (err2) {
21019
- console.error(`[whatsapp:route] agent invocation failed: ${String(err2)}`);
21047
+ } catch (err) {
21048
+ console.error(`[whatsapp:route] agent invocation failed: ${String(err)}`);
21020
21049
  try {
21021
21050
  if (!msg.isOwnerMirror) {
21022
21051
  await msg.reply("I'm having trouble right now. Please try again in a moment.");
@@ -21025,8 +21054,8 @@ init({
21025
21054
  }
21026
21055
  }
21027
21056
  }
21028
- }).catch((err2) => {
21029
- console.error(`[whatsapp] init failed: ${String(err2)}`);
21057
+ }).catch((err) => {
21058
+ console.error(`[whatsapp] init failed: ${String(err)}`);
21030
21059
  });
21031
21060
  var shuttingDown = false;
21032
21061
  process.on("SIGTERM", async () => {
@@ -21038,24 +21067,24 @@ process.on("SIGTERM", async () => {
21038
21067
  console.error("[server] SIGTERM received \u2014 starting graceful shutdown");
21039
21068
  try {
21040
21069
  sigtermFlushStreamLogs("systemd-stop", "server-index");
21041
- } catch (err2) {
21042
- console.error(`[server] sigterm flush error: ${String(err2)}`);
21070
+ } catch (err) {
21071
+ console.error(`[server] sigterm flush error: ${String(err)}`);
21043
21072
  }
21044
21073
  try {
21045
21074
  broadcastAdminShutdown("systemd-stop");
21046
- } catch (err2) {
21047
- console.error(`[server] sigterm broadcast error: ${String(err2)}`);
21075
+ } catch (err) {
21076
+ console.error(`[server] sigterm broadcast error: ${String(err)}`);
21048
21077
  }
21049
21078
  await new Promise((res) => setImmediate(res));
21050
21079
  try {
21051
21080
  await shutdown();
21052
- } catch (err2) {
21053
- console.error(`[server] shutdown error: ${String(err2)}`);
21081
+ } catch (err) {
21082
+ console.error(`[server] shutdown error: ${String(err)}`);
21054
21083
  }
21055
21084
  try {
21056
21085
  await shutdownReviewDetector();
21057
- } catch (err2) {
21058
- console.error(`[server] review detector shutdown error: ${String(err2)}`);
21086
+ } catch (err) {
21087
+ console.error(`[server] review detector shutdown error: ${String(err)}`);
21059
21088
  }
21060
21089
  console.error("[server] graceful shutdown complete \u2014 exiting");
21061
21090
  process.exit(0);