pinggy 0.6.3 → 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-GESMZQHI.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 = {
@@ -129,6 +137,8 @@ var cliOptions = {
129
137
  // Background mode (run tunnel in background via daemon)
130
138
  b: { type: "boolean", description: "Run tunnel in background via daemon. CLI exits after tunnel starts." },
131
139
  all: { type: "boolean", description: "Start all auto-start tunnels" },
140
+ // `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
141
+ foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
132
142
  // Internal daemon child marker
133
143
  "_daemon-child": { type: "boolean", description: "Internal: daemon child process marker", hidden: true },
134
144
  // Misc
@@ -199,10 +209,17 @@ function printHelpMessage() {
199
209
  console.log("\nBackground Mode:");
200
210
  console.log(" pinggy -l 3000 --b # Start tunnel in background");
201
211
  console.log(" pinggy start my-tunnel --b # Start saved tunnel in background");
212
+ console.log("\nDevices (more: pinggy device --help):");
213
+ console.log(" pinggy device login # Sign in by email. The agent runs in the background");
214
+ console.log(" pinggy device login --foreground # Same, with the agent in this terminal");
215
+ console.log(" pinggy device status # Show this device and its agent");
216
+ console.log(" pinggy device stop # Stop the background agent");
202
217
  console.log("\nDaemon Lifecycle (also: pinggy d <command>):");
203
218
  console.log(" pinggy daemon start # Start the background daemon");
204
219
  console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
205
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");
206
223
  }
207
224
 
208
225
  // src/utils/parseArgs.ts
@@ -812,10 +829,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
812
829
  }
813
830
  function storeJson(config, saveconf) {
814
831
  if (saveconf) {
815
- const path6 = saveconf;
832
+ const path7 = saveconf;
816
833
  try {
817
- fs.writeFileSync(path6, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
818
- 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}`);
819
836
  } catch (err) {
820
837
  const msg = err instanceof Error ? err.message : String(err);
821
838
  logger.error("Error loading configuration:", msg);
@@ -1140,7 +1157,7 @@ async function connectTui(opts) {
1140
1157
  const exitMessage = opts.exitMessage || "Stopping tunnel...";
1141
1158
  if (!noTui && process.stdin.isTTY) {
1142
1159
  try {
1143
- const { TunnelTui } = await import("./TunnelTui-UCG2YSLX.js");
1160
+ const { TunnelTui } = await import("./TunnelTui-K7KESRTQ.js");
1144
1161
  const tui = new TunnelTui({
1145
1162
  urls,
1146
1163
  greet,
@@ -1363,7 +1380,7 @@ async function startBackgroundTunnels(configs, values, positionals) {
1363
1380
  client.close();
1364
1381
  }
1365
1382
  async function startAutoStartTunnels() {
1366
- const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-RR5ZU4E3.js");
1383
+ const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-DXC6WMYO.js");
1367
1384
  const configs = getAutoStartConfigs2();
1368
1385
  if (configs.length === 0) {
1369
1386
  printer_default.warn("No configs marked for auto-start. Use: pinggy config auto <name>");
@@ -1484,7 +1501,7 @@ async function initRemoteManagement(values, blocking) {
1484
1501
  }
1485
1502
 
1486
1503
  // src/cli/subcommand/handlers/daemonCommandsHandler.ts
1487
- import pico2 from "picocolors";
1504
+ import pico6 from "picocolors";
1488
1505
 
1489
1506
  // src/daemon/lifecycle/serviceInstaller.ts
1490
1507
  import os2 from "os";
@@ -1493,24 +1510,62 @@ import path2 from "path";
1493
1510
  import { execSync, execFileSync } from "child_process";
1494
1511
  var SERVICE_LABEL = "io.pinggy.agent";
1495
1512
  var SYSTEMD_SERVICE_NAME = "pinggy";
1496
- function resolveBinary() {
1497
- const isPkg = "pkg" in process;
1498
- 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) {
1499
1522
  try {
1500
- const bin = execSync(os2.platform() === "win32" ? "where pinggy" : "which pinggy", {
1501
- encoding: "utf-8"
1502
- }).trim().split(/\r?\n/)[0];
1503
- return { program: bin, args: [] };
1523
+ return fs2.realpathSync(p);
1504
1524
  } catch {
1505
- return { program: process.execPath, args: [process.argv[1]] };
1525
+ return p;
1506
1526
  }
1507
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
+ }
1508
1563
  function getSystemdServicePath() {
1509
1564
  const dir = path2.join(os2.homedir(), ".config", "systemd", "user");
1510
1565
  return path2.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
1511
1566
  }
1512
- function generateSystemdUnit(bin) {
1513
- const execStart = [bin.program, ...bin.args, "--_daemon-child"].join(" ");
1567
+ function generateSystemdUnit(program) {
1568
+ const execStart = `${program} --_daemon-child`;
1514
1569
  return `[Unit]
1515
1570
  Description=Pinggy Tunnel Daemon
1516
1571
  After=network-online.target
@@ -1526,18 +1581,17 @@ RestartSec=5
1526
1581
  WantedBy=default.target
1527
1582
  `;
1528
1583
  }
1529
- function installSystemd() {
1530
- const bin = resolveBinary();
1584
+ function installSystemd(program) {
1531
1585
  const servicePath = getSystemdServicePath();
1532
1586
  const dir = path2.dirname(servicePath);
1533
1587
  fs2.mkdirSync(dir, { recursive: true });
1534
- fs2.writeFileSync(servicePath, generateSystemdUnit(bin), "utf-8");
1535
- execSync("systemctl --user daemon-reload");
1536
- execSync(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`);
1537
- execSync(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`);
1538
- logger.info("systemd user service installed and started", { servicePath });
1539
- console.log(`Service installed: ${servicePath}`);
1540
- 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}`);
1541
1595
  }
1542
1596
  function uninstallSystemd() {
1543
1597
  const servicePath = getSystemdServicePath();
@@ -1548,17 +1602,18 @@ function uninstallSystemd() {
1548
1602
  }
1549
1603
  if (fs2.existsSync(servicePath)) {
1550
1604
  fs2.unlinkSync(servicePath);
1551
- execSync("systemctl --user daemon-reload");
1552
- console.log(`Service removed: ${servicePath}`);
1605
+ execSync("systemctl --user daemon-reload", QUIET);
1606
+ logger.info("systemd user service removed", { servicePath });
1607
+ printUninstalled();
1553
1608
  } else {
1554
- console.log("No systemd service found to remove.");
1609
+ printNotInstalled();
1555
1610
  }
1556
1611
  }
1557
1612
  function getLaunchdPlistPath() {
1558
1613
  return path2.join(os2.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
1559
1614
  }
1560
- function generateLaunchdPlist(bin) {
1561
- const allArgs = [bin.program, ...bin.args, "--_daemon-child"];
1615
+ function generateLaunchdPlist(program) {
1616
+ const allArgs = [program, "--_daemon-child"];
1562
1617
  const programArgs = allArgs.map((p) => ` <string>${p}</string>`).join("\n");
1563
1618
  return `<?xml version="1.0" encoding="UTF-8"?>
1564
1619
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
@@ -1579,17 +1634,21 @@ ${programArgs}
1579
1634
  </plist>
1580
1635
  `;
1581
1636
  }
1582
- function installLaunchd() {
1583
- const bin = resolveBinary();
1637
+ function installLaunchd(program) {
1584
1638
  const plistPath = getLaunchdPlistPath();
1585
1639
  const dir = path2.dirname(plistPath);
1586
1640
  fs2.mkdirSync(dir, { recursive: true });
1587
- fs2.writeFileSync(plistPath, generateLaunchdPlist(bin), "utf-8");
1641
+ fs2.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
1588
1642
  const uid = process.getuid?.() ?? 501;
1589
1643
  try {
1590
1644
  execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
1591
1645
  } catch {
1592
1646
  }
1647
+ loadLaunchdPlist(uid, plistPath);
1648
+ logger.info("launchd agent installed", { plistPath });
1649
+ printInstalled();
1650
+ }
1651
+ function loadLaunchdPlist(uid, plistPath) {
1593
1652
  try {
1594
1653
  execSync(`launchctl bootstrap gui/${uid} ${plistPath}`);
1595
1654
  } catch {
@@ -1598,8 +1657,6 @@ function installLaunchd() {
1598
1657
  } catch {
1599
1658
  }
1600
1659
  }
1601
- logger.info("launchd agent installed and started", { plistPath });
1602
- console.log(`Service installed and started: ${plistPath}`);
1603
1660
  }
1604
1661
  function uninstallLaunchd() {
1605
1662
  const plistPath = getLaunchdPlistPath();
@@ -1614,24 +1671,34 @@ function uninstallLaunchd() {
1614
1671
  }
1615
1672
  if (fs2.existsSync(plistPath)) {
1616
1673
  fs2.unlinkSync(plistPath);
1617
- console.log(`Service removed: ${plistPath}`);
1674
+ logger.info("launchd agent removed", { plistPath });
1675
+ printUninstalled();
1618
1676
  } else {
1619
- console.log("No launchd agent found to remove.");
1677
+ printNotInstalled();
1620
1678
  }
1621
1679
  }
1622
1680
  var WINDOWS_TASK_NAME = "PinggyDaemon";
1623
- function generateTaskXml(bin) {
1624
- const command = bin.program;
1625
- 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);
1626
1691
  return `<?xml version="1.0" encoding="UTF-16"?>
1627
1692
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
1628
1693
  <Triggers>
1629
1694
  <LogonTrigger>
1630
1695
  <Enabled>true</Enabled>
1696
+ <UserId>${user}</UserId>
1631
1697
  </LogonTrigger>
1632
1698
  </Triggers>
1633
1699
  <Principals>
1634
1700
  <Principal id="Author">
1701
+ <UserId>${user}</UserId>
1635
1702
  <LogonType>InteractiveToken</LogonType>
1636
1703
  <RunLevel>LeastPrivilege</RunLevel>
1637
1704
  </Principal>
@@ -1649,71 +1716,105 @@ function generateTaskXml(bin) {
1649
1716
  </Settings>
1650
1717
  <Actions>
1651
1718
  <Exec>
1652
- <Command>${command}</Command>${args ? `
1653
- <Arguments>${args}</Arguments>` : ""}
1719
+ <Command>${escapeXml(program)}</Command>
1720
+ <Arguments>daemon start</Arguments>
1654
1721
  </Exec>
1655
1722
  </Actions>
1656
1723
  </Task>`;
1657
1724
  }
1658
- function installWindows() {
1659
- const bin = resolveBinary();
1660
- const xml = generateTaskXml(bin);
1725
+ function createWindowsTask(program) {
1726
+ const xml = generateTaskXml(program, getWindowsUserId());
1661
1727
  const tmpPath = path2.join(os2.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
1662
1728
  fs2.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
1663
1729
  try {
1664
- execFileSync("schtasks", [
1665
- "/Create",
1666
- "/TN",
1667
- WINDOWS_TASK_NAME,
1668
- "/XML",
1669
- tmpPath,
1670
- "/F"
1671
- ], { stdio: "inherit" });
1730
+ execFileSync("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
1672
1731
  } finally {
1673
1732
  try {
1674
1733
  fs2.unlinkSync(tmpPath);
1675
1734
  } catch {
1676
1735
  }
1677
1736
  }
1678
- execFileSync("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], { stdio: "inherit" });
1679
- console.log(`Scheduled task "${WINDOWS_TASK_NAME}" created and started (runs at login, hidden).`);
1680
1737
  }
1681
- function uninstallWindows() {
1738
+ function windowsTaskExists() {
1682
1739
  try {
1683
- execFileSync("schtasks", ["/End", "/TN", WINDOWS_TASK_NAME], { stdio: "ignore" });
1740
+ execFileSync("schtasks", ["/Query", "/TN", WINDOWS_TASK_NAME], QUIET);
1741
+ return true;
1684
1742
  } catch {
1743
+ return false;
1685
1744
  }
1745
+ }
1746
+ function isElevated() {
1686
1747
  try {
1687
- execFileSync("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], { stdio: "inherit" });
1688
- console.log(`Scheduled task "${WINDOWS_TASK_NAME}" removed.`);
1748
+ return /S-1-16-(12288|16384)\b/.test(execFileSync("whoami", ["/groups"], { encoding: "utf-8" }));
1689
1749
  } catch {
1690
- console.log("No scheduled task found to remove.");
1750
+ return false;
1751
+ }
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}.`;
1691
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();
1692
1787
  }
1693
1788
  function installService() {
1694
1789
  const platform2 = os2.platform();
1695
- const bin = resolveBinary();
1696
- if (!("pkg" in process) && bin.program !== process.execPath) {
1697
- console.warn(
1698
- "Warning: Using npm-installed binary. The path may change if Node.js is updated.\nConsider using a standalone binary (pkg) for system services."
1699
- );
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);
1700
1801
  }
1701
1802
  switch (platform2) {
1702
1803
  case "linux":
1703
- installSystemd();
1804
+ installSystemd(program);
1704
1805
  break;
1705
1806
  case "darwin":
1706
- installLaunchd();
1807
+ installLaunchd(program);
1707
1808
  break;
1708
1809
  case "win32":
1709
- installWindows();
1810
+ installWindows(program);
1710
1811
  break;
1711
1812
  default:
1712
1813
  console.error(`Unsupported platform: ${platform2}`);
1713
1814
  process.exit(1);
1714
1815
  }
1715
1816
  }
1716
- function uninstallService() {
1817
+ async function uninstallService() {
1717
1818
  const platform2 = os2.platform();
1718
1819
  switch (platform2) {
1719
1820
  case "linux":
@@ -1723,7 +1824,7 @@ function uninstallService() {
1723
1824
  uninstallLaunchd();
1724
1825
  break;
1725
1826
  case "win32":
1726
- uninstallWindows();
1827
+ await uninstallWindows();
1727
1828
  break;
1728
1829
  default:
1729
1830
  console.error(`Unsupported platform: ${platform2}`);
@@ -1739,6 +1840,8 @@ function printDaemonHelp() {
1739
1840
  console.log(" start Start the daemon process");
1740
1841
  console.log(" stop Stop the daemon (stops all tunnels)");
1741
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");
1742
1845
  console.log("Tunnel operations:");
1743
1846
  console.log(" pinggy ps List running tunnels");
1744
1847
  console.log(" pinggy stop <name|id> Stop a specific tunnel");
@@ -1775,22 +1878,32 @@ function printDeviceHelp() {
1775
1878
  console.log("\nUsage: pinggy device <command> [options]\n");
1776
1879
  console.log("Run this machine as a Pinggy device.\n");
1777
1880
  console.log("Commands:");
1778
- console.log(" login Sign this machine in with your email, then stay connected");
1779
- console.log(" connect --token <TOKEN> Enrol, then stay connected until interrupted");
1780
- console.log(" stop Stop the agent running in the background");
1881
+ console.log(" login Sign this machine in with your email, then run the agent in the");
1882
+ console.log(" background");
1883
+ console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
1884
+ console.log(" background. Without --token: start the enrolled device's agent again");
1885
+ console.log(" stop Stop the agent running in the background, until the daemon");
1886
+ console.log(" starts again");
1781
1887
  console.log(" status Show the enrolment, and the agent running in the background");
1782
- console.log(" remove Forget the local credential (does not delete the device)\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");
1783
1892
  console.log("Options:");
1784
- console.log(" -b login and connect: run the agent in the background, in the daemon.");
1785
- console.log(" It stays connected after this terminal closes");
1893
+ console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
1894
+ console.log(" -b login and connect: run the agent in the background. The default");
1786
1895
  console.log(" --token <TOKEN> Device token from the dashboard");
1787
1896
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
1788
- 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");
1789
1899
  console.log("Environment:");
1790
1900
  console.log(" DEVICE_AGENT_TOKEN connect only: the device token, when --token is not given. With no");
1791
1901
  console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
1792
1902
  }
1793
1903
 
1904
+ // src/devices/backgroundAgent.ts
1905
+ import pico5 from "picocolors";
1906
+
1794
1907
  // src/devices/deviceIdentity.ts
1795
1908
  import fs3 from "fs";
1796
1909
  var SECRET_FILE_MODE = 384;
@@ -1885,10 +1998,11 @@ var WelcomeSchema = z.object({
1885
1998
  max_terminals_per_device: z.number().optional(),
1886
1999
  // No default on the agent. Without it, terminals stay unavailable rather than unbraked.
1887
2000
  terminal_window_bytes: z.number().optional(),
1888
- // No default either. Without them the agent runs no expiry timers, and the dashboard's sweep
1889
- // still ends an expired shell, only later.
2001
+ // No default either. Without it the agent runs no expiry timer, and the dashboard's sweep
2002
+ // still ends an idle shell, only later. A shell has no cap on its running time.
1890
2003
  terminal_idle_timeout_seconds: z.number().optional(),
1891
- terminal_max_session_seconds: z.number().optional(),
2004
+ // Optional: without it the agent keeps T2's brake and never skips output (slice T8).
2005
+ terminal_resync: z.boolean().optional(),
1892
2006
  // Optional: a dashboard older than these sends neither, and the agent prints only the device id.
1893
2007
  email: z.string().optional(),
1894
2008
  device_url: z.string().optional()
@@ -1910,28 +2024,36 @@ var TunnelActionSchema = z.object({
1910
2024
  });
1911
2025
 
1912
2026
  // src/devices/deviceAgentReporter.ts
2027
+ import pico2 from "picocolors";
2028
+ function printDeviceUrl(print, label, url) {
2029
+ print(label);
2030
+ print("");
2031
+ print(` ${pico2.magentaBright(url)}`);
2032
+ print("");
2033
+ }
1913
2034
  function printConnected(welcome) {
1914
2035
  printer_default.success(`Connected as device ${welcome.device_agent_id}`);
1915
2036
  if (welcome.email) {
1916
2037
  printer_default.print(`Signed in as ${welcome.email}`);
1917
2038
  }
1918
2039
  if (welcome.device_url) {
1919
- printer_default.print("Open the device in a browser:");
1920
- printer_default.print(` ${welcome.device_url}`);
2040
+ printDeviceUrl((message) => printer_default.print(message), "Open the device in a browser:", welcome.device_url);
1921
2041
  }
1922
2042
  }
1923
2043
  function formatSeconds(millis) {
1924
2044
  return (millis / 1e3).toFixed(1);
1925
2045
  }
1926
2046
  var printingReporter = {
1927
- connecting: (server) => printer_default.print(`Connecting to ${server}`),
2047
+ connecting: (server) => printer_default.print(pico2.cyanBright(`Connecting to ${server}...`)),
1928
2048
  connected: printConnected,
1929
2049
  reconnecting: (delayMillis, attempt) => printer_default.warn(
1930
2050
  `Disconnected. Reconnecting in ${formatSeconds(delayMillis)} seconds (attempt ${attempt}).`
1931
2051
  ),
1932
2052
  warn: (message) => printer_default.warn(message),
1933
2053
  failed: (error) => printer_default.error(error.message),
1934
- replacingDevice: (oldDeviceAgentId) => printer_default.print(`This machine was device ${oldDeviceAgentId}. Connecting it with the token from the command.`)
2054
+ replacingDevice: (oldDeviceAgentId) => printer_default.print(pico2.yellow(
2055
+ `This machine was device ${oldDeviceAgentId}. That device stays in the dashboard, offline.`
2056
+ ))
1935
2057
  };
1936
2058
 
1937
2059
  // src/devices/collectors/systemInfo.ts
@@ -2441,12 +2563,13 @@ var OP_RESIZE = "resize";
2441
2563
  var OP_SIGNAL = "signal";
2442
2564
  var OP_CONTEXT = "context";
2443
2565
  var OP_SNAPSHOT = "snapshot";
2566
+ var OP_RESYNC = "resync";
2567
+ var OP_ACTIVITY = "activity";
2444
2568
  var TERMINAL_SIGNALS = ["INT", "TERM", "QUIT", "HUP"];
2445
2569
  var MIN_GRID = 1;
2446
2570
  var MAX_GRID = 1e3;
2447
2571
  var CLOSE_REASON_USER_CLOSED = "user_closed";
2448
2572
  var CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
2449
- var CLOSE_REASON_MAX_SESSION = "max_session";
2450
2573
  var ERROR_INVALID_PAYLOAD2 = "invalid_payload";
2451
2574
  var ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
2452
2575
  var ERROR_TERMINAL_DISABLED = "terminal_disabled";
@@ -2491,6 +2614,7 @@ function clampGrid(requested, fallback) {
2491
2614
  }
2492
2615
 
2493
2616
  // src/devices/terminal/terminalHandler.ts
2617
+ import { randomUUID as randomUUID2 } from "crypto";
2494
2618
  import os6 from "os";
2495
2619
 
2496
2620
  // src/devices/terminal/flowWindow.ts
@@ -2803,6 +2927,7 @@ var ScreenMirror = class _ScreenMirror {
2803
2927
  this.terminal = terminal;
2804
2928
  this.serializer = serializer;
2805
2929
  this.disposed = false;
2930
+ this.unparsedBytes = 0;
2806
2931
  }
2807
2932
  /** Null when the headless terminal cannot load. The shell then works as before, without restore. */
2808
2933
  static create(cols, rows) {
@@ -2813,28 +2938,45 @@ var ScreenMirror = class _ScreenMirror {
2813
2938
  terminal.loadAddon(serializer);
2814
2939
  return new _ScreenMirror(terminal, serializer);
2815
2940
  }
2816
- /** Bytes exactly as they were sent. xterm parses them later, in order, and joins split characters. */
2817
- feed(bytes) {
2818
- if (!this.disposed) this.terminal.write(bytes);
2941
+ /**
2942
+ * Bytes exactly as they were sent or skipped. xterm parses them later, in order, and joins split
2943
+ * characters. `onParsed` runs once they are parsed, when {@link backlogBytes} has already dropped by them.
2944
+ */
2945
+ feed(bytes, onParsed) {
2946
+ if (this.disposed) return;
2947
+ const byteCount = bytes.length;
2948
+ this.unparsedBytes += byteCount;
2949
+ this.terminal.write(bytes, () => {
2950
+ this.unparsedBytes -= byteCount;
2951
+ onParsed?.();
2952
+ });
2953
+ }
2954
+ /**
2955
+ * Fed and not yet parsed. xterm queues writes without limit, so a shell that skips its output
2956
+ * (slice T8) pauses on this, and on nothing else.
2957
+ */
2958
+ get backlogBytes() {
2959
+ return this.unparsedBytes;
2819
2960
  }
2820
2961
  resize(cols, rows) {
2821
2962
  if (!this.disposed) this.terminal.resize(cols, rows);
2822
2963
  }
2823
2964
  /**
2824
- * The screen after everything fed before this call, and nothing fed after it. Null when the
2825
- * mirror was disposed first.
2965
+ * The screen after everything fed before this call, and nothing fed after it, serialised under
2966
+ * `maxBytes`. Null when the mirror was disposed first, or when even the screen alone is over
2967
+ * {@link MAX_SNAPSHOT_BYTES}.
2826
2968
  *
2827
2969
  * xterm parses writes in batches, on a timer. An empty write queued now has its callback run
2828
2970
  * after every earlier chunk is parsed and before the next one is, so serialising inside it sees
2829
2971
  * exactly what was fed before this call.
2830
2972
  */
2831
- snapshot() {
2973
+ snapshot(maxBytes = MAX_SNAPSHOT_BYTES) {
2832
2974
  return new Promise((resolve) => {
2833
2975
  if (this.disposed) {
2834
2976
  resolve(null);
2835
2977
  return;
2836
2978
  }
2837
- this.terminal.write("", () => resolve(this.disposed ? null : this.serialise()));
2979
+ this.terminal.write("", () => resolve(this.disposed ? null : this.serialise(maxBytes)));
2838
2980
  });
2839
2981
  }
2840
2982
  dispose() {
@@ -2842,14 +2984,24 @@ var ScreenMirror = class _ScreenMirror {
2842
2984
  this.disposed = true;
2843
2985
  this.terminal.dispose();
2844
2986
  }
2845
- /** Null when even the screen alone is over the cap. The tab then waits out its fallback. */
2846
- serialise() {
2987
+ /**
2988
+ * Fewer lines of scrollback until the text fits `maxBytes`. A screen alone over a cap below
2989
+ * {@link MAX_SNAPSHOT_BYTES} is still sent under that: a resync over its cap beats a tab that never
2990
+ * catches up. Null when even the screen alone is over {@link MAX_SNAPSHOT_BYTES}.
2991
+ */
2992
+ serialise(maxBytes) {
2847
2993
  for (const scrollback of SCROLLBACK_LINES_TO_TRY) {
2848
2994
  const text = this.serializer.serialize({ scrollback });
2849
- if (Buffer.byteLength(text, "utf-8") <= MAX_SNAPSHOT_BYTES) {
2995
+ if (Buffer.byteLength(text, "utf-8") <= maxBytes) {
2850
2996
  return { text, cols: this.terminal.cols, rows: this.terminal.rows };
2851
2997
  }
2852
2998
  }
2999
+ if (maxBytes < MAX_SNAPSHOT_BYTES) {
3000
+ const screenOnly = this.serializer.serialize({ scrollback: 0 });
3001
+ if (Buffer.byteLength(screenOnly, "utf-8") <= MAX_SNAPSHOT_BYTES) {
3002
+ return { text: screenOnly, cols: this.terminal.cols, rows: this.terminal.rows };
3003
+ }
3004
+ }
2853
3005
  return null;
2854
3006
  }
2855
3007
  };
@@ -2862,16 +3014,31 @@ var DEFAULT_COLS = 80;
2862
3014
  var DEFAULT_ROWS = 24;
2863
3015
  var EXPIRY_CHECK_MILLIS = 5e3;
2864
3016
  var MILLIS_PER_SECOND = 1e3;
2865
- var TerminalHandler = class {
3017
+ var RESYNC_MIN_INTERVAL_MILLIS = 1e3;
3018
+ var MIRROR_HIGH_WATER_BYTES = 1024 * 1024;
3019
+ var MIRROR_LOW_WATER_BYTES = 256 * 1024;
3020
+ var ACTIVITY_REPORT_MILLIS = 6e4;
3021
+ var DEFAULT_SKIP_TUNING = {
3022
+ resyncMinIntervalMillis: RESYNC_MIN_INTERVAL_MILLIS,
3023
+ mirrorHighWaterBytes: MIRROR_HIGH_WATER_BYTES,
3024
+ mirrorLowWaterBytes: MIRROR_LOW_WATER_BYTES,
3025
+ activityReportMillis: ACTIVITY_REPORT_MILLIS
3026
+ };
3027
+ var TerminalHandler = class _TerminalHandler {
2866
3028
  constructor(dependencies) {
2867
3029
  this.dependencies = dependencies;
2868
3030
  this.enabled = true;
2869
3031
  this.suspended = false;
3032
+ /** `terminal_resync` in `welcome` (slice T8). Off, every shell keeps T2's brake. */
3033
+ this.resyncEnabled = false;
3034
+ /** Paused by `suspend` under T2's brake, so `resumeAll` resumes them if `welcome` turned skip mode on. */
3035
+ this.pausedBySuspend = /* @__PURE__ */ new Set();
2870
3036
  this.expiryTimer = null;
2871
3037
  this.contextTimer = null;
2872
3038
  this.contextPollInFlight = false;
2873
3039
  this.contextTracker = new ShellContextTracker();
2874
3040
  this.streams = /* @__PURE__ */ new Map();
3041
+ this.tuning = { ...DEFAULT_SKIP_TUNING, ...dependencies.skipTuning };
2875
3042
  }
2876
3043
  /**
2877
3044
  * From welcome. An older dashboard sends no terminal fields, and `terminal_enabled` and the
@@ -2881,7 +3048,7 @@ var TerminalHandler = class {
2881
3048
  * the field, and nobody notices until a node falls over, so an agent without one refuses to open
2882
3049
  * a terminal at all.
2883
3050
  */
2884
- configure(terminalEnabled, maxTerminalsPerDevice, terminalWindowBytes, maxFrameBytes, idleTimeoutSeconds, maxSessionSeconds) {
3051
+ configure(terminalEnabled, maxTerminalsPerDevice, terminalWindowBytes, maxFrameBytes, idleTimeoutSeconds, terminalResync) {
2885
3052
  if (terminalEnabled !== void 0) this.enabled = terminalEnabled;
2886
3053
  if (maxTerminalsPerDevice !== void 0) this.dependencies.registry.setMaxTerminals(maxTerminalsPerDevice);
2887
3054
  this.windowBytes = terminalWindowBytes;
@@ -2890,21 +3057,33 @@ var TerminalHandler = class {
2890
3057
  logger.info("Terminals unavailable: welcome carried no terminal_window_bytes");
2891
3058
  }
2892
3059
  this.idleTimeoutMillis = positiveMillis(idleTimeoutSeconds);
2893
- this.maxSessionMillis = positiveMillis(maxSessionSeconds);
3060
+ this.setSkipMode(terminalResync === true);
2894
3061
  this.startExpiryTimer();
2895
3062
  }
2896
3063
  /**
2897
- * Ends every shell past its idle timeout or its max-session cap. Runs on a timer; public so a test
2898
- * decides when. The cap goes first: a shell both idle and too old is closed for the rule typing
2899
- * cannot reset.
3064
+ * `welcome` turned skip mode on or off. Off, a skipping shell stops skipping without a resync, since
3065
+ * this dashboard cannot route one, and its tabs miss what was skipped. `resumeAll` then sets the reads.
2900
3066
  */
3067
+ setSkipMode(enabled) {
3068
+ if (enabled === this.resyncEnabled) return;
3069
+ this.resyncEnabled = enabled;
3070
+ for (const stream of this.streams.values()) {
3071
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
3072
+ stream.resyncTimer = null;
3073
+ stream.skipping = false;
3074
+ stream.skippedBytes = 0;
3075
+ stream.resyncOverflowed = false;
3076
+ stream.resyncHeldBundles.splice(0);
3077
+ stream.resyncHeldBytes = 0;
3078
+ stream.mirrorPaused = false;
3079
+ }
3080
+ }
3081
+ /** Ends every shell past its idle timeout. Runs on a timer; public so a test decides when. */
2901
3082
  expireShells() {
2902
3083
  if (this.suspended) return;
2903
3084
  const nowMillis = this.nowMillis();
2904
3085
  for (const [terminalId, stream] of [...this.streams.entries()]) {
2905
- if (this.maxSessionMillis !== void 0 && nowMillis - stream.openedAtMillis >= this.maxSessionMillis) {
2906
- this.expire(terminalId, CLOSE_REASON_MAX_SESSION);
2907
- } else if (this.idleTimeoutMillis !== void 0 && nowMillis - stream.lastActivityMillis >= this.idleTimeoutMillis) {
3086
+ if (this.idleTimeoutMillis !== void 0 && nowMillis - stream.lastActivityMillis >= this.idleTimeoutMillis) {
2908
3087
  this.expire(terminalId, CLOSE_REASON_IDLE_TIMEOUT);
2909
3088
  }
2910
3089
  }
@@ -2938,22 +3117,28 @@ var TerminalHandler = class {
2938
3117
  this.contextTracker.clear();
2939
3118
  this.suspended = false;
2940
3119
  for (const stream of this.streams.values()) {
3120
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
2941
3121
  stream.splitter.dispose();
2942
3122
  stream.mirror?.dispose();
2943
3123
  }
2944
3124
  this.streams.clear();
3125
+ this.pausedBySuspend.clear();
2945
3126
  this.dependencies.registry.killAll();
2946
3127
  }
2947
3128
  /**
2948
- * The socket dropped and the agent will redial. Every shell stops being read and keeps running.
2949
- * Whatever it prints waits in the kernel, and the shell blocks once that buffer is full.
3129
+ * The socket dropped and the agent will redial. Under T2's brake every shell stops being read and
3130
+ * keeps running: whatever it prints waits in the kernel, and the shell blocks once that buffer is
3131
+ * full. In skip mode (slice T8) a shell is read on, and its output is skipped.
2950
3132
  */
2951
3133
  suspend() {
2952
3134
  if (this.suspended) return;
2953
3135
  this.suspended = true;
2954
3136
  for (const [terminalId, session] of this.dependencies.registry.entries()) {
3137
+ const stream = this.streams.get(terminalId);
3138
+ if (stream && this.skipsOutput(stream)) continue;
2955
3139
  try {
2956
3140
  session.pause();
3141
+ this.pausedBySuspend.add(terminalId);
2957
3142
  } catch (err) {
2958
3143
  logger.warn("Terminal pause failed", { terminal_id: terminalId, error: errorName2(err) });
2959
3144
  }
@@ -2962,13 +3147,18 @@ var TerminalHandler = class {
2962
3147
  }
2963
3148
  /**
2964
3149
  * `welcome` arrived. Every shell the dashboard did not close is read again, except one whose
2965
- * window is still full. That one resumes on the `ack` that reopens it.
3150
+ * window is still full. That one resumes on the `ack` that reopens it. A shell in skip mode was
3151
+ * never paused, and resyncs instead (slice T8).
2966
3152
  */
2967
3153
  resumeAll() {
2968
3154
  if (!this.suspended) return;
2969
3155
  this.suspended = false;
2970
3156
  for (const [terminalId, session] of this.dependencies.registry.entries()) {
2971
3157
  const stream = this.streams.get(terminalId);
3158
+ if (stream && this.skipsOutput(stream)) {
3159
+ this.resumeSkipping(terminalId, stream, session);
3160
+ continue;
3161
+ }
2972
3162
  if (stream) {
2973
3163
  for (const chunk of stream.heldBundles.splice(0)) {
2974
3164
  this.sendData(terminalId, chunk);
@@ -2981,6 +3171,7 @@ var TerminalHandler = class {
2981
3171
  logger.warn("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
2982
3172
  }
2983
3173
  }
3174
+ this.pausedBySuspend.clear();
2984
3175
  for (const context of this.contextTracker.current()) {
2985
3176
  if (this.streams.has(context.terminal_id)) {
2986
3177
  this.dependencies.send(event(CHANNEL_TERMINAL, OP_CONTEXT, context));
@@ -3083,7 +3274,6 @@ var TerminalHandler = class {
3083
3274
  this.dependencies.send(response(envelope, OP_OPENED, opened));
3084
3275
  }
3085
3276
  startStream(terminalId, session, windowBytes, bundleBytes) {
3086
- const openedAtMillis = this.nowMillis();
3087
3277
  const stream = {
3088
3278
  session,
3089
3279
  window: new FlowWindow(windowBytes),
@@ -3092,8 +3282,17 @@ var TerminalHandler = class {
3092
3282
  paused: false,
3093
3283
  sentSeq: 0,
3094
3284
  heldBundles: [],
3095
- openedAtMillis,
3096
- lastActivityMillis: openedAtMillis
3285
+ lastActivityMillis: this.nowMillis(),
3286
+ skipping: false,
3287
+ skippedBytes: 0,
3288
+ lastResyncAtMillis: 0,
3289
+ resyncTimer: null,
3290
+ resyncInFlight: null,
3291
+ resyncHeldBundles: [],
3292
+ resyncHeldBytes: 0,
3293
+ resyncOverflowed: false,
3294
+ mirrorPaused: false,
3295
+ lastActivityReportMillis: 0
3097
3296
  };
3098
3297
  this.streams.set(terminalId, stream);
3099
3298
  this.startContextTimer();
@@ -3105,17 +3304,29 @@ var TerminalHandler = class {
3105
3304
  if (this.dependencies.registry.remove(terminalId) === void 0) return;
3106
3305
  stream.splitter.flush();
3107
3306
  stream.splitter.dispose();
3108
- this.forgetStream(terminalId);
3109
- logger.info("Terminal shell exited", { terminal_id: terminalId, exit_code: exitCode, signal });
3110
- const exit = signal ? { terminal_id: terminalId, exit_code: null, signal: signalName(signal) } : { terminal_id: terminalId, exit_code: exitCode, signal: null };
3111
- this.dependencies.send(event(CHANNEL_TERMINAL, OP_EXIT, exit));
3112
- this.dependencies.send(event(
3113
- CHANNEL_TERMINAL,
3114
- OP_CLOSE,
3115
- { terminal_id: terminalId, reason: CLOSE_REASON_USER_CLOSED }
3116
- ));
3307
+ void this.finishExit(terminalId, stream, exitCode, signal);
3117
3308
  });
3118
3309
  }
3310
+ /**
3311
+ * The shell exited on its own. A shell that skipped its last output sends its last screen first, at
3312
+ * once, so the tabs see how it ended (slice T8). Then `exit` and `close`. With nothing to resync this
3313
+ * runs to the end without yielding, as before.
3314
+ */
3315
+ async finishExit(terminalId, stream, exitCode, signal) {
3316
+ if (this.skipsOutput(stream)) {
3317
+ if (stream.resyncInFlight) await stream.resyncInFlight;
3318
+ if (stream.skipping && !this.suspended) await this.resync(terminalId, stream);
3319
+ }
3320
+ this.forgetStream(terminalId);
3321
+ logger.info("Terminal shell exited", { terminal_id: terminalId, exit_code: exitCode, signal });
3322
+ const exit = signal ? { terminal_id: terminalId, exit_code: null, signal: signalName(signal) } : { terminal_id: terminalId, exit_code: exitCode, signal: null };
3323
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_EXIT, exit));
3324
+ this.dependencies.send(event(
3325
+ CHANNEL_TERMINAL,
3326
+ OP_CLOSE,
3327
+ { terminal_id: terminalId, reason: CLOSE_REASON_USER_CLOSED }
3328
+ ));
3329
+ }
3119
3330
  /**
3120
3331
  * 1 bundle leaves, and the window narrows by what it carried.
3121
3332
  *
@@ -3129,10 +3340,16 @@ var TerminalHandler = class {
3129
3340
  * The mirror is fed here, in the same tick as the seq, and nowhere else. A snapshot then holds
3130
3341
  * exactly the bundles up to its `after_seq`. Fed when the pty is read, a bundle still being cut
3131
3342
  * would be in the screen and drawn a second time when it is sent.
3343
+ *
3344
+ * In skip mode (slice T8) `sendOrSkip` decides instead, and never pauses the pty.
3132
3345
  */
3133
3346
  sendData(terminalId, chunk) {
3134
3347
  const stream = this.streams.get(terminalId);
3135
3348
  if (!stream) return;
3349
+ if (this.skipsOutput(stream)) {
3350
+ this.sendOrSkip(terminalId, stream, chunk);
3351
+ return;
3352
+ }
3136
3353
  if (this.suspended) {
3137
3354
  stream.heldBundles.push(chunk);
3138
3355
  return;
@@ -3148,12 +3365,215 @@ var TerminalHandler = class {
3148
3365
  logger.debug("Terminal window full, reads paused", { terminal_id: terminalId });
3149
3366
  }
3150
3367
  }
3368
+ /** Skip mode applies: `welcome` asked for it, and the shell has a screen to resync with. */
3369
+ skipsOutput(stream) {
3370
+ return this.resyncEnabled && stream.mirror !== null;
3371
+ }
3372
+ /**
3373
+ * Skip mode (slice T8). A resync being serialised holds the bundle. A skipping stream, a socket that is
3374
+ * down, or a closed window skips it. Otherwise it goes out as `data`.
3375
+ */
3376
+ sendOrSkip(terminalId, stream, chunk) {
3377
+ if (stream.resyncInFlight) {
3378
+ this.holdDuringResync(terminalId, stream, chunk);
3379
+ } else if (stream.skipping || this.suspended || !stream.window.isOpen()) {
3380
+ this.skip(terminalId, stream, chunk);
3381
+ } else {
3382
+ this.transmit(terminalId, stream, chunk);
3383
+ }
3384
+ }
3385
+ /**
3386
+ * A bundle cut while a resync is serialised is not in its screen, so it waits and goes out after the
3387
+ * parts. Past the window size the held bundles are skipped instead, and the stream stays skipping.
3388
+ */
3389
+ holdDuringResync(terminalId, stream, chunk) {
3390
+ if (!stream.resyncOverflowed && stream.resyncHeldBytes + chunk.length <= (this.windowBytes ?? 0)) {
3391
+ stream.resyncHeldBundles.push(chunk);
3392
+ stream.resyncHeldBytes += chunk.length;
3393
+ return;
3394
+ }
3395
+ if (!stream.resyncOverflowed) {
3396
+ stream.resyncOverflowed = true;
3397
+ this.skipHeldDuringResync(terminalId, stream);
3398
+ }
3399
+ this.skip(terminalId, stream, chunk);
3400
+ }
3401
+ skipHeldDuringResync(terminalId, stream) {
3402
+ const held = stream.resyncHeldBundles.splice(0);
3403
+ stream.resyncHeldBytes = 0;
3404
+ for (const chunk of held) {
3405
+ this.skip(terminalId, stream, chunk);
3406
+ }
3407
+ }
3408
+ /** Into the screen, not onto the wire. It takes no seq, and the window never counts it. */
3409
+ skip(terminalId, stream, chunk) {
3410
+ stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
3411
+ stream.skippedBytes += chunk.length;
3412
+ if (!stream.skipping) {
3413
+ stream.skipping = true;
3414
+ logger.debug("Terminal output skipped until the tabs catch up", { terminal_id: terminalId });
3415
+ }
3416
+ this.brakeIfMirrorBehind(terminalId, stream);
3417
+ this.reportActivityWhileSkipping(terminalId, stream);
3418
+ }
3419
+ /** As T2's send, minus the pause: with the window closed, the next bundle is skipped instead. */
3420
+ transmit(terminalId, stream, chunk) {
3421
+ stream.sentSeq += 1;
3422
+ stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
3423
+ const data = { terminal_id: terminalId, data: chunk.toString("base64") };
3424
+ this.dependencies.send({ ...event(CHANNEL_TERMINAL, OP_DATA, data), seq: stream.sentSeq });
3425
+ stream.window.recordSent(chunk.length);
3426
+ this.brakeIfMirrorBehind(terminalId, stream);
3427
+ }
3428
+ /** The one pause in skip mode: the mirror's parser fell behind. Local CPU, never the network. */
3429
+ brakeIfMirrorBehind(terminalId, stream) {
3430
+ if (stream.mirrorPaused || !stream.mirror || stream.mirror.backlogBytes <= this.tuning.mirrorHighWaterBytes) return;
3431
+ stream.mirrorPaused = true;
3432
+ stream.session.pause();
3433
+ logger.debug("Terminal reads paused until the screen catches up", { terminal_id: terminalId });
3434
+ }
3435
+ mirrorParsed(terminalId, stream) {
3436
+ if (!stream.mirrorPaused || !stream.mirror || stream.mirror.backlogBytes > this.tuning.mirrorLowWaterBytes) return;
3437
+ stream.mirrorPaused = false;
3438
+ if (this.streams.get(terminalId) !== stream) return;
3439
+ try {
3440
+ stream.session.resume();
3441
+ } catch (err) {
3442
+ logger.debug("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
3443
+ }
3444
+ }
3445
+ /**
3446
+ * Skipped output never reaches the dashboard, so its sweep would see an idle shell. At most every
3447
+ * `ACTIVITY_REPORT_MILLIS` it hears that this one is busy.
3448
+ */
3449
+ reportActivityWhileSkipping(terminalId, stream) {
3450
+ if (this.suspended) return;
3451
+ const nowMillis = this.nowMillis();
3452
+ if (nowMillis - stream.lastActivityReportMillis < this.tuning.activityReportMillis) return;
3453
+ stream.lastActivityReportMillis = nowMillis;
3454
+ const activity = { terminal_id: terminalId, skipped_bytes: stream.skippedBytes };
3455
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_ACTIVITY, activity));
3456
+ }
3457
+ /**
3458
+ * Skip mode after `welcome`. A shell that skipped, or had bytes in flight, resyncs at once: frames in
3459
+ * flight died with the old socket, and the tab's ack of the resync's `after_bytes` stands in for theirs.
3460
+ */
3461
+ resumeSkipping(terminalId, stream, session) {
3462
+ stream.paused = false;
3463
+ for (const chunk of stream.heldBundles.splice(0)) {
3464
+ this.skip(terminalId, stream, chunk);
3465
+ }
3466
+ if (this.pausedBySuspend.has(terminalId) && !stream.mirrorPaused) {
3467
+ try {
3468
+ session.resume();
3469
+ } catch (err) {
3470
+ logger.warn("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
3471
+ }
3472
+ }
3473
+ if (stream.skipping || stream.window.sent > stream.window.acked) {
3474
+ void this.resync(terminalId, stream);
3475
+ }
3476
+ }
3477
+ /** Every sent byte is acked: the tabs have drawn everything they were sent. */
3478
+ static isDrained(stream) {
3479
+ return stream.window.acked >= stream.window.sent;
3480
+ }
3481
+ /**
3482
+ * A skipping stream resyncs once its window has drained, and no sooner than the interval after the
3483
+ * last resync. Not drained yet, it waits for the next `ack`.
3484
+ */
3485
+ scheduleResync(terminalId, stream) {
3486
+ if (!stream.skipping || stream.resyncInFlight || stream.resyncTimer || this.suspended || !_TerminalHandler.isDrained(stream)) return;
3487
+ const waitMillis = stream.lastResyncAtMillis + this.tuning.resyncMinIntervalMillis - this.nowMillis();
3488
+ if (waitMillis <= 0) {
3489
+ void this.resync(terminalId, stream);
3490
+ return;
3491
+ }
3492
+ stream.resyncTimer = setTimeout(() => {
3493
+ stream.resyncTimer = null;
3494
+ if (this.streams.get(terminalId) === stream) this.scheduleResync(terminalId, stream);
3495
+ }, waitMillis);
3496
+ stream.resyncTimer.unref();
3497
+ }
3498
+ /** Starts a resync, or returns the one already being serialised. */
3499
+ resync(terminalId, stream) {
3500
+ if (stream.resyncInFlight) return stream.resyncInFlight;
3501
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
3502
+ stream.resyncTimer = null;
3503
+ stream.resyncInFlight = this.serialiseAndSendResync(terminalId, stream);
3504
+ return stream.resyncInFlight;
3505
+ }
3506
+ /**
3507
+ * The latest screen to every tab (slice T8). `after_seq` and `after_bytes` are read before the mirror
3508
+ * is asked, as for a snapshot, and skipped bytes took neither: the screen holds the output up to
3509
+ * `after_seq` plus everything skipped. Serialised under the window size, so a resync never puts more in
3510
+ * flight than the window allows. Bundles held meanwhile go out after the parts, from `after_seq + 1`.
3511
+ */
3512
+ async serialiseAndSendResync(terminalId, stream) {
3513
+ stream.lastResyncAtMillis = this.nowMillis();
3514
+ stream.resyncOverflowed = false;
3515
+ const afterSeq = stream.sentSeq;
3516
+ const afterBytes = stream.window.sent;
3517
+ const skippedBytes = stream.skippedBytes;
3518
+ stream.skippedBytes = 0;
3519
+ const screen = stream.mirror ? await stream.mirror.snapshot(this.windowBytes) : null;
3520
+ stream.resyncInFlight = null;
3521
+ if (this.streams.get(terminalId) !== stream) return;
3522
+ if (this.suspended) {
3523
+ stream.skippedBytes += skippedBytes;
3524
+ this.skipHeldDuringResync(terminalId, stream);
3525
+ stream.resyncOverflowed = false;
3526
+ return;
3527
+ }
3528
+ if (screen && this.bundleBytes !== void 0) {
3529
+ const resyncId = randomUUID2();
3530
+ const parts = splitIntoParts(Buffer.from(screen.text, "utf-8"), this.bundleBytes);
3531
+ parts.forEach((part, index) => {
3532
+ const payload = {
3533
+ terminal_id: terminalId,
3534
+ resync_id: resyncId,
3535
+ part: index,
3536
+ last: index === parts.length - 1,
3537
+ after_seq: afterSeq,
3538
+ after_bytes: afterBytes,
3539
+ skipped_bytes: skippedBytes,
3540
+ cols: screen.cols,
3541
+ rows: screen.rows,
3542
+ data: part.toString("base64")
3543
+ };
3544
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_RESYNC, payload));
3545
+ });
3546
+ logger.debug("Terminal resynced", {
3547
+ terminal_id: terminalId,
3548
+ parts: parts.length,
3549
+ after_seq: afterSeq,
3550
+ skipped_bytes: skippedBytes
3551
+ });
3552
+ } else {
3553
+ logger.warn("Terminal resync dropped: the screen is too large to send", { terminal_id: terminalId });
3554
+ }
3555
+ if (stream.resyncOverflowed) {
3556
+ stream.resyncOverflowed = false;
3557
+ this.scheduleResync(terminalId, stream);
3558
+ return;
3559
+ }
3560
+ stream.skipping = false;
3561
+ const held = stream.resyncHeldBundles.splice(0);
3562
+ stream.resyncHeldBytes = 0;
3563
+ for (const chunk of held) {
3564
+ this.sendOrSkip(terminalId, stream, chunk);
3565
+ }
3566
+ }
3151
3567
  acknowledge(envelope) {
3152
3568
  const parsed = TerminalAckSchema.safeParse(envelope.payload);
3153
3569
  if (!parsed.success) return;
3154
3570
  const stream = this.streams.get(parsed.data.terminal_id);
3155
3571
  if (!stream) return;
3156
3572
  stream.window.recordAck(parsed.data.ack_bytes);
3573
+ if (this.skipsOutput(stream)) {
3574
+ this.scheduleResync(parsed.data.terminal_id, stream);
3575
+ return;
3576
+ }
3157
3577
  if (stream.paused && stream.window.isOpen()) {
3158
3578
  stream.paused = false;
3159
3579
  if (this.suspended) return;
@@ -3281,7 +3701,9 @@ var TerminalHandler = class {
3281
3701
  }
3282
3702
  /** A shell is gone. The context poll stops with the last one, so an idle agent spawns nothing. */
3283
3703
  forgetStream(terminalId) {
3284
- this.streams.get(terminalId)?.mirror?.dispose();
3704
+ const stream = this.streams.get(terminalId);
3705
+ if (stream?.resyncTimer) clearTimeout(stream.resyncTimer);
3706
+ stream?.mirror?.dispose();
3285
3707
  this.streams.delete(terminalId);
3286
3708
  this.contextTracker.forget(terminalId);
3287
3709
  if (this.streams.size === 0) this.stopContextTimer();
@@ -3298,7 +3720,7 @@ var TerminalHandler = class {
3298
3720
  }
3299
3721
  }
3300
3722
  startExpiryTimer() {
3301
- if (this.expiryTimer || this.idleTimeoutMillis === void 0 && this.maxSessionMillis === void 0) {
3723
+ if (this.expiryTimer || this.idleTimeoutMillis === void 0) {
3302
3724
  return;
3303
3725
  }
3304
3726
  this.expiryTimer = setInterval(() => this.expireShells(), EXPIRY_CHECK_MILLIS);
@@ -3623,9 +4045,9 @@ function readShellEnvironment() {
3623
4045
  platform: process.platform,
3624
4046
  loginShell: process.env.SHELL,
3625
4047
  etcShells,
3626
- exists: (path6) => {
4048
+ exists: (path7) => {
3627
4049
  try {
3628
- return fs7.statSync(path6).isFile();
4050
+ return fs7.statSync(path7).isFile();
3629
4051
  } catch {
3630
4052
  return false;
3631
4053
  }
@@ -3657,6 +4079,104 @@ function resolveShell(requested, environment) {
3657
4079
  return firstUsable ? { shell: firstUsable } : { error: "No allowed shell exists on this machine." };
3658
4080
  }
3659
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
+
3660
4180
  // src/devices/deviceAgent.ts
3661
4181
  var CLOSE_CODE_REVOKED = 4001;
3662
4182
  var CLOSE_CODE_NORMAL = 1e3;
@@ -3668,14 +4188,17 @@ var AGENT_ERROR_UNAUTHORIZED = "unauthorized";
3668
4188
  var AGENT_ERROR_HANDSHAKE_REFUSED = "handshake_refused";
3669
4189
  var AGENT_ERROR_DISCONNECTED = "disconnected";
3670
4190
  var AGENT_ERROR_NOT_CONNECTED = "not_connected";
4191
+ var UNAUTHORIZED_STORED_TOKEN_MESSAGE = "The dashboard refused this machine's device token. The device was deleted, or its token was rotated. Sign this machine in again: pinggy device login";
4192
+ var UNAUTHORIZED_NEW_TOKEN_MESSAGE = "The dashboard refused this device token. Check the token, or copy the install command from the dashboard again.";
3671
4193
  var HANDSHAKE_TIMEOUT_MILLIS = 3e4;
3672
4194
  var PONG_GRACE_INTERVALS = 2;
3673
4195
  var BASE_CAPABILITIES = ["tunnel", "stats", "tunnel_control", "tunnel_update", "saved_config_update"];
3674
4196
  var CAPABILITY_TERMINAL = "terminal";
3675
4197
  var CAPABILITY_TERMINAL_SNAPSHOT = "terminal_snapshot";
4198
+ var CAPABILITY_TERMINAL_RESYNC = "terminal_resync";
3676
4199
  function buildCapabilities(terminalSupported, screenRestoreSupported = false) {
3677
4200
  if (!terminalSupported) return BASE_CAPABILITIES;
3678
- return screenRestoreSupported ? [...BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT] : [...BASE_CAPABILITIES, CAPABILITY_TERMINAL];
4201
+ return screenRestoreSupported ? [...BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC] : [...BASE_CAPABILITIES, CAPABILITY_TERMINAL];
3679
4202
  }
3680
4203
  function buildDeviceAgentWsUrl(manage) {
3681
4204
  let baseUrl = (manage || DEFAULT_SERVER).trim();
@@ -3730,9 +4253,7 @@ function startDeviceAgent(token, manage, options = {}) {
3730
4253
  const server = manage || DEFAULT_SERVER;
3731
4254
  const reporter = options.reporter ?? printingReporter;
3732
4255
  const stored = readDeviceIdentity();
3733
- if (stored?.device_agent_id && stored.token !== token) {
3734
- reporter.replacingDevice(stored.device_agent_id);
3735
- }
4256
+ const usesStoredToken = stored?.token === token;
3736
4257
  const connection = { send: null, close: null };
3737
4258
  const context = {
3738
4259
  wsUrl: buildDeviceAgentWsUrl(manage),
@@ -3752,7 +4273,9 @@ function startDeviceAgent(token, manage, options = {}) {
3752
4273
  reporter,
3753
4274
  writeIdentity: options.writeIdentity ?? writeDeviceIdentity,
3754
4275
  options,
3755
- state: { stopRequested: false, cancelPendingSleep: null, error: null, welcomed: false }
4276
+ state: { stopRequested: false, cancelPendingSleep: null, error: null, welcomed: false },
4277
+ usesStoredToken,
4278
+ replacedDeviceAgentId: usesStoredToken ? null : stored?.device_agent_id ?? null
3756
4279
  };
3757
4280
  const done = runLoop(context);
3758
4281
  return {
@@ -3767,14 +4290,20 @@ function startDeviceAgent(token, manage, options = {}) {
3767
4290
  }
3768
4291
  async function runDeviceAgent(token, manage, options = {}) {
3769
4292
  const run2 = startDeviceAgent(token, manage, options);
4293
+ const reporter = options.reporter ?? printingReporter;
3770
4294
  const sigintHandler = () => {
3771
4295
  void run2.stop();
3772
4296
  };
4297
+ const releaseRecord = recordForegroundAgent(() => {
4298
+ reporter.warn("Stopping: pinggy device remove ran in another terminal.");
4299
+ void run2.stop();
4300
+ });
3773
4301
  process.once("SIGINT", sigintHandler);
3774
4302
  try {
3775
4303
  await run2.done;
3776
4304
  } finally {
3777
4305
  process.removeListener("SIGINT", sigintHandler);
4306
+ releaseRecord();
3778
4307
  }
3779
4308
  }
3780
4309
  async function runLoop(context) {
@@ -3909,7 +4438,7 @@ function connectOnce(context) {
3909
4438
  welcome.terminal_window_bytes,
3910
4439
  welcome.max_frame_bytes,
3911
4440
  welcome.terminal_idle_timeout_seconds,
3912
- welcome.terminal_max_session_seconds
4441
+ welcome.terminal_resync
3913
4442
  );
3914
4443
  terminalHandler.resumeAll();
3915
4444
  startHeartbeat(welcome.heartbeat_interval_seconds);
@@ -3949,10 +4478,10 @@ function connectOnce(context) {
3949
4478
  if (res.statusCode === 401) {
3950
4479
  finish(fail(context, {
3951
4480
  code: AGENT_ERROR_UNAUTHORIZED,
3952
- message: "Unauthorized. This device token is not valid. Re-enrol this machine with: pinggy device login"
4481
+ message: context.usesStoredToken ? UNAUTHORIZED_STORED_TOKEN_MESSAGE : UNAUTHORIZED_NEW_TOKEN_MESSAGE
3953
4482
  }));
3954
4483
  } else {
3955
- reporter.warn(`Unexpected HTTP ${res.statusCode}.`);
4484
+ reporter.warn(`The dashboard answered HTTP ${res.statusCode}.`);
3956
4485
  finish("retry");
3957
4486
  }
3958
4487
  ws.close();
@@ -3963,7 +4492,7 @@ function connectOnce(context) {
3963
4492
  });
3964
4493
  ws.on("error", (err) => {
3965
4494
  logger.warn("Device agent socket error", { error: err.message });
3966
- if (!state.stopRequested) {
4495
+ if (!state.stopRequested && !settled) {
3967
4496
  reporter.warn(err.message);
3968
4497
  }
3969
4498
  finish("retry");
@@ -3997,6 +4526,10 @@ function handleFrame(envelope, context, onWelcome) {
3997
4526
  identity.enrolled_at = identity.enrolled_at ?? (/* @__PURE__ */ new Date()).toISOString();
3998
4527
  context.writeIdentity(identity);
3999
4528
  context.state.welcomed = true;
4529
+ if (context.replacedDeviceAgentId) {
4530
+ reporter.replacingDevice(context.replacedDeviceAgentId);
4531
+ context.replacedDeviceAgentId = null;
4532
+ }
4000
4533
  reporter.connected(welcome.data);
4001
4534
  onWelcome(welcome.data);
4002
4535
  return "retry";
@@ -4035,6 +4568,7 @@ function describeDisconnect(reason) {
4035
4568
 
4036
4569
  // src/devices/login/deviceLogin.ts
4037
4570
  import os9 from "os";
4571
+ import pico4 from "picocolors";
4038
4572
 
4039
4573
  // src/devices/login/login_schema.ts
4040
4574
  import { z as z3 } from "zod";
@@ -4094,8 +4628,8 @@ var DeviceLoginApiError = class extends Error {
4094
4628
  var UNREADABLE_ANSWER = "invalid_answer";
4095
4629
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
4096
4630
  const baseUrl = buildDashboardHttpUrl(manage);
4097
- async function post(path6, body, schema) {
4098
- const response2 = await fetchImpl(`${baseUrl}/${path6}`, {
4631
+ async function post(path7, body, schema) {
4632
+ const response2 = await fetchImpl(`${baseUrl}/${path7}`, {
4099
4633
  method: "POST",
4100
4634
  headers: { "Content-Type": "application/json", Accept: "application/json" },
4101
4635
  body: JSON.stringify(body)
@@ -4142,20 +4676,22 @@ async function readJson(response2) {
4142
4676
  }
4143
4677
 
4144
4678
  // src/devices/login/prompts.ts
4679
+ import pico3 from "picocolors";
4145
4680
  import { createInterface } from "readline/promises";
4146
4681
  import { Writable } from "stream";
4682
+ var QUESTION_MARKER = pico3.cyan(pico3.bold("\u2192"));
4147
4683
  function createTerminalPrompter(input, output) {
4148
4684
  return {
4149
4685
  async ask(question, signal) {
4150
4686
  const readline = createInterface({ input, output, terminal: true });
4151
4687
  try {
4152
- return await readline.question(question, signal ? { signal } : {});
4688
+ return await readline.question(marked(question), signal ? { signal } : {});
4153
4689
  } finally {
4154
4690
  readline.close();
4155
4691
  }
4156
4692
  },
4157
4693
  async askHidden(question, signal) {
4158
- output.write(question);
4694
+ output.write(marked(question));
4159
4695
  const readline = createInterface({ input, output: discardingOutput(), terminal: true });
4160
4696
  try {
4161
4697
  const answer = await readline.question("", signal ? { signal } : {});
@@ -4171,6 +4707,9 @@ var terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
4171
4707
  function isInteractiveTerminal() {
4172
4708
  return process.stdin.isTTY === true;
4173
4709
  }
4710
+ function marked(question) {
4711
+ return `${QUESTION_MARKER} ${question}`;
4712
+ }
4174
4713
  function discardingOutput() {
4175
4714
  return new Writable({
4176
4715
  write(_chunk, _encoding, callback) {
@@ -4184,10 +4723,12 @@ var EXIT_OK = 0;
4184
4723
  var EXIT_FAILED = 1;
4185
4724
  var DEFAULT_SERVER2 = "dashboard.pinggy.io";
4186
4725
  var YES_ANSWER = /^y(es)?$/i;
4726
+ var RESULT_MARKER = pico4.green(pico4.bold("\u2192"));
4187
4727
  var SECONDS_PER_MINUTE = 60;
4188
4728
  var MILLIS_PER_SECOND2 = 1e3;
4189
4729
  var FIRST_SERVER_ERROR_STATUS = 500;
4190
4730
  var NO_TERMINAL_MESSAGE = "pinggy device login needs a terminal to type the email and the code. On a machine without one, add the device in the dashboard and run: pinggy device connect --token <TOKEN>";
4731
+ var ABORT_ERROR_NAME = "AbortError";
4191
4732
  function machineDeviceLoginDependencies() {
4192
4733
  return {
4193
4734
  createApi: (manage) => createDeviceLoginApi(manage),
@@ -4209,6 +4750,20 @@ function machineDeviceLoginDependencies() {
4209
4750
  };
4210
4751
  }
4211
4752
  async function runDeviceLogin(options, dependencies = machineDeviceLoginDependencies()) {
4753
+ try {
4754
+ return await signInAndRunAgent(options, dependencies);
4755
+ } catch (err) {
4756
+ if (!isCtrlCAtPrompt(err)) {
4757
+ throw err;
4758
+ }
4759
+ dependencies.print(pico4.yellow("Sign-in cancelled."));
4760
+ return EXIT_FAILED;
4761
+ }
4762
+ }
4763
+ function isCtrlCAtPrompt(err) {
4764
+ return err instanceof Error && err.name === ABORT_ERROR_NAME;
4765
+ }
4766
+ async function signInAndRunAgent(options, dependencies) {
4212
4767
  if (!dependencies.isInteractive()) {
4213
4768
  dependencies.printError(NO_TERMINAL_MESSAGE);
4214
4769
  return EXIT_FAILED;
@@ -4220,7 +4775,7 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
4220
4775
  `This machine is already enrolled as ${stored.device_agent_id ?? "a device"} on ${stored.server}. Add it again as a new device? [y/N] `
4221
4776
  );
4222
4777
  if (!YES_ANSWER.test(answer.trim())) {
4223
- return await dependencies.runAgent(stored.token, manage) ?? EXIT_OK;
4778
+ return await dependencies.runAgent(stored.token, manage, false) ?? EXIT_OK;
4224
4779
  }
4225
4780
  }
4226
4781
  const email = (await dependencies.prompter.ask("Email: ")).trim();
@@ -4239,13 +4794,12 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
4239
4794
  ...options.name ? { name: options.name } : {}
4240
4795
  });
4241
4796
  linkMinutes = Math.round(started.expires_in_seconds / SECONDS_PER_MINUTE);
4242
- dependencies.print(`We sent a 6-digit code to ${email}. It works for ${linkMinutes} minutes.`);
4243
- if (started.match_code) {
4244
- dependencies.print("Type it below, or click Approve sign-in in the email.");
4245
- dependencies.print(`If you use the email: approve only if the page shows ${started.match_code}. A different code is someone else's sign-in.`);
4246
- }
4797
+ printCodeSent(email, started.match_code, dependencies);
4247
4798
  approved = await waitForApproval(api, started.device_code, started.poll_interval_seconds, dependencies);
4248
4799
  } catch (err) {
4800
+ if (isCtrlCAtPrompt(err)) {
4801
+ throw err;
4802
+ }
4249
4803
  dependencies.printError(messageOf(err, manage));
4250
4804
  return EXIT_FAILED;
4251
4805
  }
@@ -4259,9 +4813,19 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
4259
4813
  server: manage || DEFAULT_SERVER2,
4260
4814
  enrolled_at: null
4261
4815
  });
4262
- dependencies.print(`Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
4816
+ dependencies.print(`${RESULT_MARKER} Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
4263
4817
  await printDeviceLink(approved, linkMinutes, dependencies);
4264
- return await dependencies.runAgent(approved.token, manage) ?? EXIT_OK;
4818
+ return await dependencies.runAgent(approved.token, manage, true) ?? EXIT_OK;
4819
+ }
4820
+ function printCodeSent(email, matchCode, dependencies) {
4821
+ dependencies.print("");
4822
+ if (matchCode) {
4823
+ dependencies.print(`Device Code: ${pico4.bold(pico4.yellow(matchCode))}`);
4824
+ dependencies.print("");
4825
+ }
4826
+ dependencies.print(`We have sent a 6-digit code to ${email}.`);
4827
+ dependencies.print(matchCode ? "Enter the code below or click the approve button in the email." : "Enter the code below.");
4828
+ dependencies.print("");
4265
4829
  }
4266
4830
  async function waitForApproval(api, deviceCode, pollIntervalSeconds, dependencies) {
4267
4831
  const controller = new AbortController();
@@ -4309,7 +4873,7 @@ async function typeTheCode(api, deviceCode, signal, prompt, dependencies) {
4309
4873
  }
4310
4874
  }
4311
4875
  if (answer.status === LoginStatus.Pending) {
4312
- dependencies.print("Approved from the email link. Waiting for the dashboard to finish.");
4876
+ dependencies.print(pico4.cyanBright("Approved from the email link. Waiting for the dashboard to finish..."));
4313
4877
  return waitUntilAborted(signal);
4314
4878
  }
4315
4879
  if (answer.status !== LoginStatus.Approved) {
@@ -4353,16 +4917,17 @@ async function pollUntilApproved(api, deviceCode, intervalMillis, signal, depend
4353
4917
  }
4354
4918
  async function printDeviceLink(approved, linkMinutes, dependencies) {
4355
4919
  let link;
4920
+ let label;
4356
4921
  if (approved.open_url) {
4357
4922
  link = approved.open_url;
4358
- dependencies.print(`Open the device in a browser. This link signs you in once, within ${linkMinutes} minutes:`);
4923
+ label = `Open the device in a browser. This link signs you in once, within ${linkMinutes} minutes:`;
4359
4924
  } else if (approved.device_url) {
4360
4925
  link = approved.device_url;
4361
- dependencies.print("Open the device in a browser:");
4926
+ label = "Open the device in a browser:";
4362
4927
  } else {
4363
4928
  return;
4364
4929
  }
4365
- dependencies.print(` ${link}`);
4930
+ printDeviceUrl((message) => dependencies.print(message), label, link);
4366
4931
  try {
4367
4932
  dependencies.print(await dependencies.renderQr(link));
4368
4933
  } catch {
@@ -4408,6 +4973,12 @@ function sleepUnlessAborted(millis, signal) {
4408
4973
  // src/devices/backgroundAgent.ts
4409
4974
  var POLL_INTERVAL_MILLIS = 500;
4410
4975
  var CONNECT_WAIT_MILLIS = 15e3;
4976
+ var MANAGE_COMMANDS = [
4977
+ ["pinggy device status", "Show this device, and whether its agent runs"],
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"]
4981
+ ];
4411
4982
  var verifyingReporter = {
4412
4983
  connecting: () => void 0,
4413
4984
  connected: () => void 0,
@@ -4420,7 +4991,10 @@ var verifyingReporter = {
4420
4991
  function machineBackgroundAgentDependencies() {
4421
4992
  return {
4422
4993
  readIdentity: readDeviceIdentity,
4994
+ readForegroundAgent,
4423
4995
  findDaemon: getDaemonInfo,
4996
+ hasSavedAgent: () => savedDeviceAgent() !== null,
4997
+ forgetSavedAgent: forgetDeviceAgent,
4424
4998
  ensureDaemon: ensureDaemonRunning,
4425
4999
  client: (port) => new IPCClient(port, "cli"),
4426
5000
  verify: (token, manage) => startDeviceAgent(token, manage, {
@@ -4461,7 +5035,7 @@ async function readBackgroundAgent(dependencies) {
4461
5035
  return null;
4462
5036
  }
4463
5037
  }
4464
- async function startAgentInBackground(target, dependencies) {
5038
+ async function startAgentInBackground(target, dependencies, options = {}) {
4465
5039
  if (differsFromStored(target, dependencies.readIdentity())) {
4466
5040
  const verified = await dependencies.verify(target.token, target.manage);
4467
5041
  if (verified.error || !verified.welcomed) {
@@ -4469,7 +5043,6 @@ async function startAgentInBackground(target, dependencies) {
4469
5043
  return EXIT_FAILED;
4470
5044
  }
4471
5045
  }
4472
- dependencies.print("Starting the device agent in the background.");
4473
5046
  let daemon;
4474
5047
  try {
4475
5048
  daemon = await dependencies.ensureDaemon();
@@ -4488,18 +5061,20 @@ async function startAgentInBackground(target, dependencies) {
4488
5061
  dependencies.printError(daemonFailureMessage(err, daemon));
4489
5062
  return EXIT_FAILED;
4490
5063
  }
4491
- return waitUntilConnected(client, daemon, dependencies);
5064
+ printManageCommands(dependencies);
5065
+ dependencies.print(pico5.cyanBright("Starting the device agent in the background..."));
5066
+ return waitUntilConnected(client, daemon, options, dependencies);
4492
5067
  }
4493
5068
  async function stopAgentInBackground(dependencies) {
4494
5069
  const reading = await readBackgroundAgent(dependencies);
4495
5070
  if (!reading || !isAgentRunning(reading.status)) {
4496
- dependencies.print("No device agent is running in the background.");
5071
+ dependencies.print(pico5.yellow("No device agent is running in the background."));
4497
5072
  return EXIT_OK;
4498
5073
  }
4499
5074
  if (!await stopReadAgent(reading, dependencies)) {
4500
5075
  return EXIT_FAILED;
4501
5076
  }
4502
- 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.");
4503
5078
  return EXIT_OK;
4504
5079
  }
4505
5080
  async function stopAgentBeforeRemove(dependencies) {
@@ -4567,7 +5142,16 @@ function daemonFailureMessage(err, daemon) {
4567
5142
  }
4568
5143
  return `Could not reach the daemon: ${errorMessage(err)}`;
4569
5144
  }
4570
- async function waitUntilConnected(client, daemon, dependencies) {
5145
+ function printManageCommands(dependencies) {
5146
+ const commandWidth = Math.max(...MANAGE_COMMANDS.map(([command]) => command.length));
5147
+ dependencies.print("");
5148
+ dependencies.print("Manage this device:");
5149
+ for (const [command, purpose] of MANAGE_COMMANDS) {
5150
+ dependencies.print(` ${pico5.cyan(command.padEnd(commandWidth))} ${purpose}`);
5151
+ }
5152
+ dependencies.print("");
5153
+ }
5154
+ async function waitUntilConnected(client, daemon, options, dependencies) {
4571
5155
  const deadline = dependencies.now() + CONNECT_WAIT_MILLIS;
4572
5156
  for (; ; ) {
4573
5157
  let status;
@@ -4578,7 +5162,7 @@ async function waitUntilConnected(client, daemon, dependencies) {
4578
5162
  return EXIT_FAILED;
4579
5163
  }
4580
5164
  if (status.state === DeviceAgentState.Connected) {
4581
- printRunning(status, daemon, dependencies);
5165
+ printRunning(status, daemon, options, dependencies);
4582
5166
  return EXIT_OK;
4583
5167
  }
4584
5168
  if (status.state === DeviceAgentState.Stopped) {
@@ -4592,20 +5176,18 @@ async function waitUntilConnected(client, daemon, dependencies) {
4592
5176
  await dependencies.sleep(POLL_INTERVAL_MILLIS);
4593
5177
  }
4594
5178
  }
4595
- function printRunning(status, daemon, dependencies) {
5179
+ function printRunning(status, daemon, options, dependencies) {
4596
5180
  dependencies.printSuccess(`Running in the background as device ${status.deviceAgentId}`);
4597
- if (status.email) {
5181
+ if (status.email && !options.signInShown) {
4598
5182
  dependencies.print(`Signed in as ${status.email}`);
4599
5183
  }
4600
- if (status.deviceUrl) {
4601
- dependencies.print("Open the device in a browser:");
4602
- dependencies.print(` ${status.deviceUrl}`);
5184
+ if (status.deviceUrl && !options.signInShown) {
5185
+ printDeviceUrl((message) => dependencies.print(message), "Open the device in a browser:", status.deviceUrl);
4603
5186
  }
4604
5187
  if (daemon.host === DaemonHost.APP) {
4605
- dependencies.print("It runs inside the Pinggy app, and stops when the app quits.");
5188
+ dependencies.print(pico5.gray("It runs inside the Pinggy app, and stops when the app quits."));
4606
5189
  }
4607
- dependencies.print(`Logs: ${dependencies.daemonLogPath()}`);
4608
- dependencies.print("Stop it with: pinggy device stop");
5190
+ dependencies.print(pico5.gray(`Logs: ${dependencies.daemonLogPath()}`));
4609
5191
  }
4610
5192
 
4611
5193
  // src/cli/subcommand/handlers/daemonCommandsHandler.ts
@@ -4629,7 +5211,7 @@ async function handleDaemon(args) {
4629
5211
  installService();
4630
5212
  return;
4631
5213
  case "service-uninstall":
4632
- uninstallService();
5214
+ await uninstallService();
4633
5215
  return;
4634
5216
  default:
4635
5217
  printer_default.error(`Unknown daemon command: "${verb}"`);
@@ -4644,17 +5226,17 @@ async function handleDaemonStart() {
4644
5226
  printer_default.error(ipcMismatchMessage(info));
4645
5227
  process.exit(1);
4646
5228
  }
4647
- printer_default.print(pico2.yellow(`Daemon already running (PID ${info.pid}, port ${info.port}). Use: pinggy daemon status for details.`));
5229
+ printer_default.print(pico6.yellow(`Daemon already running (PID ${info.pid}, port ${info.port}). Use: pinggy daemon status for details.`));
4648
5230
  return;
4649
5231
  }
4650
5232
  const autoConfigs = getAutoStartConfigs();
4651
5233
  if (autoConfigs.length > 0) {
4652
- printer_default.print(pico2.cyanBright(`Starting daemon with ${autoConfigs.length} auto-start tunnel(s):`));
5234
+ printer_default.print(pico6.cyanBright(`Starting daemon with ${autoConfigs.length} auto-start tunnel(s):`));
4653
5235
  for (const c of autoConfigs) {
4654
- printer_default.print(` ${pico2.bold(c.name)} (${c.configId.slice(0, 8)})`);
5236
+ printer_default.print(` ${pico6.bold(c.name)} (${c.configId.slice(0, 8)})`);
4655
5237
  }
4656
5238
  } else {
4657
- printer_default.print(pico2.cyanBright("Starting daemon..."));
5239
+ printer_default.print(pico6.cyanBright("Starting daemon..."));
4658
5240
  }
4659
5241
  try {
4660
5242
  const info2 = await startDaemon();
@@ -4666,7 +5248,7 @@ async function handleDaemonStart() {
4666
5248
  }
4667
5249
  async function handleDaemonStop() {
4668
5250
  if (!isDaemonRunning()) {
4669
- printer_default.print(pico2.yellow("No daemon is running."));
5251
+ printer_default.print(pico6.yellow("No daemon is running."));
4670
5252
  return;
4671
5253
  }
4672
5254
  const agent = await readBackgroundAgent(machineBackgroundAgentDependencies());
@@ -4677,7 +5259,7 @@ async function handleDaemonStop() {
4677
5259
  printer_default.print("The background device agent stopped too. The device shows offline in the dashboard.");
4678
5260
  }
4679
5261
  } else if (result.reason === DaemonHost.APP) {
4680
- printer_default.print(pico2.yellow("The Pinggy daemon is running inside the Pinggy desktop app. Please quit the Pinggy app to stop it."));
5262
+ printer_default.print(pico6.yellow("The Pinggy daemon is running inside the Pinggy desktop app. Please quit the Pinggy app to stop it."));
4681
5263
  } else {
4682
5264
  printer_default.error(result.error);
4683
5265
  }
@@ -4685,7 +5267,7 @@ async function handleDaemonStop() {
4685
5267
  async function handleDaemonStatus() {
4686
5268
  const info = getDaemonInfo();
4687
5269
  if (!info) {
4688
- printer_default.print(pico2.yellow("No daemon is running. Start with: pinggy daemon start"));
5270
+ printer_default.print(pico6.yellow("No daemon is running. Start with: pinggy daemon start"));
4689
5271
  return;
4690
5272
  }
4691
5273
  const uptimeSec = Math.floor((Date.now() - new Date(info.startedAt).getTime()) / 1e3);
@@ -4693,7 +5275,7 @@ async function handleDaemonStatus() {
4693
5275
  const m = Math.floor(uptimeSec % 3600 / 60);
4694
5276
  const s = uptimeSec % 60;
4695
5277
  const uptimeStr = h > 0 ? `${h}h ${m}m ${s}s` : m > 0 ? `${m}m ${s}s` : `${s}s`;
4696
- printer_default.print(pico2.cyanBright("Daemon Status"));
5278
+ printer_default.print(pico6.cyanBright("Daemon Status"));
4697
5279
  printer_default.print(` PID: ${info.pid}`);
4698
5280
  printer_default.print(` Port: ${info.port}`);
4699
5281
  printer_default.print(` Started: ${info.startedAt}`);
@@ -4701,7 +5283,7 @@ async function handleDaemonStatus() {
4701
5283
  printer_default.print(` Host: ${info.host === DaemonHost.APP ? "Pinggy app (in-process)" : "standalone (CLI)"}`);
4702
5284
  printer_default.print(` IPC: v${daemonIpcVersion(info)}`);
4703
5285
  if (!isIpcCompatible(info)) {
4704
- printer_default.print(pico2.yellow(` Warning: ${ipcMismatchMessage(info)}`));
5286
+ printer_default.print(pico6.yellow(` Warning: ${ipcMismatchMessage(info)}`));
4705
5287
  }
4706
5288
  const agent = await readBackgroundAgent(machineBackgroundAgentDependencies());
4707
5289
  if (agent) {
@@ -4710,11 +5292,14 @@ async function handleDaemonStatus() {
4710
5292
  }
4711
5293
 
4712
5294
  // src/cli/subcommand/handlers/psCommand.ts
4713
- import pico3 from "picocolors";
5295
+ import pico7 from "picocolors";
4714
5296
  async function handlePs() {
4715
5297
  const client = new TunnelClient();
4716
5298
  try {
4717
- await client.ensureDaemon();
5299
+ if (!client.connectIfRunning()) {
5300
+ printer_default.print("No active tunnels. The daemon is not running.");
5301
+ return;
5302
+ }
4718
5303
  } catch (err) {
4719
5304
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
4720
5305
  return;
@@ -4726,21 +5311,21 @@ async function handlePs() {
4726
5311
  return;
4727
5312
  }
4728
5313
  if (tunnels.length === 0) {
4729
- printer_default.print("No tunnels running.");
5314
+ printer_default.print("No active tunnels.");
4730
5315
  return;
4731
5316
  }
4732
5317
  const header = `${pad("ID", 14)} ${pad("NAME", 16)} ${pad("STATUS", 10)} ${pad("LOCAL", 20)} URL`;
4733
- printer_default.print(pico3.gray(header));
4734
- printer_default.print(pico3.gray("\u2500".repeat(90)));
5318
+ printer_default.print(pico7.gray(header));
5319
+ printer_default.print(pico7.gray("\u2500".repeat(90)));
4735
5320
  for (const t of tunnels) {
4736
5321
  const id = t.tunnelid.slice(0, 12);
4737
5322
  const name = t.tunnelconfig?.name || "-";
4738
5323
  const status = t.status.state;
4739
5324
  const local = getLocalAddress(t.tunnelconfig);
4740
5325
  const url = t.remoteurls?.[0] || "-";
4741
- const statusColor = status === "running" ? pico3.green : status === "starting" ? pico3.yellow : pico3.red;
5326
+ const statusColor = status === "running" ? pico7.green : status === "starting" ? pico7.yellow : pico7.red;
4742
5327
  printer_default.print(
4743
- `${pico3.cyan(pad(id, 14))} ${pad(name, 16)} ${statusColor(pad(status, 10))} ${pad(local, 20)} ${pico3.magentaBright(url)}`
5328
+ `${pico7.cyan(pad(id, 14))} ${pad(name, 16)} ${statusColor(pad(status, 10))} ${pad(local, 20)} ${pico7.magentaBright(url)}`
4744
5329
  );
4745
5330
  }
4746
5331
  } catch (err) {
@@ -4761,7 +5346,10 @@ async function handleStop(args) {
4761
5346
  }
4762
5347
  const client = new TunnelClient();
4763
5348
  try {
4764
- await client.ensureDaemon();
5349
+ if (!client.connectIfRunning()) {
5350
+ printer_default.print("Nothing to stop. No tunnels are running.");
5351
+ return;
5352
+ }
4765
5353
  } catch (err) {
4766
5354
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
4767
5355
  return;
@@ -4812,7 +5400,21 @@ function resolveTargets(tunnels, args) {
4812
5400
  }
4813
5401
 
4814
5402
  // src/cli/subcommand/handlers/attachCommand.ts
4815
- import pico4 from "picocolors";
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
4816
5418
  async function handleAttach(args) {
4817
5419
  if (args.length === 0) {
4818
5420
  printer_default.error("Usage: pinggy attach <name|id>");
@@ -4821,7 +5423,10 @@ async function handleAttach(args) {
4821
5423
  const nameOrId = args[0];
4822
5424
  const client = new TunnelClient();
4823
5425
  try {
4824
- await client.ensureDaemon();
5426
+ if (!client.connectIfRunning()) {
5427
+ printer_default.error(tunnelNotRunningMessage(nameOrId));
5428
+ return;
5429
+ }
4825
5430
  } catch (err) {
4826
5431
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
4827
5432
  return;
@@ -4840,14 +5445,14 @@ async function handleAttach(args) {
4840
5445
  }
4841
5446
  const tunnelId = match.tunnelid;
4842
5447
  const name = match.tunnelconfig?.name || tunnelId.slice(0, 12);
4843
- printer_default.print(pico4.cyanBright(`Attaching to tunnel "${name}"...`));
5448
+ printer_default.print(pico8.cyanBright(`Attaching to tunnel "${name}"...`));
4844
5449
  const attachMode = match.mode ?? "detached";
4845
5450
  await client.attach(tunnelId, attachMode);
4846
5451
  const urls = match.remoteurls || [];
4847
5452
  if (urls.length > 0) {
4848
5453
  printer_default.print("");
4849
5454
  for (const url of urls) {
4850
- printer_default.print(" " + pico4.magentaBright(url));
5455
+ printer_default.print(" " + pico8.magentaBright(url));
4851
5456
  }
4852
5457
  printer_default.print("");
4853
5458
  }
@@ -4868,12 +5473,86 @@ async function handleAttach(args) {
4868
5473
  }
4869
5474
 
4870
5475
  // src/cli/subcommand/handlers/logsCommand.ts
4871
- 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
4872
5551
  async function handleLogs(args, follow) {
4873
5552
  const arg = args.find((a) => !a.startsWith("-"));
4874
- const client = new TunnelClient();
5553
+ let client;
4875
5554
  try {
4876
- await client.ensureDaemon();
5555
+ client = openLogLookup();
4877
5556
  } catch (err) {
4878
5557
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
4879
5558
  return;
@@ -4881,7 +5560,7 @@ async function handleLogs(args, follow) {
4881
5560
  let filePath;
4882
5561
  try {
4883
5562
  if (arg) {
4884
- const result = await client.resolveLogPath(arg);
5563
+ const result = await client.resolve(arg);
4885
5564
  if (result.status === "config-only") {
4886
5565
  printer_default.error(`Tunnel "${arg}" is saved but has not been started yet. No logs available.`);
4887
5566
  client.close();
@@ -4899,8 +5578,7 @@ async function handleLogs(args, follow) {
4899
5578
  }
4900
5579
  filePath = result.path;
4901
5580
  } else {
4902
- const paths = await client.getLogPaths();
4903
- filePath = paths.daemon;
5581
+ filePath = await client.daemonLogPath();
4904
5582
  }
4905
5583
  } catch (err) {
4906
5584
  printer_default.error(`Failed to resolve log path: ${errorMessage(err)}`);
@@ -4908,7 +5586,7 @@ async function handleLogs(args, follow) {
4908
5586
  return;
4909
5587
  }
4910
5588
  client.close();
4911
- if (!filePath || !fs8.existsSync(filePath)) {
5589
+ if (!filePath || !fs10.existsSync(filePath)) {
4912
5590
  printer_default.error(`Log file not found: ${filePath}`);
4913
5591
  process.exit(1);
4914
5592
  }
@@ -4919,18 +5597,18 @@ async function handleLogs(args, follow) {
4919
5597
  }
4920
5598
  }
4921
5599
  function printTail(filePath, lines) {
4922
- const content = fs8.readFileSync(filePath, "utf-8");
5600
+ const content = fs10.readFileSync(filePath, "utf-8");
4923
5601
  const allLines = content.split("\n");
4924
5602
  const tail = allLines.slice(-lines).join("\n");
4925
5603
  process.stdout.write(tail);
4926
5604
  if (!tail.endsWith("\n")) process.stdout.write("\n");
4927
5605
  }
4928
5606
  async function followFile(filePath) {
4929
- if (fs8.existsSync(filePath)) printTail(filePath, 20);
4930
- 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;
4931
5609
  let watcher = null;
4932
5610
  const openStream = () => {
4933
- const stream = fs8.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
5611
+ const stream = fs10.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
4934
5612
  stream.on("data", (chunk) => {
4935
5613
  process.stdout.write(chunk);
4936
5614
  fileSize += Buffer.byteLength(chunk, "utf-8");
@@ -4938,9 +5616,9 @@ async function followFile(filePath) {
4938
5616
  stream.on("error", () => {
4939
5617
  });
4940
5618
  };
4941
- watcher = fs8.watch(filePath, { persistent: true }, (event2) => {
5619
+ watcher = fs10.watch(filePath, { persistent: true }, (event2) => {
4942
5620
  if (event2 === "change") {
4943
- const stat = fs8.existsSync(filePath) ? fs8.statSync(filePath) : null;
5621
+ const stat = fs10.existsSync(filePath) ? fs10.statSync(filePath) : null;
4944
5622
  if (!stat || stat.size < fileSize) {
4945
5623
  fileSize = 0;
4946
5624
  }
@@ -4976,26 +5654,39 @@ async function handleLog(args) {
4976
5654
  printLogHelp();
4977
5655
  }
4978
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
+ }
4979
5673
  async function handleLogLevel(args) {
5674
+ const level = args.length > 0 ? parseLevel(args[0]) : void 0;
4980
5675
  const client = new TunnelClient();
4981
5676
  try {
4982
- await client.ensureDaemon();
5677
+ if (!client.connectIfRunning()) {
5678
+ handleLogLevelWithoutDaemon(level);
5679
+ return;
5680
+ }
4983
5681
  } catch (err) {
4984
5682
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
4985
5683
  return;
4986
5684
  }
4987
5685
  try {
4988
- if (args.length === 0) {
4989
- const level2 = await client.getLogLevel();
4990
- printer_default.print(`Log level: ${level2}`);
5686
+ if (!level) {
5687
+ printer_default.print(`Log level: ${await client.getLogLevel()}`);
4991
5688
  return;
4992
5689
  }
4993
- const level = args[0].toLowerCase();
4994
- if (!VALID_LEVELS.includes(level)) {
4995
- printer_default.error(`Invalid log level: "${level}". Must be one of: ${VALID_LEVELS.join(", ")}`);
4996
- client.close();
4997
- process.exit(1);
4998
- }
4999
5690
  await client.setLogLevel(level);
5000
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.`);
5001
5692
  } catch (err) {
@@ -5005,21 +5696,20 @@ async function handleLogLevel(args) {
5005
5696
  }
5006
5697
  }
5007
5698
  async function handleLogPath(args) {
5008
- const client = new TunnelClient();
5699
+ let client;
5009
5700
  try {
5010
- await client.ensureDaemon();
5701
+ client = openLogLookup();
5011
5702
  } catch (err) {
5012
5703
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5013
5704
  return;
5014
5705
  }
5015
5706
  try {
5016
5707
  if (args.length === 0) {
5017
- const paths = await client.getLogPaths();
5018
- printer_default.print(paths.daemon);
5708
+ printer_default.print(await client.daemonLogPath());
5019
5709
  return;
5020
5710
  }
5021
5711
  const arg = args[0];
5022
- const result = await client.resolveLogPath(arg);
5712
+ const result = await client.resolve(arg);
5023
5713
  switch (result.status) {
5024
5714
  case "running":
5025
5715
  case "historical":
@@ -5052,7 +5742,10 @@ async function handleRestart(args) {
5052
5742
  const nameOrId = args[0];
5053
5743
  const client = new TunnelClient();
5054
5744
  try {
5055
- await client.ensureDaemon();
5745
+ if (!client.connectIfRunning()) {
5746
+ printer_default.error(tunnelNotRunningMessage(nameOrId));
5747
+ process.exit(1);
5748
+ }
5056
5749
  } catch (err) {
5057
5750
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
5058
5751
  return;
@@ -5083,7 +5776,89 @@ async function handleRestart(args) {
5083
5776
  }
5084
5777
 
5085
5778
  // src/cli/subcommand/handlers/deviceCommand.ts
5086
- import pico5 from "picocolors";
5779
+ import pico10 from "picocolors";
5780
+
5781
+ // src/devices/removeDevice.ts
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
5087
5862
  var DeviceVerb = {
5088
5863
  Login: "login",
5089
5864
  Connect: "connect",
@@ -5119,7 +5894,11 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
5119
5894
  const flagArgs = args.slice(1);
5120
5895
  const { values } = parseCliArgs(cliOptions, flagArgs);
5121
5896
  configureLogger(values);
5122
- const inBackground = Boolean(values.b);
5897
+ if (values.b && values.foreground) {
5898
+ printer_default.error("-b and --foreground contradict each other. The agent runs in the background unless --foreground is given.");
5899
+ process.exit(1);
5900
+ }
5901
+ const inBackground = !values.foreground;
5123
5902
  switch (verb) {
5124
5903
  case DeviceVerb.Login:
5125
5904
  exitUnlessOk(await handleDeviceLogin(values.manage, values.name, inBackground, background));
@@ -5140,7 +5919,10 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
5140
5919
  await handleDeviceStatus(background);
5141
5920
  return;
5142
5921
  case DeviceVerb.Remove:
5143
- exitUnlessOk(await handleDeviceRemove(background));
5922
+ exitUnlessOk(await runDeviceRemove(
5923
+ { skipConfirmation: Boolean(values.force) },
5924
+ machineDeviceRemoveDependencies(background)
5925
+ ));
5144
5926
  return;
5145
5927
  default:
5146
5928
  if (verb === "help" || verb === "--help" || verb === "-h") {
@@ -5166,7 +5948,15 @@ function devicesSpellingMessage(args) {
5166
5948
  return `"pinggy devices" is now "pinggy device". Run: pinggy device ${suggestion}`;
5167
5949
  }
5168
5950
  async function mayRunInForeground(background) {
5169
- 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());
5170
5960
  if (refusal) {
5171
5961
  printer_default.error(refusal);
5172
5962
  return false;
@@ -5178,9 +5968,10 @@ async function handleDeviceLogin(manage, name, inBackground, background) {
5178
5968
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
5179
5969
  return runDeviceLogin({ manage, name });
5180
5970
  }
5971
+ if (!mayRunInBackground(background)) return EXIT_FAILED;
5181
5972
  return runDeviceLogin({ manage, name }, {
5182
5973
  ...machineDeviceLoginDependencies(),
5183
- runAgent: (token, agentManage) => startAgentInBackground({ token, manage: agentManage }, background)
5974
+ runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
5184
5975
  });
5185
5976
  }
5186
5977
  async function handleDeviceConnect(flagToken, environmentToken, manage, inBackground, background) {
@@ -5190,6 +5981,7 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
5190
5981
  return EXIT_FAILED;
5191
5982
  }
5192
5983
  if (inBackground) {
5984
+ if (!mayRunInBackground(background)) return EXIT_FAILED;
5193
5985
  return startAgentInBackground(target, background);
5194
5986
  }
5195
5987
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
@@ -5199,26 +5991,19 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
5199
5991
  async function handleDeviceStatus(background) {
5200
5992
  const identity = background.readIdentity();
5201
5993
  if (!identity) {
5202
- printer_default.print("This machine is not enrolled. Run: pinggy device login");
5994
+ printer_default.print(pico10.yellow("This machine is not enrolled. Run: pinggy device login"));
5203
5995
  return;
5204
5996
  }
5205
- printer_default.print(` Device id ${identity.device_agent_id ?? pico5.gray("not yet assigned")}`);
5997
+ printer_default.print(` Device id ${identity.device_agent_id ?? pico10.gray("not yet assigned")}`);
5206
5998
  printer_default.print(` Server ${identity.server}`);
5207
5999
  printer_default.print(` Token ${maskToken(identity.token)}`);
5208
- printer_default.print(` Enrolled ${identity.enrolled_at ?? pico5.gray("never")}`);
5209
- await printBackgroundStatus(background);
5210
- }
5211
- async function handleDeviceRemove(background) {
5212
- if (!await stopAgentBeforeRemove(background)) {
5213
- return EXIT_FAILED;
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}`);
5214
6005
  }
5215
- if (clearDeviceIdentity()) {
5216
- printer_default.success("Local device credential removed.");
5217
- printer_default.print(pico5.gray("The device still exists in the dashboard. Delete it there to revoke it."));
5218
- } else {
5219
- printer_default.print("This machine is not enrolled.");
5220
- }
5221
- return EXIT_OK;
6006
+ await printBackgroundStatus(background);
5222
6007
  }
5223
6008
 
5224
6009
  // src/cli/subcommand/subcommands.ts
@@ -5489,12 +6274,12 @@ async function initRemoteManagementBackground(values) {
5489
6274
  }
5490
6275
 
5491
6276
  // src/daemon/lifecycle/daemonChild.ts
5492
- import fs11 from "fs";
6277
+ import fs14 from "fs";
5493
6278
 
5494
6279
  // src/daemon/ipc/ipcServer.ts
5495
6280
  import http from "http";
5496
- import fs10 from "fs";
5497
- import path5 from "path";
6281
+ import fs12 from "fs";
6282
+ import path6 from "path";
5498
6283
  import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
5499
6284
 
5500
6285
  // src/daemon/ws/wsProtocol.ts
@@ -5521,17 +6306,17 @@ function parseClientMessage(raw) {
5521
6306
  }
5522
6307
 
5523
6308
  // src/daemon/lifecycle/stateStore.ts
5524
- import fs9 from "fs";
5525
- import path4 from "path";
6309
+ import fs11 from "fs";
6310
+ import path5 from "path";
5526
6311
  var STATE_FILENAME = "daemon-state.json";
5527
6312
  function getStatePath() {
5528
- return path4.join(getPinggyConfigDir(), STATE_FILENAME);
6313
+ return path5.join(getPinggyConfigDir(), STATE_FILENAME);
5529
6314
  }
5530
6315
  function loadDaemonState() {
5531
6316
  const statePath = getStatePath();
5532
6317
  try {
5533
- if (!fs9.existsSync(statePath)) return null;
5534
- const raw = fs9.readFileSync(statePath, "utf-8");
6318
+ if (!fs11.existsSync(statePath)) return null;
6319
+ const raw = fs11.readFileSync(statePath, "utf-8");
5535
6320
  const state = JSON.parse(raw);
5536
6321
  if (!Array.isArray(state.tunnels)) return null;
5537
6322
  return state;
@@ -5545,8 +6330,8 @@ function persistDaemonState(state) {
5545
6330
  const tmpPath = statePath + ".tmp";
5546
6331
  try {
5547
6332
  state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
5548
- fs9.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
5549
- fs9.renameSync(tmpPath, statePath);
6333
+ fs11.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
6334
+ fs11.renameSync(tmpPath, statePath);
5550
6335
  } catch (err) {
5551
6336
  logger.error("Failed to persist daemon state", { error: errorMessage(err) });
5552
6337
  }
@@ -5554,8 +6339,8 @@ function persistDaemonState(state) {
5554
6339
  function clearDaemonState() {
5555
6340
  const statePath = getStatePath();
5556
6341
  try {
5557
- if (fs9.existsSync(statePath)) {
5558
- fs9.unlinkSync(statePath);
6342
+ if (fs11.existsSync(statePath)) {
6343
+ fs11.unlinkSync(statePath);
5559
6344
  }
5560
6345
  } catch {
5561
6346
  }
@@ -5569,33 +6354,16 @@ function removeTunnelFromState(state, tunnelId) {
5569
6354
  }
5570
6355
 
5571
6356
  // src/daemon/ipc/ipcServer.ts
5572
- var VALID_ORIGINS = ["app", "cli", "remote", "device"];
5573
6357
  function parseOrigin(req) {
5574
6358
  const raw = req.headers["x-pinggy-origin"];
5575
6359
  const v = Array.isArray(raw) ? raw[0] : raw;
5576
- return v && VALID_ORIGINS.includes(v) ? v : "cli";
6360
+ return v && TUNNEL_ORIGINS.includes(v) ? v : "cli";
5577
6361
  }
5578
6362
  function parseBody(method, body) {
5579
6363
  if (method === "GET") return void 0;
5580
6364
  if (!body) return {};
5581
6365
  return JSON.parse(body);
5582
6366
  }
5583
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5584
- function parseTunnelLogFilename(filename) {
5585
- const base = filename.replace(/\.log$/, "");
5586
- const parts = base.split("__");
5587
- if (parts.length < 2) return null;
5588
- const origin = parts[0];
5589
- if (!VALID_ORIGINS.includes(origin)) return null;
5590
- if (parts.length === 2) {
5591
- const second = parts[1];
5592
- if (UUID_RE.test(second)) return { origin, tunnelId: second };
5593
- return { origin, name: second };
5594
- }
5595
- const tunnelId = parts[parts.length - 1];
5596
- const name = parts.slice(1, -1).join("__");
5597
- return { origin, name, tunnelId };
5598
- }
5599
6367
  var IPCServer = class {
5600
6368
  constructor() {
5601
6369
  this.sessions = /* @__PURE__ */ new Map();
@@ -5731,8 +6499,8 @@ var IPCServer = class {
5731
6499
  const logDir = getTunnelLogDir();
5732
6500
  const daemonPath = getDaemonLogPath();
5733
6501
  const tunnels = [];
5734
- if (fs10.existsSync(logDir)) {
5735
- const files = fs10.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
6502
+ const files = listTunnelLogFiles();
6503
+ if (files.length > 0) {
5736
6504
  const manager = TunnelManager.getInstance();
5737
6505
  const activeIds = manager.getActiveTunnelIds();
5738
6506
  const activeNames = /* @__PURE__ */ new Set();
@@ -5742,8 +6510,8 @@ var IPCServer = class {
5742
6510
  if (n) activeNames.add(n);
5743
6511
  }
5744
6512
  for (const file of files) {
5745
- const filePath = path5.join(logDir, file);
5746
- const stat = fs10.statSync(filePath);
6513
+ const filePath = path6.join(logDir, file);
6514
+ const stat = fs12.statSync(filePath);
5747
6515
  const parsed = parseTunnelLogFilename(file);
5748
6516
  if (!parsed) continue;
5749
6517
  const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
@@ -5850,7 +6618,6 @@ var IPCServer = class {
5850
6618
  }
5851
6619
  async resolveLogPath(q) {
5852
6620
  if (!q) return { status: "not-found" };
5853
- const logDir = getTunnelLogDir();
5854
6621
  const manager = TunnelManager.getInstance();
5855
6622
  const activeIds = manager.getActiveTunnelIds();
5856
6623
  for (const t of await manager.getAllTunnels()) {
@@ -5862,32 +6629,7 @@ var IPCServer = class {
5862
6629
  return { status: "running", path: logPath, tunnelId: t.tunnelid, name, origin, running: true };
5863
6630
  }
5864
6631
  }
5865
- if (fs10.existsSync(logDir)) {
5866
- const files = fs10.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
5867
- const matches = [];
5868
- for (const file of files) {
5869
- const parsed = parseTunnelLogFilename(file);
5870
- if (!parsed) continue;
5871
- const nameMatch = parsed.name !== void 0 && parsed.name === q;
5872
- const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
5873
- if (nameMatch || idMatch) {
5874
- const filePath = path5.join(logDir, file);
5875
- const stat = fs10.statSync(filePath);
5876
- matches.push({ path: filePath, mtime: stat.mtimeMs, tunnelId: parsed.tunnelId, name: parsed.name, origin: parsed.origin });
5877
- }
5878
- }
5879
- if (matches.length > 0) {
5880
- matches.sort((a, b) => b.mtime - a.mtime);
5881
- const best = matches[0];
5882
- return { status: "historical", path: best.path, tunnelId: best.tunnelId, name: best.name, origin: best.origin, running: false };
5883
- }
5884
- }
5885
- const saved = listSavedConfigs();
5886
- const matchedConfig = saved.find((c) => c.name === q || c.configId === q || c.configId.startsWith(q));
5887
- if (matchedConfig) {
5888
- return { status: "config-only", name: matchedConfig.name, configId: matchedConfig.configId };
5889
- }
5890
- return { status: "not-found" };
6632
+ return resolveStoppedLogPath(q);
5891
6633
  }
5892
6634
  setupWebSocket() {
5893
6635
  this.server.on("upgrade", (req, socket, head) => {
@@ -6249,7 +6991,7 @@ var DeviceAgentHost = class {
6249
6991
  this.statusValue = stoppedStatus();
6250
6992
  /** Bumped on every start and stop. A run's reporter whose number is old belongs to a run that ended. */
6251
6993
  this.generation = 0;
6252
- /** 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. */
6253
6995
  this.closed = false;
6254
6996
  /** Start and stop chain on this, so 1 finishes before the next begins. */
6255
6997
  this.queue = Promise.resolve();
@@ -6287,8 +7029,8 @@ var DeviceAgentHost = class {
6287
7029
  });
6288
7030
  }
6289
7031
  /**
6290
- * The daemon is shutting down. Stops the run at once, outside the queue, and writes nothing to
6291
- * 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.
6292
7034
  */
6293
7035
  close() {
6294
7036
  this.closed = true;
@@ -6331,9 +7073,6 @@ var DeviceAgentHost = class {
6331
7073
  this.current = null;
6332
7074
  this.generation += 1;
6333
7075
  this.statusValue = { ...this.statusValue, state: DeviceAgentState.Stopped, connectedAt: null };
6334
- if (!this.closed) {
6335
- this.dependencies.recordStopped();
6336
- }
6337
7076
  await current.run.stop();
6338
7077
  logger.info("Device agent stopped in the daemon");
6339
7078
  }
@@ -6417,6 +7156,56 @@ function machineDeviceAgentHostDependencies(port, record) {
6417
7156
  };
6418
7157
  }
6419
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
+
6420
7209
  // src/daemon/lifecycle/daemonChild.ts
6421
7210
  var daemonState = { tunnels: [], lastUpdated: "" };
6422
7211
  var daemonHost = DaemonHost.CLI;
@@ -6431,13 +7220,14 @@ function writeDaemonInfo(info) {
6431
7220
  ensurePinggyConfigDir();
6432
7221
  const infoPath = getDaemonInfoPath();
6433
7222
  const tmpPath = infoPath + ".tmp";
6434
- fs11.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
6435
- fs11.renameSync(tmpPath, infoPath);
7223
+ fs14.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
7224
+ fs14.renameSync(tmpPath, infoPath);
6436
7225
  }
6437
7226
  function removeDaemonInfo() {
6438
7227
  try {
6439
7228
  const infoPath = getDaemonInfoPath();
6440
- 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);
6441
7231
  } catch {
6442
7232
  }
6443
7233
  }
@@ -6462,27 +7252,23 @@ function trackTunnelStop(tunnelId) {
6462
7252
  persistDaemonState(daemonState);
6463
7253
  sessionTrackerRef?.removeTunnel(tunnelId);
6464
7254
  }
6465
- function trackDeviceAgentStart(startedBy) {
6466
- daemonState.deviceAgent = { startedAt: (/* @__PURE__ */ new Date()).toISOString(), startedBy };
6467
- persistDaemonState(daemonState);
6468
- }
6469
- function trackDeviceAgentStop() {
6470
- if (!daemonState.deviceAgent) return;
6471
- delete daemonState.deviceAgent;
6472
- persistDaemonState(daemonState);
6473
- }
6474
- 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
+ }
6475
7261
  try {
6476
7262
  const result = await host.start(saved.startedBy);
6477
7263
  if (isErrorResponse(result)) {
6478
- logger.warn("Crash recovery: device agent not restored", { reason: result.message });
6479
- trackDeviceAgentStop();
7264
+ logger.warn("Saved device agent not started", { reason: result.message });
7265
+ forgetDeviceAgent();
6480
7266
  return;
6481
7267
  }
6482
- logger.info("Crash recovery: device agent restored");
7268
+ logger.info("Saved device agent started");
6483
7269
  } catch (err) {
6484
- logger.error("Crash recovery: device agent failed to start", { error: errorMessage(err) });
6485
- trackDeviceAgentStop();
7270
+ logger.error("Saved device agent failed to start", { error: errorMessage(err) });
7271
+ forgetDeviceAgent();
6486
7272
  }
6487
7273
  }
6488
7274
  function trackIPCTunnelStart(tunnelId, origin, mode = SessionMode.Detached) {
@@ -6577,9 +7363,7 @@ async function runDaemonChild(opts = {}) {
6577
7363
  const exitOnFailure = opts.exitOnFailure ?? true;
6578
7364
  daemonHost = opts.host ?? DaemonHost.CLI;
6579
7365
  ensurePinggyConfigDir();
6580
- const persistedLevel = readDaemonConfig()?.logLevel;
6581
- const envLevel = process.env.PINGGY_LOG_LEVEL;
6582
- const initialLevel = persistedLevel ?? envLevel ?? "info";
7366
+ const initialLevel = configuredLogLevel();
6583
7367
  setLogLevel(initialLevel);
6584
7368
  ensurePinggyLogDir();
6585
7369
  const logPath = getDaemonLogPath();
@@ -6590,6 +7374,11 @@ async function runDaemonChild(opts = {}) {
6590
7374
  enableSdkLog: true
6591
7375
  });
6592
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
+ }
6593
7382
  const manager = TunnelManager.getInstance();
6594
7383
  const ipcServer = new IPCServer();
6595
7384
  const sessionTracker = new SessionTracker();
@@ -6612,6 +7401,10 @@ async function runDaemonChild(opts = {}) {
6612
7401
  removeDaemonInfo();
6613
7402
  } catch {
6614
7403
  }
7404
+ try {
7405
+ releaseDaemonLock();
7406
+ } catch {
7407
+ }
6615
7408
  try {
6616
7409
  clearDaemonState();
6617
7410
  } catch {
@@ -6654,14 +7447,10 @@ async function runDaemonChild(opts = {}) {
6654
7447
  try {
6655
7448
  const port = await ipcServer.listen();
6656
7449
  deviceAgentHost = new DeviceAgentHost(machineDeviceAgentHostDependencies(port, {
6657
- recordRunning: trackDeviceAgentStart,
6658
- recordStopped: trackDeviceAgentStop
7450
+ recordRunning: saveDeviceAgent,
7451
+ recordStopped: forgetDeviceAgent
6659
7452
  }));
6660
7453
  ipcServer.setDeviceAgentHost(deviceAgentHost);
6661
- const crashedDeviceAgent = loadDaemonState()?.deviceAgent;
6662
- if (crashedDeviceAgent) {
6663
- daemonState.deviceAgent = crashedDeviceAgent;
6664
- }
6665
7454
  const info = {
6666
7455
  pid: process.pid,
6667
7456
  port,
@@ -6685,8 +7474,9 @@ async function runDaemonChild(opts = {}) {
6685
7474
  } else {
6686
7475
  logger.info("No auto-start tunnels configured");
6687
7476
  }
6688
- if (crashedDeviceAgent) {
6689
- await restoreCrashedDeviceAgent(deviceAgentHost, crashedDeviceAgent);
7477
+ const savedAgent = savedDeviceAgent();
7478
+ if (savedAgent) {
7479
+ await startSavedDeviceAgent(deviceAgentHost, savedAgent);
6690
7480
  }
6691
7481
  logger.info("Daemon ready", { pid: process.pid, port });
6692
7482
  return {
@@ -6697,6 +7487,7 @@ async function runDaemonChild(opts = {}) {
6697
7487
  } catch (err) {
6698
7488
  logger.error("Daemon failed to start", { error: errorMessage(err) });
6699
7489
  removeDaemonInfo();
7490
+ releaseDaemonLock();
6700
7491
  if (exitOnFailure) {
6701
7492
  process.exit(1);
6702
7493
  }
@@ -6711,7 +7502,7 @@ async function main() {
6711
7502
  const { values, positionals, hasAnyArgs } = parseCliArgs(cliOptions);
6712
7503
  configureLogger(values);
6713
7504
  if (values["_daemon-child"]) {
6714
- const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-E73NFWKE.js");
7505
+ const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-HZ27YJKQ.js");
6715
7506
  await runDaemonChild2();
6716
7507
  return;
6717
7508
  }
@@ -6750,8 +7541,6 @@ export {
6750
7541
  removeDaemonInfo,
6751
7542
  trackTunnelStart,
6752
7543
  trackTunnelStop,
6753
- trackDeviceAgentStart,
6754
- trackDeviceAgentStop,
6755
7544
  trackIPCTunnelStart,
6756
7545
  runDaemonChild
6757
7546
  };