revdeck 0.16.1 → 0.18.0

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/daemon.js CHANGED
@@ -138,7 +138,7 @@ var init_errors = __esm({
138
138
  // src/core/exec.ts
139
139
  import { execFile } from "node:child_process";
140
140
  import { access, constants as constants2 } from "node:fs/promises";
141
- import os2 from "node:os";
141
+ import os3 from "node:os";
142
142
  import path3 from "node:path";
143
143
  function scrubEnv(extra) {
144
144
  const env = {};
@@ -170,10 +170,10 @@ async function resolveExecutable(command) {
170
170
  if (cached) return cached;
171
171
  const dirs = [
172
172
  ...(process.env.PATH ?? "").split(path3.delimiter),
173
- path3.join(os2.homedir(), ".local", "bin"),
174
- path3.join(os2.homedir(), ".local", "share", "mise", "shims"),
175
- path3.join(os2.homedir(), ".asdf", "shims"),
176
- path3.join(os2.homedir(), ".npm-global", "bin"),
173
+ path3.join(os3.homedir(), ".local", "bin"),
174
+ path3.join(os3.homedir(), ".local", "share", "mise", "shims"),
175
+ path3.join(os3.homedir(), ".asdf", "shims"),
176
+ path3.join(os3.homedir(), ".npm-global", "bin"),
177
177
  "/opt/homebrew/bin",
178
178
  "/usr/local/bin",
179
179
  "/usr/bin",
@@ -419,11 +419,11 @@ function diffStats(files) {
419
419
  function changedPaths(files) {
420
420
  return files.map((file) => file.path);
421
421
  }
422
- function findFile(files, path12) {
423
- return files.find((file) => file.path === path12) ?? files.find((file) => file.oldPath === path12);
422
+ function findFile(files, path13) {
423
+ return files.find((file) => file.path === path13) ?? files.find((file) => file.oldPath === path13);
424
424
  }
425
- function findNewLine(files, path12, line) {
426
- const file = findFile(files, path12);
425
+ function findNewLine(files, path13, line) {
426
+ const file = findFile(files, path13);
427
427
  if (!file) return void 0;
428
428
  for (const hunk of file.hunks) {
429
429
  for (const item of hunk.lines) {
@@ -432,8 +432,8 @@ function findNewLine(files, path12, line) {
432
432
  }
433
433
  return void 0;
434
434
  }
435
- function snippetAround(files, path12, line, radius = 6) {
436
- const file = findFile(files, path12);
435
+ function snippetAround(files, path13, line, radius = 6) {
436
+ const file = findFile(files, path13);
437
437
  if (!file || line == null) return null;
438
438
  const flat = file.hunks.flatMap((hunk) => hunk.lines);
439
439
  const target = flat.findIndex((item) => item.newLine === line);
@@ -451,11 +451,11 @@ function snippetAt(flat, target, line, radius) {
451
451
  }
452
452
  function createSnippetReader(files) {
453
453
  const cache = /* @__PURE__ */ new Map();
454
- return (path12, line, radius = 6) => {
454
+ return (path13, line, radius = 6) => {
455
455
  if (line == null) return null;
456
- let entry = cache.get(path12);
456
+ let entry = cache.get(path13);
457
457
  if (entry === void 0) {
458
- const file = findFile(files, path12);
458
+ const file = findFile(files, path13);
459
459
  if (!file) {
460
460
  entry = null;
461
461
  } else {
@@ -467,7 +467,7 @@ function createSnippetReader(files) {
467
467
  }
468
468
  entry = { flat, byNewLine };
469
469
  }
470
- cache.set(path12, entry);
470
+ cache.set(path13, entry);
471
471
  }
472
472
  if (!entry) return null;
473
473
  const target = entry.byNewLine.get(line);
@@ -475,9 +475,9 @@ function createSnippetReader(files) {
475
475
  return snippetAt(entry.flat, target, line, radius);
476
476
  };
477
477
  }
478
- function linePosition(files, path12, line) {
479
- const file = findFile(files, path12);
480
- const found = findNewLine(files, path12, line);
478
+ function linePosition(files, path13, line) {
479
+ const file = findFile(files, path13);
480
+ const found = findNewLine(files, path13, line);
481
481
  if (!file || !found) return null;
482
482
  return { newPath: file.path, newLine: line, oldPath: file.oldPath, oldLine: found.kind === " " ? found.oldLine : null };
483
483
  }
@@ -518,7 +518,8 @@ function cliError(error, platform, host) {
518
518
  );
519
519
  }
520
520
  if (/(auth|unauthor|401|403|not logged|token|credential|forbidden)/.test(lower)) {
521
- const hint = platform === "gitlab" ? tr(`\u0432\u043E\u0439\u0434\u0438\u0442\u0435 \u0432 glab \u043D\u0430 \u044D\u0442\u043E\u043C \u0445\u043E\u0441\u0442\u0435: glab auth login --hostname ${host}`, `log in to glab for this host: glab auth login --hostname ${host}`) : tr(`\u0432\u043E\u0439\u0434\u0438\u0442\u0435 \u0432 gh: GH_HOST=${host} gh auth login`, `log in to gh: GH_HOST=${host} gh auth login`);
521
+ const login = platform === "gitlab" ? tr(`\u0432\u043E\u0439\u0434\u0438\u0442\u0435 \u0432 glab \u043D\u0430 \u044D\u0442\u043E\u043C \u0445\u043E\u0441\u0442\u0435: glab auth login --hostname ${host}`, `log in to glab for this host: glab auth login --hostname ${host}`) : tr(`\u0432\u043E\u0439\u0434\u0438\u0442\u0435 \u0432 gh: GH_HOST=${host} gh auth login`, `log in to gh: GH_HOST=${host} gh auth login`);
522
+ const hint = `${login}; ${tr("\u0438\u043B\u0438 \u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u0442\u043E\u043A\u0435\u043D \u0432 UI: \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u2192 \u0414\u043E\u0441\u0442\u0443\u043F", "or paste a token in the UI: Settings \u2192 Access")}`;
522
523
  throw new AuthError(`${platform}: ${message || tr("\u043D\u0435\u0442 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0430\u0446\u0438\u0438", "not authenticated")}`, hint);
523
524
  }
524
525
  if (/(not found|404)/.test(lower)) throw new ProviderError(`${platform}: ${message}`, tr("\u043F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u043D\u043E\u043C\u0435\u0440 \u0440\u0435\u0432\u044C\u044E \u0438 \u0434\u043E\u0441\u0442\u0443\u043F \u043A \u043F\u0440\u043E\u0435\u043A\u0442\u0443", "check the review number and project access"));
@@ -534,8 +535,8 @@ async function withTempJson(data, fn) {
534
535
  await rm(dir, { recursive: true, force: true });
535
536
  }
536
537
  }
537
- function query(path12, params) {
538
- const url = new URL(path12.startsWith("/") ? path12 : `/${path12}`, "http://local");
538
+ function query(path13, params) {
539
+ const url = new URL(path13.startsWith("/") ? path13 : `/${path13}`, "http://local");
539
540
  for (const [key, value] of Object.entries(params)) {
540
541
  if (value !== void 0 && value !== "") url.searchParams.set(key, String(value));
541
542
  }
@@ -698,8 +699,8 @@ rename to ${newPath}
698
699
  }
699
700
  return parseUnifiedDiff(chunks.join("\n"));
700
701
  }
701
- async fileContent(path12, ref) {
702
- const endpoint = `projects/${this.projectRef}/repository/files/${encodeURIComponent(path12)}/raw`;
702
+ async fileContent(path13, ref) {
703
+ const endpoint = `projects/${this.projectRef}/repository/files/${encodeURIComponent(path13)}/raw`;
703
704
  return this.call([query(endpoint, { ref })]);
704
705
  }
705
706
  async readiness() {
@@ -1104,8 +1105,8 @@ rename to ${newPath}
1104
1105
  }
1105
1106
  return parseUnifiedDiff(chunks.join("\n"));
1106
1107
  }
1107
- async fileContent(path12, ref) {
1108
- const encoded = path12.split("/").map(encodeURIComponent).join("/");
1108
+ async fileContent(path13, ref) {
1109
+ const encoded = path13.split("/").map(encodeURIComponent).join("/");
1109
1110
  return this.call(["-H", "Accept: application/vnd.github.raw", query(`repos/${this.repo}/contents/${encoded}`, { ref })]);
1110
1111
  }
1111
1112
  async readiness() {
@@ -1340,9 +1341,9 @@ rename to ${newPath}
1340
1341
 
1341
1342
  // src/daemon/main.ts
1342
1343
  import { existsSync as existsSync5, readFileSync } from "node:fs";
1343
- import { appendFile, open as open2, readFile as readFile3, unlink as unlink4 } from "node:fs/promises";
1344
+ import { appendFile, open as open2, readFile as readFile4, rename as rename2, stat as stat3, unlink as unlink4 } from "node:fs/promises";
1344
1345
  import net2 from "node:net";
1345
- import path11 from "node:path";
1346
+ import path12 from "node:path";
1346
1347
  import { fileURLToPath } from "node:url";
1347
1348
  import { parseArgs } from "node:util";
1348
1349
 
@@ -1499,12 +1500,85 @@ async function writeFileAtomic(file, data, mode = 384, dirMode = 448) {
1499
1500
  init_redact();
1500
1501
 
1501
1502
  // src/version.ts
1502
- var VERSION = "0.16.1";
1503
+ var VERSION = "0.18.0";
1503
1504
  var PROTOCOL_VERSION = 2;
1504
1505
 
1505
1506
  // src/daemon/main.ts
1506
1507
  init_locale();
1507
1508
 
1509
+ // src/cli/report.ts
1510
+ init_locale();
1511
+ import os2 from "node:os";
1512
+ function createPalette(stream) {
1513
+ const enabled = (() => {
1514
+ if (process.env.NO_COLOR) return false;
1515
+ const force = process.env.FORCE_COLOR;
1516
+ if (force === "0") return false;
1517
+ if (force !== void 0 && force !== "") return true;
1518
+ return Boolean(stream.isTTY) && process.env.TERM !== "dumb";
1519
+ })();
1520
+ const wrap = (open3, close) => (text2) => enabled ? `\x1B[${open3}m${text2}\x1B[${close}m` : text2;
1521
+ return {
1522
+ enabled,
1523
+ bold: wrap("1", "22"),
1524
+ dim: wrap("2", "22"),
1525
+ red: wrap("31", "39"),
1526
+ green: wrap("32", "39"),
1527
+ yellow: wrap("33", "39"),
1528
+ blue: wrap("34", "39"),
1529
+ magenta: wrap("35", "39"),
1530
+ cyan: wrap("36", "39"),
1531
+ link: (text2) => enabled ? `\x1B[4;34m${text2}\x1B[0m` : text2
1532
+ };
1533
+ }
1534
+ var colors = createPalette(process.stdout);
1535
+ var errorColors = createPalette(process.stderr);
1536
+ function tildify(value, home = os2.homedir()) {
1537
+ if (!value || !home) return value;
1538
+ const prefix = home.replace(/[\\/]+$/, "");
1539
+ if (value === prefix) return "~";
1540
+ if (value.startsWith(`${prefix}/`) || value.startsWith(`${prefix}\\`)) return `~${value.slice(prefix.length)}`;
1541
+ return value;
1542
+ }
1543
+ function padEnd(value, width) {
1544
+ const length = [...value].length;
1545
+ return length >= width ? value : value + " ".repeat(width - length);
1546
+ }
1547
+ function rows(fields) {
1548
+ const width = Math.max(...fields.map(([label]) => [...label].length));
1549
+ return fields.map(([label, value]) => ` ${colors.dim(padEnd(label, width))} ${value}`);
1550
+ }
1551
+ function startTitle(mode) {
1552
+ if (mode === "restarted") return tr("\u0414\u0435\u043C\u043E\u043D \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0449\u0435\u043D", "Daemon restarted");
1553
+ if (mode === "running") return tr("\u0414\u0435\u043C\u043E\u043D \u0443\u0436\u0435 \u0440\u0430\u0431\u043E\u0442\u0430\u0435\u0442", "Daemon already running");
1554
+ return tr("\u0414\u0435\u043C\u043E\u043D \u0437\u0430\u043F\u0443\u0449\u0435\u043D", "Daemon started");
1555
+ }
1556
+ var START_FOOTER = () => ` ${colors.dim(tr("\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441:", "Open the UI:"))} ${colors.cyan("revdeck ui --open")}`;
1557
+ function daemonStartedLines(view, mode = "started") {
1558
+ return [
1559
+ "",
1560
+ ` ${colors.dim("revdeck")} ${colors.dim(view.version)}`,
1561
+ "",
1562
+ ` ${colors.green("\u25CF")} ${colors.bold(startTitle(mode))} ${colors.dim(`\xB7 pid ${view.pid}`)}`,
1563
+ "",
1564
+ ...rows([
1565
+ [tr("\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441", "ui"), colors.link(view.url)],
1566
+ [tr("\u0441\u043E\u043A\u0435\u0442", "socket"), colors.dim(tildify(view.socket))],
1567
+ [tr("\u0434\u0430\u043D\u043D\u044B\u0435", "state"), colors.dim(tildify(view.stateDir))],
1568
+ [tr("\u043B\u043E\u0433", "log"), colors.dim(tildify(view.logPath))]
1569
+ ]),
1570
+ "",
1571
+ START_FOOTER(),
1572
+ ""
1573
+ ];
1574
+ }
1575
+ function errorLine(message, hint) {
1576
+ return [
1577
+ `${errorColors.red("revdeck:")} ${message}`,
1578
+ ...hint ? [` ${errorColors.dim(hint)}`] : []
1579
+ ];
1580
+ }
1581
+
1508
1582
  // src/daemon/store.ts
1509
1583
  import { DatabaseSync } from "node:sqlite";
1510
1584
  import { mkdirSync } from "node:fs";
@@ -1807,6 +1881,11 @@ var Store = class {
1807
1881
  created_at TEXT NOT NULL
1808
1882
  );
1809
1883
  CREATE INDEX IF NOT EXISTS review_versions_review ON review_versions(review_id, created_at);
1884
+ CREATE TABLE IF NOT EXISTS ui_settings (
1885
+ key TEXT PRIMARY KEY,
1886
+ value_json TEXT NOT NULL,
1887
+ updated_at TEXT NOT NULL
1888
+ );
1810
1889
  `);
1811
1890
  const findingColumns = this.db.prepare("PRAGMA table_info(findings)").all();
1812
1891
  if (!findingColumns.some((column) => text(column, "name") === "agent_note")) {
@@ -1936,7 +2015,7 @@ var Store = class {
1936
2015
  return key;
1937
2016
  }
1938
2017
  listProjects() {
1939
- const rows = this.db.prepare(
2018
+ const rows2 = this.db.prepare(
1940
2019
  `SELECT p.*,
1941
2020
  (SELECT COUNT(*) FROM reviews r WHERE r.project_key = p.key) AS reviews,
1942
2021
  (SELECT MAX(r.synced_at) FROM reviews r WHERE r.project_key = p.key) AS last_activity
@@ -1951,7 +2030,7 @@ var Store = class {
1951
2030
  list.push(text(row, "root"));
1952
2031
  rootsByProject.set(key, list);
1953
2032
  }
1954
- return rows.map((row) => {
2033
+ return rows2.map((row) => {
1955
2034
  const key = text(row, "key");
1956
2035
  return {
1957
2036
  key,
@@ -1970,6 +2049,36 @@ var Store = class {
1970
2049
  getProject(key) {
1971
2050
  return this.listProjects().find((project) => project.key === key) ?? null;
1972
2051
  }
2052
+ /**
2053
+ * Настройки UI. Порт обычно переиспользуется, но может смениться (занят,
2054
+ * --port, смена хоста), поэтому localStorage в браузере привязан к origin и
2055
+ * после перезапуска может быть пуст: надёжное место — база на хосте.
2056
+ */
2057
+ uiSettings() {
2058
+ const rows2 = this.db.prepare("SELECT key, value_json FROM ui_settings ORDER BY key").all();
2059
+ const settings = {};
2060
+ for (const row of rows2) {
2061
+ try {
2062
+ settings[text(row, "key")] = JSON.parse(text(row, "value_json"));
2063
+ } catch {
2064
+ }
2065
+ }
2066
+ return settings;
2067
+ }
2068
+ updateUiSettings(patch, now = (/* @__PURE__ */ new Date()).toISOString()) {
2069
+ const upsert = this.db.prepare(
2070
+ `INSERT INTO ui_settings (key, value_json, updated_at) VALUES (?, ?, ?)
2071
+ ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json, updated_at = excluded.updated_at`
2072
+ );
2073
+ this.transaction(() => {
2074
+ for (const [key, value] of Object.entries(patch)) {
2075
+ const json2 = JSON.stringify(value);
2076
+ if (json2 === void 0) continue;
2077
+ upsert.run(key, json2, now);
2078
+ }
2079
+ });
2080
+ return this.uiSettings();
2081
+ }
1973
2082
  /** Переименование проекта и явное управление root'ами рабочих копий. */
1974
2083
  updateProject(key, patch, now = (/* @__PURE__ */ new Date()).toISOString()) {
1975
2084
  const current2 = this.getProject(key);
@@ -2001,14 +2110,14 @@ var Store = class {
2001
2110
  }
2002
2111
  // ---------------------------------------------------------------- features
2003
2112
  featureMembers(id) {
2004
- const rows = this.db.prepare(
2113
+ const rows2 = this.db.prepare(
2005
2114
  `SELECT fr.role, fr.sort_order, fr.added_at, r.*
2006
2115
  FROM feature_reviews fr
2007
2116
  JOIN reviews r ON r.id = fr.review_id
2008
2117
  WHERE fr.feature_id = ?
2009
2118
  ORDER BY fr.sort_order ASC, fr.added_at ASC, r.number ASC`
2010
2119
  ).all(id);
2011
- return rows.map((row) => ({
2120
+ return rows2.map((row) => ({
2012
2121
  review: reviewItem(row),
2013
2122
  role: text(row, "role"),
2014
2123
  sortOrder: Number(row.sort_order),
@@ -2048,12 +2157,12 @@ var Store = class {
2048
2157
  clauses.push("EXISTS (SELECT 1 FROM feature_reviews fr JOIN reviews r ON r.id = fr.review_id WHERE fr.feature_id = f.id AND r.project_key = ?)");
2049
2158
  args.push(project);
2050
2159
  }
2051
- const rows = this.db.prepare(`SELECT f.* FROM features f WHERE ${clauses.join(" AND ")} ORDER BY f.updated_at DESC, f.title ASC`).all(...args);
2052
- return rows.map((row) => this.featureSummary(row, this.featureMembers(text(row, "id"))));
2160
+ const rows2 = this.db.prepare(`SELECT f.* FROM features f WHERE ${clauses.join(" AND ")} ORDER BY f.updated_at DESC, f.title ASC`).all(...args);
2161
+ return rows2.map((row) => this.featureSummary(row, this.featureMembers(text(row, "id"))));
2053
2162
  }
2054
2163
  featureNotes(featureId) {
2055
- const rows = this.db.prepare("SELECT * FROM feature_notes WHERE feature_id = ? ORDER BY created_at ASC, rowid ASC").all(featureId);
2056
- return rows.map((row) => ({
2164
+ const rows2 = this.db.prepare("SELECT * FROM feature_notes WHERE feature_id = ? ORDER BY created_at ASC, rowid ASC").all(featureId);
2165
+ return rows2.map((row) => ({
2057
2166
  id: text(row, "id"),
2058
2167
  featureId: text(row, "feature_id"),
2059
2168
  kind: text(row, "kind") === "finding" ? "finding" : "note",
@@ -2105,13 +2214,13 @@ var Store = class {
2105
2214
  this.touchFeature(featureId, now);
2106
2215
  }
2107
2216
  featuresForReview(reviewId2) {
2108
- const rows = this.db.prepare(
2217
+ const rows2 = this.db.prepare(
2109
2218
  `SELECT f.* FROM features f
2110
2219
  JOIN feature_reviews fr ON fr.feature_id = f.id
2111
2220
  WHERE fr.review_id = ?
2112
2221
  ORDER BY f.updated_at DESC, f.title ASC`
2113
2222
  ).all(reviewId2);
2114
- return rows.map((row) => this.featureSummary(row, this.featureMembers(text(row, "id"))));
2223
+ return rows2.map((row) => this.featureSummary(row, this.featureMembers(text(row, "id"))));
2115
2224
  }
2116
2225
  touchFeature(id, now) {
2117
2226
  this.db.prepare("UPDATE features SET updated_at = ? WHERE id = ?").run(now, id);
@@ -2205,8 +2314,8 @@ var Store = class {
2205
2314
  this.snapshotCache = null;
2206
2315
  }
2207
2316
  listReviews(project) {
2208
- const rows = project ? this.db.prepare("SELECT * FROM reviews WHERE project_key = ? ORDER BY updated_at DESC, number DESC").all(project) : this.db.prepare("SELECT * FROM reviews ORDER BY updated_at DESC, number DESC").all();
2209
- return rows.map(reviewItem);
2317
+ const rows2 = project ? this.db.prepare("SELECT * FROM reviews WHERE project_key = ? ORDER BY updated_at DESC, number DESC").all(project) : this.db.prepare("SELECT * FROM reviews ORDER BY updated_at DESC, number DESC").all();
2318
+ return rows2.map(reviewItem);
2210
2319
  }
2211
2320
  getReview(id) {
2212
2321
  const row = this.db.prepare("SELECT * FROM reviews WHERE id = ?").get(id);
@@ -2263,8 +2372,8 @@ var Store = class {
2263
2372
  this.db.prepare("DELETE FROM review_versions WHERE review_id = ? AND id NOT IN (SELECT id FROM review_versions WHERE review_id = ? ORDER BY id DESC LIMIT ?)").run(id, id, Math.max(1, keep));
2264
2373
  }
2265
2374
  listVersions(id) {
2266
- const rows = this.db.prepare("SELECT * FROM review_versions WHERE review_id = ? ORDER BY id DESC").all(id);
2267
- return rows.map((row) => {
2375
+ const rows2 = this.db.prepare("SELECT * FROM review_versions WHERE review_id = ? ORDER BY id DESC").all(id);
2376
+ return rows2.map((row) => {
2268
2377
  const data = json(row, "data_json", {});
2269
2378
  const stats = data.stats ?? {};
2270
2379
  const files = Array.isArray(data.files) ? data.files.length : 0;
@@ -2347,8 +2456,8 @@ var Store = class {
2347
2456
  }
2348
2457
  // --- findings ---
2349
2458
  listFindings(id) {
2350
- const rows = this.db.prepare("SELECT * FROM findings WHERE review_id = ? ORDER BY rowid").all(id);
2351
- return rows.map((row) => ({
2459
+ const rows2 = this.db.prepare("SELECT * FROM findings WHERE review_id = ? ORDER BY rowid").all(id);
2460
+ return rows2.map((row) => ({
2352
2461
  id: text(row, "id"),
2353
2462
  fingerprint: text(row, "fingerprint"),
2354
2463
  level: text(row, "level"),
@@ -2429,8 +2538,8 @@ var Store = class {
2429
2538
  }
2430
2539
  // --- drafts ---
2431
2540
  listDrafts(id) {
2432
- const rows = this.db.prepare("SELECT * FROM drafts WHERE review_id = ? ORDER BY rowid").all(id);
2433
- return rows.map((row) => ({
2541
+ const rows2 = this.db.prepare("SELECT * FROM drafts WHERE review_id = ? ORDER BY rowid").all(id);
2542
+ return rows2.map((row) => ({
2434
2543
  threadId: text(row, "thread_id"),
2435
2544
  body: text(row, "body"),
2436
2545
  resolve: Number(row.resolve) === 1,
@@ -2470,8 +2579,8 @@ var Store = class {
2470
2579
  }
2471
2580
  // --- notes ---
2472
2581
  listNotes(id) {
2473
- const rows = this.db.prepare("SELECT * FROM notes WHERE review_id = ? ORDER BY created_at").all(id);
2474
- return rows.map((row) => ({
2582
+ const rows2 = this.db.prepare("SELECT * FROM notes WHERE review_id = ? ORDER BY created_at").all(id);
2583
+ return rows2.map((row) => ({
2475
2584
  id: text(row, "id"),
2476
2585
  file: text(row, "file"),
2477
2586
  line: Number(row.line),
@@ -2520,8 +2629,8 @@ var Store = class {
2520
2629
  }
2521
2630
  // --- agent messages ---
2522
2631
  listAgentMessages(id) {
2523
- const rows = this.db.prepare("SELECT * FROM agent_messages WHERE review_id = ? ORDER BY created_at, rowid").all(id);
2524
- return rows.map((row) => ({
2632
+ const rows2 = this.db.prepare("SELECT * FROM agent_messages WHERE review_id = ? ORDER BY created_at, rowid").all(id);
2633
+ return rows2.map((row) => ({
2525
2634
  id: text(row, "id"),
2526
2635
  role: text(row, "role") === "agent" ? "agent" : "human",
2527
2636
  text: text(row, "text"),
@@ -2533,9 +2642,9 @@ var Store = class {
2533
2642
  }
2534
2643
  // --- decisions ---
2535
2644
  listDecisions(id) {
2536
- const rows = this.db.prepare("SELECT * FROM decisions WHERE review_id = ?").all(id);
2645
+ const rows2 = this.db.prepare("SELECT * FROM decisions WHERE review_id = ?").all(id);
2537
2646
  const out = {};
2538
- for (const row of rows) {
2647
+ for (const row of rows2) {
2539
2648
  out[text(row, "finding_id")] = {
2540
2649
  decision: row.decision ? String(row.decision) : null,
2541
2650
  note: text(row, "note")
@@ -2605,8 +2714,8 @@ var Store = class {
2605
2714
  params.push(to);
2606
2715
  }
2607
2716
  params.push(limit);
2608
- const rows = this.db.prepare(`SELECT * FROM review_events WHERE ${clauses.join(" AND ")} ORDER BY id ASC LIMIT ?`).all(...params);
2609
- return rows.map((row) => ({
2717
+ const rows2 = this.db.prepare(`SELECT * FROM review_events WHERE ${clauses.join(" AND ")} ORDER BY id ASC LIMIT ?`).all(...params);
2718
+ return rows2.map((row) => ({
2610
2719
  id: Number(row.id),
2611
2720
  at: text(row, "at"),
2612
2721
  reviewId: row.review_id ? String(row.review_id) : null,
@@ -2624,8 +2733,8 @@ var Store = class {
2624
2733
  this.db.prepare("INSERT INTO audit (at, review_id, action, detail) VALUES (?, ?, ?, ?)").run((/* @__PURE__ */ new Date()).toISOString(), reviewId2, action, JSON.stringify(detail));
2625
2734
  }
2626
2735
  auditTail(limit = 100) {
2627
- const rows = this.db.prepare("SELECT * FROM audit ORDER BY id DESC LIMIT ?").all(limit);
2628
- return rows.map((row) => ({
2736
+ const rows2 = this.db.prepare("SELECT * FROM audit ORDER BY id DESC LIMIT ?").all(limit);
2737
+ return rows2.map((row) => ({
2629
2738
  at: text(row, "at"),
2630
2739
  reviewId: text(row, "review_id"),
2631
2740
  action: text(row, "action"),
@@ -2704,8 +2813,8 @@ function globToRegExp(glob) {
2704
2813
  function escapeRegExp(value) {
2705
2814
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2706
2815
  }
2707
- function classifyFile(path12) {
2708
- const lower = path12.toLowerCase();
2816
+ function classifyFile(path13) {
2817
+ const lower = path13.toLowerCase();
2709
2818
  if (/(^|\/)(node_modules|dist|build|coverage|vendor)\//.test(lower)) return "generated";
2710
2819
  if (/\.(md|mdx|rst|txt|adoc)$/.test(lower) || /(^|\/)(docs?|adr)\//.test(lower)) return "docs";
2711
2820
  if (/(^|\/)(__tests__|tests?|spec|e2e)\//.test(lower) || /\.(test|spec)\.[cm]?[jt]sx?$/.test(lower) || /_test\.go$/.test(lower)) return "test";
@@ -3367,8 +3476,8 @@ var CLASS_LABEL = {
3367
3476
  };
3368
3477
  function computeGroups(diff, custom = []) {
3369
3478
  const groups = /* @__PURE__ */ new Map();
3370
- const add = (group, path12, additions, deletions) => {
3371
- group.files.push(path12);
3479
+ const add = (group, path13, additions, deletions) => {
3480
+ group.files.push(path13);
3372
3481
  group.additions += additions;
3373
3482
  group.deletions += deletions;
3374
3483
  groups.set(group.id, group);
@@ -3418,15 +3527,15 @@ function parseCodeowners(text2) {
3418
3527
  }
3419
3528
  return entries;
3420
3529
  }
3421
- function matches(path12, pattern) {
3530
+ function matches(path13, pattern) {
3422
3531
  const cleaned = pattern.replace(/^\/+/, "").replace(/\/+$/, "");
3423
3532
  if (!cleaned) return false;
3424
3533
  if (!cleaned.includes("/")) {
3425
3534
  const segment = cleaned.includes("*") || cleaned.includes("?") ? cleaned : cleaned.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3426
- return new RegExp(`(^|/)${segment}(/|$)`).test(path12);
3535
+ return new RegExp(`(^|/)${segment}(/|$)`).test(path13);
3427
3536
  }
3428
- if (globToRegExp(cleaned).test(path12)) return true;
3429
- return globToRegExp(`${cleaned}/**`).test(path12);
3537
+ if (globToRegExp(cleaned).test(path13)) return true;
3538
+ return globToRegExp(`${cleaned}/**`).test(path13);
3430
3539
  }
3431
3540
  function codeownersFor(files, entries) {
3432
3541
  const result = [];
@@ -3463,23 +3572,23 @@ function maskSecret(value) {
3463
3572
  if (trimmed.length <= 8) return "***";
3464
3573
  return `${trimmed.slice(0, 4)}\u2026${trimmed.slice(-2)}`;
3465
3574
  }
3466
- function isAllowlisted(path12, rule, allowlist) {
3575
+ function isAllowlisted(path13, rule, allowlist) {
3467
3576
  return allowlist.some((entry) => {
3468
3577
  const normalized = entry.trim();
3469
3578
  if (!normalized) return false;
3470
3579
  if (normalized === rule || normalized === `rule:${rule}`) return true;
3471
3580
  if (normalized.startsWith("rule:")) return false;
3472
- return globToRegExp(normalized).test(path12);
3581
+ return globToRegExp(normalized).test(path13);
3473
3582
  });
3474
3583
  }
3475
- function scanLines(path12, lines, options = {}) {
3476
- if (!options.includeTests && classifyFile(path12) === "test") return [];
3584
+ function scanLines(path13, lines, options = {}) {
3585
+ if (!options.includeTests && classifyFile(path13) === "test") return [];
3477
3586
  const allowlist = options.allowlist ?? [];
3478
3587
  const findings = [];
3479
3588
  for (const line of lines) {
3480
3589
  let specific = false;
3481
3590
  for (const pattern of PATTERNS) {
3482
- if (isAllowlisted(path12, pattern.id, allowlist)) continue;
3591
+ if (isAllowlisted(path13, pattern.id, allowlist)) continue;
3483
3592
  if (pattern.id === "generic-secret" && specific) continue;
3484
3593
  pattern.regex.lastIndex = 0;
3485
3594
  const match = pattern.regex.exec(line.text);
@@ -3488,7 +3597,7 @@ function scanLines(path12, lines, options = {}) {
3488
3597
  findings.push({
3489
3598
  rule: pattern.id,
3490
3599
  title: pattern.title,
3491
- file: path12,
3600
+ file: path13,
3492
3601
  line: line.number,
3493
3602
  preview: maskSecret(match[0])
3494
3603
  });
@@ -3805,8 +3914,8 @@ async function resolveReviewRef(options) {
3805
3914
  if (!branch || branch === "HEAD") {
3806
3915
  throw new ProviderError(tr("\u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0438\u0442\u044C \u0432\u0435\u0442\u043A\u0443 \u0434\u043B\u044F \u043F\u043E\u0438\u0441\u043A\u0430 \u0440\u0435\u0432\u044C\u044E", "could not determine the branch to search for a review"), tr("\u043F\u0435\u0440\u0435\u0434\u0430\u0439\u0442\u0435 \u043D\u043E\u043C\u0435\u0440 \u0440\u0435\u0432\u044C\u044E \u044F\u0432\u043D\u043E", "pass the review number explicitly"));
3807
3916
  }
3808
- const probe = await createProvider({ ...context, number: 0 }, { root });
3809
- const found = await probe.findByBranch(branch);
3917
+ const probe2 = await createProvider({ ...context, number: 0 }, { root });
3918
+ const found = await probe2.findByBranch(branch);
3810
3919
  if (!found) throw new ProviderError(tr(`\u043E\u0442\u043A\u0440\u044B\u0442\u043E\u0435 \u0440\u0435\u0432\u044C\u044E \u0434\u043B\u044F \u0432\u0435\u0442\u043A\u0438 ${branch} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E`, `no open review found for branch ${branch}`), tr("\u043F\u0435\u0440\u0435\u0434\u0430\u0439\u0442\u0435 \u043D\u043E\u043C\u0435\u0440 \u0440\u0435\u0432\u044C\u044E \u044F\u0432\u043D\u043E", "pass the review number explicitly"));
3811
3920
  return found;
3812
3921
  }
@@ -4461,7 +4570,7 @@ function parseOpenApi(text2) {
4461
4570
  const info = isRecord2(document.info) ? document.info : {};
4462
4571
  const paths = isRecord2(document.paths) ? document.paths : {};
4463
4572
  const operations = [];
4464
- for (const [path12, value] of Object.entries(paths)) {
4573
+ for (const [path13, value] of Object.entries(paths)) {
4465
4574
  if (!isRecord2(value)) continue;
4466
4575
  for (const method of METHODS) {
4467
4576
  const operation = value[method];
@@ -4472,7 +4581,7 @@ function parseOpenApi(text2) {
4472
4581
  const media = isRecord2(firstMedia) ? firstMedia : {};
4473
4582
  operations.push({
4474
4583
  method: method.toUpperCase(),
4475
- path: path12,
4584
+ path: path13,
4476
4585
  operationId: String(operation.operationId ?? ""),
4477
4586
  summary: String(operation.summary ?? ""),
4478
4587
  parameters: parametersOf(operation, document),
@@ -4524,9 +4633,9 @@ function renderOpenApiSummary(summary) {
4524
4633
  }
4525
4634
  return lines.join("\n");
4526
4635
  }
4527
- function openApiPathRegExp(path12) {
4528
- if (path12 === "/") return /(?!)/;
4529
- const escaped = path12.replace(/\{[^}]+\}/g, "\0").replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\u0000/g, "[^/?#\\s]+");
4636
+ function openApiPathRegExp(path13) {
4637
+ if (path13 === "/") return /(?!)/;
4638
+ const escaped = path13.replace(/\{[^}]+\}/g, "\0").replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\u0000/g, "[^/?#\\s]+");
4530
4639
  return new RegExp(`(?<![\\w-])${escaped}(?![\\w-])`);
4531
4640
  }
4532
4641
 
@@ -5053,6 +5162,33 @@ var ReviewService = class {
5053
5162
  listProjects() {
5054
5163
  return this.store.listProjects();
5055
5164
  }
5165
+ /** Настройки интерфейса переживают перезапуск демона, в отличие от localStorage. */
5166
+ uiSettings() {
5167
+ return this.store.uiSettings();
5168
+ }
5169
+ /**
5170
+ * Частичное обновление настроек. Ключи и размеры ограничены: база не должна
5171
+ * превращаться в свалку произвольного JSON даже для доверенного человека.
5172
+ */
5173
+ updateUiSettings(patch) {
5174
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
5175
+ throw new MrReviewError(tr("\u043D\u0443\u0436\u0435\u043D \u043E\u0431\u044A\u0435\u043A\u0442 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A", "an object of settings is required"), "BAD_INPUT");
5176
+ }
5177
+ const entries = Object.entries(patch);
5178
+ if (entries.length > 50) {
5179
+ throw new MrReviewError(tr("\u0441\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u043D\u043E\u0433\u043E \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u0437\u0430 \u043E\u0434\u0438\u043D \u0440\u0430\u0437", "too many settings at once"), "BAD_INPUT");
5180
+ }
5181
+ for (const [key, value] of entries) {
5182
+ if (!/^[a-zA-Z][a-zA-Z0-9]{0,63}$/.test(key)) {
5183
+ throw new MrReviewError(tr(`\u043D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438: ${key}`, `invalid settings key: ${key}`), "BAD_INPUT");
5184
+ }
5185
+ const json2 = JSON.stringify(value);
5186
+ if (json2 === void 0 || json2.length > 4096) {
5187
+ throw new MrReviewError(tr(`\u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438: ${key}`, `the value of ${key} is too large`), "BAD_INPUT");
5188
+ }
5189
+ }
5190
+ return this.store.updateUiSettings(patch);
5191
+ }
5056
5192
  /** Резолвит проект по рабочей копии и регистрирует его без открытия ревью. */
5057
5193
  async registerProject(rootInput) {
5058
5194
  const root = findRepoRoot(rootInput);
@@ -5500,25 +5636,25 @@ ${t("\u2026 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u0444\u0438\u0447\
5500
5636
  }
5501
5637
  const side = found.status === "deleted" ? "base" : "head";
5502
5638
  const sha = side === "head" ? info.commit.head : info.commit.base;
5503
- const path12 = side === "head" ? found.path : found.oldPath || found.path;
5504
- if (!sha || !path12) {
5639
+ const path13 = side === "head" ? found.path : found.oldPath || found.path;
5640
+ if (!sha || !path13) {
5505
5641
  throw Object.assign(new Error(tr("\u043D\u0435 \u0438\u0437\u0432\u0435\u0441\u0442\u0435\u043D \u043A\u043E\u043C\u043C\u0438\u0442 \u0444\u0430\u0439\u043B\u0430", "the file commit is unknown")), { status: 404 });
5506
5642
  }
5507
- const key = `${id}|${side}|${sha}|${path12}`;
5643
+ const key = `${id}|${side}|${sha}|${path13}`;
5508
5644
  const hit = this.fileContentCache.get(key);
5509
5645
  if (hit && this.now().getTime() - hit.at < 10 * 6e4) return hit.value;
5510
5646
  let text2;
5511
5647
  try {
5512
5648
  const provider = preview ? await this.providerFactory(preview.ref, preview.root) : await this.providerFor(id);
5513
5649
  try {
5514
- const result = await this.runImpl("git", ["show", `${sha}:${path12}`], {
5650
+ const result = await this.runImpl("git", ["show", `${sha}:${path13}`], {
5515
5651
  cwd: root,
5516
5652
  timeoutMs: 3e4,
5517
5653
  maxBuffer: 16 * 1024 * 1024
5518
5654
  });
5519
5655
  text2 = result.stdout;
5520
5656
  } catch {
5521
- text2 = await provider.fileContent(path12, sha);
5657
+ text2 = await provider.fileContent(path13, sha);
5522
5658
  }
5523
5659
  } catch (error) {
5524
5660
  throw Object.assign(
@@ -5534,7 +5670,7 @@ ${t("\u2026 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 \u0444\u0438\u0447\
5534
5670
  const normalized = text2.replace(/\r\n/g, "\n");
5535
5671
  const all = normalized === "" ? [] : (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
5536
5672
  const value = {
5537
- path: path12,
5673
+ path: path13,
5538
5674
  side,
5539
5675
  lines: all.slice(0, 2e4),
5540
5676
  totalLines: all.length,
@@ -6380,12 +6516,13 @@ function fallbackInfo(row) {
6380
6516
 
6381
6517
  // src/daemon/http.ts
6382
6518
  init_redact();
6519
+ init_locale();
6383
6520
  init_errors();
6384
6521
  import http from "node:http";
6385
6522
  import { createReadStream } from "node:fs";
6386
6523
  import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
6387
6524
  import path9 from "node:path";
6388
- import { timingSafeEqual } from "node:crypto";
6525
+ import { randomBytes as randomBytes3, timingSafeEqual } from "node:crypto";
6389
6526
 
6390
6527
  // src/daemon/rpc.ts
6391
6528
  import net from "node:net";
@@ -6394,6 +6531,167 @@ init_redact();
6394
6531
  init_errors();
6395
6532
  init_exec();
6396
6533
 
6534
+ // src/providers/auth.ts
6535
+ init_exec();
6536
+ init_errors();
6537
+ init_locale();
6538
+ init_redact();
6539
+ import { tmpdir as tmpdir5 } from "node:os";
6540
+ var HOST_RE = /^(?!-)[a-z0-9-]{1,63}(?:\.[a-z0-9-]{1,63})*(?::\d{1,5})?$/i;
6541
+ var TOKEN_MIN = 8;
6542
+ var TOKEN_MAX = 4096;
6543
+ function binaryFor(platform) {
6544
+ return platform === "gitlab" ? "glab" : "gh";
6545
+ }
6546
+ function parseAuthTarget(platform, host) {
6547
+ const value = String(platform ?? "").trim().toLowerCase();
6548
+ if (value !== "gitlab" && value !== "github") {
6549
+ throw new MrReviewError(tr("\u043F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u0430 \u0434\u043E\u043B\u0436\u043D\u0430 \u0431\u044B\u0442\u044C gitlab \u0438\u043B\u0438 github", "platform must be gitlab or github"), "BAD_INPUT");
6550
+ }
6551
+ const name = String(host ?? "").trim().toLowerCase();
6552
+ if (!HOST_RE.test(name)) {
6553
+ throw new MrReviewError(
6554
+ tr("\u043D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 \u0445\u043E\u0441\u0442 \u043F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u044B", "invalid platform host"),
6555
+ "BAD_INPUT",
6556
+ tr("\u0445\u043E\u0441\u0442 \u0431\u0435\u0437 \u0441\u0445\u0435\u043C\u044B \u0438 \u043F\u0443\u0442\u0438, \u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440 gitlab.example.com", "a host without a scheme or path, for example gitlab.example.com")
6557
+ );
6558
+ }
6559
+ return { platform: value, host: name };
6560
+ }
6561
+ function parseToken(token) {
6562
+ const value = String(token ?? "").trim();
6563
+ const bad = value.length < TOKEN_MIN || value.length > TOKEN_MAX || /\s/.test(value) || /[\u0000-\u001f\u007f]/.test(value);
6564
+ if (bad) {
6565
+ throw new MrReviewError(
6566
+ tr("\u0442\u043E\u043A\u0435\u043D \u0432\u044B\u0433\u043B\u044F\u0434\u0438\u0442 \u043D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u043E", "the token looks invalid"),
6567
+ "BAD_INPUT",
6568
+ tr("\u0432\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0442\u043E\u043A\u0435\u043D \u0446\u0435\u043B\u0438\u043A\u043E\u043C, \u0431\u0435\u0437 \u043F\u0440\u043E\u0431\u0435\u043B\u043E\u0432 \u0438 \u043F\u0435\u0440\u0435\u043D\u043E\u0441\u043E\u0432", "paste the whole token without spaces or line breaks")
6569
+ );
6570
+ }
6571
+ return value;
6572
+ }
6573
+ function authTargets(projects) {
6574
+ const targets = /* @__PURE__ */ new Map();
6575
+ for (const project of projects) {
6576
+ if (project.platform !== "gitlab" && project.platform !== "github") continue;
6577
+ try {
6578
+ const target = parseAuthTarget(project.platform, project.host);
6579
+ targets.set(`${target.platform}:${target.host}`, target);
6580
+ } catch {
6581
+ }
6582
+ }
6583
+ return [...targets.values()];
6584
+ }
6585
+ async function probe(target, deps, token) {
6586
+ const bin = binaryFor(target.platform);
6587
+ const runner = deps.run ?? run;
6588
+ const args = target.platform === "gitlab" ? ["api", "--hostname", target.host, "user"] : ["api", "user"];
6589
+ const env = target.platform === "gitlab" ? token ? { GITLAB_TOKEN: token } : {} : { GH_HOST: target.host, ...token ? { GH_TOKEN: token } : {} };
6590
+ try {
6591
+ const { stdout } = await runner(bin, args, { cwd: tmpdir5(), timeoutMs: 3e4, env });
6592
+ let data = {};
6593
+ try {
6594
+ data = JSON.parse(stdout);
6595
+ } catch {
6596
+ return { error: tr(`${bin}: \u043E\u0442\u0432\u0435\u0442 \u043D\u0435 JSON`, `${bin}: response is not JSON`) };
6597
+ }
6598
+ const account = String(data.username ?? data.login ?? data.name ?? "").trim();
6599
+ return account ? { account } : {};
6600
+ } catch (error) {
6601
+ return { error: redact(error?.message ?? error).replace(/\s+/g, " ").trim().slice(0, 300) };
6602
+ }
6603
+ }
6604
+ async function installHint(platform, resolve) {
6605
+ const bin = binaryFor(platform);
6606
+ const url = platform === "gitlab" ? "https://docs.gitlab.com/cli/installation/" : "https://cli.github.com/";
6607
+ if (await resolve("brew")) return { url, command: `brew install ${bin}` };
6608
+ if (process.platform === "linux" && await resolve("pacman")) {
6609
+ return { url, command: `sudo pacman -S ${platform === "gitlab" ? "glab" : "github-cli"}` };
6610
+ }
6611
+ if (platform === "github" && process.platform === "win32" && await resolve("winget")) {
6612
+ return { url, command: "winget install --id GitHub.cli" };
6613
+ }
6614
+ return { url };
6615
+ }
6616
+ async function authStatus(target, deps = {}) {
6617
+ const bin = binaryFor(target.platform);
6618
+ const resolve = deps.resolve ?? resolveExecutable;
6619
+ const base = { platform: target.platform, host: target.host, binary: false, authenticated: false };
6620
+ if (!await resolve(bin)) {
6621
+ return {
6622
+ ...base,
6623
+ hint: tr(
6624
+ `${bin} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u0432 PATH \u0434\u0435\u043C\u043E\u043D\u0430: \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u0435\u0433\u043E \u043D\u0430 \u0445\u043E\u0441\u0442\u0435 \u0438 \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u0434\u0435\u043C\u043E\u043D \u0438\u043B\u0438 \u0437\u0430\u0434\u0430\u0439\u0442\u0435 REVDECK_${bin.toUpperCase()}`,
6625
+ `${bin} is not in the daemon PATH: install it on the host and restart the daemon, or set REVDECK_${bin.toUpperCase()}`
6626
+ ),
6627
+ install: await installHint(target.platform, resolve)
6628
+ };
6629
+ }
6630
+ const result = await probe(target, deps);
6631
+ if (result.account) return { ...base, binary: true, authenticated: true, account: result.account };
6632
+ return {
6633
+ ...base,
6634
+ binary: true,
6635
+ ...result.error ? { error: result.error } : {},
6636
+ hint: tr(
6637
+ `\u0432\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0442\u043E\u043A\u0435\u043D \u043D\u0438\u0436\u0435 \u0438\u043B\u0438 \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 ${bin} auth login --hostname ${target.host} \u043D\u0430 \u0445\u043E\u0441\u0442\u0435`,
6638
+ `paste a token below or run ${bin} auth login --hostname ${target.host} on the host`
6639
+ )
6640
+ };
6641
+ }
6642
+ async function authLogin(target, token, deps = {}) {
6643
+ const bin = binaryFor(target.platform);
6644
+ const resolve = deps.resolve ?? resolveExecutable;
6645
+ const runner = deps.run ?? run;
6646
+ if (!await resolve(bin)) {
6647
+ throw new MrReviewError(
6648
+ tr(`${bin} \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u0432 PATH \u0434\u0435\u043C\u043E\u043D\u0430`, `${bin} is not in the daemon PATH`),
6649
+ "ENVIRONMENT",
6650
+ tr(`\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 ${bin} \u043D\u0430 \u0445\u043E\u0441\u0442\u0435 \u0438 \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 \u0434\u0435\u043C\u043E\u043D`, `install ${bin} on the host and restart the daemon`)
6651
+ );
6652
+ }
6653
+ const checked = await probe(target, deps, token);
6654
+ if (!checked.account) {
6655
+ throw new AuthError(
6656
+ tr(
6657
+ `\u0442\u043E\u043A\u0435\u043D \u043D\u0435 \u043F\u0440\u0438\u043D\u044F\u0442 ${target.host}${checked.error ? `: ${checked.error}` : ""}`,
6658
+ `the token was rejected by ${target.host}${checked.error ? `: ${checked.error}` : ""}`
6659
+ ),
6660
+ tr(
6661
+ "\u043F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u0441\u0440\u043E\u043A \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F \u0438 \u043F\u0440\u0430\u0432\u0430: GitLab \u2014 api, GitHub \u2014 repo \u0438 read:org",
6662
+ "check the expiry and scopes: GitLab \u2014 api, GitHub \u2014 repo and read:org"
6663
+ )
6664
+ );
6665
+ }
6666
+ try {
6667
+ if (target.platform === "gitlab") {
6668
+ await runner(bin, ["auth", "login", "--hostname", target.host, "--stdin"], {
6669
+ cwd: tmpdir5(),
6670
+ timeoutMs: 6e4,
6671
+ input: token
6672
+ });
6673
+ } else {
6674
+ await runner(bin, ["auth", "login", "--hostname", target.host, "--with-token"], {
6675
+ cwd: tmpdir5(),
6676
+ timeoutMs: 6e4,
6677
+ input: token
6678
+ });
6679
+ }
6680
+ } catch (error) {
6681
+ throw new AuthError(
6682
+ tr(
6683
+ `${bin} \u043D\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u043B \u0442\u043E\u043A\u0435\u043D: ${redact(error?.message ?? error).replace(/\s+/g, " ").trim().slice(0, 300)}`,
6684
+ `${bin} did not store the token: ${redact(error?.message ?? error).replace(/\s+/g, " ").trim().slice(0, 300)}`
6685
+ ),
6686
+ tr(
6687
+ `\u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u0435 ${bin} auth login --hostname ${target.host} \u0432\u0440\u0443\u0447\u043D\u0443\u044E \u043D\u0430 \u0445\u043E\u0441\u0442\u0435`,
6688
+ `run ${bin} auth login --hostname ${target.host} manually on the host`
6689
+ )
6690
+ );
6691
+ }
6692
+ return authStatus(target, deps);
6693
+ }
6694
+
6397
6695
  // src/daemon/capabilities.ts
6398
6696
  var AGENT_METHODS = /* @__PURE__ */ new Set([
6399
6697
  "ping",
@@ -6480,6 +6778,22 @@ async function dispatch(service, method, params, policy = HUMAN_POLICY) {
6480
6778
  binaries: { glab, gh, git }
6481
6779
  };
6482
6780
  }
6781
+ case "auth.status": {
6782
+ if (params.platform !== void 0 || params.host !== void 0) {
6783
+ return { hosts: [await authStatus(parseAuthTarget(params.platform, params.host))] };
6784
+ }
6785
+ const targets = authTargets(service.listProjects());
6786
+ return { hosts: await Promise.all(targets.map((target) => authStatus(target))) };
6787
+ }
6788
+ case "auth.login": {
6789
+ const target = parseAuthTarget(params.platform, params.host);
6790
+ const token = parseToken(params.token);
6791
+ return { host: await authLogin(target, token) };
6792
+ }
6793
+ case "settings.get":
6794
+ return { settings: service.uiSettings() };
6795
+ case "settings.put":
6796
+ return { settings: service.updateUiSettings(params.patch ?? {}) };
6483
6797
  case "projects.list":
6484
6798
  return { projects: service.listProjects() };
6485
6799
  case "projects.register": {
@@ -6838,6 +7152,11 @@ var SECURITY_HEADERS = {
6838
7152
  "referrer-policy": "no-referrer",
6839
7153
  "content-security-policy": "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: http: https:; media-src 'self' http: https:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
6840
7154
  };
7155
+ function hostAuthority(host) {
7156
+ if (host === "0.0.0.0") return "127.0.0.1";
7157
+ if (host === "::") return "[::1]";
7158
+ return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
7159
+ }
6841
7160
  var COOKIE = "revdeck_session";
6842
7161
  function safeEqual(left, right) {
6843
7162
  const a = Buffer.from(left);
@@ -6875,12 +7194,208 @@ function reply(res, status, data) {
6875
7194
  });
6876
7195
  res.end(body);
6877
7196
  }
7197
+ function escapeHtml(value) {
7198
+ return value.replace(/[&<>"']/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char]);
7199
+ }
7200
+ function pageLocale(header) {
7201
+ const first = String(header ?? "").split(",")[0]?.trim().toLowerCase() ?? "";
7202
+ if (first.startsWith("ru")) return "ru";
7203
+ if (first.startsWith("en")) return "en";
7204
+ return locale();
7205
+ }
7206
+ function launchPage(options) {
7207
+ const text2 = (ru, en) => options.locale === "ru" ? ru : en;
7208
+ const title = options.stale ? text2("\u0421\u0435\u0441\u0441\u0438\u044F \u0434\u0435\u043C\u043E\u043D\u0430 \u0443\u0441\u0442\u0430\u0440\u0435\u043B\u0430", "The daemon session expired") : text2("\u041D\u0443\u0436\u043D\u0430 \u0441\u0441\u044B\u043B\u043A\u0430 \u0437\u0430\u043F\u0443\u0441\u043A\u0430", "A launch link is required");
7209
+ const lead = options.stale ? text2(
7210
+ "\u0414\u0435\u043C\u043E\u043D \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A\u0430\u043B\u0441\u044F \u0438 \u0441\u043C\u0435\u043D\u0438\u043B launch-\u0442\u043E\u043A\u0435\u043D \u0438 \u043F\u043E\u0440\u0442. Cookie-\u0441\u0435\u0441\u0441\u0438\u044F \u044D\u0442\u043E\u0433\u043E \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0430 \u0431\u043E\u043B\u044C\u0448\u0435 \u043D\u0435 \u0434\u0435\u0439\u0441\u0442\u0432\u0443\u0435\u0442.",
7211
+ "The daemon restarted and rotated its launch token and port. This browser\u2019s cookie session is no longer valid."
7212
+ ) : text2(
7213
+ "\u0418\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441 \u043E\u0442\u043A\u0440\u044B\u0432\u0430\u0435\u0442\u0441\u044F \u043F\u043E \u043E\u0434\u043D\u043E\u0440\u0430\u0437\u043E\u0432\u043E\u0439 \u0441\u0441\u044B\u043B\u043A\u0435 \u0438\u0437 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430: \u043E\u043D\u0430 \u0430\u0432\u0442\u043E\u0440\u0438\u0437\u0443\u0435\u0442 \u0431\u0440\u0430\u0443\u0437\u0435\u0440 \u0438 \u043D\u0435 \u0442\u0440\u0435\u0431\u0443\u0435\u0442 \u043F\u0430\u0440\u043E\u043B\u044F.",
7214
+ "The interface opens from a one-time link in your terminal: it authorizes this browser and needs no password."
7215
+ );
7216
+ const command = "revdeck daemon start && revdeck ui --open";
7217
+ const labels = {
7218
+ copy: text2("\u041A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C", "Copy"),
7219
+ copied: text2("\u0421\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D\u043E", "Copied"),
7220
+ checking: text2("\u041F\u0440\u043E\u0432\u0435\u0440\u044F\u0435\u043C \u0434\u043E\u0441\u0442\u0443\u043F\u2026", "Checking access\u2026"),
7221
+ waiting: text2("\u041D\u0443\u0436\u043D\u0430 \u043D\u043E\u0432\u0430\u044F \u0441\u0441\u044B\u043B\u043A\u0430", "A new link is required"),
7222
+ ok: text2("\u0414\u043E\u0441\u0442\u0443\u043F \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D, \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C\u2026", "Access restored, reloading\u2026"),
7223
+ offline: text2("\u0414\u0435\u043C\u043E\u043D \u043D\u0435 \u043E\u0442\u0432\u0435\u0447\u0430\u0435\u0442", "The daemon is not responding")
7224
+ };
7225
+ const version = options.version ? `<span>revdeck ${escapeHtml(options.version)}</span>` : "<span>revdeck</span>";
7226
+ return `<!doctype html>
7227
+ <html lang="${options.locale}">
7228
+ <head>
7229
+ <meta charset="utf-8">
7230
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7231
+ <meta name="referrer" content="no-referrer">
7232
+ <meta name="color-scheme" content="light dark">
7233
+ <title>revdeck \u2014 ${escapeHtml(title)}</title>
7234
+ <link rel="icon" href="/favicon.svg" type="image/svg+xml">
7235
+ <style>
7236
+ :root {
7237
+ color-scheme: light dark;
7238
+ --bg: #f6f7f9; --panel: #ffffff; --border: #dfe3e8; --text: #16191d; --muted: #68707a;
7239
+ --accent: #3b6ef5; --accent-soft: #e6edff; --code: #f1f3f6; --ok: #1f8f4e; --warn: #b26a00; --danger: #c93838;
7240
+ --mono: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, 'Liberation Mono', monospace;
7241
+ --sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, 'Helvetica Neue', sans-serif;
7242
+ }
7243
+ @media (prefers-color-scheme: dark) {
7244
+ :root {
7245
+ --bg: #101216; --panel: #171a20; --border: #2a2f38; --text: #e6e9ee; --muted: #98a1ad;
7246
+ --accent: #6f95ff; --accent-soft: #1e2a4d; --code: #1f242c; --ok: #4cc27d; --warn: #e0a33a; --danger: #f07a7a;
7247
+ }
7248
+ }
7249
+ * { box-sizing: border-box; }
7250
+ body {
7251
+ margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 26px;
7252
+ background:
7253
+ radial-gradient(900px 520px at 12% -12%, color-mix(in srgb, var(--accent) 16%, transparent), transparent 62%),
7254
+ radial-gradient(760px 460px at 112% 112%, color-mix(in srgb, #7c5cff 13%, transparent), transparent 60%),
7255
+ var(--bg);
7256
+ color: var(--text); font: 14px/1.55 var(--sans);
7257
+ }
7258
+ .card {
7259
+ width: 100%; max-width: 574px; background: var(--panel); border: 1px solid var(--border);
7260
+ border-radius: 18px; padding: 26px 30px 22px;
7261
+ box-shadow: 0 1px 2px rgb(16 24 40 / 6%), 0 18px 50px rgb(16 24 40 / 10%);
7262
+ }
7263
+ .brand { display: flex; align-items: center; gap: 9px; font-size: 15px; font-weight: 700; letter-spacing: -0.01em; }
7264
+ .brand img { width: 24px; height: 24px; }
7265
+ .chip {
7266
+ margin-left: auto; padding: 3px 9px; border: 1px solid var(--border); border-radius: 999px;
7267
+ color: var(--muted); font-size: 10.5px; font-weight: 650; letter-spacing: 0.07em; text-transform: uppercase;
7268
+ }
7269
+ h1 { margin: 28px 0 10px; font-size: 25px; line-height: 1.2; letter-spacing: -0.025em; }
7270
+ .lead { margin: 0 0 20px; color: var(--muted); font-size: 13.5px; }
7271
+ .command {
7272
+ display: flex; align-items: center; gap: 10px; padding: 8px 8px 8px 12px;
7273
+ background: var(--code); border: 1px solid var(--border); border-radius: 10px;
7274
+ }
7275
+ .command code { flex: 1; min-width: 0; overflow-x: auto; white-space: nowrap; font: 12.5px/1.5 var(--mono); }
7276
+ .command button, .reload {
7277
+ border: 1px solid var(--border); background: var(--panel); color: var(--text);
7278
+ border-radius: 7px; padding: 5px 10px; font: inherit; font-size: 12px; font-weight: 600;
7279
+ white-space: nowrap; cursor: pointer;
7280
+ }
7281
+ .command button:hover, .reload:hover { background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 35%, var(--border)); }
7282
+ .command button:focus, .reload:focus { outline: 2px solid var(--accent); outline-offset: 2px; }
7283
+ .command button.copied { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 45%, var(--border)); }
7284
+ .hint { margin: 10px 0 0; color: var(--muted); font-size: 12.5px; }
7285
+ .status {
7286
+ display: flex; align-items: center; gap: 8px; margin-top: 22px; padding-top: 15px;
7287
+ border-top: 1px solid var(--border); color: var(--muted); font-size: 12.5px;
7288
+ }
7289
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--muted); flex: none; }
7290
+ .status[data-state="checking"] .dot { background: var(--warn); animation: pulse 1.4s ease-in-out infinite; }
7291
+ .status[data-state="waiting"] .dot { background: var(--warn); }
7292
+ .status[data-state="ok"] .dot { background: var(--ok); }
7293
+ .status[data-state="offline"] .dot { background: var(--danger); }
7294
+ @keyframes pulse { 50% { opacity: 0.3; } }
7295
+ .actions { display: flex; align-items: center; gap: 12px; margin-top: 14px; }
7296
+ .actions .hint { margin: 0; }
7297
+ .foot { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-top: 18px; color: var(--muted); font-size: 11.5px; }
7298
+ .origin { font-family: var(--mono); overflow-wrap: anywhere; }
7299
+ @media (max-width: 480px) { .card { padding: 22px 20px 18px; } h1 { font-size: 22px; } .actions { flex-wrap: wrap; } }
7300
+ </style>
7301
+ </head>
7302
+ <body>
7303
+ <main class="card">
7304
+ <div class="brand"><img src="/favicon.svg" alt="">revdeck<span class="chip">${text2("\u043B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0439 \u0434\u0435\u043C\u043E\u043D", "local daemon")}</span></div>
7305
+ <h1>${escapeHtml(title)}</h1>
7306
+ <p class="lead">${escapeHtml(lead)}</p>
7307
+ <div class="command">
7308
+ <code>${escapeHtml(command)}</code>
7309
+ <button id="copy" type="button">${escapeHtml(labels.copy)}</button>
7310
+ </div>
7311
+ <p class="hint">${text2(
7312
+ "\u041A\u043E\u043C\u0430\u043D\u0434\u0430 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442 \u0434\u0435\u043C\u043E\u043D, \u0435\u0441\u043B\u0438 \u043E\u043D \u043E\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D, \u0438 \u043E\u0442\u043A\u0440\u043E\u0435\u0442 \u0441\u0432\u0435\u0436\u0443\u044E \u0441\u0441\u044B\u043B\u043A\u0443. \u0414\u0430\u043D\u043D\u044B\u0435 \u043E\u0441\u0442\u0430\u044E\u0442\u0441\u044F \u043D\u0430 \u044D\u0442\u043E\u043C \u0445\u043E\u0441\u0442\u0435.",
7313
+ "The command starts the daemon if needed and opens a fresh link. Everything stays on this host."
7314
+ )}</p>
7315
+ <div class="status" id="status" data-state="checking" role="status" aria-live="polite">
7316
+ <span class="dot" aria-hidden="true"></span><span id="status-text">${escapeHtml(labels.checking)}</span>
7317
+ </div>
7318
+ <div class="actions">
7319
+ <button class="reload" id="reload" type="button">${text2("\u041F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C \u0441\u043D\u043E\u0432\u0430", "Check again")}</button>
7320
+ <span class="hint">${text2(
7321
+ "\u0412\u043A\u043B\u0430\u0434\u043A\u0430 \u043F\u0435\u0440\u0435\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u0441\u044F \u0441\u0430\u043C\u0430, \u043A\u043E\u0433\u0434\u0430 \u043F\u043E\u044F\u0432\u0438\u0442\u0441\u044F \u0434\u043E\u0441\u0442\u0443\u043F.",
7322
+ "This tab reconnects by itself once access is restored."
7323
+ )}</span>
7324
+ </div>
7325
+ <div class="foot">${version}<span class="origin" id="origin"></span></div>
7326
+ </main>
7327
+ <script nonce="${options.nonce}">
7328
+ (function () {
7329
+ var command = ${JSON.stringify(command)};
7330
+ var labels = ${JSON.stringify(labels)};
7331
+ var copyButton = document.getElementById('copy');
7332
+ var reloadButton = document.getElementById('reload');
7333
+ var status = document.getElementById('status');
7334
+ var statusText = document.getElementById('status-text');
7335
+ var origin = document.getElementById('origin');
7336
+ if (origin) origin.textContent = location.origin;
7337
+ copyButton.addEventListener('click', function () {
7338
+ function done() {
7339
+ copyButton.textContent = labels.copied;
7340
+ copyButton.classList.add('copied');
7341
+ setTimeout(function () {
7342
+ copyButton.textContent = labels.copy;
7343
+ copyButton.classList.remove('copied');
7344
+ }, 1800);
7345
+ }
7346
+ if (navigator.clipboard && navigator.clipboard.writeText) {
7347
+ navigator.clipboard.writeText(command).then(done, function () { fallback(); done(); });
7348
+ return;
7349
+ }
7350
+ fallback();
7351
+ done();
7352
+ function fallback() {
7353
+ var area = document.createElement('textarea');
7354
+ area.value = command;
7355
+ area.setAttribute('readonly', '');
7356
+ area.style.position = 'fixed';
7357
+ area.style.opacity = '0';
7358
+ document.body.appendChild(area);
7359
+ area.select();
7360
+ try { document.execCommand('copy'); } catch (error) {}
7361
+ area.remove();
7362
+ }
7363
+ });
7364
+ reloadButton.addEventListener('click', function () { location.reload(); });
7365
+ var checking = false;
7366
+ function probe() {
7367
+ if (checking) return;
7368
+ checking = true;
7369
+ fetch('/api/health', { credentials: 'same-origin', cache: 'no-store' }).then(function (response) {
7370
+ checking = false;
7371
+ if (response.ok) {
7372
+ status.dataset.state = 'ok';
7373
+ statusText.textContent = labels.ok;
7374
+ setTimeout(function () { location.reload(); }, 250);
7375
+ return;
7376
+ }
7377
+ status.dataset.state = 'waiting';
7378
+ statusText.textContent = labels.waiting;
7379
+ }, function () {
7380
+ checking = false;
7381
+ status.dataset.state = 'offline';
7382
+ statusText.textContent = labels.offline;
7383
+ });
7384
+ }
7385
+ setTimeout(probe, 1500);
7386
+ setInterval(probe, 5000);
7387
+ })();
7388
+ </script>
7389
+ </body>
7390
+ </html>`;
7391
+ }
6878
7392
  async function startHttpServer(options) {
6879
7393
  const { service, token } = options;
6880
7394
  const host = options.host ?? "127.0.0.1";
6881
7395
  const server = http.createServer(async (req, res) => {
6882
7396
  const port2 = server.address()?.port ?? 0;
6883
7397
  const expectedHosts = /* @__PURE__ */ new Set([`127.0.0.1:${port2}`, `localhost:${port2}`, `[::1]:${port2}`]);
7398
+ if (host !== "0.0.0.0" && host !== "::") expectedHosts.add(`${hostAuthority(host).toLowerCase()}:${port2}`);
6884
7399
  for (const name of options.allowedHosts ?? []) expectedHosts.add(`${name}:${port2}`);
6885
7400
  expectedHosts.add(`host.docker.internal:${port2}`);
6886
7401
  if (!expectedHosts.has(String(req.headers.host ?? ""))) {
@@ -6913,7 +7428,7 @@ async function startHttpServer(options) {
6913
7428
  if (req.method === "GET" && url.pathname === "/") {
6914
7429
  const provided = url.searchParams.get("t");
6915
7430
  if (provided && safeEqual(provided, token)) {
6916
- const next = new URL("/", url);
7431
+ const next = new URL(url.href);
6917
7432
  next.searchParams.delete("t");
6918
7433
  res.writeHead(302, {
6919
7434
  ...SECURITY_HEADERS,
@@ -6924,8 +7439,14 @@ async function startHttpServer(options) {
6924
7439
  return;
6925
7440
  }
6926
7441
  if (!authorized) {
6927
- res.writeHead(401, { ...SECURITY_HEADERS, "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
6928
- res.end('<meta charset="utf-8"><h1>\u041D\u0443\u0436\u043D\u0430 \u0441\u0441\u044B\u043B\u043A\u0430 \u0437\u0430\u043F\u0443\u0441\u043A\u0430</h1><p>\u041E\u0442\u043A\u0440\u043E\u0439\u0442\u0435 \u0430\u0434\u0440\u0435\u0441 \u0438\u0437 \u0442\u0435\u0440\u043C\u0438\u043D\u0430\u043B\u0430: \u043E\u043D \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u0442 \u043E\u0434\u043D\u043E\u0440\u0430\u0437\u043E\u0432\u044B\u0439 \u0442\u043E\u043A\u0435\u043D.</p>');
7442
+ const nonce = randomBytes3(16).toString("base64");
7443
+ res.writeHead(401, {
7444
+ ...SECURITY_HEADERS,
7445
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
7446
+ "content-type": "text/html; charset=utf-8",
7447
+ "cache-control": "no-store"
7448
+ });
7449
+ res.end(launchPage({ stale: presented !== "", nonce, version: options.version, locale: pageLocale(req.headers["accept-language"]) }));
6929
7450
  return;
6930
7451
  }
6931
7452
  const html = await readFile2(path9.join(options.uiDir, "index.html"));
@@ -7320,7 +7841,7 @@ data: ${JSON.stringify(event)}
7320
7841
  });
7321
7842
  const port = server.address().port;
7322
7843
  return {
7323
- url: `http://127.0.0.1:${port}`,
7844
+ url: `http://${hostAuthority(host)}:${port}`,
7324
7845
  port,
7325
7846
  close: () => new Promise((resolve) => {
7326
7847
  server.close(() => resolve());
@@ -7329,11 +7850,31 @@ data: ${JSON.stringify(event)}
7329
7850
  };
7330
7851
  }
7331
7852
 
7853
+ // src/daemon/port.ts
7854
+ import path10 from "node:path";
7855
+ import { readFile as readFile3 } from "node:fs/promises";
7856
+ function portHintPath(state = stateDir()) {
7857
+ return path10.join(state, "daemon.port");
7858
+ }
7859
+ async function readPortHint(file = portHintPath()) {
7860
+ try {
7861
+ const value = Number((await readFile3(file, "utf8")).trim());
7862
+ return Number.isInteger(value) && value > 0 && value < 65536 ? value : null;
7863
+ } catch {
7864
+ return null;
7865
+ }
7866
+ }
7867
+ async function writePortHint(port, file = portHintPath()) {
7868
+ if (!Number.isInteger(port) || port <= 0 || port >= 65536) return;
7869
+ await writeFileAtomic(file, `${port}
7870
+ `, 384);
7871
+ }
7872
+
7332
7873
  // src/daemon/bridge.ts
7333
7874
  import { unlink as unlink3 } from "node:fs/promises";
7334
- import path10 from "node:path";
7875
+ import path11 from "node:path";
7335
7876
  async function startDevcontainerBridge(service, info) {
7336
- await ensureDir(path10.dirname(devcontainerBridgeDir()), 448);
7877
+ await ensureDir(path11.dirname(devcontainerBridgeDir()), 448);
7337
7878
  await ensureDir(devcontainerBridgeDir(), 448);
7338
7879
  await ensureDir(devcontainerRunDir(), 493);
7339
7880
  await ensureDir(devcontainerStateDir(), 493);
@@ -7386,26 +7927,39 @@ async function main() {
7386
7927
  if (values["state-dir"]) process.env.REVDECK_STATE_DIR = values["state-dir"];
7387
7928
  if (values["runtime-dir"]) process.env.REVDECK_RUNTIME_DIR = values["runtime-dir"];
7388
7929
  const foreground = values.foreground === true;
7930
+ const file = logPath();
7931
+ const maxLogBytes = 1024 * 1024;
7932
+ let logSize = null;
7389
7933
  const log = async (line) => {
7390
7934
  const message = `${(/* @__PURE__ */ new Date()).toISOString()} ${redactLine(line, 4e3)}
7391
7935
  `;
7392
7936
  if (foreground) process.stderr.write(message);
7393
7937
  try {
7394
- await appendFile(logPath(), message, { mode: 384 });
7938
+ const bytes = Buffer.byteLength(message);
7939
+ logSize ??= (await stat3(file).catch(() => null))?.size ?? 0;
7940
+ if (logSize + bytes > maxLogBytes) {
7941
+ await rename2(file, `${file}.1`).catch(() => void 0);
7942
+ logSize = 0;
7943
+ }
7944
+ await appendFile(file, message, { mode: 384 });
7945
+ logSize += bytes;
7395
7946
  } catch {
7396
7947
  }
7397
7948
  };
7398
7949
  const existing = await runningDaemon();
7399
7950
  if (existing) {
7400
- process.stdout.write(`revdeck daemon ${tr("\u0443\u0436\u0435 \u0437\u0430\u043F\u0443\u0449\u0435\u043D", "is already running")} (pid ${existing.pid}): ${existing.url}/
7401
- `);
7951
+ process.stdout.write(
7952
+ ` ${colors.green("\u25CF")} ${tr("\u0414\u0435\u043C\u043E\u043D \u0443\u0436\u0435 \u0437\u0430\u043F\u0443\u0449\u0435\u043D", "Daemon is already running")} ${colors.dim(`\xB7 pid ${existing.pid}`)}
7953
+ ${colors.dim("revdeck ui --open")}
7954
+ `
7955
+ );
7402
7956
  return;
7403
7957
  }
7404
7958
  await ensureDir(stateDir(), 448);
7405
7959
  await ensureDir(runtimeDir(), 448);
7406
7960
  const lock = await acquireLock();
7407
7961
  if (!lock) {
7408
- process.stdout.write(`revdeck daemon ${tr("\u0443\u0436\u0435 \u0437\u0430\u043F\u0443\u0441\u043A\u0430\u0435\u0442\u0441\u044F \u0438\u043B\u0438 \u0437\u0430\u043F\u0443\u0449\u0435\u043D", "is already starting or running")}
7962
+ process.stdout.write(` ${colors.dim("\u25CB")} ${tr("\u0414\u0435\u043C\u043E\u043D \u0443\u0436\u0435 \u0437\u0430\u043F\u0443\u0441\u043A\u0430\u0435\u0442\u0441\u044F \u0438\u043B\u0438 \u0437\u0430\u043F\u0443\u0449\u0435\u043D", "Daemon is already starting or running")}
7409
7963
  `);
7410
7964
  return;
7411
7965
  }
@@ -7418,17 +7972,40 @@ async function main() {
7418
7972
  });
7419
7973
  const socket = socketPath();
7420
7974
  const rpc = await startRpcServer(service, socket);
7421
- const uiDir = values["ui-dir"] ? path11.resolve(values["ui-dir"]) : path11.join(packageRoot(), "dist", "ui");
7422
- const http2 = await startHttpServer({
7975
+ const uiDir = values["ui-dir"] ? path12.resolve(values["ui-dir"]) : path12.join(packageRoot(), "dist", "ui");
7976
+ const requestedPort = parsePort(values.port);
7977
+ const preferredPort = requestedPort ?? await readPortHint();
7978
+ const listen = (port) => startHttpServer({
7423
7979
  service,
7424
7980
  token,
7425
7981
  agentToken,
7426
7982
  uiDir,
7427
- ...values.port ? { port: Number(values.port) } : {},
7983
+ ...port ? { port } : {},
7428
7984
  ...values.host ? { host: String(values.host) } : {},
7429
7985
  ...process.env.REVDECK_HTTP_ALLOWED_HOSTS ? { allowedHosts: process.env.REVDECK_HTTP_ALLOWED_HOSTS.split(",").map((item) => item.trim()).filter(Boolean) } : {},
7430
7986
  version: VERSION
7431
7987
  });
7988
+ let http2;
7989
+ try {
7990
+ http2 = await listen(preferredPort ?? void 0);
7991
+ } catch (error) {
7992
+ const code = error.code;
7993
+ if (requestedPort) {
7994
+ if (code === "EADDRINUSE" || code === "EACCES") {
7995
+ throw new Error(
7996
+ tr(
7997
+ `\u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u043D\u044F\u0442\u044C \u043F\u043E\u0440\u0442 ${requestedPort}: ${code === "EADDRINUSE" ? "\u043E\u043D \u0437\u0430\u043D\u044F\u0442" : "\u043D\u0435\u0442 \u043F\u0440\u0430\u0432"}; \u0432\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0434\u0440\u0443\u0433\u043E\u0439 --port`,
7998
+ `cannot bind port ${requestedPort}: ${code === "EADDRINUSE" ? "already in use" : "permission denied"}; choose another --port`
7999
+ )
8000
+ );
8001
+ }
8002
+ throw error;
8003
+ }
8004
+ if (code !== "EADDRINUSE" && code !== "EACCES") throw error;
8005
+ await log(`port ${preferredPort} is busy, falling back to a random port`);
8006
+ http2 = await listen();
8007
+ }
8008
+ await writePortHint(http2.port).catch((error) => log(`cannot remember port: ${redactLine(error instanceof Error ? error.message : error)}`));
7432
8009
  const info = {
7433
8010
  pid: process.pid,
7434
8011
  port: http2.port,
@@ -7450,13 +8027,18 @@ async function main() {
7450
8027
  }
7451
8028
  service.startSync();
7452
8029
  process.stdout.write(
7453
- [
7454
- `revdeck daemon ${VERSION} (pid ${process.pid})`,
7455
- `UI: ${http2.url}/?t=${token}`,
7456
- `${tr("\u0441\u043E\u043A\u0435\u0442", "socket")}: ${socket}`,
7457
- `${tr("\u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435", "state")}: ${stateDir()}`,
7458
- ""
7459
- ].join("\n")
8030
+ `${daemonStartedLines(
8031
+ {
8032
+ version: VERSION,
8033
+ pid: process.pid,
8034
+ url: `${http2.url}/?t=${token}`,
8035
+ socket,
8036
+ stateDir: stateDir(),
8037
+ logPath: logPath()
8038
+ },
8039
+ "started"
8040
+ ).join("\n")}
8041
+ `
7460
8042
  );
7461
8043
  await log(`daemon started pid=${process.pid} port=${http2.port}`);
7462
8044
  let closing = false;
@@ -7472,7 +8054,7 @@ async function main() {
7472
8054
  service.close();
7473
8055
  await unlink4(daemonInfoPath()).catch(() => void 0);
7474
8056
  await lock.close().catch(() => void 0);
7475
- await unlink4(path11.join(stateDir(), "daemon.lock")).catch(() => void 0);
8057
+ await unlink4(path12.join(stateDir(), "daemon.lock")).catch(() => void 0);
7476
8058
  process.exit(0);
7477
8059
  }
7478
8060
  };
@@ -7483,10 +8065,18 @@ async function main() {
7483
8065
  });
7484
8066
  }
7485
8067
  }
8068
+ function parsePort(value) {
8069
+ if (value === void 0) return null;
8070
+ const port = Number(value);
8071
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
8072
+ throw new Error(tr(`\u043D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 \u043F\u043E\u0440\u0442 ${value}: \u043D\u0443\u0436\u043D\u043E 1\u201365535`, `invalid port ${value}: expected 1\u201365535`));
8073
+ }
8074
+ return port;
8075
+ }
7486
8076
  function packageRoot() {
7487
- let dir = path11.dirname(fileURLToPath(import.meta.url));
8077
+ let dir = path12.dirname(fileURLToPath(import.meta.url));
7488
8078
  for (; ; ) {
7489
- const candidate = path11.join(dir, "package.json");
8079
+ const candidate = path12.join(dir, "package.json");
7490
8080
  if (existsSync5(candidate)) {
7491
8081
  try {
7492
8082
  const parsed = JSON.parse(readFileSync(candidate, "utf8"));
@@ -7494,7 +8084,7 @@ function packageRoot() {
7494
8084
  } catch {
7495
8085
  }
7496
8086
  }
7497
- const parent = path11.dirname(dir);
8087
+ const parent = path12.dirname(dir);
7498
8088
  if (parent === dir) return process.cwd();
7499
8089
  dir = parent;
7500
8090
  }
@@ -7533,7 +8123,7 @@ async function runningDaemon() {
7533
8123
  return reachable ? info : null;
7534
8124
  }
7535
8125
  async function acquireLock() {
7536
- const file = path11.join(stateDir(), "daemon.lock");
8126
+ const file = path12.join(stateDir(), "daemon.lock");
7537
8127
  for (let attempt = 0; attempt < 2; attempt++) {
7538
8128
  try {
7539
8129
  const handle = await open2(file, "wx", 384);
@@ -7541,7 +8131,7 @@ async function acquireLock() {
7541
8131
  return handle;
7542
8132
  } catch (error) {
7543
8133
  if (error.code !== "EEXIST") throw error;
7544
- const pid = Number(await readFile3(file, "utf8").catch(() => ""));
8134
+ const pid = Number(await readFile4(file, "utf8").catch(() => ""));
7545
8135
  if (pid) {
7546
8136
  try {
7547
8137
  process.kill(pid, 0);
@@ -7554,8 +8144,13 @@ async function acquireLock() {
7554
8144
  }
7555
8145
  return null;
7556
8146
  }
8147
+ for (const stream of [process.stdout, process.stderr]) {
8148
+ stream.on("error", (error) => {
8149
+ if (error.code === "EPIPE") process.exit(0);
8150
+ });
8151
+ }
7557
8152
  void main().catch((error) => {
7558
- process.stderr.write(`revdeck: ${redactLine(error instanceof Error ? error.message : error)}
8153
+ for (const line of errorLine(redactLine(error instanceof Error ? error.message : error))) process.stderr.write(`${line}
7559
8154
  `);
7560
8155
  process.exit(1);
7561
8156
  });