pinggy 0.6.4 → 0.6.5

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.
@@ -10,13 +10,19 @@ import {
10
10
  ipcMismatchMessage,
11
11
  isDaemonRunning,
12
12
  isIpcCompatible,
13
+ isProcessAlive,
13
14
  startDaemon,
14
15
  startRemoteManagement,
16
+ startedBeforeBoot,
15
17
  stopDaemon
16
- } from "./chunk-CIOYQU7F.js";
18
+ } from "./chunk-3PTLHLFL.js";
17
19
  import {
18
- readDaemonConfig
19
- } from "./chunk-PD7HXVQ3.js";
20
+ configuredLogLevel,
21
+ forgetDeviceAgent,
22
+ saveDeviceAgent,
23
+ savedDeviceAgent,
24
+ writeDaemonConfig
25
+ } from "./chunk-X6TZN5CT.js";
20
26
  import {
21
27
  DaemonHost,
22
28
  DeviceAgentState,
@@ -46,7 +52,7 @@ import {
46
52
  upsertConfig,
47
53
  validateName,
48
54
  validateNameStrict
49
- } from "./chunk-Y435RMHQ.js";
55
+ } from "./chunk-QZJGTQZC.js";
50
56
  import {
51
57
  createQrCodes
52
58
  } from "./chunk-XZ64ZAGO.js";
@@ -65,24 +71,26 @@ import {
65
71
  newErrorResponse,
66
72
  printer_default,
67
73
  setTunnelLoggingEnabled
68
- } from "./chunk-QNUVQ6KD.js";
74
+ } from "./chunk-EMCDDH3B.js";
69
75
  import {
70
76
  configureLogger,
71
77
  enablePackageLogging,
72
78
  getLogLevel,
73
79
  logger,
74
80
  setLogLevel
75
- } from "./chunk-MV56U3E6.js";
81
+ } from "./chunk-IRKMUV37.js";
76
82
  import {
77
83
  ensurePinggyConfigDir,
78
84
  ensurePinggyLogDir,
79
85
  getDaemonInfoPath,
86
+ getDaemonLockPath,
80
87
  getDaemonLogPath,
81
88
  getDeviceConfigPath,
89
+ getForegroundAgentPath,
82
90
  getPinggyConfigDir,
83
91
  getTunnelLogDir,
84
92
  getTunnelLogPath
85
- } from "./chunk-AFMTIELL.js";
93
+ } from "./chunk-N5WE4DYD.js";
86
94
 
87
95
  // src/cli/options.ts
88
96
  var cliOptions = {
@@ -210,6 +218,8 @@ function printHelpMessage() {
210
218
  console.log(" pinggy daemon start # Start the background daemon");
211
219
  console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
212
220
  console.log(" pinggy daemon status # Show daemon PID and uptime");
221
+ console.log(" pinggy daemon service-install # Run the daemon at login as a system service");
222
+ console.log(" pinggy daemon service-uninstall # Stop the daemon and remove the system service");
213
223
  }
214
224
 
215
225
  // src/utils/parseArgs.ts
@@ -819,10 +829,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
819
829
  }
