@threadbase-sh/streamer 1.31.2 → 1.32.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/cli.cjs CHANGED
@@ -123460,6 +123460,97 @@ var require_semver2 = __commonJS({
123460
123460
  }
123461
123461
  });
123462
123462
 
123463
+ // src/lifecycle/conflict-check.ts
123464
+ var conflict_check_exports = {};
123465
+ __export(conflict_check_exports, {
123466
+ KNOWN_STREAMER_LABELS: () => KNOWN_STREAMER_LABELS,
123467
+ detectConflictingAgents: () => detectConflictingAgents,
123468
+ formatConflictMessage: () => formatConflictMessage
123469
+ });
123470
+ function uidScope() {
123471
+ return `gui/${process.getuid?.() ?? 501}`;
123472
+ }
123473
+ function resolveOwnLabel() {
123474
+ if (process.env.LAUNCHD_LABEL) return process.env.LAUNCHD_LABEL;
123475
+ try {
123476
+ (0, import_node_child_process4.execFileSync)("launchctl", ["print", `${uidScope()}/homebrew.mxcl.tb-streamer`], {
123477
+ stdio: "ignore"
123478
+ });
123479
+ return "homebrew.mxcl.tb-streamer";
123480
+ } catch {
123481
+ return LAUNCHD_LABEL;
123482
+ }
123483
+ }
123484
+ function isLabelLoaded(label) {
123485
+ try {
123486
+ (0, import_node_child_process4.execFileSync)("launchctl", ["list", label], { stdio: "ignore" });
123487
+ return true;
123488
+ } catch {
123489
+ return false;
123490
+ }
123491
+ }
123492
+ function detectConflictingAgents() {
123493
+ if (process.platform !== "darwin") return [];
123494
+ const ownLabel = resolveOwnLabel();
123495
+ const conflicts = [];
123496
+ for (const label of KNOWN_STREAMER_LABELS) {
123497
+ if (label === ownLabel) continue;
123498
+ if (isLabelLoaded(label)) {
123499
+ conflicts.push({
123500
+ label,
123501
+ resolution: label === "homebrew.mxcl.tb-streamer" ? "uninstall-homebrew" : "bootout"
123502
+ });
123503
+ }
123504
+ }
123505
+ try {
123506
+ const out = (0, import_node_child_process4.execFileSync)("launchctl", ["list"], {
123507
+ stdio: ["ignore", "pipe", "ignore"]
123508
+ }).toString();
123509
+ for (const line of out.split("\n")) {
123510
+ const parts = line.trim().split(/\s+/);
123511
+ const label = parts[2];
123512
+ if (!label) continue;
123513
+ if (LEGACY_PATTERN.test(label) && label !== ownLabel && !conflicts.some((c) => c.label === label)) {
123514
+ conflicts.push({ label, resolution: "bootout" });
123515
+ }
123516
+ }
123517
+ } catch {
123518
+ }
123519
+ return conflicts;
123520
+ }
123521
+ function formatConflictMessage(conflicts) {
123522
+ if (conflicts.length === 0) return "";
123523
+ const lines = ["Conflicting Threadbase streamer agents detected:", ""];
123524
+ for (const c of conflicts) {
123525
+ if (c.resolution === "uninstall-homebrew") {
123526
+ lines.push(
123527
+ ` \u2022 ${c.label} \u2014 run: brew services stop tb-streamer && brew uninstall tb-streamer`
123528
+ );
123529
+ } else {
123530
+ lines.push(` \u2022 ${c.label} \u2014 run: launchctl bootout gui/$(id -u)/${c.label}`);
123531
+ }
123532
+ }
123533
+ lines.push(
123534
+ "",
123535
+ "Only one Threadbase streamer can bind port 8766. Remove the conflicting agent(s) to proceed."
123536
+ );
123537
+ return lines.join("\n");
123538
+ }
123539
+ var import_node_child_process4, KNOWN_STREAMER_LABELS, LEGACY_PATTERN;
123540
+ var init_conflict_check = __esm({
123541
+ "src/lifecycle/conflict-check.ts"() {
123542
+ "use strict";
123543
+ import_node_child_process4 = require("child_process");
123544
+ init_constants();
123545
+ KNOWN_STREAMER_LABELS = [
123546
+ "com.ronen.threadbase",
123547
+ "homebrew.mxcl.tb-streamer",
123548
+ "com.threadbase.streamer"
123549
+ ];
123550
+ LEGACY_PATTERN = /^com\.threadbase\.streamer/;
123551
+ }
123552
+ });
123553
+
123463
123554
  // src/lifecycle/launchd.ts
