@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.
@@ -5164,10 +5164,10 @@ var OpenAIProvider = class {
5164
5164
  let timer;
5165
5165
  try {
5166
5166
  for (; ; ) {
5167
- const idle = new Promise((resolve18) => {
5167
+ const idle = new Promise((resolve19) => {
5168
5168
  timer = setTimeout(() => {
5169
5169
  onIdle();
5170
- resolve18({ timedOut: true });
5170
+ resolve19({ timedOut: true });
5171
5171
  }, idleMs);
5172
5172
  });
5173
5173
  const next = iter.next();
@@ -5795,12 +5795,12 @@ function makeSink(maxBuffer) {
5795
5795
  };
5796
5796
  }
5797
5797
  function execAsync(file, argv, opts = {}) {
5798
- return new Promise((resolve18) => {
5798
+ return new Promise((resolve19) => {
5799
5799
  const maxBuffer = opts.maxBuffer ?? DEFAULT_MAX_BUFFER;
5800
5800
  const out = makeSink(maxBuffer);
5801
5801
  const err = makeSink(maxBuffer);
5802
5802
  if (opts.signal?.aborted) {
5803
- resolve18({
5803
+ resolve19({
5804
5804
  status: null,
5805
5805
  stdout: Buffer.alloc(0),
5806
5806
  stderr: Buffer.alloc(0),
@@ -5821,7 +5821,7 @@ function execAsync(file, argv, opts = {}) {
5821
5821
  windowsHide: true
5822
5822
  });
5823
5823
  } catch (e) {
5824
- resolve18({
5824
+ resolve19({
5825
5825
  status: null,
5826
5826
  stdout: Buffer.alloc(0),
5827
5827
  stderr: Buffer.alloc(0),
@@ -5858,7 +5858,7 @@ function execAsync(file, argv, opts = {}) {
5858
5858
  };
5859
5859
  if (aborted) result.aborted = true;
5860
5860
  if (spawnError) result.error = spawnError;
5861
- resolve18(result);
5861
+ resolve19(result);
5862
5862
  };
5863
5863
  const killAndSettle = () => {
5864
5864
  killTree(child.pid);
@@ -9857,11 +9857,11 @@ function isAffirmative(answer) {
9857
9857
  return /^(yes|approve|同意|批准|允许|确定|可以|好的|确认)/.test(a);
9858
9858
  }
9859
9859
  function defer() {
9860
- let resolve18;
9860
+ let resolve19;
9861
9861
  const promise = new Promise((r) => {
9862
- resolve18 = r;
9862
+ resolve19 = r;
9863
9863
  });
9864
- return { promise, resolve: resolve18 };
9864
+ return { promise, resolve: resolve19 };
9865
9865
  }
9866
9866
  var SessionManager = class {
9867
9867
  constructor(store, approvalTimeoutMs = APPROVAL_TIMEOUT_MS, opts = {}) {
@@ -10433,11 +10433,11 @@ data: ${JSON.stringify({ sessionId, seq: entry.seq, ts: entry.ts, data: entry.da
10433
10433
  status: "pending",
10434
10434
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
10435
10435
  };
10436
- const { promise, resolve: resolve18 } = defer();
10436
+ const { promise, resolve: resolve19 } = defer();
10437
10437
  const timer = setTimeout(() => {
10438
10438
  this._recycleApproval(rt, id);
10439
10439
  }, this.approvalTimeoutMs);
10440
- rt.pendingApprovals.set(id, { promise, resolve: resolve18, record, timer });
10440
+ rt.pendingApprovals.set(id, { promise, resolve: resolve19, record, timer });
10441
10441
  rt.approvals.set(id, record);
10442
10442
  this._setStatus(rt, "waiting_approval");
10443
10443
  this._persist(rt);
@@ -10515,11 +10515,11 @@ data: ${JSON.stringify({ sessionId, seq: entry.seq, ts: entry.ts, data: entry.da
10515
10515
  status: "pending",
10516
10516
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
10517
10517
  };
10518
- const { promise, resolve: resolve18 } = defer();
10518
+ const { promise, resolve: resolve19 } = defer();
10519
10519
  const timer = setTimeout(() => {
10520
10520
  this._recycleQuestion(rt, qid);
10521
10521
  }, this.approvalTimeoutMs);
10522
- rt.pendingQuestions.set(qid, { promise, resolve: resolve18, record, timer });
10522
+ rt.pendingQuestions.set(qid, { promise, resolve: resolve19, record, timer });
10523
10523
  rt.questions.set(qid, record);
10524
10524
  this._setStatus(rt, "waiting_question");
10525
10525
  this._persist(rt);
@@ -10828,7 +10828,7 @@ data: ${JSON.stringify(entry.data)}
10828
10828
  if (rt.mcpReady) {
10829
10829
  await Promise.race([
10830
10830
  rt.mcpReady,
10831
- new Promise((resolve18) => setTimeout(resolve18, 15e3))
10831
+ new Promise((resolve19) => setTimeout(resolve19, 15e3))
10832
10832
  ]).catch(() => void 0);
10833
10833
  }
10834
10834
  for await (const event of gen) {
@@ -11413,7 +11413,7 @@ function buildNodeInfo(store, opts) {
11413
11413
  nodeId: opts.nodeId ?? ensureNodeId(store),
11414
11414
  platform: process.platform,
11415
11415
  mode: process.env.NODE_MODE ?? "standalone",
11416
- version: "0.2.7",
11416
+ version: "0.2.10",
11417
11417
  admin: opts.admin,
11418
11418
  projects: opts.projects
11419
11419
  };
@@ -12406,7 +12406,7 @@ function buildNodeHost(store, manager, diskPath) {
12406
12406
  arch: process.arch,
12407
12407
  release: os6.release(),
12408
12408
  uptimeSec: Math.round(os6.uptime()),
12409
- version: "0.2.7",
12409
+ version: "0.2.10",
12410
12410
  mode: process.env.NODE_MODE ?? "standalone",
12411
12411
  cpu: {
12412
12412
  count: cpus2.length,
@@ -12450,7 +12450,7 @@ function saveNotifications(tenant, secretBox, notifications) {
12450
12450
  var API_PREFIX = "/api/v1";
12451
12451
  var MAX_BODY_BYTES = 10 * 1024 * 1024;
12452
12452
  function readBody(req2) {
12453
- return new Promise((resolve18, reject) => {
12453
+ return new Promise((resolve19, reject) => {
12454
12454
  const chunks = [];
12455
12455
  let size = 0;
12456
12456
  req2.on("data", (c) => {
@@ -12463,9 +12463,9 @@ function readBody(req2) {
12463
12463
  chunks.push(c);
12464
12464
  });
12465
12465
  req2.on("end", () => {
12466
- if (chunks.length === 0) return resolve18(void 0);
12466
+ if (chunks.length === 0) return resolve19(void 0);
12467
12467
  try {
12468
- resolve18(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
12468
+ resolve19(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
12469
12469
  } catch {
12470
12470
  reject(new ApiError(400, "bad_request", "\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5 JSON"));
12471
12471
  }
@@ -12981,8 +12981,18 @@ function createApp(store, manager, opts = {}) {
12981
12981
  applyProvidersPatch(tenant, raw);
12982
12982
  if (typeof raw.workspaceRoot === "string") {
12983
12983
  const ws = raw.workspaceRoot.trim();
12984
- if (ws) tenant.workspaceRoot = path25.resolve(ws);
12985
- else delete tenant.workspaceRoot;
12984
+ const next = ws ? path25.resolve(ws) : void 0;
12985
+ if (tenant.workspaceRoot) {
12986
+ if (next !== tenant.workspaceRoot) {
12987
+ throw new ApiError(
12988
+ 409,
12989
+ "workspace_locked",
12990
+ "\u8BE5\u9879\u76EE\u5DF2\u8BBE\u7F6E\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u4E0D\u80FD\u518D\u4FEE\u6539"
12991
+ );
12992
+ }
12993
+ } else if (next) {
12994
+ tenant.workspaceRoot = next;
12995
+ }
12986
12996
  }
12987
12997
  if (typeof raw.name === "string" && raw.name.trim()) {
12988
12998
  tenant.name = raw.name.trim();
@@ -13958,7 +13968,7 @@ function createApp(store, manager, opts = {}) {
13958
13968
  json(res, 200, {
13959
13969
  status: "ok",
13960
13970
  // 版本让运维/探针能确认线上跑的是哪个构建(更新与回滚据此判断)
13961
- version: "0.2.7",
13971
+ version: "0.2.10",
13962
13972
  features: { mcp: hasServerMcpConfig() }
13963
13973
  });
13964
13974
  return;
@@ -14074,8 +14084,8 @@ async function cachedFetchModels(baseURL, apiKey) {
14074
14084
  try {
14075
14085
  result = await Promise.race([
14076
14086
  fetchModels(baseURL, apiKey),
14077
- new Promise((resolve18) => {
14078
- const t = setTimeout(() => resolve18(null), MODEL_FETCH_TIMEOUT_MS);
14087
+ new Promise((resolve19) => {
14088
+ const t = setTimeout(() => resolve19(null), MODEL_FETCH_TIMEOUT_MS);
14079
14089
  t.unref?.();
14080
14090
  })
14081
14091
  ]);
@@ -14100,8 +14110,8 @@ async function cachedFetchModelsEnriched(baseURL, apiKey, preferred) {
14100
14110
  if (!target) return r;
14101
14111
  const ctx = await Promise.race([
14102
14112
  fetchModelContext(baseURL, apiKey, target),
14103
- new Promise((resolve18) => {
14104
- const t = setTimeout(() => resolve18(void 0), MODEL_FETCH_TIMEOUT_MS);
14113
+ new Promise((resolve19) => {
14114
+ const t = setTimeout(() => resolve19(void 0), MODEL_FETCH_TIMEOUT_MS);
14105
14115
  t.unref?.();
14106
14116
  })
14107
14117
  ]);
@@ -15295,13 +15305,13 @@ var EVENT_FLUSH_MAX_EVENTS = 60;
15295
15305
  var EVENT_FLUSH_MAX_BYTES = 200 * 1024;
15296
15306
  var LOOP_LAG_WARN_MS = 2e3;
15297
15307
  function withTimeout(p, ms) {
15298
- return new Promise((resolve18, reject) => {
15308
+ return new Promise((resolve19, reject) => {
15299
15309
  const timer = setTimeout(() => reject(new Error(`\u5B50\u6307\u4EE4\u8D85\u65F6\uFF08${ms}ms\uFF09`)), ms);
15300
15310
  timer.unref?.();
15301
15311
  p.then(
15302
15312
  (v) => {
15303
15313
  clearTimeout(timer);
15304
- resolve18(v);
15314
+ resolve19(v);
15305
15315
  },
15306
15316
  (e) => {
15307
15317
  clearTimeout(timer);
@@ -15661,7 +15671,7 @@ var FleetNodeBridge = class {
15661
15671
  label: this.opts.deps.store.loadNodeLabel() ?? void 0,
15662
15672
  platform: process.platform,
15663
15673
  mode: process.env.NODE_MODE ?? "standalone",
15664
- version: "0.2.7",
15674
+ version: "0.2.10",
15665
15675
  ip: primaryIp()
15666
15676
  };
15667
15677
  }
@@ -15716,7 +15726,7 @@ var FleetNodeBridge = class {
15716
15726
  label: this.opts.deps.store.loadNodeLabel() ?? void 0,
15717
15727
  platform: process.platform,
15718
15728
  mode: process.env.NODE_MODE ?? "standalone",
15719
- version: "0.2.7",
15729
+ version: "0.2.10",
15720
15730
  ip: primaryIp(),
15721
15731
  projects,
15722
15732
  totals,
@@ -17245,8 +17255,10 @@ var PLATFORM_NAMES = {
17245
17255
  linux: "linux",
17246
17256
  win32: "windows"
17247
17257
  };
17258
+ var LIBC_VARIANT = "";
17248
17259
  function platformKey(platform = process.platform, arch = process.arch) {
17249
- return `${PLATFORM_NAMES[platform] ?? platform}-${arch}`;
17260
+ const base = `${PLATFORM_NAMES[platform] ?? platform}-${arch}`;
17261
+ return LIBC_VARIANT ? `${base}-${LIBC_VARIANT}` : base;
17250
17262
  }
17251
17263
  var SHA256_HEX = /^[0-9a-f]{64}$/;
17252
17264
  function isRecord(v) {
@@ -17433,10 +17445,12 @@ function selfCheck(binPath, expectedVersion) {
17433
17445
  // src/update/platform.ts
17434
17446
  init_cjs_shims();
17435
17447
  var fs25 = __toESM(require("fs"), 1);
17448
+ var os8 = __toESM(require("os"), 1);
17436
17449
  var path29 = __toESM(require("path"), 1);
17450
+ var import_node_child_process5 = require("child_process");
17437
17451
  var import_node_module3 = require("module");
17438
17452
  function currentVersion() {
17439
- const injected = "0.2.7"?.trim();
17453
+ const injected = "0.2.10"?.trim();
17440
17454
  if (injected) return injected;
17441
17455
  try {
17442
17456
  const req2 = (0, import_node_module3.createRequire)(importMetaUrl);
@@ -17452,6 +17466,7 @@ function isSeaRuntime() {
17452
17466
  return base !== "node" && base !== "nodejs";
17453
17467
  }
17454
17468
  var DEFAULT_SERVICE_NAME = "zqagent";
17469
+ var DEFAULT_SERVICE_LABEL = "com.zqagent.node";
17455
17470
  function serviceManagerFromCgroup(cgroup, serviceName = DEFAULT_SERVICE_NAME) {
17456
17471
  const unitName = `${serviceName}.service`;
17457
17472
  for (const line of cgroup.split("\n")) {
@@ -17462,7 +17477,46 @@ function serviceManagerFromCgroup(cgroup, serviceName = DEFAULT_SERVICE_NAME) {
17462
17477
  }
17463
17478
  return null;
17464
17479
  }
17480
+ function launchdDomain() {
17481
+ const uid = typeof process.getuid === "function" ? process.getuid() : -1;
17482
+ return uid === 0 ? "system" : `gui/${uid}`;
17483
+ }
17484
+ function launchdLabel() {
17485
+ return process.env.ZQAGENT_SERVICE_LABEL?.trim() || DEFAULT_SERVICE_LABEL;
17486
+ }
17487
+ function launchdPlistPath() {
17488
+ const label2 = launchdLabel();
17489
+ const uid = typeof process.getuid === "function" ? process.getuid() : -1;
17490
+ if (uid === 0) return `/Library/LaunchDaemons/${label2}.plist`;
17491
+ return path29.join(os8.homedir(), "Library", "LaunchAgents", `${label2}.plist`);
17492
+ }
17493
+ function serviceManagerFromLaunchctl(output, pid, execPath, sea = true) {
17494
+ const pidMatch = /^\s*pid = (\d+)\s*$/m.exec(output);
17495
+ if (pidMatch && Number(pidMatch[1]) === pid) return "launchd";
17496
+ const program = /^\s*program = (.+?)\s*$/m.exec(output);
17497
+ if (program) {
17498
+ const shown = program[1].replace(/^"|"$/g, "");
17499
+ if (path29.resolve(shown) === path29.resolve(execPath)) return "launchd";
17500
+ }
17501
+ if (!sea && /^\s*state = /m.test(output)) return "launchd";
17502
+ return null;
17503
+ }
17504
+ function parseLaunchdEnvironment(xml) {
17505
+ const out = {};
17506
+ const marker = xml.indexOf("<key>EnvironmentVariables</key>");
17507
+ if (marker < 0) return out;
17508
+ const open = xml.indexOf("<dict>", marker);
17509
+ if (open < 0) return out;
17510
+ const close = xml.indexOf("</dict>", open);
17511
+ if (close < 0) return out;
17512
+ const body = xml.slice(open + "<dict>".length, close);
17513
+ for (const m of body.matchAll(/<key>([^<]+)<\/key>\s*<string>([^<]*)<\/string>/g)) {
17514
+ out[m[1]] = m[2];
17515
+ }
17516
+ return out;
17517
+ }
17465
17518
  function detectServiceManager() {
17519
+ if (process.platform === "darwin") return detectLaunchd();
17466
17520
  if (process.platform !== "linux") return null;
17467
17521
  const serviceName = process.env.ZQAGENT_SERVICE_NAME?.trim() || DEFAULT_SERVICE_NAME;
17468
17522
  try {
@@ -17474,11 +17528,71 @@ function detectServiceManager() {
17474
17528
  return null;
17475
17529
  }
17476
17530
  }
17531
+ function detectLaunchd() {
17532
+ try {
17533
+ const res = (0, import_node_child_process5.spawnSync)(
17534
+ "launchctl",
17535
+ ["print", `${launchdDomain()}/${launchdLabel()}`],
17536
+ { encoding: "utf8", timeout: 3e3 }
17537
+ );
17538
+ if (res.status !== 0 || !res.stdout) return null;
17539
+ return serviceManagerFromLaunchctl(
17540
+ res.stdout,
17541
+ process.pid,
17542
+ process.execPath,
17543
+ isSeaRuntime()
17544
+ );
17545
+ } catch {
17546
+ return null;
17547
+ }
17548
+ }
17477
17549
  function serviceManager() {
17478
17550
  const v = process.env.ZQAGENT_SERVICE_MANAGER?.trim().toLowerCase();
17479
17551
  if (v === "systemd" || v === "launchd") return v;
17480
17552
  return detectServiceManager();
17481
17553
  }
17554
+ function parseServiceEnvironment(raw) {
17555
+ const out = {};
17556
+ for (const token of raw.trim().split(/\s+/)) {
17557
+ const idx = token.indexOf("=");
17558
+ if (idx > 0) out[token.slice(0, idx)] = token.slice(idx + 1);
17559
+ }
17560
+ return out;
17561
+ }
17562
+ var cachedServiceEnv = null;
17563
+ function readServiceEnvironment() {
17564
+ const serviceName = process.env.ZQAGENT_SERVICE_NAME?.trim() || DEFAULT_SERVICE_NAME;
17565
+ try {
17566
+ const res = (0, import_node_child_process5.spawnSync)(
17567
+ "systemctl",
17568
+ ["show", serviceName, "--property=Environment", "--value", "--no-pager"],
17569
+ { encoding: "utf8", timeout: 3e3 }
17570
+ );
17571
+ if (res.status !== 0 || !res.stdout) return {};
17572
+ return parseServiceEnvironment(res.stdout);
17573
+ } catch {
17574
+ return {};
17575
+ }
17576
+ }
17577
+ function serviceEnvValue(key) {
17578
+ if (process.platform === "darwin") {
17579
+ if (serviceManager() !== "launchd") return void 0;
17580
+ cachedLaunchdEnv ??= readLaunchdEnvironment();
17581
+ return cachedLaunchdEnv[key];
17582
+ }
17583
+ if (process.platform !== "linux") return void 0;
17584
+ if (serviceManager() !== "systemd") return void 0;
17585
+ cachedServiceEnv ??= readServiceEnvironment();
17586
+ return cachedServiceEnv[key];
17587
+ }
17588
+ var cachedLaunchdEnv = null;
17589
+ function readLaunchdEnvironment() {
17590
+ try {
17591
+ return parseLaunchdEnvironment(fs25.readFileSync(launchdPlistPath(), "utf8"));
17592
+ } catch {
17593
+ return {};
17594
+ }
17595
+ }
17482
17596
  function selfUpdateCapability(hasPublicKey) {
17483
17597
  if (!isSeaRuntime()) {
17484
17598
  return {
@@ -17631,7 +17745,9 @@ function readRollbackTarget(dataDir) {
17631
17745
  var DEFAULT_BASE = "https://agent.cd-zq.com/downloads/zqagent";
17632
17746
  function env(key) {
17633
17747
  const v = process.env[key]?.trim();
17634
- return v ? v : void 0;
17748
+ if (v) return v;
17749
+ const fromService = serviceEnvValue(key)?.trim();
17750
+ return fromService ? fromService : void 0;
17635
17751
  }
17636
17752
  function num(key, fallback) {
17637
17753
  const n = Number(env(key));
@@ -17668,7 +17784,7 @@ var UpdateController = class {
17668
17784
  return parsePublicKey(env("ZQAGENT_UPDATE_PUBKEY") ?? "");
17669
17785
  }
17670
17786
  get autoUpdateOff() {
17671
- return process.env.ZQAGENT_AUTO_UPDATE?.trim() === "0";
17787
+ return env("ZQAGENT_AUTO_UPDATE") === "0";
17672
17788
  }
17673
17789
  get enabled() {
17674
17790
  return !this.autoUpdateOff && selfUpdateCapability(Boolean(this.publicKey)).ok;
@@ -17861,11 +17977,11 @@ var UpdateController = class {
17861
17977
  const minUptime = num("ZQAGENT_UPDATE_MIN_UPTIME_MS", 10 * 60 * 1e3);
17862
17978
  const idleMs = num("ZQAGENT_UPDATE_IDLE_MS", 60 * 1e3);
17863
17979
  let idleSince = null;
17864
- return new Promise((resolve18) => {
17980
+ return new Promise((resolve19) => {
17865
17981
  const timer = setInterval(() => {
17866
17982
  if (this.stopped) {
17867
17983
  clearInterval(timer);
17868
- resolve18(false);
17984
+ resolve19(false);
17869
17985
  return;
17870
17986
  }
17871
17987
  if (Date.now() - this.startedAt < minUptime || !this.opts.isIdle()) {
@@ -17875,7 +17991,7 @@ var UpdateController = class {
17875
17991
  idleSince ??= Date.now();
17876
17992
  if (Date.now() - idleSince >= idleMs) {
17877
17993
  clearInterval(timer);
17878
- resolve18(true);
17994
+ resolve19(true);
17879
17995
  }
17880
17996
  }, 1e3);
17881
17997
  timer.unref();
@@ -18056,6 +18172,46 @@ function exitWhenOrphaned() {
18056
18172
  }, 1500);
18057
18173
  timer.unref();
18058
18174
  }
18175
+ var PORT_FALLBACK_LIMIT = 20;
18176
+ function listenWithPortFallback(server, startPort, host, dataDir, limit = PORT_FALLBACK_LIMIT) {
18177
+ return new Promise((resolve19, reject) => {
18178
+ let attempts = 0;
18179
+ const tryListen = (port) => {
18180
+ server.removeAllListeners("listening");
18181
+ const onError = (err) => {
18182
+ if (err.code === "EADDRINUSE" && attempts < limit) {
18183
+ attempts += 1;
18184
+ const next = port + 1;
18185
+ console.warn(`[server] \u7AEF\u53E3 ${port} \u5DF2\u88AB\u5360\u7528\uFF08EADDRINUSE\uFF09\uFF0C\u5C1D\u8BD5 ${next} \u2026`);
18186
+ tryListen(next);
18187
+ return;
18188
+ }
18189
+ server.removeListener("error", onError);
18190
+ console.error(
18191
+ `[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` : "")
18192
+ );
18193
+ reject(err);
18194
+ };
18195
+ server.once("error", onError);
18196
+ server.listen(port, host, () => {
18197
+ server.removeListener("error", onError);
18198
+ const addr = server.address();
18199
+ const actualPort = typeof addr === "object" && addr !== null ? addr.port : port;
18200
+ if (actualPort !== startPort) {
18201
+ console.warn(`[server] \u5DF2\u6539\u7528\u7AEF\u53E3 ${actualPort}\uFF08\u539F\u5B9A ${startPort} \u88AB\u5360\u7528\uFF09`);
18202
+ }
18203
+ try {
18204
+ fs29.mkdirSync(dataDir, { recursive: true });
18205
+ fs29.writeFileSync(path33.join(dataDir, "server-port"), `${actualPort}
18206
+ `);
18207
+ } catch {
18208
+ }
18209
+ resolve19(actualPort);
18210
+ });
18211
+ };
18212
+ tryListen(startPort);
18213
+ });
18214
+ }
18059
18215
  function startServer(opts = {}) {
18060
18216
  const dataDir = path33.resolve(opts.dataDir ?? env2("DATA_DIR") ?? DEFAULT_DATA_DIR);
18061
18217
  const port = opts.port ?? Number(env2("PORT") ?? 8787);
@@ -18281,11 +18437,11 @@ function startServer(opts = {}) {
18281
18437
  server.timeout = 0;
18282
18438
  server.keepAliveTimeout = 65e3;
18283
18439
  server.headersTimeout = 66e3;
18284
- const ready = new Promise((resolve18) => {
18285
- server.listen(port, host, () => {
18440
+ const ready = new Promise((resolve19, reject) => {
18441
+ listenWithPortFallback(server, port, host, dataDir).then((actualPort) => {
18286
18442
  const info = {
18287
18443
  host,
18288
- port,
18444
+ port: actualPort,
18289
18445
  dataDir,
18290
18446
  adminKey,
18291
18447
  fleetNodeId: fleet ? fleet.getNodeId() : void 0,
@@ -18298,8 +18454,8 @@ function startServer(opts = {}) {
18298
18454
  printReady(info, qq);
18299
18455
  }
18300
18456
  updater?.start();
18301
- resolve18(info);
18302
- });
18457
+ resolve19(info);
18458
+ }, reject);
18303
18459
  });
18304
18460
  return {
18305
18461
  store,
@@ -18435,7 +18591,7 @@ async function runWizard(rl, store, opts) {
18435
18591
  }
18436
18592
  async function askHidden(rl, prompt) {
18437
18593
  if (!process.stdin.isTTY) return (await rl.question(prompt)).trim();
18438
- return new Promise((resolve18) => {
18594
+ return new Promise((resolve19) => {
18439
18595
  const saved = process.stdin.listeners("data");
18440
18596
  process.stdin.removeAllListeners("data");
18441
18597
  cliWrite(prompt);
@@ -18457,13 +18613,13 @@ async function askHidden(rl, prompt) {
18457
18613
  if (ch === "\r" || ch === "\n") {
18458
18614
  cleanup();
18459
18615
  cliWrite("\n");
18460
- resolve18(buf);
18616
+ resolve19(buf);
18461
18617
  return;
18462
18618
  }
18463
18619
  if (ch === "") {
18464
18620
  cleanup();
18465
18621
  cliWrite("\n");
18466
- resolve18("");
18622
+ resolve19("");
18467
18623
  return;
18468
18624
  }
18469
18625
  if (ch === "\x7F" || ch === "\b") {