820
830
  function storeJson(config, saveconf) {
821
831
  if (saveconf) {
822
- const path6 = saveconf;
832
+ const path7 = saveconf;
823
833
  try {
824
- fs.writeFileSync(path6, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
825
- logger.info(`Configuration saved to ${path6}`);
834
+ fs.writeFileSync(path7, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
835
+ logger.info(`Configuration saved to ${path7}`);
826
836
  } catch (err) {
827
837
  const msg = err instanceof Error ? err.message : String(err);
828
838
  logger.error("Error loading configuration:", msg);
@@ -1147,7 +1157,7 @@ async function connectTui(opts) {
1147
1157
  const exitMessage = opts.exitMessage || "Stopping tunnel...";
1148
1158
  if (!noTui && process.stdin.isTTY) {
1149
1159
  try {
1150
- const { TunnelTui } = await import("./TunnelTui-UCG2YSLX.js");
1160
+ const { TunnelTui } = await import("./TunnelTui-K7KESRTQ.js");
1151
1161
  const tui = new TunnelTui({
1152
1162
  urls,
1153
1163
  greet,
@@ -1370,7 +1380,7 @@ async function startBackgroundTunnels(configs, values, positionals) {
1370
1380
  client.close();
1371
1381
  }
1372
1382
  async function startAutoStartTunnels() {
1373
- const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-RR5ZU4E3.js");
1383
+ const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-DXC6WMYO.js");
1374
1384
  const configs = getAutoStartConfigs2();
1375
1385
  if (configs.length === 0) {
1376
1386
  printer_default.warn("No configs marked for auto-start. Use: pinggy config auto <name>");
@@ -1500,24 +1510,62 @@ import path2 from "path";
1500
1510
  import { execSync, execFileSync } from "child_process";
1501
1511
  var SERVICE_LABEL = "io.pinggy.agent";
1502
1512
  var SYSTEMD_SERVICE_NAME = "pinggy";
1503
- function resolveBinary() {
1504
- const isPkg = "pkg" in process;
1505
- if (isPkg) return { program: process.execPath, args: [] };
1513
+ var SERVICE_ANY_LOCATION_ENV = "PINGGY_SERVICE_ANY_LOCATION";
1514
+ function installerBinaryPath(platform2, home, env) {
1515
+ if (platform2 === "win32") {
1516
+ const localAppData = env.LOCALAPPDATA || path2.win32.join(home, "AppData", "Local");
1517
+ return path2.win32.join(localAppData, "Pinggy", "bin", "pinggy.exe");
1518
+ }
1519
+ return path2.posix.join(home, ".pinggy", "bin", "pinggy");
1520
+ }
1521
+ function realPath(p) {
1506
1522
  try {
1507
- const bin = execSync(os2.platform() === "win32" ? "where pinggy" : "which pinggy", {
1508
- encoding: "utf-8"
1509
- }).trim().split(/\r?\n/)[0];
1510
- return { program: bin, args: [] };
1523
+ return fs2.realpathSync(p);
1511
1524
  } catch {
1512
- return { program: process.execPath, args: [process.argv[1]] };
1525
+ return p;
1513
1526
  }
1514
1527
  }
1528
+ function isInstallerBinary(ctx) {
1529
+ const actual = realPath(ctx.execPath);
1530
+ const expected = realPath(installerBinaryPath(ctx.platform, ctx.home, ctx.env));
1531
+ if (ctx.platform === "win32") return actual.toLowerCase() === expected.toLowerCase();
1532
+ return actual === expected;
1533
+ }
1534
+ function installerFix(platform2) {
1535
+ const installCommand = platform2 === "win32" ? "irm https://pinggy.io/install.ps1 | iex" : "curl -fsSL https://pinggy.io/install.sh | sh";
1536
+ return [
1537
+ "pinggy can only run as a service when it is installed with the Pinggy installer.",
1538
+ "Install it, then run this command again:",
1539
+ ` ${installCommand}`,
1540
+ " pinggy daemon service-install"
1541
+ ].join("\n");
1542
+ }
1543
+ function serviceInstallRefusal(ctx) {
1544
+ if (!ctx.isPkg) return `The npm version of pinggy cannot run as a service.
1545
+ ${installerFix(ctx.platform)}`;
1546
+ if (ctx.env[SERVICE_ANY_LOCATION_ENV] === "1" || isInstallerBinary(ctx)) return null;
1547
+ return installerFix(ctx.platform);
1548
+ }
1549
+ function printInstalled() {
1550
+ printer_default.success("pinggy now starts automatically when this computer starts.");
1551
+ }
1552
+ function printUninstalled() {
1553
+ printer_default.success("pinggy no longer starts automatically when this computer starts.");
1554
+ }
1555
+ function printNotInstalled() {
1556
+ printer_default.print("pinggy is not set to start automatically.");
1557
+ }
1558
+ var QUIET = { stdio: ["ignore", "ignore", "pipe"] };
1559
+ function toolError(err) {
1560
+ const stderr = err.stderr?.toString().trim();
1561
+ return stderr ? stderr.replace(/^ERROR:\s*/i, "") : errorMessage(err);
1562
+ }
1515
1563
  function getSystemdServicePath() {
1516
1564
  const dir = path2.join(os2.homedir(), ".config", "systemd", "user");
1517
1565
  return path2.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
1518
1566
  }
1519
- function generateSystemdUnit(bin) {
1520
- const execStart = [bin.program, ...bin.args, "--_daemon-child"].join(" ");
1567
+ function generateSystemdUnit(program) {
1568
+ const execStart = `${program} --_daemon-child`;
1521
1569
  return `[Unit]
1522
1570
  Description=Pinggy Tunnel Daemon
1523
1571
  After=network-online.target
@@ -1533,18 +1581,17 @@ RestartSec=5
1533
1581
  WantedBy=default.target
1534
1582
  `;
1535
1583
  }
1536
- function installSystemd() {
1537
- const bin = resolveBinary();
1584
+ function installSystemd(program) {
1538
1585
  const servicePath = getSystemdServicePath();
1539
1586
  const dir = path2.dirname(servicePath);
1540
1587
  fs2.mkdirSync(dir, { recursive: true });
1541
- fs2.writeFileSync(servicePath, generateSystemdUnit(bin), "utf-8");
1542
- execSync("systemctl --user daemon-reload");
1543
- execSync(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`);
1544
- execSync(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`);
1545
- logger.info("systemd user service installed and started", { servicePath });
1546
- console.log(`Service installed: ${servicePath}`);
1547
- console.log(`Enable at boot: loginctl enable-linger ${os2.userInfo().username}`);
1588
+ fs2.writeFileSync(servicePath, generateSystemdUnit(program), "utf-8");
1589
+ execSync("systemctl --user daemon-reload", QUIET);
1590
+ execSync(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`, QUIET);
1591
+ execSync(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`, QUIET);
1592
+ logger.info("systemd user service installed", { servicePath });
1593
+ printInstalled();
1594
+ printer_default.print(`To start it before anyone signs in, run: loginctl enable-linger ${os2.userInfo().username}`);
1548
1595
  }
1549
1596
  function uninstallSystemd() {
1550
1597
  const servicePath = getSystemdServicePath();
@@ -1555,17 +1602,18 @@ function uninstallSystemd() {
1555
1602
  }
1556
1603
  if (fs2.existsSync(servicePath)) {
1557
1604
  fs2.unlinkSync(servicePath);
1558
- execSync("systemctl --user daemon-reload");
1559
- console.log(`Service removed: ${servicePath}`);
1605
+ execSync("systemctl --user daemon-reload", QUIET);
1606
+ logger.info("systemd user service removed", { servicePath });
1607
+ printUninstalled();
1560
1608
  } else {
1561
- console.log("No systemd service found to remove.");
1609
+ printNotInstalled();
1562
1610
  }
1563
1611
  }
1564
1612
  function getLaunchdPlistPath() {
1565
1613
  return path2.join(os2.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
1566
1614
  }
1567
- function generateLaunchdPlist(bin) {
1568
- const allArgs = [bin.program, ...bin.args, "--_daemon-child"];
1615
+ function generateLaunchdPlist(program) {
1616
+ const allArgs = [program, "--_daemon-child"];
1569
1617
  const programArgs = allArgs.map((p) => ` <string>${p}</string>`).join("\n");
1570
1618
  return `<?xml version="1.0" encoding="UTF-8"?>
1571
1619
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
@@ -1586,17 +1634,21 @@ ${programArgs}
1586
1634
  </plist>
1587
1635
  `;
1588
1636
  }
1589
- function installLaunchd() {
1590
- const bin = resolveBinary();
1637
+ function installLaunchd(program) {
1591
1638
  const plistPath = getLaunchdPlistPath();
1592
1639
  const dir = path2.dirname(plistPath);
1593
1640
  fs2.mkdirSync(dir, { recursive: true });
1594
- fs2.writeFileSync(plistPath, generateLaunchdPlist(bin), "utf-8");
1641
+ fs2.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
1595
1642
  const uid = process.getuid?.() ?? 501;
1596
1643
  try {
1597
1644
  execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
1598
1645
  } catch {
1599
1646
  }
1647
+ loadLaunchdPlist(uid, plistPath);
1648
+ logger.info("launchd agent installed", { plistPath });
1649
+ printInstalled();
1650
+ }
1651
+ function loadLaunchdPlist(uid, plistPath) {
1600
1652
  try {
1601
1653
  execSync(`launchctl bootstrap gui/${uid} ${plistPath}`);
1602
1654
  } catch {
@@ -1605,8 +1657,6 @@ function installLaunchd() {
1605
1657
  } catch {
1606
1658
  }
1607
1659
  }
1608
- logger.info("launchd agent installed and started", { plistPath });
1609
- console.log(`Service installed and started: ${plistPath}`);
1610
1660
  }
1611
1661
  function uninstallLaunchd() {
1612
1662
  const plistPath = getLaunchdPlistPath();
@@ -1621,24 +1671,34 @@ function uninstallLaunchd() {
1621
1671
  }
1622
1672
  if (fs2.existsSync(plistPath)) {
1623
1673
  fs2.unlinkSync(plistPath);
1624
- console.log(`Service removed: ${plistPath}`);
1674
+ logger.info("launchd agent removed", { plistPath });
1675
+ printUninstalled();
1625
1676
  } else {
1626
- console.log("No launchd agent found to remove.");
1677
+ printNotInstalled();
1627
1678
  }
1628
1679
  }
1629
1680
  var WINDOWS_TASK_NAME = "PinggyDaemon";
1630
- function generateTaskXml(bin) {
1631
- const command = bin.program;
1632
- const args = [...bin.args, "--_daemon-child"].join(" ");
1681
+ function escapeXml(value) {
1682
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1683
+ }
1684
+ function getWindowsUserId() {
1685
+ const user = process.env.USERNAME || os2.userInfo().username;
1686
+ const domain = process.env.USERDOMAIN;
1687
+ return domain ? `${domain}\\${user}` : user;
1688
+ }
1689
+ function generateTaskXml(program, userId) {
1690
+ const user = escapeXml(userId);
1633
1691
  return `<?xml version="1.0" encoding="UTF-16"?>
1634
1692
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
1635
1693
  <Triggers>
1636
1694
  <LogonTrigger>
1637
1695
  <Enabled>true</Enabled>
1696
+ <UserId>${user}</UserId>
1638
1697
  </LogonTrigger>
1639
1698
  </Triggers>
1640
1699
  <Principals>
1641
1700
  <Principal id="Author">
1701
+ <UserId>${user}</UserId>
1642
1702
  <LogonType>InteractiveToken</LogonType>
1643
1703
  <RunLevel>LeastPrivilege</RunLevel>
1644
1704
  </Principal>
@@ -1656,71 +1716,105 @@ function generateTaskXml(bin) {
1656
1716
  </Settings>
1657
1717
  <Actions>
1658
1718
  <Exec>
1659
- <Command>${command}</Command>${args ? `
1660
- <Arguments>${args}</Arguments>` : ""}
1719
+ <Command>${escapeXml(program)}</Command>
1720
+ <Arguments>daemon start</Arguments>
1661
1721
  </Exec>
1662
1722
  </Actions>
1663
1723
  </Task>`;
1664
1724
  }
1665
- function installWindows() {
1666
- const bin = resolveBinary();
1667
- const xml = generateTaskXml(bin);
1725
+ function createWindowsTask(program) {
1726
+ const xml = generateTaskXml(program, getWindowsUserId());
1668
1727
  const tmpPath = path2.join(os2.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
1669
1728
  fs2.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
1670
1729
  try {
1671
- execFileSync("schtasks", [
1672
- "/Create",
1673
- "/TN",
1674
- WINDOWS_TASK_NAME,
1675
- "/XML",
1676
- tmpPath,
1677
- "/F"
1678
- ], { stdio: "inherit" });
1730
+ execFileSync("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
1679
1731
  } finally {
1680
1732
  try {
1681
1733
  fs2.unlinkSync(tmpPath);
1682
1734
  } catch {
1683
1735
  }
1684
1736
  }
1685
- execFileSync("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], { stdio: "inherit" });
1686
- console.log(`Scheduled task "${WINDOWS_TASK_NAME}" created and started (runs at login, hidden).`);
1687
1737
  }
1688
- function uninstallWindows() {
1738
+ function windowsTaskExists() {
1689
1739
  try {
1690
- execFileSync("schtasks", ["/End", "/TN", WINDOWS_TASK_NAME], { stdio: "ignore" });
1740
+ execFileSync("schtasks", ["/Query", "/TN", WINDOWS_TASK_NAME], QUIET);
1741
+ return true;
1691
1742
  } catch {
1743
+ return false;
1692
1744
  }
1745
+ }
1746
+ function isElevated() {
1693
1747
  try {
1694
- execFileSync("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], { stdio: "inherit" });
1695
- console.log(`Scheduled task "${WINDOWS_TASK_NAME}" removed.`);
1748
+ return /S-1-16-(12288|16384)\b/.test(execFileSync("whoami", ["/groups"], { encoding: "utf-8" }));
1696
1749
  } catch {
1697
- console.log("No scheduled task found to remove.");
1750
+ return false;
1698
1751
  }
1699
1752
  }
1753
+ function windowsTaskError(action, undo, err) {
1754
+ if (windowsTaskExists() && !isElevated()) {
1755
+ return `Could not ${action}. It was set up from an Administrator terminal. Run this command from an Administrator terminal to ${undo}.`;
1756
+ }
1757
+ return `Could not ${action}: ${toolError(err)}`;
1758
+ }
1759
+ function installWindows(program) {
1760
+ try {
1761
+ createWindowsTask(program);
1762
+ execFileSync("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], QUIET);
1763
+ } catch (err) {
1764
+ printer_default.error(windowsTaskError("set pinggy to start automatically", "change it", err));
1765
+ process.exit(1);
1766
+ }
1767
+ logger.info("Scheduled task installed", { task: WINDOWS_TASK_NAME });
1768
+ printInstalled();
1769
+ }
1770
+ async function uninstallWindows() {
1771
+ if (!windowsTaskExists()) {
1772
+ printNotInstalled();
1773
+ return;
1774
+ }
1775
+ try {
1776
+ execFileSync("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], QUIET);
1777
+ } catch (err) {
1778
+ printer_default.error(windowsTaskError("stop pinggy from starting automatically", "turn it off", err));
1779
+ process.exit(1);
1780
+ }
1781
+ logger.info("Scheduled task removed", { task: WINDOWS_TASK_NAME });
1782
+ if (isDaemonRunning()) {
1783
+ const result = await stopDaemon();
1784
+ if (!result.ok) console.log(`Could not stop the daemon: ${result.error}`);
1785
+ }
1786
+ printUninstalled();
1787
+ }
1700
1788
  function installService() {
1701
1789
  const platform2 = os2.platform();
1702
- const bin = resolveBinary();
1703
- if (!("pkg" in process) && bin.program !== process.execPath) {
1704
- console.warn(
1705
- "Warning: Using npm-installed binary. The path may change if Node.js is updated.\nConsider using a standalone binary (pkg) for system services."
1706
- );
1790
+ const program = process.execPath;
1791
+ const refusal = serviceInstallRefusal({
1792
+ platform: platform2,
1793
+ isPkg: "pkg" in process,
1794
+ execPath: program,
1795
+ home: os2.homedir(),
1796
+ env: process.env
1797
+ });
1798
+ if (refusal) {
1799
+ console.error(refusal);
1800
+ process.exit(1);
1707
1801
  }
1708
1802
  switch (platform2) {
1709
1803
  case "linux":
1710
- installSystemd();
1804
+ installSystemd(program);
1711
1805
  break;
1712
1806
  case "darwin":
1713
- installLaunchd();
1807
+ installLaunchd(program);
1714
1808
  break;
1715
1809
  case "win32":
1716
- installWindows();
1810
+ installWindows(program);
1717
1811
  break;
1718
1812
  default:
1719
1813
  console.error(`Unsupported platform: ${platform2}`);
1720
1814
  process.exit(1);
1721
1815
  }
1722
1816
  }
1723
- function uninstallService() {
1817
+ async function uninstallService() {
1724
1818
  const platform2 = os2.platform();
1725
1819
  switch (platform2) {
1726
1820
  case "linux":
@@ -1730,7 +1824,7 @@ function uninstallService() {
1730
1824
  uninstallLaunchd();
1731
1825
  break;
1732
1826
  case "win32":
1733
- uninstallWindows();
1827
+ await uninstallWindows();
1734
1828
  break;
1735
1829
  default:
1736
1830
  console.error(`Unsupported platform: ${platform2}`);
@@ -1746,6 +1840,8 @@ function printDaemonHelp() {
1746
1840
  console.log(" start Start the daemon process");
1747
1841
  console.log(" stop Stop the daemon (stops all tunnels)");
1748
1842
  console.log(" status Show daemon PID and uptime");
1843
+ console.log(" service-install Run the daemon at login as a system service");
1844
+ console.log(" service-uninstall Stop the daemon and remove the system service");
1749
1845
  console.log("Tunnel operations:");
1750
1846
  console.log(" pinggy ps List running tunnels");
1751
1847
  console.log(" pinggy stop <name|id> Stop a specific tunnel");
@@ -1786,16 +1882,20 @@ function printDeviceHelp() {
1786
1882
  console.log(" background");
1787
1883
  console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
1788
1884
  console.log(" background. Without --token: start the enrolled device's agent again");
1789
- console.log(" stop Stop the agent running in the background");
1885
+ console.log(" stop Stop the agent running in the background, until the daemon");
1886
+ console.log(" starts again");
1790
1887
  console.log(" status Show the enrolment, and the agent running in the background");
1791
- console.log(" remove Forget the local credential (does not delete the device)\n");
1792
- console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.\n");
1888
+ console.log(" remove Stop the agent and forget the local credential, after asking.");
1889
+ console.log(" The device stays in the dashboard\n");
1890
+ console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.");
1891
+ console.log("Each time the daemon starts, it starts the agent again, until remove.\n");
1793
1892
  console.log("Options:");
1794
1893
  console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
1795
1894
  console.log(" -b login and connect: run the agent in the background. The default");
1796
1895
  console.log(" --token <TOKEN> Device token from the dashboard");
1797
1896
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
1798
- console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname\n");
1897
+ console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
1898
+ console.log(" -f remove only: remove without asking\n");
1799
1899
  console.log("Environment:");
1800
1900
  console.log(" DEVICE_AGENT_TOKEN connect only: the device token, when --token is not given. With no");
1801
1901
  console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
@@ -3945,9 +4045,9 @@ function readShellEnvironment() {
3945
4045
  platform: process.platform,
3946
4046
  loginShell: process.env.SHELL,
3947
4047
  etcShells,
3948
- exists: (path6) => {
4048
+ exists: (path7) => {
3949
4049
  try {
3950
- return fs7.statSync(path6).isFile();
4050
+ return fs7.statSync(path7).isFile();
3951
4051
  } catch {
3952
4052
  return false;
3953
4053
  }
@@ -3979,6 +4079,104 @@ function resolveShell(requested, environment) {
3979
4079
  return firstUsable ? { shell: firstUsable } : { error: "No allowed shell exists on this machine." };
3980
4080
  }
3981
4081
 
4082
+ // src/devices/foregroundAgent.ts
4083
+ import fs8 from "fs";
4084
+ var RECORD_CHECK_INTERVAL_MILLIS = 1e3;
4085
+ var STOP_WAIT_MILLIS = 1e4;
4086
+ var STOP_POLL_INTERVAL_MILLIS = 200;
4087
+ function readRecordFile(filePath) {
4088
+ try {
4089
+ const record = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
4090
+ return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
4091
+ } catch {
4092
+ return null;
4093
+ }
4094
+ }
4095
+ function deleteRecordFile(filePath) {
4096
+ try {
4097
+ fs8.unlinkSync(filePath);
4098
+ } catch (err) {
4099
+ logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
4100
+ }
4101
+ }
4102
+ function readForegroundAgent() {
4103
+ const filePath = getForegroundAgentPath();
4104
+ const record = readRecordFile(filePath);
4105
+ if (!record) {
4106
+ return null;
4107
+ }
4108
+ if (record.pid === process.pid) {
4109
+ return null;
4110
+ }
4111
+ if (startedBeforeBoot(record.started_at) || !isProcessAlive(record.pid)) {
4112
+ logger.info("Stale device-agent.json found, cleaning up", { stalePid: record.pid });
4113
+ deleteRecordFile(filePath);
4114
+ return null;
4115
+ }
4116
+ return record;
4117
+ }
4118
+ function recordForegroundAgent(onRecordDeleted) {
4119
+ const filePath = getForegroundAgentPath();
4120
+ const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
4121
+ try {
4122
+ ensurePinggyConfigDir();
4123
+ fs8.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
4124
+ } catch (err) {
4125
+ logger.warn(
4126
+ "Could not write device-agent.json. pinggy device remove cannot stop this agent.",
4127
+ { error: errorMessage(err) }
4128
+ );
4129
+ return () => void 0;
4130
+ }
4131
+ const timer = setInterval(() => {
4132
+ if (!fs8.existsSync(filePath)) {
4133
+ clearInterval(timer);
4134
+ onRecordDeleted();
4135
+ }
4136
+ }, RECORD_CHECK_INTERVAL_MILLIS);
4137
+ timer.unref();
4138
+ return () => {
4139
+ clearInterval(timer);
4140
+ if (readRecordFile(filePath)?.pid === process.pid) {
4141
+ deleteRecordFile(filePath);
4142
+ }
4143
+ };
4144
+ }
4145
+ function machineForegroundStopDependencies() {
4146
+ return {
4147
+ readAgent: readForegroundAgent,
4148
+ deleteRecord: () => deleteRecordFile(getForegroundAgentPath()),
4149
+ isAlive: isProcessAlive,
4150
+ sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),
4151
+ now: () => Date.now(),
4152
+ print: (message) => printer_default.print(message),
4153
+ printError: (message) => printer_default.error(message)
4154
+ };
4155
+ }
4156
+ async function stopForegroundAgentBeforeRemove(dependencies = machineForegroundStopDependencies()) {
4157
+ const record = dependencies.readAgent();
4158
+ if (!record) {
4159
+ return true;
4160
+ }
4161
+ dependencies.deleteRecord();
4162
+ const deadline = dependencies.now() + STOP_WAIT_MILLIS;
4163
+ while (dependencies.isAlive(record.pid)) {
4164
+ if (dependencies.now() >= deadline) {
4165
+ dependencies.printError(`The device agent in another terminal (PID ${record.pid}) did not stop. Press Ctrl+C in that terminal, then run: pinggy device remove`);
4166
+ return false;
4167
+ }
4168
+ await dependencies.sleep(STOP_POLL_INTERVAL_MILLIS);
4169
+ }
4170
+ dependencies.print(`Stopped the device agent running in another terminal (PID ${record.pid}).`);
4171
+ return true;
4172
+ }
4173
+ function foregroundAgentRefusal(record = readForegroundAgent()) {
4174
+ if (!record) {
4175
+ return null;
4176
+ }
4177
+ return `This machine already runs as a device in another terminal (PID ${record.pid}). Press Ctrl+C in that terminal first.`;
4178
+ }
4179
+
3982
4180
  // src/devices/deviceAgent.ts
3983
4181
  var CLOSE_CODE_REVOKED = 4001;
3984
4182
  var CLOSE_CODE_NORMAL = 1e3;
@@ -4092,14 +4290,20 @@ function startDeviceAgent(token, manage, options = {}) {
4092
4290
  }
4093
4291
  async function runDeviceAgent(token, manage, options = {}) {
4094
4292
  const run2 = startDeviceAgent(token, manage, options);
4293
+ const reporter = options.reporter ?? printingReporter;
4095
4294
  const sigintHandler = () => {
4096
4295
  void run2.stop();
4097
4296
  };
4297
+ const releaseRecord = recordForegroundAgent(() => {
4298
+ reporter.warn("Stopping: pinggy device remove ran in another terminal.");
4299
+ void run2.stop();
4300
+ });
4098
4301
  process.once("SIGINT", sigintHandler);
4099
4302
  try {
4100
4303
  await run2.done;
4101
4304
  } finally {
4102
4305
  process.removeListener("SIGINT", sigintHandler);
4306
+ releaseRecord();
4103
4307
  }
4104
4308
  }
4105
4309
  async function runLoop(context) {
@@ -4424,8 +4628,8 @@ var DeviceLoginApiError = class extends Error {
4424
4628
  var UNREADABLE_ANSWER = "invalid_answer";
4425
4629
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
4426
4630
  const baseUrl = buildDashboardHttpUrl(manage);
4427
- async function post(path6, body, schema) {
4428
- const response2 = await fetchImpl(`${baseUrl}/${path6}`, {
4631
+ async function post(path7, body, schema) {
4632
+ const response2 = await fetchImpl(`${baseUrl}/${path7}`, {
4429
4633
  method: "POST",
4430
4634
  headers: { "Content-Type": "application/json", Accept: "application/json" },
4431
4635
  body: JSON.stringify(body)
@@ -4771,9 +4975,9 @@ var POLL_INTERVAL_MILLIS = 500;
4771
4975
  var CONNECT_WAIT_MILLIS = 15e3;
4772
4976
  var MANAGE_COMMANDS = [
4773
4977
  ["pinggy device status", "Show this device, and whether its agent runs"],
4774
- ["pinggy device stop", "Stop the agent. The device shows offline"],
4775
- ["pinggy device connect", "Start the agent again, after a stop or a reboot"],
4776
- ["pinggy device remove", "Forget this machine's credential"]
4978
+ ["pinggy device stop", "Stop the agent until the daemon starts again. The device shows offline"],
4979
+ ["pinggy device connect", "Start the agent again after a stop"],
4980
+ ["pinggy device remove", "Stop the agent and forget this machine's credential"]
4777
4981
  ];
4778
4982
  var verifyingReporter = {
4779
4983
  connecting: () => void 0,
@@ -4787,7 +4991,10 @@ var verifyingReporter = {
4787
4991
  function machineBackgroundAgentDependencies() {
4788
4992
  return {
4789
4993
  readIdentity: readDeviceIdentity,
4994
+ readForegroundAgent,
4790
4995
  findDaemon: getDaemonInfo,
4996
+ hasSavedAgent: () => savedDeviceAgent() !== null,
4997
+ forgetSavedAgent: forgetDeviceAgent,
4791
4998
  ensureDaemon: ensureDaemonRunning,
4792
4999
  client: (port) => new IPCClient(port, "cli"),
4793
5000
  verify: (token, manage) => startDeviceAgent(token, manage, {
@@ -4867,7 +5074,7 @@ async function stopAgentInBackground(dependencies) {
4867
5074
  if (!await stopReadAgent(reading, dependencies)) {
4868
5075
  return EXIT_FAILED;
4869
5076
  }
4870
- dependencies.printSuccess("Stopped. The device shows offline in the dashboard.");
5077
+ dependencies.printSuccess("Stopped. The device shows offline in the dashboard until the daemon starts again.");
4871
5078
  return EXIT_OK;
4872
5079
  }
4873
5080
  async function stopAgentBeforeRemove(dependencies) {
@@ -5004,7 +5211,7 @@ async function handleDaemon(args) {
5004
5211
  installService();
5005
5212
  return;
5006
5213
  case "service-uninstall":
5007
- uninstallService();
5214
+ await uninstallService();
5008
5215
  return;
5009
5216
  default:
5010
5217
  printer_default.error(`Unknown daemon command: "${verb}"`);
@@ -5089,7 +5296,10 @@ import pico7 from "picocolors";
5089
5296
  async function handlePs() {
5090
5297
  const client = new TunnelClient();
5091
5298
  try {
5092
- await client.ensureDaemon();
5299
+ if (!client.connectIfRunning()) {
5300
+ printer_default.print("No active tunnels. The daemon is not running.");
5301
+ return;
5302
+ }
5093
5303
  } catch (err) {
5094
5304
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5095
5305
  return;
@@ -5101,7 +5311,7 @@ async function handlePs() {
5101
5311
  return;
5102
5312
  }
5103
5313
  if (tunnels.length === 0) {
5104
- printer_default.print("No tunnels running.");
5314
+ printer_default.print("No active tunnels.");
5105
5315
  return;
5106
5316
  }
5107
5317
  const header = `${pad("ID", 14)} ${pad("NAME", 16)} ${pad("STATUS", 10)} ${pad("LOCAL", 20)} URL`;
@@ -5136,7 +5346,10 @@ async function handleStop(args) {
5136
5346
  }
5137
5347
  const client = new TunnelClient();
5138
5348
  try {
5139
- await client.ensureDaemon();
5349
+ if (!client.connectIfRunning()) {
5350
+ printer_default.print("Nothing to stop. No tunnels are running.");
5351
+ return;
5352
+ }
5140
5353
  } catch (err) {
5141
5354
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5142
5355
  return;
@@ -5188,6 +5401,20 @@ function resolveTargets(tunnels, args) {
5188
5401
 
5189
5402
  // src/cli/subcommand/handlers/attachCommand.ts
5190
5403
  import pico8 from "picocolors";
5404
+
5405
+ // src/cli/subcommand/handlers/noDaemon.ts
5406
+ function startCommand(name) {
5407
+ return /\s/.test(name) ? `pinggy start "${name}"` : `pinggy start ${name}`;
5408
+ }
5409
+ function tunnelNotRunningMessage(nameOrId) {
5410
+ const saved = findConfig(nameOrId);
5411
+ if (saved) {
5412
+ return `Tunnel "${saved.name}" is not running. Start it with: ${startCommand(saved.name)}`;
5413
+ }
5414
+ return `No tunnel matches "${nameOrId}". No tunnels are running.`;
5415
+ }
5416
+
5417
+ // src/cli/subcommand/handlers/attachCommand.ts
5191
5418
  async function handleAttach(args) {
5192
5419
  if (args.length === 0) {
5193
5420
  printer_default.error("Usage: pinggy attach <name|id>");
@@ -5196,7 +5423,10 @@ async function handleAttach(args) {
5196
5423
  const nameOrId = args[0];
5197
5424
  const client = new TunnelClient();
5198
5425
  try {
5199
- await client.ensureDaemon();
5426
+ if (!client.connectIfRunning()) {
5427
+ printer_default.error(tunnelNotRunningMessage(nameOrId));
5428
+ return;
5429
+ }
5200
5430
  } catch (err) {
5201
5431
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5202
5432
  return;
@@ -5243,12 +5473,86 @@ async function handleAttach(args) {
5243
5473
  }
5244
5474
 
5245
5475
  // src/cli/subcommand/handlers/logsCommand.ts
5246
- import fs8 from "fs";
5476
+ import fs10 from "fs";
5477
+
5478
+ // src/daemon/logPaths.ts
5479
+ import fs9 from "fs";
5480
+ import path4 from "path";
5481
+ var TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
5482
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5483
+ function parseTunnelLogFilename(filename) {
5484
+ const base = filename.replace(/\.log$/, "");
5485
+ const parts = base.split("__");
5486
+ if (parts.length < 2) return null;
5487
+ const origin = parts[0];
5488
+ if (!TUNNEL_ORIGINS.includes(origin)) return null;
5489
+ if (parts.length === 2) {
5490
+ const second = parts[1];
5491
+ if (UUID_RE.test(second)) return { origin, tunnelId: second };
5492
+ return { origin, name: second };
5493
+ }
5494
+ const tunnelId = parts[parts.length - 1];
5495
+ const name = parts.slice(1, -1).join("__");
5496
+ return { origin, name, tunnelId };
5497
+ }
5498
+ function listTunnelLogFiles() {
5499
+ const logDir = getTunnelLogDir();
5500
+ if (!fs9.existsSync(logDir)) return [];
5501
+ return fs9.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
5502
+ }
5503
+ function newestLogFile(q) {
5504
+ const logDir = getTunnelLogDir();
5505
+ const matches = [];
5506
+ for (const file of listTunnelLogFiles()) {
5507
+ const parsed = parseTunnelLogFilename(file);
5508
+ if (!parsed) continue;
5509
+ const nameMatch = parsed.name !== void 0 && parsed.name === q;
5510
+ const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
5511
+ if (nameMatch || idMatch) {
5512
+ const filePath = path4.join(logDir, file);
5513
+ matches.push({ ...parsed, path: filePath, mtime: fs9.statSync(filePath).mtimeMs });
5514
+ }
5515
+ }
5516
+ if (matches.length === 0) return null;
5517
+ matches.sort((a, b) => b.mtime - a.mtime);
5518
+ const best = matches[0];
5519
+ return { status: "historical", path: best.path, tunnelId: best.tunnelId, name: best.name, origin: best.origin, running: false };
5520
+ }
5521
+ function resolveStoppedLogPath(q) {
5522
+ if (!q) return { status: "not-found" };
5523
+ const historical = newestLogFile(q);
5524
+ if (historical) return historical;
5525
+ const saved = listSavedConfigs();
5526
+ const matchedConfig = saved.find((c) => c.name === q || c.configId === q || c.configId.startsWith(q));
5527
+ if (matchedConfig) {
5528
+ return { status: "config-only", name: matchedConfig.name, configId: matchedConfig.configId };
5529
+ }
5530
+ return { status: "not-found" };
5531
+ }
5532
+
5533
+ // src/cli/subcommand/handlers/logLookup.ts
5534
+ function openLogLookup() {
5535
+ const client = new TunnelClient();
5536
+ if (!client.connectIfRunning()) {
5537
+ return {
5538
+ daemonLogPath: () => Promise.resolve(getDaemonLogPath()),
5539
+ resolve: (nameOrId) => Promise.resolve(resolveStoppedLogPath(nameOrId)),
5540
+ close: () => void 0
5541
+ };
5542
+ }
5543
+ return {
5544
+ daemonLogPath: async () => (await client.getLogPaths()).daemon,
5545
+ resolve: (nameOrId) => client.resolveLogPath(nameOrId),
5546
+ close: () => client.close()
5547
+ };
5548
+ }
5549
+
5550
+ // src/cli/subcommand/handlers/logsCommand.ts
5247
5551
  async function handleLogs(args, follow) {
5248
5552
  const arg = args.find((a) => !a.startsWith("-"));
5249
- const client = new TunnelClient();
5553
+ let client;
5250
5554
  try {
5251
- await client.ensureDaemon();
5555
+ client = openLogLookup();
5252
5556
  } catch (err) {
5253
5557
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5254
5558
  return;
@@ -5256,7 +5560,7 @@ async function handleLogs(args, follow) {
5256
5560
  let filePath;
5257
5561
  try {
5258
5562
  if (arg) {
5259
- const result = await client.resolveLogPath(arg);
5563
+ const result = await client.resolve(arg);
5260
5564
  if (result.status === "config-only") {
5261
5565
  printer_default.error(`Tunnel "${arg}" is saved but has not been started yet. No logs available.`);
5262
5566
  client.close();
@@ -5274,8 +5578,7 @@ async function handleLogs(args, follow) {
5274
5578
  }
5275
5579
  filePath = result.path;
5276
5580
  } else {
5277
- const paths = await client.getLogPaths();
5278
- filePath = paths.daemon;
5581
+ filePath = await client.daemonLogPath();
5279
5582
  }
5280
5583
  } catch (err) {
5281
5584
  printer_default.error(`Failed to resolve log path: ${errorMessage(err)}`);
@@ -5283,7 +5586,7 @@ async function handleLogs(args, follow) {
5283
5586
  return;
5284
5587
  }
5285
5588
  client.close();
5286
- if (!filePath || !fs8.existsSync(filePath)) {
5589
+ if (!filePath || !fs10.existsSync(filePath)) {
5287
5590
  printer_default.error(`Log file not found: ${filePath}`);
5288
5591
  process.exit(1);
5289
5592
  }
@@ -5294,18 +5597,18 @@ async function handleLogs(args, follow) {
5294
5597
  }
5295
5598
  }
5296
5599
  function printTail(filePath, lines) {
5297
- const content = fs8.readFileSync(filePath, "utf-8");
5600
+ const content = fs10.readFileSync(filePath, "utf-8");
5298
5601
  const allLines = content.split("\n");
5299
5602
  const tail = allLines.slice(-lines).join("\n");
5300
5603
  process.stdout.write(tail);
5301
5604
  if (!tail.endsWith("\n")) process.stdout.write("\n");
5302
5605
  }
5303
5606
  async function followFile(filePath) {
5304
- if (fs8.existsSync(filePath)) printTail(filePath, 20);
5305
- let fileSize = fs8.existsSync(filePath) ? fs8.statSync(filePath).size : 0;
5607
+ if (fs10.existsSync(filePath)) printTail(filePath, 20);
5608
+ let fileSize = fs10.existsSync(filePath) ? fs10.statSync(filePath).size : 0;
5306
5609
  let watcher = null;
5307
5610
  const openStream = () => {
5308
- const stream = fs8.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
5611
+ const stream = fs10.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
5309
5612
  stream.on("data", (chunk) => {
5310
5613
  process.stdout.write(chunk);
5311
5614
  fileSize += Buffer.byteLength(chunk, "utf-8");
@@ -5313,9 +5616,9 @@ async function followFile(filePath) {
5313
5616
  stream.on("error", () => {
5314
5617
  });
5315
5618
  };
5316
- watcher = fs8.watch(filePath, { persistent: true }, (event2) => {
5619
+ watcher = fs10.watch(filePath, { persistent: true }, (event2) => {
5317
5620
  if (event2 === "change") {
5318
- const stat = fs8.existsSync(filePath) ? fs8.statSync(filePath) : null;
5621
+ const stat = fs10.existsSync(filePath) ? fs10.statSync(filePath) : null;
5319
5622
  if (!stat || stat.size < fileSize) {
5320
5623
  fileSize = 0;
5321
5624
  }
@@ -5351,26 +5654,39 @@ async function handleLog(args) {
5351
5654
  printLogHelp();
5352
5655
  }
5353
5656
  }
5657
+ function parseLevel(arg) {
5658
+ const level = arg.toLowerCase();
5659
+ if (!VALID_LEVELS.includes(level)) {
5660
+ printer_default.error(`Invalid log level: "${level}". Must be one of: ${VALID_LEVELS.join(", ")}`);
5661
+ process.exit(1);
5662
+ }
5663
+ return level;
5664
+ }
5665
+ function handleLogLevelWithoutDaemon(level) {
5666
+ if (!level) {
5667
+ printer_default.print(`Log level: ${configuredLogLevel()}`);
5668
+ return;
5669
+ }
5670
+ writeDaemonConfig({ logLevel: level });
5671
+ printer_default.success(`Log level set to "${level}". The daemon uses it when it starts.`);
5672
+ }
5354
5673
  async function handleLogLevel(args) {
5674
+ const level = args.length > 0 ? parseLevel(args[0]) : void 0;
5355
5675
  const client = new TunnelClient();
5356
5676
  try {
5357
- await client.ensureDaemon();
5677
+ if (!client.connectIfRunning()) {
5678
+ handleLogLevelWithoutDaemon(level);
5679
+ return;
5680
+ }
5358
5681
  } catch (err) {
5359
5682
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5360
5683
  return;
5361
5684
  }
5362
5685
  try {
5363
- if (args.length === 0) {
5364
- const level2 = await client.getLogLevel();
5365
- printer_default.print(`Log level: ${level2}`);
5686
+ if (!level) {
5687
+ printer_default.print(`Log level: ${await client.getLogLevel()}`);
5366
5688
  return;
5367
5689
  }
5368
- const level = args[0].toLowerCase();
5369
- if (!VALID_LEVELS.includes(level)) {
5370
- printer_default.error(`Invalid log level: "${level}". Must be one of: ${VALID_LEVELS.join(", ")}`);
5371
- client.close();
5372
- process.exit(1);
5373
- }
5374
5690
  await client.setLogLevel(level);
5375
5691
  printer_default.success(`Log level set to "${level}". Affects daemon JS logs and new tunnels. Run \`pinggy restart <name>\` to apply to a running tunnel.`);
5376
5692
  } catch (err) {
@@ -5380,21 +5696,20 @@ async function handleLogLevel(args) {
5380
5696
  }
5381
5697
  }
5382
5698
  async function handleLogPath(args) {
5383
- const client = new TunnelClient();
5699
+ let client;
5384
5700
  try {
5385
- await client.ensureDaemon();
5701
+ client = openLogLookup();
5386
5702
  } catch (err) {
5387
5703
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5388
5704
  return;
5389
5705
  }
5390
5706
  try {
5391
5707
  if (args.length === 0) {
5392
- const paths = await client.getLogPaths();
5393
- printer_default.print(paths.daemon);
5708
+ printer_default.print(await client.daemonLogPath());
5394
5709
  return;
5395
5710
  }
5396
5711
  const arg = args[0];
5397
- const result = await client.resolveLogPath(arg);
5712
+ const result = await client.resolve(arg);
5398
5713
  switch (result.status) {
5399
5714
  case "running":
5400
5715
  case "historical":
@@ -5427,7 +5742,10 @@ async function handleRestart(args) {
5427
5742
  const nameOrId = args[0];
5428
5743
  const client = new TunnelClient();
5429
5744
  try {
5430
- await client.ensureDaemon();
5745
+ if (!client.connectIfRunning()) {
5746
+ printer_default.error(tunnelNotRunningMessage(nameOrId));
5747
+ process.exit(1);
5748
+ }
5431
5749
  } catch (err) {
5432
5750
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5433
5751
  return;
@@ -5458,7 +5776,89 @@ async function handleRestart(args) {
5458
5776
  }
5459
5777
 
5460
5778
  // src/cli/subcommand/handlers/deviceCommand.ts
5779
+ import pico10 from "picocolors";
5780
+
5781
+ // src/devices/removeDevice.ts
5461
5782
  import pico9 from "picocolors";
5783
+ var YES_ANSWER2 = /^y(es)?$/i;
5784
+ var NO_TERMINAL_MESSAGE2 = "pinggy device remove asks before it removes the device. Run it in a terminal, or add -f to remove without asking.";
5785
+ function machineDeviceRemoveDependencies(background) {
5786
+ return {
5787
+ background,
5788
+ foreground: machineForegroundStopDependencies(),
5789
+ clearIdentity: clearDeviceIdentity,
5790
+ isInteractive: isInteractiveTerminal,
5791
+ prompter: terminalPrompter,
5792
+ print: (message) => printer_default.print(message),
5793
+ printSuccess: (message) => printer_default.success(message),
5794
+ printError: (message) => printer_default.error(message)
5795
+ };
5796
+ }
5797
+ async function readActivity(dependencies) {
5798
+ const reading = await readBackgroundAgent(dependencies.background);
5799
+ return {
5800
+ identity: dependencies.background.readIdentity(),
5801
+ background: reading && isAgentRunning(reading.status) ? reading : null,
5802
+ foreground: dependencies.background.readForegroundAgent()
5803
+ };
5804
+ }
5805
+ function describeActivity(activity) {
5806
+ const { identity, background, foreground } = activity;
5807
+ const lines = [];
5808
+ if (identity) {
5809
+ const deviceAgentId = identity.device_agent_id ?? "(id not yet assigned)";
5810
+ lines.push(`This machine is device ${deviceAgentId} on ${identity.server}.`);
5811
+ }
5812
+ if (background) {
5813
+ lines.push(`The device agent runs in the background: ${describeAgent(background)}.`);
5814
+ }
5815
+ if (foreground) {
5816
+ lines.push(`The device agent runs in another terminal, PID ${foreground.pid}.`);
5817
+ }
5818
+ if (background || foreground) {
5819
+ lines.push("Removing it stops the agent, and the device shows offline in the dashboard.");
5820
+ } else {
5821
+ lines.push("The device is not connected now.");
5822
+ }
5823
+ return lines;
5824
+ }
5825
+ async function confirmed(options, dependencies) {
5826
+ if (options.skipConfirmation) {
5827
+ return true;
5828
+ }
5829
+ const answer = await dependencies.prompter.ask("Remove this device from this machine? [y/N] ");
5830
+ return YES_ANSWER2.test(answer.trim());
5831
+ }
5832
+ async function runDeviceRemove(options, dependencies) {
5833
+ const activity = await readActivity(dependencies);
5834
+ if (!activity.identity && !activity.background && !activity.foreground) {
5835
+ dependencies.print(pico9.yellow("This machine is not enrolled."));
5836
+ return EXIT_OK;
5837
+ }
5838
+ if (!options.skipConfirmation && !dependencies.isInteractive()) {
5839
+ dependencies.printError(NO_TERMINAL_MESSAGE2);
5840
+ return EXIT_FAILED;
5841
+ }
5842
+ describeActivity(activity).forEach((line) => dependencies.print(line));
5843
+ if (!await confirmed(options, dependencies)) {
5844
+ dependencies.print("Nothing removed.");
5845
+ return EXIT_OK;
5846
+ }
5847
+ if (!await stopAgentBeforeRemove(dependencies.background)) {
5848
+ return EXIT_FAILED;
5849
+ }
5850
+ if (!await stopForegroundAgentBeforeRemove(dependencies.foreground)) {
5851
+ return EXIT_FAILED;
5852
+ }
5853
+ dependencies.background.forgetSavedAgent();
5854
+ if (dependencies.clearIdentity()) {
5855
+ dependencies.printSuccess("Local device credential removed.");
5856
+ dependencies.print(pico9.gray("The device still exists in the dashboard. Delete it there to revoke it."));
5857
+ }
5858
+ return EXIT_OK;
5859
+ }
5860
+
5861
+ // src/cli/subcommand/handlers/deviceCommand.ts
5462
5862
  var DeviceVerb = {
5463
5863
  Login: "login",
5464
5864
  Connect: "connect",
@@ -5519,7 +5919,10 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
5519
5919
  await handleDeviceStatus(background);
5520
5920
  return;
5521
5921
  case DeviceVerb.Remove:
5522
- exitUnlessOk(await handleDeviceRemove(background));
5922
+ exitUnlessOk(await runDeviceRemove(
5923
+ { skipConfirmation: Boolean(values.force) },
5924
+ machineDeviceRemoveDependencies(background)
5925
+ ));
5523
5926
  return;
5524
5927
  default:
5525
5928
  if (verb === "help" || verb === "--help" || verb === "-h") {
@@ -5545,7 +5948,15 @@ function devicesSpellingMessage(args) {
5545
5948
  return `"pinggy devices" is now "pinggy device". Run: pinggy device ${suggestion}`;
5546
5949
  }
5547
5950
  async function mayRunInForeground(background) {
5548
- const refusal = await foregroundRefusal(background);
5951
+ const refusal = foregroundAgentRefusal(background.readForegroundAgent()) ?? await foregroundRefusal(background);
5952
+ if (refusal) {
5953
+ printer_default.error(refusal);
5954
+ return false;
5955
+ }
5956
+ return true;
5957
+ }
5958
+ function mayRunInBackground(background) {
5959
+ const refusal = foregroundAgentRefusal(background.readForegroundAgent());
5549
5960
  if (refusal) {
5550
5961
  printer_default.error(refusal);
5551
5962
  return false;
@@ -5557,6 +5968,7 @@ async function handleDeviceLogin(manage, name, inBackground, background) {
5557
5968
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
5558
5969
  return runDeviceLogin({ manage, name });
5559
5970
  }
5971
+ if (!mayRunInBackground(background)) return EXIT_FAILED;
5560
5972
  return runDeviceLogin({ manage, name }, {
5561
5973
  ...machineDeviceLoginDependencies(),
5562
5974
  runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
@@ -5569,6 +5981,7 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
5569
5981
  return EXIT_FAILED;
5570
5982
  }
5571
5983
  if (inBackground) {
5984
+ if (!mayRunInBackground(background)) return EXIT_FAILED;
5572
5985
  return startAgentInBackground(target, background);
5573
5986
  }
5574
5987
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
@@ -5578,26 +5991,19 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
5578
5991
  async function handleDeviceStatus(background) {
5579
5992
  const identity = background.readIdentity();
5580
5993
  if (!identity) {
5581
- printer_default.print(pico9.yellow("This machine is not enrolled. Run: pinggy device login"));
5994
+ printer_default.print(pico10.yellow("This machine is not enrolled. Run: pinggy device login"));
5582
5995
  return;
5583
5996
  }
5584
- printer_default.print(` Device id ${identity.device_agent_id ?? pico9.gray("not yet assigned")}`);
5997
+ printer_default.print(` Device id ${identity.device_agent_id ?? pico10.gray("not yet assigned")}`);
5585
5998
  printer_default.print(` Server ${identity.server}`);
5586
5999
  printer_default.print(` Token ${maskToken(identity.token)}`);
5587
- printer_default.print(` Enrolled ${identity.enrolled_at ?? pico9.gray("never")}`);
5588
- await printBackgroundStatus(background);
5589
- }
5590
- async function handleDeviceRemove(background) {
5591
- if (!await stopAgentBeforeRemove(background)) {
5592
- return EXIT_FAILED;
5593
- }
5594
- if (clearDeviceIdentity()) {
5595
- printer_default.success("Local device credential removed.");
5596
- printer_default.print(pico9.gray("The device still exists in the dashboard. Delete it there to revoke it."));
5597
- } else {
5598
- printer_default.print(pico9.yellow("This machine is not enrolled."));
6000
+ printer_default.print(` Enrolled ${identity.enrolled_at ?? pico10.gray("never")}`);
6001
+ printer_default.print(` Autostart ${background.hasSavedAgent() ? "on, starts with the daemon" : pico10.gray("off")}`);
6002
+ const foreground = background.readForegroundAgent();
6003
+ if (foreground) {
6004
+ printer_default.print(` Foreground running in another terminal, PID ${foreground.pid}`);
5599
6005
  }
5600
- return EXIT_OK;
6006
+ await printBackgroundStatus(background);
5601
6007
  }
5602
6008
 
5603
6009
  // src/cli/subcommand/subcommands.ts
@@ -5868,12 +6274,12 @@ async function initRemoteManagementBackground(values) {
5868
6274
  }
5869
6275
 
5870
6276
  // src/daemon/lifecycle/daemonChild.ts
5871
- import fs11 from "fs";
6277
+ import fs14 from "fs";
5872
6278
 
5873
6279
  // src/daemon/ipc/ipcServer.ts
5874
6280
  import http from "http";
5875
- import fs10 from "fs";
5876
- import path5 from "path";
6281
+ import fs12 from "fs";
6282
+ import path6 from "path";
5877
6283
  import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
5878
6284
 
5879
6285
  // src/daemon/ws/wsProtocol.ts
@@ -5900,17 +6306,17 @@ function parseClientMessage(raw) {
5900
6306
  }
5901
6307
 
5902
6308
  // src/daemon/lifecycle/stateStore.ts
5903
- import fs9 from "fs";
5904
- import path4 from "path";
6309
+ import fs11 from "fs";
6310
+ import path5 from "path";
5905
6311
  var STATE_FILENAME = "daemon-state.json";
5906
6312
  function getStatePath() {
5907
- return path4.join(getPinggyConfigDir(), STATE_FILENAME);
6313
+ return path5.join(getPinggyConfigDir(), STATE_FILENAME);
5908
6314
  }
5909
6315
  function loadDaemonState() {
5910
6316
  const statePath = getStatePath();
5911
6317
  try {
5912
- if (!fs9.existsSync(statePath)) return null;
5913
- const raw = fs9.readFileSync(statePath, "utf-8");
6318
+ if (!fs11.existsSync(statePath)) return null;
6319
+ const raw = fs11.readFileSync(statePath, "utf-8");
5914
6320
  const state = JSON.parse(raw);
5915
6321
  if (!Array.isArray(state.tunnels)) return null;
5916
6322
  return state;
@@ -5924,8 +6330,8 @@ function persistDaemonState(state) {
5924
6330
  const tmpPath = statePath + ".tmp";
5925
6331
  try {
5926
6332
  state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
5927
- fs9.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
5928
- fs9.renameSync(tmpPath, statePath);
6333
+ fs11.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
6334
+ fs11.renameSync(tmpPath, statePath);
5929
6335
  } catch (err) {
5930
6336
  logger.error("Failed to persist daemon state", { error: errorMessage(err) });
5931
6337
  }
@@ -5933,8 +6339,8 @@ function persistDaemonState(state) {
5933
6339
  function clearDaemonState() {
5934
6340
  const statePath = getStatePath();
5935
6341
  try {
5936
- if (fs9.existsSync(statePath)) {
5937
- fs9.unlinkSync(statePath);
6342
+ if (fs11.existsSync(statePath)) {
6343
+ fs11.unlinkSync(statePath);
5938
6344
  }
5939
6345
  } catch {
5940
6346
  }
@@ -5948,33 +6354,16 @@ function removeTunnelFromState(state, tunnelId) {
5948
6354
  }
5949
6355
 
5950
6356
  // src/daemon/ipc/ipcServer.ts
5951
- var VALID_ORIGINS = ["app", "cli", "remote", "device"];
5952
6357
  function parseOrigin(req) {
5953
6358
  const raw = req.headers["x-pinggy-origin"];
5954
6359
  const v = Array.isArray(raw) ? raw[0] : raw;
5955
- return v && VALID_ORIGINS.includes(v) ? v : "cli";
6360
+ return v && TUNNEL_ORIGINS.includes(v) ? v : "cli";
5956
6361
  }
5957
6362
  function parseBody(method, body) {
5958
6363
  if (method === "GET") return void 0;
5959
6364
  if (!body) return {};
5960
6365
  return JSON.parse(body);
5961
6366
  }
5962
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5963
- function parseTunnelLogFilename(filename) {
5964
- const base = filename.replace(/\.log$/, "");
5965
- const parts = base.split("__");
5966
- if (parts.length < 2) return null;
5967
- const origin = parts[0];
5968
- if (!VALID_ORIGINS.includes(origin)) return null;
5969
- if (parts.length === 2) {
5970
- const second = parts[1];
5971
- if (UUID_RE.test(second)) return { origin, tunnelId: second };
5972
- return { origin, name: second };
5973
- }
5974
- const tunnelId = parts[parts.length - 1];
5975
- const name = parts.slice(1, -1).join("__");
5976
- return { origin, name, tunnelId };
5977
- }
5978
6367
  var IPCServer = class {
5979
6368
  constructor() {
5980
6369
  this.sessions = /* @__PURE__ */ new Map();
@@ -6110,8 +6499,8 @@ var IPCServer = class {
6110
6499
  const logDir = getTunnelLogDir();
6111
6500
  const daemonPath = getDaemonLogPath();
6112
6501
  const tunnels = [];
6113
- if (fs10.existsSync(logDir)) {
6114
- const files = fs10.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
6502
+ const files = listTunnelLogFiles();
6503
+ if (files.length > 0) {
6115
6504
  const manager = TunnelManager.getInstance();
6116
6505
  const activeIds = manager.getActiveTunnelIds();
6117
6506
  const activeNames = /* @__PURE__ */ new Set();
@@ -6121,8 +6510,8 @@ var IPCServer = class {
6121
6510
  if (n) activeNames.add(n);
6122
6511
  }
6123
6512
  for (const file of files) {
6124
- const filePath = path5.join(logDir, file);
6125
- const stat = fs10.statSync(filePath);
6513
+ const filePath = path6.join(logDir, file);
6514
+ const stat = fs12.statSync(filePath);
6126
6515
  const parsed = parseTunnelLogFilename(file);
6127
6516
  if (!parsed) continue;
6128
6517
  const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
@@ -6229,7 +6618,6 @@ var IPCServer = class {
6229
6618
  }
6230
6619
  async resolveLogPath(q) {
6231
6620
  if (!q) return { status: "not-found" };
6232
- const logDir = getTunnelLogDir();
6233
6621
  const manager = TunnelManager.getInstance();
6234
6622
  const activeIds = manager.getActiveTunnelIds();
6235
6623
  for (const t of await manager.getAllTunnels()) {
@@ -6241,32 +6629,7 @@ var IPCServer = class {
6241
6629
  return { status: "running", path: logPath, tunnelId: t.tunnelid, name, origin, running: true };
6242
6630
  }
6243
6631
  }
6244
- if (fs10.existsSync(logDir)) {
6245
- const files = fs10.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
6246
- const matches = [];
6247
- for (const file of files) {
6248
- const parsed = parseTunnelLogFilename(file);
6249
- if (!parsed) continue;
6250
- const nameMatch = parsed.name !== void 0 && parsed.name === q;
6251
- const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
6252
- if (nameMatch || idMatch) {
6253
- const filePath = path5.join(logDir, file);
6254
- const stat = fs10.statSync(filePath);
6255
- matches.push({ path: filePath, mtime: stat.mtimeMs, tunnelId: parsed.tunnelId, name: parsed.name, origin: parsed.origin });
6256
- }
6257
- }
6258
- if (matches.length > 0) {
6259
- matches.sort((a, b) => b.mtime - a.mtime);
6260
- const best = matches[0];
6261
- return { status: "historical", path: best.path, tunnelId: best.tunnelId, name: best.name, origin: best.origin, running: false };
6262
- }
6263
- }
6264
- const saved = listSavedConfigs();
6265
- const matchedConfig = saved.find((c) => c.name === q || c.configId === q || c.configId.startsWith(q));
6266
- if (matchedConfig) {
6267
- return { status: "config-only", name: matchedConfig.name, configId: matchedConfig.configId };
6268
- }
6269
- return { status: "not-found" };
6632
+ return resolveStoppedLogPath(q);
6270
6633
  }
6271
6634
  setupWebSocket() {
6272
6635
  this.server.on("upgrade", (req, socket, head) => {
@@ -6628,7 +6991,7 @@ var DeviceAgentHost = class {
6628
6991
  this.statusValue = stoppedStatus();
6629
6992
  /** Bumped on every start and stop. A run's reporter whose number is old belongs to a run that ended. */
6630
6993
  this.generation = 0;
6631
- /** Set once the daemon shuts down. Nothing starts and nothing more reaches daemon-state.json. */
6994
+ /** Set once the daemon shuts down. Nothing starts and nothing more is recorded. */
6632
6995
  this.closed = false;
6633
6996
  /** Start and stop chain on this, so 1 finishes before the next begins. */
6634
6997
  this.queue = Promise.resolve();
@@ -6666,8 +7029,8 @@ var DeviceAgentHost = class {
6666
7029
  });
6667
7030
  }
6668
7031
  /**
6669
- * The daemon is shutting down. Stops the run at once, outside the queue, and writes nothing to
6670
- * daemon-state.json: the shutdown deletes that file, and a write after it would bring the file back.
7032
+ * The daemon is shutting down. Stops the run at once, outside the queue. Records nothing, so the saved
7033
+ * agent stays and the next daemon start runs it again.
6671
7034
  */
6672
7035
  close() {
6673
7036
  this.closed = true;
@@ -6710,9 +7073,6 @@ var DeviceAgentHost = class {
6710
7073
  this.current = null;
6711
7074
  this.generation += 1;
6712
7075
  this.statusValue = { ...this.statusValue, state: DeviceAgentState.Stopped, connectedAt: null };
6713
- if (!this.closed) {
6714
- this.dependencies.recordStopped();
6715
- }
6716
7076
  await current.run.stop();
6717
7077
  logger.info("Device agent stopped in the daemon");
6718
7078
  }
@@ -6796,6 +7156,56 @@ function machineDeviceAgentHostDependencies(port, record) {
6796
7156
  };
6797
7157
  }
6798
7158
 
7159
+ // src/daemon/lifecycle/daemonLock.ts
7160
+ import fs13 from "fs";
7161
+ var UNREADABLE_LOCK_GRACE_MILLIS = 1e4;
7162
+ function readLock(lockPath) {
7163
+ try {
7164
+ const record = JSON.parse(fs13.readFileSync(lockPath, "utf-8"));
7165
+ return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
7166
+ } catch {
7167
+ return null;
7168
+ }
7169
+ }
7170
+ function isUnreadableLockOld(lockPath) {
7171
+ try {
7172
+ return Date.now() - fs13.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
7173
+ } catch {
7174
+ return true;
7175
+ }
7176
+ }
7177
+ function isStale(lockPath, holder) {
7178
+ if (!holder) return isUnreadableLockOld(lockPath);
7179
+ return startedBeforeBoot(holder.started_at) || !isProcessAlive(holder.pid);
7180
+ }
7181
+ function createLock(lockPath, record) {
7182
+ try {
7183
+ fs13.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
7184
+ return true;
7185
+ } catch (err) {
7186
+ if (err.code === "EEXIST") return false;
7187
+ throw err;
7188
+ }
7189
+ }
7190
+ function acquireDaemonLock() {
7191
+ ensurePinggyConfigDir();
7192
+ const lockPath = getDaemonLockPath();
7193
+ const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
7194
+ if (createLock(lockPath, record)) return true;
7195
+ const holder = readLock(lockPath);
7196
+ if (holder?.pid === process.pid) return true;
7197
+ if (!isStale(lockPath, holder)) return false;
7198
+ logger.info("Stale daemon.lock found, replacing it", { stalePid: holder?.pid });
7199
+ fs13.rmSync(lockPath, { force: true });
7200
+ return createLock(lockPath, record);
7201
+ }
7202
+ function releaseDaemonLock() {
7203
+ const lockPath = getDaemonLockPath();
7204
+ if (readLock(lockPath)?.pid === process.pid) {
7205
+ fs13.rmSync(lockPath, { force: true });
7206
+ }
7207
+ }
7208
+
6799
7209
  // src/daemon/lifecycle/daemonChild.ts
6800
7210
  var daemonState = { tunnels: [], lastUpdated: "" };
6801
7211
  var daemonHost = DaemonHost.CLI;
@@ -6810,13 +7220,14 @@ function writeDaemonInfo(info) {
6810
7220
  ensurePinggyConfigDir();
6811
7221
  const infoPath = getDaemonInfoPath();
6812
7222
  const tmpPath = infoPath + ".tmp";
6813
- fs11.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
6814
- fs11.renameSync(tmpPath, infoPath);
7223
+ fs14.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
7224
+ fs14.renameSync(tmpPath, infoPath);
6815
7225
  }
6816
7226
  function removeDaemonInfo() {
6817
7227
  try {
6818
7228
  const infoPath = getDaemonInfoPath();
6819
- if (fs11.existsSync(infoPath)) fs11.unlinkSync(infoPath);
7229
+ const info = JSON.parse(fs14.readFileSync(infoPath, "utf-8"));
7230
+ if (info.pid === process.pid) fs14.unlinkSync(infoPath);
6820
7231
  } catch {
6821
7232
  }
6822
7233
  }
@@ -6841,27 +7252,23 @@ function trackTunnelStop(tunnelId) {
6841
7252
  persistDaemonState(daemonState);
6842
7253
  sessionTrackerRef?.removeTunnel(tunnelId);
6843
7254
  }
6844
- function trackDeviceAgentStart(startedBy) {
6845
- daemonState.deviceAgent = { startedAt: (/* @__PURE__ */ new Date()).toISOString(), startedBy };
6846
- persistDaemonState(daemonState);
6847
- }
6848
- function trackDeviceAgentStop() {
6849
- if (!daemonState.deviceAgent) return;
6850
- delete daemonState.deviceAgent;
6851
- persistDaemonState(daemonState);
6852
- }
6853
- async function restoreCrashedDeviceAgent(host, saved) {
7255
+ async function startSavedDeviceAgent(host, saved) {
7256
+ const foreground = readForegroundAgent();
7257
+ if (foreground) {
7258
+ logger.info("Device agent not started: it runs in a terminal", { pid: foreground.pid });
7259
+ return;
7260
+ }
6854
7261
  try {
6855
7262
  const result = await host.start(saved.startedBy);
6856
7263
  if (isErrorResponse(result)) {
6857
- logger.warn("Crash recovery: device agent not restored", { reason: result.message });
6858
- trackDeviceAgentStop();
7264
+ logger.warn("Saved device agent not started", { reason: result.message });
7265
+ forgetDeviceAgent();
6859
7266
  return;
6860
7267
  }
6861
- logger.info("Crash recovery: device agent restored");
7268
+ logger.info("Saved device agent started");
6862
7269
  } catch (err) {
6863
- logger.error("Crash recovery: device agent failed to start", { error: errorMessage(err) });
6864
- trackDeviceAgentStop();
7270
+ logger.error("Saved device agent failed to start", { error: errorMessage(err) });
7271
+ forgetDeviceAgent();
6865
7272
  }
6866
7273
  }
6867
7274
  function trackIPCTunnelStart(tunnelId, origin, mode = SessionMode.Detached) {
@@ -6956,9 +7363,7 @@ async function runDaemonChild(opts = {}) {
6956
7363
  const exitOnFailure = opts.exitOnFailure ?? true;
6957
7364
  daemonHost = opts.host ?? DaemonHost.CLI;
6958
7365
  ensurePinggyConfigDir();
6959
- const persistedLevel = readDaemonConfig()?.logLevel;
6960
- const envLevel = process.env.PINGGY_LOG_LEVEL;
6961
- const initialLevel = persistedLevel ?? envLevel ?? "info";
7366
+ const initialLevel = configuredLogLevel();
6962
7367
  setLogLevel(initialLevel);
6963
7368
  ensurePinggyLogDir();
6964
7369
  const logPath = getDaemonLogPath();
@@ -6969,6 +7374,11 @@ async function runDaemonChild(opts = {}) {
6969
7374
  enableSdkLog: true
6970
7375
  });
6971
7376
  logger.info("Daemon starting", { pid: process.pid, inProcess: !installSignalHandlers });
7377
+ if (!acquireDaemonLock()) {
7378
+ logger.info("Another daemon holds daemon.lock. Exiting.");
7379
+ if (exitOnFailure) process.exit(0);
7380
+ throw new Error("Another pinggy daemon is running.");
7381
+ }
6972
7382
  const manager = TunnelManager.getInstance();
6973
7383
  const ipcServer = new IPCServer();
6974
7384
  const sessionTracker = new SessionTracker();
@@ -6991,6 +7401,10 @@ async function runDaemonChild(opts = {}) {
6991
7401
  removeDaemonInfo();
6992
7402
  } catch {
6993
7403
  }
7404
+ try {
7405
+ releaseDaemonLock();
7406
+ } catch {
7407
+ }
6994
7408
  try {
6995
7409
  clearDaemonState();
6996
7410
  } catch {
@@ -7033,14 +7447,10 @@ async function runDaemonChild(opts = {}) {
7033
7447
  try {
7034
7448
  const port = await ipcServer.listen();
7035
7449
  deviceAgentHost = new DeviceAgentHost(machineDeviceAgentHostDependencies(port, {
7036
- recordRunning: trackDeviceAgentStart,
7037
- recordStopped: trackDeviceAgentStop
7450
+ recordRunning: saveDeviceAgent,
7451
+ recordStopped: forgetDeviceAgent
7038
7452
  }));
7039
7453
  ipcServer.setDeviceAgentHost(deviceAgentHost);
7040
- const crashedDeviceAgent = loadDaemonState()?.deviceAgent;
7041
- if (crashedDeviceAgent) {
7042
- daemonState.deviceAgent = crashedDeviceAgent;
7043
- }
7044
7454
  const info = {
7045
7455
  pid: process.pid,
7046
7456
  port,
@@ -7064,8 +7474,9 @@ async function runDaemonChild(opts = {}) {
7064
7474
  } else {
7065
7475
  logger.info("No auto-start tunnels configured");
7066
7476
  }
7067
- if (crashedDeviceAgent) {
7068
- await restoreCrashedDeviceAgent(deviceAgentHost, crashedDeviceAgent);
7477
+ const savedAgent = savedDeviceAgent();
7478
+ if (savedAgent) {
7479
+ await startSavedDeviceAgent(deviceAgentHost, savedAgent);
7069
7480
  }
7070
7481
  logger.info("Daemon ready", { pid: process.pid, port });
7071
7482
  return {
@@ -7076,6 +7487,7 @@ async function runDaemonChild(opts = {}) {
7076
7487
  } catch (err) {
7077
7488
  logger.error("Daemon failed to start", { error: errorMessage(err) });
7078
7489
  removeDaemonInfo();
7490
+ releaseDaemonLock();
7079
7491
  if (exitOnFailure) {
7080
7492
  process.exit(1);
7081
7493
  }
@@ -7090,7 +7502,7 @@ async function main() {
7090
7502
  const { values, positionals, hasAnyArgs } = parseCliArgs(cliOptions);
7091
7503
  configureLogger(values);
7092
7504
  if (values["_daemon-child"]) {
7093
- const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-WHS676G4.js");
7505
+ const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-HZ27YJKQ.js");
7094
7506
  await runDaemonChild2();
7095
7507
  return;
7096
7508
  }
@@ -7129,8 +7541,6 @@ export {
7129
7541
  removeDaemonInfo,
7130
7542
  trackTunnelStart,
7131
7543
  trackTunnelStop,
7132
- trackDeviceAgentStart,
7133
- trackDeviceAgentStop,
7134
7544
  trackIPCTunnelStart,
7135
7545
  runDaemonChild
7136
7546
  };