123464
123555
  var launchd_exports = {};
123465
123556
  __export(launchd_exports, {
@@ -123471,13 +123562,13 @@ __export(launchd_exports, {
123471
123562
  isAgentLoaded: () => isAgentLoaded,
123472
123563
  kickstartAgent: () => kickstartAgent
123473
123564
  });
123474
- function uidScope() {
123565
+ function uidScope2() {
123475
123566
  return `gui/${process.getuid?.() ?? 501}`;
123476
123567
  }
123477
123568
  function resolveLoadedLabel() {
123478
123569
  if (process.env.LAUNCHD_LABEL) return process.env.LAUNCHD_LABEL;
123479
123570
  try {
123480
- (0, import_node_child_process4.execFileSync)("launchctl", ["print", `${uidScope()}/${BREW_LAUNCHD_LABEL2}`], {
123571
+ (0, import_node_child_process5.execFileSync)("launchctl", ["print", `${uidScope2()}/${BREW_LAUNCHD_LABEL2}`], {
123481
123572
  stdio: "ignore"
123482
123573
  });
123483
123574
  return BREW_LAUNCHD_LABEL2;
@@ -123486,11 +123577,11 @@ function resolveLoadedLabel() {
123486
123577
  }
123487
123578
  }
123488
123579
  function fullTarget() {
123489
- return `${uidScope()}/${resolveLoadedLabel()}`;
123580
+ return `${uidScope2()}/${resolveLoadedLabel()}`;
123490
123581
  }
123491
123582
  function isAgentLoaded() {
123492
123583
  try {
123493
- (0, import_node_child_process4.execFileSync)("launchctl", ["list", resolveLoadedLabel()], { stdio: "ignore" });
123584
+ (0, import_node_child_process5.execFileSync)("launchctl", ["list", resolveLoadedLabel()], { stdio: "ignore" });
123494
123585
  return true;
123495
123586
  } catch {
123496
123587
  return false;
@@ -123498,7 +123589,7 @@ function isAgentLoaded() {
123498
123589
  }
123499
123590
  function bootoutAgent(timeoutMs = 2e3) {
123500
123591
  try {
123501
- (0, import_node_child_process4.execFileSync)("launchctl", ["bootout", fullTarget()], { stdio: "ignore" });
123592
+ (0, import_node_child_process5.execFileSync)("launchctl", ["bootout", fullTarget()], { stdio: "ignore" });
123502
123593
  } catch {
123503
123594
  }
123504
123595
  const deadline = Date.now() + timeoutMs;
@@ -123510,7 +123601,7 @@ function bootoutAgent(timeoutMs = 2e3) {
123510
123601
  }
123511
123602
  function bootstrapAgent(plistPath) {
123512
123603
  try {
123513
- (0, import_node_child_process4.execFileSync)("launchctl", ["bootstrap", uidScope(), plistPath], {
123604
+ (0, import_node_child_process5.execFileSync)("launchctl", ["bootstrap", uidScope2(), plistPath], {
123514
123605
  stdio: ["ignore", "ignore", "pipe"]
123515
123606
  });
123516
123607
  } catch (err) {
@@ -123523,7 +123614,7 @@ function bootstrapAgent(plistPath) {
123523
123614
  }
123524
123615
  }
123525
123616
  function kickstartAgent() {
123526
- (0, import_node_child_process4.execFileSync)("launchctl", ["kickstart", "-k", fullTarget()], { stdio: "ignore" });
123617
+ (0, import_node_child_process5.execFileSync)("launchctl", ["kickstart", "-k", fullTarget()], { stdio: "ignore" });
123527
123618
  }
123528
123619
  function darwinPlistPath() {
123529
123620
  return `${process.env.HOME}/Library/LaunchAgents/${resolveLoadedLabel()}.plist`;
@@ -123534,7 +123625,7 @@ function getLogPaths() {
123534
123625
  }
123535
123626
  function getAgentPid() {
123536
123627
  try {
123537
- const out = (0, import_node_child_process4.execFileSync)("launchctl", ["list"], {
123628
+ const out = (0, import_node_child_process5.execFileSync)("launchctl", ["list"], {
123538
123629
  stdio: ["ignore", "pipe", "ignore"]
123539
123630
  }).toString();
123540
123631
  const label = resolveLoadedLabel();
@@ -123550,11 +123641,11 @@ function getAgentPid() {
123550
123641
  return null;
123551
123642
  }
123552
123643
  }
123553
- var import_node_child_process4, import_node_path25, BREW_LAUNCHD_LABEL2;
123644
+ var import_node_child_process5, import_node_path25, BREW_LAUNCHD_LABEL2;
123554
123645
  var init_launchd = __esm({
123555
123646
  "src/lifecycle/launchd.ts"() {
123556
123647
  "use strict";
123557
- import_node_child_process4 = require("child_process");
123648
+ import_node_child_process5 = require("child_process");
123558
123649
  import_node_path25 = require("path");
123559
123650
  init_constants();
123560
123651
  BREW_LAUNCHD_LABEL2 = "homebrew.mxcl.tb-streamer";
@@ -123627,7 +123718,7 @@ __export(task_scheduler_exports, {
123627
123718
  kickstartAgent: () => kickstartAgent2
123628
123719
  });
123629
123720
  function ps2(command) {
123630
- return (0, import_node_child_process5.execFileSync)("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
123721
+ return (0, import_node_child_process6.execFileSync)("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
123631
123722
  stdio: ["ignore", "pipe", "ignore"]
123632
123723
  }).toString();
123633
123724
  }
@@ -123673,11 +123764,11 @@ function getAgentPid2() {
123673
123764
  return null;
123674
123765
  }
123675
123766
  }
123676
- var import_node_child_process5;
123767
+ var import_node_child_process6;
123677
123768
  var init_task_scheduler = __esm({
123678
123769
  "src/lifecycle/task-scheduler.ts"() {
123679
123770
  "use strict";
123680
- import_node_child_process5 = require("child_process");
123771
+ import_node_child_process6 = require("child_process");
123681
123772
  init_constants();
123682
123773
  }
123683
123774
  });
@@ -124021,7 +124112,7 @@ __export(repo_exports, {
124021
124112
  });
124022
124113
  function getGitToplevel(cwd) {
124023
124114
  try {
124024
- return (0, import_node_child_process7.execFileSync)("git", ["rev-parse", "--show-toplevel"], {
124115
+ return (0, import_node_child_process8.execFileSync)("git", ["rev-parse", "--show-toplevel"], {
124025
124116
  cwd,
124026
124117
  stdio: ["ignore", "pipe", "ignore"]
124027
124118
  }).toString().trim();
@@ -124029,11 +124120,11 @@ function getGitToplevel(cwd) {
124029
124120
  return null;
124030
124121
  }
124031
124122
  }
124032
- var import_node_child_process7;
124123
+ var import_node_child_process8;
124033
124124
  var init_repo = __esm({
124034
124125
  "src/lifecycle/repo.ts"() {
124035
124126
  "use strict";
124036
- import_node_child_process7 = require("child_process");
124127
+ import_node_child_process8 = require("child_process");
124037
124128
  }
124038
124129
  });
124039
124130
 
@@ -147757,7 +147848,81 @@ async function stopService(opts = {}) {
147757
147848
  const { stdout: stdout2, stderr } = await execFileP("schtasks.exe", ["/End", "/TN", label]).catch(
147758
147849
  (err) => ({ stdout: "", stderr: String(err) })
147759
147850
  );
147760
- return { method: "schtasks-end", stdout: stdout2, stderr };
147851
+ const listenerResult = await stopWindowsListener(opts.port ?? 8766);
147852
+ return {
147853
+ method: "schtasks-end",
147854
+ stdout: `${stdout2}
147855
+ ${listenerResult.stdout}`,
147856
+ stderr: `${stderr}
147857
+ ${listenerResult.stderr}`
147858
+ };
147859
+ }
147860
+ async function stopWindowsListener(port) {
147861
+ let netstat;
147862
+ try {
147863
+ netstat = await execFileP("netstat.exe", ["-ano", "-p", "tcp"]);
147864
+ } catch (err) {
147865
+ return { stdout: "", stderr: `Could not inspect port ${port}: ${String(err)}` };
147866
+ }
147867
+ const pids = /* @__PURE__ */ new Set();
147868
+ for (const line of netstat.stdout.split(/\r?\n/)) {
147869
+ const columns = line.trim().split(/\s+/);
147870
+ if (columns.length < 5 || columns[0]?.toUpperCase() !== "TCP") continue;
147871
+ const [localAddress, state, pid] = [columns[1], columns[3], columns[4]];
147872
+ if (state?.toUpperCase() !== "LISTENING" || !pid || pid === "0") continue;
147873
+ if (localAddress?.endsWith(`:${port}`)) pids.add(pid);
147874
+ }
147875
+ const output = [];
147876
+ const errors = [];
147877
+ for (const pid of pids) {
147878
+ try {
147879
+ const result = await execFileP("taskkill.exe", ["/PID", pid, "/T", "/F"]);
147880
+ output.push(result.stdout);
147881
+ if (result.stderr) errors.push(result.stderr);
147882
+ } catch (err) {
147883
+ errors.push(`Could not stop PID ${pid} on port ${port}: ${String(err)}`);
147884
+ }
147885
+ }
147886
+ return { stdout: output.join("\n"), stderr: errors.join("\n") };
147887
+ }
147888
+
147889
+ // src/updater/restart-health.ts
147890
+ function isExpectedVersion(actual, expected) {
147891
+ return actual === expected || actual.startsWith(`${expected}+`);
147892
+ }
147893
+ async function waitForRestartHealth(opts) {
147894
+ const timeoutMs = opts.timeoutMs ?? 15e3;
147895
+ const pollIntervalMs = opts.pollIntervalMs ?? 250;
147896
+ const deadline = Date.now() + timeoutMs;
147897
+ let lastFailure = "server did not respond";
147898
+ while (Date.now() <= deadline) {
147899
+ const controller = new AbortController();
147900
+ const requestTimer = setTimeout(() => controller.abort(), Math.min(2e3, timeoutMs));
147901
+ try {
147902
+ const response = await fetch(`http://127.0.0.1:${opts.port}/healthz`, {
147903
+ signal: controller.signal
147904
+ });
147905
+ if (response.ok) {
147906
+ const body = await response.json();
147907
+ if (body.ok === true && typeof body.version === "string") {
147908
+ if (isExpectedVersion(body.version, opts.expectedVersion)) return;
147909
+ lastFailure = `running version is ${body.version}, expected ${opts.expectedVersion}`;
147910
+ } else {
147911
+ lastFailure = "health response is missing ok/version";
147912
+ }
147913
+ } else {
147914
+ lastFailure = `health endpoint returned ${response.status}`;
147915
+ }
147916
+ } catch (err) {
147917
+ lastFailure = err instanceof Error ? err.message : String(err);
147918
+ } finally {
147919
+ clearTimeout(requestTimer);
147920
+ }
147921
+ const remaining = deadline - Date.now();
147922
+ if (remaining <= 0) break;
147923
+ await new Promise((resolve6) => setTimeout(resolve6, Math.min(pollIntervalMs, remaining)));
147924
+ }
147925
+ throw new Error(`restart verification failed: ${lastFailure}`);
147761
147926
  }
147762
147927
 
147763
147928
  // src/updater/stamp-version.ts
@@ -150899,7 +151064,7 @@ async function runInstall(opts) {
150899
151064
  await unpackTarball({ tarballPath, destDir });
150900
151065
  stampVersionTxt(destDir, targetVersion);
150901
151066
  if (process.platform === "win32") {
150902
- await stopService().catch(() => {
151067
+ await stopService({ port: opts.runningServer?.port }).catch(() => {
150903
151068
  });
150904
151069
  }
150905
151070
  swapCurrent(targetVersion);
@@ -150908,6 +151073,12 @@ async function runInstall(opts) {
150908
151073
  try {
150909
151074
  const r = await restartService();
150910
151075
  restartMethod = r.method;
151076
+ if (opts.runningServer && r.method !== "none") {
151077
+ await waitForRestartHealth({
151078
+ port: opts.runningServer.port,
151079
+ expectedVersion: targetVersion
151080
+ });
151081
+ }
150911
151082
  } catch (err) {
150912
151083
  restartMethod = `failed: ${err instanceof Error ? err.message : String(err)}`;
150913
151084
  }
@@ -150918,15 +151089,17 @@ async function runInstall(opts) {
150918
151089
  pruned,
150919
151090
  restart: { method: restartMethod }
150920
151091
  };
151092
+ const outcome = restartMethod.startsWith("failed:") ? "failed" : "installed";
150921
151093
  appendUpdateLog(
150922
- `[installed] ${installed.previous} \u2192 ${installed.installed} restart=${installed.restart.method}${pruned.length > 0 ? ` pruned=${pruned.length}` : ""}`
151094
+ `[${outcome}] ${installed.previous} \u2192 ${installed.installed} restart=${installed.restart.method}${pruned.length > 0 ? ` pruned=${pruned.length}` : ""}`
150923
151095
  );
150924
151096
  return installed;
150925
151097
  }
150926
151098
 
150927
151099
  // cli/prod.ts
150928
- var import_node_child_process6 = require("child_process");
151100
+ var import_node_child_process7 = require("child_process");
150929
151101
  var import_node_fs22 = require("fs");
151102
+ init_conflict_check();
150930
151103
  init_constants();
150931
151104
  init_launchd();
150932
151105
  init_marker();
@@ -151009,6 +151182,18 @@ async function runProdDoctor(opts) {
151009
151182
  if (!getSupervisor().isAgentLoaded()) {
151010
151183
  findings.push("launchd agent is not loaded \u2014 prod is fully down");
151011
151184
  }
151185
+ const conflicts = detectConflictingAgents();
151186
+ for (const c of conflicts) {
151187
+ if (c.resolution === "uninstall-homebrew") {
151188
+ findings.push(
151189
+ `conflicting agent: ${c.label} \u2014 run: brew services stop tb-streamer && brew uninstall tb-streamer`
151190
+ );
151191
+ } else {
151192
+ findings.push(
151193
+ `conflicting agent: ${c.label} \u2014 run: launchctl bootout gui/$(id -u)/${c.label}`
151194
+ );
151195
+ }
151196
+ }
151012
151197
  return { findings, repairs };
151013
151198
  }
151014
151199
  var defaultSpawnTail = ({ files, lines, follow }) => {
@@ -151023,7 +151208,7 @@ var defaultSpawnTail = ({ files, lines, follow }) => {
151023
151208
  if (follow) args.push("-F");
151024
151209
  args.push(...existing);
151025
151210
  return new Promise((resolve6) => {
151026
- const child = (0, import_node_child_process6.spawn)("tail", args, { stdio: ["ignore", "inherit", "inherit"] });
151211
+ const child = (0, import_node_child_process7.spawn)("tail", args, { stdio: ["ignore", "inherit", "inherit"] });
151027
151212
  child.on("error", (err) => resolve6({ ok: false, message: `tail failed: ${err.message}` }));
151028
151213
  child.on("exit", (code) => resolve6({ ok: code === 0 }));
151029
151214
  });
@@ -151179,6 +151364,13 @@ program2.command("serve").description("Start the streamer server").option("-p, -
151179
151364
  const publicUrl = opts.publicUrl ?? loadPublicUrl() ?? null;
151180
151365
  const isProdInvocation = opts.prod === true || process.ppid === 1;
151181
151366
  if (!isProdInvocation) appendDevSessionMarker();
151367
+ if (process.platform === "darwin") {
151368
+ const { detectConflictingAgents: detectConflictingAgents2, formatConflictMessage: formatConflictMessage2 } = await Promise.resolve().then(() => (init_conflict_check(), conflict_check_exports));
151369
+ const conflicts = detectConflictingAgents2();
151370
+ if (conflicts.length > 0) {
151371
+ log7.warn(formatConflictMessage2(conflicts), void 0, "console");
151372
+ }
151373
+ }
151182
151374
  let resolvedDefaultPermissionMode = opts.defaultPermissionMode;
151183
151375
  if (resolvedDefaultPermissionMode === void 0 && !isProdInvocation && process.env.THREADBASE_SKIP_PERMISSION_MODE_PROMPT !== "true" && loadDefaultPermissionMode() === void 0 && import_node_process3.stdin.isTTY) {
151184
151376
  const { interactivePermissionModePrompt: interactivePermissionModePrompt2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports));
@@ -151378,11 +151570,20 @@ program2.command("update").description("Check for streamer updates from GitHub R
151378
151570
  );
151379
151571
  break;
151380
151572
  case "installed":
151381
- log7.info(
151382
- `Installed ${result.installed} (was ${result.previous}). Restart: ${result.restart.method}.`,
151383
- void 0,
151384
- "console"
151385
- );
151573
+ if (result.restart.method.startsWith("failed:")) {
151574
+ log7.error(
151575
+ `Installed ${result.installed} on disk, but the running service was not updated. Restart: ${result.restart.method}.`,
151576
+ void 0,
151577
+ "console"
151578
+ );
151579
+ process.exitCode = 1;
151580
+ } else {
151581
+ log7.info(
151582
+ `Installed ${result.installed} (was ${result.previous}). Restart: ${result.restart.method}.`,
151583
+ void 0,
151584
+ "console"
151585
+ );
151586
+ }
151386
151587
  if (result.pruned.length > 0) {
151387
151588
  log7.info(`Pruned old releases: ${result.pruned.join(", ")}`, void 0, "console");
151388
151589
  }