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.
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
@@ -3151,6 +3174,8 @@ var init_options = __esm({
3151
3174
  // Background mode (run tunnel in background via daemon)
3152
3175
  b: { type: "boolean", description: "Run tunnel in background via daemon. CLI exits after tunnel starts." },
3153
3176
  all: { type: "boolean", description: "Start all auto-start tunnels" },
3177
+ // `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
3178
+ foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
3154
3179
  // Internal daemon child marker
3155
3180
  "_daemon-child": { type: "boolean", description: "Internal: daemon child process marker", hidden: true },
3156
3181
  // Misc
@@ -3223,10 +3248,17 @@ function printHelpMessage() {
3223
3248
  console.log("\nBackground Mode:");
3224
3249
  console.log(" pinggy -l 3000 --b # Start tunnel in background");
3225
3250
  console.log(" pinggy start my-tunnel --b # Start saved tunnel in background");
3251
+ console.log("\nDevices (more: pinggy device --help):");
3252
+ console.log(" pinggy device login # Sign in by email. The agent runs in the background");
3253
+ console.log(" pinggy device login --foreground # Same, with the agent in this terminal");
3254
+ console.log(" pinggy device status # Show this device and its agent");
3255
+ console.log(" pinggy device stop # Stop the background agent");
3226
3256
  console.log("\nDaemon Lifecycle (also: pinggy d <command>):");
3227
3257
  console.log(" pinggy daemon start # Start the background daemon");
3228
3258
  console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
3229
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");
3230
3262
  }
3231
3263
  var init_help = __esm({
3232
3264
  "src/cli/help.ts"() {
@@ -4739,10 +4771,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
4739
4771
  }
4740
4772
  function storeJson(config, saveconf) {
4741
4773
  if (saveconf) {
4742
- const path12 = saveconf;
4774
+ const path13 = saveconf;
4743
4775
  try {
4744
- import_fs6.default.writeFileSync(path12, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
4745
- 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}`);
4746
4778
  } catch (err) {
4747
4779
  const msg = err instanceof Error ? err.message : String(err);
4748
4780
  logger.error("Error loading configuration:", msg);
@@ -7334,24 +7366,60 @@ var init_buildAndStartTunnel = __esm({
7334
7366
  });
7335
7367
 
7336
7368
  // src/daemon/lifecycle/serviceInstaller.ts
7337
- function resolveBinary() {
7338
- const isPkg = "pkg" in process;
7339
- 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) {
7340
7377
  try {
7341
- const bin = (0, import_node_child_process.execSync)(import_node_os.default.platform() === "win32" ? "where pinggy" : "which pinggy", {
7342
- encoding: "utf-8"
7343
- }).trim().split(/\r?\n/)[0];
7344
- return { program: bin, args: [] };
7378
+ return import_node_fs3.default.realpathSync(p);
7345
7379
  } catch {
7346
- return { program: process.execPath, args: [process.argv[1]] };
7380
+ return p;
7347
7381
  }
7348
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
+ }
7349
7417
  function getSystemdServicePath() {
7350
7418
  const dir = import_node_path2.default.join(import_node_os.default.homedir(), ".config", "systemd", "user");
7351
7419
  return import_node_path2.default.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
7352
7420
  }
7353
- function generateSystemdUnit(bin) {
7354
- const execStart = [bin.program, ...bin.args, "--_daemon-child"].join(" ");
7421
+ function generateSystemdUnit(program) {
7422
+ const execStart = `${program} --_daemon-child`;
7355
7423
  return `[Unit]
7356
7424
  Description=Pinggy Tunnel Daemon
7357
7425
  After=network-online.target
@@ -7367,18 +7435,17 @@ RestartSec=5
7367
7435
  WantedBy=default.target
7368
7436
  `;
7369
7437
  }
7370
- function installSystemd() {
7371
- const bin = resolveBinary();
7438
+ function installSystemd(program) {
7372
7439
  const servicePath = getSystemdServicePath();
7373
7440
  const dir = import_node_path2.default.dirname(servicePath);
7374
7441
  import_node_fs3.default.mkdirSync(dir, { recursive: true });
7375
- import_node_fs3.default.writeFileSync(servicePath, generateSystemdUnit(bin), "utf-8");
7376
- (0, import_node_child_process.execSync)("systemctl --user daemon-reload");
7377
- (0, import_node_child_process.execSync)(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`);
7378
- (0, import_node_child_process.execSync)(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`);
7379
- logger.info("systemd user service installed and started", { servicePath });
7380
- console.log(`Service installed: ${servicePath}`);
7381
- 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}`);
7382
7449
  }
7383
7450
  function uninstallSystemd() {
7384
7451
  const servicePath = getSystemdServicePath();
@@ -7389,17 +7456,18 @@ function uninstallSystemd() {
7389
7456
  }
7390
7457
  if (import_node_fs3.default.existsSync(servicePath)) {
7391
7458
  import_node_fs3.default.unlinkSync(servicePath);
7392
- (0, import_node_child_process.execSync)("systemctl --user daemon-reload");
7393
- 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();
7394
7462
  } else {
7395
- console.log("No systemd service found to remove.");
7463
+ printNotInstalled();
7396
7464
  }
7397
7465
  }
7398
7466
  function getLaunchdPlistPath() {
7399
7467
  return import_node_path2.default.join(import_node_os.default.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
7400
7468
  }
7401
- function generateLaunchdPlist(bin) {
7402
- const allArgs = [bin.program, ...bin.args, "--_daemon-child"];
7469
+ function generateLaunchdPlist(program) {
7470
+ const allArgs = [program, "--_daemon-child"];
7403
7471
  const programArgs = allArgs.map((p) => ` <string>${p}</string>`).join("\n");
7404
7472
  return `<?xml version="1.0" encoding="UTF-8"?>
7405
7473
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
@@ -7420,17 +7488,21 @@ ${programArgs}
7420
7488
  </plist>
7421
7489
  `;
7422
7490
  }
7423
- function installLaunchd() {
7424
- const bin = resolveBinary();
7491
+ function installLaunchd(program) {
7425
7492
  const plistPath = getLaunchdPlistPath();
7426
7493
  const dir = import_node_path2.default.dirname(plistPath);
7427
7494
  import_node_fs3.default.mkdirSync(dir, { recursive: true });
7428
- import_node_fs3.default.writeFileSync(plistPath, generateLaunchdPlist(bin), "utf-8");
7495
+ import_node_fs3.default.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
7429
7496
  const uid = process.getuid?.() ?? 501;
7430
7497
  try {
7431
7498
  (0, import_node_child_process.execSync)(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
7432
7499
  } catch {
7433
7500
  }
7501
+ loadLaunchdPlist(uid, plistPath);
7502
+ logger.info("launchd agent installed", { plistPath });
7503
+ printInstalled();
7504
+ }
7505
+ function loadLaunchdPlist(uid, plistPath) {
7434
7506
  try {
7435
7507
  (0, import_node_child_process.execSync)(`launchctl bootstrap gui/${uid} ${plistPath}`);
7436
7508
  } catch {
@@ -7439,8 +7511,6 @@ function installLaunchd() {
7439
7511
  } catch {
7440
7512
  }
7441
7513
  }
7442
- logger.info("launchd agent installed and started", { plistPath });
7443
- console.log(`Service installed and started: ${plistPath}`);
7444
7514
  }
7445
7515
  function uninstallLaunchd() {
7446
7516
  const plistPath = getLaunchdPlistPath();
@@ -7455,23 +7525,33 @@ function uninstallLaunchd() {
7455
7525
  }
7456
7526
  if (import_node_fs3.default.existsSync(plistPath)) {
7457
7527
  import_node_fs3.default.unlinkSync(plistPath);
7458
- console.log(`Service removed: ${plistPath}`);
7528
+ logger.info("launchd agent removed", { plistPath });
7529
+ printUninstalled();
7459
7530
  } else {
7460
- console.log("No launchd agent found to remove.");
7531
+ printNotInstalled();
7461
7532
  }
7462
7533
  }
7463
- function generateTaskXml(bin) {
7464
- const command = bin.program;
7465
- 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);
7466
7544
  return `<?xml version="1.0" encoding="UTF-16"?>
7467
7545
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
7468
7546
  <Triggers>
7469
7547
  <LogonTrigger>
7470
7548
  <Enabled>true</Enabled>
7549
+ <UserId>${user}</UserId>
7471
7550
  </LogonTrigger>
7472
7551
  </Triggers>
7473
7552
  <Principals>
7474
7553
  <Principal id="Author">
7554
+ <UserId>${user}</UserId>
7475
7555
  <LogonType>InteractiveToken</LogonType>
7476
7556
  <RunLevel>LeastPrivilege</RunLevel>
7477
7557
  </Principal>
@@ -7489,71 +7569,105 @@ function generateTaskXml(bin) {
7489
7569
  </Settings>
7490
7570
  <Actions>
7491
7571
  <Exec>
7492
- <Command>${command}</Command>${args ? `
7493
- <Arguments>${args}</Arguments>` : ""}
7572
+ <Command>${escapeXml(program)}</Command>
7573
+ <Arguments>daemon start</Arguments>
7494
7574
  </Exec>
7495
7575
  </Actions>
7496
7576
  </Task>`;
7497
7577
  }
7498
- function installWindows() {
7499
- const bin = resolveBinary();
7500
- const xml = generateTaskXml(bin);
7578
+ function createWindowsTask(program) {
7579
+ const xml = generateTaskXml(program, getWindowsUserId());
7501
7580
  const tmpPath = import_node_path2.default.join(import_node_os.default.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
7502
7581
  import_node_fs3.default.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
7503
7582
  try {
7504
- (0, import_node_child_process.execFileSync)("schtasks", [
7505
- "/Create",
7506
- "/TN",
7507
- WINDOWS_TASK_NAME,
7508
- "/XML",
7509
- tmpPath,
7510
- "/F"
7511
- ], { stdio: "inherit" });
7583
+ (0, import_node_child_process.execFileSync)("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
7512
7584
  } finally {
7513
7585
  try {
7514
7586
  import_node_fs3.default.unlinkSync(tmpPath);
7515
7587
  } catch {
7516
7588
  }
7517
7589
  }
7518
- (0, import_node_child_process.execFileSync)("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], { stdio: "inherit" });
7519
- console.log(`Scheduled task "${WINDOWS_TASK_NAME}" created and started (runs at login, hidden).`);
7520
7590
  }
7521
- function uninstallWindows() {
7591
+ function windowsTaskExists() {
7522
7592
  try {
7523
- (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;
7524
7595
  } catch {
7596
+ return false;
7525
7597
  }
7598
+ }
7599
+ function isElevated() {
7526
7600
  try {
7527
- (0, import_node_child_process.execFileSync)("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], { stdio: "inherit" });
7528
- 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" }));
7529
7602
  } catch {
7530
- 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}.`;
7531
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}`);
7638
+ }
7639
+ printUninstalled();
7532
7640
  }
7533
7641
  function installService() {
7534
7642
  const platform2 = import_node_os.default.platform();
7535
- const bin = resolveBinary();
7536
- if (!("pkg" in process) && bin.program !== process.execPath) {
7537
- console.warn(
7538
- "Warning: Using npm-installed binary. The path may change if Node.js is updated.\nConsider using a standalone binary (pkg) for system services."
7539
- );
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);
7540
7654
  }
7541
7655
  switch (platform2) {
7542
7656
  case "linux":
7543
- installSystemd();
7657
+ installSystemd(program);
7544
7658
  break;
7545
7659
  case "darwin":
7546
- installLaunchd();
7660
+ installLaunchd(program);
7547
7661
  break;
7548
7662
  case "win32":
7549
- installWindows();
7663
+ installWindows(program);
7550
7664
  break;
7551
7665
  default:
7552
7666
  console.error(`Unsupported platform: ${platform2}`);
7553
7667
  process.exit(1);
7554
7668
  }
7555
7669
  }
7556
- function uninstallService() {
7670
+ async function uninstallService() {
7557
7671
  const platform2 = import_node_os.default.platform();
7558
7672
  switch (platform2) {
7559
7673
  case "linux":
@@ -7563,14 +7677,14 @@ function uninstallService() {
7563
7677
  uninstallLaunchd();
7564
7678
  break;
7565
7679
  case "win32":
7566
- uninstallWindows();
7680
+ await uninstallWindows();
7567
7681
  break;
7568
7682
  default:
7569
7683
  console.error(`Unsupported platform: ${platform2}`);
7570
7684
  process.exit(1);
7571
7685
  }
7572
7686
  }
7573
- 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;
7574
7688
  var init_serviceInstaller = __esm({
7575
7689
  "src/daemon/lifecycle/serviceInstaller.ts"() {
7576
7690
  "use strict";
@@ -7580,8 +7694,13 @@ var init_serviceInstaller = __esm({
7580
7694
  import_node_path2 = __toESM(require("path"), 1);
7581
7695
  import_node_child_process = require("child_process");
7582
7696
  init_logger();
7697
+ init_printer();
7698
+ init_util();
7699
+ init_daemonManager();
7583
7700
  SERVICE_LABEL = "io.pinggy.agent";
7584
7701
  SYSTEMD_SERVICE_NAME = "pinggy";
7702
+ SERVICE_ANY_LOCATION_ENV = "PINGGY_SERVICE_ANY_LOCATION";
7703
+ QUIET = { stdio: ["ignore", "ignore", "pipe"] };
7585
7704
  WINDOWS_TASK_NAME = "PinggyDaemon";
7586
7705
  }
7587
7706
  });
@@ -7594,6 +7713,8 @@ function printDaemonHelp() {
7594
7713
  console.log(" start Start the daemon process");
7595
7714
  console.log(" stop Stop the daemon (stops all tunnels)");
7596
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");
7597
7718
  console.log("Tunnel operations:");
7598
7719
  console.log(" pinggy ps List running tunnels");
7599
7720
  console.log(" pinggy stop <name|id> Stop a specific tunnel");
@@ -7630,17 +7751,24 @@ function printDeviceHelp() {
7630
7751
  console.log("\nUsage: pinggy device <command> [options]\n");
7631
7752
  console.log("Run this machine as a Pinggy device.\n");
7632
7753
  console.log("Commands:");
7633
- console.log(" login Sign this machine in with your email, then stay connected");
7634
- console.log(" connect --token <TOKEN> Enrol, then stay connected until interrupted");
7635
- console.log(" stop Stop the agent running in the background");
7754
+ console.log(" login Sign this machine in with your email, then run the agent in the");
7755
+ console.log(" background");
7756
+ console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
7757
+ console.log(" background. Without --token: start the enrolled device's agent again");
7758
+ console.log(" stop Stop the agent running in the background, until the daemon");
7759
+ console.log(" starts again");
7636
7760
  console.log(" status Show the enrolment, and the agent running in the background");
7637
- console.log(" remove Forget the local credential (does not delete the device)\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");
7638
7765
  console.log("Options:");
7639
- console.log(" -b login and connect: run the agent in the background, in the daemon.");
7640
- console.log(" It stays connected after this terminal closes");
7766
+ console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
7767
+ console.log(" -b login and connect: run the agent in the background. The default");
7641
7768
  console.log(" --token <TOKEN> Device token from the dashboard");
7642
7769
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
7643
- 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");
7644
7772
  console.log("Environment:");
7645
7773
  console.log(" DEVICE_AGENT_TOKEN connect only: the device token, when --token is not given. With no");
7646
7774
  console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
@@ -7763,10 +7891,11 @@ var init_device_schema = __esm({
7763
7891
  max_terminals_per_device: import_zod3.z.number().optional(),
7764
7892
  // No default on the agent. Without it, terminals stay unavailable rather than unbraked.
7765
7893
  terminal_window_bytes: import_zod3.z.number().optional(),
7766
- // No default either. Without them the agent runs no expiry timers, and the dashboard's sweep
7767
- // still ends an expired shell, only later.
7894
+ // No default either. Without it the agent runs no expiry timer, and the dashboard's sweep
7895
+ // still ends an idle shell, only later. A shell has no cap on its running time.
7768
7896
  terminal_idle_timeout_seconds: import_zod3.z.number().optional(),
7769
- terminal_max_session_seconds: import_zod3.z.number().optional(),
7897
+ // Optional: without it the agent keeps T2's brake and never skips output (slice T8).
7898
+ terminal_resync: import_zod3.z.boolean().optional(),
7770
7899
  // Optional: a dashboard older than these sends neither, and the agent prints only the device id.
7771
7900
  email: import_zod3.z.string().optional(),
7772
7901
  device_url: import_zod3.z.string().optional()
@@ -7790,34 +7919,42 @@ var init_device_schema = __esm({
7790
7919
  });
7791
7920
 
7792
7921
  // src/devices/deviceAgentReporter.ts
7922
+ function printDeviceUrl(print, label, url) {
7923
+ print(label);
7924
+ print("");
7925
+ print(` ${import_picocolors6.default.magentaBright(url)}`);
7926
+ print("");
7927
+ }
7793
7928
  function printConnected(welcome) {
7794
7929
  printer_default.success(`Connected as device ${welcome.device_agent_id}`);
7795
7930
  if (welcome.email) {
7796
7931
  printer_default.print(`Signed in as ${welcome.email}`);
7797
7932
  }
7798
7933
  if (welcome.device_url) {
7799
- printer_default.print("Open the device in a browser:");
7800
- printer_default.print(` ${welcome.device_url}`);
7934
+ printDeviceUrl((message) => printer_default.print(message), "Open the device in a browser:", welcome.device_url);
7801
7935
  }
7802
7936
  }
7803
7937
  function formatSeconds(millis) {
7804
7938
  return (millis / 1e3).toFixed(1);
7805
7939
  }
7806
- var printingReporter;
7940
+ var import_picocolors6, printingReporter;
7807
7941
  var init_deviceAgentReporter = __esm({
7808
7942
  "src/devices/deviceAgentReporter.ts"() {
7809
7943
  "use strict";
7810
7944
  init_cjs_shims();
7945
+ import_picocolors6 = __toESM(require("picocolors"), 1);
7811
7946
  init_printer();
7812
7947
  printingReporter = {
7813
- connecting: (server) => printer_default.print(`Connecting to ${server}`),
7948
+ connecting: (server) => printer_default.print(import_picocolors6.default.cyanBright(`Connecting to ${server}...`)),
7814
7949
  connected: printConnected,
7815
7950
  reconnecting: (delayMillis, attempt) => printer_default.warn(
7816
7951
  `Disconnected. Reconnecting in ${formatSeconds(delayMillis)} seconds (attempt ${attempt}).`
7817
7952
  ),
7818
7953
  warn: (message) => printer_default.warn(message),
7819
7954
  failed: (error) => printer_default.error(error.message),
7820
- replacingDevice: (oldDeviceAgentId) => printer_default.print(`This machine was device ${oldDeviceAgentId}. Connecting it with the token from the command.`)
7955
+ replacingDevice: (oldDeviceAgentId) => printer_default.print(import_picocolors6.default.yellow(
7956
+ `This machine was device ${oldDeviceAgentId}. That device stays in the dashboard, offline.`
7957
+ ))
7821
7958
  };
7822
7959
  }
7823
7960
  });
@@ -8372,7 +8509,7 @@ function clampGrid(requested, fallback) {
8372
8509
  if (requested === void 0 || !Number.isFinite(requested)) return fallback;
8373
8510
  return Math.max(MIN_GRID, Math.min(MAX_GRID, Math.trunc(requested)));
8374
8511
  }
8375
- var import_zod4, CHANNEL_TERMINAL, OP_OPEN, OP_OPENED, OP_CLOSE, OP_DATA, OP_ACK, OP_EXIT, OP_RESIZE, OP_SIGNAL, OP_CONTEXT, OP_SNAPSHOT, TERMINAL_SIGNALS, MIN_GRID, MAX_GRID, CLOSE_REASON_USER_CLOSED, CLOSE_REASON_IDLE_TIMEOUT, CLOSE_REASON_MAX_SESSION, ERROR_INVALID_PAYLOAD2, ERROR_TERMINAL_LIMIT_REACHED, ERROR_TERMINAL_DISABLED, ERROR_SHELL_NOT_ALLOWED, ERROR_SPAWN_FAILED, TerminalOpenSchema, TerminalCloseSchema, TerminalResizeSchema, TerminalInputSchema, TerminalSignalSchema, TerminalAckSchema, TerminalSnapshotRequestSchema;
8512
+ var import_zod4, CHANNEL_TERMINAL, OP_OPEN, OP_OPENED, OP_CLOSE, OP_DATA, OP_ACK, OP_EXIT, OP_RESIZE, OP_SIGNAL, OP_CONTEXT, OP_SNAPSHOT, OP_RESYNC, OP_ACTIVITY, TERMINAL_SIGNALS, MIN_GRID, MAX_GRID, CLOSE_REASON_USER_CLOSED, CLOSE_REASON_IDLE_TIMEOUT, ERROR_INVALID_PAYLOAD2, ERROR_TERMINAL_LIMIT_REACHED, ERROR_TERMINAL_DISABLED, ERROR_SHELL_NOT_ALLOWED, ERROR_SPAWN_FAILED, TerminalOpenSchema, TerminalCloseSchema, TerminalResizeSchema, TerminalInputSchema, TerminalSignalSchema, TerminalAckSchema, TerminalSnapshotRequestSchema;
8376
8513
  var init_terminal_schema = __esm({
8377
8514
  "src/devices/terminal/terminal_schema.ts"() {
8378
8515
  "use strict";
@@ -8389,12 +8526,13 @@ var init_terminal_schema = __esm({
8389
8526
  OP_SIGNAL = "signal";
8390
8527
  OP_CONTEXT = "context";
8391
8528
  OP_SNAPSHOT = "snapshot";
8529
+ OP_RESYNC = "resync";
8530
+ OP_ACTIVITY = "activity";
8392
8531
  TERMINAL_SIGNALS = ["INT", "TERM", "QUIT", "HUP"];
8393
8532
  MIN_GRID = 1;
8394
8533
  MAX_GRID = 1e3;
8395
8534
  CLOSE_REASON_USER_CLOSED = "user_closed";
8396
8535
  CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
8397
- CLOSE_REASON_MAX_SESSION = "max_session";
8398
8536
  ERROR_INVALID_PAYLOAD2 = "invalid_payload";
8399
8537
  ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
8400
8538
  ERROR_TERMINAL_DISABLED = "terminal_disabled";
@@ -8775,6 +8913,7 @@ var init_screenMirror = __esm({
8775
8913
  this.terminal = terminal;
8776
8914
  this.serializer = serializer;
8777
8915
  this.disposed = false;
8916
+ this.unparsedBytes = 0;
8778
8917
  }
8779
8918
  /** Null when the headless terminal cannot load. The shell then works as before, without restore. */
8780
8919
  static create(cols, rows) {
@@ -8785,28 +8924,45 @@ var init_screenMirror = __esm({
8785
8924
  terminal.loadAddon(serializer);
8786
8925
  return new _ScreenMirror(terminal, serializer);
8787
8926
  }
8788
- /** Bytes exactly as they were sent. xterm parses them later, in order, and joins split characters. */
8789
- feed(bytes) {
8790
- if (!this.disposed) this.terminal.write(bytes);
8927
+ /**
8928
+ * Bytes exactly as they were sent or skipped. xterm parses them later, in order, and joins split
8929
+ * characters. `onParsed` runs once they are parsed, when {@link backlogBytes} has already dropped by them.
8930
+ */
8931
+ feed(bytes, onParsed) {
8932
+ if (this.disposed) return;
8933
+ const byteCount = bytes.length;
8934
+ this.unparsedBytes += byteCount;
8935
+ this.terminal.write(bytes, () => {
8936
+ this.unparsedBytes -= byteCount;
8937
+ onParsed?.();
8938
+ });
8939
+ }
8940
+ /**
8941
+ * Fed and not yet parsed. xterm queues writes without limit, so a shell that skips its output
8942
+ * (slice T8) pauses on this, and on nothing else.
8943
+ */
8944
+ get backlogBytes() {
8945
+ return this.unparsedBytes;
8791
8946
  }
8792
8947
  resize(cols, rows) {
8793
8948
  if (!this.disposed) this.terminal.resize(cols, rows);
8794
8949
  }
8795
8950
  /**
8796
- * The screen after everything fed before this call, and nothing fed after it. Null when the
8797
- * mirror was disposed first.
8951
+ * The screen after everything fed before this call, and nothing fed after it, serialised under
8952
+ * `maxBytes`. Null when the mirror was disposed first, or when even the screen alone is over
8953
+ * {@link MAX_SNAPSHOT_BYTES}.
8798
8954
  *
8799
8955
  * xterm parses writes in batches, on a timer. An empty write queued now has its callback run
8800
8956
  * after every earlier chunk is parsed and before the next one is, so serialising inside it sees
8801
8957
  * exactly what was fed before this call.
8802
8958
  */
8803
- snapshot() {
8959
+ snapshot(maxBytes = MAX_SNAPSHOT_BYTES) {
8804
8960
  return new Promise((resolve) => {
8805
8961
  if (this.disposed) {
8806
8962
  resolve(null);
8807
8963
  return;
8808
8964
  }
8809
- this.terminal.write("", () => resolve(this.disposed ? null : this.serialise()));
8965
+ this.terminal.write("", () => resolve(this.disposed ? null : this.serialise(maxBytes)));
8810
8966
  });
8811
8967
  }
8812
8968
  dispose() {
@@ -8814,14 +8970,24 @@ var init_screenMirror = __esm({
8814
8970
  this.disposed = true;
8815
8971
  this.terminal.dispose();
8816
8972
  }
8817
- /** Null when even the screen alone is over the cap. The tab then waits out its fallback. */
8818
- serialise() {
8973
+ /**
8974
+ * Fewer lines of scrollback until the text fits `maxBytes`. A screen alone over a cap below
8975
+ * {@link MAX_SNAPSHOT_BYTES} is still sent under that: a resync over its cap beats a tab that never
8976
+ * catches up. Null when even the screen alone is over {@link MAX_SNAPSHOT_BYTES}.
8977
+ */
8978
+ serialise(maxBytes) {
8819
8979
  for (const scrollback of SCROLLBACK_LINES_TO_TRY) {
8820
8980
  const text = this.serializer.serialize({ scrollback });
8821
- if (Buffer.byteLength(text, "utf-8") <= MAX_SNAPSHOT_BYTES) {
8981
+ if (Buffer.byteLength(text, "utf-8") <= maxBytes) {
8822
8982
  return { text, cols: this.terminal.cols, rows: this.terminal.rows };
8823
8983
  }
8824
8984
  }
8985
+ if (maxBytes < MAX_SNAPSHOT_BYTES) {
8986
+ const screenOnly = this.serializer.serialize({ scrollback: 0 });
8987
+ if (Buffer.byteLength(screenOnly, "utf-8") <= MAX_SNAPSHOT_BYTES) {
8988
+ return { text: screenOnly, cols: this.terminal.cols, rows: this.terminal.rows };
8989
+ }
8990
+ }
8825
8991
  return null;
8826
8992
  }
8827
8993
  };
@@ -8848,11 +9014,12 @@ function signalName(signal) {
8848
9014
  }
8849
9015
  return String(signal);
8850
9016
  }
8851
- var import_os6, DEFAULT_COLS, DEFAULT_ROWS, EXPIRY_CHECK_MILLIS, MILLIS_PER_SECOND, TerminalHandler;
9017
+ var import_crypto3, import_os6, DEFAULT_COLS, DEFAULT_ROWS, EXPIRY_CHECK_MILLIS, MILLIS_PER_SECOND, RESYNC_MIN_INTERVAL_MILLIS, MIRROR_HIGH_WATER_BYTES, MIRROR_LOW_WATER_BYTES, ACTIVITY_REPORT_MILLIS, DEFAULT_SKIP_TUNING, TerminalHandler;
8852
9018
  var init_terminalHandler = __esm({
8853
9019
  "src/devices/terminal/terminalHandler.ts"() {
8854
9020
  "use strict";
8855
9021
  init_cjs_shims();
9022
+ import_crypto3 = require("crypto");
8856
9023
  import_os6 = __toESM(require("os"), 1);
8857
9024
  init_logger();
8858
9025
  init_envelope();
@@ -8865,16 +9032,31 @@ var init_terminalHandler = __esm({
8865
9032
  DEFAULT_ROWS = 24;
8866
9033
  EXPIRY_CHECK_MILLIS = 5e3;
8867
9034
  MILLIS_PER_SECOND = 1e3;
8868
- TerminalHandler = class {
9035
+ RESYNC_MIN_INTERVAL_MILLIS = 1e3;
9036
+ MIRROR_HIGH_WATER_BYTES = 1024 * 1024;
9037
+ MIRROR_LOW_WATER_BYTES = 256 * 1024;
9038
+ ACTIVITY_REPORT_MILLIS = 6e4;
9039
+ DEFAULT_SKIP_TUNING = {
9040
+ resyncMinIntervalMillis: RESYNC_MIN_INTERVAL_MILLIS,
9041
+ mirrorHighWaterBytes: MIRROR_HIGH_WATER_BYTES,
9042
+ mirrorLowWaterBytes: MIRROR_LOW_WATER_BYTES,
9043
+ activityReportMillis: ACTIVITY_REPORT_MILLIS
9044
+ };
9045
+ TerminalHandler = class _TerminalHandler {
8869
9046
  constructor(dependencies) {
8870
9047
  this.dependencies = dependencies;
8871
9048
  this.enabled = true;
8872
9049
  this.suspended = false;
9050
+ /** `terminal_resync` in `welcome` (slice T8). Off, every shell keeps T2's brake. */
9051
+ this.resyncEnabled = false;
9052
+ /** Paused by `suspend` under T2's brake, so `resumeAll` resumes them if `welcome` turned skip mode on. */
9053
+ this.pausedBySuspend = /* @__PURE__ */ new Set();
8873
9054
  this.expiryTimer = null;
8874
9055
  this.contextTimer = null;
8875
9056
  this.contextPollInFlight = false;
8876
9057
  this.contextTracker = new ShellContextTracker();
8877
9058
  this.streams = /* @__PURE__ */ new Map();
9059
+ this.tuning = { ...DEFAULT_SKIP_TUNING, ...dependencies.skipTuning };
8878
9060
  }
8879
9061
  /**
8880
9062
  * From welcome. An older dashboard sends no terminal fields, and `terminal_enabled` and the
@@ -8884,7 +9066,7 @@ var init_terminalHandler = __esm({
8884
9066
  * the field, and nobody notices until a node falls over, so an agent without one refuses to open
8885
9067
  * a terminal at all.
8886
9068
  */
8887
- configure(terminalEnabled, maxTerminalsPerDevice, terminalWindowBytes, maxFrameBytes, idleTimeoutSeconds, maxSessionSeconds) {
9069
+ configure(terminalEnabled, maxTerminalsPerDevice, terminalWindowBytes, maxFrameBytes, idleTimeoutSeconds, terminalResync) {
8888
9070
  if (terminalEnabled !== void 0) this.enabled = terminalEnabled;
8889
9071
  if (maxTerminalsPerDevice !== void 0) this.dependencies.registry.setMaxTerminals(maxTerminalsPerDevice);
8890
9072
  this.windowBytes = terminalWindowBytes;
@@ -8893,21 +9075,33 @@ var init_terminalHandler = __esm({
8893
9075
  logger.info("Terminals unavailable: welcome carried no terminal_window_bytes");
8894
9076
  }
8895
9077
  this.idleTimeoutMillis = positiveMillis(idleTimeoutSeconds);
8896
- this.maxSessionMillis = positiveMillis(maxSessionSeconds);
9078
+ this.setSkipMode(terminalResync === true);
8897
9079
  this.startExpiryTimer();
8898
9080
  }
8899
9081
  /**
8900
- * Ends every shell past its idle timeout or its max-session cap. Runs on a timer; public so a test
8901
- * decides when. The cap goes first: a shell both idle and too old is closed for the rule typing
8902
- * cannot reset.
9082
+ * `welcome` turned skip mode on or off. Off, a skipping shell stops skipping without a resync, since
9083
+ * this dashboard cannot route one, and its tabs miss what was skipped. `resumeAll` then sets the reads.
8903
9084
  */
9085
+ setSkipMode(enabled) {
9086
+ if (enabled === this.resyncEnabled) return;
9087
+ this.resyncEnabled = enabled;
9088
+ for (const stream of this.streams.values()) {
9089
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
9090
+ stream.resyncTimer = null;
9091
+ stream.skipping = false;
9092
+ stream.skippedBytes = 0;
9093
+ stream.resyncOverflowed = false;
9094
+ stream.resyncHeldBundles.splice(0);
9095
+ stream.resyncHeldBytes = 0;
9096
+ stream.mirrorPaused = false;
9097
+ }
9098
+ }
9099
+ /** Ends every shell past its idle timeout. Runs on a timer; public so a test decides when. */
8904
9100
  expireShells() {
8905
9101
  if (this.suspended) return;
8906
9102
  const nowMillis = this.nowMillis();
8907
9103
  for (const [terminalId, stream] of [...this.streams.entries()]) {
8908
- if (this.maxSessionMillis !== void 0 && nowMillis - stream.openedAtMillis >= this.maxSessionMillis) {
8909
- this.expire(terminalId, CLOSE_REASON_MAX_SESSION);
8910
- } else if (this.idleTimeoutMillis !== void 0 && nowMillis - stream.lastActivityMillis >= this.idleTimeoutMillis) {
9104
+ if (this.idleTimeoutMillis !== void 0 && nowMillis - stream.lastActivityMillis >= this.idleTimeoutMillis) {
8911
9105
  this.expire(terminalId, CLOSE_REASON_IDLE_TIMEOUT);
8912
9106
  }
8913
9107
  }
@@ -8941,22 +9135,28 @@ var init_terminalHandler = __esm({
8941
9135
  this.contextTracker.clear();
8942
9136
  this.suspended = false;
8943
9137
  for (const stream of this.streams.values()) {
9138
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
8944
9139
  stream.splitter.dispose();
8945
9140
  stream.mirror?.dispose();
8946
9141
  }
8947
9142
  this.streams.clear();
9143
+ this.pausedBySuspend.clear();
8948
9144
  this.dependencies.registry.killAll();
8949
9145
  }
8950
9146
  /**
8951
- * The socket dropped and the agent will redial. Every shell stops being read and keeps running.
8952
- * Whatever it prints waits in the kernel, and the shell blocks once that buffer is full.
9147
+ * The socket dropped and the agent will redial. Under T2's brake every shell stops being read and
9148
+ * keeps running: whatever it prints waits in the kernel, and the shell blocks once that buffer is
9149
+ * full. In skip mode (slice T8) a shell is read on, and its output is skipped.
8953
9150
  */
8954
9151
  suspend() {
8955
9152
  if (this.suspended) return;
8956
9153
  this.suspended = true;
8957
9154
  for (const [terminalId, session] of this.dependencies.registry.entries()) {
9155
+ const stream = this.streams.get(terminalId);
9156
+ if (stream && this.skipsOutput(stream)) continue;
8958
9157
  try {
8959
9158
  session.pause();
9159
+ this.pausedBySuspend.add(terminalId);
8960
9160
  } catch (err) {
8961
9161
  logger.warn("Terminal pause failed", { terminal_id: terminalId, error: errorName2(err) });
8962
9162
  }
@@ -8965,13 +9165,18 @@ var init_terminalHandler = __esm({
8965
9165
  }
8966
9166
  /**
8967
9167
  * `welcome` arrived. Every shell the dashboard did not close is read again, except one whose
8968
- * window is still full. That one resumes on the `ack` that reopens it.
9168
+ * window is still full. That one resumes on the `ack` that reopens it. A shell in skip mode was
9169
+ * never paused, and resyncs instead (slice T8).
8969
9170
  */
8970
9171
  resumeAll() {
8971
9172
  if (!this.suspended) return;
8972
9173
  this.suspended = false;
8973
9174
  for (const [terminalId, session] of this.dependencies.registry.entries()) {
8974
9175
  const stream = this.streams.get(terminalId);
9176
+ if (stream && this.skipsOutput(stream)) {
9177
+ this.resumeSkipping(terminalId, stream, session);
9178
+ continue;
9179
+ }
8975
9180
  if (stream) {
8976
9181
  for (const chunk of stream.heldBundles.splice(0)) {
8977
9182
  this.sendData(terminalId, chunk);
@@ -8984,6 +9189,7 @@ var init_terminalHandler = __esm({
8984
9189
  logger.warn("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
8985
9190
  }
8986
9191
  }
9192
+ this.pausedBySuspend.clear();
8987
9193
  for (const context of this.contextTracker.current()) {
8988
9194
  if (this.streams.has(context.terminal_id)) {
8989
9195
  this.dependencies.send(event(CHANNEL_TERMINAL, OP_CONTEXT, context));
@@ -9086,7 +9292,6 @@ var init_terminalHandler = __esm({
9086
9292
  this.dependencies.send(response(envelope, OP_OPENED, opened));
9087
9293
  }
9088
9294
  startStream(terminalId, session, windowBytes, bundleBytes) {
9089
- const openedAtMillis = this.nowMillis();
9090
9295
  const stream = {
9091
9296
  session,
9092
9297
  window: new FlowWindow(windowBytes),
@@ -9095,8 +9300,17 @@ var init_terminalHandler = __esm({
9095
9300
  paused: false,
9096
9301
  sentSeq: 0,
9097
9302
  heldBundles: [],
9098
- openedAtMillis,
9099
- lastActivityMillis: openedAtMillis
9303
+ lastActivityMillis: this.nowMillis(),
9304
+ skipping: false,
9305
+ skippedBytes: 0,
9306
+ lastResyncAtMillis: 0,
9307
+ resyncTimer: null,
9308
+ resyncInFlight: null,
9309
+ resyncHeldBundles: [],
9310
+ resyncHeldBytes: 0,
9311
+ resyncOverflowed: false,
9312
+ mirrorPaused: false,
9313
+ lastActivityReportMillis: 0
9100
9314
  };
9101
9315
  this.streams.set(terminalId, stream);
9102
9316
  this.startContextTimer();
@@ -9108,17 +9322,29 @@ var init_terminalHandler = __esm({
9108
9322
  if (this.dependencies.registry.remove(terminalId) === void 0) return;
9109
9323
  stream.splitter.flush();
9110
9324
  stream.splitter.dispose();
9111
- this.forgetStream(terminalId);
9112
- logger.info("Terminal shell exited", { terminal_id: terminalId, exit_code: exitCode, signal });
9113
- const exit = signal ? { terminal_id: terminalId, exit_code: null, signal: signalName(signal) } : { terminal_id: terminalId, exit_code: exitCode, signal: null };
9114
- this.dependencies.send(event(CHANNEL_TERMINAL, OP_EXIT, exit));
9115
- this.dependencies.send(event(
9116
- CHANNEL_TERMINAL,
9117
- OP_CLOSE,
9118
- { terminal_id: terminalId, reason: CLOSE_REASON_USER_CLOSED }
9119
- ));
9325
+ void this.finishExit(terminalId, stream, exitCode, signal);
9120
9326
  });
9121
9327
  }
9328
+ /**
9329
+ * The shell exited on its own. A shell that skipped its last output sends its last screen first, at
9330
+ * once, so the tabs see how it ended (slice T8). Then `exit` and `close`. With nothing to resync this
9331
+ * runs to the end without yielding, as before.
9332
+ */
9333
+ async finishExit(terminalId, stream, exitCode, signal) {
9334
+ if (this.skipsOutput(stream)) {
9335
+ if (stream.resyncInFlight) await stream.resyncInFlight;
9336
+ if (stream.skipping && !this.suspended) await this.resync(terminalId, stream);
9337
+ }
9338
+ this.forgetStream(terminalId);
9339
+ logger.info("Terminal shell exited", { terminal_id: terminalId, exit_code: exitCode, signal });
9340
+ const exit = signal ? { terminal_id: terminalId, exit_code: null, signal: signalName(signal) } : { terminal_id: terminalId, exit_code: exitCode, signal: null };
9341
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_EXIT, exit));
9342
+ this.dependencies.send(event(
9343
+ CHANNEL_TERMINAL,
9344
+ OP_CLOSE,
9345
+ { terminal_id: terminalId, reason: CLOSE_REASON_USER_CLOSED }
9346
+ ));
9347
+ }
9122
9348
  /**
9123
9349
  * 1 bundle leaves, and the window narrows by what it carried.
9124
9350
  *
@@ -9132,10 +9358,16 @@ var init_terminalHandler = __esm({
9132
9358
  * The mirror is fed here, in the same tick as the seq, and nowhere else. A snapshot then holds
9133
9359
  * exactly the bundles up to its `after_seq`. Fed when the pty is read, a bundle still being cut
9134
9360
  * would be in the screen and drawn a second time when it is sent.
9361
+ *
9362
+ * In skip mode (slice T8) `sendOrSkip` decides instead, and never pauses the pty.
9135
9363
  */
9136
9364
  sendData(terminalId, chunk) {
9137
9365
  const stream = this.streams.get(terminalId);
9138
9366
  if (!stream) return;
9367
+ if (this.skipsOutput(stream)) {
9368
+ this.sendOrSkip(terminalId, stream, chunk);
9369
+ return;
9370
+ }
9139
9371
  if (this.suspended) {
9140
9372
  stream.heldBundles.push(chunk);
9141
9373
  return;
@@ -9151,12 +9383,215 @@ var init_terminalHandler = __esm({
9151
9383
  logger.debug("Terminal window full, reads paused", { terminal_id: terminalId });
9152
9384
  }
9153
9385
  }
9386
+ /** Skip mode applies: `welcome` asked for it, and the shell has a screen to resync with. */
9387
+ skipsOutput(stream) {
9388
+ return this.resyncEnabled && stream.mirror !== null;
9389
+ }
9390
+ /**
9391
+ * Skip mode (slice T8). A resync being serialised holds the bundle. A skipping stream, a socket that is
9392
+ * down, or a closed window skips it. Otherwise it goes out as `data`.
9393
+ */
9394
+ sendOrSkip(terminalId, stream, chunk) {
9395
+ if (stream.resyncInFlight) {
9396
+ this.holdDuringResync(terminalId, stream, chunk);
9397
+ } else if (stream.skipping || this.suspended || !stream.window.isOpen()) {
9398
+ this.skip(terminalId, stream, chunk);
9399
+ } else {
9400
+ this.transmit(terminalId, stream, chunk);
9401
+ }
9402
+ }
9403
+ /**
9404
+ * A bundle cut while a resync is serialised is not in its screen, so it waits and goes out after the
9405
+ * parts. Past the window size the held bundles are skipped instead, and the stream stays skipping.
9406
+ */
9407
+ holdDuringResync(terminalId, stream, chunk) {
9408
+ if (!stream.resyncOverflowed && stream.resyncHeldBytes + chunk.length <= (this.windowBytes ?? 0)) {
9409
+ stream.resyncHeldBundles.push(chunk);
9410
+ stream.resyncHeldBytes += chunk.length;
9411
+ return;
9412
+ }
9413
+ if (!stream.resyncOverflowed) {
9414
+ stream.resyncOverflowed = true;
9415
+ this.skipHeldDuringResync(terminalId, stream);
9416
+ }
9417
+ this.skip(terminalId, stream, chunk);
9418
+ }
9419
+ skipHeldDuringResync(terminalId, stream) {
9420
+ const held = stream.resyncHeldBundles.splice(0);
9421
+ stream.resyncHeldBytes = 0;
9422
+ for (const chunk of held) {
9423
+ this.skip(terminalId, stream, chunk);
9424
+ }
9425
+ }
9426
+ /** Into the screen, not onto the wire. It takes no seq, and the window never counts it. */
9427
+ skip(terminalId, stream, chunk) {
9428
+ stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
9429
+ stream.skippedBytes += chunk.length;
9430
+ if (!stream.skipping) {
9431
+ stream.skipping = true;
9432
+ logger.debug("Terminal output skipped until the tabs catch up", { terminal_id: terminalId });
9433
+ }
9434
+ this.brakeIfMirrorBehind(terminalId, stream);
9435
+ this.reportActivityWhileSkipping(terminalId, stream);
9436
+ }
9437
+ /** As T2's send, minus the pause: with the window closed, the next bundle is skipped instead. */
9438
+ transmit(terminalId, stream, chunk) {
9439
+ stream.sentSeq += 1;
9440
+ stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
9441
+ const data = { terminal_id: terminalId, data: chunk.toString("base64") };
9442
+ this.dependencies.send({ ...event(CHANNEL_TERMINAL, OP_DATA, data), seq: stream.sentSeq });
9443
+ stream.window.recordSent(chunk.length);
9444
+ this.brakeIfMirrorBehind(terminalId, stream);
9445
+ }
9446
+ /** The one pause in skip mode: the mirror's parser fell behind. Local CPU, never the network. */
9447
+ brakeIfMirrorBehind(terminalId, stream) {
9448
+ if (stream.mirrorPaused || !stream.mirror || stream.mirror.backlogBytes <= this.tuning.mirrorHighWaterBytes) return;
9449
+ stream.mirrorPaused = true;
9450
+ stream.session.pause();
9451
+ logger.debug("Terminal reads paused until the screen catches up", { terminal_id: terminalId });
9452
+ }
9453
+ mirrorParsed(terminalId, stream) {
9454
+ if (!stream.mirrorPaused || !stream.mirror || stream.mirror.backlogBytes > this.tuning.mirrorLowWaterBytes) return;
9455
+ stream.mirrorPaused = false;
9456
+ if (this.streams.get(terminalId) !== stream) return;
9457
+ try {
9458
+ stream.session.resume();
9459
+ } catch (err) {
9460
+ logger.debug("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
9461
+ }
9462
+ }
9463
+ /**
9464
+ * Skipped output never reaches the dashboard, so its sweep would see an idle shell. At most every
9465
+ * `ACTIVITY_REPORT_MILLIS` it hears that this one is busy.
9466
+ */
9467
+ reportActivityWhileSkipping(terminalId, stream) {
9468
+ if (this.suspended) return;
9469
+ const nowMillis = this.nowMillis();
9470
+ if (nowMillis - stream.lastActivityReportMillis < this.tuning.activityReportMillis) return;
9471
+ stream.lastActivityReportMillis = nowMillis;
9472
+ const activity = { terminal_id: terminalId, skipped_bytes: stream.skippedBytes };
9473
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_ACTIVITY, activity));
9474
+ }
9475
+ /**
9476
+ * Skip mode after `welcome`. A shell that skipped, or had bytes in flight, resyncs at once: frames in
9477
+ * flight died with the old socket, and the tab's ack of the resync's `after_bytes` stands in for theirs.
9478
+ */
9479
+ resumeSkipping(terminalId, stream, session) {
9480
+ stream.paused = false;
9481
+ for (const chunk of stream.heldBundles.splice(0)) {
9482
+ this.skip(terminalId, stream, chunk);
9483
+ }
9484
+ if (this.pausedBySuspend.has(terminalId) && !stream.mirrorPaused) {
9485
+ try {
9486
+ session.resume();
9487
+ } catch (err) {
9488
+ logger.warn("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
9489
+ }
9490
+ }
9491
+ if (stream.skipping || stream.window.sent > stream.window.acked) {
9492
+ void this.resync(terminalId, stream);
9493
+ }
9494
+ }
9495
+ /** Every sent byte is acked: the tabs have drawn everything they were sent. */
9496
+ static isDrained(stream) {
9497
+ return stream.window.acked >= stream.window.sent;
9498
+ }
9499
+ /**
9500
+ * A skipping stream resyncs once its window has drained, and no sooner than the interval after the
9501
+ * last resync. Not drained yet, it waits for the next `ack`.
9502
+ */
9503
+ scheduleResync(terminalId, stream) {
9504
+ if (!stream.skipping || stream.resyncInFlight || stream.resyncTimer || this.suspended || !_TerminalHandler.isDrained(stream)) return;
9505
+ const waitMillis = stream.lastResyncAtMillis + this.tuning.resyncMinIntervalMillis - this.nowMillis();
9506
+ if (waitMillis <= 0) {
9507
+ void this.resync(terminalId, stream);
9508
+ return;
9509
+ }
9510
+ stream.resyncTimer = setTimeout(() => {
9511
+ stream.resyncTimer = null;
9512
+ if (this.streams.get(terminalId) === stream) this.scheduleResync(terminalId, stream);
9513
+ }, waitMillis);
9514
+ stream.resyncTimer.unref();
9515
+ }
9516
+ /** Starts a resync, or returns the one already being serialised. */
9517
+ resync(terminalId, stream) {
9518
+ if (stream.resyncInFlight) return stream.resyncInFlight;
9519
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
9520
+ stream.resyncTimer = null;
9521
+ stream.resyncInFlight = this.serialiseAndSendResync(terminalId, stream);
9522
+ return stream.resyncInFlight;
9523
+ }
9524
+ /**
9525
+ * The latest screen to every tab (slice T8). `after_seq` and `after_bytes` are read before the mirror
9526
+ * is asked, as for a snapshot, and skipped bytes took neither: the screen holds the output up to
9527
+ * `after_seq` plus everything skipped. Serialised under the window size, so a resync never puts more in
9528
+ * flight than the window allows. Bundles held meanwhile go out after the parts, from `after_seq + 1`.
9529
+ */
9530
+ async serialiseAndSendResync(terminalId, stream) {
9531
+ stream.lastResyncAtMillis = this.nowMillis();
9532
+ stream.resyncOverflowed = false;
9533
+ const afterSeq = stream.sentSeq;
9534
+ const afterBytes = stream.window.sent;
9535
+ const skippedBytes = stream.skippedBytes;
9536
+ stream.skippedBytes = 0;
9537
+ const screen = stream.mirror ? await stream.mirror.snapshot(this.windowBytes) : null;
9538
+ stream.resyncInFlight = null;
9539
+ if (this.streams.get(terminalId) !== stream) return;
9540
+ if (this.suspended) {
9541
+ stream.skippedBytes += skippedBytes;
9542
+ this.skipHeldDuringResync(terminalId, stream);
9543
+ stream.resyncOverflowed = false;
9544
+ return;
9545
+ }
9546
+ if (screen && this.bundleBytes !== void 0) {
9547
+ const resyncId = (0, import_crypto3.randomUUID)();
9548
+ const parts = splitIntoParts(Buffer.from(screen.text, "utf-8"), this.bundleBytes);
9549
+ parts.forEach((part, index) => {
9550
+ const payload = {
9551
+ terminal_id: terminalId,
9552
+ resync_id: resyncId,
9553
+ part: index,
9554
+ last: index === parts.length - 1,
9555
+ after_seq: afterSeq,
9556
+ after_bytes: afterBytes,
9557
+ skipped_bytes: skippedBytes,
9558
+ cols: screen.cols,
9559
+ rows: screen.rows,
9560
+ data: part.toString("base64")
9561
+ };
9562
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_RESYNC, payload));
9563
+ });
9564
+ logger.debug("Terminal resynced", {
9565
+ terminal_id: terminalId,
9566
+ parts: parts.length,
9567
+ after_seq: afterSeq,
9568
+ skipped_bytes: skippedBytes
9569
+ });
9570
+ } else {
9571
+ logger.warn("Terminal resync dropped: the screen is too large to send", { terminal_id: terminalId });
9572
+ }
9573
+ if (stream.resyncOverflowed) {
9574
+ stream.resyncOverflowed = false;
9575
+ this.scheduleResync(terminalId, stream);
9576
+ return;
9577
+ }
9578
+ stream.skipping = false;
9579
+ const held = stream.resyncHeldBundles.splice(0);
9580
+ stream.resyncHeldBytes = 0;
9581
+ for (const chunk of held) {
9582
+ this.sendOrSkip(terminalId, stream, chunk);
9583
+ }
9584
+ }
9154
9585
  acknowledge(envelope) {
9155
9586
  const parsed = TerminalAckSchema.safeParse(envelope.payload);
9156
9587
  if (!parsed.success) return;
9157
9588
  const stream = this.streams.get(parsed.data.terminal_id);
9158
9589
  if (!stream) return;
9159
9590
  stream.window.recordAck(parsed.data.ack_bytes);
9591
+ if (this.skipsOutput(stream)) {
9592
+ this.scheduleResync(parsed.data.terminal_id, stream);
9593
+ return;
9594
+ }
9160
9595
  if (stream.paused && stream.window.isOpen()) {
9161
9596
  stream.paused = false;
9162
9597
  if (this.suspended) return;
@@ -9284,7 +9719,9 @@ var init_terminalHandler = __esm({
9284
9719
  }
9285
9720
  /** A shell is gone. The context poll stops with the last one, so an idle agent spawns nothing. */
9286
9721
  forgetStream(terminalId) {
9287
- this.streams.get(terminalId)?.mirror?.dispose();
9722
+ const stream = this.streams.get(terminalId);
9723
+ if (stream?.resyncTimer) clearTimeout(stream.resyncTimer);
9724
+ stream?.mirror?.dispose();
9288
9725
  this.streams.delete(terminalId);
9289
9726
  this.contextTracker.forget(terminalId);
9290
9727
  if (this.streams.size === 0) this.stopContextTimer();
@@ -9301,7 +9738,7 @@ var init_terminalHandler = __esm({
9301
9738
  }
9302
9739
  }
9303
9740
  startExpiryTimer() {
9304
- if (this.expiryTimer || this.idleTimeoutMillis === void 0 && this.maxSessionMillis === void 0) {
9741
+ if (this.expiryTimer || this.idleTimeoutMillis === void 0) {
9305
9742
  return;
9306
9743
  }
9307
9744
  this.expiryTimer = setInterval(() => this.expireShells(), EXPIRY_CHECK_MILLIS);
@@ -9626,9 +10063,9 @@ function readShellEnvironment() {
9626
10063
  platform: process.platform,
9627
10064
  loginShell: process.env.SHELL,
9628
10065
  etcShells,
9629
- exists: (path12) => {
10066
+ exists: (path13) => {
9630
10067
  try {
9631
- return import_fs12.default.statSync(path12).isFile();
10068
+ return import_fs12.default.statSync(path13).isFile();
9632
10069
  } catch {
9633
10070
  return false;
9634
10071
  }
@@ -9671,10 +10108,120 @@ var init_shellAllowlist = __esm({
9671
10108
  }
9672
10109
  });
9673
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
+
9674
10221
  // src/devices/deviceAgent.ts
9675
10222
  function buildCapabilities(terminalSupported, screenRestoreSupported = false) {
9676
10223
  if (!terminalSupported) return BASE_CAPABILITIES;
9677
- return screenRestoreSupported ? [...BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT] : [...BASE_CAPABILITIES, CAPABILITY_TERMINAL];
10224
+ return screenRestoreSupported ? [...BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC] : [...BASE_CAPABILITIES, CAPABILITY_TERMINAL];
9678
10225
  }
9679
10226
  function buildDeviceAgentWsUrl(manage) {
9680
10227
  let baseUrl = (manage || DEFAULT_SERVER).trim();
@@ -9729,9 +10276,7 @@ function startDeviceAgent(token, manage, options = {}) {
9729
10276
  const server = manage || DEFAULT_SERVER;
9730
10277
  const reporter = options.reporter ?? printingReporter;
9731
10278
  const stored = readDeviceIdentity();
9732
- if (stored?.device_agent_id && stored.token !== token) {
9733
- reporter.replacingDevice(stored.device_agent_id);
9734
- }
10279
+ const usesStoredToken = stored?.token === token;
9735
10280
  const connection = { send: null, close: null };
9736
10281
  const context = {
9737
10282
  wsUrl: buildDeviceAgentWsUrl(manage),
@@ -9751,7 +10296,9 @@ function startDeviceAgent(token, manage, options = {}) {
9751
10296
  reporter,
9752
10297
  writeIdentity: options.writeIdentity ?? writeDeviceIdentity,
9753
10298
  options,
9754
- state: { stopRequested: false, cancelPendingSleep: null, error: null, welcomed: false }
10299
+ state: { stopRequested: false, cancelPendingSleep: null, error: null, welcomed: false },
10300
+ usesStoredToken,
10301
+ replacedDeviceAgentId: usesStoredToken ? null : stored?.device_agent_id ?? null
9755
10302
  };
9756
10303
  const done = runLoop(context);
9757
10304
  return {
@@ -9766,14 +10313,20 @@ function startDeviceAgent(token, manage, options = {}) {
9766
10313
  }
9767
10314
  async function runDeviceAgent(token, manage, options = {}) {
9768
10315
  const run2 = startDeviceAgent(token, manage, options);
10316
+ const reporter = options.reporter ?? printingReporter;
9769
10317
  const sigintHandler = () => {
9770
10318
  void run2.stop();
9771
10319
  };
10320
+ const releaseRecord = recordForegroundAgent(() => {
10321
+ reporter.warn("Stopping: pinggy device remove ran in another terminal.");
10322
+ void run2.stop();
10323
+ });
9772
10324
  process.once("SIGINT", sigintHandler);
9773
10325
  try {
9774
10326
  await run2.done;
9775
10327
  } finally {
9776
10328
  process.removeListener("SIGINT", sigintHandler);
10329
+ releaseRecord();
9777
10330
  }
9778
10331
  }
9779
10332
  async function runLoop(context) {
@@ -9908,7 +10461,7 @@ function connectOnce(context) {
9908
10461
  welcome.terminal_window_bytes,
9909
10462
  welcome.max_frame_bytes,
9910
10463
  welcome.terminal_idle_timeout_seconds,
9911
- welcome.terminal_max_session_seconds
10464
+ welcome.terminal_resync
9912
10465
  );
9913
10466
  terminalHandler.resumeAll();
9914
10467
  startHeartbeat(welcome.heartbeat_interval_seconds);
@@ -9948,10 +10501,10 @@ function connectOnce(context) {
9948
10501
  if (res.statusCode === 401) {
9949
10502
  finish(fail(context, {
9950
10503
  code: AGENT_ERROR_UNAUTHORIZED,
9951
- message: "Unauthorized. This device token is not valid. Re-enrol this machine with: pinggy device login"
10504
+ message: context.usesStoredToken ? UNAUTHORIZED_STORED_TOKEN_MESSAGE : UNAUTHORIZED_NEW_TOKEN_MESSAGE
9952
10505
  }));
9953
10506
  } else {
9954
- reporter.warn(`Unexpected HTTP ${res.statusCode}.`);
10507
+ reporter.warn(`The dashboard answered HTTP ${res.statusCode}.`);
9955
10508
  finish("retry");
9956
10509
  }
9957
10510
  ws.close();
@@ -9962,7 +10515,7 @@ function connectOnce(context) {
9962
10515
  });
9963
10516
  ws.on("error", (err) => {
9964
10517
  logger.warn("Device agent socket error", { error: err.message });
9965
- if (!state.stopRequested) {
10518
+ if (!state.stopRequested && !settled) {
9966
10519
  reporter.warn(err.message);
9967
10520
  }
9968
10521
  finish("retry");
@@ -9996,6 +10549,10 @@ function handleFrame(envelope, context, onWelcome) {
9996
10549
  identity.enrolled_at = identity.enrolled_at ?? (/* @__PURE__ */ new Date()).toISOString();
9997
10550
  context.writeIdentity(identity);
9998
10551
  context.state.welcomed = true;
10552
+ if (context.replacedDeviceAgentId) {
10553
+ reporter.replacingDevice(context.replacedDeviceAgentId);
10554
+ context.replacedDeviceAgentId = null;
10555
+ }
9999
10556
  reporter.connected(welcome.data);
10000
10557
  onWelcome(welcome.data);
10001
10558
  return "retry";
@@ -10025,7 +10582,7 @@ function describeDisconnect(reason) {
10025
10582
  message: DISCONNECT_MESSAGES[reason] ?? `Disconnected by the dashboard: ${reason}. Re-enrol this device to continue.`
10026
10583
  };
10027
10584
  }
10028
- var import_ws3, import_os8, CLOSE_CODE_REVOKED, CLOSE_CODE_NORMAL, CLOSE_TIMEOUT_MILLIS, TOKEN_HEADER, DEFAULT_SERVER, ERROR_ALREADY_CONNECTED, AGENT_ERROR_UNAUTHORIZED, AGENT_ERROR_HANDSHAKE_REFUSED, AGENT_ERROR_DISCONNECTED, AGENT_ERROR_NOT_CONNECTED, HANDSHAKE_TIMEOUT_MILLIS, PONG_GRACE_INTERVALS, BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, DISCONNECT_REASON_SHUTDOWN, DISCONNECT_MESSAGES;
10585
+ var import_ws3, import_os8, CLOSE_CODE_REVOKED, CLOSE_CODE_NORMAL, CLOSE_TIMEOUT_MILLIS, TOKEN_HEADER, DEFAULT_SERVER, ERROR_ALREADY_CONNECTED, AGENT_ERROR_UNAUTHORIZED, AGENT_ERROR_HANDSHAKE_REFUSED, AGENT_ERROR_DISCONNECTED, AGENT_ERROR_NOT_CONNECTED, UNAUTHORIZED_STORED_TOKEN_MESSAGE, UNAUTHORIZED_NEW_TOKEN_MESSAGE, HANDSHAKE_TIMEOUT_MILLIS, PONG_GRACE_INTERVALS, BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC, DISCONNECT_REASON_SHUTDOWN, DISCONNECT_MESSAGES;
10029
10586
  var init_deviceAgent = __esm({
10030
10587
  "src/devices/deviceAgent.ts"() {
10031
10588
  "use strict";
@@ -10050,6 +10607,7 @@ var init_deviceAgent = __esm({
10050
10607
  init_ptySession();
10051
10608
  init_shellAllowlist();
10052
10609
  init_shellContext();
10610
+ init_foregroundAgent();
10053
10611
  init_deviceAgentReporter();
10054
10612
  CLOSE_CODE_REVOKED = 4001;
10055
10613
  CLOSE_CODE_NORMAL = 1e3;
@@ -10061,11 +10619,14 @@ var init_deviceAgent = __esm({
10061
10619
  AGENT_ERROR_HANDSHAKE_REFUSED = "handshake_refused";
10062
10620
  AGENT_ERROR_DISCONNECTED = "disconnected";
10063
10621
  AGENT_ERROR_NOT_CONNECTED = "not_connected";
10622
+ 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";
10623
+ UNAUTHORIZED_NEW_TOKEN_MESSAGE = "The dashboard refused this device token. Check the token, or copy the install command from the dashboard again.";
10064
10624
  HANDSHAKE_TIMEOUT_MILLIS = 3e4;
10065
10625
  PONG_GRACE_INTERVALS = 2;
10066
10626
  BASE_CAPABILITIES = ["tunnel", "stats", "tunnel_control", "tunnel_update", "saved_config_update"];
10067
10627
  CAPABILITY_TERMINAL = "terminal";
10068
10628
  CAPABILITY_TERMINAL_SNAPSHOT = "terminal_snapshot";
10629
+ CAPABILITY_TERMINAL_RESYNC = "terminal_resync";
10069
10630
  DISCONNECT_REASON_SHUTDOWN = "shutdown";
10070
10631
  DISCONNECT_MESSAGES = {
10071
10632
  revoked: "Credential revoked. Copy the new install command from the dashboard and run it to reconnect.",
@@ -10126,8 +10687,8 @@ function buildDashboardHttpUrl(manage) {
10126
10687
  }
10127
10688
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
10128
10689
  const baseUrl = buildDashboardHttpUrl(manage);
10129
- async function post(path12, body, schema) {
10130
- const response2 = await fetchImpl(`${baseUrl}/${path12}`, {
10690
+ async function post(path13, body, schema) {
10691
+ const response2 = await fetchImpl(`${baseUrl}/${path13}`, {
10131
10692
  method: "POST",
10132
10693
  headers: { "Content-Type": "application/json", Accept: "application/json" },
10133
10694
  body: JSON.stringify(body)
@@ -10201,13 +10762,13 @@ function createTerminalPrompter(input, output) {
10201
10762
  async ask(question, signal) {
10202
10763
  const readline = (0, import_promises.createInterface)({ input, output, terminal: true });
10203
10764
  try {
10204
- return await readline.question(question, signal ? { signal } : {});
10765
+ return await readline.question(marked(question), signal ? { signal } : {});
10205
10766
  } finally {
10206
10767
  readline.close();
10207
10768
  }
10208
10769
  },
10209
10770
  async askHidden(question, signal) {
10210
- output.write(question);
10771
+ output.write(marked(question));
10211
10772
  const readline = (0, import_promises.createInterface)({ input, output: discardingOutput(), terminal: true });
10212
10773
  try {
10213
10774
  const answer = await readline.question("", signal ? { signal } : {});
@@ -10222,6 +10783,9 @@ function createTerminalPrompter(input, output) {
10222
10783
  function isInteractiveTerminal() {
10223
10784
  return process.stdin.isTTY === true;
10224
10785
  }
10786
+ function marked(question) {
10787
+ return `${QUESTION_MARKER} ${question}`;
10788
+ }
10225
10789
  function discardingOutput() {
10226
10790
  return new import_stream.Writable({
10227
10791
  write(_chunk, _encoding, callback) {
@@ -10229,13 +10793,15 @@ function discardingOutput() {
10229
10793
  }
10230
10794
  });
10231
10795
  }
10232
- var import_promises, import_stream, terminalPrompter;
10796
+ var import_picocolors7, import_promises, import_stream, QUESTION_MARKER, terminalPrompter;
10233
10797
  var init_prompts = __esm({
10234
10798
  "src/devices/login/prompts.ts"() {
10235
10799
  "use strict";
10236
10800
  init_cjs_shims();
10801
+ import_picocolors7 = __toESM(require("picocolors"), 1);
10237
10802
  import_promises = require("readline/promises");
10238
10803
  import_stream = require("stream");
10804
+ QUESTION_MARKER = import_picocolors7.default.cyan(import_picocolors7.default.bold("\u2192"));
10239
10805
  terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
10240
10806
  }
10241
10807
  });
@@ -10262,6 +10828,20 @@ function machineDeviceLoginDependencies() {
10262
10828
  };
10263
10829
  }
10264
10830
  async function runDeviceLogin(options, dependencies = machineDeviceLoginDependencies()) {
10831
+ try {
10832
+ return await signInAndRunAgent(options, dependencies);
10833
+ } catch (err) {
10834
+ if (!isCtrlCAtPrompt(err)) {
10835
+ throw err;
10836
+ }
10837
+ dependencies.print(import_picocolors8.default.yellow("Sign-in cancelled."));
10838
+ return EXIT_FAILED;
10839
+ }
10840
+ }
10841
+ function isCtrlCAtPrompt(err) {
10842
+ return err instanceof Error && err.name === ABORT_ERROR_NAME;
10843
+ }
10844
+ async function signInAndRunAgent(options, dependencies) {
10265
10845
  if (!dependencies.isInteractive()) {
10266
10846
  dependencies.printError(NO_TERMINAL_MESSAGE);
10267
10847
  return EXIT_FAILED;
@@ -10273,7 +10853,7 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
10273
10853
  `This machine is already enrolled as ${stored.device_agent_id ?? "a device"} on ${stored.server}. Add it again as a new device? [y/N] `
10274
10854
  );
10275
10855
  if (!YES_ANSWER.test(answer.trim())) {
10276
- return await dependencies.runAgent(stored.token, manage) ?? EXIT_OK;
10856
+ return await dependencies.runAgent(stored.token, manage, false) ?? EXIT_OK;
10277
10857
  }
10278
10858
  }
10279
10859
  const email = (await dependencies.prompter.ask("Email: ")).trim();
@@ -10292,13 +10872,12 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
10292
10872
  ...options.name ? { name: options.name } : {}
10293
10873
  });
10294
10874
  linkMinutes = Math.round(started.expires_in_seconds / SECONDS_PER_MINUTE);
10295
- dependencies.print(`We sent a 6-digit code to ${email}. It works for ${linkMinutes} minutes.`);
10296
- if (started.match_code) {
10297
- dependencies.print("Type it below, or click Approve sign-in in the email.");
10298
- 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.`);
10299
- }
10875
+ printCodeSent(email, started.match_code, dependencies);
10300
10876
  approved = await waitForApproval(api, started.device_code, started.poll_interval_seconds, dependencies);
10301
10877
  } catch (err) {
10878
+ if (isCtrlCAtPrompt(err)) {
10879
+ throw err;
10880
+ }
10302
10881
  dependencies.printError(messageOf(err, manage));
10303
10882
  return EXIT_FAILED;
10304
10883
  }
@@ -10312,9 +10891,19 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
10312
10891
  server: manage || DEFAULT_SERVER2,
10313
10892
  enrolled_at: null
10314
10893
  });
10315
- dependencies.print(`Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
10894
+ dependencies.print(`${RESULT_MARKER} Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
10316
10895
  await printDeviceLink(approved, linkMinutes, dependencies);
10317
- return await dependencies.runAgent(approved.token, manage) ?? EXIT_OK;
10896
+ return await dependencies.runAgent(approved.token, manage, true) ?? EXIT_OK;
10897
+ }
10898
+ function printCodeSent(email, matchCode, dependencies) {
10899
+ dependencies.print("");
10900
+ if (matchCode) {
10901
+ dependencies.print(`Device Code: ${import_picocolors8.default.bold(import_picocolors8.default.yellow(matchCode))}`);
10902
+ dependencies.print("");
10903
+ }
10904
+ dependencies.print(`We have sent a 6-digit code to ${email}.`);
10905
+ dependencies.print(matchCode ? "Enter the code below or click the approve button in the email." : "Enter the code below.");
10906
+ dependencies.print("");
10318
10907
  }
10319
10908
  async function waitForApproval(api, deviceCode, pollIntervalSeconds, dependencies) {
10320
10909
  const controller = new AbortController();
@@ -10362,7 +10951,7 @@ async function typeTheCode(api, deviceCode, signal, prompt, dependencies) {
10362
10951
  }
10363
10952
  }
10364
10953
  if (answer.status === LoginStatus.Pending) {
10365
- dependencies.print("Approved from the email link. Waiting for the dashboard to finish.");
10954
+ dependencies.print(import_picocolors8.default.cyanBright("Approved from the email link. Waiting for the dashboard to finish..."));
10366
10955
  return waitUntilAborted(signal);
10367
10956
  }
10368
10957
  if (answer.status !== LoginStatus.Approved) {
@@ -10406,16 +10995,17 @@ async function pollUntilApproved(api, deviceCode, intervalMillis, signal, depend
10406
10995
  }
10407
10996
  async function printDeviceLink(approved, linkMinutes, dependencies) {
10408
10997
  let link;
10998
+ let label;
10409
10999
  if (approved.open_url) {
10410
11000
  link = approved.open_url;
10411
- dependencies.print(`Open the device in a browser. This link signs you in once, within ${linkMinutes} minutes:`);
11001
+ label = `Open the device in a browser. This link signs you in once, within ${linkMinutes} minutes:`;
10412
11002
  } else if (approved.device_url) {
10413
11003
  link = approved.device_url;
10414
- dependencies.print("Open the device in a browser:");
11004
+ label = "Open the device in a browser:";
10415
11005
  } else {
10416
11006
  return;
10417
11007
  }
10418
- dependencies.print(` ${link}`);
11008
+ printDeviceUrl((message) => dependencies.print(message), label, link);
10419
11009
  try {
10420
11010
  dependencies.print(await dependencies.renderQr(link));
10421
11011
  } catch {
@@ -10457,16 +11047,18 @@ function sleepUnlessAborted(millis, signal) {
10457
11047
  signal.addEventListener("abort", onAbort, { once: true });
10458
11048
  });
10459
11049
  }
10460
- var import_os9, EXIT_OK, EXIT_FAILED, DEFAULT_SERVER2, YES_ANSWER, SECONDS_PER_MINUTE, MILLIS_PER_SECOND2, FIRST_SERVER_ERROR_STATUS, NO_TERMINAL_MESSAGE;
11050
+ var import_os9, import_picocolors8, EXIT_OK, EXIT_FAILED, DEFAULT_SERVER2, YES_ANSWER, RESULT_MARKER, SECONDS_PER_MINUTE, MILLIS_PER_SECOND2, FIRST_SERVER_ERROR_STATUS, NO_TERMINAL_MESSAGE, ABORT_ERROR_NAME;
10461
11051
  var init_deviceLogin = __esm({
10462
11052
  "src/devices/login/deviceLogin.ts"() {
10463
11053
  "use strict";
10464
11054
  init_cjs_shims();
10465
11055
  import_os9 = __toESM(require("os"), 1);
11056
+ import_picocolors8 = __toESM(require("picocolors"), 1);
10466
11057
  init_printer();
10467
11058
  init_util();
10468
11059
  init_qrCodeGenerator();
10469
11060
  init_deviceAgent();
11061
+ init_deviceAgentReporter();
10470
11062
  init_deviceIdentity();
10471
11063
  init_loginApi();
10472
11064
  init_login_schema();
@@ -10475,10 +11067,12 @@ var init_deviceLogin = __esm({
10475
11067
  EXIT_FAILED = 1;
10476
11068
  DEFAULT_SERVER2 = "dashboard.pinggy.io";
10477
11069
  YES_ANSWER = /^y(es)?$/i;
11070
+ RESULT_MARKER = import_picocolors8.default.green(import_picocolors8.default.bold("\u2192"));
10478
11071
  SECONDS_PER_MINUTE = 60;
10479
11072
  MILLIS_PER_SECOND2 = 1e3;
10480
11073
  FIRST_SERVER_ERROR_STATUS = 500;
10481
11074
  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>";
11075
+ ABORT_ERROR_NAME = "AbortError";
10482
11076
  }
10483
11077
  });
10484
11078
 
@@ -10486,7 +11080,10 @@ var init_deviceLogin = __esm({
10486
11080
  function machineBackgroundAgentDependencies() {
10487
11081
  return {
10488
11082
  readIdentity: readDeviceIdentity,
11083
+ readForegroundAgent,
10489
11084
  findDaemon: getDaemonInfo,
11085
+ hasSavedAgent: () => savedDeviceAgent() !== null,
11086
+ forgetSavedAgent: forgetDeviceAgent,
10490
11087
  ensureDaemon: ensureDaemonRunning,
10491
11088
  client: (port) => new IPCClient(port, "cli"),
10492
11089
  verify: (token, manage) => startDeviceAgent(token, manage, {
@@ -10527,7 +11124,7 @@ async function readBackgroundAgent(dependencies) {
10527
11124
  return null;
10528
11125
  }
10529
11126
  }
10530
- async function startAgentInBackground(target, dependencies) {
11127
+ async function startAgentInBackground(target, dependencies, options = {}) {
10531
11128
  if (differsFromStored(target, dependencies.readIdentity())) {
10532
11129
  const verified = await dependencies.verify(target.token, target.manage);
10533
11130
  if (verified.error || !verified.welcomed) {
@@ -10535,7 +11132,6 @@ async function startAgentInBackground(target, dependencies) {
10535
11132
  return EXIT_FAILED;
10536
11133
  }
10537
11134
  }
10538
- dependencies.print("Starting the device agent in the background.");
10539
11135
  let daemon;
10540
11136
  try {
10541
11137
  daemon = await dependencies.ensureDaemon();
@@ -10554,18 +11150,20 @@ async function startAgentInBackground(target, dependencies) {
10554
11150
  dependencies.printError(daemonFailureMessage(err, daemon));
10555
11151
  return EXIT_FAILED;
10556
11152
  }
10557
- return waitUntilConnected(client, daemon, dependencies);
11153
+ printManageCommands(dependencies);
11154
+ dependencies.print(import_picocolors9.default.cyanBright("Starting the device agent in the background..."));
11155
+ return waitUntilConnected(client, daemon, options, dependencies);
10558
11156
  }
10559
11157
  async function stopAgentInBackground(dependencies) {
10560
11158
  const reading = await readBackgroundAgent(dependencies);
10561
11159
  if (!reading || !isAgentRunning(reading.status)) {
10562
- dependencies.print("No device agent is running in the background.");
11160
+ dependencies.print(import_picocolors9.default.yellow("No device agent is running in the background."));
10563
11161
  return EXIT_OK;
10564
11162
  }
10565
11163
  if (!await stopReadAgent(reading, dependencies)) {
10566
11164
  return EXIT_FAILED;
10567
11165
  }
10568
- 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.");
10569
11167
  return EXIT_OK;
10570
11168
  }
10571
11169
  async function stopAgentBeforeRemove(dependencies) {
@@ -10633,7 +11231,16 @@ function daemonFailureMessage(err, daemon) {
10633
11231
  }
10634
11232
  return `Could not reach the daemon: ${errorMessage(err)}`;
10635
11233
  }
10636
- async function waitUntilConnected(client, daemon, dependencies) {
11234
+ function printManageCommands(dependencies) {
11235
+ const commandWidth = Math.max(...MANAGE_COMMANDS.map(([command]) => command.length));
11236
+ dependencies.print("");
11237
+ dependencies.print("Manage this device:");
11238
+ for (const [command, purpose] of MANAGE_COMMANDS) {
11239
+ dependencies.print(` ${import_picocolors9.default.cyan(command.padEnd(commandWidth))} ${purpose}`);
11240
+ }
11241
+ dependencies.print("");
11242
+ }
11243
+ async function waitUntilConnected(client, daemon, options, dependencies) {
10637
11244
  const deadline = dependencies.now() + CONNECT_WAIT_MILLIS;
10638
11245
  for (; ; ) {
10639
11246
  let status;
@@ -10644,7 +11251,7 @@ async function waitUntilConnected(client, daemon, dependencies) {
10644
11251
  return EXIT_FAILED;
10645
11252
  }
10646
11253
  if (status.state === DeviceAgentState.Connected) {
10647
- printRunning(status, daemon, dependencies);
11254
+ printRunning(status, daemon, options, dependencies);
10648
11255
  return EXIT_OK;
10649
11256
  }
10650
11257
  if (status.state === DeviceAgentState.Stopped) {
@@ -10658,40 +11265,47 @@ async function waitUntilConnected(client, daemon, dependencies) {
10658
11265
  await dependencies.sleep(POLL_INTERVAL_MILLIS);
10659
11266
  }
10660
11267
  }
10661
- function printRunning(status, daemon, dependencies) {
11268
+ function printRunning(status, daemon, options, dependencies) {
10662
11269
  dependencies.printSuccess(`Running in the background as device ${status.deviceAgentId}`);
10663
- if (status.email) {
11270
+ if (status.email && !options.signInShown) {
10664
11271
  dependencies.print(`Signed in as ${status.email}`);
10665
11272
  }
10666
- if (status.deviceUrl) {
10667
- dependencies.print("Open the device in a browser:");
10668
- dependencies.print(` ${status.deviceUrl}`);
11273
+ if (status.deviceUrl && !options.signInShown) {
11274
+ printDeviceUrl((message) => dependencies.print(message), "Open the device in a browser:", status.deviceUrl);
10669
11275
  }
10670
11276
  if (daemon.host === DaemonHost.APP) {
10671
- dependencies.print("It runs inside the Pinggy app, and stops when the app quits.");
11277
+ dependencies.print(import_picocolors9.default.gray("It runs inside the Pinggy app, and stops when the app quits."));
10672
11278
  }
10673
- dependencies.print(`Logs: ${dependencies.daemonLogPath()}`);
10674
- dependencies.print("Stop it with: pinggy device stop");
11279
+ dependencies.print(import_picocolors9.default.gray(`Logs: ${dependencies.daemonLogPath()}`));
10675
11280
  }
10676
- var POLL_INTERVAL_MILLIS, CONNECT_WAIT_MILLIS, verifyingReporter;
11281
+ var import_picocolors9, POLL_INTERVAL_MILLIS, CONNECT_WAIT_MILLIS, MANAGE_COMMANDS, verifyingReporter;
10677
11282
  var init_backgroundAgent = __esm({
10678
11283
  "src/devices/backgroundAgent.ts"() {
10679
11284
  "use strict";
10680
11285
  init_cjs_shims();
11286
+ import_picocolors9 = __toESM(require("picocolors"), 1);
10681
11287
  init_logger();
10682
11288
  init_printer();
10683
11289
  init_configDir();
10684
11290
  init_util();
10685
11291
  init_types();
10686
11292
  init_daemonManager();
11293
+ init_daemonConfig();
10687
11294
  init_ipcClient();
10688
11295
  init_ipcRoutes();
10689
11296
  init_deviceIdentity();
10690
11297
  init_deviceAgent();
10691
11298
  init_deviceAgentReporter();
10692
11299
  init_deviceLogin();
11300
+ init_foregroundAgent();
10693
11301
  POLL_INTERVAL_MILLIS = 500;
10694
11302
  CONNECT_WAIT_MILLIS = 15e3;
11303
+ MANAGE_COMMANDS = [
11304
+ ["pinggy device status", "Show this device, and whether its agent runs"],
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"]
11308
+ ];
10695
11309
  verifyingReporter = {
10696
11310
  connecting: () => void 0,
10697
11311
  connected: () => void 0,
@@ -10725,7 +11339,7 @@ async function handleDaemon(args) {
10725
11339
  installService();
10726
11340
  return;
10727
11341
  case "service-uninstall":
10728
- uninstallService();
11342
+ await uninstallService();
10729
11343
  return;
10730
11344
  default:
10731
11345
  printer_default.error(`Unknown daemon command: "${verb}"`);
@@ -10740,17 +11354,17 @@ async function handleDaemonStart() {
10740
11354
  printer_default.error(ipcMismatchMessage(info));
10741
11355
  process.exit(1);
10742
11356
  }
10743
- printer_default.print(import_picocolors6.default.yellow(`Daemon already running (PID ${info.pid}, port ${info.port}). Use: pinggy daemon status for details.`));
11357
+ printer_default.print(import_picocolors10.default.yellow(`Daemon already running (PID ${info.pid}, port ${info.port}). Use: pinggy daemon status for details.`));
10744
11358
  return;
10745
11359
  }
10746
11360
  const autoConfigs = getAutoStartConfigs();
10747
11361
  if (autoConfigs.length > 0) {
10748
- printer_default.print(import_picocolors6.default.cyanBright(`Starting daemon with ${autoConfigs.length} auto-start tunnel(s):`));
11362
+ printer_default.print(import_picocolors10.default.cyanBright(`Starting daemon with ${autoConfigs.length} auto-start tunnel(s):`));
10749
11363
  for (const c of autoConfigs) {
10750
- printer_default.print(` ${import_picocolors6.default.bold(c.name)} (${c.configId.slice(0, 8)})`);
11364
+ printer_default.print(` ${import_picocolors10.default.bold(c.name)} (${c.configId.slice(0, 8)})`);
10751
11365
  }
10752
11366
  } else {
10753
- printer_default.print(import_picocolors6.default.cyanBright("Starting daemon..."));
11367
+ printer_default.print(import_picocolors10.default.cyanBright("Starting daemon..."));
10754
11368
  }
10755
11369
  try {
10756
11370
  const info2 = await startDaemon();
@@ -10762,7 +11376,7 @@ async function handleDaemonStart() {
10762
11376
  }
10763
11377
  async function handleDaemonStop() {
10764
11378
  if (!isDaemonRunning()) {
10765
- printer_default.print(import_picocolors6.default.yellow("No daemon is running."));
11379
+ printer_default.print(import_picocolors10.default.yellow("No daemon is running."));
10766
11380
  return;
10767
11381
  }
10768
11382
  const agent = await readBackgroundAgent(machineBackgroundAgentDependencies());
@@ -10773,7 +11387,7 @@ async function handleDaemonStop() {
10773
11387
  printer_default.print("The background device agent stopped too. The device shows offline in the dashboard.");
10774
11388
  }
10775
11389
  } else if (result.reason === DaemonHost.APP) {
10776
- printer_default.print(import_picocolors6.default.yellow("The Pinggy daemon is running inside the Pinggy desktop app. Please quit the Pinggy app to stop it."));
11390
+ printer_default.print(import_picocolors10.default.yellow("The Pinggy daemon is running inside the Pinggy desktop app. Please quit the Pinggy app to stop it."));
10777
11391
  } else {
10778
11392
  printer_default.error(result.error);
10779
11393
  }
@@ -10781,7 +11395,7 @@ async function handleDaemonStop() {
10781
11395
  async function handleDaemonStatus() {
10782
11396
  const info = getDaemonInfo();
10783
11397
  if (!info) {
10784
- printer_default.print(import_picocolors6.default.yellow("No daemon is running. Start with: pinggy daemon start"));
11398
+ printer_default.print(import_picocolors10.default.yellow("No daemon is running. Start with: pinggy daemon start"));
10785
11399
  return;
10786
11400
  }
10787
11401
  const uptimeSec = Math.floor((Date.now() - new Date(info.startedAt).getTime()) / 1e3);
@@ -10789,7 +11403,7 @@ async function handleDaemonStatus() {
10789
11403
  const m = Math.floor(uptimeSec % 3600 / 60);
10790
11404
  const s = uptimeSec % 60;
10791
11405
  const uptimeStr = h > 0 ? `${h}h ${m}m ${s}s` : m > 0 ? `${m}m ${s}s` : `${s}s`;
10792
- printer_default.print(import_picocolors6.default.cyanBright("Daemon Status"));
11406
+ printer_default.print(import_picocolors10.default.cyanBright("Daemon Status"));
10793
11407
  printer_default.print(` PID: ${info.pid}`);
10794
11408
  printer_default.print(` Port: ${info.port}`);
10795
11409
  printer_default.print(` Started: ${info.startedAt}`);
@@ -10797,20 +11411,20 @@ async function handleDaemonStatus() {
10797
11411
  printer_default.print(` Host: ${info.host === DaemonHost.APP ? "Pinggy app (in-process)" : "standalone (CLI)"}`);
10798
11412
  printer_default.print(` IPC: v${daemonIpcVersion(info)}`);
10799
11413
  if (!isIpcCompatible(info)) {
10800
- printer_default.print(import_picocolors6.default.yellow(` Warning: ${ipcMismatchMessage(info)}`));
11414
+ printer_default.print(import_picocolors10.default.yellow(` Warning: ${ipcMismatchMessage(info)}`));
10801
11415
  }
10802
11416
  const agent = await readBackgroundAgent(machineBackgroundAgentDependencies());
10803
11417
  if (agent) {
10804
11418
  printer_default.print(` Device: ${describeAgentForDaemonStatus(agent.status)}`);
10805
11419
  }
10806
11420
  }
10807
- var import_picocolors6;
11421
+ var import_picocolors10;
10808
11422
  var init_daemonCommandsHandler = __esm({
10809
11423
  "src/cli/subcommand/handlers/daemonCommandsHandler.ts"() {
10810
11424
  "use strict";
10811
11425
  init_cjs_shims();
10812
11426
  init_printer();
10813
- import_picocolors6 = __toESM(require("picocolors"), 1);
11427
+ import_picocolors10 = __toESM(require("picocolors"), 1);
10814
11428
  init_configStore();
10815
11429
  init_daemonManager();
10816
11430
  init_ipcRoutes();
@@ -10825,7 +11439,10 @@ var init_daemonCommandsHandler = __esm({
10825
11439
  async function handlePs() {
10826
11440
  const client = new TunnelClient();
10827
11441
  try {
10828
- await client.ensureDaemon();
11442
+ if (!client.connectIfRunning()) {
11443
+ printer_default.print("No active tunnels. The daemon is not running.");
11444
+ return;
11445
+ }
10829
11446
  } catch (err) {
10830
11447
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
10831
11448
  return;
@@ -10837,21 +11454,21 @@ async function handlePs() {
10837
11454
  return;
10838
11455
  }
10839
11456
  if (tunnels.length === 0) {
10840
- printer_default.print("No tunnels running.");
11457
+ printer_default.print("No active tunnels.");
10841
11458
  return;
10842
11459
  }
10843
11460
  const header = `${pad("ID", 14)} ${pad("NAME", 16)} ${pad("STATUS", 10)} ${pad("LOCAL", 20)} URL`;
10844
- printer_default.print(import_picocolors7.default.gray(header));
10845
- printer_default.print(import_picocolors7.default.gray("\u2500".repeat(90)));
11461
+ printer_default.print(import_picocolors11.default.gray(header));
11462
+ printer_default.print(import_picocolors11.default.gray("\u2500".repeat(90)));
10846
11463
  for (const t of tunnels) {
10847
11464
  const id = t.tunnelid.slice(0, 12);
10848
11465
  const name = t.tunnelconfig?.name || "-";
10849
11466
  const status = t.status.state;
10850
11467
  const local = getLocalAddress(t.tunnelconfig);
10851
11468
  const url = t.remoteurls?.[0] || "-";
10852
- const statusColor = status === "running" ? import_picocolors7.default.green : status === "starting" ? import_picocolors7.default.yellow : import_picocolors7.default.red;
11469
+ const statusColor = status === "running" ? import_picocolors11.default.green : status === "starting" ? import_picocolors11.default.yellow : import_picocolors11.default.red;
10853
11470
  printer_default.print(
10854
- `${import_picocolors7.default.cyan(pad(id, 14))} ${pad(name, 16)} ${statusColor(pad(status, 10))} ${pad(local, 20)} ${import_picocolors7.default.magentaBright(url)}`
11471
+ `${import_picocolors11.default.cyan(pad(id, 14))} ${pad(name, 16)} ${statusColor(pad(status, 10))} ${pad(local, 20)} ${import_picocolors11.default.magentaBright(url)}`
10855
11472
  );
10856
11473
  }
10857
11474
  } catch (err) {
@@ -10863,7 +11480,7 @@ async function handlePs() {
10863
11480
  function pad(str, len) {
10864
11481
  return str.length >= len ? str.slice(0, len) : str + " ".repeat(len - str.length);
10865
11482
  }
10866
- var import_picocolors7;
11483
+ var import_picocolors11;
10867
11484
  var init_psCommand = __esm({
10868
11485
  "src/cli/subcommand/handlers/psCommand.ts"() {
10869
11486
  "use strict";
@@ -10872,7 +11489,7 @@ var init_psCommand = __esm({
10872
11489
  init_types();
10873
11490
  init_printer();
10874
11491
  init_util();
10875
- import_picocolors7 = __toESM(require("picocolors"), 1);
11492
+ import_picocolors11 = __toESM(require("picocolors"), 1);
10876
11493
  }
10877
11494
  });
10878
11495
 
@@ -10884,7 +11501,10 @@ async function handleStop(args) {
10884
11501
  }
10885
11502
  const client = new TunnelClient();
10886
11503
  try {
10887
- await client.ensureDaemon();
11504
+ if (!client.connectIfRunning()) {
11505
+ printer_default.print("Nothing to stop. No tunnels are running.");
11506
+ return;
11507
+ }
10888
11508
  } catch (err) {
10889
11509
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
10890
11510
  return;
@@ -10945,6 +11565,25 @@ var init_stopCommand = __esm({
10945
11565
  }
10946
11566
  });
10947
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
+
10948
11587
  // src/cli/subcommand/handlers/attachCommand.ts
10949
11588
  async function handleAttach(args) {
10950
11589
  if (args.length === 0) {
@@ -10954,7 +11593,10 @@ async function handleAttach(args) {
10954
11593
  const nameOrId = args[0];
10955
11594
  const client = new TunnelClient();
10956
11595
  try {
10957
- await client.ensureDaemon();
11596
+ if (!client.connectIfRunning()) {
11597
+ printer_default.error(tunnelNotRunningMessage(nameOrId));
11598
+ return;
11599
+ }
10958
11600
  } catch (err) {
10959
11601
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
10960
11602
  return;
@@ -10973,14 +11615,14 @@ async function handleAttach(args) {
10973
11615
  }
10974
11616
  const tunnelId = match.tunnelid;
10975
11617
  const name = match.tunnelconfig?.name || tunnelId.slice(0, 12);
10976
- printer_default.print(import_picocolors8.default.cyanBright(`Attaching to tunnel "${name}"...`));
11618
+ printer_default.print(import_picocolors12.default.cyanBright(`Attaching to tunnel "${name}"...`));
10977
11619
  const attachMode = match.mode ?? "detached";
10978
11620
  await client.attach(tunnelId, attachMode);
10979
11621
  const urls = match.remoteurls || [];
10980
11622
  if (urls.length > 0) {
10981
11623
  printer_default.print("");
10982
11624
  for (const url of urls) {
10983
- printer_default.print(" " + import_picocolors8.default.magentaBright(url));
11625
+ printer_default.print(" " + import_picocolors12.default.magentaBright(url));
10984
11626
  }
10985
11627
  printer_default.print("");
10986
11628
  }
@@ -10999,26 +11641,117 @@ async function handleAttach(args) {
10999
11641
  client.close();
11000
11642
  }
11001
11643
  }
11002
- var import_picocolors8;
11644
+ var import_picocolors12;
11003
11645
  var init_attachCommand = __esm({
11004
11646
  "src/cli/subcommand/handlers/attachCommand.ts"() {
11005
11647
  "use strict";
11006
11648
  init_cjs_shims();
11007
- import_picocolors8 = __toESM(require("picocolors"), 1);
11649
+ import_picocolors12 = __toESM(require("picocolors"), 1);
11008
11650
  init_printer();
11009
11651
  init_tunnelClient();
11010
11652
  init_types();
11011
11653
  init_startCli();
11012
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();
11013
11746
  }
11014
11747
  });
11015
11748
 
11016
11749
  // src/cli/subcommand/handlers/logsCommand.ts
11017
11750
  async function handleLogs(args, follow) {
11018
11751
  const arg = args.find((a) => !a.startsWith("-"));
11019
- const client = new TunnelClient();
11752
+ let client;
11020
11753
  try {
11021
- await client.ensureDaemon();
11754
+ client = openLogLookup();
11022
11755
  } catch (err) {
11023
11756
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11024
11757
  return;
@@ -11026,7 +11759,7 @@ async function handleLogs(args, follow) {
11026
11759
  let filePath;
11027
11760
  try {
11028
11761
  if (arg) {
11029
- const result = await client.resolveLogPath(arg);
11762
+ const result = await client.resolve(arg);
11030
11763
  if (result.status === "config-only") {
11031
11764
  printer_default.error(`Tunnel "${arg}" is saved but has not been started yet. No logs available.`);
11032
11765
  client.close();
@@ -11044,8 +11777,7 @@ async function handleLogs(args, follow) {
11044
11777
  }
11045
11778
  filePath = result.path;
11046
11779
  } else {
11047
- const paths = await client.getLogPaths();
11048
- filePath = paths.daemon;
11780
+ filePath = await client.daemonLogPath();
11049
11781
  }
11050
11782
  } catch (err) {
11051
11783
  printer_default.error(`Failed to resolve log path: ${errorMessage(err)}`);
@@ -11053,7 +11785,7 @@ async function handleLogs(args, follow) {
11053
11785
  return;
11054
11786
  }
11055
11787
  client.close();
11056
- if (!filePath || !import_node_fs4.default.existsSync(filePath)) {
11788
+ if (!filePath || !import_node_fs5.default.existsSync(filePath)) {
11057
11789
  printer_default.error(`Log file not found: ${filePath}`);
11058
11790
  process.exit(1);
11059
11791
  }
@@ -11064,18 +11796,18 @@ async function handleLogs(args, follow) {
11064
11796
  }
11065
11797
  }
11066
11798
  function printTail(filePath, lines) {
11067
- const content = import_node_fs4.default.readFileSync(filePath, "utf-8");
11799
+ const content = import_node_fs5.default.readFileSync(filePath, "utf-8");
11068
11800
  const allLines = content.split("\n");
11069
11801
  const tail = allLines.slice(-lines).join("\n");
11070
11802
  process.stdout.write(tail);
11071
11803
  if (!tail.endsWith("\n")) process.stdout.write("\n");
11072
11804
  }
11073
11805
  async function followFile(filePath) {
11074
- if (import_node_fs4.default.existsSync(filePath)) printTail(filePath, 20);
11075
- 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;
11076
11808
  let watcher = null;
11077
11809
  const openStream = () => {
11078
- 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" });
11079
11811
  stream.on("data", (chunk) => {
11080
11812
  process.stdout.write(chunk);
11081
11813
  fileSize += Buffer.byteLength(chunk, "utf-8");
@@ -11083,9 +11815,9 @@ async function followFile(filePath) {
11083
11815
  stream.on("error", () => {
11084
11816
  });
11085
11817
  };
11086
- watcher = import_node_fs4.default.watch(filePath, { persistent: true }, (event2) => {
11818
+ watcher = import_node_fs5.default.watch(filePath, { persistent: true }, (event2) => {
11087
11819
  if (event2 === "change") {
11088
- 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;
11089
11821
  if (!stat || stat.size < fileSize) {
11090
11822
  fileSize = 0;
11091
11823
  }
@@ -11099,13 +11831,13 @@ async function followFile(filePath) {
11099
11831
  });
11100
11832
  });
11101
11833
  }
11102
- var import_node_fs4;
11834
+ var import_node_fs5;
11103
11835
  var init_logsCommand = __esm({
11104
11836
  "src/cli/subcommand/handlers/logsCommand.ts"() {
11105
11837
  "use strict";
11106
11838
  init_cjs_shims();
11107
- import_node_fs4 = __toESM(require("fs"), 1);
11108
- init_tunnelClient();
11839
+ import_node_fs5 = __toESM(require("fs"), 1);
11840
+ init_logLookup();
11109
11841
  init_printer();
11110
11842
  init_util();
11111
11843
  }
@@ -11131,26 +11863,39 @@ async function handleLog(args) {
11131
11863
  printLogHelp();
11132
11864
  }
11133
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
+ }
11134
11882
  async function handleLogLevel(args) {
11883
+ const level = args.length > 0 ? parseLevel(args[0]) : void 0;
11135
11884
  const client = new TunnelClient();
11136
11885
  try {
11137
- await client.ensureDaemon();
11886
+ if (!client.connectIfRunning()) {
11887
+ handleLogLevelWithoutDaemon(level);
11888
+ return;
11889
+ }
11138
11890
  } catch (err) {
11139
11891
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11140
11892
  return;
11141
11893
  }
11142
11894
  try {
11143
- if (args.length === 0) {
11144
- const level2 = await client.getLogLevel();
11145
- printer_default.print(`Log level: ${level2}`);
11895
+ if (!level) {
11896
+ printer_default.print(`Log level: ${await client.getLogLevel()}`);
11146
11897
  return;
11147
11898
  }
11148
- const level = args[0].toLowerCase();
11149
- if (!VALID_LEVELS.includes(level)) {
11150
- printer_default.error(`Invalid log level: "${level}". Must be one of: ${VALID_LEVELS.join(", ")}`);
11151
- client.close();
11152
- process.exit(1);
11153
- }
11154
11899
  await client.setLogLevel(level);
11155
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.`);
11156
11901
  } catch (err) {
@@ -11160,21 +11905,20 @@ async function handleLogLevel(args) {
11160
11905
  }
11161
11906
  }
11162
11907
  async function handleLogPath(args) {
11163
- const client = new TunnelClient();
11908
+ let client;
11164
11909
  try {
11165
- await client.ensureDaemon();
11910
+ client = openLogLookup();
11166
11911
  } catch (err) {
11167
11912
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11168
11913
  return;
11169
11914
  }
11170
11915
  try {
11171
11916
  if (args.length === 0) {
11172
- const paths = await client.getLogPaths();
11173
- printer_default.print(paths.daemon);
11917
+ printer_default.print(await client.daemonLogPath());
11174
11918
  return;
11175
11919
  }
11176
11920
  const arg = args[0];
11177
- const result = await client.resolveLogPath(arg);
11921
+ const result = await client.resolve(arg);
11178
11922
  switch (result.status) {
11179
11923
  case "running":
11180
11924
  case "historical":
@@ -11203,6 +11947,8 @@ var init_logCommand = __esm({
11203
11947
  "use strict";
11204
11948
  init_cjs_shims();
11205
11949
  init_tunnelClient();
11950
+ init_daemonConfig();
11951
+ init_logLookup();
11206
11952
  init_helpMessages();
11207
11953
  init_printer();
11208
11954
  init_util();
@@ -11219,7 +11965,10 @@ async function handleRestart(args) {
11219
11965
  const nameOrId = args[0];
11220
11966
  const client = new TunnelClient();
11221
11967
  try {
11222
- await client.ensureDaemon();
11968
+ if (!client.connectIfRunning()) {
11969
+ printer_default.error(tunnelNotRunningMessage(nameOrId));
11970
+ process.exit(1);
11971
+ }
11223
11972
  } catch (err) {
11224
11973
  printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
11225
11974
  return;
@@ -11257,6 +12006,100 @@ var init_restartCommand = __esm({
11257
12006
  init_printer();
11258
12007
  init_util();
11259
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.";
11260
12103
  }
11261
12104
  });
11262
12105
 
@@ -11288,7 +12131,11 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
11288
12131
  const flagArgs = args.slice(1);
11289
12132
  const { values } = parseCliArgs(cliOptions, flagArgs);
11290
12133
  configureLogger(values);
11291
- const inBackground = Boolean(values.b);
12134
+ if (values.b && values.foreground) {
12135
+ printer_default.error("-b and --foreground contradict each other. The agent runs in the background unless --foreground is given.");
12136
+ process.exit(1);
12137
+ }
12138
+ const inBackground = !values.foreground;
11292
12139
  switch (verb) {
11293
12140
  case DeviceVerb.Login:
11294
12141
  exitUnlessOk(await handleDeviceLogin(values.manage, values.name, inBackground, background));
@@ -11309,7 +12156,10 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
11309
12156
  await handleDeviceStatus(background);
11310
12157
  return;
11311
12158
  case DeviceVerb.Remove:
11312
- exitUnlessOk(await handleDeviceRemove(background));
12159
+ exitUnlessOk(await runDeviceRemove(
12160
+ { skipConfirmation: Boolean(values.force) },
12161
+ machineDeviceRemoveDependencies(background)
12162
+ ));
11313
12163
  return;
11314
12164
  default:
11315
12165
  if (verb === "help" || verb === "--help" || verb === "-h") {
@@ -11335,7 +12185,15 @@ function devicesSpellingMessage(args) {
11335
12185
  return `"pinggy devices" is now "pinggy device". Run: pinggy device ${suggestion}`;
11336
12186
  }
11337
12187
  async function mayRunInForeground(background) {
11338
- 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());
11339
12197
  if (refusal) {
11340
12198
  printer_default.error(refusal);
11341
12199
  return false;
@@ -11347,9 +12205,10 @@ async function handleDeviceLogin(manage, name, inBackground, background) {
11347
12205
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
11348
12206
  return runDeviceLogin({ manage, name });
11349
12207
  }
12208
+ if (!mayRunInBackground(background)) return EXIT_FAILED;
11350
12209
  return runDeviceLogin({ manage, name }, {
11351
12210
  ...machineDeviceLoginDependencies(),
11352
- runAgent: (token, agentManage) => startAgentInBackground({ token, manage: agentManage }, background)
12211
+ runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
11353
12212
  });
11354
12213
  }
11355
12214
  async function handleDeviceConnect(flagToken, environmentToken, manage, inBackground, background) {
@@ -11359,6 +12218,7 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
11359
12218
  return EXIT_FAILED;
11360
12219
  }
11361
12220
  if (inBackground) {
12221
+ if (!mayRunInBackground(background)) return EXIT_FAILED;
11362
12222
  return startAgentInBackground(target, background);
11363
12223
  }
11364
12224
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
@@ -11368,33 +12228,26 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
11368
12228
  async function handleDeviceStatus(background) {
11369
12229
  const identity = background.readIdentity();
11370
12230
  if (!identity) {
11371
- printer_default.print("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"));
11372
12232
  return;
11373
12233
  }
11374
- printer_default.print(` Device id ${identity.device_agent_id ?? import_picocolors9.default.gray("not yet assigned")}`);
12234
+ printer_default.print(` Device id ${identity.device_agent_id ?? import_picocolors14.default.gray("not yet assigned")}`);
11375
12235
  printer_default.print(` Server ${identity.server}`);
11376
12236
  printer_default.print(` Token ${maskToken(identity.token)}`);
11377
- printer_default.print(` Enrolled ${identity.enrolled_at ?? import_picocolors9.default.gray("never")}`);
11378
- await printBackgroundStatus(background);
11379
- }
11380
- async function handleDeviceRemove(background) {
11381
- if (!await stopAgentBeforeRemove(background)) {
11382
- return EXIT_FAILED;
11383
- }
11384
- if (clearDeviceIdentity()) {
11385
- printer_default.success("Local device credential removed.");
11386
- printer_default.print(import_picocolors9.default.gray("The device still exists in the dashboard. Delete it there to revoke it."));
11387
- } else {
11388
- printer_default.print("This machine is not enrolled.");
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}`);
11389
12242
  }
11390
- return EXIT_OK;
12243
+ await printBackgroundStatus(background);
11391
12244
  }
11392
- var import_picocolors9, DeviceVerb, DEVICE_AGENT_TOKEN_VARIABLE;
12245
+ var import_picocolors14, DeviceVerb, DEVICE_AGENT_TOKEN_VARIABLE;
11393
12246
  var init_deviceCommand = __esm({
11394
12247
  "src/cli/subcommand/handlers/deviceCommand.ts"() {
11395
12248
  "use strict";
11396
12249
  init_cjs_shims();
11397
- import_picocolors9 = __toESM(require("picocolors"), 1);
12250
+ import_picocolors14 = __toESM(require("picocolors"), 1);
11398
12251
  init_options();
11399
12252
  init_parseArgs();
11400
12253
  init_logger();
@@ -11404,6 +12257,8 @@ var init_deviceCommand = __esm({
11404
12257
  init_deviceIdentity();
11405
12258
  init_deviceLogin();
11406
12259
  init_backgroundAgent();
12260
+ init_foregroundAgent();
12261
+ init_removeDevice();
11407
12262
  DeviceVerb = {
11408
12263
  Login: "login",
11409
12264
  Connect: "connect",
@@ -11754,7 +12609,7 @@ async function main() {
11754
12609
  printer_default.fatal(error);
11755
12610
  }
11756
12611
  }
11757
- var import_url2, import_process, import_fs13, currentFile, entryFile;
12612
+ var import_url2, import_process, import_fs14, currentFile, entryFile;
11758
12613
  var init_main = __esm({
11759
12614
  "src/main.ts"() {
11760
12615
  "use strict";
@@ -11769,7 +12624,7 @@ var init_main = __esm({
11769
12624
  init_handler();
11770
12625
  import_url2 = require("url");
11771
12626
  import_process = require("process");
11772
- import_fs13 = require("fs");
12627
+ import_fs14 = require("fs");
11773
12628
  init_remoteManagement();
11774
12629
  init_buildAndStartTunnel();
11775
12630
  init_subcommands();
@@ -11779,7 +12634,7 @@ var init_main = __esm({
11779
12634
  currentFile = (0, import_url2.fileURLToPath)(importMetaUrl);
11780
12635
  entryFile = null;
11781
12636
  try {
11782
- 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;
11783
12638
  } catch (e) {
11784
12639
  entryFile = null;
11785
12640
  }
@@ -11821,13 +12676,13 @@ var init_wsProtocol = __esm({
11821
12676
 
11822
12677
  // src/daemon/lifecycle/stateStore.ts
11823
12678
  function getStatePath() {
11824
- return import_node_path3.default.join(getPinggyConfigDir(), STATE_FILENAME);
12679
+ return import_node_path4.default.join(getPinggyConfigDir(), STATE_FILENAME);
11825
12680
  }
11826
12681
  function loadDaemonState() {
11827
12682
  const statePath = getStatePath();
11828
12683
  try {
11829
- if (!import_node_fs5.default.existsSync(statePath)) return null;
11830
- 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");
11831
12686
  const state = JSON.parse(raw);
11832
12687
  if (!Array.isArray(state.tunnels)) return null;
11833
12688
  return state;
@@ -11841,8 +12696,8 @@ function persistDaemonState(state) {
11841
12696
  const tmpPath = statePath + ".tmp";
11842
12697
  try {
11843
12698
  state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
11844
- import_node_fs5.default.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
11845
- 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);
11846
12701
  } catch (err) {
11847
12702
  logger.error("Failed to persist daemon state", { error: errorMessage(err) });
11848
12703
  }
@@ -11850,8 +12705,8 @@ function persistDaemonState(state) {
11850
12705
  function clearDaemonState() {
11851
12706
  const statePath = getStatePath();
11852
12707
  try {
11853
- if (import_node_fs5.default.existsSync(statePath)) {
11854
- import_node_fs5.default.unlinkSync(statePath);
12708
+ if (import_node_fs6.default.existsSync(statePath)) {
12709
+ import_node_fs6.default.unlinkSync(statePath);
11855
12710
  }
11856
12711
  } catch {
11857
12712
  }
@@ -11863,13 +12718,13 @@ function addTunnelToState(state, tunnel) {
11863
12718
  function removeTunnelFromState(state, tunnelId) {
11864
12719
  state.tunnels = state.tunnels.filter((t) => t.tunnelId !== tunnelId);
11865
12720
  }
11866
- var import_node_fs5, import_node_path3, STATE_FILENAME;
12721
+ var import_node_fs6, import_node_path4, STATE_FILENAME;
11867
12722
  var init_stateStore = __esm({
11868
12723
  "src/daemon/lifecycle/stateStore.ts"() {
11869
12724
  "use strict";
11870
12725
  init_cjs_shims();
11871
- import_node_fs5 = __toESM(require("fs"), 1);
11872
- import_node_path3 = __toESM(require("path"), 1);
12726
+ import_node_fs6 = __toESM(require("fs"), 1);
12727
+ import_node_path4 = __toESM(require("path"), 1);
11873
12728
  init_configDir();
11874
12729
  init_logger();
11875
12730
  init_util();
@@ -11881,50 +12736,34 @@ var init_stateStore = __esm({
11881
12736
  function parseOrigin(req) {
11882
12737
  const raw = req.headers["x-pinggy-origin"];
11883
12738
  const v = Array.isArray(raw) ? raw[0] : raw;
11884
- return v && VALID_ORIGINS.includes(v) ? v : "cli";
12739
+ return v && TUNNEL_ORIGINS.includes(v) ? v : "cli";
11885
12740
  }
11886
12741
  function parseBody(method, body) {
11887
12742
  if (method === "GET") return void 0;
11888
12743
  if (!body) return {};
11889
12744
  return JSON.parse(body);
11890
12745
  }
11891
- function parseTunnelLogFilename(filename) {
11892
- const base = filename.replace(/\.log$/, "");
11893
- const parts = base.split("__");
11894
- if (parts.length < 2) return null;
11895
- const origin = parts[0];
11896
- if (!VALID_ORIGINS.includes(origin)) return null;
11897
- if (parts.length === 2) {
11898
- const second = parts[1];
11899
- if (UUID_RE.test(second)) return { origin, tunnelId: second };
11900
- return { origin, name: second };
11901
- }
11902
- const tunnelId = parts[parts.length - 1];
11903
- const name = parts.slice(1, -1).join("__");
11904
- return { origin, name, tunnelId };
11905
- }
11906
- 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;
11907
12747
  var init_ipcServer = __esm({
11908
12748
  "src/daemon/ipc/ipcServer.ts"() {
11909
12749
  "use strict";
11910
12750
  init_cjs_shims();
11911
12751
  import_node_http2 = __toESM(require("http"), 1);
11912
- import_node_fs6 = __toESM(require("fs"), 1);
11913
- import_node_path4 = __toESM(require("path"), 1);
12752
+ import_node_fs7 = __toESM(require("fs"), 1);
12753
+ import_node_path5 = __toESM(require("path"), 1);
11914
12754
  import_ws4 = require("ws");
11915
12755
  init_main();
11916
12756
  init_logger();
11917
12757
  init_tunnelLogger();
11918
12758
  init_configStore();
11919
12759
  init_configDir();
12760
+ init_logPaths();
11920
12761
  init_util();
11921
12762
  init_ipcRoutes();
11922
12763
  init_wsProtocol();
11923
12764
  init_types();
11924
12765
  init_daemonChild();
11925
12766
  init_stateStore();
11926
- VALID_ORIGINS = ["app", "cli", "remote", "device"];
11927
- UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11928
12767
  IPCServer = class {
11929
12768
  constructor() {
11930
12769
  this.sessions = /* @__PURE__ */ new Map();
@@ -12060,8 +12899,8 @@ var init_ipcServer = __esm({
12060
12899
  const logDir = getTunnelLogDir();
12061
12900
  const daemonPath = getDaemonLogPath();
12062
12901
  const tunnels = [];
12063
- if (import_node_fs6.default.existsSync(logDir)) {
12064
- 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) {
12065
12904
  const manager = TunnelManager.getInstance();
12066
12905
  const activeIds = manager.getActiveTunnelIds();
12067
12906
  const activeNames = /* @__PURE__ */ new Set();
@@ -12071,8 +12910,8 @@ var init_ipcServer = __esm({
12071
12910
  if (n) activeNames.add(n);
12072
12911
  }
12073
12912
  for (const file of files) {
12074
- const filePath = import_node_path4.default.join(logDir, file);
12075
- 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);
12076
12915
  const parsed = parseTunnelLogFilename(file);
12077
12916
  if (!parsed) continue;
12078
12917
  const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
@@ -12179,7 +13018,6 @@ var init_ipcServer = __esm({
12179
13018
  }
12180
13019
  async resolveLogPath(q) {
12181
13020
  if (!q) return { status: "not-found" };
12182
- const logDir = getTunnelLogDir();
12183
13021
  const manager = TunnelManager.getInstance();
12184
13022
  const activeIds = manager.getActiveTunnelIds();
12185
13023
  for (const t of await manager.getAllTunnels()) {
@@ -12191,32 +13029,7 @@ var init_ipcServer = __esm({
12191
13029
  return { status: "running", path: logPath, tunnelId: t.tunnelid, name, origin, running: true };
12192
13030
  }
12193
13031
  }
12194
- if (import_node_fs6.default.existsSync(logDir)) {
12195
- const files = import_node_fs6.default.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
12196
- const matches = [];
12197
- for (const file of files) {
12198
- const parsed = parseTunnelLogFilename(file);
12199
- if (!parsed) continue;
12200
- const nameMatch = parsed.name !== void 0 && parsed.name === q;
12201
- const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
12202
- if (nameMatch || idMatch) {
12203
- const filePath = import_node_path4.default.join(logDir, file);
12204
- const stat = import_node_fs6.default.statSync(filePath);
12205
- matches.push({ path: filePath, mtime: stat.mtimeMs, tunnelId: parsed.tunnelId, name: parsed.name, origin: parsed.origin });
12206
- }
12207
- }
12208
- if (matches.length > 0) {
12209
- matches.sort((a, b) => b.mtime - a.mtime);
12210
- const best = matches[0];
12211
- return { status: "historical", path: best.path, tunnelId: best.tunnelId, name: best.name, origin: best.origin, running: false };
12212
- }
12213
- }
12214
- const saved = listSavedConfigs();
12215
- const matchedConfig = saved.find((c) => c.name === q || c.configId === q || c.configId.startsWith(q));
12216
- if (matchedConfig) {
12217
- return { status: "config-only", name: matchedConfig.name, configId: matchedConfig.configId };
12218
- }
12219
- return { status: "not-found" };
13032
+ return resolveStoppedLogPath(q);
12220
13033
  }
12221
13034
  setupWebSocket() {
12222
13035
  this.server.on("upgrade", (req, socket, head) => {
@@ -12626,7 +13439,7 @@ var init_deviceAgentHost = __esm({
12626
13439
  this.statusValue = stoppedStatus();
12627
13440
  /** Bumped on every start and stop. A run's reporter whose number is old belongs to a run that ended. */
12628
13441
  this.generation = 0;
12629
- /** 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. */
12630
13443
  this.closed = false;
12631
13444
  /** Start and stop chain on this, so 1 finishes before the next begins. */
12632
13445
  this.queue = Promise.resolve();
@@ -12664,8 +13477,8 @@ var init_deviceAgentHost = __esm({
12664
13477
  });
12665
13478
  }
12666
13479
  /**
12667
- * The daemon is shutting down. Stops the run at once, outside the queue, and writes nothing to
12668
- * 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.
12669
13482
  */
12670
13483
  close() {
12671
13484
  this.closed = true;
@@ -12708,9 +13521,6 @@ var init_deviceAgentHost = __esm({
12708
13521
  this.current = null;
12709
13522
  this.generation += 1;
12710
13523
  this.statusValue = { ...this.statusValue, state: DeviceAgentState.Stopped, connectedAt: null };
12711
- if (!this.closed) {
12712
- this.dependencies.recordStopped();
12713
- }
12714
13524
  await current.run.stop();
12715
13525
  logger.info("Device agent stopped in the daemon");
12716
13526
  }
@@ -12774,6 +13584,66 @@ var init_deviceAgentHost = __esm({
12774
13584
  }
12775
13585
  });
12776
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
+
12777
13647
  // src/daemon/lifecycle/daemonChild.ts
12778
13648
  var daemonChild_exports = {};
12779
13649
  __export(daemonChild_exports, {
@@ -12782,8 +13652,6 @@ __export(daemonChild_exports, {
12782
13652
  removeDaemonInfo: () => removeDaemonInfo,
12783
13653
  runDaemonChild: () => runDaemonChild,
12784
13654
  setDaemonSessionTracker: () => setDaemonSessionTracker,
12785
- trackDeviceAgentStart: () => trackDeviceAgentStart,
12786
- trackDeviceAgentStop: () => trackDeviceAgentStop,
12787
13655
  trackIPCTunnelStart: () => trackIPCTunnelStart,
12788
13656
  trackTunnelStart: () => trackTunnelStart,
12789
13657
  trackTunnelStop: () => trackTunnelStop
@@ -12798,13 +13666,14 @@ function writeDaemonInfo(info) {
12798
13666
  ensurePinggyConfigDir();
12799
13667
  const infoPath = getDaemonInfoPath();
12800
13668
  const tmpPath = infoPath + ".tmp";
12801
- import_node_fs7.default.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
12802
- 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);
12803
13671
  }
12804
13672
  function removeDaemonInfo() {
12805
13673
  try {
12806
13674
  const infoPath = getDaemonInfoPath();
12807
- 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);
12808
13677
  } catch {
12809
13678
  }
12810
13679
  }
@@ -12829,27 +13698,23 @@ function trackTunnelStop(tunnelId) {
12829
13698
  persistDaemonState(daemonState);
12830
13699
  sessionTrackerRef?.removeTunnel(tunnelId);
12831
13700
  }
12832
- function trackDeviceAgentStart(startedBy) {
12833
- daemonState.deviceAgent = { startedAt: (/* @__PURE__ */ new Date()).toISOString(), startedBy };
12834
- persistDaemonState(daemonState);
12835
- }
12836
- function trackDeviceAgentStop() {
12837
- if (!daemonState.deviceAgent) return;
12838
- delete daemonState.deviceAgent;
12839
- persistDaemonState(daemonState);
12840
- }
12841
- 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
+ }
12842
13707
  try {
12843
13708
  const result = await host.start(saved.startedBy);
12844
13709
  if (isErrorResponse(result)) {
12845
- logger.warn("Crash recovery: device agent not restored", { reason: result.message });
12846
- trackDeviceAgentStop();
13710
+ logger.warn("Saved device agent not started", { reason: result.message });
13711
+ forgetDeviceAgent();
12847
13712
  return;
12848
13713
  }
12849
- logger.info("Crash recovery: device agent restored");
13714
+ logger.info("Saved device agent started");
12850
13715
  } catch (err) {
12851
- logger.error("Crash recovery: device agent failed to start", { error: errorMessage(err) });
12852
- trackDeviceAgentStop();
13716
+ logger.error("Saved device agent failed to start", { error: errorMessage(err) });
13717
+ forgetDeviceAgent();
12853
13718
  }
12854
13719
  }
12855
13720
  function trackIPCTunnelStart(tunnelId, origin, mode = SessionMode.Detached) {
@@ -12944,9 +13809,7 @@ async function runDaemonChild(opts = {}) {
12944
13809
  const exitOnFailure = opts.exitOnFailure ?? true;
12945
13810
  daemonHost = opts.host ?? DaemonHost.CLI;
12946
13811
  ensurePinggyConfigDir();
12947
- const persistedLevel = readDaemonConfig()?.logLevel;
12948
- const envLevel = process.env.PINGGY_LOG_LEVEL;
12949
- const initialLevel = persistedLevel ?? envLevel ?? "info";
13812
+ const initialLevel = configuredLogLevel();
12950
13813
  setLogLevel(initialLevel);
12951
13814
  ensurePinggyLogDir();
12952
13815
  const logPath = getDaemonLogPath();
@@ -12957,6 +13820,11 @@ async function runDaemonChild(opts = {}) {
12957
13820
  enableSdkLog: true
12958
13821
  });
12959
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
+ }
12960
13828
  const manager = TunnelManager.getInstance();
12961
13829
  const ipcServer = new IPCServer();
12962
13830
  const sessionTracker = new SessionTracker();
@@ -12979,6 +13847,10 @@ async function runDaemonChild(opts = {}) {
12979
13847
  removeDaemonInfo();
12980
13848
  } catch {
12981
13849
  }
13850
+ try {
13851
+ releaseDaemonLock();
13852
+ } catch {
13853
+ }
12982
13854
  try {
12983
13855
  clearDaemonState();
12984
13856
  } catch {
@@ -13021,14 +13893,10 @@ async function runDaemonChild(opts = {}) {
13021
13893
  try {
13022
13894
  const port = await ipcServer.listen();
13023
13895
  deviceAgentHost = new DeviceAgentHost(machineDeviceAgentHostDependencies(port, {
13024
- recordRunning: trackDeviceAgentStart,
13025
- recordStopped: trackDeviceAgentStop
13896
+ recordRunning: saveDeviceAgent,
13897
+ recordStopped: forgetDeviceAgent
13026
13898
  }));
13027
13899
  ipcServer.setDeviceAgentHost(deviceAgentHost);
13028
- const crashedDeviceAgent = loadDaemonState()?.deviceAgent;
13029
- if (crashedDeviceAgent) {
13030
- daemonState.deviceAgent = crashedDeviceAgent;
13031
- }
13032
13900
  const info = {
13033
13901
  pid: process.pid,
13034
13902
  port,
@@ -13052,8 +13920,9 @@ async function runDaemonChild(opts = {}) {
13052
13920
  } else {
13053
13921
  logger.info("No auto-start tunnels configured");
13054
13922
  }
13055
- if (crashedDeviceAgent) {
13056
- await restoreCrashedDeviceAgent(deviceAgentHost, crashedDeviceAgent);
13923
+ const savedAgent = savedDeviceAgent();
13924
+ if (savedAgent) {
13925
+ await startSavedDeviceAgent(deviceAgentHost, savedAgent);
13057
13926
  }
13058
13927
  logger.info("Daemon ready", { pid: process.pid, port });
13059
13928
  return {
@@ -13064,18 +13933,19 @@ async function runDaemonChild(opts = {}) {
13064
13933
  } catch (err) {
13065
13934
  logger.error("Daemon failed to start", { error: errorMessage(err) });
13066
13935
  removeDaemonInfo();
13936
+ releaseDaemonLock();
13067
13937
  if (exitOnFailure) {
13068
13938
  process.exit(1);
13069
13939
  }
13070
13940
  throw err;
13071
13941
  }
13072
13942
  }
13073
- var import_node_fs7, daemonState, daemonHost, sessionTrackerRef;
13943
+ var import_node_fs9, daemonState, daemonHost, sessionTrackerRef;
13074
13944
  var init_daemonChild = __esm({
13075
13945
  "src/daemon/lifecycle/daemonChild.ts"() {
13076
13946
  "use strict";
13077
13947
  init_cjs_shims();
13078
- import_node_fs7 = __toESM(require("fs"), 1);
13948
+ import_node_fs9 = __toESM(require("fs"), 1);
13079
13949
  init_ipcServer();
13080
13950
  init_sessionTracker();
13081
13951
  init_stateStore();
@@ -13086,9 +13956,11 @@ var init_daemonChild = __esm({
13086
13956
  init_tunnelLogger();
13087
13957
  init_configStore();
13088
13958
  init_daemonConfig();
13959
+ init_foregroundAgent();
13089
13960
  init_types();
13090
13961
  init_util();
13091
13962
  init_ipcRoutes();
13963
+ init_daemonLock();
13092
13964
  daemonState = { tunnels: [], lastUpdated: "" };
13093
13965
  daemonHost = DaemonHost.CLI;
13094
13966
  sessionTrackerRef = null;
@@ -13100,20 +13972,25 @@ function isProcessAlive(pid) {
13100
13972
  try {
13101
13973
  process.kill(pid, 0);
13102
13974
  return true;
13103
- } catch {
13104
- return false;
13975
+ } catch (err) {
13976
+ return err.code === "EPERM";
13105
13977
  }
13106
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
+ }
13107
13984
  function getDaemonInfo() {
13108
13985
  const infoPath = getDaemonInfoPath();
13109
- if (!import_node_fs8.default.existsSync(infoPath)) return null;
13986
+ if (!import_node_fs10.default.existsSync(infoPath)) return null;
13110
13987
  try {
13111
- 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"));
13112
13989
  if (!data.pid || !data.port) return null;
13113
- if (!isProcessAlive(data.pid)) {
13990
+ if (startedBeforeBoot(data.startedAt) || !isProcessAlive(data.pid)) {
13114
13991
  logger.info("Stale daemon.json found, cleaning up", { stalePid: data.pid });
13115
13992
  try {
13116
- import_node_fs8.default.unlinkSync(infoPath);
13993
+ import_node_fs10.default.unlinkSync(infoPath);
13117
13994
  } catch {
13118
13995
  }
13119
13996
  return null;
@@ -13170,7 +14047,7 @@ async function startDaemon() {
13170
14047
  exitCode = code;
13171
14048
  });
13172
14049
  child.unref();
13173
- const info = await pollForDaemonInfo(DAEMON_SPAWN_TIMEOUT_MS, () => exited);
14050
+ const info = await pollForDaemonInfo(DAEMON_SPAWN_TIMEOUT_MS, () => exited && exitCode !== 0);
13174
14051
  if (!info) {
13175
14052
  const logPath = getDaemonLogPath();
13176
14053
  if (exited) {
@@ -13293,13 +14170,13 @@ async function waitForExit(pid, timeoutMs) {
13293
14170
  }
13294
14171
  return !isProcessAlive(pid);
13295
14172
  }
13296
- 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;
13297
14174
  var init_daemonManager = __esm({
13298
14175
  "src/daemon/lifecycle/daemonManager.ts"() {
13299
14176
  "use strict";
13300
14177
  init_cjs_shims();
13301
14178
  import_node_os2 = __toESM(require("os"), 1);
13302
- import_node_fs8 = __toESM(require("fs"), 1);
14179
+ import_node_fs10 = __toESM(require("fs"), 1);
13303
14180
  import_node_child_process2 = require("child_process");
13304
14181
  init_configDir();
13305
14182
  init_ipcRoutes();
@@ -13309,6 +14186,7 @@ var init_daemonManager = __esm({
13309
14186
  inProcessHandle = null;
13310
14187
  DAEMON_SPAWN_TIMEOUT_MS = 8e3;
13311
14188
  DAEMON_POLL_INTERVAL_MS = 200;
14189
+ BOOT_TIME_TOLERANCE_MILLIS = 6e4;
13312
14190
  }
13313
14191
  });
13314
14192
 
@@ -13744,7 +14622,22 @@ var init_tunnelClient = __esm({
13744
14622
  this.health = new DaemonHealth(() => this.ipc, this.stream);
13745
14623
  }
13746
14624
  async ensureDaemon() {
13747
- 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) {
13748
14641
  this.ipc = new IPCClient(info.port, this.origin);
13749
14642
  this.health.bindPid(info.pid);
13750
14643
  this.health.reset();
@@ -13866,7 +14759,7 @@ var init_tunnelClient = __esm({
13866
14759
  this.assertClient();
13867
14760
  await this.ipc.restartTunnel(tunnelId);
13868
14761
  }
13869
- // Device agent (`pinggy device connect -b`). The daemon reads the token and the server from
14762
+ // Device agent (`pinggy device connect`). The daemon reads the token and the server from
13870
14763
  // device.json, so none of these takes either.
13871
14764
  async getDeviceAgentStatus() {
13872
14765
  this.assertClient();