pinggy 0.6.4 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -202,6 +202,9 @@ function ensureTunnelConfigDir() {
202
202
  function getDaemonInfoPath() {
203
203
  return import_path2.default.join(getPinggyConfigDir(), "daemon.json");
204
204
  }
205
+ function getDaemonLockPath() {
206
+ return import_path2.default.join(getPinggyConfigDir(), "daemon.lock");
207
+ }
205
208
  function getDaemonConfigPath() {
206
209
  return import_path2.default.join(getPinggyConfigDir(), "daemon-config.json");
207
210
  }
@@ -239,6 +242,9 @@ function getDaemonLogPath() {
239
242
  function getDeviceConfigPath() {
240
243
  return import_path2.default.join(getPinggyConfigDir(), "device.json");
241
244
  }
245
+ function getForegroundAgentPath() {
246
+ return import_path2.default.join(getPinggyConfigDir(), "device-agent.json");
247
+ }
242
248
  function ensurePinggyConfigDir() {
243
249
  const dir = getPinggyConfigDir();
244
250
  import_fs2.default.mkdirSync(dir, { recursive: true });
@@ -258,7 +264,11 @@ var init_configDir = __esm({
258
264
  // src/daemon/lifecycle/daemonConfig.ts
259
265
  var daemonConfig_exports = {};
260
266
  __export(daemonConfig_exports, {
267
+ configuredLogLevel: () => configuredLogLevel,
268
+ forgetDeviceAgent: () => forgetDeviceAgent,
261
269
  readDaemonConfig: () => readDaemonConfig,
270
+ saveDeviceAgent: () => saveDeviceAgent,
271
+ savedDeviceAgent: () => savedDeviceAgent,
262
272
  writeDaemonConfig: () => writeDaemonConfig
263
273
  });
264
274
  function readDaemonConfig() {
@@ -273,6 +283,19 @@ function readDaemonConfig() {
273
283
  return null;
274
284
  }
275
285
  }
286
+ function configuredLogLevel() {
287
+ return readDaemonConfig()?.logLevel ?? process.env.PINGGY_LOG_LEVEL ?? "info";
288
+ }
289
+ function savedDeviceAgent() {
290
+ return readDaemonConfig()?.deviceAgent ?? null;
291
+ }
292
+ function saveDeviceAgent(startedBy) {
293
+ writeDaemonConfig({ deviceAgent: { startedAt: (/* @__PURE__ */ new Date()).toISOString(), startedBy } });
294
+ }
295
+ function forgetDeviceAgent() {
296
+ if (!savedDeviceAgent()) return;
297
+ writeDaemonConfig({ deviceAgent: void 0 });
298
+ }
276
299
  function writeDaemonConfig(partial) {
277
300
  try {
278
301
  ensurePinggyConfigDir();
@@ -3045,11 +3068,11 @@ var init_ipcClient = __esm({
3045
3068
  call(key, body, timeoutMs) {
3046
3069
  const spaceIdx = key.indexOf(" ");
3047
3070
  const method = key.slice(0, spaceIdx);
3048
- const path12 = key.slice(spaceIdx + 1);
3071
+ const path13 = key.slice(spaceIdx + 1);
3049
3072
  const payload = method === "GET" ? void 0 : JSON.stringify(body ?? {});
3050
- return this.request(method, path12, payload, timeoutMs);
3073
+ return this.request(method, path13, payload, timeoutMs);
3051
3074
  }
3052
- request(method, path12, body, timeoutMs) {
3075
+ request(method, path13, body, timeoutMs) {
3053
3076
  return new Promise((resolve, reject) => {
3054
3077
  const headers = {
3055
3078
  "X-Pinggy-Origin": this.origin
@@ -3062,7 +3085,7 @@ var init_ipcClient = __esm({
3062
3085
  {
3063
3086
  hostname: "127.0.0.1",
3064
3087
  port: this.port,
3065
- path: path12,
3088
+ path: path13,
3066
3089
  method,
3067
3090
  headers,
3068
3091
  timeout: timeoutMs ?? REQUEST_TIMEOUT_MS
@@ -3234,6 +3257,8 @@ function printHelpMessage() {
3234
3257
  console.log(" pinggy daemon start # Start the background daemon");
3235
3258
  console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
3236
3259
  console.log(" pinggy daemon status # Show daemon PID and uptime");
3260
+ console.log(" pinggy daemon service-install # Run the daemon at login as a system service");
3261
+ console.log(" pinggy daemon service-uninstall # Stop the daemon and remove the system service");
3237
3262
  }
3238
3263
  var init_help = __esm({
3239
3264
  "src/cli/help.ts"() {
@@ -4746,10 +4771,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
4746
4771
  }
4747
4772
  function storeJson(config, saveconf) {
4748
4773
  if (saveconf) {
4749
- const path12 = saveconf;
4774
+ const path13 = saveconf;
4750
4775
  try {
4751
- import_fs6.default.writeFileSync(path12, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
4752
- logger.info(`Configuration saved to ${path12}`);
4776
+ import_fs6.default.writeFileSync(path13, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
4777
+ logger.info(`Configuration saved to ${path13}`);
4753
4778
  } catch (err) {
4754
4779
  const msg = err instanceof Error ? err.message : String(err);
4755
4780
  logger.error("Error loading configuration:", msg);
@@ -7341,24 +7366,60 @@ var init_buildAndStartTunnel = __esm({
7341
7366
  });
7342
7367
 
7343
7368
  // src/daemon/lifecycle/serviceInstaller.ts
7344
- function resolveBinary() {
7345
- const isPkg = "pkg" in process;
7346
- if (isPkg) return { program: process.execPath, args: [] };
7369
+ function installerBinaryPath(platform2, home, env) {
7370
+ if (platform2 === "win32") {
7371
+ const localAppData = env.LOCALAPPDATA || import_node_path2.default.win32.join(home, "AppData", "Local");
7372
+ return import_node_path2.default.win32.join(localAppData, "Pinggy", "bin", "pinggy.exe");
7373
+ }
7374
+ return import_node_path2.default.posix.join(home, ".pinggy", "bin", "pinggy");
7375
+ }
7376
+ function realPath(p) {
7347
7377
  try {
7348
- const bin = (0, import_node_child_process.execSync)(import_node_os.default.platform() === "win32" ? "where pinggy" : "which pinggy", {
7349
- encoding: "utf-8"
7350
- }).trim().split(/\r?\n/)[0];
7351
- return { program: bin, args: [] };
7378
+ return import_node_fs3.default.realpathSync(p);
7352
7379
  } catch {
7353
- return { program: process.execPath, args: [process.argv[1]] };
7380
+ return p;
7354
7381
  }
7355
7382
  }
7383
+ function isInstallerBinary(ctx) {
7384
+ const actual = realPath(ctx.execPath);
7385
+ const expected = realPath(installerBinaryPath(ctx.platform, ctx.home, ctx.env));
7386
+ if (ctx.platform === "win32") return actual.toLowerCase() === expected.toLowerCase();
7387
+ return actual === expected;
7388
+ }
7389
+ function installerFix(platform2) {
7390
+ const installCommand = platform2 === "win32" ? "irm https://pinggy.io/install.ps1 | iex" : "curl -fsSL https://pinggy.io/install.sh | sh";
7391
+ return [
7392
+ "pinggy can only run as a service when it is installed with the Pinggy installer.",
7393
+ "Install it, then run this command again:",
7394
+ ` ${installCommand}`,
7395
+ " pinggy daemon service-install"
7396
+ ].join("\n");
7397
+ }
7398
+ function serviceInstallRefusal(ctx) {
7399
+ if (!ctx.isPkg) return `The npm version of pinggy cannot run as a service.
7400
+ ${installerFix(ctx.platform)}`;
7401
+ if (ctx.env[SERVICE_ANY_LOCATION_ENV] === "1" || isInstallerBinary(ctx)) return null;
7402
+ return installerFix(ctx.platform);
7403
+ }
7404
+ function printInstalled() {
7405
+ printer_default.success("pinggy now starts automatically when this computer starts.");
7406
+ }
7407
+ function printUninstalled() {
7408
+ printer_default.success("pinggy no longer starts automatically when this computer starts.");
7409
+ }
7410
+ function printNotInstalled() {
7411
+ printer_default.print("pinggy is not set to start automatically.");
7412
+ }
7413
+ function toolError(err) {
7414
+ const stderr = err.stderr?.toString().trim();
7415
+ return stderr ? stderr.replace(/^ERROR:\s*/i, "") : errorMessage(err);
7416
+ }
7356
7417
  function getSystemdServicePath() {
7357
7418
  const dir = import_node_path2.default.join(import_node_os.default.homedir(), ".config", "systemd", "user");
7358
7419
  return import_node_path2.default.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
7359
7420
  }
7360
- function generateSystemdUnit(bin) {
7361
- const execStart = [bin.program, ...bin.args, "--_daemon-child"].join(" ");
7421
+ function generateSystemdUnit(program) {
7422
+ const execStart = `${program} --_daemon-child`;
7362
7423
  return `[Unit]
7363
7424
  Description=Pinggy Tunnel Daemon
7364
7425
  After=network-online.target
@@ -7374,18 +7435,17 @@ RestartSec=5
7374
7435
  WantedBy=default.target
7375
7436
  `;
7376
7437
  }
7377
- function installSystemd() {
7378
- const bin = resolveBinary();
7438
+ function installSystemd(program) {
7379
7439
  const servicePath = getSystemdServicePath();
7380
7440
  const dir = import_node_path2.default.dirname(servicePath);
7381
7441
  import_node_fs3.default.mkdirSync(dir, { recursive: true });
7382
- import_node_fs3.default.writeFileSync(servicePath, generateSystemdUnit(bin), "utf-8");
7383
- (0, import_node_child_process.execSync)("systemctl --user daemon-reload");
7384
- (0, import_node_child_process.execSync)(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`);
7385
- (0, import_node_child_process.execSync)(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`);
7386
- logger.info("systemd user service installed and started", { servicePath });
7387
- console.log(`Service installed: ${servicePath}`);
7388
- console.log(`Enable at boot: loginctl enable-linger ${import_node_os.default.userInfo().username}`);
7442
+ import_node_fs3.default.writeFileSync(servicePath, generateSystemdUnit(program), "utf-8");
7443
+ (0, import_node_child_process.execSync)("systemctl --user daemon-reload", QUIET);
7444
+ (0, import_node_child_process.execSync)(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`, QUIET);
7445
+ (0, import_node_child_process.execSync)(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`, QUIET);
7446
+ logger.info("systemd user service installed", { servicePath });
7447
+ printInstalled();
7448
+ printer_default.print(`To start it before anyone signs in, run: loginctl enable-linger ${import_node_os.default.userInfo().username}`);
7389
7449
  }
7390
7450
  function uninstallSystemd() {
7391
7451
  const servicePath = getSystemdServicePath();
@@ -7396,17 +7456,18 @@ function uninstallSystemd() {
7396
7456
  }
7397
7457
  if (import_node_fs3.default.existsSync(servicePath)) {
7398
7458
  import_node_fs3.default.unlinkSync(servicePath);
7399
- (0, import_node_child_process.execSync)("systemctl --user daemon-reload");
7400
- console.log(`Service removed: ${servicePath}`);
7459
+ (0, import_node_child_process.execSync)("systemctl --user daemon-reload", QUIET);
7460
+ logger.info("systemd user service removed", { servicePath });
7461
+ printUninstalled();
7401
7462
  } else {
7402
- console.log("No systemd service found to remove.");
7463
+ printNotInstalled();
7403
7464
  }
7404
7465
  }
7405
7466
  function getLaunchdPlistPath() {
7406
7467
  return import_node_path2.default.join(import_node_os.default.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
7407
7468
  }
7408
- function generateLaunchdPlist(bin) {
7409
- const allArgs = [bin.program, ...bin.args, "--_daemon-child"];
7469
+ function generateLaunchdPlist(program) {
7470
+ const allArgs = [program, "--_daemon-child"];
7410
7471
  const programArgs = allArgs.map((p) => ` <string>${p}</string>`).join("\n");
7411
7472
  return `<?xml version="1.0" encoding="UTF-8"?>
7412
7473
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
@@ -7427,17 +7488,21 @@ ${programArgs}
7427
7488
  </plist>
7428
7489
  `;
7429
7490
  }
7430
- function installLaunchd() {
7431
- const bin = resolveBinary();
7491
+ function installLaunchd(program) {
7432
7492
  const plistPath = getLaunchdPlistPath();
7433
7493
  const dir = import_node_path2.default.dirname(plistPath);
7434
7494
  import_node_fs3.default.mkdirSync(dir, { recursive: true });
7435
- import_node_fs3.default.writeFileSync(plistPath, generateLaunchdPlist(bin), "utf-8");
7495
+ import_node_fs3.default.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
7436
7496
  const uid = process.getuid?.() ?? 501;
7437
7497
  try {
7438
7498
  (0, import_node_child_process.execSync)(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
7439
7499
  } catch {
7440
7500
  }
7501
+ loadLaunchdPlist(uid, plistPath);
7502
+ logger.info("launchd agent installed", { plistPath });
7503
+ printInstalled();
7504
+ }
7505
+ function loadLaunchdPlist(uid, plistPath) {
7441
7506
  try {
7442
7507
  (0, import_node_child_process.execSync)(`launchctl bootstrap gui/${uid} ${plistPath}`);
7443
7508
  } catch {
@@ -7446,8 +7511,6 @@ function installLaunchd() {
7446
7511
  } catch {
7447
7512
  }
7448
7513
  }
7449
- logger.info("launchd agent installed and started", { plistPath });
7450
- console.log(`Service installed and started: ${plistPath}`);
7451
7514
  }
7452
7515
  function uninstallLaunchd() {
7453
7516
  const plistPath = getLaunchdPlistPath();
@@ -7462,23 +7525,33 @@ function uninstallLaunchd() {
7462
7525
  }
7463
7526
  if (import_node_fs3.default.existsSync(plistPath)) {
7464
7527
  import_node_fs3.default.unlinkSync(plistPath);
7465
- console.log(`Service removed: ${plistPath}`);
7528
+ logger.info("launchd agent removed", { plistPath });
7529
+ printUninstalled();
7466
7530
  } else {
7467
- console.log("No launchd agent found to remove.");
7531
+ printNotInstalled();
7468
7532
  }
7469
7533
  }
7470
- function generateTaskXml(bin) {
7471
- const command = bin.program;
7472
- const args = [...bin.args, "--_daemon-child"].join(" ");
7534
+ function escapeXml(value) {
7535
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
7536
+ }
7537
+ function getWindowsUserId() {
7538
+ const user = process.env.USERNAME || import_node_os.default.userInfo().username;
7539
+ const domain = process.env.USERDOMAIN;
7540
+ return domain ? `${domain}\\${user}` : user;
7541
+ }
7542
+ function generateTaskXml(program, userId) {
7543
+ const user = escapeXml(userId);
7473
7544
  return `<?xml version="1.0" encoding="UTF-16"?>
7474
7545
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
7475
7546
  <Triggers>
7476
7547
  <LogonTrigger>
7477
7548
  <Enabled>true</Enabled>
7549
+ <UserId>${user}</UserId>
7478
7550
  </LogonTrigger>
7479
7551
  </Triggers>
7480
7552
  <Principals>
7481
7553
  <Principal id="Author">
7554
+ <UserId>${user}</UserId>
7482
7555
  <LogonType>InteractiveToken</LogonType>
7483
7556
  <RunLevel>LeastPrivilege</RunLevel>
7484
7557
  </Principal>
@@ -7496,71 +7569,105 @@ function generateTaskXml(bin) {
7496
7569
  </Settings>
7497
7570
  <Actions>
7498
7571
  <Exec>
7499
- <Command>${command}</Command>${args ? `
7500
- <Arguments>${args}</Arguments>` : ""}
7572
+ <Command>${escapeXml(program)}</Command>
7573
+ <Arguments>daemon start</Arguments>
7501
7574
  </Exec>
7502
7575
  </Actions>
7503
7576
  </Task>`;
7504
7577
  }
7505
- function installWindows() {
7506
- const bin = resolveBinary();
7507
- const xml = generateTaskXml(bin);
7578
+ function createWindowsTask(program) {
7579
+ const xml = generateTaskXml(program, getWindowsUserId());
7508
7580
  const tmpPath = import_node_path2.default.join(import_node_os.default.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
7509
7581
  import_node_fs3.default.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
7510
7582
  try {
7511
- (0, import_node_child_process.execFileSync)("schtasks", [
7512
- "/Create",
7513
- "/TN",
7514
- WINDOWS_TASK_NAME,
7515
- "/XML",
7516
- tmpPath,
7517
- "/F"
7518
- ], { stdio: "inherit" });
7583
+ (0, import_node_child_process.execFileSync)("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
7519
7584
  } finally {
7520
7585
  try {
7521
7586
  import_node_fs3.default.unlinkSync(tmpPath);
7522
7587
  } catch {
7523
7588
  }
7524
7589
  }
7525
- (0, import_node_child_process.execFileSync)("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], { stdio: "inherit" });
7526
- console.log(`Scheduled task "${WINDOWS_TASK_NAME}" created and started (runs at login, hidden).`);
7527
7590
  }
7528
- function uninstallWindows() {
7591
+ function windowsTaskExists() {
7529
7592
  try {
7530
- (0, import_node_child_process.execFileSync)("schtasks", ["/End", "/TN", WINDOWS_TASK_NAME], { stdio: "ignore" });
7593
+ (0, import_node_child_process.execFileSync)("schtasks", ["/Query", "/TN", WINDOWS_TASK_NAME], QUIET);
7594
+ return true;
7531
7595
  } catch {
7596
+ return false;
7532
7597
  }
7598
+ }
7599
+ function isElevated() {
7533
7600
  try {
7534
- (0, import_node_child_process.execFileSync)("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], { stdio: "inherit" });
7535
- console.log(`Scheduled task "${WINDOWS_TASK_NAME}" removed.`);
7601
+ return /S-1-16-(12288|16384)\b/.test((0, import_node_child_process.execFileSync)("whoami", ["/groups"], { encoding: "utf-8" }));
7536
7602
  } catch {
7537
- console.log("No scheduled task found to remove.");
7603
+ return false;
7604
+ }
7605
+ }
7606
+ function windowsTaskError(action, undo, err) {
7607
+ if (windowsTaskExists() && !isElevated()) {
7608
+ return `Could not ${action}. It was set up from an Administrator terminal. Run this command from an Administrator terminal to ${undo}.`;
7609
+ }
7610
+ return `Could not ${action}: ${toolError(err)}`;
7611
+ }
7612
+ function installWindows(program) {
7613
+ try {
7614
+ createWindowsTask(program);
7615
+ (0, import_node_child_process.execFileSync)("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], QUIET);
7616
+ } catch (err) {
7617
+ printer_default.error(windowsTaskError("set pinggy to start automatically", "change it", err));
7618
+ process.exit(1);
7619
+ }
7620
+ logger.info("Scheduled task installed", { task: WINDOWS_TASK_NAME });
7621
+ printInstalled();
7622
+ }
7623
+ async function uninstallWindows() {
7624
+ if (!windowsTaskExists()) {
7625
+ printNotInstalled();
7626
+ return;
7627
+ }
7628
+ try {
7629
+ (0, import_node_child_process.execFileSync)("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], QUIET);
7630
+ } catch (err) {
7631
+ printer_default.error(windowsTaskError("stop pinggy from starting automatically", "turn it off", err));
7632
+ process.exit(1);
7633
+ }
7634
+ logger.info("Scheduled task removed", { task: WINDOWS_TASK_NAME });
7635
+ if (isDaemonRunning()) {
7636
+ const result = await stopDaemon();
7637
+ if (!result.ok) console.log(`Could not stop the daemon: ${result.error}`);
7538
7638
  }
7639
+ printUninstalled();
7539
7640
  }
7540
7641
  function installService() {
7541
7642
  const platform2 = import_node_os.default.platform();
7542
- const bin = resolveBinary();
7543
- if (!("pkg" in process) && bin.program !== process.execPath) {
7544
- console.warn(
7545
- "Warning: Using npm-installed binary. The path may change if Node.js is updated.\nConsider using a standalone binary (pkg) for system services."
7546
- );
7643
+ const program = process.execPath;
7644
+ const refusal = serviceInstallRefusal({
7645
+ platform: platform2,
7646
+ isPkg: "pkg" in process,
7647
+ execPath: program,
7648
+ home: import_node_os.default.homedir(),
7649
+ env: process.env
7650
+ });
7651
+ if (refusal) {
7652
+ console.error(refusal);
7653
+ process.exit(1);
7547
7654
  }
7548
7655
  switch (platform2) {
7549
7656
  case "linux":
7550
- installSystemd();
7657
+ installSystemd(program);
7551
7658
  break;
7552
7659
  case "darwin":
7553
- installLaunchd();
7660
+ installLaunchd(program);
7554
7661
  break;
7555
7662
  case "win32":
7556
- installWindows();
7663
+ installWindows(program);
7557
7664
  break;
7558
7665
  default:
7559
7666
  console.error(`Unsupported platform: ${platform2}`);
7560
7667
  process.exit(1);
7561
7668
  }
7562
7669
  }
7563
- function uninstallService() {
7670
+ async function uninstallService() {
7564
7671
  const platform2 = import_node_os.default.platform();
7565
7672
  switch (platform2) {
7566
7673
  case "linux":
@@ -7570,14 +7677,14 @@ function uninstallService() {
7570
7677
  uninstallLaunchd();
7571
7678
  break;
7572
7679
  case "win32":
7573
- uninstallWindows();
7680
+ await uninstallWindows();
7574
7681
  break;
7575
7682
  default:
7576
7683
  console.error(`Unsupported platform: ${platform2}`);
7577
7684
  process.exit(1);
7578
7685
  }
7579
7686
  }
7580
- var import_node_os, import_node_fs3, import_node_path2, import_node_child_process, SERVICE_LABEL, SYSTEMD_SERVICE_NAME, WINDOWS_TASK_NAME;
7687
+ var import_node_os, import_node_fs3, import_node_path2, import_node_child_process, SERVICE_LABEL, SYSTEMD_SERVICE_NAME, SERVICE_ANY_LOCATION_ENV, QUIET, WINDOWS_TASK_NAME;
7581
7688
  var init_serviceInstaller = __esm({
7582
7689
  "src/daemon/lifecycle/serviceInstaller.ts"() {
7583
7690
  "use strict";
@@ -7587,8 +7694,13 @@ var init_serviceInstaller = __esm({
7587
7694
  import_node_path2 = __toESM(require("path"), 1);
7588
7695
  import_node_child_process = require("child_process");
7589
7696
  init_logger();
7697
+ init_printer();
7698
+ init_util();
7699
+ init_daemonManager();
7590
7700
  SERVICE_LABEL = "io.pinggy.agent";
7591
7701
  SYSTEMD_SERVICE_NAME = "pinggy";
7702
+ SERVICE_ANY_LOCATION_ENV = "PINGGY_SERVICE_ANY_LOCATION";
7703
+ QUIET = { stdio: ["ignore", "ignore", "pipe"] };
7592
7704
  WINDOWS_TASK_NAME = "PinggyDaemon";
7593
7705
  }
7594
7706
  });
@@ -7601,6 +7713,8 @@ function printDaemonHelp() {
7601
7713
  console.log(" start Start the daemon process");
7602
7714
  console.log(" stop Stop the daemon (stops all tunnels)");
7603
7715
  console.log(" status Show daemon PID and uptime");
7716
+ console.log(" service-install Run the daemon at login as a system service");
7717
+ console.log(" service-uninstall Stop the daemon and remove the system service");
7604
7718
  console.log("Tunnel operations:");
7605
7719
  console.log(" pinggy ps List running tunnels");
7606
7720
  console.log(" pinggy stop <name|id> Stop a specific tunnel");
@@ -7641,16 +7755,20 @@ function printDeviceHelp() {
7641
7755
  console.log(" background");
7642
7756
  console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
7643
7757
  console.log(" background. Without --token: start the enrolled device's agent again");
7644
- console.log(" stop Stop the agent running in the background");
7758
+ console.log(" stop Stop the agent running in the background, until the daemon");
7759
+ console.log(" starts again");
7645
7760
  console.log(" status Show the enrolment, and the agent running in the background");
7646
- console.log(" remove Forget the local credential (does not delete the device)\n");
7647
- console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.\n");
7761
+ console.log(" remove Stop the agent and forget the local credential, after asking.");
7762
+ console.log(" The device stays in the dashboard\n");
7763
+ console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.");
7764
+ console.log("Each time the daemon starts, it starts the agent again, until remove.\n");
7648
7765
  console.log("Options:");
7649
7766
  console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
7650
7767
  console.log(" -b login and connect: run the agent in the background. The default");
7651
7768
  console.log(" --token <TOKEN> Device token from the dashboard");
7652
7769
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
7653
- console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname\n");
7770
+ console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
7771
+ console.log(" -f remove only: remove without asking\n");
7654
7772
  console.log("Environment:");
7655
7773
  console.log(" DEVICE_AGENT_TOKEN connect only: the device token, when --token is not given. With no");
7656
7774
  console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
@@ -9945,9 +10063,9 @@ function readShellEnvironment() {
9945
10063
  platform: process.platform,
9946
10064
  loginShell: process.env.SHELL,
9947
10065
  etcShells,
9948
- exists: (path12) => {
10066
+ exists: (path13) => {
9949
10067
  try {
9950
- return import_fs12.default.statSync(path12).isFile();
10068
+ return import_fs12.default.statSync(path13).isFile();
9951
10069
  } catch {
9952
10070
  return false;
9953
10071
  }
@@ -9990,6 +10108,116 @@ var init_shellAllowlist = __esm({
9990
10108
  }
9991
10109
  });
9992
10110
 
10111
+ // src/devices/foregroundAgent.ts
10112
+ function readRecordFile(filePath) {
10113
+ try {
10114
+ const record = JSON.parse(import_fs13.default.readFileSync(filePath, "utf-8"));
10115
+ return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
10116
+ } catch {
10117
+ return null;
10118
+ }
10119
+ }
10120
+ function deleteRecordFile(filePath) {
10121
+ try {
10122
+ import_fs13.default.unlinkSync(filePath);
10123
+ } catch (err) {
10124
+ logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
10125
+ }
10126
+ }
10127
+ function readForegroundAgent() {
10128
+ const filePath = getForegroundAgentPath();
10129
+ const record = readRecordFile(filePath);
10130
+ if (!record) {
10131
+ return null;
10132
+ }
10133
+ if (record.pid === process.pid) {
10134
+ return null;
10135
+ }
10136
+ if (startedBeforeBoot(record.started_at) || !isProcessAlive(record.pid)) {
10137
+ logger.info("Stale device-agent.json found, cleaning up", { stalePid: record.pid });
10138
+ deleteRecordFile(filePath);
10139
+ return null;
10140
+ }
10141
+ return record;
10142
+ }
10143
+ function recordForegroundAgent(onRecordDeleted) {
10144
+ const filePath = getForegroundAgentPath();
10145
+ const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
10146
+ try {
10147
+ ensurePinggyConfigDir();
10148
+ import_fs13.default.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
10149
+ } catch (err) {
10150
+ logger.warn(
10151
+ "Could not write device-agent.json. pinggy device remove cannot stop this agent.",
10152
+ { error: errorMessage(err) }
10153
+ );
10154
+ return () => void 0;
10155
+ }
10156
+ const timer = setInterval(() => {
10157
+ if (!import_fs13.default.existsSync(filePath)) {
10158
+ clearInterval(timer);
10159
+ onRecordDeleted();
10160
+ }
10161
+ }, RECORD_CHECK_INTERVAL_MILLIS);
10162
+ timer.unref();
10163
+ return () => {
10164
+ clearInterval(timer);
10165
+ if (readRecordFile(filePath)?.pid === process.pid) {
10166
+ deleteRecordFile(filePath);
10167
+ }
10168
+ };
10169
+ }
10170
+ function machineForegroundStopDependencies() {
10171
+ return {
10172
+ readAgent: readForegroundAgent,
10173
+ deleteRecord: () => deleteRecordFile(getForegroundAgentPath()),
10174
+ isAlive: isProcessAlive,
10175
+ sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),
10176
+ now: () => Date.now(),
10177
+ print: (message) => printer_default.print(message),
10178
+ printError: (message) => printer_default.error(message)
10179
+ };
10180
+ }
10181
+ async function stopForegroundAgentBeforeRemove(dependencies = machineForegroundStopDependencies()) {
10182
+ const record = dependencies.readAgent();
10183
+ if (!record) {
10184
+ return true;
10185
+ }
10186
+ dependencies.deleteRecord();
10187
+ const deadline = dependencies.now() + STOP_WAIT_MILLIS;
10188
+ while (dependencies.isAlive(record.pid)) {
10189
+ if (dependencies.now() >= deadline) {
10190
+ 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`);
10191
+ return false;
10192
+ }
10193
+ await dependencies.sleep(STOP_POLL_INTERVAL_MILLIS);
10194
+ }
10195
+ dependencies.print(`Stopped the device agent running in another terminal (PID ${record.pid}).`);
10196
+ return true;
10197
+ }
10198
+ function foregroundAgentRefusal(record = readForegroundAgent()) {
10199
+ if (!record) {
10200
+ return null;
10201
+ }
10202
+ return `This machine already runs as a device in another terminal (PID ${record.pid}). Press Ctrl+C in that terminal first.`;
10203
+ }
10204
+ var import_fs13, RECORD_CHECK_INTERVAL_MILLIS, STOP_WAIT_MILLIS, STOP_POLL_INTERVAL_MILLIS;
10205
+ var init_foregroundAgent = __esm({
10206
+ "src/devices/foregroundAgent.ts"() {
10207
+ "use strict";
10208
+ init_cjs_shims();
10209
+ import_fs13 = __toESM(require("fs"), 1);
10210
+ init_configDir();
10211
+ init_daemonManager();
10212
+ init_logger();
10213
+ init_util();
10214
+ init_printer();
10215
+ RECORD_CHECK_INTERVAL_MILLIS = 1e3;
10216
+ STOP_WAIT_MILLIS = 1e4;
10217
+ STOP_POLL_INTERVAL_MILLIS = 200;
10218
+ }
10219
+ });
10220
+
9993
10221
  // src/devices/deviceAgent.ts
9994
10222
  function buildCapabilities(terminalSupported, screenRestoreSupported = false) {
9995
10223
  if (!terminalSupported) return BASE_CAPABILITIES;
@@ -10085,14 +10313,20 @@ function startDeviceAgent(token, manage, options = {}) {
10085
10313
  }
10086
10314
  async function runDeviceAgent(token, manage, options = {}) {
10087
10315
  const run2 = startDeviceAgent(token, manage, options);
10316
+ const reporter = options.reporter ?? printingReporter;
10088
10317
  const sigintHandler = () => {
10089
10318
  void run2.stop();
10090
10319
  };
10320
+ const releaseRecord = recordForegroundAgent(() => {
10321
+ reporter.warn("Stopping: pinggy device remove ran in another terminal.");
10322
+ void run2.stop();
10323
+ });
10091
10324
  process.once("SIGINT", sigintHandler);
10092
10325
  try {
10093
10326
  await run2.done;
10094
10327
  } finally {
10095
10328
  process.removeListener("SIGINT", sigintHandler);
10329
+ releaseRecord();
10096
10330
  }
10097
10331
  }
10098
10332
  async function runLoop(context) {
@@ -10373,6 +10607,7 @@ var init_deviceAgent = __esm({
10373
10607
  init_ptySession();
10374
10608
  init_shellAllowlist();
10375
10609
  init_shellContext();
10610
+ init_foregroundAgent();
10376
10611
  init_deviceAgentReporter();
10377
10612
  CLOSE_CODE_REVOKED = 4001;
10378
10613
  CLOSE_CODE_NORMAL = 1e3;
@@ -10452,8 +10687,8 @@ function buildDashboardHttpUrl(manage) {
10452
10687
  }
10453
10688
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
10454
10689
  const baseUrl = buildDashboardHttpUrl(manage);
10455
- async function post(path12, body, schema) {
10456
- const response2 = await fetchImpl(`${baseUrl}/${path12}`, {
10690
+ async function post(path13, body, schema) {
10691
+ const response2 = await fetchImpl(`${baseUrl}/${path13}`, {
10457
10692
  method: "POST",
10458
10693
  headers: { "Content-Type": "application/json", Accept: "application/json" },
10459
10694
  body: JSON.stringify(body)
@@ -10845,7 +11080,10 @@ var init_deviceLogin = __esm({
10845
11080
  function machineBackgroundAgentDependencies() {
10846
11081
  return {
10847
11082
  readIdentity: readDeviceIdentity,
11083
+ readForegroundAgent,
10848
11084
  findDaemon: getDaemonInfo,
11085
+ hasSavedAgent: () => savedDeviceAgent() !== null,
11086
+ forgetSavedAgent: forgetDeviceAgent,
10849
11087
  ensureDaemon: ensureDaemonRunning,
10850
11088
  client: (port) => new IPCClient(port, "cli"),
10851
11089
  verify: (token, manage) => startDeviceAgent(token, manage, {
@@ -10925,7 +11163,7 @@ async function stopAgentInBackground(dependencies) {
10925
11163
  if (!await stopReadAgent(reading, dependencies)) {
10926
11164
  return EXIT_FAILED;
10927
11165
  }
10928
- dependencies.printSuccess("Stopped. The device shows offline in the dashboard.");
11166
+ dependencies.printSuccess("Stopped. The device shows offline in the dashboard until the daemon starts again.");
10929
11167
  return EXIT_OK;
10930
11168
  }
10931
11169
  async function stopAgentBeforeRemove(dependencies) {
@@ -11052,19 +11290,21 @@ var init_backgroundAgent = __esm({
11052
11290
  init_util();
11053
11291
  init_types();
11054
11292
  init_daemonManager();
11293
+ init_daemonConfig();
11055
11294
  init_ipcClient();
11056
11295
  init_ipcRoutes();
11057
11296
  init_deviceIdentity();
11058
11297
  init_deviceAgent();
11059
11298
  init_deviceAgentReporter();
11060
11299
  init_deviceLogin();
11300
+ init_foregroundAgent();
11061
11301
  POLL_INTERVAL_MILLIS = 500;
11062
11302
  CONNECT_WAIT_MILLIS = 15e3;
11063
11303
  MANAGE_COMMANDS = [
11064
11304
  ["pinggy device status", "Show this device, and whether its agent runs"],
11065
- ["pinggy device stop", "Stop the agent. The device shows offline"],
11066
- ["pinggy device connect", "Start the agent again, after a stop or a reboot"],
11067
- ["pinggy device remove", "Forget this machine's credential"]
11305
+ ["pinggy device stop", "Stop the agent until the daemon starts again. The device shows offline"],
11306
+ ["pinggy device connect", "Start the agent again after a stop"],
11307
+ ["pinggy device remove", "Stop the agent and forget this machine's credential"]
11068
11308
  ];
11069
11309
  verifyingReporter = {
11070
11310
  connecting: () => void 0,
@@ -11099,7 +11339,7 @@ async function handleDaemon(args) {
11099
11339
  installService();
11100
11340
  return;
11101
11341
  case "service-uninstall":
11102
- uninstallService();
11342
+ await uninstallService();
11103
11343
  return;
11104
11344
  default:
11105
11345
  printer_default.error(`Unknown daemon command: "${verb}"`);
@@ -11199,7 +11439,10 @@ var init_daemonCommandsHandler = __esm({
11199
11439
  async function handlePs() {
11200
11440
  const client = new TunnelClient();
11201
11441
  try {
11202
- await client.ensureDaemon();
11442
+ if (!client.connectIfRunning()) {
11443
+ printer_default.print("No active tunnels. The daemon is not running.");
11444
+ return;
11445
+ }
11203
11446
  } catch (err) {
11204
11447
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11205
11448
  return;
@@ -11211,7 +11454,7 @@ async function handlePs() {
11211
11454
  return;
11212
11455
  }
11213
11456
  if (tunnels.length === 0) {
11214
- printer_default.print("No tunnels running.");
11457
+ printer_default.print("No active tunnels.");
11215
11458
  return;
11216
11459
  }
11217
11460
  const header = `${pad("ID", 14)} ${pad("NAME", 16)} ${pad("STATUS", 10)} ${pad("LOCAL", 20)} URL`;
@@ -11258,7 +11501,10 @@ async function handleStop(args) {
11258
11501
  }
11259
11502
  const client = new TunnelClient();
11260
11503
  try {
11261
- await client.ensureDaemon();
11504
+ if (!client.connectIfRunning()) {
11505
+ printer_default.print("Nothing to stop. No tunnels are running.");
11506
+ return;
11507
+ }
11262
11508
  } catch (err) {
11263
11509
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11264
11510
  return;
@@ -11319,6 +11565,25 @@ var init_stopCommand = __esm({
11319
11565
  }
11320
11566
  });
11321
11567
 
11568
+ // src/cli/subcommand/handlers/noDaemon.ts
11569
+ function startCommand(name) {
11570
+ return /\s/.test(name) ? `pinggy start "${name}"` : `pinggy start ${name}`;
11571
+ }
11572
+ function tunnelNotRunningMessage(nameOrId) {
11573
+ const saved = findConfig(nameOrId);
11574
+ if (saved) {
11575
+ return `Tunnel "${saved.name}" is not running. Start it with: ${startCommand(saved.name)}`;
11576
+ }
11577
+ return `No tunnel matches "${nameOrId}". No tunnels are running.`;
11578
+ }
11579
+ var init_noDaemon = __esm({
11580
+ "src/cli/subcommand/handlers/noDaemon.ts"() {
11581
+ "use strict";
11582
+ init_cjs_shims();
11583
+ init_configStore();
11584
+ }
11585
+ });
11586
+
11322
11587
  // src/cli/subcommand/handlers/attachCommand.ts
11323
11588
  async function handleAttach(args) {
11324
11589
  if (args.length === 0) {
@@ -11328,7 +11593,10 @@ async function handleAttach(args) {
11328
11593
  const nameOrId = args[0];
11329
11594
  const client = new TunnelClient();
11330
11595
  try {
11331
- await client.ensureDaemon();
11596
+ if (!client.connectIfRunning()) {
11597
+ printer_default.error(tunnelNotRunningMessage(nameOrId));
11598
+ return;
11599
+ }
11332
11600
  } catch (err) {
11333
11601
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11334
11602
  return;
@@ -11384,15 +11652,106 @@ var init_attachCommand = __esm({
11384
11652
  init_types();
11385
11653
  init_startCli();
11386
11654
  init_util();
11655
+ init_noDaemon();
11656
+ }
11657
+ });
11658
+
11659
+ // src/daemon/logPaths.ts
11660
+ function parseTunnelLogFilename(filename) {
11661
+ const base = filename.replace(/\.log$/, "");
11662
+ const parts = base.split("__");
11663
+ if (parts.length < 2) return null;
11664
+ const origin = parts[0];
11665
+ if (!TUNNEL_ORIGINS.includes(origin)) return null;
11666
+ if (parts.length === 2) {
11667
+ const second = parts[1];
11668
+ if (UUID_RE.test(second)) return { origin, tunnelId: second };
11669
+ return { origin, name: second };
11670
+ }
11671
+ const tunnelId = parts[parts.length - 1];
11672
+ const name = parts.slice(1, -1).join("__");
11673
+ return { origin, name, tunnelId };
11674
+ }
11675
+ function listTunnelLogFiles() {
11676
+ const logDir = getTunnelLogDir();
11677
+ if (!import_node_fs4.default.existsSync(logDir)) return [];
11678
+ return import_node_fs4.default.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
11679
+ }
11680
+ function newestLogFile(q) {
11681
+ const logDir = getTunnelLogDir();
11682
+ const matches = [];
11683
+ for (const file of listTunnelLogFiles()) {
11684
+ const parsed = parseTunnelLogFilename(file);
11685
+ if (!parsed) continue;
11686
+ const nameMatch = parsed.name !== void 0 && parsed.name === q;
11687
+ const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
11688
+ if (nameMatch || idMatch) {
11689
+ const filePath = import_node_path3.default.join(logDir, file);
11690
+ matches.push({ ...parsed, path: filePath, mtime: import_node_fs4.default.statSync(filePath).mtimeMs });
11691
+ }
11692
+ }
11693
+ if (matches.length === 0) return null;
11694
+ matches.sort((a, b) => b.mtime - a.mtime);
11695
+ const best = matches[0];
11696
+ return { status: "historical", path: best.path, tunnelId: best.tunnelId, name: best.name, origin: best.origin, running: false };
11697
+ }
11698
+ function resolveStoppedLogPath(q) {
11699
+ if (!q) return { status: "not-found" };
11700
+ const historical = newestLogFile(q);
11701
+ if (historical) return historical;
11702
+ const saved = listSavedConfigs();
11703
+ const matchedConfig = saved.find((c) => c.name === q || c.configId === q || c.configId.startsWith(q));
11704
+ if (matchedConfig) {
11705
+ return { status: "config-only", name: matchedConfig.name, configId: matchedConfig.configId };
11706
+ }
11707
+ return { status: "not-found" };
11708
+ }
11709
+ var import_node_fs4, import_node_path3, TUNNEL_ORIGINS, UUID_RE;
11710
+ var init_logPaths = __esm({
11711
+ "src/daemon/logPaths.ts"() {
11712
+ "use strict";
11713
+ init_cjs_shims();
11714
+ import_node_fs4 = __toESM(require("fs"), 1);
11715
+ import_node_path3 = __toESM(require("path"), 1);
11716
+ init_configStore();
11717
+ init_configDir();
11718
+ TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
11719
+ UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11720
+ }
11721
+ });
11722
+
11723
+ // src/cli/subcommand/handlers/logLookup.ts
11724
+ function openLogLookup() {
11725
+ const client = new TunnelClient();
11726
+ if (!client.connectIfRunning()) {
11727
+ return {
11728
+ daemonLogPath: () => Promise.resolve(getDaemonLogPath()),
11729
+ resolve: (nameOrId) => Promise.resolve(resolveStoppedLogPath(nameOrId)),
11730
+ close: () => void 0
11731
+ };
11732
+ }
11733
+ return {
11734
+ daemonLogPath: async () => (await client.getLogPaths()).daemon,
11735
+ resolve: (nameOrId) => client.resolveLogPath(nameOrId),
11736
+ close: () => client.close()
11737
+ };
11738
+ }
11739
+ var init_logLookup = __esm({
11740
+ "src/cli/subcommand/handlers/logLookup.ts"() {
11741
+ "use strict";
11742
+ init_cjs_shims();
11743
+ init_tunnelClient();
11744
+ init_logPaths();
11745
+ init_configDir();
11387
11746
  }
11388
11747
  });
11389
11748
 
11390
11749
  // src/cli/subcommand/handlers/logsCommand.ts
11391
11750
  async function handleLogs(args, follow) {
11392
11751
  const arg = args.find((a) => !a.startsWith("-"));
11393
- const client = new TunnelClient();
11752
+ let client;
11394
11753
  try {
11395
- await client.ensureDaemon();
11754
+ client = openLogLookup();
11396
11755
  } catch (err) {
11397
11756
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11398
11757
  return;
@@ -11400,7 +11759,7 @@ async function handleLogs(args, follow) {
11400
11759
  let filePath;
11401
11760
  try {
11402
11761
  if (arg) {
11403
- const result = await client.resolveLogPath(arg);
11762
+ const result = await client.resolve(arg);
11404
11763
  if (result.status === "config-only") {
11405
11764
  printer_default.error(`Tunnel "${arg}" is saved but has not been started yet. No logs available.`);
11406
11765
  client.close();
@@ -11418,8 +11777,7 @@ async function handleLogs(args, follow) {
11418
11777
  }
11419
11778
  filePath = result.path;
11420
11779
  } else {
11421
- const paths = await client.getLogPaths();
11422
- filePath = paths.daemon;
11780
+ filePath = await client.daemonLogPath();
11423
11781
  }
11424
11782
  } catch (err) {
11425
11783
  printer_default.error(`Failed to resolve log path: ${errorMessage(err)}`);
@@ -11427,7 +11785,7 @@ async function handleLogs(args, follow) {
11427
11785
  return;
11428
11786
  }
11429
11787
  client.close();
11430
- if (!filePath || !import_node_fs4.default.existsSync(filePath)) {
11788
+ if (!filePath || !import_node_fs5.default.existsSync(filePath)) {
11431
11789
  printer_default.error(`Log file not found: ${filePath}`);
11432
11790
  process.exit(1);
11433
11791
  }
@@ -11438,18 +11796,18 @@ async function handleLogs(args, follow) {
11438
11796
  }
11439
11797
  }
11440
11798
  function printTail(filePath, lines) {
11441
- const content = import_node_fs4.default.readFileSync(filePath, "utf-8");
11799
+ const content = import_node_fs5.default.readFileSync(filePath, "utf-8");
11442
11800
  const allLines = content.split("\n");
11443
11801
  const tail = allLines.slice(-lines).join("\n");
11444
11802
  process.stdout.write(tail);
11445
11803
  if (!tail.endsWith("\n")) process.stdout.write("\n");
11446
11804
  }
11447
11805
  async function followFile(filePath) {
11448
- if (import_node_fs4.default.existsSync(filePath)) printTail(filePath, 20);
11449
- let fileSize = import_node_fs4.default.existsSync(filePath) ? import_node_fs4.default.statSync(filePath).size : 0;
11806
+ if (import_node_fs5.default.existsSync(filePath)) printTail(filePath, 20);
11807
+ let fileSize = import_node_fs5.default.existsSync(filePath) ? import_node_fs5.default.statSync(filePath).size : 0;
11450
11808
  let watcher = null;
11451
11809
  const openStream = () => {
11452
- const stream = import_node_fs4.default.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
11810
+ const stream = import_node_fs5.default.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
11453
11811
  stream.on("data", (chunk) => {
11454
11812
  process.stdout.write(chunk);
11455
11813
  fileSize += Buffer.byteLength(chunk, "utf-8");
@@ -11457,9 +11815,9 @@ async function followFile(filePath) {
11457
11815
  stream.on("error", () => {
11458
11816
  });
11459
11817
  };
11460
- watcher = import_node_fs4.default.watch(filePath, { persistent: true }, (event2) => {
11818
+ watcher = import_node_fs5.default.watch(filePath, { persistent: true }, (event2) => {
11461
11819
  if (event2 === "change") {
11462
- const stat = import_node_fs4.default.existsSync(filePath) ? import_node_fs4.default.statSync(filePath) : null;
11820
+ const stat = import_node_fs5.default.existsSync(filePath) ? import_node_fs5.default.statSync(filePath) : null;
11463
11821
  if (!stat || stat.size < fileSize) {
11464
11822
  fileSize = 0;
11465
11823
  }
@@ -11473,13 +11831,13 @@ async function followFile(filePath) {
11473
11831
  });
11474
11832
  });
11475
11833
  }
11476
- var import_node_fs4;
11834
+ var import_node_fs5;
11477
11835
  var init_logsCommand = __esm({
11478
11836
  "src/cli/subcommand/handlers/logsCommand.ts"() {
11479
11837
  "use strict";
11480
11838
  init_cjs_shims();
11481
- import_node_fs4 = __toESM(require("fs"), 1);
11482
- init_tunnelClient();
11839
+ import_node_fs5 = __toESM(require("fs"), 1);
11840
+ init_logLookup();
11483
11841
  init_printer();
11484
11842
  init_util();
11485
11843
  }
@@ -11505,26 +11863,39 @@ async function handleLog(args) {
11505
11863
  printLogHelp();
11506
11864
  }
11507
11865
  }
11866
+ function parseLevel(arg) {
11867
+ const level = arg.toLowerCase();
11868
+ if (!VALID_LEVELS.includes(level)) {
11869
+ printer_default.error(`Invalid log level: "${level}". Must be one of: ${VALID_LEVELS.join(", ")}`);
11870
+ process.exit(1);
11871
+ }
11872
+ return level;
11873
+ }
11874
+ function handleLogLevelWithoutDaemon(level) {
11875
+ if (!level) {
11876
+ printer_default.print(`Log level: ${configuredLogLevel()}`);
11877
+ return;
11878
+ }
11879
+ writeDaemonConfig({ logLevel: level });
11880
+ printer_default.success(`Log level set to "${level}". The daemon uses it when it starts.`);
11881
+ }
11508
11882
  async function handleLogLevel(args) {
11883
+ const level = args.length > 0 ? parseLevel(args[0]) : void 0;
11509
11884
  const client = new TunnelClient();
11510
11885
  try {
11511
- await client.ensureDaemon();
11886
+ if (!client.connectIfRunning()) {
11887
+ handleLogLevelWithoutDaemon(level);
11888
+ return;
11889
+ }
11512
11890
  } catch (err) {
11513
11891
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11514
11892
  return;
11515
11893
  }
11516
11894
  try {
11517
- if (args.length === 0) {
11518
- const level2 = await client.getLogLevel();
11519
- printer_default.print(`Log level: ${level2}`);
11895
+ if (!level) {
11896
+ printer_default.print(`Log level: ${await client.getLogLevel()}`);
11520
11897
  return;
11521
11898
  }
11522
- const level = args[0].toLowerCase();
11523
- if (!VALID_LEVELS.includes(level)) {
11524
- printer_default.error(`Invalid log level: "${level}". Must be one of: ${VALID_LEVELS.join(", ")}`);
11525
- client.close();
11526
- process.exit(1);
11527
- }
11528
11899
  await client.setLogLevel(level);
11529
11900
  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.`);
11530
11901
  } catch (err) {
@@ -11534,21 +11905,20 @@ async function handleLogLevel(args) {
11534
11905
  }
11535
11906
  }
11536
11907
  async function handleLogPath(args) {
11537
- const client = new TunnelClient();
11908
+ let client;
11538
11909
  try {
11539
- await client.ensureDaemon();
11910
+ client = openLogLookup();
11540
11911
  } catch (err) {
11541
11912
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11542
11913
  return;
11543
11914
  }
11544
11915
  try {
11545
11916
  if (args.length === 0) {
11546
- const paths = await client.getLogPaths();
11547
- printer_default.print(paths.daemon);
11917
+ printer_default.print(await client.daemonLogPath());
11548
11918
  return;
11549
11919
  }
11550
11920
  const arg = args[0];
11551
- const result = await client.resolveLogPath(arg);
11921
+ const result = await client.resolve(arg);
11552
11922
  switch (result.status) {
11553
11923
  case "running":
11554
11924
  case "historical":
@@ -11577,6 +11947,8 @@ var init_logCommand = __esm({
11577
11947
  "use strict";
11578
11948
  init_cjs_shims();
11579
11949
  init_tunnelClient();
11950
+ init_daemonConfig();
11951
+ init_logLookup();
11580
11952
  init_helpMessages();
11581
11953
  init_printer();
11582
11954
  init_util();
@@ -11593,7 +11965,10 @@ async function handleRestart(args) {
11593
11965
  const nameOrId = args[0];
11594
11966
  const client = new TunnelClient();
11595
11967
  try {
11596
- await client.ensureDaemon();
11968
+ if (!client.connectIfRunning()) {
11969
+ printer_default.error(tunnelNotRunningMessage(nameOrId));
11970
+ process.exit(1);
11971
+ }
11597
11972
  } catch (err) {
11598
11973
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11599
11974
  return;
@@ -11631,6 +12006,100 @@ var init_restartCommand = __esm({
11631
12006
  init_printer();
11632
12007
  init_util();
11633
12008
  init_startCli();
12009
+ init_noDaemon();
12010
+ }
12011
+ });
12012
+
12013
+ // src/devices/removeDevice.ts
12014
+ function machineDeviceRemoveDependencies(background) {
12015
+ return {
12016
+ background,
12017
+ foreground: machineForegroundStopDependencies(),
12018
+ clearIdentity: clearDeviceIdentity,
12019
+ isInteractive: isInteractiveTerminal,
12020
+ prompter: terminalPrompter,
12021
+ print: (message) => printer_default.print(message),
12022
+ printSuccess: (message) => printer_default.success(message),
12023
+ printError: (message) => printer_default.error(message)
12024
+ };
12025
+ }
12026
+ async function readActivity(dependencies) {
12027
+ const reading = await readBackgroundAgent(dependencies.background);
12028
+ return {
12029
+ identity: dependencies.background.readIdentity(),
12030
+ background: reading && isAgentRunning(reading.status) ? reading : null,
12031
+ foreground: dependencies.background.readForegroundAgent()
12032
+ };
12033
+ }
12034
+ function describeActivity(activity) {
12035
+ const { identity, background, foreground } = activity;
12036
+ const lines = [];
12037
+ if (identity) {
12038
+ const deviceAgentId = identity.device_agent_id ?? "(id not yet assigned)";
12039
+ lines.push(`This machine is device ${deviceAgentId} on ${identity.server}.`);
12040
+ }
12041
+ if (background) {
12042
+ lines.push(`The device agent runs in the background: ${describeAgent(background)}.`);
12043
+ }
12044
+ if (foreground) {
12045
+ lines.push(`The device agent runs in another terminal, PID ${foreground.pid}.`);
12046
+ }
12047
+ if (background || foreground) {
12048
+ lines.push("Removing it stops the agent, and the device shows offline in the dashboard.");
12049
+ } else {
12050
+ lines.push("The device is not connected now.");
12051
+ }
12052
+ return lines;
12053
+ }
12054
+ async function confirmed(options, dependencies) {
12055
+ if (options.skipConfirmation) {
12056
+ return true;
12057
+ }
12058
+ const answer = await dependencies.prompter.ask("Remove this device from this machine? [y/N] ");
12059
+ return YES_ANSWER2.test(answer.trim());
12060
+ }
12061
+ async function runDeviceRemove(options, dependencies) {
12062
+ const activity = await readActivity(dependencies);
12063
+ if (!activity.identity && !activity.background && !activity.foreground) {
12064
+ dependencies.print(import_picocolors13.default.yellow("This machine is not enrolled."));
12065
+ return EXIT_OK;
12066
+ }
12067
+ if (!options.skipConfirmation && !dependencies.isInteractive()) {
12068
+ dependencies.printError(NO_TERMINAL_MESSAGE2);
12069
+ return EXIT_FAILED;
12070
+ }
12071
+ describeActivity(activity).forEach((line) => dependencies.print(line));
12072
+ if (!await confirmed(options, dependencies)) {
12073
+ dependencies.print("Nothing removed.");
12074
+ return EXIT_OK;
12075
+ }
12076
+ if (!await stopAgentBeforeRemove(dependencies.background)) {
12077
+ return EXIT_FAILED;
12078
+ }
12079
+ if (!await stopForegroundAgentBeforeRemove(dependencies.foreground)) {
12080
+ return EXIT_FAILED;
12081
+ }
12082
+ dependencies.background.forgetSavedAgent();
12083
+ if (dependencies.clearIdentity()) {
12084
+ dependencies.printSuccess("Local device credential removed.");
12085
+ dependencies.print(import_picocolors13.default.gray("The device still exists in the dashboard. Delete it there to revoke it."));
12086
+ }
12087
+ return EXIT_OK;
12088
+ }
12089
+ var import_picocolors13, YES_ANSWER2, NO_TERMINAL_MESSAGE2;
12090
+ var init_removeDevice = __esm({
12091
+ "src/devices/removeDevice.ts"() {
12092
+ "use strict";
12093
+ init_cjs_shims();
12094
+ import_picocolors13 = __toESM(require("picocolors"), 1);
12095
+ init_deviceIdentity();
12096
+ init_backgroundAgent();
12097
+ init_foregroundAgent();
12098
+ init_prompts();
12099
+ init_deviceLogin();
12100
+ init_printer();
12101
+ YES_ANSWER2 = /^y(es)?$/i;
12102
+ NO_TERMINAL_MESSAGE2 = "pinggy device remove asks before it removes the device. Run it in a terminal, or add -f to remove without asking.";
11634
12103
  }
11635
12104
  });
11636
12105
 
@@ -11687,7 +12156,10 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
11687
12156
  await handleDeviceStatus(background);
11688
12157
  return;
11689
12158
  case DeviceVerb.Remove:
11690
- exitUnlessOk(await handleDeviceRemove(background));
12159
+ exitUnlessOk(await runDeviceRemove(
12160
+ { skipConfirmation: Boolean(values.force) },
12161
+ machineDeviceRemoveDependencies(background)
12162
+ ));
11691
12163
  return;
11692
12164
  default:
11693
12165
  if (verb === "help" || verb === "--help" || verb === "-h") {
@@ -11713,7 +12185,15 @@ function devicesSpellingMessage(args) {
11713
12185
  return `"pinggy devices" is now "pinggy device". Run: pinggy device ${suggestion}`;
11714
12186
  }
11715
12187
  async function mayRunInForeground(background) {
11716
- const refusal = await foregroundRefusal(background);
12188
+ const refusal = foregroundAgentRefusal(background.readForegroundAgent()) ?? await foregroundRefusal(background);
12189
+ if (refusal) {
12190
+ printer_default.error(refusal);
12191
+ return false;
12192
+ }
12193
+ return true;
12194
+ }
12195
+ function mayRunInBackground(background) {
12196
+ const refusal = foregroundAgentRefusal(background.readForegroundAgent());
11717
12197
  if (refusal) {
11718
12198
  printer_default.error(refusal);
11719
12199
  return false;
@@ -11725,6 +12205,7 @@ async function handleDeviceLogin(manage, name, inBackground, background) {
11725
12205
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
11726
12206
  return runDeviceLogin({ manage, name });
11727
12207
  }
12208
+ if (!mayRunInBackground(background)) return EXIT_FAILED;
11728
12209
  return runDeviceLogin({ manage, name }, {
11729
12210
  ...machineDeviceLoginDependencies(),
11730
12211
  runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
@@ -11737,6 +12218,7 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
11737
12218
  return EXIT_FAILED;
11738
12219
  }
11739
12220
  if (inBackground) {
12221
+ if (!mayRunInBackground(background)) return EXIT_FAILED;
11740
12222
  return startAgentInBackground(target, background);
11741
12223
  }
11742
12224
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
@@ -11746,33 +12228,26 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
11746
12228
  async function handleDeviceStatus(background) {
11747
12229
  const identity = background.readIdentity();
11748
12230
  if (!identity) {
11749
- printer_default.print(import_picocolors13.default.yellow("This machine is not enrolled. Run: pinggy device login"));
12231
+ printer_default.print(import_picocolors14.default.yellow("This machine is not enrolled. Run: pinggy device login"));
11750
12232
  return;
11751
12233
  }
11752
- printer_default.print(` Device id ${identity.device_agent_id ?? import_picocolors13.default.gray("not yet assigned")}`);
12234
+ printer_default.print(` Device id ${identity.device_agent_id ?? import_picocolors14.default.gray("not yet assigned")}`);
11753
12235
  printer_default.print(` Server ${identity.server}`);
11754
12236
  printer_default.print(` Token ${maskToken(identity.token)}`);
11755
- printer_default.print(` Enrolled ${identity.enrolled_at ?? import_picocolors13.default.gray("never")}`);
11756
- await printBackgroundStatus(background);
11757
- }
11758
- async function handleDeviceRemove(background) {
11759
- if (!await stopAgentBeforeRemove(background)) {
11760
- return EXIT_FAILED;
12237
+ printer_default.print(` Enrolled ${identity.enrolled_at ?? import_picocolors14.default.gray("never")}`);
12238
+ printer_default.print(` Autostart ${background.hasSavedAgent() ? "on, starts with the daemon" : import_picocolors14.default.gray("off")}`);
12239
+ const foreground = background.readForegroundAgent();
12240
+ if (foreground) {
12241
+ printer_default.print(` Foreground running in another terminal, PID ${foreground.pid}`);
11761
12242
  }
11762
- if (clearDeviceIdentity()) {
11763
- printer_default.success("Local device credential removed.");
11764
- printer_default.print(import_picocolors13.default.gray("The device still exists in the dashboard. Delete it there to revoke it."));
11765
- } else {
11766
- printer_default.print(import_picocolors13.default.yellow("This machine is not enrolled."));
11767
- }
11768
- return EXIT_OK;
12243
+ await printBackgroundStatus(background);
11769
12244
  }
11770
- var import_picocolors13, DeviceVerb, DEVICE_AGENT_TOKEN_VARIABLE;
12245
+ var import_picocolors14, DeviceVerb, DEVICE_AGENT_TOKEN_VARIABLE;
11771
12246
  var init_deviceCommand = __esm({
11772
12247
  "src/cli/subcommand/handlers/deviceCommand.ts"() {
11773
12248
  "use strict";
11774
12249
  init_cjs_shims();
11775
- import_picocolors13 = __toESM(require("picocolors"), 1);
12250
+ import_picocolors14 = __toESM(require("picocolors"), 1);
11776
12251
  init_options();
11777
12252
  init_parseArgs();
11778
12253
  init_logger();
@@ -11782,6 +12257,8 @@ var init_deviceCommand = __esm({
11782
12257
  init_deviceIdentity();
11783
12258
  init_deviceLogin();
11784
12259
  init_backgroundAgent();
12260
+ init_foregroundAgent();
12261
+ init_removeDevice();
11785
12262
  DeviceVerb = {
11786
12263
  Login: "login",
11787
12264
  Connect: "connect",
@@ -12132,7 +12609,7 @@ async function main() {
12132
12609
  printer_default.fatal(error);
12133
12610
  }
12134
12611
  }
12135
- var import_url2, import_process, import_fs13, currentFile, entryFile;
12612
+ var import_url2, import_process, import_fs14, currentFile, entryFile;
12136
12613
  var init_main = __esm({
12137
12614
  "src/main.ts"() {
12138
12615
  "use strict";
@@ -12147,7 +12624,7 @@ var init_main = __esm({
12147
12624
  init_handler();
12148
12625
  import_url2 = require("url");
12149
12626
  import_process = require("process");
12150
- import_fs13 = require("fs");
12627
+ import_fs14 = require("fs");
12151
12628
  init_remoteManagement();
12152
12629
  init_buildAndStartTunnel();
12153
12630
  init_subcommands();
@@ -12157,7 +12634,7 @@ var init_main = __esm({
12157
12634
  currentFile = (0, import_url2.fileURLToPath)(importMetaUrl);
12158
12635
  entryFile = null;
12159
12636
  try {
12160
- entryFile = import_process.argv[1] ? (0, import_fs13.realpathSync)(import_process.argv[1]) : null;
12637
+ entryFile = import_process.argv[1] ? (0, import_fs14.realpathSync)(import_process.argv[1]) : null;
12161
12638
  } catch (e) {
12162
12639
  entryFile = null;
12163
12640
  }
@@ -12199,13 +12676,13 @@ var init_wsProtocol = __esm({
12199
12676
 
12200
12677
  // src/daemon/lifecycle/stateStore.ts
12201
12678
  function getStatePath() {
12202
- return import_node_path3.default.join(getPinggyConfigDir(), STATE_FILENAME);
12679
+ return import_node_path4.default.join(getPinggyConfigDir(), STATE_FILENAME);
12203
12680
  }
12204
12681
  function loadDaemonState() {
12205
12682
  const statePath = getStatePath();
12206
12683
  try {
12207
- if (!import_node_fs5.default.existsSync(statePath)) return null;
12208
- const raw = import_node_fs5.default.readFileSync(statePath, "utf-8");
12684
+ if (!import_node_fs6.default.existsSync(statePath)) return null;
12685
+ const raw = import_node_fs6.default.readFileSync(statePath, "utf-8");
12209
12686
  const state = JSON.parse(raw);
12210
12687
  if (!Array.isArray(state.tunnels)) return null;
12211
12688
  return state;
@@ -12219,8 +12696,8 @@ function persistDaemonState(state) {
12219
12696
  const tmpPath = statePath + ".tmp";
12220
12697
  try {
12221
12698
  state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
12222
- import_node_fs5.default.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
12223
- import_node_fs5.default.renameSync(tmpPath, statePath);
12699
+ import_node_fs6.default.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
12700
+ import_node_fs6.default.renameSync(tmpPath, statePath);
12224
12701
  } catch (err) {
12225
12702
  logger.error("Failed to persist daemon state", { error: errorMessage(err) });
12226
12703
  }
@@ -12228,8 +12705,8 @@ function persistDaemonState(state) {
12228
12705
  function clearDaemonState() {
12229
12706
  const statePath = getStatePath();
12230
12707
  try {
12231
- if (import_node_fs5.default.existsSync(statePath)) {
12232
- import_node_fs5.default.unlinkSync(statePath);
12708
+ if (import_node_fs6.default.existsSync(statePath)) {
12709
+ import_node_fs6.default.unlinkSync(statePath);
12233
12710
  }
12234
12711
  } catch {
12235
12712
  }
@@ -12241,13 +12718,13 @@ function addTunnelToState(state, tunnel) {
12241
12718
  function removeTunnelFromState(state, tunnelId) {
12242
12719
  state.tunnels = state.tunnels.filter((t) => t.tunnelId !== tunnelId);
12243
12720
  }
12244
- var import_node_fs5, import_node_path3, STATE_FILENAME;
12721
+ var import_node_fs6, import_node_path4, STATE_FILENAME;
12245
12722
  var init_stateStore = __esm({
12246
12723
  "src/daemon/lifecycle/stateStore.ts"() {
12247
12724
  "use strict";
12248
12725
  init_cjs_shims();
12249
- import_node_fs5 = __toESM(require("fs"), 1);
12250
- import_node_path3 = __toESM(require("path"), 1);
12726
+ import_node_fs6 = __toESM(require("fs"), 1);
12727
+ import_node_path4 = __toESM(require("path"), 1);
12251
12728
  init_configDir();
12252
12729
  init_logger();
12253
12730
  init_util();
@@ -12259,50 +12736,34 @@ var init_stateStore = __esm({
12259
12736
  function parseOrigin(req) {
12260
12737
  const raw = req.headers["x-pinggy-origin"];
12261
12738
  const v = Array.isArray(raw) ? raw[0] : raw;
12262
- return v && VALID_ORIGINS.includes(v) ? v : "cli";
12739
+ return v && TUNNEL_ORIGINS.includes(v) ? v : "cli";
12263
12740
  }
12264
12741
  function parseBody(method, body) {
12265
12742
  if (method === "GET") return void 0;
12266
12743
  if (!body) return {};
12267
12744
  return JSON.parse(body);
12268
12745
  }
12269
- function parseTunnelLogFilename(filename) {
12270
- const base = filename.replace(/\.log$/, "");
12271
- const parts = base.split("__");
12272
- if (parts.length < 2) return null;
12273
- const origin = parts[0];
12274
- if (!VALID_ORIGINS.includes(origin)) return null;
12275
- if (parts.length === 2) {
12276
- const second = parts[1];
12277
- if (UUID_RE.test(second)) return { origin, tunnelId: second };
12278
- return { origin, name: second };
12279
- }
12280
- const tunnelId = parts[parts.length - 1];
12281
- const name = parts.slice(1, -1).join("__");
12282
- return { origin, name, tunnelId };
12283
- }
12284
- var import_node_http2, import_node_fs6, import_node_path4, import_ws4, VALID_ORIGINS, UUID_RE, IPCServer;
12746
+ var import_node_http2, import_node_fs7, import_node_path5, import_ws4, IPCServer;
12285
12747
  var init_ipcServer = __esm({
12286
12748
  "src/daemon/ipc/ipcServer.ts"() {
12287
12749
  "use strict";
12288
12750
  init_cjs_shims();
12289
12751
  import_node_http2 = __toESM(require("http"), 1);
12290
- import_node_fs6 = __toESM(require("fs"), 1);
12291
- import_node_path4 = __toESM(require("path"), 1);
12752
+ import_node_fs7 = __toESM(require("fs"), 1);
12753
+ import_node_path5 = __toESM(require("path"), 1);
12292
12754
  import_ws4 = require("ws");
12293
12755
  init_main();
12294
12756
  init_logger();
12295
12757
  init_tunnelLogger();
12296
12758
  init_configStore();
12297
12759
  init_configDir();
12760
+ init_logPaths();
12298
12761
  init_util();
12299
12762
  init_ipcRoutes();
12300
12763
  init_wsProtocol();
12301
12764
  init_types();
12302
12765
  init_daemonChild();
12303
12766
  init_stateStore();
12304
- VALID_ORIGINS = ["app", "cli", "remote", "device"];
12305
- UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12306
12767
  IPCServer = class {
12307
12768
  constructor() {
12308
12769
  this.sessions = /* @__PURE__ */ new Map();
@@ -12438,8 +12899,8 @@ var init_ipcServer = __esm({
12438
12899
  const logDir = getTunnelLogDir();
12439
12900
  const daemonPath = getDaemonLogPath();
12440
12901
  const tunnels = [];
12441
- if (import_node_fs6.default.existsSync(logDir)) {
12442
- const files = import_node_fs6.default.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
12902
+ const files = listTunnelLogFiles();
12903
+ if (files.length > 0) {
12443
12904
  const manager = TunnelManager.getInstance();
12444
12905
  const activeIds = manager.getActiveTunnelIds();
12445
12906
  const activeNames = /* @__PURE__ */ new Set();
@@ -12449,8 +12910,8 @@ var init_ipcServer = __esm({
12449
12910
  if (n) activeNames.add(n);
12450
12911
  }
12451
12912
  for (const file of files) {
12452
- const filePath = import_node_path4.default.join(logDir, file);
12453
- const stat = import_node_fs6.default.statSync(filePath);
12913
+ const filePath = import_node_path5.default.join(logDir, file);
12914
+ const stat = import_node_fs7.default.statSync(filePath);
12454
12915
  const parsed = parseTunnelLogFilename(file);
12455
12916
  if (!parsed) continue;
12456
12917
  const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
@@ -12557,7 +13018,6 @@ var init_ipcServer = __esm({
12557
13018
  }
12558
13019
  async resolveLogPath(q) {
12559
13020
  if (!q) return { status: "not-found" };
12560
- const logDir = getTunnelLogDir();
12561
13021
  const manager = TunnelManager.getInstance();
12562
13022
  const activeIds = manager.getActiveTunnelIds();
12563
13023
  for (const t of await manager.getAllTunnels()) {
@@ -12569,32 +13029,7 @@ var init_ipcServer = __esm({
12569
13029
  return { status: "running", path: logPath, tunnelId: t.tunnelid, name, origin, running: true };
12570
13030
  }
12571
13031
  }
12572
- if (import_node_fs6.default.existsSync(logDir)) {
12573
- const files = import_node_fs6.default.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
12574
- const matches = [];
12575
- for (const file of files) {
12576
- const parsed = parseTunnelLogFilename(file);
12577
- if (!parsed) continue;
12578
- const nameMatch = parsed.name !== void 0 && parsed.name === q;
12579
- const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
12580
- if (nameMatch || idMatch) {
12581
- const filePath = import_node_path4.default.join(logDir, file);
12582
- const stat = import_node_fs6.default.statSync(filePath);
12583
- matches.push({ path: filePath, mtime: stat.mtimeMs, tunnelId: parsed.tunnelId, name: parsed.name, origin: parsed.origin });
12584
- }
12585
- }
12586
- if (matches.length > 0) {
12587
- matches.sort((a, b) => b.mtime - a.mtime);
12588
- const best = matches[0];
12589
- return { status: "historical", path: best.path, tunnelId: best.tunnelId, name: best.name, origin: best.origin, running: false };
12590
- }
12591
- }
12592
- const saved = listSavedConfigs();
12593
- const matchedConfig = saved.find((c) => c.name === q || c.configId === q || c.configId.startsWith(q));
12594
- if (matchedConfig) {
12595
- return { status: "config-only", name: matchedConfig.name, configId: matchedConfig.configId };
12596
- }
12597
- return { status: "not-found" };
13032
+ return resolveStoppedLogPath(q);
12598
13033
  }
12599
13034
  setupWebSocket() {
12600
13035
  this.server.on("upgrade", (req, socket, head) => {
@@ -13004,7 +13439,7 @@ var init_deviceAgentHost = __esm({
13004
13439
  this.statusValue = stoppedStatus();
13005
13440
  /** Bumped on every start and stop. A run's reporter whose number is old belongs to a run that ended. */
13006
13441
  this.generation = 0;
13007
- /** Set once the daemon shuts down. Nothing starts and nothing more reaches daemon-state.json. */
13442
+ /** Set once the daemon shuts down. Nothing starts and nothing more is recorded. */
13008
13443
  this.closed = false;
13009
13444
  /** Start and stop chain on this, so 1 finishes before the next begins. */
13010
13445
  this.queue = Promise.resolve();
@@ -13042,8 +13477,8 @@ var init_deviceAgentHost = __esm({
13042
13477
  });
13043
13478
  }
13044
13479
  /**
13045
- * The daemon is shutting down. Stops the run at once, outside the queue, and writes nothing to
13046
- * daemon-state.json: the shutdown deletes that file, and a write after it would bring the file back.
13480
+ * The daemon is shutting down. Stops the run at once, outside the queue. Records nothing, so the saved
13481
+ * agent stays and the next daemon start runs it again.
13047
13482
  */
13048
13483
  close() {
13049
13484
  this.closed = true;
@@ -13086,9 +13521,6 @@ var init_deviceAgentHost = __esm({
13086
13521
  this.current = null;
13087
13522
  this.generation += 1;
13088
13523
  this.statusValue = { ...this.statusValue, state: DeviceAgentState.Stopped, connectedAt: null };
13089
- if (!this.closed) {
13090
- this.dependencies.recordStopped();
13091
- }
13092
13524
  await current.run.stop();
13093
13525
  logger.info("Device agent stopped in the daemon");
13094
13526
  }
@@ -13152,6 +13584,66 @@ var init_deviceAgentHost = __esm({
13152
13584
  }
13153
13585
  });
13154
13586
 
13587
+ // src/daemon/lifecycle/daemonLock.ts
13588
+ function readLock(lockPath) {
13589
+ try {
13590
+ const record = JSON.parse(import_node_fs8.default.readFileSync(lockPath, "utf-8"));
13591
+ return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
13592
+ } catch {
13593
+ return null;
13594
+ }
13595
+ }
13596
+ function isUnreadableLockOld(lockPath) {
13597
+ try {
13598
+ return Date.now() - import_node_fs8.default.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
13599
+ } catch {
13600
+ return true;
13601
+ }
13602
+ }
13603
+ function isStale(lockPath, holder) {
13604
+ if (!holder) return isUnreadableLockOld(lockPath);
13605
+ return startedBeforeBoot(holder.started_at) || !isProcessAlive(holder.pid);
13606
+ }
13607
+ function createLock(lockPath, record) {
13608
+ try {
13609
+ import_node_fs8.default.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
13610
+ return true;
13611
+ } catch (err) {
13612
+ if (err.code === "EEXIST") return false;
13613
+ throw err;
13614
+ }
13615
+ }
13616
+ function acquireDaemonLock() {
13617
+ ensurePinggyConfigDir();
13618
+ const lockPath = getDaemonLockPath();
13619
+ const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
13620
+ if (createLock(lockPath, record)) return true;
13621
+ const holder = readLock(lockPath);
13622
+ if (holder?.pid === process.pid) return true;
13623
+ if (!isStale(lockPath, holder)) return false;
13624
+ logger.info("Stale daemon.lock found, replacing it", { stalePid: holder?.pid });
13625
+ import_node_fs8.default.rmSync(lockPath, { force: true });
13626
+ return createLock(lockPath, record);
13627
+ }
13628
+ function releaseDaemonLock() {
13629
+ const lockPath = getDaemonLockPath();
13630
+ if (readLock(lockPath)?.pid === process.pid) {
13631
+ import_node_fs8.default.rmSync(lockPath, { force: true });
13632
+ }
13633
+ }
13634
+ var import_node_fs8, UNREADABLE_LOCK_GRACE_MILLIS;
13635
+ var init_daemonLock = __esm({
13636
+ "src/daemon/lifecycle/daemonLock.ts"() {
13637
+ "use strict";
13638
+ init_cjs_shims();
13639
+ import_node_fs8 = __toESM(require("fs"), 1);
13640
+ init_configDir();
13641
+ init_daemonManager();
13642
+ init_logger();
13643
+ UNREADABLE_LOCK_GRACE_MILLIS = 1e4;
13644
+ }
13645
+ });
13646
+
13155
13647
  // src/daemon/lifecycle/daemonChild.ts
13156
13648
  var daemonChild_exports = {};
13157
13649
  __export(daemonChild_exports, {
@@ -13160,8 +13652,6 @@ __export(daemonChild_exports, {
13160
13652
  removeDaemonInfo: () => removeDaemonInfo,
13161
13653
  runDaemonChild: () => runDaemonChild,
13162
13654
  setDaemonSessionTracker: () => setDaemonSessionTracker,
13163
- trackDeviceAgentStart: () => trackDeviceAgentStart,
13164
- trackDeviceAgentStop: () => trackDeviceAgentStop,
13165
13655
  trackIPCTunnelStart: () => trackIPCTunnelStart,
13166
13656
  trackTunnelStart: () => trackTunnelStart,
13167
13657
  trackTunnelStop: () => trackTunnelStop
@@ -13176,13 +13666,14 @@ function writeDaemonInfo(info) {
13176
13666
  ensurePinggyConfigDir();
13177
13667
  const infoPath = getDaemonInfoPath();
13178
13668
  const tmpPath = infoPath + ".tmp";
13179
- import_node_fs7.default.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
13180
- import_node_fs7.default.renameSync(tmpPath, infoPath);
13669
+ import_node_fs9.default.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
13670
+ import_node_fs9.default.renameSync(tmpPath, infoPath);
13181
13671
  }
13182
13672
  function removeDaemonInfo() {
13183
13673
  try {
13184
13674
  const infoPath = getDaemonInfoPath();
13185
- if (import_node_fs7.default.existsSync(infoPath)) import_node_fs7.default.unlinkSync(infoPath);
13675
+ const info = JSON.parse(import_node_fs9.default.readFileSync(infoPath, "utf-8"));
13676
+ if (info.pid === process.pid) import_node_fs9.default.unlinkSync(infoPath);
13186
13677
  } catch {
13187
13678
  }
13188
13679
  }
@@ -13207,27 +13698,23 @@ function trackTunnelStop(tunnelId) {
13207
13698
  persistDaemonState(daemonState);
13208
13699
  sessionTrackerRef?.removeTunnel(tunnelId);
13209
13700
  }
13210
- function trackDeviceAgentStart(startedBy) {
13211
- daemonState.deviceAgent = { startedAt: (/* @__PURE__ */ new Date()).toISOString(), startedBy };
13212
- persistDaemonState(daemonState);
13213
- }
13214
- function trackDeviceAgentStop() {
13215
- if (!daemonState.deviceAgent) return;
13216
- delete daemonState.deviceAgent;
13217
- persistDaemonState(daemonState);
13218
- }
13219
- async function restoreCrashedDeviceAgent(host, saved) {
13701
+ async function startSavedDeviceAgent(host, saved) {
13702
+ const foreground = readForegroundAgent();
13703
+ if (foreground) {
13704
+ logger.info("Device agent not started: it runs in a terminal", { pid: foreground.pid });
13705
+ return;
13706
+ }
13220
13707
  try {
13221
13708
  const result = await host.start(saved.startedBy);
13222
13709
  if (isErrorResponse(result)) {
13223
- logger.warn("Crash recovery: device agent not restored", { reason: result.message });
13224
- trackDeviceAgentStop();
13710
+ logger.warn("Saved device agent not started", { reason: result.message });
13711
+ forgetDeviceAgent();
13225
13712
  return;
13226
13713
  }
13227
- logger.info("Crash recovery: device agent restored");
13714
+ logger.info("Saved device agent started");
13228
13715
  } catch (err) {
13229
- logger.error("Crash recovery: device agent failed to start", { error: errorMessage(err) });
13230
- trackDeviceAgentStop();
13716
+ logger.error("Saved device agent failed to start", { error: errorMessage(err) });
13717
+ forgetDeviceAgent();
13231
13718
  }
13232
13719
  }
13233
13720
  function trackIPCTunnelStart(tunnelId, origin, mode = SessionMode.Detached) {
@@ -13322,9 +13809,7 @@ async function runDaemonChild(opts = {}) {
13322
13809
  const exitOnFailure = opts.exitOnFailure ?? true;
13323
13810
  daemonHost = opts.host ?? DaemonHost.CLI;
13324
13811
  ensurePinggyConfigDir();
13325
- const persistedLevel = readDaemonConfig()?.logLevel;
13326
- const envLevel = process.env.PINGGY_LOG_LEVEL;
13327
- const initialLevel = persistedLevel ?? envLevel ?? "info";
13812
+ const initialLevel = configuredLogLevel();
13328
13813
  setLogLevel(initialLevel);
13329
13814
  ensurePinggyLogDir();
13330
13815
  const logPath = getDaemonLogPath();
@@ -13335,6 +13820,11 @@ async function runDaemonChild(opts = {}) {
13335
13820
  enableSdkLog: true
13336
13821
  });
13337
13822
  logger.info("Daemon starting", { pid: process.pid, inProcess: !installSignalHandlers });
13823
+ if (!acquireDaemonLock()) {
13824
+ logger.info("Another daemon holds daemon.lock. Exiting.");
13825
+ if (exitOnFailure) process.exit(0);
13826
+ throw new Error("Another pinggy daemon is running.");
13827
+ }
13338
13828
  const manager = TunnelManager.getInstance();
13339
13829
  const ipcServer = new IPCServer();
13340
13830
  const sessionTracker = new SessionTracker();
@@ -13357,6 +13847,10 @@ async function runDaemonChild(opts = {}) {
13357
13847
  removeDaemonInfo();
13358
13848
  } catch {
13359
13849
  }
13850
+ try {
13851
+ releaseDaemonLock();
13852
+ } catch {
13853
+ }
13360
13854
  try {
13361
13855
  clearDaemonState();
13362
13856
  } catch {
@@ -13399,14 +13893,10 @@ async function runDaemonChild(opts = {}) {
13399
13893
  try {
13400
13894
  const port = await ipcServer.listen();
13401
13895
  deviceAgentHost = new DeviceAgentHost(machineDeviceAgentHostDependencies(port, {
13402
- recordRunning: trackDeviceAgentStart,
13403
- recordStopped: trackDeviceAgentStop
13896
+ recordRunning: saveDeviceAgent,
13897
+ recordStopped: forgetDeviceAgent
13404
13898
  }));
13405
13899
  ipcServer.setDeviceAgentHost(deviceAgentHost);
13406
- const crashedDeviceAgent = loadDaemonState()?.deviceAgent;
13407
- if (crashedDeviceAgent) {
13408
- daemonState.deviceAgent = crashedDeviceAgent;
13409
- }
13410
13900
  const info = {
13411
13901
  pid: process.pid,
13412
13902
  port,
@@ -13430,8 +13920,9 @@ async function runDaemonChild(opts = {}) {
13430
13920
  } else {
13431
13921
  logger.info("No auto-start tunnels configured");
13432
13922
  }
13433
- if (crashedDeviceAgent) {
13434
- await restoreCrashedDeviceAgent(deviceAgentHost, crashedDeviceAgent);
13923
+ const savedAgent = savedDeviceAgent();
13924
+ if (savedAgent) {
13925
+ await startSavedDeviceAgent(deviceAgentHost, savedAgent);
13435
13926
  }
13436
13927
  logger.info("Daemon ready", { pid: process.pid, port });
13437
13928
  return {
@@ -13442,18 +13933,19 @@ async function runDaemonChild(opts = {}) {
13442
13933
  } catch (err) {
13443
13934
  logger.error("Daemon failed to start", { error: errorMessage(err) });
13444
13935
  removeDaemonInfo();
13936
+ releaseDaemonLock();
13445
13937
  if (exitOnFailure) {
13446
13938
  process.exit(1);
13447
13939
  }
13448
13940
  throw err;
13449
13941
  }
13450
13942
  }
13451
- var import_node_fs7, daemonState, daemonHost, sessionTrackerRef;
13943
+ var import_node_fs9, daemonState, daemonHost, sessionTrackerRef;
13452
13944
  var init_daemonChild = __esm({
13453
13945
  "src/daemon/lifecycle/daemonChild.ts"() {
13454
13946
  "use strict";
13455
13947
  init_cjs_shims();
13456
- import_node_fs7 = __toESM(require("fs"), 1);
13948
+ import_node_fs9 = __toESM(require("fs"), 1);
13457
13949
  init_ipcServer();
13458
13950
  init_sessionTracker();
13459
13951
  init_stateStore();
@@ -13464,9 +13956,11 @@ var init_daemonChild = __esm({
13464
13956
  init_tunnelLogger();
13465
13957
  init_configStore();
13466
13958
  init_daemonConfig();
13959
+ init_foregroundAgent();
13467
13960
  init_types();
13468
13961
  init_util();
13469
13962
  init_ipcRoutes();
13963
+ init_daemonLock();
13470
13964
  daemonState = { tunnels: [], lastUpdated: "" };
13471
13965
  daemonHost = DaemonHost.CLI;
13472
13966
  sessionTrackerRef = null;
@@ -13478,20 +13972,25 @@ function isProcessAlive(pid) {
13478
13972
  try {
13479
13973
  process.kill(pid, 0);
13480
13974
  return true;
13481
- } catch {
13482
- return false;
13975
+ } catch (err) {
13976
+ return err.code === "EPERM";
13483
13977
  }
13484
13978
  }
13979
+ function startedBeforeBoot(startedAt) {
13980
+ const startedAtMillis = Date.parse(startedAt);
13981
+ const bootMillis = Date.now() - import_node_os2.default.uptime() * 1e3;
13982
+ return Number.isNaN(startedAtMillis) || startedAtMillis < bootMillis - BOOT_TIME_TOLERANCE_MILLIS;
13983
+ }
13485
13984
  function getDaemonInfo() {
13486
13985
  const infoPath = getDaemonInfoPath();
13487
- if (!import_node_fs8.default.existsSync(infoPath)) return null;
13986
+ if (!import_node_fs10.default.existsSync(infoPath)) return null;
13488
13987
  try {
13489
- const data = JSON.parse(import_node_fs8.default.readFileSync(infoPath, "utf-8"));
13988
+ const data = JSON.parse(import_node_fs10.default.readFileSync(infoPath, "utf-8"));
13490
13989
  if (!data.pid || !data.port) return null;
13491
- if (!isProcessAlive(data.pid)) {
13990
+ if (startedBeforeBoot(data.startedAt) || !isProcessAlive(data.pid)) {
13492
13991
  logger.info("Stale daemon.json found, cleaning up", { stalePid: data.pid });
13493
13992
  try {
13494
- import_node_fs8.default.unlinkSync(infoPath);
13993
+ import_node_fs10.default.unlinkSync(infoPath);
13495
13994
  } catch {
13496
13995
  }
13497
13996
  return null;
@@ -13548,7 +14047,7 @@ async function startDaemon() {
13548
14047
  exitCode = code;
13549
14048
  });
13550
14049
  child.unref();
13551
- const info = await pollForDaemonInfo(DAEMON_SPAWN_TIMEOUT_MS, () => exited);
14050
+ const info = await pollForDaemonInfo(DAEMON_SPAWN_TIMEOUT_MS, () => exited && exitCode !== 0);
13552
14051
  if (!info) {
13553
14052
  const logPath = getDaemonLogPath();
13554
14053
  if (exited) {
@@ -13671,13 +14170,13 @@ async function waitForExit(pid, timeoutMs) {
13671
14170
  }
13672
14171
  return !isProcessAlive(pid);
13673
14172
  }
13674
- var import_node_os2, import_node_fs8, import_node_child_process2, inProcessHandle, DAEMON_SPAWN_TIMEOUT_MS, DAEMON_POLL_INTERVAL_MS;
14173
+ var import_node_os2, import_node_fs10, import_node_child_process2, inProcessHandle, DAEMON_SPAWN_TIMEOUT_MS, DAEMON_POLL_INTERVAL_MS, BOOT_TIME_TOLERANCE_MILLIS;
13675
14174
  var init_daemonManager = __esm({
13676
14175
  "src/daemon/lifecycle/daemonManager.ts"() {
13677
14176
  "use strict";
13678
14177
  init_cjs_shims();
13679
14178
  import_node_os2 = __toESM(require("os"), 1);
13680
- import_node_fs8 = __toESM(require("fs"), 1);
14179
+ import_node_fs10 = __toESM(require("fs"), 1);
13681
14180
  import_node_child_process2 = require("child_process");
13682
14181
  init_configDir();
13683
14182
  init_ipcRoutes();
@@ -13687,6 +14186,7 @@ var init_daemonManager = __esm({
13687
14186
  inProcessHandle = null;
13688
14187
  DAEMON_SPAWN_TIMEOUT_MS = 8e3;
13689
14188
  DAEMON_POLL_INTERVAL_MS = 200;
14189
+ BOOT_TIME_TOLERANCE_MILLIS = 6e4;
13690
14190
  }
13691
14191
  });
13692
14192
 
@@ -14122,7 +14622,22 @@ var init_tunnelClient = __esm({
14122
14622
  this.health = new DaemonHealth(() => this.ipc, this.stream);
14123
14623
  }
14124
14624
  async ensureDaemon() {
14125
- const info = await ensureDaemonRunning();
14625
+ this.bindDaemon(await ensureDaemonRunning());
14626
+ }
14627
+ /**
14628
+ * Connects to the daemon that runs now, and never starts one. For commands that only read state.
14629
+ * Throws when that daemon speaks another IPC version, as ensureDaemon() does.
14630
+ *
14631
+ * @returns false when no daemon runs
14632
+ */
14633
+ connectIfRunning() {
14634
+ const info = getDaemonInfo();
14635
+ if (!info) return false;
14636
+ if (!isIpcCompatible(info)) throw new Error(ipcMismatchMessage(info));
14637
+ this.bindDaemon(info);
14638
+ return true;
14639
+ }
14640
+ bindDaemon(info) {
14126
14641
  this.ipc = new IPCClient(info.port, this.origin);
14127
14642
  this.health.bindPid(info.pid);
14128
14643
  this.health.reset();