pinggy 0.6.7 → 0.6.9

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.
@@ -5,14 +5,14 @@ import {
5
5
  buildRemoteManagementWsUrl,
6
6
  initiateRemoteManagement,
7
7
  startRemoteManagement
8
- } from "./chunk-H527WMTF.js";
8
+ } from "./chunk-Q5RYSWFK.js";
9
9
  import {
10
10
  configuredLogLevel,
11
11
  forgetDeviceAgent,
12
12
  saveDeviceAgent,
13
13
  savedDeviceAgent,
14
14
  writeDaemonConfig
15
- } from "./chunk-CZOKR73F.js";
15
+ } from "./chunk-VD5ZFCZW.js";
16
16
  import {
17
17
  HTTP_NOT_FOUND,
18
18
  IPCClient,
@@ -36,7 +36,7 @@ import {
36
36
  upsertConfig,
37
37
  validateName,
38
38
  validateNameStrict
39
- } from "./chunk-2GIJXE4K.js";
39
+ } from "./chunk-3IPMFCEF.js";
40
40
  import {
41
41
  createQrCodes
42
42
  } from "./chunk-XZ64ZAGO.js";
@@ -44,8 +44,9 @@ import {
44
44
  TunnelManager,
45
45
  detachAllTunnelLoggers,
46
46
  isTunnelLoggingEnabled,
47
+ setNativeLogging,
47
48
  setTunnelLoggingEnabled
48
- } from "./chunk-3WMTTJHI.js";
49
+ } from "./chunk-5HBGVJSW.js";
49
50
  import {
50
51
  UpdateError,
51
52
  acquireUpdateLock,
@@ -57,7 +58,10 @@ import {
57
58
  isReleaseComplete,
58
59
  isUpdateLockHeld,
59
60
  parseVersion,
61
+ pinggyBinaryRunOptions,
60
62
  readBinaryIpcVersion,
63
+ readBinaryVersion,
64
+ readLinkVersion,
61
65
  releaseUpdateLock,
62
66
  removeQuietly,
63
67
  removeStaleUpdateFiles,
@@ -65,13 +69,14 @@ import {
65
69
  runPinggyBinary,
66
70
  versionFromTag,
67
71
  windowsInstallPaths
68
- } from "./chunk-PMZJ6HFH.js";
72
+ } from "./chunk-HJECJ7LC.js";
69
73
  import {
70
74
  InstallKind,
71
75
  NPM_INSTALL_COMMAND,
72
76
  backgroundInstallKind,
73
77
  canReplaceItself,
74
78
  createInstallProbe,
79
+ currentBootId,
75
80
  daemonIpcVersion,
76
81
  detectInstallKind,
77
82
  ensureDaemonRunning,
@@ -80,6 +85,7 @@ import {
80
85
  hasPathSegment,
81
86
  installCommandFor,
82
87
  installService,
88
+ installerBinaryPath,
83
89
  ipcMismatchMessage,
84
90
  isDaemonRunning,
85
91
  isIpcCompatible,
@@ -92,11 +98,13 @@ import {
92
98
  requireNodePty,
93
99
  resolveNodePtyRoot,
94
100
  startDaemon,
95
- startedBeforeBoot,
101
+ startDaemonFromInstalledBinary,
102
+ startedInEarlierBoot,
96
103
  stopDaemon,
97
104
  uninstallService,
105
+ unixLayoutPaths,
98
106
  writeUpdateState
99
- } from "./chunk-3KCXR33Y.js";
107
+ } from "./chunk-OQVFQ5VG.js";
100
108
  import {
101
109
  DaemonHost,
102
110
  DeviceAgentState,
@@ -123,7 +131,7 @@ import {
123
131
  getLogLevel,
124
132
  logger,
125
133
  setLogLevel
126
- } from "./chunk-LWCVB42S.js";
134
+ } from "./chunk-DGAH7UVX.js";
127
135
  import {
128
136
  ensurePinggyConfigDir,
129
137
  ensurePinggyLogDir,
@@ -132,10 +140,11 @@ import {
132
140
  getDaemonLogPath,
133
141
  getDeviceConfigPath,
134
142
  getForegroundAgentPath,
143
+ getLibpinggyLogPath,
135
144
  getPinggyConfigDir,
136
145
  getTunnelLogDir,
137
146
  getTunnelLogPath
138
- } from "./chunk-MAK5R4WQ.js";
147
+ } from "./chunk-WFHMERT3.js";
139
148
 
140
149
  // src/cli/options.ts
141
150
  var cliOptions = {
@@ -256,6 +265,7 @@ function printHelpMessage() {
256
265
  console.log(" pinggy attach <name|id> # Re-attach TUI to a running tunnel");
257
266
  console.log(" pinggy restart <name|id> # Restart a running tunnel (picks up latest log level)");
258
267
  console.log(" pinggy logs [-f] [<name|id>] # Show (or follow) tunnel or daemon logs");
268
+ console.log(" pinggy logs [-f] libpinggy # Show (or follow) the native library log, shared by all tunnels");
259
269
  console.log(" pinggy log level [debug|info|error] # Get or set the log level");
260
270
  console.log(" pinggy log path [<name|id>] # Print log file path");
261
271
  console.log("\nBackground Mode:");
@@ -380,8 +390,11 @@ function isAutoUpdateOff(variables) {
380
390
  function isExplicitOrPrintOnly({ rawArgs, values, hasAnyArgs }) {
381
391
  return rawArgs[0] === UPDATE_SUBCOMMAND || !hasAnyArgs || Boolean(values.help) || Boolean(values.version);
382
392
  }
393
+ function isUnderSudoOrInContainer(variables, fileExists) {
394
+ return Boolean(variables[SUDO_UID_ENV]) || CONTAINER_MARKER_FILES.some(fileExists);
395
+ }
383
396
  function isExcludedProcess(environment) {
384
- return Boolean(environment.variables[SUDO_UID_ENV]) || CONTAINER_MARKER_FILES.some(environment.fileExists) || parseVersion(environment.runningVersion) === null || hasPathSegment(environment.scriptRealPath, NPX_SEGMENT);
397
+ return isUnderSudoOrInContainer(environment.variables, environment.fileExists) || parseVersion(environment.runningVersion) === null || hasPathSegment(environment.scriptRealPath, NPX_SEGMENT);
385
398
  }
386
399
  function updatedNotice(state, running) {
387
400
  if (state.updatedToVersion !== running || !state.updatedFromVersion) return null;
@@ -437,7 +450,7 @@ function runGates(command, environment) {
437
450
  let detectedKind;
438
451
  const kind = () => detectedKind ?? (detectedKind = environment.detectKind());
439
452
  const state = environment.readState();
440
- printPendingNotice(state, kind, environment);
453
+ if (!command.installQuestionShown) printPendingNotice(state, kind, environment);
441
454
  const now = environment.nowEpochSeconds();
442
455
  if (!isDue(state.lastCheckEpochSeconds, CHECK_INTERVAL_SECONDS, now)) return;
443
456
  if (!isDue(state.lastAttemptEpochSeconds, ATTEMPT_INTERVAL_SECONDS, now)) return;
@@ -483,8 +496,478 @@ function startBackgroundUpdate(command, createEnvironment = realEnvironment) {
483
496
  }
484
497
  }
485
498
 
499
+ // src/install/selfInstall.ts
500
+ import { execFile, spawn as spawn2 } from "child_process";
501
+ import fs3 from "fs";
502
+ import os3 from "os";
503
+ import path2 from "path";
504
+ import { createInterface } from "readline";
505
+ import { fileURLToPath, pathToFileURL } from "url";
506
+
507
+ // src/install/pinggyOnPath.ts
508
+ import fs2 from "fs";
509
+ import path from "path";
510
+ var NPM_PACKAGE = "pinggy";
511
+ var UNIX_NPM_SEGMENT = `/lib/node_modules/${NPM_PACKAGE}/`;
512
+ var DEFAULT_PATH_EXTENSIONS = ".COM;.EXE;.BAT;.CMD";
513
+ var POWERSHELL_SCRIPT_EXTENSION = ".ps1";
514
+ var CURRENT_FOLDER = ".";
515
+ function pathModule(platform3) {
516
+ return platform3 === "win32" ? path.win32 : path.posix;
517
+ }
518
+ function pathFolders(platform3, pathValue) {
519
+ const separator = platform3 === "win32" ? ";" : ":";
520
+ return pathValue.split(separator).filter((folder) => folder !== "" && folder !== CURRENT_FOLDER);
521
+ }
522
+ function windowsCommandNames(name, pathExtensions) {
523
+ const extensions = (pathExtensions || DEFAULT_PATH_EXTENSIONS).split(";").filter(Boolean);
524
+ return [...extensions, POWERSHELL_SCRIPT_EXTENSION].map((extension) => `${name}${extension.toLowerCase()}`);
525
+ }
526
+ function findOnPath(names, lookup) {
527
+ const paths = pathModule(lookup.platform);
528
+ for (const folder of pathFolders(lookup.platform, lookup.pathValue)) {
529
+ for (const name of names) {
530
+ const candidate = paths.join(folder, name);
531
+ if (lookup.files.isExecutableFile(candidate)) return candidate;
532
+ }
533
+ }
534
+ return null;
535
+ }
536
+ function npmCopyFor(commandPath, lookup) {
537
+ if (lookup.platform === "win32") {
538
+ const folder = path.win32.dirname(commandPath);
539
+ const packageFolder = path.win32.join(folder, "node_modules", NPM_PACKAGE);
540
+ const isPackage = lookup.files.isFile(path.win32.join(packageFolder, "package.json"));
541
+ return isPackage && !lookup.files.isLink(packageFolder) ? { prefix: folder, packageFolder } : null;
542
+ }
543
+ const realPath = lookup.files.realPath(commandPath);
544
+ const segmentStart = realPath?.indexOf(UNIX_NPM_SEGMENT) ?? -1;
545
+ if (realPath === null || segmentStart < 0) return null;
546
+ const prefix = realPath.slice(0, segmentStart);
547
+ return { prefix, packageFolder: path.posix.join(prefix, "lib", "node_modules", NPM_PACKAGE) };
548
+ }
549
+ function findPinggyCommand(lookup) {
550
+ const names = lookup.platform === "win32" ? windowsCommandNames(NPM_PACKAGE, lookup.pathExtensions) : [NPM_PACKAGE];
551
+ const commandPath = findOnPath(names, lookup);
552
+ if (commandPath === null) return null;
553
+ return { commandPath, npm: npmCopyFor(commandPath, lookup) };
554
+ }
555
+ function isFile(filePath) {
556
+ try {
557
+ return fs2.statSync(filePath).isFile();
558
+ } catch {
559
+ return false;
560
+ }
561
+ }
562
+ function realPathFileSystem(platform3) {
563
+ return {
564
+ isExecutableFile: (filePath) => {
565
+ if (!isFile(filePath)) return false;
566
+ if (platform3 === "win32") return true;
567
+ try {
568
+ fs2.accessSync(filePath, fs2.constants.X_OK);
569
+ return true;
570
+ } catch {
571
+ return false;
572
+ }
573
+ },
574
+ isFile,
575
+ realPath: (filePath) => {
576
+ try {
577
+ return fs2.realpathSync(filePath);
578
+ } catch {
579
+ return null;
580
+ }
581
+ },
582
+ isLink: (filePath) => {
583
+ try {
584
+ return fs2.lstatSync(filePath).isSymbolicLink();
585
+ } catch {
586
+ return false;
587
+ }
588
+ }
589
+ };
590
+ }
591
+ function processPathLookup() {
592
+ return {
593
+ platform: process.platform,
594
+ pathValue: process.env.PATH ?? process.env.Path ?? "",
595
+ pathExtensions: process.env.PATHEXT,
596
+ files: realPathFileSystem(process.platform)
597
+ };
598
+ }
599
+
600
+ // src/install/selfInstall.ts
601
+ var UPDATE_SUBCOMMAND2 = "update";
602
+ var NPM_PACKAGE2 = "pinggy";
603
+ var LINK_DIRECTORY = path2.posix.join(".local", "bin");
604
+ var NO_ANSWER = /^\s*n/i;
605
+ var INTERRUPTED_EXIT_CODE = 130;
606
+ var VERSION_RUN_TIMEOUT_MILLIS = 1e4;
607
+ var OUTPUT_ONLY = ["ignore", "inherit", "inherit"];
608
+ var INSTALL_ONLY_ENV = "PINGGY_INSTALL_ONLY";
609
+ var BINARY_URL_ENV = "PINGGY_BINARY_URL";
610
+ var VERSION_ENV = "PINGGY_VERSION";
611
+ var BUNDLE_DIRECTORY = path2.dirname(fileURLToPath(import.meta.url));
612
+ var SCRIPTS_DIRECTORY = path2.join(BUNDLE_DIRECTORY, "..", "scripts", "install");
613
+ var SelfInstallAnswer = {
614
+ Yes: "yes",
615
+ No: "no",
616
+ /** Ctrl+D: the input ended. Not a decision, so nothing is installed or remembered. */
617
+ Closed: "closed"
618
+ };
619
+ var NpmRemoval = {
620
+ Removed: "removed",
621
+ NotWritable: "not-writable",
622
+ NoNpm: "no-npm",
623
+ Failed: "failed"
624
+ };
625
+ function installPathFor(environment, home) {
626
+ return installerBinaryPath(environment.platform, home, environment.variables);
627
+ }
628
+ function shown(filePath, environment, home) {
629
+ if (environment.platform === "win32") return filePath;
630
+ return filePath === home || filePath.startsWith(`${home}/`) ? `~${filePath.slice(home.length)}` : filePath;
631
+ }
632
+ function samePath(first, second, platform3) {
633
+ return platform3 === "win32" ? first.toLowerCase() === second.toLowerCase() : first === second;
634
+ }
635
+ function wasDeclined(environment) {
636
+ const state = environment.readState();
637
+ return state.declinedInstallVersion === environment.runningVersion && state.declinedInstallPath !== void 0 && samePath(state.declinedInstallPath, environment.execPath, environment.platform);
638
+ }
639
+ function isPrintOnlyOrUpdate({ rawArgs, values }) {
640
+ return rawArgs[0] === UPDATE_SUBCOMMAND2 || Boolean(values.help) || Boolean(values.version);
641
+ }
642
+ function passesGates(command, environment) {
643
+ if (!environment.isPackaged || isPrintOnlyOrUpdate(command)) return false;
644
+ if (!environment.stdinIsTerminal || !environment.stdoutIsTerminal) return false;
645
+ if (isUnderSudoOrInContainer(environment.variables, environment.fileExists)) return false;
646
+ if (parseVersion(environment.runningVersion) === null || environment.home === null) return false;
647
+ if (environment.isInstalledCopy() || wasDeclined(environment)) return false;
648
+ return !environment.isLockHeld();
649
+ }
650
+ async function decideOffer(environment, home) {
651
+ const command = environment.findPinggyCommand();
652
+ if (command?.npm) return { kind: "npm", npm: command.npm, npmVersion: environment.npmVersion(command.npm) };
653
+ const installed = await environment.installedBinary(installPathFor(environment, home));
654
+ return installed ? { kind: "replace", installedVersion: installed.version } : { kind: "install" };
655
+ }
656
+ function questionFor(offer, environment, home) {
657
+ const running = environment.runningVersion;
658
+ const installPath = shown(installPathFor(environment, home), environment, home);
659
+ switch (offer.kind) {
660
+ case "npm": {
661
+ const npmCopy = offer.npmVersion ? `pinggy ${offer.npmVersion}` : "pinggy";
662
+ return `${npmCopy} is installed with npm. Remove it, and install this pinggy, ${running}, to ${installPath}? [Y/n] `;
663
+ }
664
+ case "replace":
665
+ if (offer.installedVersion === null) {
666
+ return `${installPath} does not run. Replace it with this pinggy, ${running}? [Y/n] `;
667
+ }
668
+ return `pinggy ${offer.installedVersion} is installed in ${installPath}. Replace it with this pinggy, ${running}? [Y/n] `;
669
+ case "install":
670
+ return `Install this pinggy, ${running}, to ${installPath}? [Y/n] `;
671
+ }
672
+ }
673
+ function rememberDecline(environment) {
674
+ environment.writeState({ declinedInstallPath: environment.execPath, declinedInstallVersion: environment.runningVersion });
675
+ }
676
+ function npmUninstallCommand(npm) {
677
+ return `npm uninstall -g --prefix ${npm.prefix} ${NPM_PACKAGE2}`;
678
+ }
679
+ function printNpmRemoval(result, npm, environment) {
680
+ switch (result) {
681
+ case NpmRemoval.Removed:
682
+ environment.print("Removed npm's pinggy.");
683
+ environment.print("Open a new terminal to use the installed pinggy.");
684
+ return;
685
+ case NpmRemoval.NotWritable:
686
+ environment.print(`This user cannot change ${npm.prefix}. To remove npm's pinggy, run: sudo ${npmUninstallCommand(npm)}`);
687
+ return;
688
+ case NpmRemoval.NoNpm:
689
+ environment.print(`npm is not on PATH. To remove npm's pinggy, run: ${npmUninstallCommand(npm)}`);
690
+ return;
691
+ case NpmRemoval.Failed:
692
+ environment.print("Could not remove npm's pinggy. If pinggy is running, run: pinggy daemon stop");
693
+ environment.print(`Then run: ${npmUninstallCommand(npm)}`);
694
+ return;
695
+ }
696
+ }
697
+ function warnIfShadowed(environment, home) {
698
+ const found = environment.findPinggyCommand();
699
+ if (found === null) return;
700
+ let expectedFolder;
701
+ if (environment.platform === "win32") {
702
+ expectedFolder = path2.win32.dirname(installPathFor(environment, home));
703
+ if (samePath(path2.win32.dirname(found.commandPath), expectedFolder, "win32")) return;
704
+ } else {
705
+ expectedFolder = path2.posix.join(home, LINK_DIRECTORY);
706
+ const folders = pathFolders(environment.platform, environment.variables.PATH ?? "").map((folder2) => path2.posix.normalize(`${folder2}/`));
707
+ if (!folders.includes(`${expectedFolder}/`)) return;
708
+ if (found.commandPath === path2.posix.join(expectedFolder, NPM_PACKAGE2)) return;
709
+ }
710
+ const folder = shown(expectedFolder, environment, home);
711
+ environment.print(`Another pinggy, ${shown(found.commandPath, environment, home)}, comes before ${folder} on PATH, so the pinggy command runs it.`);
712
+ environment.print(`Remove it, or move ${folder} earlier in PATH.`);
713
+ }
714
+ async function installAfterYes(offer, environment, home) {
715
+ if (!await environment.acquireLock()) {
716
+ environment.print("Another pinggy is installing or updating. Skipped the install.");
717
+ return;
718
+ }
719
+ try {
720
+ if (!await environment.runInstaller()) {
721
+ environment.print(`Could not install pinggy. To install it later, run: ${installCommandFor(environment.platform)}`);
722
+ rememberDecline(environment);
723
+ return;
724
+ }
725
+ environment.useInstalledBinaryForDaemon(installPathFor(environment, home));
726
+ if (offer.kind === "npm") printNpmRemoval(await environment.removeNpmCopy(offer.npm), offer.npm, environment);
727
+ warnIfShadowed(environment, home);
728
+ } finally {
729
+ environment.releaseLock();
730
+ }
731
+ }
732
+ async function offerSelfInstall(command, createEnvironment = realEnvironment2) {
733
+ let questionShown = false;
734
+ try {
735
+ const environment = createEnvironment();
736
+ if (!passesGates(command, environment) || environment.home === null) return { questionShown };
737
+ const home = environment.home;
738
+ const offer = await decideOffer(environment, home);
739
+ if (!environment.writeState({})) return { questionShown };
740
+ questionShown = true;
741
+ const answer = await environment.ask(questionFor(offer, environment, home));
742
+ if (answer === SelfInstallAnswer.No) rememberDecline(environment);
743
+ if (answer === SelfInstallAnswer.Yes) await installAfterYes(offer, environment, home);
744
+ } catch (error) {
745
+ logger.debug("Self-install check failed", { error: errorMessage(error) });
746
+ }
747
+ return { questionShown };
748
+ }
749
+ function existingFolder(folder) {
750
+ if (!folder) return null;
751
+ try {
752
+ return fs3.statSync(folder).isDirectory() ? folder : null;
753
+ } catch {
754
+ return null;
755
+ }
756
+ }
757
+ function installHome(platform3, variables) {
758
+ if (platform3 === "win32") return existingFolder(variables.LOCALAPPDATA) ? os3.homedir() : null;
759
+ return existingFolder(variables.HOME);
760
+ }
761
+ function isInstalledCopy(platform3, execPath, home, variables) {
762
+ if (platform3 === "win32") {
763
+ if (home === null) return false;
764
+ const installFolder = path2.win32.dirname(installerBinaryPath(platform3, home, variables));
765
+ return samePath(path2.win32.dirname(execPath), installFolder, platform3);
766
+ }
767
+ const kind = detectInstallKind(createInstallProbe());
768
+ return kind === InstallKind.UnixLayout || kind === InstallKind.UnixPlainFile;
769
+ }
770
+ var runForVersion = (binaryPath, args) => new Promise((resolve, reject) => {
771
+ execFile(binaryPath, args, { ...pinggyBinaryRunOptions(), timeout: VERSION_RUN_TIMEOUT_MILLIS }, (error, stdout) => {
772
+ if (error) reject(error);
773
+ else resolve(String(stdout));
774
+ });
775
+ });
776
+ async function cachedBinaryVersion(binaryPath) {
777
+ const stats = fs3.statSync(binaryPath);
778
+ const state = readUpdateState();
779
+ if (state.cachedVersionPath === binaryPath && state.cachedVersionSizeBytes === stats.size && state.cachedVersionModifiedMillis === stats.mtimeMs) {
780
+ return state.cachedVersion || null;
781
+ }
782
+ let version = null;
783
+ try {
784
+ version = await readBinaryVersion(binaryPath, runForVersion);
785
+ } catch (error) {
786
+ logger.debug("The installed pinggy printed no version", { binaryPath, error: errorMessage(error) });
787
+ }
788
+ writeUpdateState({
789
+ cachedVersionPath: binaryPath,
790
+ cachedVersionSizeBytes: stats.size,
791
+ cachedVersionModifiedMillis: stats.mtimeMs,
792
+ cachedVersion: version ?? ""
793
+ });
794
+ return version;
795
+ }
796
+ async function realInstalledBinary(platform3, home, installPath) {
797
+ if (platform3 !== "win32") {
798
+ let isLink;
799
+ try {
800
+ isLink = fs3.lstatSync(installPath).isSymbolicLink();
801
+ } catch {
802
+ return null;
803
+ }
804
+ if (!fs3.existsSync(installPath)) return { path: installPath, version: null };
805
+ const linkVersion = isLink ? readLinkVersion(unixLayoutPaths(home)) : null;
806
+ if (linkVersion) return { path: installPath, version: linkVersion };
807
+ } else if (!fs3.existsSync(installPath)) {
808
+ return null;
809
+ }
810
+ return { path: installPath, version: await cachedBinaryVersion(installPath) };
811
+ }
812
+ function readNpmVersion(npm) {
813
+ try {
814
+ const parsed = JSON.parse(fs3.readFileSync(path2.join(npm.packageFolder, "package.json"), "utf-8"));
815
+ return typeof parsed.version === "string" && parseVersion(parsed.version) ? parsed.version : null;
816
+ } catch {
817
+ return null;
818
+ }
819
+ }
820
+ function askOnTerminal(question) {
821
+ return new Promise((resolve) => {
822
+ const readline = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
823
+ let settled = false;
824
+ const finish = (answer) => {
825
+ if (settled) return;
826
+ settled = true;
827
+ readline.close();
828
+ process.stdin.pause();
829
+ resolve(answer);
830
+ };
831
+ readline.on("SIGINT", () => {
832
+ readline.close();
833
+ process.stdout.write("\n");
834
+ process.exit(INTERRUPTED_EXIT_CODE);
835
+ });
836
+ readline.on("close", () => {
837
+ if (!settled) process.stdout.write("\n");
838
+ finish(SelfInstallAnswer.Closed);
839
+ });
840
+ readline.question(question, (text) => finish(NO_ANSWER.test(text) ? SelfInstallAnswer.No : SelfInstallAnswer.Yes));
841
+ });
842
+ }
843
+ function waitForEnterToClose() {
844
+ return new Promise((resolve) => {
845
+ const readline = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
846
+ readline.on("close", () => resolve());
847
+ readline.on("SIGINT", () => readline.close());
848
+ readline.question("Press Enter to close.", () => readline.close());
849
+ });
850
+ }
851
+ function waitForExit(command, args, options) {
852
+ return new Promise((resolve) => {
853
+ const child = spawn2(command, args, options);
854
+ child.on("error", (error) => {
855
+ logger.debug("Could not start a process", { command, error: errorMessage(error) });
856
+ resolve(null);
857
+ });
858
+ child.on("close", (code) => resolve(code));
859
+ });
860
+ }
861
+ function binaryUrlFor(platform3, execPath) {
862
+ return platform3 === "win32" ? pathToFileURL(execPath).href : `file://${execPath}`;
863
+ }
864
+ function installerEnvironment(platform3, execPath) {
865
+ const environment = {
866
+ ...environmentWithoutDeviceToken(),
867
+ PKG_EXECPATH: "",
868
+ [BINARY_URL_ENV]: binaryUrlFor(platform3, execPath),
869
+ [INSTALL_ONLY_ENV]: "1"
870
+ };
871
+ delete environment[VERSION_ENV];
872
+ return environment;
873
+ }
874
+ function windowsPowerShell() {
875
+ const systemRoot = process.env.SystemRoot;
876
+ return systemRoot ? path2.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
877
+ }
878
+ async function runEmbeddedInstaller(platform3, execPath) {
879
+ const scriptName = platform3 === "win32" ? "install.ps1" : "install.sh";
880
+ const temporaryFolder = fs3.mkdtempSync(path2.join(os3.tmpdir(), "pinggy-install-"));
881
+ try {
882
+ const scriptPath = path2.join(temporaryFolder, scriptName);
883
+ fs3.writeFileSync(scriptPath, fs3.readFileSync(path2.join(SCRIPTS_DIRECTORY, scriptName)), { mode: 384 });
884
+ const options = { stdio: OUTPUT_ONLY, env: installerEnvironment(platform3, execPath) };
885
+ if (platform3 !== "win32") return await waitForExit("/bin/sh", [scriptPath], options) === 0;
886
+ const command = `iex ([IO.File]::ReadAllText('${scriptPath.replace(/'/g, "''")}'))`;
887
+ const encoded = Buffer.from(command, "utf16le").toString("base64");
888
+ return await waitForExit(windowsPowerShell(), ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], options) === 0;
889
+ } catch (error) {
890
+ logger.debug("The install script did not run", { error: errorMessage(error) });
891
+ printer_default.error(`pinggy install: ${errorMessage(error)}`);
892
+ return false;
893
+ } finally {
894
+ fs3.rmSync(temporaryFolder, { recursive: true, force: true });
895
+ }
896
+ }
897
+ function canWrite(folder) {
898
+ try {
899
+ fs3.accessSync(folder, fs3.constants.W_OK);
900
+ return true;
901
+ } catch {
902
+ return false;
903
+ }
904
+ }
905
+ function findNpm(npm, lookup) {
906
+ if (lookup.platform === "win32") {
907
+ const onPath2 = findOnPath(["npm.cmd"], lookup);
908
+ const inPrefix2 = path2.win32.join(npm.prefix, "npm.cmd");
909
+ return onPath2 ?? (lookup.files.isFile(inPrefix2) ? inPrefix2 : null);
910
+ }
911
+ const onPath = findOnPath(["npm"], lookup);
912
+ const inPrefix = path2.posix.join(npm.prefix, "bin", "npm");
913
+ return onPath ?? (lookup.files.isExecutableFile(inPrefix) ? inPrefix : null);
914
+ }
915
+ async function removeNpmCopy(npm) {
916
+ const lookup = processPathLookup();
917
+ if (lookup.platform !== "win32") {
918
+ const folders = [path2.posix.join(npm.prefix, "lib", "node_modules"), path2.posix.join(npm.prefix, "bin")];
919
+ if (!folders.every(canWrite)) return NpmRemoval.NotWritable;
920
+ }
921
+ const npmPath = findNpm(npm, lookup);
922
+ if (npmPath === null) return NpmRemoval.NoNpm;
923
+ printer_default.print(`Running: ${npmUninstallCommand(npm)}`);
924
+ const options = { stdio: OUTPUT_ONLY, env: environmentWithoutDeviceToken() };
925
+ let exitCode;
926
+ if (lookup.platform === "win32") {
927
+ const commandLine = `""${npmPath}" uninstall -g --prefix "${npm.prefix}" ${NPM_PACKAGE2}"`;
928
+ exitCode = await waitForExit(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", commandLine], {
929
+ ...options,
930
+ windowsVerbatimArguments: true
931
+ });
932
+ } else {
933
+ exitCode = await waitForExit(npmPath, ["uninstall", "-g", "--prefix", npm.prefix, NPM_PACKAGE2], options);
934
+ }
935
+ return exitCode === 0 ? NpmRemoval.Removed : NpmRemoval.Failed;
936
+ }
937
+ function realEnvironment2() {
938
+ const platform3 = process.platform;
939
+ const variables = process.env;
940
+ const home = installHome(platform3, variables);
941
+ const execPath = process.execPath;
942
+ return {
943
+ platform: platform3,
944
+ variables,
945
+ isPackaged: isPackagedBinary(),
946
+ stdinIsTerminal: process.stdin.isTTY === true,
947
+ stdoutIsTerminal: process.stdout.isTTY === true,
948
+ execPath,
949
+ runningVersion: getVersion(),
950
+ home,
951
+ fileExists: (filePath) => fs3.existsSync(filePath),
952
+ isInstalledCopy: () => isInstalledCopy(platform3, execPath, home, variables),
953
+ findPinggyCommand: () => findPinggyCommand(processPathLookup()),
954
+ installedBinary: (installPath) => home === null ? Promise.resolve(null) : realInstalledBinary(platform3, home, installPath),
955
+ npmVersion: readNpmVersion,
956
+ readState: readUpdateState,
957
+ writeState: writeUpdateState,
958
+ isLockHeld: isUpdateLockHeld,
959
+ acquireLock: acquireUpdateLock,
960
+ releaseLock: releaseUpdateLock,
961
+ ask: askOnTerminal,
962
+ runInstaller: () => runEmbeddedInstaller(platform3, execPath),
963
+ removeNpmCopy,
964
+ useInstalledBinaryForDaemon: startDaemonFromInstalledBinary,
965
+ print: (line) => printer_default.print(line)
966
+ };
967
+ }
968
+
486
969
  // src/main.ts
487
- import { fileURLToPath } from "url";
970
+ import { fileURLToPath as fileURLToPath2 } from "url";
488
971
  import { argv } from "process";
489
972
  import { platform as platform2 } from "os";
490
973
  import { realpathSync } from "fs";
@@ -659,8 +1142,8 @@ function isValidIpV6Cidr(input) {
659
1142
 
660
1143
  // src/cli/buildConfig.ts
661
1144
  import { TunnelType } from "@pinggy/pinggy";
662
- import fs2 from "fs";
663
- import path from "path";
1145
+ import fs4 from "fs";
1146
+ import path3 from "path";
664
1147
  import { isIP as isIP2 } from "net";
665
1148
  var domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
666
1149
  function removeIPv6Brackets(ip) {
@@ -1030,10 +1513,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
1030
1513
  }
1031
1514
  function storeJson(config, saveconf) {
1032
1515
  if (saveconf) {
1033
- const path5 = saveconf;
1516
+ const path7 = saveconf;
1034
1517
  try {
1035
- fs2.writeFileSync(path5, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
1036
- logger.info(`Configuration saved to ${path5}`);
1518
+ fs4.writeFileSync(path7, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
1519
+ logger.info(`Configuration saved to ${path7}`);
1037
1520
  } catch (err) {
1038
1521
  const msg = err instanceof Error ? err.message : String(err);
1039
1522
  logger.error("Error loading configuration:", msg);
@@ -1043,9 +1526,9 @@ function storeJson(config, saveconf) {
1043
1526
  function loadJsonConfig(config) {
1044
1527
  const configpath = config["conf"];
1045
1528
  if (typeof configpath === "string" && configpath.trim().length > 0) {
1046
- const filepath = path.resolve(configpath);
1529
+ const filepath = path3.resolve(configpath);
1047
1530
  try {
1048
- const data = fs2.readFileSync(filepath, { encoding: "utf-8" });
1531
+ const data = fs4.readFileSync(filepath, { encoding: "utf-8" });
1049
1532
  const json = JSON.parse(data);
1050
1533
  return json;
1051
1534
  } catch (err) {
@@ -1359,7 +1842,7 @@ async function connectTui(opts) {
1359
1842
  const exitMessage = opts.exitMessage || "Stopping tunnel...";
1360
1843
  if (!noTui && process.stdin.isTTY) {
1361
1844
  try {
1362
- const { TunnelTui } = await import("./TunnelTui-6H4NPUNF.js");
1845
+ const { TunnelTui } = await import("./TunnelTui-M5SIZX6B.js");
1363
1846
  const tui = new TunnelTui({
1364
1847
  urls,
1365
1848
  greet,
@@ -1582,7 +2065,7 @@ async function startBackgroundTunnels(configs, values, positionals) {
1582
2065
  client.close();
1583
2066
  }
1584
2067
  async function startAutoStartTunnels() {
1585
- const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-JJUWT2YO.js");
2068
+ const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-6LCHFPQX.js");
1586
2069
  const configs = getAutoStartConfigs2();
1587
2070
  if (configs.length === 0) {
1588
2071
  printer_default.warn("No configs marked for auto-start. Use: pinggy config auto <name>");
@@ -1726,7 +2209,8 @@ function printLogHelp() {
1726
2209
  console.log(" level Print current log level");
1727
2210
  console.log(" level debug|info|error Set log level");
1728
2211
  console.log(" path Print daemon log path");
1729
- console.log(" path <name|id> Print tunnel log path\n");
2212
+ console.log(" path <name|id> Print tunnel log path");
2213
+ console.log(" path libpinggy Print the native library's log path (one file for all tunnels)\n");
1730
2214
  }
1731
2215
  function printConfigHelp() {
1732
2216
  console.log("\nUsage: pinggy config <command> [name] [options]\n");
@@ -1755,6 +2239,7 @@ function printDeviceHelp() {
1755
2239
  console.log(" background");
1756
2240
  console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
1757
2241
  console.log(" background. Without --token: start the enrolled device's agent again");
2242
+ console.log(" start Same as connect");
1758
2243
  console.log(" stop Stop the agent running in the background, until the daemon");
1759
2244
  console.log(" starts again");
1760
2245
  console.log(" status Show whether the agent runs, the enrolment, and the background agent");
@@ -1763,15 +2248,15 @@ function printDeviceHelp() {
1763
2248
  console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.");
1764
2249
  console.log("Each time the daemon starts, it starts the agent again, until remove.\n");
1765
2250
  console.log("Options:");
1766
- console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
1767
- console.log(" -b login and connect: run the agent in the background. The default");
2251
+ console.log(" --foreground login, connect and start: run the agent in this terminal until Ctrl+C");
2252
+ console.log(" -b login, connect and start: run the agent in the background. The default");
1768
2253
  console.log(" --token <TOKEN> Device token from the dashboard");
1769
2254
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
1770
2255
  console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
1771
2256
  console.log(" -f remove only: remove without asking\n");
1772
2257
  console.log("Environment:");
1773
- console.log(" DEVICE_AGENT_TOKEN connect only: the device token, when --token is not given. With no");
1774
- console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
2258
+ console.log(" DEVICE_AGENT_TOKEN connect and start: the device token, when --token is not given.");
2259
+ console.log(" With no --manage, it dials dashboard.pinggy.io. Removed once read\n");
1775
2260
  }
1776
2261
  function printUpdateHelp() {
1777
2262
  console.log("\nUsage: pinggy update [--check | --rollback]\n");
@@ -1785,15 +2270,15 @@ function printUpdateHelp() {
1785
2270
  import pico5 from "picocolors";
1786
2271
 
1787
2272
  // src/devices/deviceIdentity.ts
1788
- import fs3 from "fs";
2273
+ import fs5 from "fs";
1789
2274
  var SECRET_FILE_MODE = 384;
1790
2275
  function readDeviceIdentity() {
1791
2276
  const filePath = getDeviceConfigPath();
1792
- if (!fs3.existsSync(filePath)) {
2277
+ if (!fs5.existsSync(filePath)) {
1793
2278
  return null;
1794
2279
  }
1795
2280
  try {
1796
- return JSON.parse(fs3.readFileSync(filePath, "utf-8"));
2281
+ return JSON.parse(fs5.readFileSync(filePath, "utf-8"));
1797
2282
  } catch (e) {
1798
2283
  logger.warn("Could not read device identity file", { error: String(e) });
1799
2284
  return null;
@@ -1802,18 +2287,18 @@ function readDeviceIdentity() {
1802
2287
  function writeDeviceIdentity(identity) {
1803
2288
  ensurePinggyConfigDir();
1804
2289
  const filePath = getDeviceConfigPath();
1805
- fs3.writeFileSync(filePath, JSON.stringify(identity, null, 2), {
2290
+ fs5.writeFileSync(filePath, JSON.stringify(identity, null, 2), {
1806
2291
  encoding: "utf-8",
1807
2292
  mode: SECRET_FILE_MODE
1808
2293
  });
1809
- fs3.chmodSync(filePath, SECRET_FILE_MODE);
2294
+ fs5.chmodSync(filePath, SECRET_FILE_MODE);
1810
2295
  }
1811
2296
  function clearDeviceIdentity() {
1812
2297
  const filePath = getDeviceConfigPath();
1813
- if (!fs3.existsSync(filePath)) {
2298
+ if (!fs5.existsSync(filePath)) {
1814
2299
  return false;
1815
2300
  }
1816
- fs3.unlinkSync(filePath);
2301
+ fs5.unlinkSync(filePath);
1817
2302
  return true;
1818
2303
  }
1819
2304
  function maskToken(token) {
@@ -1822,7 +2307,7 @@ function maskToken(token) {
1822
2307
 
1823
2308
  // src/devices/deviceAgent.ts
1824
2309
  import WebSocket from "ws";
1825
- import os8 from "os";
2310
+ import os9 from "os";
1826
2311
 
1827
2312
  // src/devices/envelope.ts
1828
2313
  import { randomUUID } from "crypto";
@@ -1937,27 +2422,27 @@ var printingReporter = {
1937
2422
  };
1938
2423
 
1939
2424
  // src/devices/collectors/systemInfo.ts
1940
- import os3 from "os";
2425
+ import os4 from "os";
1941
2426
  var UNKNOWN_CPU_MODEL = "unknown";
1942
2427
  function collectSystemInfo() {
1943
- const cpus = os3.cpus();
2428
+ const cpus = os4.cpus();
1944
2429
  return {
1945
- hostname: os3.hostname(),
1946
- os: os3.platform(),
1947
- os_version: os3.release(),
2430
+ hostname: os4.hostname(),
2431
+ os: os4.platform(),
2432
+ os_version: os4.release(),
1948
2433
  // os.machine() reports what uname does (x86_64, arm64, aarch64). os.arch() reports the Node
1949
2434
  // build target (x64), which is not what an operator reads on the machine itself.
1950
- arch: os3.machine(),
1951
- kernel: os3.type(),
2435
+ arch: os4.machine(),
2436
+ kernel: os4.type(),
1952
2437
  // os.cpus() is empty on some Android and container builds.
1953
2438
  cpu_model: cpus[0]?.model?.trim() || UNKNOWN_CPU_MODEL,
1954
2439
  cpu_cores: cpus.length,
1955
- total_memory_bytes: os3.totalmem()
2440
+ total_memory_bytes: os4.totalmem()
1956
2441
  };
1957
2442
  }
1958
2443
 
1959
2444
  // src/devices/collectors/metrics.ts
1960
- import os4 from "os";
2445
+ import os5 from "os";
1961
2446
  var CPU_SAMPLE_WINDOW_MS = 200;
1962
2447
  function sumCpuTicks(cpus) {
1963
2448
  let idleTicks = 0;
@@ -1991,18 +2476,32 @@ function buildMetrics(readings) {
1991
2476
  collected_at: readings.collectedAtEpochSeconds
1992
2477
  };
1993
2478
  }
1994
- async function collectMetrics() {
1995
- const earlier = sumCpuTicks(os4.cpus());
2479
+ function ticksMovedForward(earlier, later) {
2480
+ return later.totalTicks > earlier.totalTicks && later.idleTicks >= earlier.idleTicks;
2481
+ }
2482
+ async function readCpuPercent(previousTicks, readCpus) {
2483
+ const currentTicks = sumCpuTicks(readCpus());
2484
+ if (previousTicks && ticksMovedForward(previousTicks, currentTicks)) {
2485
+ return { cpuPercent: cpuPercentBetween(previousTicks, currentTicks), endTicks: currentTicks };
2486
+ }
1996
2487
  await new Promise((resolve) => setTimeout(resolve, CPU_SAMPLE_WINDOW_MS));
1997
- const later = sumCpuTicks(os4.cpus());
1998
- return buildMetrics({
1999
- cpuPercent: cpuPercentBetween(earlier, later),
2000
- loadAverages: os4.loadavg(),
2001
- totalMemoryBytes: os4.totalmem(),
2002
- freeMemoryBytes: os4.freemem(),
2003
- uptimeSeconds: os4.uptime(),
2004
- collectedAtEpochSeconds: Math.floor(Date.now() / 1e3)
2005
- });
2488
+ const laterTicks = sumCpuTicks(readCpus());
2489
+ return { cpuPercent: cpuPercentBetween(currentTicks, laterTicks), endTicks: laterTicks };
2490
+ }
2491
+ function createMetricsCollector(readCpus = () => os5.cpus()) {
2492
+ let previousTicks = null;
2493
+ return async () => {
2494
+ const cpuReading = await readCpuPercent(previousTicks, readCpus);
2495
+ previousTicks = cpuReading.endTicks;
2496
+ return buildMetrics({
2497
+ cpuPercent: cpuReading.cpuPercent,
2498
+ loadAverages: os5.loadavg(),
2499
+ totalMemoryBytes: os5.totalmem(),
2500
+ freeMemoryBytes: os5.freemem(),
2501
+ uptimeSeconds: os5.uptime(),
2502
+ collectedAtEpochSeconds: Math.floor(Date.now() / 1e3)
2503
+ });
2504
+ };
2006
2505
  }
2007
2506
 
2008
2507
  // src/devices/tunnels/tunnelList.ts
@@ -2495,7 +2994,7 @@ function clampGrid(requested, fallback) {
2495
2994
 
2496
2995
  // src/devices/terminal/terminalHandler.ts
2497
2996
  import { randomUUID as randomUUID2 } from "crypto";
2498
- import os6 from "os";
2997
+ import os7 from "os";
2499
2998
 
2500
2999
  // src/devices/terminal/flowWindow.ts
2501
3000
  var FlowWindow = class {
@@ -2619,9 +3118,9 @@ var FrameSplitter = class {
2619
3118
  };
2620
3119
 
2621
3120
  // src/devices/terminal/shellContext.ts
2622
- import { execFile } from "child_process";
2623
- import fs4 from "fs";
2624
- import os5 from "os";
3121
+ import { execFile as execFile2 } from "child_process";
3122
+ import fs6 from "fs";
3123
+ import os6 from "os";
2625
3124
  var SHELL_CONTEXT_POLL_MILLIS = 5e3;
2626
3125
  var MAX_CWD_CHARACTERS = 1024;
2627
3126
  var MAX_COMMAND_CHARACTERS = 64;
@@ -2642,17 +3141,17 @@ function programName(rawName) {
2642
3141
  function displayCwd(rawCwd, resolvedHome) {
2643
3142
  const cwd = cleanText(rawCwd, Number.MAX_SAFE_INTEGER);
2644
3143
  if (cwd === null) return null;
2645
- let shown = cwd;
3144
+ let shown2 = cwd;
2646
3145
  if (resolvedHome && cwd === resolvedHome) {
2647
- shown = HOME_PREFIX;
3146
+ shown2 = HOME_PREFIX;
2648
3147
  } else if (resolvedHome && cwd.startsWith(resolvedHome + "/")) {
2649
- shown = HOME_PREFIX + cwd.slice(resolvedHome.length);
3148
+ shown2 = HOME_PREFIX + cwd.slice(resolvedHome.length);
2650
3149
  }
2651
- return truncate(shown, MAX_CWD_CHARACTERS);
3150
+ return truncate(shown2, MAX_CWD_CHARACTERS);
2652
3151
  }
2653
3152
  function resolvedHomeDirectory() {
2654
3153
  try {
2655
- return fs4.realpathSync(os5.homedir());
3154
+ return fs6.realpathSync(os6.homedir());
2656
3155
  } catch {
2657
3156
  return null;
2658
3157
  }
@@ -2704,14 +3203,14 @@ async function readFromProc(shellPids) {
2704
3203
  await Promise.all(shellPids.map(async (shellPid) => {
2705
3204
  const groups = await readProcGroups(shellPid);
2706
3205
  if (!groups) return;
2707
- const cwd = await readOrNull(() => fs4.promises.readlink(`/proc/${shellPid}/cwd`));
2708
- const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() => fs4.promises.readFile(`/proc/${groups.foregroundGroupId}/comm`, "utf8"));
3206
+ const cwd = await readOrNull(() => fs6.promises.readlink(`/proc/${shellPid}/cwd`));
3207
+ const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() => fs6.promises.readFile(`/proc/${groups.foregroundGroupId}/comm`, "utf8"));
2709
3208
  contexts.set(shellPid, { cwd, foregroundName });
2710
3209
  }));
2711
3210
  return contexts;
2712
3211
  }
2713
3212
  async function readProcGroups(shellPid) {
2714
- const stat = await readOrNull(() => fs4.promises.readFile(`/proc/${shellPid}/stat`, "utf8"));
3213
+ const stat = await readOrNull(() => fs6.promises.readFile(`/proc/${shellPid}/stat`, "utf8"));
2715
3214
  if (stat === null) return null;
2716
3215
  const afterName = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
2717
3216
  const shellGroupId = Number.parseInt(afterName[2], 10);
@@ -2766,7 +3265,7 @@ function parseLsofCwds(stdout) {
2766
3265
  }
2767
3266
  function run(program, args) {
2768
3267
  return new Promise((resolve) => {
2769
- execFile(program, args, { timeout: PROCESS_READ_TIMEOUT_MILLIS }, (err, stdout) => {
3268
+ execFile2(program, args, { timeout: PROCESS_READ_TIMEOUT_MILLIS }, (err, stdout) => {
2770
3269
  const output = String(stdout ?? "");
2771
3270
  resolve(err && output === "" ? null : output);
2772
3271
  });
@@ -3635,7 +4134,7 @@ function errorName2(err) {
3635
4134
  return err instanceof Error ? err.name : typeof err;
3636
4135
  }
3637
4136
  function signalName(signal) {
3638
- for (const [name, number] of Object.entries(os6.constants.signals)) {
4137
+ for (const [name, number] of Object.entries(os7.constants.signals)) {
3639
4138
  if (number === signal) return name.replace(/^SIG/, "");
3640
4139
  }
3641
4140
  return String(signal);
@@ -3695,14 +4194,14 @@ var TerminalRegistry = class {
3695
4194
  };
3696
4195
 
3697
4196
  // src/devices/terminal/ptySession.ts
3698
- import { execFile as execFile2 } from "child_process";
3699
- import fs5 from "fs";
3700
- import os7 from "os";
4197
+ import { execFile as execFile3 } from "child_process";
4198
+ import fs7 from "fs";
4199
+ import os8 from "os";
3701
4200
  var loadedPty;
3702
4201
  var TERM_NAME = "xterm-256color";
3703
4202
  function foregroundProcessGroup(shellPid) {
3704
4203
  return new Promise((resolve) => {
3705
- execFile2("ps", ["-o", "tpgid=", "-p", String(shellPid)], (err, stdout) => {
4204
+ execFile3("ps", ["-o", "tpgid=", "-p", String(shellPid)], (err, stdout) => {
3706
4205
  const processGroupId = err ? NaN : Number.parseInt(String(stdout).trim(), 10);
3707
4206
  resolve(Number.isInteger(processGroupId) && processGroupId > 0 ? processGroupId : null);
3708
4207
  });
@@ -3745,11 +4244,11 @@ function ensureSpawnHelperExecutable(packageRoot) {
3745
4244
  function resolveCwd(requested) {
3746
4245
  if (requested) {
3747
4246
  try {
3748
- if (fs5.statSync(requested).isDirectory()) return requested;
4247
+ if (fs7.statSync(requested).isDirectory()) return requested;
3749
4248
  } catch {
3750
4249
  }
3751
4250
  }
3752
- return os7.homedir();
4251
+ return os8.homedir();
3753
4252
  }
3754
4253
  function spawnPty(request2) {
3755
4254
  const pty = loadNodePty();
@@ -3795,14 +4294,14 @@ function spawnPty(request2) {
3795
4294
  }
3796
4295
 
3797
4296
  // src/devices/terminal/shellAllowlist.ts
3798
- import fs6 from "fs";
4297
+ import fs8 from "fs";
3799
4298
  var FALLBACK_UNIX_SHELLS = ["/bin/bash", "/bin/zsh", "/bin/sh", "/usr/bin/bash", "/usr/bin/zsh"];
3800
4299
  var WINDOWS_SHELLS = ["powershell.exe", "cmd.exe"];
3801
4300
  var ETC_SHELLS_PATH = "/etc/shells";
3802
4301
  function readShellEnvironment() {
3803
4302
  let etcShells = null;
3804
4303
  try {
3805
- etcShells = fs6.readFileSync(ETC_SHELLS_PATH, "utf8");
4304
+ etcShells = fs8.readFileSync(ETC_SHELLS_PATH, "utf8");
3806
4305
  } catch {
3807
4306
  etcShells = null;
3808
4307
  }
@@ -3810,9 +4309,9 @@ function readShellEnvironment() {
3810
4309
  platform: process.platform,
3811
4310
  loginShell: process.env.SHELL,
3812
4311
  etcShells,
3813
- exists: (path5) => {
4312
+ exists: (path7) => {
3814
4313
  try {
3815
- return fs6.statSync(path5).isFile();
4314
+ return fs8.statSync(path7).isFile();
3816
4315
  } catch {
3817
4316
  return false;
3818
4317
  }
@@ -3845,13 +4344,13 @@ function resolveShell(requested, environment) {
3845
4344
  }
3846
4345
 
3847
4346
  // src/devices/foregroundAgent.ts
3848
- import fs7 from "fs";
4347
+ import fs9 from "fs";
3849
4348
  var RECORD_CHECK_INTERVAL_MILLIS = 1e3;
3850
4349
  var STOP_WAIT_MILLIS = 1e4;
3851
4350
  var STOP_POLL_INTERVAL_MILLIS = 200;
3852
4351
  function readRecordFile(filePath) {
3853
4352
  try {
3854
- const record = JSON.parse(fs7.readFileSync(filePath, "utf-8"));
4353
+ const record = JSON.parse(fs9.readFileSync(filePath, "utf-8"));
3855
4354
  return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
3856
4355
  } catch {
3857
4356
  return null;
@@ -3859,7 +4358,7 @@ function readRecordFile(filePath) {
3859
4358
  }
3860
4359
  function deleteRecordFile(filePath) {
3861
4360
  try {
3862
- fs7.unlinkSync(filePath);
4361
+ fs9.unlinkSync(filePath);
3863
4362
  } catch (err) {
3864
4363
  logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
3865
4364
  }
@@ -3873,7 +4372,7 @@ function readForegroundAgent() {
3873
4372
  if (record.pid === process.pid) {
3874
4373
  return null;
3875
4374
  }
3876
- if (startedBeforeBoot(record.started_at) || !isProcessAlive(record.pid)) {
4375
+ if (startedInEarlierBoot(record.boot_id, record.started_at) || !isProcessAlive(record.pid)) {
3877
4376
  logger.info("Stale device-agent.json found, cleaning up", { stalePid: record.pid });
3878
4377
  deleteRecordFile(filePath);
3879
4378
  return null;
@@ -3882,10 +4381,14 @@ function readForegroundAgent() {
3882
4381
  }
3883
4382
  function recordForegroundAgent(onRecordDeleted) {
3884
4383
  const filePath = getForegroundAgentPath();
3885
- const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
4384
+ const record = {
4385
+ pid: process.pid,
4386
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
4387
+ boot_id: currentBootId() ?? void 0
4388
+ };
3886
4389
  try {
3887
4390
  ensurePinggyConfigDir();
3888
- fs7.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
4391
+ fs9.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
3889
4392
  } catch (err) {
3890
4393
  logger.warn(
3891
4394
  "Could not write device-agent.json. pinggy device remove cannot stop this agent.",
@@ -3894,7 +4397,7 @@ function recordForegroundAgent(onRecordDeleted) {
3894
4397
  return () => void 0;
3895
4398
  }
3896
4399
  const timer = setInterval(() => {
3897
- if (!fs7.existsSync(filePath)) {
4400
+ if (!fs9.existsSync(filePath)) {
3898
4401
  clearInterval(timer);
3899
4402
  onRecordDeleted();
3900
4403
  }
@@ -3988,8 +4491,8 @@ function sleep(millis, state) {
3988
4491
  function buildHello(terminalHandler) {
3989
4492
  return {
3990
4493
  agent_version: getVersion(),
3991
- os: os8.platform(),
3992
- hostname: os8.hostname(),
4494
+ os: os9.platform(),
4495
+ hostname: os9.hostname(),
3993
4496
  capabilities: buildCapabilities(isTerminalSupported(), isScreenMirrorSupported()),
3994
4497
  terminals: terminalHandler.held()
3995
4498
  };
@@ -4184,7 +4687,7 @@ function connectOnce(context) {
4184
4687
  const startHeartbeat = (intervalSeconds) => {
4185
4688
  heartbeat = setInterval(
4186
4689
  () => sendFrame(
4187
- event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(os8.uptime()) })
4690
+ event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(os9.uptime()) })
4188
4691
  ),
4189
4692
  intervalSeconds * 1e3
4190
4693
  );
@@ -4211,7 +4714,7 @@ function connectOnce(context) {
4211
4714
  sendFrame(event(CHANNEL_DEVICE, OP_INFO, collectSystemInfo()));
4212
4715
  stopMetrics = startMetricsReporting(
4213
4716
  welcome.stats_interval_seconds,
4214
- collectMetrics,
4717
+ createMetricsCollector(),
4215
4718
  (metrics) => sendFrame(event(CHANNEL_DEVICE, OP_METRICS, metrics))
4216
4719
  );
4217
4720
  stopTunnels = startTunnelReporting(
@@ -4332,7 +4835,7 @@ function describeDisconnect(reason) {
4332
4835
  }
4333
4836
 
4334
4837
  // src/devices/login/deviceLogin.ts
4335
- import os9 from "os";
4838
+ import os10 from "os";
4336
4839
  import pico4 from "picocolors";
4337
4840
 
4338
4841
  // src/devices/login/login_schema.ts
@@ -4393,8 +4896,8 @@ var DeviceLoginApiError = class extends Error {
4393
4896
  var UNREADABLE_ANSWER = "invalid_answer";
4394
4897
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
4395
4898
  const baseUrl = buildDashboardHttpUrl(manage);
4396
- async function post(path5, body, schema) {
4397
- const response2 = await fetchImpl(`${baseUrl}/${path5}`, {
4899
+ async function post(path7, body, schema) {
4900
+ const response2 = await fetchImpl(`${baseUrl}/${path7}`, {
4398
4901
  method: "POST",
4399
4902
  headers: { "Content-Type": "application/json", Accept: "application/json" },
4400
4903
  body: JSON.stringify(body)
@@ -4442,13 +4945,13 @@ async function readJson(response2) {
4442
4945
 
4443
4946
  // src/devices/login/prompts.ts
4444
4947
  import pico3 from "picocolors";
4445
- import { createInterface } from "readline/promises";
4948
+ import { createInterface as createInterface2 } from "readline/promises";
4446
4949
  import { Writable } from "stream";
4447
4950
  var QUESTION_MARKER = pico3.cyan(pico3.bold("\u2192"));
4448
4951
  function createTerminalPrompter(input, output) {
4449
4952
  return {
4450
4953
  async ask(question, signal) {
4451
- const readline = createInterface({ input, output, terminal: true });
4954
+ const readline = createInterface2({ input, output, terminal: true });
4452
4955
  try {
4453
4956
  return await readline.question(marked(question), signal ? { signal } : {});
4454
4957
  } finally {
@@ -4457,7 +4960,7 @@ function createTerminalPrompter(input, output) {
4457
4960
  },
4458
4961
  async askHidden(question, signal) {
4459
4962
  output.write(marked(question));
4460
- const readline = createInterface({ input, output: discardingOutput(), terminal: true });
4963
+ const readline = createInterface2({ input, output: discardingOutput(), terminal: true });
4461
4964
  try {
4462
4965
  const answer = await readline.question("", signal ? { signal } : {});
4463
4966
  output.write("\n");
@@ -4504,9 +5007,9 @@ function machineDeviceLoginDependencies() {
4504
5007
  runAgent: (token, manage) => runDeviceAgent(token, manage),
4505
5008
  renderQr: async (url) => (await createQrCodes([url]))[0],
4506
5009
  machine: () => ({
4507
- hostname: os9.hostname(),
4508
- os: os9.platform(),
4509
- arch: os9.arch(),
5010
+ hostname: os10.hostname(),
5011
+ os: os10.platform(),
5012
+ arch: os10.arch(),
4510
5013
  agent_version: getVersion()
4511
5014
  }),
4512
5015
  print: (message) => printer_default.print(message),
@@ -4741,7 +5244,8 @@ var CONNECT_WAIT_MILLIS = 15e3;
4741
5244
  var MANAGE_COMMANDS = [
4742
5245
  ["pinggy device status", "Show this device, and whether its agent runs"],
4743
5246
  ["pinggy device stop", "Stop the agent until the daemon starts again. The device shows offline"],
4744
- ["pinggy device connect", "Start the agent again after a stop"],
5247
+ ["pinggy device start", "Start the agent again after a stop"],
5248
+ ["pinggy device connect", "Same as start"],
4745
5249
  ["pinggy device remove", "Stop the agent and forget this machine's credential"]
4746
5250
  ];
4747
5251
  var verifyingReporter = {
@@ -4876,7 +5380,7 @@ function describeDeviceState(reading, daemonFound, foreground) {
4876
5380
  return pico5.green("running, with --foreground in another terminal");
4877
5381
  }
4878
5382
  if (reading || !daemonFound) {
4879
- return `${pico5.red("stopped")}. To start it, run: pinggy device connect`;
5383
+ return `${pico5.red("stopped")}. To start it, run: pinggy device start or pinggy device connect`;
4880
5384
  }
4881
5385
  return pico5.gray("unknown, could not read the daemon");
4882
5386
  }
@@ -5251,11 +5755,11 @@ async function handleAttach(args) {
5251
5755
  }
5252
5756
 
5253
5757
  // src/cli/subcommand/handlers/logsCommand.ts
5254
- import fs9 from "fs";
5758
+ import fs11 from "fs";
5255
5759
 
5256
5760
  // src/daemon/logPaths.ts
5257
- import fs8 from "fs";
5258
- import path2 from "path";
5761
+ import fs10 from "fs";
5762
+ import path4 from "path";
5259
5763
  var TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
5260
5764
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5261
5765
  function parseTunnelLogFilename(filename) {
@@ -5275,8 +5779,8 @@ function parseTunnelLogFilename(filename) {
5275
5779
  }
5276
5780
  function listTunnelLogFiles() {
5277
5781
  const logDir = getTunnelLogDir();
5278
- if (!fs8.existsSync(logDir)) return [];
5279
- return fs8.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
5782
+ if (!fs10.existsSync(logDir)) return [];
5783
+ return fs10.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
5280
5784
  }
5281
5785
  function newestLogFile(q) {
5282
5786
  const logDir = getTunnelLogDir();
@@ -5287,8 +5791,8 @@ function newestLogFile(q) {
5287
5791
  const nameMatch = parsed.name !== void 0 && parsed.name === q;
5288
5792
  const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
5289
5793
  if (nameMatch || idMatch) {
5290
- const filePath = path2.join(logDir, file);
5291
- matches.push({ ...parsed, path: filePath, mtime: fs8.statSync(filePath).mtimeMs });
5794
+ const filePath = path4.join(logDir, file);
5795
+ matches.push({ ...parsed, path: filePath, mtime: fs10.statSync(filePath).mtimeMs });
5292
5796
  }
5293
5797
  }
5294
5798
  if (matches.length === 0) return null;
@@ -5309,18 +5813,25 @@ function resolveStoppedLogPath(q) {
5309
5813
  }
5310
5814
 
5311
5815
  // src/cli/subcommand/handlers/logLookup.ts
5816
+ var LIBPINGGY_LOG_NAME = "libpinggy";
5817
+ function orLibpinggyLog(nameOrId, result) {
5818
+ if (nameOrId === LIBPINGGY_LOG_NAME && result.status === "not-found") {
5819
+ return { status: "libpinggy", path: getLibpinggyLogPath() };
5820
+ }
5821
+ return result;
5822
+ }
5312
5823
  function openLogLookup() {
5313
5824
  const client = new TunnelClient();
5314
5825
  if (!client.connectIfRunning()) {
5315
5826
  return {
5316
5827
  daemonLogPath: () => Promise.resolve(getDaemonLogPath()),
5317
- resolve: (nameOrId) => Promise.resolve(resolveStoppedLogPath(nameOrId)),
5828
+ resolve: (nameOrId) => Promise.resolve(orLibpinggyLog(nameOrId, resolveStoppedLogPath(nameOrId))),
5318
5829
  close: () => void 0
5319
5830
  };
5320
5831
  }
5321
5832
  return {
5322
5833
  daemonLogPath: async () => (await client.getLogPaths()).daemon,
5323
- resolve: (nameOrId) => client.resolveLogPath(nameOrId),
5834
+ resolve: async (nameOrId) => orLibpinggyLog(nameOrId, await client.resolveLogPath(nameOrId)),
5324
5835
  close: () => client.close()
5325
5836
  };
5326
5837
  }
@@ -5364,7 +5875,7 @@ async function handleLogs(args, follow) {
5364
5875
  return;
5365
5876
  }
5366
5877
  client.close();
5367
- if (!filePath || !fs9.existsSync(filePath)) {
5878
+ if (!filePath || !fs11.existsSync(filePath)) {
5368
5879
  printer_default.error(`Log file not found: ${filePath}`);
5369
5880
  process.exit(1);
5370
5881
  }
@@ -5375,18 +5886,18 @@ async function handleLogs(args, follow) {
5375
5886
  }
5376
5887
  }
5377
5888
  function printTail(filePath, lines) {
5378
- const content = fs9.readFileSync(filePath, "utf-8");
5889
+ const content = fs11.readFileSync(filePath, "utf-8");
5379
5890
  const allLines = content.split("\n");
5380
5891
  const tail = allLines.slice(-lines).join("\n");
5381
5892
  process.stdout.write(tail);
5382
5893
  if (!tail.endsWith("\n")) process.stdout.write("\n");
5383
5894
  }
5384
5895
  async function followFile(filePath) {
5385
- if (fs9.existsSync(filePath)) printTail(filePath, 20);
5386
- let fileSize = fs9.existsSync(filePath) ? fs9.statSync(filePath).size : 0;
5896
+ if (fs11.existsSync(filePath)) printTail(filePath, 20);
5897
+ let fileSize = fs11.existsSync(filePath) ? fs11.statSync(filePath).size : 0;
5387
5898
  let watcher = null;
5388
5899
  const openStream = () => {
5389
- const stream = fs9.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
5900
+ const stream = fs11.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
5390
5901
  stream.on("data", (chunk) => {
5391
5902
  process.stdout.write(chunk);
5392
5903
  fileSize += Buffer.byteLength(chunk, "utf-8");
@@ -5394,9 +5905,9 @@ async function followFile(filePath) {
5394
5905
  stream.on("error", () => {
5395
5906
  });
5396
5907
  };
5397
- watcher = fs9.watch(filePath, { persistent: true }, (event2) => {
5908
+ watcher = fs11.watch(filePath, { persistent: true }, (event2) => {
5398
5909
  if (event2 === "change") {
5399
- const stat = fs9.existsSync(filePath) ? fs9.statSync(filePath) : null;
5910
+ const stat = fs11.existsSync(filePath) ? fs11.statSync(filePath) : null;
5400
5911
  if (!stat || stat.size < fileSize) {
5401
5912
  fileSize = 0;
5402
5913
  }
@@ -5491,6 +6002,7 @@ async function handleLogPath(args) {
5491
6002
  switch (result.status) {
5492
6003
  case "running":
5493
6004
  case "historical":
6005
+ case "libpinggy":
5494
6006
  printer_default.print(result.path);
5495
6007
  break;
5496
6008
  case "config-only":
@@ -5640,6 +6152,7 @@ async function runDeviceRemove(options, dependencies) {
5640
6152
  var DeviceVerb = {
5641
6153
  Login: "login",
5642
6154
  Connect: "connect",
6155
+ Start: "start",
5643
6156
  Stop: "stop",
5644
6157
  Status: "status",
5645
6158
  Remove: "remove"
@@ -5682,6 +6195,7 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
5682
6195
  exitUnlessOk(await handleDeviceLogin(values.manage, values.name, inBackground, background));
5683
6196
  return;
5684
6197
  case DeviceVerb.Connect:
6198
+ case DeviceVerb.Start:
5685
6199
  exitUnlessOk(await handleDeviceConnect(
5686
6200
  values.token,
5687
6201
  environmentToken,
@@ -5707,7 +6221,7 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
5707
6221
  printDeviceHelp();
5708
6222
  return;
5709
6223
  }
5710
- printer_default.error(`Unknown command "${verb}". Valid commands: login, connect, stop, status, remove.`);
6224
+ printer_default.error(`Unknown command "${verb}". Valid commands: login, connect, start, stop, status, remove.`);
5711
6225
  process.exit(1);
5712
6226
  }
5713
6227
  }
@@ -6225,12 +6739,12 @@ async function initRemoteManagementBackground(values) {
6225
6739
  }
6226
6740
 
6227
6741
  // src/daemon/lifecycle/daemonChild.ts
6228
- import fs13 from "fs";
6742
+ import fs15 from "fs";
6229
6743
 
6230
6744
  // src/daemon/ipc/ipcServer.ts
6231
6745
  import http from "http";
6232
- import fs11 from "fs";
6233
- import path4 from "path";
6746
+ import fs13 from "fs";
6747
+ import path6 from "path";
6234
6748
  import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
6235
6749
 
6236
6750
  // src/daemon/ws/wsProtocol.ts
@@ -6257,17 +6771,17 @@ function parseClientMessage(raw) {
6257
6771
  }
6258
6772
 
6259
6773
  // src/daemon/lifecycle/stateStore.ts
6260
- import fs10 from "fs";
6261
- import path3 from "path";
6774
+ import fs12 from "fs";
6775
+ import path5 from "path";
6262
6776
  var STATE_FILENAME = "daemon-state.json";
6263
6777
  function getStatePath() {
6264
- return path3.join(getPinggyConfigDir(), STATE_FILENAME);
6778
+ return path5.join(getPinggyConfigDir(), STATE_FILENAME);
6265
6779
  }
6266
6780
  function loadDaemonState() {
6267
6781
  const statePath = getStatePath();
6268
6782
  try {
6269
- if (!fs10.existsSync(statePath)) return null;
6270
- const raw = fs10.readFileSync(statePath, "utf-8");
6783
+ if (!fs12.existsSync(statePath)) return null;
6784
+ const raw = fs12.readFileSync(statePath, "utf-8");
6271
6785
  const state = JSON.parse(raw);
6272
6786
  if (!Array.isArray(state.tunnels)) return null;
6273
6787
  return state;
@@ -6281,8 +6795,8 @@ function persistDaemonState(state) {
6281
6795
  const tmpPath = statePath + ".tmp";
6282
6796
  try {
6283
6797
  state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
6284
- fs10.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
6285
- fs10.renameSync(tmpPath, statePath);
6798
+ fs12.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
6799
+ fs12.renameSync(tmpPath, statePath);
6286
6800
  } catch (err) {
6287
6801
  logger.error("Failed to persist daemon state", { error: errorMessage(err) });
6288
6802
  }
@@ -6290,8 +6804,8 @@ function persistDaemonState(state) {
6290
6804
  function clearDaemonState() {
6291
6805
  const statePath = getStatePath();
6292
6806
  try {
6293
- if (fs10.existsSync(statePath)) {
6294
- fs10.unlinkSync(statePath);
6807
+ if (fs12.existsSync(statePath)) {
6808
+ fs12.unlinkSync(statePath);
6295
6809
  }
6296
6810
  } catch {
6297
6811
  }
@@ -6444,6 +6958,8 @@ var IPCServer = class {
6444
6958
  [Route.SetTunnelLogging]: (req) => {
6445
6959
  if (typeof req.enabled !== "boolean") throw new Error("Missing 'enabled' boolean");
6446
6960
  setTunnelLoggingEnabled(req.enabled);
6961
+ setNativeLogging(req.enabled);
6962
+ TunnelManager.getInstance().applyLogLevelToActiveTunnels(getLogLevel());
6447
6963
  return { enabled: isTunnelLoggingEnabled() };
6448
6964
  },
6449
6965
  [Route.GetLogPaths]: async () => {
@@ -6461,8 +6977,8 @@ var IPCServer = class {
6461
6977
  if (n) activeNames.add(n);
6462
6978
  }
6463
6979
  for (const file of files) {
6464
- const filePath = path4.join(logDir, file);
6465
- const stat = fs11.statSync(filePath);
6980
+ const filePath = path6.join(logDir, file);
6981
+ const stat = fs13.statSync(filePath);
6466
6982
  const parsed = parseTunnelLogFilename(file);
6467
6983
  if (!parsed) continue;
6468
6984
  const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
@@ -7108,11 +7624,11 @@ function machineDeviceAgentHostDependencies(port, record) {
7108
7624
  }
7109
7625
 
7110
7626
  // src/daemon/lifecycle/daemonLock.ts
7111
- import fs12 from "fs";
7627
+ import fs14 from "fs";
7112
7628
  var UNREADABLE_LOCK_GRACE_MILLIS = 1e4;
7113
7629
  function readLock(lockPath) {
7114
7630
  try {
7115
- const record = JSON.parse(fs12.readFileSync(lockPath, "utf-8"));
7631
+ const record = JSON.parse(fs14.readFileSync(lockPath, "utf-8"));
7116
7632
  return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
7117
7633
  } catch {
7118
7634
  return null;
@@ -7120,18 +7636,18 @@ function readLock(lockPath) {
7120
7636
  }
7121
7637
  function isUnreadableLockOld(lockPath) {
7122
7638
  try {
7123
- return Date.now() - fs12.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
7639
+ return Date.now() - fs14.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
7124
7640
  } catch {
7125
7641
  return true;
7126
7642
  }
7127
7643
  }
7128
7644
  function isStale(lockPath, holder) {
7129
7645
  if (!holder) return isUnreadableLockOld(lockPath);
7130
- return startedBeforeBoot(holder.started_at) || !isProcessAlive(holder.pid);
7646
+ return startedInEarlierBoot(holder.boot_id, holder.started_at) || !isProcessAlive(holder.pid);
7131
7647
  }
7132
7648
  function createLock(lockPath, record) {
7133
7649
  try {
7134
- fs12.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
7650
+ fs14.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
7135
7651
  return true;
7136
7652
  } catch (err) {
7137
7653
  if (err.code === "EEXIST") return false;
@@ -7141,19 +7657,23 @@ function createLock(lockPath, record) {
7141
7657
  function acquireDaemonLock() {
7142
7658
  ensurePinggyConfigDir();
7143
7659
  const lockPath = getDaemonLockPath();
7144
- const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
7660
+ const record = {
7661
+ pid: process.pid,
7662
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
7663
+ boot_id: currentBootId() ?? void 0
7664
+ };
7145
7665
  if (createLock(lockPath, record)) return true;
7146
7666
  const holder = readLock(lockPath);
7147
7667
  if (holder?.pid === process.pid) return true;
7148
7668
  if (!isStale(lockPath, holder)) return false;
7149
7669
  logger.info("Stale daemon.lock found, replacing it", { stalePid: holder?.pid });
7150
- fs12.rmSync(lockPath, { force: true });
7670
+ fs14.rmSync(lockPath, { force: true });
7151
7671
  return createLock(lockPath, record);
7152
7672
  }
7153
7673
  function releaseDaemonLock() {
7154
7674
  const lockPath = getDaemonLockPath();
7155
7675
  if (readLock(lockPath)?.pid === process.pid) {
7156
- fs12.rmSync(lockPath, { force: true });
7676
+ fs14.rmSync(lockPath, { force: true });
7157
7677
  }
7158
7678
  }
7159
7679
 
@@ -7171,14 +7691,14 @@ function writeDaemonInfo(info) {
7171
7691
  ensurePinggyConfigDir();
7172
7692
  const infoPath = getDaemonInfoPath();
7173
7693
  const tmpPath = infoPath + ".tmp";
7174
- fs13.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
7175
- fs13.renameSync(tmpPath, infoPath);
7694
+ fs15.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
7695
+ fs15.renameSync(tmpPath, infoPath);
7176
7696
  }
7177
7697
  function removeDaemonInfo() {
7178
7698
  try {
7179
7699
  const infoPath = getDaemonInfoPath();
7180
- const info = JSON.parse(fs13.readFileSync(infoPath, "utf-8"));
7181
- if (info.pid === process.pid) fs13.unlinkSync(infoPath);
7700
+ const info = JSON.parse(fs15.readFileSync(infoPath, "utf-8"));
7701
+ if (info.pid === process.pid) fs15.unlinkSync(infoPath);
7182
7702
  } catch {
7183
7703
  }
7184
7704
  }
@@ -7408,7 +7928,8 @@ async function runDaemonChild(opts = {}) {
7408
7928
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
7409
7929
  host: daemonHost,
7410
7930
  ipcVersion: IPC_VERSION,
7411
- cliVersion: getVersion()
7931
+ cliVersion: getVersion(),
7932
+ bootId: currentBootId() ?? void 0
7412
7933
  };
7413
7934
  writeDaemonInfo(info);
7414
7935
  logger.info("Daemon info written", info);
@@ -7454,7 +7975,7 @@ async function main() {
7454
7975
  const { values, positionals, hasAnyArgs } = parseCliArgs(cliOptions);
7455
7976
  configureLogger(values);
7456
7977
  if (values["_daemon-child"]) {
7457
- const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-24Y3AKII.js");
7978
+ const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-WTZ7X6SZ.js");
7458
7979
  await runDaemonChild2();
7459
7980
  return;
7460
7981
  }
@@ -7463,18 +7984,20 @@ async function main() {
7463
7984
  return;
7464
7985
  }
7465
7986
  if (values["_update-child"]) {
7466
- const { runUpdateChild } = await import("./updateChild-JNGDWIAK.js");
7987
+ const { runUpdateChild } = await import("./updateChild-BPWBQ3WR.js");
7467
7988
  await runUpdateChild();
7468
7989
  process.exit(0);
7469
7990
  }
7470
7991
  if (isPackagedBinary() && platform2() === "win32") removeStaleUpdateFiles();
7471
- startBackgroundUpdate({ rawArgs, values, hasAnyArgs });
7992
+ const { questionShown } = await offerSelfInstall({ rawArgs, values });
7993
+ startBackgroundUpdate({ rawArgs, values, hasAnyArgs, installQuestionShown: questionShown });
7472
7994
  if (isSubcommand(rawArgs)) {
7473
7995
  await handleSubcommand(rawArgs);
7474
7996
  return;
7475
7997
  }
7476
7998
  if (!hasAnyArgs || values.help) {
7477
7999
  printHelpMessage();
8000
+ if (questionShown && !hasAnyArgs && platform2() === "win32") await waitForEnterToClose();
7478
8001
  return;
7479
8002
  }
7480
8003
  if (values.version) {
@@ -7487,7 +8010,7 @@ async function main() {
7487
8010
  printer_default.fatal(error);
7488
8011
  }
7489
8012
  }
7490
- var currentFile = fileURLToPath(import.meta.url);
8013
+ var currentFile = fileURLToPath2(import.meta.url);
7491
8014
  var entryFile = null;
7492
8015
  try {
7493
8016
  entryFile = argv[1] ? realpathSync(argv[1]) : null;