@zqagent/core 0.2.7 → 0.2.10

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.
@@ -5147,10 +5147,10 @@ var OpenAIProvider = class {
5147
5147
  let timer;
5148
5148
  try {
5149
5149
  for (; ; ) {
5150
- const idle = new Promise((resolve18) => {
5150
+ const idle = new Promise((resolve19) => {
5151
5151
  timer = setTimeout(() => {
5152
5152
  onIdle();
5153
- resolve18({ timedOut: true });
5153
+ resolve19({ timedOut: true });
5154
5154
  }, idleMs);
5155
5155
  });
5156
5156
  const next = iter.next();
@@ -5778,12 +5778,12 @@ function makeSink(maxBuffer) {
5778
5778
  };
5779
5779
  }
5780
5780
  function execAsync(file, argv, opts = {}) {
5781
- return new Promise((resolve18) => {
5781
+ return new Promise((resolve19) => {
5782
5782
  const maxBuffer = opts.maxBuffer ?? DEFAULT_MAX_BUFFER;
5783
5783
  const out = makeSink(maxBuffer);
5784
5784
  const err = makeSink(maxBuffer);
5785
5785
  if (opts.signal?.aborted) {
5786
- resolve18({
5786
+ resolve19({
5787
5787
  status: null,
5788
5788
  stdout: Buffer.alloc(0),
5789
5789
  stderr: Buffer.alloc(0),
@@ -5804,7 +5804,7 @@ function execAsync(file, argv, opts = {}) {
5804
5804
  windowsHide: true
5805
5805
  });
5806
5806
  } catch (e) {
5807
- resolve18({
5807
+ resolve19({
5808
5808
  status: null,
5809
5809
  stdout: Buffer.alloc(0),
5810
5810
  stderr: Buffer.alloc(0),
@@ -5841,7 +5841,7 @@ function execAsync(file, argv, opts = {}) {
5841
5841
  };
5842
5842
  if (aborted) result.aborted = true;
5843
5843
  if (spawnError) result.error = spawnError;
5844
- resolve18(result);
5844
+ resolve19(result);
5845
5845
  };
5846
5846
  const killAndSettle = () => {
5847
5847
  killTree(child.pid);
@@ -9840,11 +9840,11 @@ function isAffirmative(answer) {
9840
9840
  return /^(yes|approve|同意|批准|允许|确定|可以|好的|确认)/.test(a);
9841
9841
  }
9842
9842
  function defer() {
9843
- let resolve18;
9843
+ let resolve19;
9844
9844
  const promise = new Promise((r) => {
9845
- resolve18 = r;
9845
+ resolve19 = r;
9846
9846
  });
9847
- return { promise, resolve: resolve18 };
9847
+ return { promise, resolve: resolve19 };
9848
9848
  }
9849
9849
  var SessionManager = class {
9850
9850
  constructor(store, approvalTimeoutMs = APPROVAL_TIMEOUT_MS, opts = {}) {
@@ -10416,11 +10416,11 @@ data: ${JSON.stringify({ sessionId, seq: entry.seq, ts: entry.ts, data: entry.da
10416
10416
  status: "pending",
10417
10417
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
10418
10418
  };
10419
- const { promise, resolve: resolve18 } = defer();
10419
+ const { promise, resolve: resolve19 } = defer();
10420
10420
  const timer = setTimeout(() => {
10421
10421
  this._recycleApproval(rt, id);
10422
10422
  }, this.approvalTimeoutMs);
10423
- rt.pendingApprovals.set(id, { promise, resolve: resolve18, record, timer });
10423
+ rt.pendingApprovals.set(id, { promise, resolve: resolve19, record, timer });
10424
10424
  rt.approvals.set(id, record);
10425
10425
  this._setStatus(rt, "waiting_approval");
10426
10426
  this._persist(rt);
@@ -10498,11 +10498,11 @@ data: ${JSON.stringify({ sessionId, seq: entry.seq, ts: entry.ts, data: entry.da
10498
10498
  status: "pending",
10499
10499
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
10500
10500
  };
10501
- const { promise, resolve: resolve18 } = defer();
10501
+ const { promise, resolve: resolve19 } = defer();
10502
10502
  const timer = setTimeout(() => {
10503
10503
  this._recycleQuestion(rt, qid);
10504
10504
  }, this.approvalTimeoutMs);
10505
- rt.pendingQuestions.set(qid, { promise, resolve: resolve18, record, timer });
10505
+ rt.pendingQuestions.set(qid, { promise, resolve: resolve19, record, timer });
10506
10506
  rt.questions.set(qid, record);
10507
10507
  this._setStatus(rt, "waiting_question");
10508
10508
  this._persist(rt);
@@ -10811,7 +10811,7 @@ data: ${JSON.stringify(entry.data)}
10811
10811
  if (rt.mcpReady) {
10812
10812
  await Promise.race([
10813
10813
  rt.mcpReady,
10814
- new Promise((resolve18) => setTimeout(resolve18, 15e3))
10814
+ new Promise((resolve19) => setTimeout(resolve19, 15e3))
10815
10815
  ]).catch(() => void 0);
10816
10816
  }
10817
10817
  for await (const event of gen) {
@@ -11396,7 +11396,7 @@ function buildNodeInfo(store, opts) {
11396
11396
  nodeId: opts.nodeId ?? ensureNodeId(store),
11397
11397
  platform: process.platform,
11398
11398
  mode: process.env.NODE_MODE ?? "standalone",
11399
- version: "0.2.7",
11399
+ version: "0.2.10",
11400
11400
  admin: opts.admin,
11401
11401
  projects: opts.projects
11402
11402
  };
@@ -12389,7 +12389,7 @@ function buildNodeHost(store, manager, diskPath) {
12389
12389
  arch: process.arch,
12390
12390
  release: os6.release(),
12391
12391
  uptimeSec: Math.round(os6.uptime()),
12392
- version: "0.2.7",
12392
+ version: "0.2.10",
12393
12393
  mode: process.env.NODE_MODE ?? "standalone",
12394
12394
  cpu: {
12395
12395
  count: cpus2.length,
@@ -12433,7 +12433,7 @@ function saveNotifications(tenant, secretBox, notifications) {
12433
12433
  var API_PREFIX = "/api/v1";
12434
12434
  var MAX_BODY_BYTES = 10 * 1024 * 1024;
12435
12435
  function readBody(req2) {
12436
- return new Promise((resolve18, reject) => {
12436
+ return new Promise((resolve19, reject) => {
12437
12437
  const chunks = [];
12438
12438
  let size = 0;
12439
12439
  req2.on("data", (c) => {
@@ -12446,9 +12446,9 @@ function readBody(req2) {
12446
12446
  chunks.push(c);
12447
12447
  });
12448
12448
  req2.on("end", () => {
12449
- if (chunks.length === 0) return resolve18(void 0);
12449
+ if (chunks.length === 0) return resolve19(void 0);
12450
12450
  try {
12451
- resolve18(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
12451
+ resolve19(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
12452
12452
  } catch {
12453
12453
  reject(new ApiError(400, "bad_request", "\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5 JSON"));
12454
12454
  }
@@ -12964,8 +12964,18 @@ function createApp(store, manager, opts = {}) {
12964
12964
  applyProvidersPatch(tenant, raw);
12965
12965
  if (typeof raw.workspaceRoot === "string") {
12966
12966
  const ws = raw.workspaceRoot.trim();
12967
- if (ws) tenant.workspaceRoot = path26.resolve(ws);
12968
- else delete tenant.workspaceRoot;
12967
+ const next = ws ? path26.resolve(ws) : void 0;
12968
+ if (tenant.workspaceRoot) {
12969
+ if (next !== tenant.workspaceRoot) {
12970
+ throw new ApiError(
12971
+ 409,
12972
+ "workspace_locked",
12973
+ "\u8BE5\u9879\u76EE\u5DF2\u8BBE\u7F6E\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u4E0D\u80FD\u518D\u4FEE\u6539"
12974
+ );
12975
+ }
12976
+ } else if (next) {
12977
+ tenant.workspaceRoot = next;
12978
+ }
12969
12979
  }
12970
12980
  if (typeof raw.name === "string" && raw.name.trim()) {
12971
12981
  tenant.name = raw.name.trim();
@@ -13941,7 +13951,7 @@ function createApp(store, manager, opts = {}) {
13941
13951
  json(res, 200, {
13942
13952
  status: "ok",
13943
13953
  // 版本让运维/探针能确认线上跑的是哪个构建(更新与回滚据此判断)
13944
- version: "0.2.7",
13954
+ version: "0.2.10",
13945
13955
  features: { mcp: hasServerMcpConfig() }
13946
13956
  });
13947
13957
  return;
@@ -14057,8 +14067,8 @@ async function cachedFetchModels(baseURL, apiKey) {
14057
14067
  try {
14058
14068
  result = await Promise.race([
14059
14069
  fetchModels(baseURL, apiKey),
14060
- new Promise((resolve18) => {
14061
- const t = setTimeout(() => resolve18(null), MODEL_FETCH_TIMEOUT_MS);
14070
+ new Promise((resolve19) => {
14071
+ const t = setTimeout(() => resolve19(null), MODEL_FETCH_TIMEOUT_MS);
14062
14072
  t.unref?.();
14063
14073
  })
14064
14074
  ]);
@@ -14083,8 +14093,8 @@ async function cachedFetchModelsEnriched(baseURL, apiKey, preferred) {
14083
14093
  if (!target) return r;
14084
14094
  const ctx = await Promise.race([
14085
14095
  fetchModelContext(baseURL, apiKey, target),
14086
- new Promise((resolve18) => {
14087
- const t = setTimeout(() => resolve18(void 0), MODEL_FETCH_TIMEOUT_MS);
14096
+ new Promise((resolve19) => {
14097
+ const t = setTimeout(() => resolve19(void 0), MODEL_FETCH_TIMEOUT_MS);
14088
14098
  t.unref?.();
14089
14099
  })
14090
14100
  ]);
@@ -15278,13 +15288,13 @@ var EVENT_FLUSH_MAX_EVENTS = 60;
15278
15288
  var EVENT_FLUSH_MAX_BYTES = 200 * 1024;
15279
15289
  var LOOP_LAG_WARN_MS = 2e3;
15280
15290
  function withTimeout(p, ms) {
15281
- return new Promise((resolve18, reject) => {
15291
+ return new Promise((resolve19, reject) => {
15282
15292
  const timer = setTimeout(() => reject(new Error(`\u5B50\u6307\u4EE4\u8D85\u65F6\uFF08${ms}ms\uFF09`)), ms);
15283
15293
  timer.unref?.();
15284
15294
  p.then(
15285
15295
  (v) => {
15286
15296
  clearTimeout(timer);
15287
- resolve18(v);
15297
+ resolve19(v);
15288
15298
  },
15289
15299
  (e) => {
15290
15300
  clearTimeout(timer);
@@ -15644,7 +15654,7 @@ var FleetNodeBridge = class {
15644
15654
  label: this.opts.deps.store.loadNodeLabel() ?? void 0,
15645
15655
  platform: process.platform,
15646
15656
  mode: process.env.NODE_MODE ?? "standalone",
15647
- version: "0.2.7",
15657
+ version: "0.2.10",
15648
15658
  ip: primaryIp()
15649
15659
  };
15650
15660
  }
@@ -15699,7 +15709,7 @@ var FleetNodeBridge = class {
15699
15709
  label: this.opts.deps.store.loadNodeLabel() ?? void 0,
15700
15710
  platform: process.platform,
15701
15711
  mode: process.env.NODE_MODE ?? "standalone",
15702
- version: "0.2.7",
15712
+ version: "0.2.10",
15703
15713
  ip: primaryIp(),
15704
15714
  projects,
15705
15715
  totals,
@@ -17228,8 +17238,10 @@ var PLATFORM_NAMES = {
17228
17238
  linux: "linux",
17229
17239
  win32: "windows"
17230
17240
  };
17241
+ var LIBC_VARIANT = "";
17231
17242
  function platformKey(platform = process.platform, arch = process.arch) {
17232
- return `${PLATFORM_NAMES[platform] ?? platform}-${arch}`;
17243
+ const base = `${PLATFORM_NAMES[platform] ?? platform}-${arch}`;
17244
+ return LIBC_VARIANT ? `${base}-${LIBC_VARIANT}` : base;
17233
17245
  }
17234
17246
  var SHA256_HEX = /^[0-9a-f]{64}$/;
17235
17247
  function isRecord(v) {
@@ -17416,10 +17428,12 @@ function selfCheck(binPath, expectedVersion) {
17416
17428
  // src/update/platform.ts
17417
17429
  init_esm_shims();
17418
17430
  import * as fs25 from "fs";
17431
+ import * as os8 from "os";
17419
17432
  import * as path30 from "path";
17433
+ import { spawnSync as spawnSync3 } from "child_process";
17420
17434
  import { createRequire as createRequire3 } from "module";
17421
17435
  function currentVersion() {
17422
- const injected = "0.2.7"?.trim();
17436
+ const injected = "0.2.10"?.trim();
17423
17437
  if (injected) return injected;
17424
17438
  try {
17425
17439
  const req2 = createRequire3(import.meta.url);
@@ -17435,6 +17449,7 @@ function isSeaRuntime() {
17435
17449
  return base !== "node" && base !== "nodejs";
17436
17450
  }
17437
17451
  var DEFAULT_SERVICE_NAME = "zqagent";
17452
+ var DEFAULT_SERVICE_LABEL = "com.zqagent.node";
17438
17453
  function serviceManagerFromCgroup(cgroup, serviceName = DEFAULT_SERVICE_NAME) {
17439
17454
  const unitName = `${serviceName}.service`;
17440
17455
  for (const line of cgroup.split("\n")) {
@@ -17445,7 +17460,46 @@ function serviceManagerFromCgroup(cgroup, serviceName = DEFAULT_SERVICE_NAME) {
17445
17460
  }
17446
17461
  return null;
17447
17462
  }
17463
+ function launchdDomain() {
17464
+ const uid = typeof process.getuid === "function" ? process.getuid() : -1;
17465
+ return uid === 0 ? "system" : `gui/${uid}`;
17466
+ }
17467
+ function launchdLabel() {
17468
+ return process.env.ZQAGENT_SERVICE_LABEL?.trim() || DEFAULT_SERVICE_LABEL;
17469
+ }
17470
+ function launchdPlistPath() {
17471
+ const label2 = launchdLabel();
17472
+ const uid = typeof process.getuid === "function" ? process.getuid() : -1;
17473
+ if (uid === 0) return `/Library/LaunchDaemons/${label2}.plist`;
17474
+ return path30.join(os8.homedir(), "Library", "LaunchAgents", `${label2}.plist`);
17475
+ }
17476
+ function serviceManagerFromLaunchctl(output, pid, execPath, sea = true) {
17477
+ const pidMatch = /^\s*pid = (\d+)\s*$/m.exec(output);
17478
+ if (pidMatch && Number(pidMatch[1]) === pid) return "launchd";
17479
+ const program = /^\s*program = (.+?)\s*$/m.exec(output);
17480
+ if (program) {
17481
+ const shown = program[1].replace(/^"|"$/g, "");
17482
+ if (path30.resolve(shown) === path30.resolve(execPath)) return "launchd";
17483
+ }
17484
+ if (!sea && /^\s*state = /m.test(output)) return "launchd";
17485
+ return null;
17486
+ }
17487
+ function parseLaunchdEnvironment(xml) {
17488
+ const out = {};
17489
+ const marker = xml.indexOf("<key>EnvironmentVariables</key>");
17490
+ if (marker < 0) return out;
17491
+ const open = xml.indexOf("<dict>", marker);
17492
+ if (open < 0) return out;
17493
+ const close = xml.indexOf("</dict>", open);
17494
+ if (close < 0) return out;
17495
+ const body = xml.slice(open + "<dict>".length, close);
17496
+ for (const m of body.matchAll(/<key>([^<]+)<\/key>\s*<string>([^<]*)<\/string>/g)) {
17497
+ out[m[1]] = m[2];
17498
+ }
17499
+ return out;
17500
+ }
17448
17501
  function detectServiceManager() {
17502
+ if (process.platform === "darwin") return detectLaunchd();
17449
17503
  if (process.platform !== "linux") return null;
17450
17504
  const serviceName = process.env.ZQAGENT_SERVICE_NAME?.trim() || DEFAULT_SERVICE_NAME;
17451
17505
  try {
@@ -17457,11 +17511,71 @@ function detectServiceManager() {
17457
17511
  return null;
17458
17512
  }
17459
17513
  }
17514
+ function detectLaunchd() {
17515
+ try {
17516
+ const res = spawnSync3(
17517
+ "launchctl",
17518
+ ["print", `${launchdDomain()}/${launchdLabel()}`],
17519
+ { encoding: "utf8", timeout: 3e3 }
17520
+ );
17521
+ if (res.status !== 0 || !res.stdout) return null;
17522
+ return serviceManagerFromLaunchctl(
17523
+ res.stdout,
17524
+ process.pid,
17525
+ process.execPath,
17526
+ isSeaRuntime()
17527
+ );
17528
+ } catch {
17529
+ return null;
17530
+ }
17531
+ }
17460
17532
  function serviceManager() {
17461
17533
  const v = process.env.ZQAGENT_SERVICE_MANAGER?.trim().toLowerCase();
17462
17534
  if (v === "systemd" || v === "launchd") return v;
17463
17535
  return detectServiceManager();
17464
17536
  }
17537
+ function parseServiceEnvironment(raw) {
17538
+ const out = {};
17539
+ for (const token of raw.trim().split(/\s+/)) {
17540
+ const idx = token.indexOf("=");
17541
+ if (idx > 0) out[token.slice(0, idx)] = token.slice(idx + 1);
17542
+ }
17543
+ return out;
17544
+ }
17545
+ var cachedServiceEnv = null;
17546
+ function readServiceEnvironment() {
17547
+ const serviceName = process.env.ZQAGENT_SERVICE_NAME?.trim() || DEFAULT_SERVICE_NAME;
17548
+ try {
17549
+ const res = spawnSync3(
17550
+ "systemctl",
17551
+ ["show", serviceName, "--property=Environment", "--value", "--no-pager"],
17552
+ { encoding: "utf8", timeout: 3e3 }
17553
+ );
17554
+ if (res.status !== 0 || !res.stdout) return {};
17555
+ return parseServiceEnvironment(res.stdout);
17556
+ } catch {
17557
+ return {};
17558
+ }
17559
+ }
17560
+ function serviceEnvValue(key) {
17561
+ if (process.platform === "darwin") {
17562
+ if (serviceManager() !== "launchd") return void 0;
17563
+ cachedLaunchdEnv ??= readLaunchdEnvironment();
17564
+ return cachedLaunchdEnv[key];
17565
+ }
17566
+ if (process.platform !== "linux") return void 0;
17567
+ if (serviceManager() !== "systemd") return void 0;
17568
+ cachedServiceEnv ??= readServiceEnvironment();
17569
+ return cachedServiceEnv[key];
17570
+ }
17571
+ var cachedLaunchdEnv = null;
17572
+ function readLaunchdEnvironment() {
17573
+ try {
17574
+ return parseLaunchdEnvironment(fs25.readFileSync(launchdPlistPath(), "utf8"));
17575
+ } catch {
17576
+ return {};
17577
+ }
17578
+ }
17465
17579
  function selfUpdateCapability(hasPublicKey) {
17466
17580
  if (!isSeaRuntime()) {
17467
17581
  return {
@@ -17614,7 +17728,9 @@ function readRollbackTarget(dataDir) {
17614
17728
  var DEFAULT_BASE = "https://agent.cd-zq.com/downloads/zqagent";
17615
17729
  function env(key) {
17616
17730
  const v = process.env[key]?.trim();
17617
- return v ? v : void 0;
17731
+ if (v) return v;
17732
+ const fromService = serviceEnvValue(key)?.trim();
17733
+ return fromService ? fromService : void 0;
17618
17734
  }
17619
17735
  function num(key, fallback) {
17620
17736
  const n = Number(env(key));
@@ -17651,7 +17767,7 @@ var UpdateController = class {
17651
17767
  return parsePublicKey(env("ZQAGENT_UPDATE_PUBKEY") ?? "");
17652
17768
  }
17653
17769
  get autoUpdateOff() {
17654
- return process.env.ZQAGENT_AUTO_UPDATE?.trim() === "0";
17770
+ return env("ZQAGENT_AUTO_UPDATE") === "0";
17655
17771
  }
17656
17772
  get enabled() {
17657
17773
  return !this.autoUpdateOff && selfUpdateCapability(Boolean(this.publicKey)).ok;
@@ -17844,11 +17960,11 @@ var UpdateController = class {
17844
17960
  const minUptime = num("ZQAGENT_UPDATE_MIN_UPTIME_MS", 10 * 60 * 1e3);
17845
17961
  const idleMs = num("ZQAGENT_UPDATE_IDLE_MS", 60 * 1e3);
17846
17962
  let idleSince = null;
17847
- return new Promise((resolve18) => {
17963
+ return new Promise((resolve19) => {
17848
17964
  const timer = setInterval(() => {
17849
17965
  if (this.stopped) {
17850
17966
  clearInterval(timer);
17851
- resolve18(false);
17967
+ resolve19(false);
17852
17968
  return;
17853
17969
  }
17854
17970
  if (Date.now() - this.startedAt < minUptime || !this.opts.isIdle()) {
@@ -17858,7 +17974,7 @@ var UpdateController = class {
17858
17974
  idleSince ??= Date.now();
17859
17975
  if (Date.now() - idleSince >= idleMs) {
17860
17976
  clearInterval(timer);
17861
- resolve18(true);
17977
+ resolve19(true);
17862
17978
  }
17863
17979
  }, 1e3);
17864
17980
  timer.unref();
@@ -18039,6 +18155,46 @@ function exitWhenOrphaned() {
18039
18155
  }, 1500);
18040
18156
  timer.unref();
18041
18157
  }
18158
+ var PORT_FALLBACK_LIMIT = 20;
18159
+ function listenWithPortFallback(server, startPort, host, dataDir, limit = PORT_FALLBACK_LIMIT) {
18160
+ return new Promise((resolve19, reject) => {
18161
+ let attempts = 0;
18162
+ const tryListen = (port) => {
18163
+ server.removeAllListeners("listening");
18164
+ const onError = (err) => {
18165
+ if (err.code === "EADDRINUSE" && attempts < limit) {
18166
+ attempts += 1;
18167
+ const next = port + 1;
18168
+ console.warn(`[server] \u7AEF\u53E3 ${port} \u5DF2\u88AB\u5360\u7528\uFF08EADDRINUSE\uFF09\uFF0C\u5C1D\u8BD5 ${next} \u2026`);
18169
+ tryListen(next);
18170
+ return;
18171
+ }
18172
+ server.removeListener("error", onError);
18173
+ console.error(
18174
+ `[server] \u65E0\u6CD5\u76D1\u542C ${host}:${port}\uFF1A${err.message}` + (err.code === "EADDRINUSE" ? `\uFF08\u5DF2\u5C1D\u8BD5 ${attempts + 1} \u4E2A\u7AEF\u53E3\u5747\u88AB\u5360\u7528\uFF09` : "")
18175
+ );
18176
+ reject(err);
18177
+ };
18178
+ server.once("error", onError);
18179
+ server.listen(port, host, () => {
18180
+ server.removeListener("error", onError);
18181
+ const addr = server.address();
18182
+ const actualPort = typeof addr === "object" && addr !== null ? addr.port : port;
18183
+ if (actualPort !== startPort) {
18184
+ console.warn(`[server] \u5DF2\u6539\u7528\u7AEF\u53E3 ${actualPort}\uFF08\u539F\u5B9A ${startPort} \u88AB\u5360\u7528\uFF09`);
18185
+ }
18186
+ try {
18187
+ fs29.mkdirSync(dataDir, { recursive: true });
18188
+ fs29.writeFileSync(path34.join(dataDir, "server-port"), `${actualPort}
18189
+ `);
18190
+ } catch {
18191
+ }
18192
+ resolve19(actualPort);
18193
+ });
18194
+ };
18195
+ tryListen(startPort);
18196
+ });
18197
+ }
18042
18198
  function startServer(opts = {}) {
18043
18199
  const dataDir = path34.resolve(opts.dataDir ?? env2("DATA_DIR") ?? DEFAULT_DATA_DIR);
18044
18200
  const port = opts.port ?? Number(env2("PORT") ?? 8787);
@@ -18264,11 +18420,11 @@ function startServer(opts = {}) {
18264
18420
  server.timeout = 0;
18265
18421
  server.keepAliveTimeout = 65e3;
18266
18422
  server.headersTimeout = 66e3;
18267
- const ready = new Promise((resolve18) => {
18268
- server.listen(port, host, () => {
18423
+ const ready = new Promise((resolve19, reject) => {
18424
+ listenWithPortFallback(server, port, host, dataDir).then((actualPort) => {
18269
18425
  const info = {
18270
18426
  host,
18271
- port,
18427
+ port: actualPort,
18272
18428
  dataDir,
18273
18429
  adminKey,
18274
18430
  fleetNodeId: fleet ? fleet.getNodeId() : void 0,
@@ -18281,8 +18437,8 @@ function startServer(opts = {}) {
18281
18437
  printReady(info, qq);
18282
18438
  }
18283
18439
  updater?.start();
18284
- resolve18(info);
18285
- });
18440
+ resolve19(info);
18441
+ }, reject);
18286
18442
  });
18287
18443
  return {
18288
18444
  store,
@@ -18418,7 +18574,7 @@ async function runWizard(rl, store, opts) {
18418
18574
  }
18419
18575
  async function askHidden(rl, prompt) {
18420
18576
  if (!process.stdin.isTTY) return (await rl.question(prompt)).trim();
18421
- return new Promise((resolve18) => {
18577
+ return new Promise((resolve19) => {
18422
18578
  const saved = process.stdin.listeners("data");
18423
18579
  process.stdin.removeAllListeners("data");
18424
18580
  cliWrite(prompt);
@@ -18440,13 +18596,13 @@ async function askHidden(rl, prompt) {
18440
18596
  if (ch === "\r" || ch === "\n") {
18441
18597
  cleanup();
18442
18598
  cliWrite("\n");
18443
- resolve18(buf);
18599
+ resolve19(buf);
18444
18600
  return;
18445
18601
  }
18446
18602
  if (ch === "") {
18447
18603
  cleanup();
18448
18604
  cliWrite("\n");
18449
- resolve18("");
18605
+ resolve19("");
18450
18606
  return;
18451
18607
  }
18452
18608
  if (ch === "\x7F" || ch === "\b") {