@buildautomaton/cli 0.1.79 → 0.1.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -973,8 +973,8 @@ var require_command = __commonJS({
973
973
  "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js"(exports) {
974
974
  var EventEmitter2 = __require("node:events").EventEmitter;
975
975
  var childProcess2 = __require("node:child_process");
976
- var path86 = __require("node:path");
977
- var fs65 = __require("node:fs");
976
+ var path88 = __require("node:path");
977
+ var fs67 = __require("node:fs");
978
978
  var process8 = __require("node:process");
979
979
  var { Argument: Argument2, humanReadableArgName } = require_argument();
980
980
  var { CommanderError: CommanderError2 } = require_error();
@@ -1906,11 +1906,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
1906
1906
  let launchWithNode = false;
1907
1907
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1908
1908
  function findFile(baseDir, baseName) {
1909
- const localBin = path86.resolve(baseDir, baseName);
1910
- if (fs65.existsSync(localBin)) return localBin;
1911
- if (sourceExt.includes(path86.extname(baseName))) return void 0;
1909
+ const localBin = path88.resolve(baseDir, baseName);
1910
+ if (fs67.existsSync(localBin)) return localBin;
1911
+ if (sourceExt.includes(path88.extname(baseName))) return void 0;
1912
1912
  const foundExt = sourceExt.find(
1913
- (ext) => fs65.existsSync(`${localBin}${ext}`)
1913
+ (ext) => fs67.existsSync(`${localBin}${ext}`)
1914
1914
  );
1915
1915
  if (foundExt) return `${localBin}${foundExt}`;
1916
1916
  return void 0;
@@ -1922,21 +1922,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
1922
1922
  if (this._scriptPath) {
1923
1923
  let resolvedScriptPath;
1924
1924
  try {
1925
- resolvedScriptPath = fs65.realpathSync(this._scriptPath);
1925
+ resolvedScriptPath = fs67.realpathSync(this._scriptPath);
1926
1926
  } catch (err) {
1927
1927
  resolvedScriptPath = this._scriptPath;
1928
1928
  }
1929
- executableDir = path86.resolve(
1930
- path86.dirname(resolvedScriptPath),
1929
+ executableDir = path88.resolve(
1930
+ path88.dirname(resolvedScriptPath),
1931
1931
  executableDir
1932
1932
  );
1933
1933
  }
1934
1934
  if (executableDir) {
1935
1935
  let localFile = findFile(executableDir, executableFile);
1936
1936
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
1937
- const legacyName = path86.basename(
1937
+ const legacyName = path88.basename(
1938
1938
  this._scriptPath,
1939
- path86.extname(this._scriptPath)
1939
+ path88.extname(this._scriptPath)
1940
1940
  );
1941
1941
  if (legacyName !== this._name) {
1942
1942
  localFile = findFile(
@@ -1947,7 +1947,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1947
1947
  }
1948
1948
  executableFile = localFile || executableFile;
1949
1949
  }
1950
- launchWithNode = sourceExt.includes(path86.extname(executableFile));
1950
+ launchWithNode = sourceExt.includes(path88.extname(executableFile));
1951
1951
  let proc;
1952
1952
  if (process8.platform !== "win32") {
1953
1953
  if (launchWithNode) {
@@ -2787,7 +2787,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2787
2787
  * @return {Command}
2788
2788
  */
2789
2789
  nameFromFilename(filename) {
2790
- this._name = path86.basename(filename, path86.extname(filename));
2790
+ this._name = path88.basename(filename, path88.extname(filename));
2791
2791
  return this;
2792
2792
  }
2793
2793
  /**
@@ -2801,9 +2801,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2801
2801
  * @param {string} [path]
2802
2802
  * @return {(string|null|Command)}
2803
2803
  */
2804
- executableDir(path87) {
2805
- if (path87 === void 0) return this._executableDir;
2806
- this._executableDir = path87;
2804
+ executableDir(path89) {
2805
+ if (path89 === void 0) return this._executableDir;
2806
+ this._executableDir = path89;
2807
2807
  return this;
2808
2808
  }
2809
2809
  /**
@@ -7004,7 +7004,7 @@ var init_activity_tracker = __esm({
7004
7004
 
7005
7005
  // src/runtime/yield-to-event-loop.ts
7006
7006
  function yieldToEventLoop() {
7007
- return new Promise((resolve37) => setImmediate(resolve37));
7007
+ return new Promise((resolve38) => setImmediate(resolve38));
7008
7008
  }
7009
7009
  var init_yield_to_event_loop = __esm({
7010
7010
  "src/runtime/yield-to-event-loop.ts"() {
@@ -7045,7 +7045,7 @@ async function yieldUntilFileBrowserReadsIdle(pollMs = 5) {
7045
7045
  while (getFileBrowserInFlightReadCount() > 0) {
7046
7046
  await yieldToEventLoop();
7047
7047
  if (getFileBrowserInFlightReadCount() > 0) {
7048
- await new Promise((resolve37) => setTimeout(resolve37, pollMs));
7048
+ await new Promise((resolve38) => setTimeout(resolve38, pollMs));
7049
7049
  }
7050
7050
  }
7051
7051
  }
@@ -7055,7 +7055,7 @@ async function yieldUntilFileBrowserBrowseIdle(pollMs = 5) {
7055
7055
  const browseCooldownDone = lastActivityAt === 0 || Date.now() - lastActivityAt >= BROWSE_INDEX_COOLDOWN_MS;
7056
7056
  if (inFlightRequests2 === 0 && browseCooldownDone) return;
7057
7057
  await yieldToEventLoop();
7058
- await new Promise((resolve37) => setTimeout(resolve37, pollMs));
7058
+ await new Promise((resolve38) => setTimeout(resolve38, pollMs));
7059
7059
  }
7060
7060
  }
7061
7061
  async function yieldUntilFileBrowserIdle(pollMs = 5) {
@@ -7232,8 +7232,8 @@ function createRequestId(prefix) {
7232
7232
  }
7233
7233
  function waitForWorkerReady() {
7234
7234
  if (workerReady) return Promise.resolve();
7235
- return new Promise((resolve37) => {
7236
- workerReadyWaiters.push(resolve37);
7235
+ return new Promise((resolve38) => {
7236
+ workerReadyWaiters.push(resolve38);
7237
7237
  });
7238
7238
  }
7239
7239
  function registerWorkerReadyListener(listener) {
@@ -7245,7 +7245,7 @@ function registerWorkerReadyListener(listener) {
7245
7245
  }
7246
7246
  function markWorkerReady() {
7247
7247
  workerReady = true;
7248
- for (const resolve37 of workerReadyWaiters) resolve37();
7248
+ for (const resolve38 of workerReadyWaiters) resolve38();
7249
7249
  workerReadyWaiters = [];
7250
7250
  workerReadyListener?.();
7251
7251
  }
@@ -7392,7 +7392,7 @@ async function waitForOuterCodeNavCacheAccessAsync() {
7392
7392
  if (isCliImmediateShutdownRequested() || isSymbolIndexWorkerShutdownRequested()) {
7393
7393
  throw new CliSqliteInterrupted();
7394
7394
  }
7395
- await new Promise((resolve37) => setTimeout(resolve37, 5));
7395
+ await new Promise((resolve38) => setTimeout(resolve38, 5));
7396
7396
  await yieldToEventLoop();
7397
7397
  }
7398
7398
  }
@@ -7729,7 +7729,7 @@ function readMigrationSql(filename, ...searchSubdirs) {
7729
7729
  join3(moduleDir, "..", sub, filename),
7730
7730
  join3(moduleDir, "..", "..", "dist", sub, filename)
7731
7731
  ]);
7732
- const resolved = candidates.find((path86) => existsSync(path86));
7732
+ const resolved = candidates.find((path88) => existsSync(path88));
7733
7733
  if (!resolved) {
7734
7734
  throw new Error(`Missing SQLite migration SQL: ${filename} (searched ${searchSubdirs.join(", ")})`);
7735
7735
  }
@@ -8807,7 +8807,7 @@ var require_ignore = __commonJS({
8807
8807
  // path matching.
8808
8808
  // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
8809
8809
  // @returns {TestResult} true if a file is ignored
8810
- test(path86, checkUnignored, mode) {
8810
+ test(path88, checkUnignored, mode) {
8811
8811
  let ignored = false;
8812
8812
  let unignored = false;
8813
8813
  let matchedRule;
@@ -8816,7 +8816,7 @@ var require_ignore = __commonJS({
8816
8816
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
8817
8817
  return;
8818
8818
  }
8819
- const matched = rule[mode].test(path86);
8819
+ const matched = rule[mode].test(path88);
8820
8820
  if (!matched) {
8821
8821
  return;
8822
8822
  }
@@ -8837,17 +8837,17 @@ var require_ignore = __commonJS({
8837
8837
  var throwError = (message, Ctor) => {
8838
8838
  throw new Ctor(message);
8839
8839
  };
8840
- var checkPath = (path86, originalPath, doThrow) => {
8841
- if (!isString(path86)) {
8840
+ var checkPath = (path88, originalPath, doThrow) => {
8841
+ if (!isString(path88)) {
8842
8842
  return doThrow(
8843
8843
  `path must be a string, but got \`${originalPath}\``,
8844
8844
  TypeError
8845
8845
  );
8846
8846
  }
8847
- if (!path86) {
8847
+ if (!path88) {
8848
8848
  return doThrow(`path must not be empty`, TypeError);
8849
8849
  }
8850
- if (checkPath.isNotRelative(path86)) {
8850
+ if (checkPath.isNotRelative(path88)) {
8851
8851
  const r = "`path.relative()`d";
8852
8852
  return doThrow(
8853
8853
  `path should be a ${r} string, but got "${originalPath}"`,
@@ -8856,7 +8856,7 @@ var require_ignore = __commonJS({
8856
8856
  }
8857
8857
  return true;
8858
8858
  };
8859
- var isNotRelative = (path86) => REGEX_TEST_INVALID_PATH.test(path86);
8859
+ var isNotRelative = (path88) => REGEX_TEST_INVALID_PATH.test(path88);
8860
8860
  checkPath.isNotRelative = isNotRelative;
8861
8861
  checkPath.convert = (p) => p;
8862
8862
  var Ignore = class {
@@ -8886,19 +8886,19 @@ var require_ignore = __commonJS({
8886
8886
  }
8887
8887
  // @returns {TestResult}
8888
8888
  _test(originalPath, cache2, checkUnignored, slices) {
8889
- const path86 = originalPath && checkPath.convert(originalPath);
8889
+ const path88 = originalPath && checkPath.convert(originalPath);
8890
8890
  checkPath(
8891
- path86,
8891
+ path88,
8892
8892
  originalPath,
8893
8893
  this._strictPathCheck ? throwError : RETURN_FALSE
8894
8894
  );
8895
- return this._t(path86, cache2, checkUnignored, slices);
8895
+ return this._t(path88, cache2, checkUnignored, slices);
8896
8896
  }
8897
- checkIgnore(path86) {
8898
- if (!REGEX_TEST_TRAILING_SLASH.test(path86)) {
8899
- return this.test(path86);
8897
+ checkIgnore(path88) {
8898
+ if (!REGEX_TEST_TRAILING_SLASH.test(path88)) {
8899
+ return this.test(path88);
8900
8900
  }
8901
- const slices = path86.split(SLASH).filter(Boolean);
8901
+ const slices = path88.split(SLASH).filter(Boolean);
8902
8902
  slices.pop();
8903
8903
  if (slices.length) {
8904
8904
  const parent = this._t(
@@ -8911,18 +8911,18 @@ var require_ignore = __commonJS({
8911
8911
  return parent;
8912
8912
  }
8913
8913
  }
8914
- return this._rules.test(path86, false, MODE_CHECK_IGNORE);
8914
+ return this._rules.test(path88, false, MODE_CHECK_IGNORE);
8915
8915
  }
8916
- _t(path86, cache2, checkUnignored, slices) {
8917
- if (path86 in cache2) {
8918
- return cache2[path86];
8916
+ _t(path88, cache2, checkUnignored, slices) {
8917
+ if (path88 in cache2) {
8918
+ return cache2[path88];
8919
8919
  }
8920
8920
  if (!slices) {
8921
- slices = path86.split(SLASH).filter(Boolean);
8921
+ slices = path88.split(SLASH).filter(Boolean);
8922
8922
  }
8923
8923
  slices.pop();
8924
8924
  if (!slices.length) {
8925
- return cache2[path86] = this._rules.test(path86, checkUnignored, MODE_IGNORE);
8925
+ return cache2[path88] = this._rules.test(path88, checkUnignored, MODE_IGNORE);
8926
8926
  }
8927
8927
  const parent = this._t(
8928
8928
  slices.join(SLASH) + SLASH,
@@ -8930,29 +8930,29 @@ var require_ignore = __commonJS({
8930
8930
  checkUnignored,
8931
8931
  slices
8932
8932
  );
8933
- return cache2[path86] = parent.ignored ? parent : this._rules.test(path86, checkUnignored, MODE_IGNORE);
8933
+ return cache2[path88] = parent.ignored ? parent : this._rules.test(path88, checkUnignored, MODE_IGNORE);
8934
8934
  }
8935
- ignores(path86) {
8936
- return this._test(path86, this._ignoreCache, false).ignored;
8935
+ ignores(path88) {
8936
+ return this._test(path88, this._ignoreCache, false).ignored;
8937
8937
  }
8938
8938
  createFilter() {
8939
- return (path86) => !this.ignores(path86);
8939
+ return (path88) => !this.ignores(path88);
8940
8940
  }
8941
8941
  filter(paths) {
8942
8942
  return makeArray(paths).filter(this.createFilter());
8943
8943
  }
8944
8944
  // @returns {TestResult}
8945
- test(path86) {
8946
- return this._test(path86, this._testCache, true);
8945
+ test(path88) {
8946
+ return this._test(path88, this._testCache, true);
8947
8947
  }
8948
8948
  };
8949
8949
  var factory = (options) => new Ignore(options);
8950
- var isPathValid = (path86) => checkPath(path86 && checkPath.convert(path86), path86, RETURN_FALSE);
8950
+ var isPathValid = (path88) => checkPath(path88 && checkPath.convert(path88), path88, RETURN_FALSE);
8951
8951
  var setupWindows = () => {
8952
8952
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
8953
8953
  checkPath.convert = makePosix;
8954
8954
  const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
8955
- checkPath.isNotRelative = (path86) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path86) || isNotRelative(path86);
8955
+ checkPath.isNotRelative = (path88) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path88) || isNotRelative(path88);
8956
8956
  };
8957
8957
  if (
8958
8958
  // Detect `process` so that it can run in browsers.
@@ -12143,7 +12143,7 @@ var init_setup_handlers = __esm({
12143
12143
  // src/code-nav/symbol-index/worker/handle-message.ts
12144
12144
  async function waitForActiveWorkerHandlersIdle(pollMs = 10) {
12145
12145
  while (activeWorkerHandlers > 0) {
12146
- await new Promise((resolve37) => setTimeout(resolve37, pollMs));
12146
+ await new Promise((resolve38) => setTimeout(resolve38, pollMs));
12147
12147
  }
12148
12148
  }
12149
12149
  async function handleRequestMessage(port, msg) {
@@ -12386,9 +12386,9 @@ async function requestWorker(message) {
12386
12386
  }
12387
12387
  ensureWorkerStarted();
12388
12388
  await ensureWorkerReadyForRequests();
12389
- return new Promise((resolve37, reject) => {
12389
+ return new Promise((resolve38, reject) => {
12390
12390
  pendingRequests.set(message.requestId, {
12391
- resolve: (value) => resolve37(value),
12391
+ resolve: (value) => resolve38(value),
12392
12392
  reject
12393
12393
  });
12394
12394
  postToWorker(message);
@@ -12414,37 +12414,37 @@ async function shutdownWorkerThread() {
12414
12414
  if (activeWorker != null) {
12415
12415
  setWorker(null);
12416
12416
  await Promise.race([
12417
- new Promise((resolve37) => {
12417
+ new Promise((resolve38) => {
12418
12418
  const onMessage = (message) => {
12419
12419
  if (message.type !== "shutdownComplete") return;
12420
12420
  activeWorker.off("message", onMessage);
12421
- resolve37();
12421
+ resolve38();
12422
12422
  };
12423
12423
  activeWorker.on("message", onMessage);
12424
12424
  try {
12425
12425
  activeWorker.postMessage({ type: "shutdown" });
12426
12426
  } catch {
12427
12427
  activeWorker.off("message", onMessage);
12428
- resolve37();
12428
+ resolve38();
12429
12429
  }
12430
12430
  }),
12431
- new Promise((resolve37) => setTimeout(resolve37, WORKER_SHUTDOWN_GRACE_MS))
12431
+ new Promise((resolve38) => setTimeout(resolve38, WORKER_SHUTDOWN_GRACE_MS))
12432
12432
  ]);
12433
12433
  await activeWorker.terminate();
12434
12434
  } else {
12435
12435
  const inProcess = getInProcessBridge();
12436
12436
  if (inProcess != null) {
12437
12437
  await Promise.race([
12438
- new Promise((resolve37) => {
12438
+ new Promise((resolve38) => {
12439
12439
  const onMessage = (message) => {
12440
12440
  if (message.type !== "shutdownComplete") return;
12441
12441
  inProcess.off("message", onMessage);
12442
- resolve37();
12442
+ resolve38();
12443
12443
  };
12444
12444
  inProcess.on("message", onMessage);
12445
12445
  inProcess.postMessage({ type: "shutdown" });
12446
12446
  }),
12447
- new Promise((resolve37) => setTimeout(resolve37, WORKER_SHUTDOWN_GRACE_MS))
12447
+ new Promise((resolve38) => setTimeout(resolve38, WORKER_SHUTDOWN_GRACE_MS))
12448
12448
  ]);
12449
12449
  }
12450
12450
  }
@@ -12522,6 +12522,16 @@ async function awaitSymbolIndexWorkerShutdown() {
12522
12522
  await terminateSymbolIndexWorker2();
12523
12523
  }
12524
12524
  }
12525
+ async function clearCliImmediateShutdown() {
12526
+ if (symbolIndexShutdownPromise != null) {
12527
+ try {
12528
+ await symbolIndexShutdownPromise;
12529
+ } catch {
12530
+ }
12531
+ }
12532
+ cliImmediateShutdownRequested = false;
12533
+ symbolIndexShutdownPromise = null;
12534
+ }
12525
12535
  function resetCliImmediateShutdownForTests() {
12526
12536
  cliImmediateShutdownRequested = false;
12527
12537
  symbolIndexShutdownPromise = null;
@@ -12958,8 +12968,8 @@ var init_parseUtil = __esm({
12958
12968
  init_errors();
12959
12969
  init_en();
12960
12970
  makeIssue = (params) => {
12961
- const { data, path: path86, errorMaps, issueData } = params;
12962
- const fullPath = [...path86, ...issueData.path || []];
12971
+ const { data, path: path88, errorMaps, issueData } = params;
12972
+ const fullPath = [...path88, ...issueData.path || []];
12963
12973
  const fullIssue = {
12964
12974
  ...issueData,
12965
12975
  path: fullPath
@@ -13267,11 +13277,11 @@ var init_types2 = __esm({
13267
13277
  init_parseUtil();
13268
13278
  init_util();
13269
13279
  ParseInputLazyPath = class {
13270
- constructor(parent, value, path86, key) {
13280
+ constructor(parent, value, path88, key) {
13271
13281
  this._cachedPath = [];
13272
13282
  this.parent = parent;
13273
13283
  this.data = value;
13274
- this._path = path86;
13284
+ this._path = path88;
13275
13285
  this._key = key;
13276
13286
  }
13277
13287
  get path() {
@@ -16996,10 +17006,10 @@ function assignProp(target, prop, value) {
16996
17006
  configurable: true
16997
17007
  });
16998
17008
  }
16999
- function getElementAtPath(obj, path86) {
17000
- if (!path86)
17009
+ function getElementAtPath(obj, path88) {
17010
+ if (!path88)
17001
17011
  return obj;
17002
- return path86.reduce((acc, key) => acc?.[key], obj);
17012
+ return path88.reduce((acc, key) => acc?.[key], obj);
17003
17013
  }
17004
17014
  function promiseAllObject(promisesObj) {
17005
17015
  const keys = Object.keys(promisesObj);
@@ -17248,11 +17258,11 @@ function aborted(x, startIndex = 0) {
17248
17258
  }
17249
17259
  return false;
17250
17260
  }
17251
- function prefixIssues(path86, issues) {
17261
+ function prefixIssues(path88, issues) {
17252
17262
  return issues.map((iss) => {
17253
17263
  var _a2;
17254
17264
  (_a2 = iss).path ?? (_a2.path = []);
17255
- iss.path.unshift(path86);
17265
+ iss.path.unshift(path88);
17256
17266
  return iss;
17257
17267
  });
17258
17268
  }
@@ -17441,7 +17451,7 @@ function treeifyError(error40, _mapper) {
17441
17451
  return issue2.message;
17442
17452
  };
17443
17453
  const result = { errors: [] };
17444
- const processError = (error41, path86 = []) => {
17454
+ const processError = (error41, path88 = []) => {
17445
17455
  var _a2, _b;
17446
17456
  for (const issue2 of error41.issues) {
17447
17457
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -17451,7 +17461,7 @@ function treeifyError(error40, _mapper) {
17451
17461
  } else if (issue2.code === "invalid_element") {
17452
17462
  processError({ issues: issue2.issues }, issue2.path);
17453
17463
  } else {
17454
- const fullpath = [...path86, ...issue2.path];
17464
+ const fullpath = [...path88, ...issue2.path];
17455
17465
  if (fullpath.length === 0) {
17456
17466
  result.errors.push(mapper(issue2));
17457
17467
  continue;
@@ -17481,9 +17491,9 @@ function treeifyError(error40, _mapper) {
17481
17491
  processError(error40);
17482
17492
  return result;
17483
17493
  }
17484
- function toDotPath(path86) {
17494
+ function toDotPath(path88) {
17485
17495
  const segs = [];
17486
- for (const seg of path86) {
17496
+ for (const seg of path88) {
17487
17497
  if (typeof seg === "number")
17488
17498
  segs.push(`[${seg}]`);
17489
17499
  else if (typeof seg === "symbol")
@@ -29946,8 +29956,8 @@ var init_acp = __esm({
29946
29956
  this.#requestHandler = requestHandler;
29947
29957
  this.#notificationHandler = notificationHandler;
29948
29958
  this.#stream = stream;
29949
- this.#closedPromise = new Promise((resolve37) => {
29950
- this.#abortController.signal.addEventListener("abort", () => resolve37());
29959
+ this.#closedPromise = new Promise((resolve38) => {
29960
+ this.#abortController.signal.addEventListener("abort", () => resolve38());
29951
29961
  });
29952
29962
  this.#receive();
29953
29963
  }
@@ -30096,8 +30106,8 @@ var init_acp = __esm({
30096
30106
  }
30097
30107
  async sendRequest(method, params) {
30098
30108
  const id = this.#nextRequestId++;
30099
- const responsePromise = new Promise((resolve37, reject) => {
30100
- this.#pendingResponses.set(id, { resolve: resolve37, reject });
30109
+ const responsePromise = new Promise((resolve38, reject) => {
30110
+ this.#pendingResponses.set(id, { resolve: resolve38, reject });
30101
30111
  });
30102
30112
  await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
30103
30113
  return responsePromise;
@@ -30966,10 +30976,10 @@ var require_src2 = __commonJS({
30966
30976
  var fs_1 = __require("fs");
30967
30977
  var debug_1 = __importDefault(require_src());
30968
30978
  var log2 = debug_1.default("@kwsites/file-exists");
30969
- function check2(path86, isFile, isDirectory) {
30970
- log2(`checking %s`, path86);
30979
+ function check2(path88, isFile, isDirectory) {
30980
+ log2(`checking %s`, path88);
30971
30981
  try {
30972
- const stat3 = fs_1.statSync(path86);
30982
+ const stat3 = fs_1.statSync(path88);
30973
30983
  if (stat3.isFile() && isFile) {
30974
30984
  log2(`[OK] path represents a file`);
30975
30985
  return true;
@@ -30989,8 +30999,8 @@ var require_src2 = __commonJS({
30989
30999
  throw e;
30990
31000
  }
30991
31001
  }
30992
- function exists2(path86, type = exports.READABLE) {
30993
- return check2(path86, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0);
31002
+ function exists2(path88, type = exports.READABLE) {
31003
+ return check2(path88, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0);
30994
31004
  }
30995
31005
  exports.exists = exists2;
30996
31006
  exports.FILE = 1;
@@ -31071,7 +31081,7 @@ var {
31071
31081
  } = import_index.default;
31072
31082
 
31073
31083
  // src/cli-version.ts
31074
- var CLI_VERSION = "0.1.79".length > 0 ? "0.1.79" : "0.0.0-dev";
31084
+ var CLI_VERSION = "0.1.81".length > 0 ? "0.1.81" : "0.0.0-dev";
31075
31085
 
31076
31086
  // src/cli/defaults.ts
31077
31087
  var DEFAULT_API_URL = process.env.BUILDAUTOMATON_API_URL ?? "https://api.buildautomaton.com";
@@ -31079,8 +31089,8 @@ var DEFAULT_FIREHOSE_URL = "https://buildautomaton-firehose.fly.dev";
31079
31089
 
31080
31090
  // src/cli/run-cli-action.ts
31081
31091
  init_cli_log_level();
31082
- import * as fs64 from "node:fs";
31083
- import * as path85 from "node:path";
31092
+ import * as fs66 from "node:fs";
31093
+ import * as path87 from "node:path";
31084
31094
 
31085
31095
  // src/config.ts
31086
31096
  import fs from "node:fs";
@@ -31533,181 +31543,8 @@ function installBridgeProcessResilience() {
31533
31543
  });
31534
31544
  }
31535
31545
 
31536
- // ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/wrapper.mjs
31537
- var import_stream = __toESM(require_stream(), 1);
31538
- var import_receiver = __toESM(require_receiver(), 1);
31539
- var import_sender = __toESM(require_sender(), 1);
31540
- var import_websocket = __toESM(require_websocket(), 1);
31541
- var import_websocket_server = __toESM(require_websocket_server(), 1);
31542
- var wrapper_default = import_websocket.default;
31543
-
31544
- // src/connection/cli-ws-client.ts
31545
- import https from "node:https";
31546
- var CLI_WEBSOCKET_CLIENT_PING_MS = 25e3;
31547
- function attachWebSocketClientPing(ws, intervalMs) {
31548
- let timer = null;
31549
- function clear() {
31550
- if (timer != null) {
31551
- clearInterval(timer);
31552
- timer = null;
31553
- }
31554
- }
31555
- clear();
31556
- timer = setInterval(() => {
31557
- if (ws.readyState === wrapper_default.OPEN) {
31558
- try {
31559
- ws.ping();
31560
- } catch {
31561
- }
31562
- }
31563
- }, intervalMs);
31564
- return clear;
31565
- }
31566
- function buildCliWebSocketClientOptions(wsUrl) {
31567
- const wsOptions = { perMessageDeflate: false };
31568
- if (wsUrl.startsWith("wss://")) {
31569
- wsOptions.agent = new https.Agent({ rejectUnauthorized: false });
31570
- }
31571
- return wsOptions;
31572
- }
31573
- function logCliWebSocketError(log2, serviceLabel, err, detail) {
31574
- const mid = detail ? ` ${detail}` : "";
31575
- log2(`${serviceLabel} WebSocket error${mid}: ${err.message}`);
31576
- }
31577
- function safeCloseWebSocket(ws) {
31578
- try {
31579
- if (ws.readyState === wrapper_default.CLOSED) {
31580
- ws.removeAllListeners();
31581
- return;
31582
- }
31583
- ws.once("close", () => {
31584
- ws.removeAllListeners();
31585
- });
31586
- ws.close();
31587
- } catch {
31588
- try {
31589
- ws.removeAllListeners();
31590
- } catch {
31591
- }
31592
- }
31593
- }
31594
- function safeSendWebSocketBinary(ws, data) {
31595
- if (ws.readyState !== wrapper_default.OPEN) return false;
31596
- try {
31597
- ws.send(data, { binary: true });
31598
- return true;
31599
- } catch {
31600
- return false;
31601
- }
31602
- }
31603
-
31604
- // src/connection/parse-compact-heartbeat-ack.ts
31605
- function tryParseCompactHeartbeatAck(raw) {
31606
- let str = null;
31607
- if (typeof raw === "string") {
31608
- str = raw;
31609
- } else if (Buffer.isBuffer(raw)) {
31610
- str = raw.toString("utf8");
31611
- } else if (raw instanceof ArrayBuffer) {
31612
- str = Buffer.from(raw).toString("utf8");
31613
- } else {
31614
- return null;
31615
- }
31616
- if (str.length > 64 || !str.includes('"ha"')) return null;
31617
- try {
31618
- const parsed = JSON.parse(str);
31619
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
31620
- const o = parsed;
31621
- if (o.t !== "ha") return null;
31622
- const s = o.s;
31623
- if (typeof s !== "number" || !Number.isFinite(s)) return null;
31624
- return Math.trunc(s);
31625
- } catch {
31626
- return null;
31627
- }
31628
- }
31629
-
31630
- // src/connection/create-ws-bridge.ts
31631
- var BRIDGE_AUTH_ERROR_HEADER = "x-bridge-auth-error";
31632
- var BRIDGE_AUTH_ERROR_TOKEN_INVALID = "token_invalid";
31633
- function createWsBridge(options) {
31634
- const {
31635
- url: url2,
31636
- onMessage,
31637
- onOpen,
31638
- onClose,
31639
- onError: onError2,
31640
- onAuthInvalid,
31641
- clientPingIntervalMs,
31642
- onCompactHeartbeatAck,
31643
- isActiveSocket
31644
- } = options;
31645
- const ws = new wrapper_default(url2, buildCliWebSocketClientOptions(url2));
31646
- let clearClientPing = null;
31647
- function disposeClientPing() {
31648
- clearClientPing?.();
31649
- clearClientPing = null;
31650
- }
31651
- ws.on("unexpected-response", (request, response) => {
31652
- const status = response?.statusCode ?? 0;
31653
- const headers = response?.headers ?? {};
31654
- const errCode = (headers[BRIDGE_AUTH_ERROR_HEADER] ?? headers["X-Bridge-Auth-Error"] ?? "").toLowerCase();
31655
- if (status === 401 && errCode === BRIDGE_AUTH_ERROR_TOKEN_INVALID) {
31656
- void Promise.resolve(onAuthInvalid?.());
31657
- }
31658
- });
31659
- ws.on("open", () => {
31660
- disposeClientPing();
31661
- if (clientPingIntervalMs != null && clientPingIntervalMs > 0) {
31662
- clearClientPing = attachWebSocketClientPing(ws, clientPingIntervalMs);
31663
- }
31664
- onOpen?.();
31665
- });
31666
- ws.on("message", (raw) => {
31667
- const ackSeq = tryParseCompactHeartbeatAck(raw);
31668
- if (ackSeq != null) {
31669
- onCompactHeartbeatAck?.(ackSeq);
31670
- return;
31671
- }
31672
- setImmediate(() => {
31673
- if (isActiveSocket && !isActiveSocket(ws)) return;
31674
- try {
31675
- let data;
31676
- if (typeof raw === "string") {
31677
- data = JSON.parse(raw);
31678
- } else if (Buffer.isBuffer(raw) || raw instanceof ArrayBuffer) {
31679
- const str = Buffer.isBuffer(raw) ? raw.toString("utf8") : Buffer.from(raw).toString("utf8");
31680
- data = JSON.parse(str);
31681
- } else {
31682
- data = raw;
31683
- }
31684
- onMessage?.(data, ws);
31685
- } catch {
31686
- onMessage?.(raw, ws);
31687
- }
31688
- });
31689
- });
31690
- ws.on("close", (code, reason) => {
31691
- disposeClientPing();
31692
- onClose?.(code, reason.toString());
31693
- });
31694
- ws.on("error", (err) => {
31695
- disposeClientPing();
31696
- onError2?.(err);
31697
- });
31698
- return ws;
31699
- }
31700
- function sendWsMessage(ws, payload) {
31701
- if (ws.readyState !== wrapper_default.OPEN) return false;
31702
- ws.send(JSON.stringify(payload));
31703
- return true;
31704
- }
31705
-
31706
- // src/connection/heartbeat/constants.ts
31707
- var BRIDGE_APP_HEARTBEAT_INTERVAL_MS = 1e4;
31708
- var BRIDGE_HEARTBEAT_SEQ_MAX = 2147483646;
31709
- var BRIDGE_HEARTBEAT_MISSED_ACKS_BEFORE_RECONNECT = 4;
31710
- var BRIDGE_HEARTBEAT_RTT_SAMPLE_MAX = 5;
31546
+ // src/auth/pending/run-pending-auth.ts
31547
+ init_log();
31711
31548
 
31712
31549
  // ../../node_modules/.pnpm/open@10.2.0/node_modules/open/index.js
31713
31550
  import process7 from "node:process";
@@ -32142,14 +31979,14 @@ var baseOpen = async (options) => {
32142
31979
  }
32143
31980
  const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
32144
31981
  if (options.wait) {
32145
- return new Promise((resolve37, reject) => {
31982
+ return new Promise((resolve38, reject) => {
32146
31983
  subprocess.once("error", reject);
32147
31984
  subprocess.once("close", (exitCode) => {
32148
31985
  if (!options.allowNonzeroExitCode && exitCode > 0) {
32149
31986
  reject(new Error(`Exited with code ${exitCode}`));
32150
31987
  return;
32151
31988
  }
32152
- resolve37(subprocess);
31989
+ resolve38(subprocess);
32153
31990
  });
32154
31991
  });
32155
31992
  }
@@ -32262,8 +32099,196 @@ async function openBrowser(connectionId, initialWorkspaceId, preferredBridgeName
32262
32099
  }
32263
32100
  }
32264
32101
 
32265
- // src/auth/run-pending-auth.ts
32266
- init_log();
32102
+ // src/auth/pending/constants.ts
32103
+ var PENDING_KEEPALIVE_MS = 25e3;
32104
+ var BROWSER_OPEN_FALLBACK_MS = 4e3;
32105
+
32106
+ // ../../node_modules/.pnpm/ws@8.19.0/node_modules/ws/wrapper.mjs
32107
+ var import_stream = __toESM(require_stream(), 1);
32108
+ var import_receiver = __toESM(require_receiver(), 1);
32109
+ var import_sender = __toESM(require_sender(), 1);
32110
+ var import_websocket = __toESM(require_websocket(), 1);
32111
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
32112
+ var wrapper_default = import_websocket.default;
32113
+
32114
+ // src/connection/cli-ws-client.ts
32115
+ import https from "node:https";
32116
+ var CLI_WEBSOCKET_CLIENT_PING_MS = 25e3;
32117
+ function attachWebSocketClientPing(ws, intervalMs) {
32118
+ let timer = null;
32119
+ function clear() {
32120
+ if (timer != null) {
32121
+ clearInterval(timer);
32122
+ timer = null;
32123
+ }
32124
+ }
32125
+ clear();
32126
+ timer = setInterval(() => {
32127
+ if (ws.readyState === wrapper_default.OPEN) {
32128
+ try {
32129
+ ws.ping();
32130
+ } catch {
32131
+ }
32132
+ }
32133
+ }, intervalMs);
32134
+ return clear;
32135
+ }
32136
+ function buildCliWebSocketClientOptions(wsUrl) {
32137
+ const wsOptions = { perMessageDeflate: false };
32138
+ if (wsUrl.startsWith("wss://")) {
32139
+ wsOptions.agent = new https.Agent({ rejectUnauthorized: false });
32140
+ }
32141
+ return wsOptions;
32142
+ }
32143
+ function logCliWebSocketError(log2, serviceLabel, err, detail) {
32144
+ const mid = detail ? ` ${detail}` : "";
32145
+ log2(`${serviceLabel} WebSocket error${mid}: ${err.message}`);
32146
+ }
32147
+ function safeCloseWebSocket(ws) {
32148
+ try {
32149
+ if (ws.readyState === wrapper_default.CLOSED) {
32150
+ ws.removeAllListeners();
32151
+ return;
32152
+ }
32153
+ ws.once("close", () => {
32154
+ ws.removeAllListeners();
32155
+ });
32156
+ ws.close();
32157
+ } catch {
32158
+ try {
32159
+ ws.removeAllListeners();
32160
+ } catch {
32161
+ }
32162
+ }
32163
+ }
32164
+ function safeSendWebSocketBinary(ws, data) {
32165
+ if (ws.readyState !== wrapper_default.OPEN) return false;
32166
+ try {
32167
+ ws.send(data, { binary: true });
32168
+ return true;
32169
+ } catch {
32170
+ return false;
32171
+ }
32172
+ }
32173
+
32174
+ // src/connection/create-ws-bridge-options.ts
32175
+ var BRIDGE_AUTH_ERROR_HEADER = "x-bridge-auth-error";
32176
+ var BRIDGE_AUTH_ERROR_TOKEN_INVALID = "token_invalid";
32177
+
32178
+ // src/connection/dispatch-ws-inbound-message.ts
32179
+ function dispatchWsInboundMessage(raw, ws, onMessage, isActiveSocket) {
32180
+ if (isActiveSocket && !isActiveSocket(ws)) return;
32181
+ try {
32182
+ let data;
32183
+ if (typeof raw === "string") {
32184
+ data = JSON.parse(raw);
32185
+ } else if (Buffer.isBuffer(raw) || raw instanceof ArrayBuffer) {
32186
+ const str = Buffer.isBuffer(raw) ? raw.toString("utf8") : Buffer.from(raw).toString("utf8");
32187
+ data = JSON.parse(str);
32188
+ } else {
32189
+ data = raw;
32190
+ }
32191
+ onMessage?.(data, ws);
32192
+ } catch {
32193
+ onMessage?.(raw, ws);
32194
+ }
32195
+ }
32196
+
32197
+ // src/connection/parse-compact-heartbeat-ack.ts
32198
+ function tryParseCompactHeartbeatAck(raw) {
32199
+ let str = null;
32200
+ if (typeof raw === "string") {
32201
+ str = raw;
32202
+ } else if (Buffer.isBuffer(raw)) {
32203
+ str = raw.toString("utf8");
32204
+ } else if (raw instanceof ArrayBuffer) {
32205
+ str = Buffer.from(raw).toString("utf8");
32206
+ } else {
32207
+ return null;
32208
+ }
32209
+ if (str.length > 64 || !str.includes('"ha"')) return null;
32210
+ try {
32211
+ const parsed = JSON.parse(str);
32212
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
32213
+ const o = parsed;
32214
+ if (o.t !== "ha") return null;
32215
+ const s = o.s;
32216
+ if (typeof s !== "number" || !Number.isFinite(s)) return null;
32217
+ return Math.trunc(s);
32218
+ } catch {
32219
+ return null;
32220
+ }
32221
+ }
32222
+
32223
+ // src/connection/create-ws-bridge.ts
32224
+ function createWsBridge(options) {
32225
+ const {
32226
+ url: url2,
32227
+ onMessage,
32228
+ onOpen,
32229
+ onClose,
32230
+ onError: onError2,
32231
+ onAuthInvalid,
32232
+ clientPingIntervalMs,
32233
+ onCompactHeartbeatAck,
32234
+ isActiveSocket,
32235
+ deferInboundMessages = true
32236
+ } = options;
32237
+ const ws = new wrapper_default(url2, buildCliWebSocketClientOptions(url2));
32238
+ let clearClientPing = null;
32239
+ const disposeClientPing = () => {
32240
+ clearClientPing?.();
32241
+ clearClientPing = null;
32242
+ };
32243
+ ws.on("unexpected-response", (_request, response) => {
32244
+ const status = response?.statusCode ?? 0;
32245
+ const headers = response?.headers ?? {};
32246
+ const errCode = (headers[BRIDGE_AUTH_ERROR_HEADER] ?? headers["X-Bridge-Auth-Error"] ?? "").toLowerCase();
32247
+ if (status === 401 && errCode === BRIDGE_AUTH_ERROR_TOKEN_INVALID) {
32248
+ void Promise.resolve(onAuthInvalid?.());
32249
+ }
32250
+ });
32251
+ ws.on("open", () => {
32252
+ disposeClientPing();
32253
+ if (clientPingIntervalMs != null && clientPingIntervalMs > 0) {
32254
+ clearClientPing = attachWebSocketClientPing(ws, clientPingIntervalMs);
32255
+ }
32256
+ onOpen?.();
32257
+ });
32258
+ ws.on("message", (raw) => {
32259
+ const ackSeq = tryParseCompactHeartbeatAck(raw);
32260
+ if (ackSeq != null) {
32261
+ onCompactHeartbeatAck?.(ackSeq);
32262
+ return;
32263
+ }
32264
+ if (deferInboundMessages) {
32265
+ setImmediate(() => dispatchWsInboundMessage(raw, ws, onMessage, isActiveSocket));
32266
+ return;
32267
+ }
32268
+ dispatchWsInboundMessage(raw, ws, onMessage, isActiveSocket);
32269
+ });
32270
+ ws.on("close", (code, reason) => {
32271
+ disposeClientPing();
32272
+ onClose?.(code, reason.toString());
32273
+ });
32274
+ ws.on("error", (err) => {
32275
+ disposeClientPing();
32276
+ onError2?.(err);
32277
+ });
32278
+ return ws;
32279
+ }
32280
+ function sendWsMessage(ws, payload) {
32281
+ if (ws.readyState !== wrapper_default.OPEN) return false;
32282
+ ws.send(JSON.stringify(payload));
32283
+ return true;
32284
+ }
32285
+
32286
+ // src/auth/pending/build-pending-bridge-url.ts
32287
+ function buildPendingBridgeUrl(apiUrl, connectionId) {
32288
+ const base = apiUrl.startsWith("https") ? apiUrl.replace(/^https/, "wss") : apiUrl.replace(/^http/, "ws");
32289
+ const params = new URLSearchParams({ connectionId });
32290
+ return `${base}/ws/bridge/pending?${params.toString()}`;
32291
+ }
32267
32292
 
32268
32293
  // src/connection/reconnect/constants.ts
32269
32294
  var RECONNECT_QUIET_MS = 2e3;
@@ -32594,6 +32619,12 @@ function scheduleMainBridgeReconnect(state, connect, log2, closeMeta) {
32594
32619
  });
32595
32620
  }
32596
32621
 
32622
+ // src/connection/heartbeat/constants.ts
32623
+ var BRIDGE_APP_HEARTBEAT_INTERVAL_MS = 1e4;
32624
+ var BRIDGE_HEARTBEAT_SEQ_MAX = 2147483646;
32625
+ var BRIDGE_HEARTBEAT_MISSED_ACKS_BEFORE_RECONNECT = 4;
32626
+ var BRIDGE_HEARTBEAT_RTT_SAMPLE_MAX = 5;
32627
+
32597
32628
  // src/connection/reconnect/duplicate-bridge-connection-detect.ts
32598
32629
  var BRIDGE_SUPERSEDED_CLOSE_REASON_SNIPPET = "superseded";
32599
32630
  var DUPLICATE_BRIDGE_SHORT_SESSION_MS = 25e3;
@@ -32678,145 +32709,177 @@ function clearFirehoseReconnectQuietOnOpen(ctx, log2) {
32678
32709
  });
32679
32710
  }
32680
32711
 
32681
- // src/auth/run-pending-auth.ts
32682
- var PENDING_KEEPALIVE_MS = 25e3;
32683
- var BROWSER_OPEN_FALLBACK_MS = 4e3;
32684
- function buildPendingBridgeUrl(apiUrl, connectionId) {
32685
- const base = apiUrl.startsWith("https") ? apiUrl.replace(/^https/, "wss") : apiUrl.replace(/^http/, "ws");
32686
- const params = new URLSearchParams({ connectionId });
32687
- return `${base}/ws/bridge/pending?${params.toString()}`;
32688
- }
32689
- function runPendingAuth(options) {
32690
- const { apiUrl, initialWorkspaceId, preferredBridgeName, onAuth } = options;
32691
- const logFn = options.log ?? log;
32692
- let ws = null;
32693
- let reconnectTimeout = null;
32694
- let keepaliveInterval = null;
32695
- let browserFallback = null;
32696
- const connectionId = crypto.randomUUID();
32697
- let hasOpenedBrowser = false;
32698
- let resolved = false;
32699
- let resolveAuth;
32700
- const authPromise = new Promise((resolve37) => {
32701
- resolveAuth = resolve37;
32702
- });
32703
- let reconnectAttempt = 0;
32704
- const signInQuiet = createEmptyReconnectQuietSlot();
32705
- function clearQuietOnOpen() {
32706
- clearReconnectQuietOnSuccessfulConnection(
32707
- signInQuiet,
32708
- logFn,
32709
- "[Bridge service] Sign-in connection restored."
32710
- );
32711
- reconnectAttempt = 0;
32712
- }
32713
- function beginDeferredPendingCloseLog(code, reason) {
32712
+ // src/auth/pending/pending-auth-on-close.ts
32713
+ function createPendingAuthOnClose(params) {
32714
+ const { session, log: log2, connect } = params;
32715
+ return (code, reason) => {
32716
+ if (session.keepaliveInterval) {
32717
+ clearInterval(session.keepaliveInterval);
32718
+ session.keepaliveInterval = null;
32719
+ }
32720
+ if (session.resolved) return;
32714
32721
  beginDeferredDisconnectForReconnect({
32715
- isClosedByUser: () => resolved,
32716
- quiet: signInQuiet,
32722
+ isClosedByUser: () => session.resolved,
32723
+ quiet: session.signInQuiet,
32717
32724
  code,
32718
32725
  reason,
32719
32726
  willReconnect: true,
32720
- log: logFn,
32727
+ log: log2,
32721
32728
  serviceLabel: "[Bridge service]",
32722
32729
  shutdownDetail: "Not reconnecting (shutting down).",
32723
32730
  reconnectingDetail: "Waiting for browser sign-in; reconnecting\u2026",
32724
- shouldAbortQuietWindow: () => ws != null && ws.readyState === wrapper_default.OPEN
32731
+ shouldAbortQuietWindow: () => session.ws != null && session.ws.readyState === wrapper_default.OPEN
32725
32732
  });
32726
- }
32727
- function cleanup() {
32728
- clearReconnectQuietTimer(signInQuiet);
32729
- if (reconnectTimeout) {
32730
- clearTimeout(reconnectTimeout);
32731
- reconnectTimeout = null;
32732
- }
32733
- if (browserFallback) {
32734
- clearTimeout(browserFallback);
32735
- browserFallback = null;
32736
- }
32737
- if (keepaliveInterval) {
32738
- clearInterval(keepaliveInterval);
32739
- keepaliveInterval = null;
32740
- }
32741
- if (ws) {
32742
- const w = ws;
32743
- ws = null;
32744
- safeCloseWebSocket(w);
32733
+ const delay4 = pendingAuthReconnectDelayMs(session.reconnectAttempt);
32734
+ session.reconnectAttempt += 1;
32735
+ if (session.signInQuiet.verboseLogs) {
32736
+ const delayLabel = formatReconnectDelayForLog(delay4);
32737
+ log2(
32738
+ `[Bridge service] Next sign-in connection attempt in ${delayLabel} (attempt ${session.reconnectAttempt}).`
32739
+ );
32745
32740
  }
32741
+ session.reconnectTimeout = setTimeout(() => {
32742
+ session.reconnectTimeout = null;
32743
+ connect();
32744
+ }, delay4);
32745
+ };
32746
+ }
32747
+
32748
+ // src/auth/pending/pending-auth-session.ts
32749
+ function createPendingAuthSession() {
32750
+ let resolveAuth;
32751
+ const authPromise = new Promise((resolve38) => {
32752
+ resolveAuth = resolve38;
32753
+ });
32754
+ return {
32755
+ ws: null,
32756
+ reconnectTimeout: null,
32757
+ keepaliveInterval: null,
32758
+ browserFallback: null,
32759
+ connectionId: crypto.randomUUID(),
32760
+ hasOpenedBrowser: false,
32761
+ resolved: false,
32762
+ resolveAuth,
32763
+ reconnectAttempt: 0,
32764
+ signInQuiet: createEmptyReconnectQuietSlot(),
32765
+ authPromise
32766
+ };
32767
+ }
32768
+ function cleanupPendingAuthSession(session) {
32769
+ clearReconnectQuietTimer(session.signInQuiet);
32770
+ if (session.reconnectTimeout) {
32771
+ clearTimeout(session.reconnectTimeout);
32772
+ session.reconnectTimeout = null;
32746
32773
  }
32747
- function connect() {
32748
- const url2 = buildPendingBridgeUrl(apiUrl, connectionId);
32749
- let pendingHbSeq = -1;
32750
- ws = createWsBridge({
32751
- url: url2,
32752
- onOpen: () => {
32753
- clearQuietOnOpen();
32754
- pendingHbSeq = -1;
32755
- sendWsMessage(ws, { type: "identify", role: "cli", cliVersion: CLI_VERSION });
32756
- keepaliveInterval = setInterval(() => {
32757
- if (resolved || !ws || ws.readyState !== 1) return;
32758
- pendingHbSeq = pendingHbSeq >= BRIDGE_HEARTBEAT_SEQ_MAX ? 0 : pendingHbSeq + 1;
32759
- const hb = { t: "h", s: pendingHbSeq };
32760
- sendWsMessage(ws, hb);
32761
- }, PENDING_KEEPALIVE_MS);
32762
- if (browserFallback) {
32763
- clearTimeout(browserFallback);
32764
- browserFallback = null;
32765
- }
32766
- if (!hasOpenedBrowser) {
32767
- hasOpenedBrowser = true;
32768
- void openBrowser(connectionId, initialWorkspaceId, preferredBridgeName, apiUrl, logFn);
32769
- }
32770
- },
32771
- onClose: (code, reason) => {
32772
- if (keepaliveInterval) {
32773
- clearInterval(keepaliveInterval);
32774
- keepaliveInterval = null;
32775
- }
32776
- if (resolved) return;
32777
- beginDeferredPendingCloseLog(code, reason);
32778
- const delay4 = pendingAuthReconnectDelayMs(reconnectAttempt);
32779
- reconnectAttempt += 1;
32780
- if (signInQuiet.verboseLogs) {
32781
- const delayLabel = formatReconnectDelayForLog(delay4);
32782
- logFn(
32783
- `[Bridge service] Next sign-in connection attempt in ${delayLabel} (attempt ${reconnectAttempt}).`
32784
- );
32785
- }
32786
- reconnectTimeout = setTimeout(() => {
32787
- reconnectTimeout = null;
32788
- connect();
32789
- }, delay4);
32790
- },
32791
- onError: (err) => logCliWebSocketError(logFn, "[Bridge service]", err, "while waiting for sign-in"),
32792
- onMessage: (data) => {
32793
- const msg = data;
32794
- if (msg.type === "auth_token" && typeof msg.token === "string") {
32795
- resolved = true;
32796
- const workspaceId = typeof msg.workspaceId === "string" ? msg.workspaceId : "";
32797
- cleanup();
32798
- const refreshToken = typeof msg.refreshToken === "string" ? msg.refreshToken : void 0;
32799
- const result = { workspaceId, token: msg.token, refreshToken };
32800
- resolveAuth(result);
32801
- onAuth(result);
32802
- }
32803
- }
32804
- });
32774
+ if (session.browserFallback) {
32775
+ clearTimeout(session.browserFallback);
32776
+ session.browserFallback = null;
32805
32777
  }
32806
- browserFallback = setTimeout(() => {
32807
- browserFallback = null;
32808
- if (!hasOpenedBrowser) {
32809
- hasOpenedBrowser = true;
32810
- void openBrowser(connectionId, initialWorkspaceId, preferredBridgeName, apiUrl, logFn);
32778
+ if (session.keepaliveInterval) {
32779
+ clearInterval(session.keepaliveInterval);
32780
+ session.keepaliveInterval = null;
32781
+ }
32782
+ if (session.ws) {
32783
+ const w = session.ws;
32784
+ session.ws = null;
32785
+ safeCloseWebSocket(w);
32786
+ }
32787
+ }
32788
+
32789
+ // src/auth/pending/pending-auth-on-message.ts
32790
+ function createPendingAuthOnMessage(params) {
32791
+ const { session, onAuth } = params;
32792
+ return (data) => {
32793
+ const msg = data;
32794
+ if (msg.type !== "auth_token" || typeof msg.token !== "string") return;
32795
+ session.resolved = true;
32796
+ const workspaceId = typeof msg.workspaceId === "string" ? msg.workspaceId : "";
32797
+ const refreshToken = typeof msg.refreshToken === "string" ? msg.refreshToken : void 0;
32798
+ const result = { workspaceId, token: msg.token, refreshToken };
32799
+ session.resolveAuth(result);
32800
+ onAuth(result);
32801
+ cleanupPendingAuthSession(session);
32802
+ };
32803
+ }
32804
+
32805
+ // src/auth/pending/pending-auth-on-open.ts
32806
+ function createPendingAuthOnOpen(params) {
32807
+ const { session, apiUrl, initialWorkspaceId, preferredBridgeName, log: log2 } = params;
32808
+ let pendingHbSeq = -1;
32809
+ return () => {
32810
+ clearReconnectQuietOnSuccessfulConnection(
32811
+ session.signInQuiet,
32812
+ log2,
32813
+ "[Bridge service] Sign-in connection restored."
32814
+ );
32815
+ session.reconnectAttempt = 0;
32816
+ pendingHbSeq = -1;
32817
+ sendWsMessage(session.ws, { type: "identify", role: "cli", cliVersion: CLI_VERSION });
32818
+ session.keepaliveInterval = setInterval(() => {
32819
+ if (session.resolved || !session.ws || session.ws.readyState !== 1) return;
32820
+ pendingHbSeq = pendingHbSeq >= BRIDGE_HEARTBEAT_SEQ_MAX ? 0 : pendingHbSeq + 1;
32821
+ const hb = { t: "h", s: pendingHbSeq };
32822
+ sendWsMessage(session.ws, hb);
32823
+ }, PENDING_KEEPALIVE_MS);
32824
+ if (session.browserFallback) {
32825
+ clearTimeout(session.browserFallback);
32826
+ session.browserFallback = null;
32827
+ }
32828
+ if (!session.hasOpenedBrowser) {
32829
+ session.hasOpenedBrowser = true;
32830
+ void openBrowser(session.connectionId, initialWorkspaceId, preferredBridgeName, apiUrl, log2);
32831
+ }
32832
+ };
32833
+ }
32834
+
32835
+ // src/auth/pending/connect-pending-auth.ts
32836
+ function connectPendingAuth(params) {
32837
+ const { session, apiUrl, initialWorkspaceId, preferredBridgeName, onAuth, log: log2 } = params;
32838
+ const connect = () => {
32839
+ session.ws = createWsBridge({
32840
+ url: buildPendingBridgeUrl(apiUrl, session.connectionId),
32841
+ deferInboundMessages: false,
32842
+ onOpen: createPendingAuthOnOpen({
32843
+ session,
32844
+ apiUrl,
32845
+ initialWorkspaceId,
32846
+ preferredBridgeName,
32847
+ log: log2
32848
+ }),
32849
+ onClose: createPendingAuthOnClose({ session, log: log2, connect }),
32850
+ onError: (err) => logCliWebSocketError(log2, "[Bridge service]", err, "while waiting for sign-in"),
32851
+ onMessage: createPendingAuthOnMessage({ session, onAuth })
32852
+ });
32853
+ };
32854
+ connect();
32855
+ }
32856
+
32857
+ // src/auth/pending/run-pending-auth.ts
32858
+ function runPendingAuth(options) {
32859
+ const { apiUrl, initialWorkspaceId, preferredBridgeName, onAuth } = options;
32860
+ const logFn = options.log ?? log;
32861
+ const session = createPendingAuthSession();
32862
+ session.browserFallback = setTimeout(() => {
32863
+ session.browserFallback = null;
32864
+ if (!session.hasOpenedBrowser) {
32865
+ session.hasOpenedBrowser = true;
32866
+ void openBrowser(session.connectionId, initialWorkspaceId, preferredBridgeName, apiUrl, logFn);
32811
32867
  }
32812
32868
  }, BROWSER_OPEN_FALLBACK_MS);
32813
- connect();
32869
+ connectPendingAuth({
32870
+ session,
32871
+ apiUrl,
32872
+ initialWorkspaceId,
32873
+ preferredBridgeName,
32874
+ onAuth,
32875
+ log: logFn
32876
+ });
32814
32877
  return {
32815
32878
  close: () => {
32816
- if (!resolved) resolveAuth(null);
32817
- cleanup();
32879
+ if (!session.resolved) session.resolveAuth(null);
32880
+ cleanupPendingAuthSession(session);
32818
32881
  },
32819
- authPromise
32882
+ authPromise: session.authPromise
32820
32883
  };
32821
32884
  }
32822
32885
 
@@ -35183,10 +35246,10 @@ async function killChildProcessTreeGracefully(child, graceMs = ACP_PROCESS_TREE_
35183
35246
  }
35184
35247
  await killProcessTree(pid, "SIGTERM");
35185
35248
  if (graceMs <= 0) return;
35186
- const exited = new Promise((resolve37) => {
35187
- child.once("exit", () => resolve37());
35249
+ const exited = new Promise((resolve38) => {
35250
+ child.once("exit", () => resolve38());
35188
35251
  });
35189
- await Promise.race([exited, new Promise((resolve37) => setTimeout(resolve37, graceMs))]);
35252
+ await Promise.race([exited, new Promise((resolve38) => setTimeout(resolve38, graceMs))]);
35190
35253
  if (child.exitCode == null && child.signalCode == null) {
35191
35254
  await killProcessTree(pid, "SIGKILL");
35192
35255
  }
@@ -35203,8 +35266,8 @@ async function gracefulAcpSubprocessDisconnect(params) {
35203
35266
  await transport.closeSession?.(sessionId);
35204
35267
  } catch {
35205
35268
  }
35206
- await new Promise((resolve37) => {
35207
- const timer = setTimeout(resolve37, ACP_GRACEFUL_SESSION_CLOSE_WAIT_MS);
35269
+ await new Promise((resolve38) => {
35270
+ const timer = setTimeout(resolve38, ACP_GRACEFUL_SESSION_CLOSE_WAIT_MS);
35208
35271
  timer.unref?.();
35209
35272
  });
35210
35273
  }
@@ -35479,11 +35542,11 @@ function createSdkStdioExtNotificationHandler(options) {
35479
35542
  // src/agents/acp/clients/sdk/sdk-stdio-permission-request-handshake.ts
35480
35543
  function awaitSdkStdioPermissionRequestHandshake(params) {
35481
35544
  const { requestId, paramsRecord, pending: pending2, onRequest } = params;
35482
- return new Promise((resolve37) => {
35483
- pending2.set(requestId, { resolve: resolve37, params: paramsRecord });
35545
+ return new Promise((resolve38) => {
35546
+ pending2.set(requestId, { resolve: resolve38, params: paramsRecord });
35484
35547
  if (onRequest == null) {
35485
35548
  pending2.delete(requestId);
35486
- resolve37({ outcome: { outcome: "denied" } });
35549
+ resolve38({ outcome: { outcome: "denied" } });
35487
35550
  return;
35488
35551
  }
35489
35552
  try {
@@ -35995,10 +36058,10 @@ function createSdkStdioInitSettle(child) {
35995
36058
  forceAcpSubprocessDisconnect(child);
35996
36059
  reject(err);
35997
36060
  },
35998
- settleResolve(resolve37, handle) {
36061
+ settleResolve(resolve38, handle) {
35999
36062
  if (initSettled) return;
36000
36063
  initSettled = true;
36001
- resolve37(handle);
36064
+ resolve38(handle);
36002
36065
  }
36003
36066
  };
36004
36067
  }
@@ -36087,7 +36150,7 @@ async function createSdkStdioAcpClient(options) {
36087
36150
  onFileChange,
36088
36151
  stderrCapture
36089
36152
  });
36090
- return new Promise((resolve37, reject) => {
36153
+ return new Promise((resolve38, reject) => {
36091
36154
  const init = createSdkStdioInitSettle(child);
36092
36155
  child.on("error", (err) => {
36093
36156
  init.settleReject(reject, new Error(formatSpawnError(err, command[0])));
@@ -36112,7 +36175,7 @@ async function createSdkStdioAcpClient(options) {
36112
36175
  protocolVersion: PROTOCOL_VERSION2
36113
36176
  });
36114
36177
  init.settleResolve(
36115
- resolve37,
36178
+ resolve38,
36116
36179
  createSdkStdioHandle({
36117
36180
  child,
36118
36181
  sessionId: established.sessionId,
@@ -36693,7 +36756,7 @@ async function createCursorAcpClient(options) {
36693
36756
  onFileChange,
36694
36757
  stderrCapture
36695
36758
  });
36696
- return new Promise((resolve37, reject) => {
36759
+ return new Promise((resolve38, reject) => {
36697
36760
  child.on("error", (err) => {
36698
36761
  killChildProcessTree(child, "SIGKILL");
36699
36762
  reject(new Error(formatSpawnError(err, command[0])));
@@ -36706,7 +36769,7 @@ async function createCursorAcpClient(options) {
36706
36769
  skipBrowserAuthenticate,
36707
36770
  incomingDeps: { dbgFs, sessionCtx, onSessionUpdate, onRequest }
36708
36771
  });
36709
- resolve37(
36772
+ resolve38(
36710
36773
  createCursorAcpHandle({
36711
36774
  child,
36712
36775
  sessionId: established.sessionId,
@@ -38145,8 +38208,8 @@ async function runGitTask(fn) {
38145
38208
  }
38146
38209
  async function yieldToEventLoop2() {
38147
38210
  throwIfGitShutdownRequested();
38148
- await new Promise((resolve37) => {
38149
- setImmediate(resolve37);
38211
+ await new Promise((resolve38) => {
38212
+ setImmediate(resolve38);
38150
38213
  });
38151
38214
  throwIfGitShutdownRequested();
38152
38215
  }
@@ -38183,8 +38246,8 @@ async function execGitFile(args, options) {
38183
38246
  }
38184
38247
 
38185
38248
  // src/git/changes/parse/normalize-git-diff-path.ts
38186
- function normalizeGitDiffPath(path86) {
38187
- return path86.replace(/\\/g, "/").replace(/\/ +/g, "/").trim();
38249
+ function normalizeGitDiffPath(path88) {
38250
+ return path88.replace(/\\/g, "/").replace(/\/ +/g, "/").trim();
38188
38251
  }
38189
38252
 
38190
38253
  // src/git/changes/parse/parse-name-status-entries.ts
@@ -39502,11 +39565,11 @@ function isServerNotRunningError(err) {
39502
39565
  }
39503
39566
  function closeHttpServer(server) {
39504
39567
  if (!server) return Promise.resolve();
39505
- return new Promise((resolve37) => {
39568
+ return new Promise((resolve38) => {
39506
39569
  server.close((err) => {
39507
39570
  if (err && !isServerNotRunningError(err)) {
39508
39571
  }
39509
- resolve37();
39572
+ resolve38();
39510
39573
  });
39511
39574
  });
39512
39575
  }
@@ -39519,7 +39582,7 @@ var RequestBodyTooLargeError = class extends Error {
39519
39582
  }
39520
39583
  };
39521
39584
  function readJsonBody(req) {
39522
- return new Promise((resolve37, reject) => {
39585
+ return new Promise((resolve38, reject) => {
39523
39586
  const chunks = [];
39524
39587
  let total = 0;
39525
39588
  let tooLarge = false;
@@ -39539,11 +39602,11 @@ function readJsonBody(req) {
39539
39602
  try {
39540
39603
  const raw = Buffer.concat(chunks).toString("utf8").trim();
39541
39604
  if (!raw) {
39542
- resolve37({});
39605
+ resolve38({});
39543
39606
  return;
39544
39607
  }
39545
39608
  const parsed = JSON.parse(raw);
39546
- resolve37(parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {});
39609
+ resolve38(parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {});
39547
39610
  } catch (e) {
39548
39611
  reject(e);
39549
39612
  }
@@ -39601,7 +39664,7 @@ function createBridgeAccessRequestHandler(registry2) {
39601
39664
  // src/mcp/bridge-access/start-server.ts
39602
39665
  function startBridgeAccessServer(registry2) {
39603
39666
  const server = http.createServer(createBridgeAccessRequestHandler(registry2));
39604
- return new Promise((resolve37, reject) => {
39667
+ return new Promise((resolve38, reject) => {
39605
39668
  server.once("error", reject);
39606
39669
  server.listen(0, "127.0.0.1", () => {
39607
39670
  const addr = server.address();
@@ -39609,7 +39672,7 @@ function startBridgeAccessServer(registry2) {
39609
39672
  reject(new Error("Bridge access server did not bind"));
39610
39673
  return;
39611
39674
  }
39612
- resolve37({
39675
+ resolve38({
39613
39676
  port: addr.port,
39614
39677
  close: () => closeHttpServer(server)
39615
39678
  });
@@ -41248,19 +41311,19 @@ function buildLocalHttpRequestOptions(built) {
41248
41311
  }
41249
41312
  function runLocalHttpRequestOnce(mod, built) {
41250
41313
  const opts = buildLocalHttpRequestOptions(built);
41251
- return new Promise((resolve37) => {
41314
+ return new Promise((resolve38) => {
41252
41315
  const req = mod.request(opts, (res) => {
41253
41316
  const chunks = [];
41254
41317
  res.on("data", (chunk) => chunks.push(chunk));
41255
41318
  res.on("end", () => {
41256
- resolve37({
41319
+ resolve38({
41257
41320
  statusCode: res.statusCode ?? 0,
41258
41321
  headers: incomingMessageHeaders(res),
41259
41322
  body: Buffer.concat(chunks)
41260
41323
  });
41261
41324
  });
41262
41325
  res.on("error", (err) => {
41263
- resolve37({
41326
+ resolve38({
41264
41327
  statusCode: 0,
41265
41328
  headers: {},
41266
41329
  body: Buffer.alloc(0),
@@ -41272,7 +41335,7 @@ function runLocalHttpRequestOnce(mod, built) {
41272
41335
  req.destroy(new Error(`Local preview request timed out after ${LOCAL_PROXY_REQUEST_TIMEOUT_MS}ms`));
41273
41336
  });
41274
41337
  req.on("error", (err) => {
41275
- resolve37({
41338
+ resolve38({
41276
41339
  statusCode: 0,
41277
41340
  headers: {},
41278
41341
  body: Buffer.alloc(0),
@@ -41296,14 +41359,14 @@ async function proxyToLocalStreaming(request, callbacks) {
41296
41359
  const isHttps = request.url.startsWith("https:");
41297
41360
  const mod = await loadHttpModule(isHttps);
41298
41361
  const opts = buildLocalHttpRequestOptions(built);
41299
- await new Promise((resolve37) => {
41362
+ await new Promise((resolve38) => {
41300
41363
  const req = mod.request(opts, (res) => {
41301
41364
  try {
41302
41365
  callbacks.onStart(res.statusCode ?? 0, incomingMessageHeaders(res));
41303
41366
  } catch (err) {
41304
41367
  req.destroy();
41305
41368
  callbacks.onError(err instanceof Error ? err.message : String(err));
41306
- resolve37();
41369
+ resolve38();
41307
41370
  return;
41308
41371
  }
41309
41372
  res.on("data", (chunk) => {
@@ -41316,11 +41379,11 @@ async function proxyToLocalStreaming(request, callbacks) {
41316
41379
  });
41317
41380
  res.on("end", () => {
41318
41381
  callbacks.onEnd();
41319
- resolve37();
41382
+ resolve38();
41320
41383
  });
41321
41384
  res.on("error", (err) => {
41322
41385
  callbacks.onError(err.message);
41323
- resolve37();
41386
+ resolve38();
41324
41387
  });
41325
41388
  });
41326
41389
  req.setTimeout(LOCAL_PROXY_REQUEST_TIMEOUT_MS, () => {
@@ -41328,7 +41391,7 @@ async function proxyToLocalStreaming(request, callbacks) {
41328
41391
  });
41329
41392
  req.on("error", (err) => {
41330
41393
  callbacks.onError(err.message);
41331
- resolve37();
41394
+ resolve38();
41332
41395
  });
41333
41396
  if (built.sendingBody && built.body != null) {
41334
41397
  req.write(built.body);
@@ -42452,8 +42515,8 @@ function pathspec(...paths) {
42452
42515
  cache.set(key, paths);
42453
42516
  return key;
42454
42517
  }
42455
- function isPathSpec(path86) {
42456
- return path86 instanceof String && cache.has(path86);
42518
+ function isPathSpec(path88) {
42519
+ return path88 instanceof String && cache.has(path88);
42457
42520
  }
42458
42521
  function toPaths(pathSpec) {
42459
42522
  return cache.get(pathSpec) || [];
@@ -42542,8 +42605,8 @@ function toLinesWithContent(input = "", trimmed2 = true, separator = "\n") {
42542
42605
  function forEachLineWithContent(input, callback) {
42543
42606
  return toLinesWithContent(input, true).map((line) => callback(line));
42544
42607
  }
42545
- function folderExists(path86) {
42546
- return (0, import_file_exists.exists)(path86, import_file_exists.FOLDER);
42608
+ function folderExists(path88) {
42609
+ return (0, import_file_exists.exists)(path88, import_file_exists.FOLDER);
42547
42610
  }
42548
42611
  function append(target, item) {
42549
42612
  if (Array.isArray(target)) {
@@ -42947,8 +43010,8 @@ function checkIsRepoRootTask() {
42947
43010
  commands,
42948
43011
  format: "utf-8",
42949
43012
  onError,
42950
- parser(path86) {
42951
- return /^\.(git)?$/.test(path86.trim());
43013
+ parser(path88) {
43014
+ return /^\.(git)?$/.test(path88.trim());
42952
43015
  }
42953
43016
  };
42954
43017
  }
@@ -43382,11 +43445,11 @@ function parseGrep(grep) {
43382
43445
  const paths = /* @__PURE__ */ new Set();
43383
43446
  const results = {};
43384
43447
  forEachLineWithContent(grep, (input) => {
43385
- const [path86, line, preview] = input.split(NULL);
43386
- paths.add(path86);
43387
- (results[path86] = results[path86] || []).push({
43448
+ const [path88, line, preview] = input.split(NULL);
43449
+ paths.add(path88);
43450
+ (results[path88] = results[path88] || []).push({
43388
43451
  line: asNumber(line),
43389
- path: path86,
43452
+ path: path88,
43390
43453
  preview
43391
43454
  });
43392
43455
  });
@@ -44151,14 +44214,14 @@ var init_hash_object = __esm2({
44151
44214
  init_task();
44152
44215
  }
44153
44216
  });
44154
- function parseInit(bare, path86, text) {
44217
+ function parseInit(bare, path88, text) {
44155
44218
  const response = String(text).trim();
44156
44219
  let result;
44157
44220
  if (result = initResponseRegex.exec(response)) {
44158
- return new InitSummary(bare, path86, false, result[1]);
44221
+ return new InitSummary(bare, path88, false, result[1]);
44159
44222
  }
44160
44223
  if (result = reInitResponseRegex.exec(response)) {
44161
- return new InitSummary(bare, path86, true, result[1]);
44224
+ return new InitSummary(bare, path88, true, result[1]);
44162
44225
  }
44163
44226
  let gitDir = "";
44164
44227
  const tokens = response.split(" ");
@@ -44169,7 +44232,7 @@ function parseInit(bare, path86, text) {
44169
44232
  break;
44170
44233
  }
44171
44234
  }
44172
- return new InitSummary(bare, path86, /^re/i.test(response), gitDir);
44235
+ return new InitSummary(bare, path88, /^re/i.test(response), gitDir);
44173
44236
  }
44174
44237
  var InitSummary;
44175
44238
  var initResponseRegex;
@@ -44178,9 +44241,9 @@ var init_InitSummary = __esm2({
44178
44241
  "src/lib/responses/InitSummary.ts"() {
44179
44242
  "use strict";
44180
44243
  InitSummary = class {
44181
- constructor(bare, path86, existing, gitDir) {
44244
+ constructor(bare, path88, existing, gitDir) {
44182
44245
  this.bare = bare;
44183
- this.path = path86;
44246
+ this.path = path88;
44184
44247
  this.existing = existing;
44185
44248
  this.gitDir = gitDir;
44186
44249
  }
@@ -44192,7 +44255,7 @@ var init_InitSummary = __esm2({
44192
44255
  function hasBareCommand(command) {
44193
44256
  return command.includes(bareCommand);
44194
44257
  }
44195
- function initTask(bare = false, path86, customArgs) {
44258
+ function initTask(bare = false, path88, customArgs) {
44196
44259
  const commands = ["init", ...customArgs];
44197
44260
  if (bare && !hasBareCommand(commands)) {
44198
44261
  commands.splice(1, 0, bareCommand);
@@ -44201,7 +44264,7 @@ function initTask(bare = false, path86, customArgs) {
44201
44264
  commands,
44202
44265
  format: "utf-8",
44203
44266
  parser(text) {
44204
- return parseInit(commands.includes("--bare"), path86, text);
44267
+ return parseInit(commands.includes("--bare"), path88, text);
44205
44268
  }
44206
44269
  };
44207
44270
  }
@@ -45017,12 +45080,12 @@ var init_FileStatusSummary = __esm2({
45017
45080
  "use strict";
45018
45081
  fromPathRegex = /^(.+)\0(.+)$/;
45019
45082
  FileStatusSummary = class {
45020
- constructor(path86, index, working_dir) {
45021
- this.path = path86;
45083
+ constructor(path88, index, working_dir) {
45084
+ this.path = path88;
45022
45085
  this.index = index;
45023
45086
  this.working_dir = working_dir;
45024
45087
  if (index === "R" || working_dir === "R") {
45025
- const detail = fromPathRegex.exec(path86) || [null, path86, path86];
45088
+ const detail = fromPathRegex.exec(path88) || [null, path88, path88];
45026
45089
  this.from = detail[2] || "";
45027
45090
  this.path = detail[1] || "";
45028
45091
  }
@@ -45053,14 +45116,14 @@ function splitLine(result, lineStr) {
45053
45116
  default:
45054
45117
  return;
45055
45118
  }
45056
- function data(index, workingDir, path86) {
45119
+ function data(index, workingDir, path88) {
45057
45120
  const raw = `${index}${workingDir}`;
45058
45121
  const handler = parsers6.get(raw);
45059
45122
  if (handler) {
45060
- handler(result, path86);
45123
+ handler(result, path88);
45061
45124
  }
45062
45125
  if (raw !== "##" && raw !== "!!") {
45063
- result.files.push(new FileStatusSummary(path86, index, workingDir));
45126
+ result.files.push(new FileStatusSummary(path88, index, workingDir));
45064
45127
  }
45065
45128
  }
45066
45129
  }
@@ -45369,9 +45432,9 @@ var init_simple_git_api = __esm2({
45369
45432
  next
45370
45433
  );
45371
45434
  }
45372
- hashObject(path86, write) {
45435
+ hashObject(path88, write) {
45373
45436
  return this._runTask(
45374
- hashObjectTask(path86, write === true),
45437
+ hashObjectTask(path88, write === true),
45375
45438
  trailingFunctionArgument(arguments)
45376
45439
  );
45377
45440
  }
@@ -45724,8 +45787,8 @@ var init_branch = __esm2({
45724
45787
  }
45725
45788
  });
45726
45789
  function toPath(input) {
45727
- const path86 = input.trim().replace(/^["']|["']$/g, "");
45728
- return path86 && normalize3(path86);
45790
+ const path88 = input.trim().replace(/^["']|["']$/g, "");
45791
+ return path88 && normalize3(path88);
45729
45792
  }
45730
45793
  var parseCheckIgnore;
45731
45794
  var init_CheckIgnore = __esm2({
@@ -46039,8 +46102,8 @@ __export2(sub_module_exports, {
46039
46102
  subModuleTask: () => subModuleTask,
46040
46103
  updateSubModuleTask: () => updateSubModuleTask
46041
46104
  });
46042
- function addSubModuleTask(repo, path86) {
46043
- return subModuleTask(["add", repo, path86]);
46105
+ function addSubModuleTask(repo, path88) {
46106
+ return subModuleTask(["add", repo, path88]);
46044
46107
  }
46045
46108
  function initSubModuleTask(customArgs) {
46046
46109
  return subModuleTask(["init", ...customArgs]);
@@ -46373,8 +46436,8 @@ var require_git = __commonJS2({
46373
46436
  }
46374
46437
  return this._runTask(straightThroughStringTask2(command, this._trimmed), next);
46375
46438
  };
46376
- Git2.prototype.submoduleAdd = function(repo, path86, then) {
46377
- return this._runTask(addSubModuleTask2(repo, path86), trailingFunctionArgument2(arguments));
46439
+ Git2.prototype.submoduleAdd = function(repo, path88, then) {
46440
+ return this._runTask(addSubModuleTask2(repo, path88), trailingFunctionArgument2(arguments));
46378
46441
  };
46379
46442
  Git2.prototype.submoduleUpdate = function(args, then) {
46380
46443
  return this._runTask(
@@ -47113,8 +47176,8 @@ function parseNumstatEntries(lines) {
47113
47176
  }
47114
47177
  function parseNumstat(lines) {
47115
47178
  const m = /* @__PURE__ */ new Map();
47116
- for (const [path86, entry] of parseNumstatEntries(lines)) {
47117
- m.set(path86, { additions: entry.additions, deletions: entry.deletions });
47179
+ for (const [path88, entry] of parseNumstatEntries(lines)) {
47180
+ m.set(path88, { additions: entry.additions, deletions: entry.deletions });
47118
47181
  }
47119
47182
  return m;
47120
47183
  }
@@ -51202,7 +51265,7 @@ init_symbol_index_file_ready();
51202
51265
  var CODE_NAV_INDEX_READY_WAIT_MS = 75;
51203
51266
  var CODE_NAV_INDEX_READY_POLL_MS = 15;
51204
51267
  function delay2(ms) {
51205
- return new Promise((resolve37) => setTimeout(resolve37, ms));
51268
+ return new Promise((resolve38) => setTimeout(resolve38, ms));
51206
51269
  }
51207
51270
  async function waitForSymbolIndexReady(sessionParentPath, reqPath, maxWaitMs = CODE_NAV_INDEX_READY_WAIT_MS) {
51208
51271
  const deadline = Date.now() + maxWaitMs;
@@ -51334,12 +51397,12 @@ function parseOptionalInt2(raw) {
51334
51397
  return Number.isInteger(parsed) ? parsed : void 0;
51335
51398
  }
51336
51399
  function parseCodeNavParams(url2) {
51337
- const path86 = url2.searchParams.get("path") ?? "";
51400
+ const path88 = url2.searchParams.get("path") ?? "";
51338
51401
  const opRaw = url2.searchParams.get("op")?.trim();
51339
51402
  const op = opRaw === "references" ? "references" : opRaw === "symbols" ? "symbols" : opRaw === "definitions" ? "definitions" : "definition";
51340
51403
  const line = parseOptionalInt2(url2.searchParams.get("line")) ?? 1;
51341
51404
  const column = parseOptionalInt2(url2.searchParams.get("column")) ?? 0;
51342
- return { path: path86, op, line, column };
51405
+ return { path: path88, op, line, column };
51343
51406
  }
51344
51407
  function parseCodeNavPath(url2) {
51345
51408
  const raw = url2.searchParams.get("path")?.trim();
@@ -51515,7 +51578,7 @@ function createLocalShortcutRequestHandler(ctx) {
51515
51578
  var RESTART_DELAY_MS = 250;
51516
51579
  var MAX_RESTART_ATTEMPTS = 5;
51517
51580
  function listenOnPort(server, port) {
51518
- return new Promise((resolve37, reject) => {
51581
+ return new Promise((resolve38, reject) => {
51519
51582
  server.once("error", reject);
51520
51583
  server.listen(port, "127.0.0.1", () => {
51521
51584
  const addr = server.address();
@@ -51523,12 +51586,12 @@ function listenOnPort(server, port) {
51523
51586
  reject(new Error("Local shortcut server did not bind"));
51524
51587
  return;
51525
51588
  }
51526
- resolve37(addr.port);
51589
+ resolve38(addr.port);
51527
51590
  });
51528
51591
  });
51529
51592
  }
51530
51593
  function delay3(ms) {
51531
- return new Promise((resolve37) => setTimeout(resolve37, ms));
51594
+ return new Promise((resolve38) => setTimeout(resolve38, ms));
51532
51595
  }
51533
51596
  function startLocalShortcutServer(ctx) {
51534
51597
  let closed = false;
@@ -51728,7 +51791,8 @@ var API_TO_BRIDGE_MESSAGE_TYPES = [
51728
51791
  "install_agent",
51729
51792
  "refresh_local_skills",
51730
51793
  "bridge_git_context_request",
51731
- "list_repo_branches_request"
51794
+ "list_repo_branches_request",
51795
+ "bridge_git_checkout_request"
51732
51796
  ];
51733
51797
  var API_TO_BRIDGE_TYPE_SET = new Set(API_TO_BRIDGE_MESSAGE_TYPES);
51734
51798
  function parseApiToBridgeMessage(data, log2) {
@@ -52421,10 +52485,10 @@ async function awaitGitStatePreparation(options) {
52421
52485
  try {
52422
52486
  return await Promise.race([
52423
52487
  work,
52424
- new Promise((resolve37) => {
52488
+ new Promise((resolve38) => {
52425
52489
  timer = setTimeout(() => {
52426
52490
  log2(`[Agent] ${label} exceeded ${timeoutMs}ms; continuing without it.`);
52427
- resolve37(fallback);
52491
+ resolve38(fallback);
52428
52492
  }, timeoutMs);
52429
52493
  timer.unref?.();
52430
52494
  })
@@ -52987,8 +53051,8 @@ function randomSecret() {
52987
53051
  }
52988
53052
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
52989
53053
  }
52990
- async function requestPreviewApi(port, secret, method, path86, body) {
52991
- const url2 = `http://127.0.0.1:${port}${path86}`;
53054
+ async function requestPreviewApi(port, secret, method, path88, body) {
53055
+ const url2 = `http://127.0.0.1:${port}${path88}`;
52992
53056
  const headers = {
52993
53057
  [PREVIEW_SECRET_HEADER]: secret,
52994
53058
  "Content-Type": "application/json"
@@ -53000,7 +53064,7 @@ async function requestPreviewApi(port, secret, method, path86, body) {
53000
53064
  });
53001
53065
  const data = await res.json().catch(() => ({}));
53002
53066
  if (!res.ok) {
53003
- throw new Error(data?.error ?? `Preview API ${method} ${path86}: ${res.status}`);
53067
+ throw new Error(data?.error ?? `Preview API ${method} ${path88}: ${res.status}`);
53004
53068
  }
53005
53069
  return data;
53006
53070
  }
@@ -53257,7 +53321,7 @@ var handleInstallSkillsMessage = (msg, deps) => {
53257
53321
  import { spawn as spawn11 } from "node:child_process";
53258
53322
  import * as readline3 from "node:readline";
53259
53323
  function runStreamingCommand(command, args, options) {
53260
- return new Promise((resolve37, reject) => {
53324
+ return new Promise((resolve38, reject) => {
53261
53325
  const child = spawn11(command, args, {
53262
53326
  env: options.env,
53263
53327
  stdio: ["ignore", "pipe", "pipe"]
@@ -53290,7 +53354,7 @@ function runStreamingCommand(command, args, options) {
53290
53354
  if (timer) clearTimeout(timer);
53291
53355
  if (!settled) {
53292
53356
  settled = true;
53293
- resolve37({ code, signal });
53357
+ resolve38({ code, signal });
53294
53358
  }
53295
53359
  });
53296
53360
  });
@@ -53729,6 +53793,23 @@ async function listRepoBranchRefs(repoPath) {
53729
53793
  }
53730
53794
  }
53731
53795
 
53796
+ // src/git/checkout/pending-checkouts.ts
53797
+ var pendingByRelPath = /* @__PURE__ */ new Map();
53798
+ function beginPendingCheckout(row) {
53799
+ const relPath = row.relPath.trim() || ".";
53800
+ pendingByRelPath.set(relPath, {
53801
+ relPath,
53802
+ folderName: row.folderName.trim() || (relPath === "." ? "repo" : relPath),
53803
+ remoteUrl: row.remoteUrl
53804
+ });
53805
+ }
53806
+ function endPendingCheckout(relPath) {
53807
+ pendingByRelPath.delete(relPath.trim() || ".");
53808
+ }
53809
+ function listPendingCheckouts() {
53810
+ return [...pendingByRelPath.values()];
53811
+ }
53812
+
53732
53813
  // src/git/bridge-git-context.ts
53733
53814
  function folderNameForRelPath(relPath, bridgeRoot) {
53734
53815
  if (relPath === "." || relPath === "") {
@@ -53765,7 +53846,23 @@ async function getBridgeGitContext(bridgeRoot = getBridgeRoot()) {
53765
53846
  relPath,
53766
53847
  folderName: folderNameForRelPath(relPath, bridgeResolved),
53767
53848
  currentBranch,
53768
- remoteUrl
53849
+ remoteUrl,
53850
+ cloning: false
53851
+ });
53852
+ }
53853
+ const seen = new Set(rows.map((r) => r.relPath));
53854
+ for (const pending2 of listPendingCheckouts()) {
53855
+ if (seen.has(pending2.relPath)) {
53856
+ const row = rows.find((r) => r.relPath === pending2.relPath);
53857
+ if (row) row.cloning = true;
53858
+ continue;
53859
+ }
53860
+ rows.push({
53861
+ relPath: pending2.relPath,
53862
+ folderName: pending2.folderName,
53863
+ currentBranch: null,
53864
+ remoteUrl: pending2.remoteUrl,
53865
+ cloning: true
53769
53866
  });
53770
53867
  }
53771
53868
  rows.sort((a, b) => a.relPath.localeCompare(b.relPath));
@@ -53825,6 +53922,143 @@ function handleListRepoBranchesRequestMessage(msg, getWs) {
53825
53922
  })();
53826
53923
  }
53827
53924
 
53925
+ // src/git/checkout/bridge-git-checkout.ts
53926
+ import * as fs65 from "node:fs/promises";
53927
+ import * as path86 from "node:path";
53928
+
53929
+ // src/git/checkout/normalize-clone-url.ts
53930
+ function normalizeCloneUrl(url2) {
53931
+ const u = url2.trim();
53932
+ if (!u.startsWith("http://") && !u.startsWith("https://")) {
53933
+ throw new Error("Only http(s) git remote URLs are supported");
53934
+ }
53935
+ return u.endsWith(".git") ? u : `${u}.git`;
53936
+ }
53937
+ function cloneUrlWithHttpsAuth(url2, auth) {
53938
+ const normalized = normalizeCloneUrl(url2);
53939
+ if (!auth) return normalized;
53940
+ const parsed = new URL(normalized);
53941
+ parsed.username = auth.username;
53942
+ parsed.password = auth.password;
53943
+ return parsed.toString();
53944
+ }
53945
+
53946
+ // src/git/checkout/resolve-checkout-target.ts
53947
+ import * as fs64 from "node:fs/promises";
53948
+ import * as path85 from "node:path";
53949
+ var FOLDER_NAME_RE = /^[A-Za-z0-9._-]+$/;
53950
+ async function pathExists(p) {
53951
+ try {
53952
+ await fs64.access(p);
53953
+ return true;
53954
+ } catch {
53955
+ return false;
53956
+ }
53957
+ }
53958
+ async function resolveCheckoutTarget(opts) {
53959
+ const bridgeRoot = getBridgeRoot();
53960
+ if (opts.layout === "monorepo") {
53961
+ if (await isGitRepoDirectory(bridgeRoot)) {
53962
+ throw new Error("Bridge root is already a git repository");
53963
+ }
53964
+ const entries = await fs64.readdir(bridgeRoot).catch(() => []);
53965
+ if (entries.length > 0) {
53966
+ throw new Error("Bridge root must be empty to initialize a monorepo checkout");
53967
+ }
53968
+ return { targetDir: bridgeRoot, relPath: "." };
53969
+ }
53970
+ const folder = (opts.folderName ?? "").trim();
53971
+ if (!folder || folder === "." || folder === ".." || !FOLDER_NAME_RE.test(folder)) {
53972
+ throw new Error("folderName must be a single path segment (letters, numbers, . _ -)");
53973
+ }
53974
+ if (await isGitRepoDirectory(bridgeRoot)) {
53975
+ throw new Error("Cannot add a nested repo while the bridge root is itself a git repository");
53976
+ }
53977
+ const targetDir = path85.resolve(bridgeRoot, folder);
53978
+ if (!targetDir.startsWith(bridgeRoot + path85.sep)) {
53979
+ throw new Error("Invalid folderName");
53980
+ }
53981
+ if (await pathExists(targetDir)) {
53982
+ throw new Error(`Folder already exists: ${folder}`);
53983
+ }
53984
+ return { targetDir, relPath: folder };
53985
+ }
53986
+
53987
+ // src/git/checkout/bridge-git-checkout.ts
53988
+ async function bridgeGitCheckout(params) {
53989
+ const cloneUrl = (params.cloneUrl ?? "").trim();
53990
+ if (!cloneUrl) throw new Error("cloneUrl required");
53991
+ const { targetDir, relPath } = await resolveCheckoutTarget({
53992
+ layout: params.layout,
53993
+ folderName: params.folderName
53994
+ });
53995
+ const folderName = relPath === "." ? "repo" : relPath;
53996
+ beginPendingCheckout({ relPath, folderName, remoteUrl: cloneUrl });
53997
+ const parent = path86.dirname(targetDir);
53998
+ await fs65.mkdir(parent, { recursive: true });
53999
+ if (relPath !== ".") {
54000
+ await fs65.mkdir(targetDir, { recursive: true });
54001
+ }
54002
+ const url2 = cloneUrlWithHttpsAuth(cloneUrl, params.auth ?? null);
54003
+ try {
54004
+ await execGitFile(["clone", "--", url2, targetDir], {
54005
+ cwd: parent,
54006
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }
54007
+ });
54008
+ return { relPath, folderName };
54009
+ } catch (e) {
54010
+ if (relPath !== ".") {
54011
+ await fs65.rm(targetDir, { recursive: true, force: true }).catch(() => void 0);
54012
+ }
54013
+ const msg = e instanceof Error ? e.message : String(e);
54014
+ throw new Error(
54015
+ msg.includes("Authentication") || msg.includes("403") || msg.includes("401") ? `Clone failed (auth?): ${msg}` : `Clone failed: ${msg}`
54016
+ );
54017
+ } finally {
54018
+ endPendingCheckout(relPath);
54019
+ }
54020
+ }
54021
+
54022
+ // src/routing/handlers/bridge-git-checkout-messages.ts
54023
+ function handleBridgeGitCheckoutRequestMessage(msg, getWs) {
54024
+ void (async () => {
54025
+ const socket = getWs();
54026
+ if (!socket) return;
54027
+ const layout = msg.layout === "multi_repo" ? "multi_repo" : msg.layout === "monorepo" ? "monorepo" : null;
54028
+ if (!layout) {
54029
+ sendWsMessage(socket, {
54030
+ type: "bridge_git_checkout_response",
54031
+ id: msg.id,
54032
+ error: "layout must be monorepo or multi_repo"
54033
+ });
54034
+ return;
54035
+ }
54036
+ try {
54037
+ const user = typeof msg.authUsername === "string" ? msg.authUsername : "";
54038
+ const pass = typeof msg.authPassword === "string" ? msg.authPassword : "";
54039
+ const result = await bridgeGitCheckout({
54040
+ layout,
54041
+ folderName: msg.folderName,
54042
+ cloneUrl: msg.cloneUrl ?? "",
54043
+ auth: user && pass ? { username: user, password: pass } : null
54044
+ });
54045
+ sendWsMessage(socket, {
54046
+ type: "bridge_git_checkout_response",
54047
+ id: msg.id,
54048
+ ok: true,
54049
+ relPath: result.relPath,
54050
+ folderName: result.folderName
54051
+ });
54052
+ } catch (e) {
54053
+ sendWsMessage(socket, {
54054
+ type: "bridge_git_checkout_response",
54055
+ id: msg.id,
54056
+ error: e instanceof Error ? e.message : String(e)
54057
+ });
54058
+ }
54059
+ })();
54060
+ }
54061
+
53828
54062
  // src/routing/dispatch/file-browser.ts
53829
54063
  function dispatchBridgeFileBrowserMessage(msg, deps) {
53830
54064
  switch (msg.type) {
@@ -53843,6 +54077,9 @@ function dispatchBridgeFileBrowserMessage(msg, deps) {
53843
54077
  case "list_repo_branches_request":
53844
54078
  handleListRepoBranchesRequestMessage(msg, deps.getWs);
53845
54079
  break;
54080
+ case "bridge_git_checkout_request":
54081
+ handleBridgeGitCheckoutRequestMessage(msg, deps.getWs);
54082
+ break;
53846
54083
  }
53847
54084
  }
53848
54085
 
@@ -53883,6 +54120,7 @@ function dispatchBridgeMessage(msg, deps) {
53883
54120
  case "code_nav":
53884
54121
  case "bridge_git_context_request":
53885
54122
  case "list_repo_branches_request":
54123
+ case "bridge_git_checkout_request":
53886
54124
  dispatchBridgeFileBrowserMessage(msg, deps);
53887
54125
  break;
53888
54126
  }
@@ -54266,32 +54504,42 @@ async function openE2eCertificateImportUrl({
54266
54504
  }
54267
54505
  }
54268
54506
 
54269
- // src/run-bridge-connected.ts
54507
+ // src/run-bridge-e2ee-key-command.ts
54508
+ function installConnectedBridgeE2eeKeyCommand(params) {
54509
+ let openingCertificate = false;
54510
+ return installE2eCertificateKeyCommand({
54511
+ log: params.log,
54512
+ onInterrupt: params.onInterrupt,
54513
+ onOpenCertificate: () => {
54514
+ if (openingCertificate) return;
54515
+ openingCertificate = true;
54516
+ void openE2eCertificateImportUrl({
54517
+ apiUrl: params.apiUrl,
54518
+ workspaceId: params.workspaceId,
54519
+ certificate: params.e2eCertificate,
54520
+ log: params.log
54521
+ }).finally(() => {
54522
+ openingCertificate = false;
54523
+ });
54524
+ }
54525
+ });
54526
+ }
54527
+
54528
+ // src/run-bridge-connected-signals.ts
54529
+ init_log();
54270
54530
  init_cli_process_interrupt();
54271
- init_cli_database();
54272
- async function runConnectedBridge(options, restartWithoutAuth) {
54273
- const {
54274
- apiUrl,
54275
- workspaceId,
54276
- authToken,
54277
- refreshToken,
54278
- justAuthenticated,
54279
- worktreesRootPath,
54280
- e2eCertificate
54281
- } = options;
54282
- const firehoseServerUrl = options.firehoseServerUrl ?? options.proxyServerUrl;
54283
- let cleanupKeyCommand;
54284
- let bridgeClose = null;
54531
+ function installConnectedBridgeSignals(params) {
54285
54532
  let shutdownStarted = false;
54286
54533
  const onSignal = (kind) => {
54287
54534
  requestCliImmediateShutdown();
54288
54535
  abortActiveGitChildProcesses();
54289
- cleanupKeyCommand?.();
54536
+ params.cleanupKeyCommand();
54290
54537
  if (shutdownStarted) return;
54291
54538
  shutdownStarted = true;
54292
54539
  logImmediate(
54293
54540
  kind === "interrupt" ? "Keyboard interrupt (Ctrl+C) \u2014 stopping\u2026" : "Stop requested \u2014 shutting down\u2026"
54294
54541
  );
54542
+ const bridgeClose = params.getBridgeClose();
54295
54543
  if (bridgeClose) {
54296
54544
  void bridgeClose().finally(() => process.exit(0));
54297
54545
  return;
@@ -54302,9 +54550,56 @@ async function runConnectedBridge(options, restartWithoutAuth) {
54302
54550
  const onSigTerm = () => onSignal("stop");
54303
54551
  process.on("SIGINT", onSigInt);
54304
54552
  process.on("SIGTERM", onSigTerm);
54305
- let handle;
54553
+ return {
54554
+ onSigInt,
54555
+ remove: () => {
54556
+ process.off("SIGINT", onSigInt);
54557
+ process.off("SIGTERM", onSigTerm);
54558
+ }
54559
+ };
54560
+ }
54561
+
54562
+ // src/run-bridge-on-auth-invalid.ts
54563
+ init_cli_process_interrupt();
54564
+ async function closeBridgeForReauth(params) {
54565
+ params.log("[Bridge service] Access token invalid or revoked; re-authenticating\u2026");
54566
+ clearConfigForApi(params.apiUrl);
54567
+ await params.close();
54568
+ params.removeSignalHandlers();
54569
+ await clearCliImmediateShutdown();
54570
+ params.endConnectedSession();
54571
+ }
54572
+
54573
+ // src/run-bridge-connected.ts
54574
+ init_cli_database();
54575
+ async function runConnectedBridge(options, restartWithoutAuth) {
54576
+ const {
54577
+ apiUrl,
54578
+ workspaceId,
54579
+ authToken,
54580
+ refreshToken,
54581
+ justAuthenticated,
54582
+ worktreesRootPath,
54583
+ e2eCertificate
54584
+ } = options;
54585
+ const firehoseServerUrl = options.firehoseServerUrl ?? options.proxyServerUrl;
54586
+ let cleanupKeyCommand;
54587
+ let bridgeClose = null;
54588
+ let endConnectedSession;
54589
+ const sessionDone = new Promise((resolve38) => {
54590
+ endConnectedSession = resolve38;
54591
+ });
54592
+ let resolveHandleReady;
54593
+ const handleReady = new Promise((resolve38) => {
54594
+ resolveHandleReady = resolve38;
54595
+ });
54596
+ const handleRef = { current: null };
54597
+ const signals = installConnectedBridgeSignals({
54598
+ getBridgeClose: () => bridgeClose,
54599
+ cleanupKeyCommand: () => cleanupKeyCommand?.()
54600
+ });
54306
54601
  try {
54307
- handle = await createBridgeConnection({
54602
+ const handle = await createBridgeConnection({
54308
54603
  apiUrl,
54309
54604
  workspaceId,
54310
54605
  authToken,
@@ -54323,41 +54618,40 @@ async function runConnectedBridge(options, restartWithoutAuth) {
54323
54618
  },
54324
54619
  onAuthInvalid: () => {
54325
54620
  cleanupKeyCommand?.();
54326
- log("[Bridge service] Access token invalid or revoked; re-authenticating\u2026");
54327
- clearConfigForApi(apiUrl);
54328
- void handle.close().then(() => {
54329
- void restartWithoutAuth({ apiUrl, firehoseServerUrl, worktreesRootPath, e2eCertificate });
54330
- });
54621
+ void (async () => {
54622
+ await handleReady;
54623
+ await closeBridgeForReauth({
54624
+ apiUrl,
54625
+ log,
54626
+ close: async () => {
54627
+ if (handleRef.current) await handleRef.current.close();
54628
+ },
54629
+ removeSignalHandlers: signals.remove,
54630
+ endConnectedSession
54631
+ });
54632
+ })();
54331
54633
  }
54332
54634
  });
54333
- } catch (e) {
54334
- process.off("SIGINT", onSigInt);
54335
- process.off("SIGTERM", onSigTerm);
54336
- if (e instanceof CliSqliteInterrupted) {
54337
- process.exit(0);
54635
+ handleRef.current = handle;
54636
+ bridgeClose = () => handle.close();
54637
+ if (e2eCertificate) {
54638
+ cleanupKeyCommand = installConnectedBridgeE2eeKeyCommand({
54639
+ apiUrl,
54640
+ workspaceId,
54641
+ e2eCertificate,
54642
+ log,
54643
+ onInterrupt: signals.onSigInt
54644
+ });
54338
54645
  }
54646
+ } catch (e) {
54647
+ signals.remove();
54648
+ if (e instanceof CliSqliteInterrupted) process.exit(0);
54339
54649
  throw e;
54650
+ } finally {
54651
+ resolveHandleReady();
54340
54652
  }
54341
- bridgeClose = () => handle.close();
54342
- if (e2eCertificate) {
54343
- let openingCertificate = false;
54344
- cleanupKeyCommand = installE2eCertificateKeyCommand({
54345
- log,
54346
- onInterrupt: onSigInt,
54347
- onOpenCertificate: () => {
54348
- if (openingCertificate) return;
54349
- openingCertificate = true;
54350
- void openE2eCertificateImportUrl({
54351
- apiUrl,
54352
- workspaceId,
54353
- certificate: e2eCertificate,
54354
- log
54355
- }).finally(() => {
54356
- openingCertificate = false;
54357
- });
54358
- }
54359
- });
54360
- }
54653
+ await sessionDone;
54654
+ await restartWithoutAuth({ apiUrl, firehoseServerUrl, worktreesRootPath, e2eCertificate });
54361
54655
  }
54362
54656
 
54363
54657
  // src/run-bridge.ts
@@ -54401,12 +54695,16 @@ async function runBridge(options) {
54401
54695
  process.off("SIGINT", onSigInt);
54402
54696
  process.off("SIGTERM", onSigTerm);
54403
54697
  handle.close();
54404
- if (!auth) return;
54698
+ if (!auth) {
54699
+ log("Sign-in ended before a token was received.");
54700
+ return;
54701
+ }
54405
54702
  writeConfigForApi(apiUrl, {
54406
54703
  workspaceId: auth.workspaceId,
54407
54704
  token: auth.token,
54408
54705
  refreshToken: auth.refreshToken
54409
54706
  });
54707
+ log("Link established. Connecting with the new token\u2026");
54410
54708
  await runBridge({
54411
54709
  apiUrl,
54412
54710
  workspaceId: auth.workspaceId,
@@ -54444,9 +54742,9 @@ async function runCliAction(program2, opts) {
54444
54742
  const firehoseServerUrl = opts.firehoseUrl ?? opts.proxyUrl ?? process.env.BUILDAUTOMATON_FIREHOSE_URL ?? process.env.BUILDAUTOMATON_PROXY_URL ?? DEFAULT_FIREHOSE_URL;
54445
54743
  const bridgeRootOpt = (opts.bridgeRoot && typeof opts.bridgeRoot === "string" && opts.bridgeRoot.trim() ? opts.bridgeRoot.trim() : null) ?? (opts.cwd && typeof opts.cwd === "string" && opts.cwd.trim() ? opts.cwd.trim() : null);
54446
54744
  if (bridgeRootOpt) {
54447
- const resolvedBridgeRoot = path85.resolve(process.cwd(), bridgeRootOpt);
54745
+ const resolvedBridgeRoot = path87.resolve(process.cwd(), bridgeRootOpt);
54448
54746
  try {
54449
- const st = fs64.statSync(resolvedBridgeRoot);
54747
+ const st = fs66.statSync(resolvedBridgeRoot);
54450
54748
  if (!st.isDirectory()) {
54451
54749
  console.error(`Bridge root is not a directory: ${resolvedBridgeRoot}`);
54452
54750
  process.exit(1);
@@ -54466,7 +54764,7 @@ async function runCliAction(program2, opts) {
54466
54764
  );
54467
54765
  let worktreesRootPath;
54468
54766
  if (opts.worktreesRoot && opts.worktreesRoot.trim()) {
54469
- worktreesRootPath = path85.resolve(opts.worktreesRoot.trim());
54767
+ worktreesRootPath = path87.resolve(opts.worktreesRoot.trim());
54470
54768
  }
54471
54769
  const e2eCertificates = opts.e2eeCertificatesDir?.trim() ? await loadOrCreateE2eCertificates(opts.e2eeCertificatesDir.trim()) : void 0;
54472
54770
  if (e2eCertificates) {