pinggy 0.6.5 → 0.6.6

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.
Files changed (30) hide show
  1. package/ARCHITECTURE.md +90 -36
  2. package/CLAUDE.md +18 -8
  3. package/dist/{TunnelManager-DXNXIH5W.js → TunnelManager-JRVEADS4.js} +4 -3
  4. package/dist/{TunnelTui-K7KESRTQ.js → TunnelTui-6H4NPUNF.js} +4 -3
  5. package/dist/{chunk-QZJGTQZC.js → chunk-2GIJXE4K.js} +3 -2
  6. package/dist/{chunk-EMCDDH3B.js → chunk-3WMTTJHI.js} +11 -299
  7. package/dist/chunk-4XXAHYCJ.js +927 -0
  8. package/dist/{chunk-X6TZN5CT.js → chunk-CZOKR73F.js} +1 -1
  9. package/dist/chunk-FQ22KFVV.js +882 -0
  10. package/dist/{chunk-K5QHR5KU.js → chunk-HAFTH5MX.js} +498 -551
  11. package/dist/chunk-HTIWY3O5.js +293 -0
  12. package/dist/{chunk-IRKMUV37.js → chunk-LWCVB42S.js} +2 -2
  13. package/dist/{chunk-N5WE4DYD.js → chunk-MAK5R4WQ.js} +12 -0
  14. package/dist/{chunk-7EQKHVQX.js → chunk-MHQ3CVEB.js} +4 -51
  15. package/dist/chunk-MKGD2QAI.js +51 -0
  16. package/dist/{chunk-3PTLHLFL.js → chunk-Q5NCTGNS.js} +33 -240
  17. package/dist/{configStore-DXC6WMYO.js → configStore-JJUWT2YO.js} +3 -3
  18. package/dist/{daemonChild-HZ27YJKQ.js → daemonChild-Q6WGYKYX.js} +14 -10
  19. package/dist/{daemonConfig-MCAKZHY2.js → daemonConfig-VWK4TXVS.js} +2 -2
  20. package/dist/index.cjs +3555 -1791
  21. package/dist/index.d.cts +142 -129
  22. package/dist/index.d.ts +142 -129
  23. package/dist/index.js +18 -13
  24. package/dist/{ipcClient-XGF2KCQO.js → ipcClient-IZ5R6TPN.js} +2 -1
  25. package/dist/{main-TDQB5ZB4.js → main-BI7ACRHS.js} +19 -14
  26. package/dist/updateChild-Z3SIRYO5.js +237 -0
  27. package/dist/workers/file_serve_worker.js +1 -1
  28. package/package.json +2 -1
  29. package/scripts/install/install.ps1 +3 -1
  30. package/scripts/install/install.sh +34 -6
@@ -3,37 +3,21 @@ import {
3
3
  TunnelConfigV1Schema,
4
4
  TunnelOperations,
5
5
  buildRemoteManagementWsUrl,
6
- daemonIpcVersion,
7
- ensureDaemonRunning,
8
- getDaemonInfo,
9
6
  initiateRemoteManagement,
10
- ipcMismatchMessage,
11
- isDaemonRunning,
12
- isIpcCompatible,
13
- isProcessAlive,
14
- startDaemon,
15
- startRemoteManagement,
16
- startedBeforeBoot,
17
- stopDaemon
18
- } from "./chunk-3PTLHLFL.js";
7
+ startRemoteManagement
8
+ } from "./chunk-Q5NCTGNS.js";
19
9
  import {
20
10
  configuredLogLevel,
21
11
  forgetDeviceAgent,
22
12
  saveDeviceAgent,
23
13
  savedDeviceAgent,
24
14
  writeDaemonConfig
25
- } from "./chunk-X6TZN5CT.js";
15
+ } from "./chunk-CZOKR73F.js";
26
16
  import {
27
- DaemonHost,
28
- DeviceAgentState,
29
17
  HTTP_NOT_FOUND,
30
18
  IPCClient,
31
- IPCHttpError,
32
- IPC_VERSION,
33
- Route,
34
- SessionMode,
35
- ShutdownStatus
36
- } from "./chunk-7EQKHVQX.js";
19
+ IPCHttpError
20
+ } from "./chunk-MHQ3CVEB.js";
37
21
  import {
38
22
  ConfigVerb,
39
23
  SUBCOMMANDS,
@@ -52,33 +36,94 @@ import {
52
36
  upsertConfig,
53
37
  validateName,
54
38
  validateNameStrict
55
- } from "./chunk-QZJGTQZC.js";
39
+ } from "./chunk-2GIJXE4K.js";
56
40
  import {
57
41
  createQrCodes
58
42
  } from "./chunk-XZ64ZAGO.js";
59
43
  import {
60
- ErrorCode,
61
44
  TunnelManager,
62
- TunnelStateType,
63
45
  detachAllTunnelLoggers,
46
+ isTunnelLoggingEnabled,
47
+ setTunnelLoggingEnabled
48
+ } from "./chunk-3WMTTJHI.js";
49
+ import {
50
+ UpdateError,
51
+ acquireUpdateLock,
52
+ assetNameFor,
53
+ createUpdateTarget,
54
+ downloadRelease,
55
+ environmentWithoutDeviceToken,
56
+ isNewerVersion,
57
+ isReleaseComplete,
58
+ isUpdateLockHeld,
59
+ parseVersion,
60
+ readBinaryIpcVersion,
61
+ releaseUpdateLock,
62
+ removeQuietly,
63
+ removeStaleUpdateFiles,
64
+ resolveLatestTag,
65
+ runPinggyBinary,
66
+ versionFromTag,
67
+ windowsInstallPaths
68
+ } from "./chunk-FQ22KFVV.js";
69
+ import {
70
+ InstallKind,
71
+ NPM_INSTALL_COMMAND,
72
+ backgroundInstallKind,
73
+ canReplaceItself,
74
+ createInstallProbe,
75
+ daemonIpcVersion,
76
+ detectInstallKind,
77
+ ensureDaemonRunning,
78
+ getDaemonInfo,
79
+ hasExecutableSpawnHelper,
80
+ hasPathSegment,
81
+ installCommandFor,
82
+ installService,
83
+ ipcMismatchMessage,
84
+ isDaemonRunning,
85
+ isIpcCompatible,
86
+ isPackagedBinary,
87
+ isProcessAlive,
88
+ makeSpawnHelperExecutable,
89
+ nowEpochSeconds,
90
+ readUpdateState,
91
+ recordLatestVersion,
92
+ requireNodePty,
93
+ resolveNodePtyRoot,
94
+ startDaemon,
95
+ startedBeforeBoot,
96
+ stopDaemon,
97
+ uninstallService,
98
+ writeUpdateState
99
+ } from "./chunk-4XXAHYCJ.js";
100
+ import {
101
+ DaemonHost,
102
+ DeviceAgentState,
103
+ IPC_VERSION,
104
+ Route,
105
+ SessionMode,
106
+ ShutdownStatus
107
+ } from "./chunk-MKGD2QAI.js";
108
+ import {
109
+ ErrorCode,
110
+ TunnelStateType,
64
111
  errorMessage,
65
112
  getLocalAddress,
66
113
  getRandomId,
67
114
  getVersion,
68
115
  isErrorResponse,
69
- isTunnelLoggingEnabled,
70
116
  isValidPort,
71
117
  newErrorResponse,
72
- printer_default,
73
- setTunnelLoggingEnabled
74
- } from "./chunk-EMCDDH3B.js";
118
+ printer_default
119
+ } from "./chunk-HTIWY3O5.js";
75
120
  import {
76
121
  configureLogger,
77
122
  enablePackageLogging,
78
123
  getLogLevel,
79
124
  logger,
80
125
  setLogLevel
81
- } from "./chunk-IRKMUV37.js";
126
+ } from "./chunk-LWCVB42S.js";
82
127
  import {
83
128
  ensurePinggyConfigDir,
84
129
  ensurePinggyLogDir,
@@ -90,7 +135,7 @@ import {
90
135
  getPinggyConfigDir,
91
136
  getTunnelLogDir,
92
137
  getTunnelLogPath
93
- } from "./chunk-N5WE4DYD.js";
138
+ } from "./chunk-MAK5R4WQ.js";
94
139
 
95
140
  // src/cli/options.ts
96
141
  var cliOptions = {
@@ -139,8 +184,15 @@ var cliOptions = {
139
184
  all: { type: "boolean", description: "Start all auto-start tunnels" },
140
185
  // `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
141
186
  foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
187
+ // `pinggy update` only.
188
+ check: { type: "boolean", description: "Print the latest version and change nothing", hidden: true },
189
+ rollback: { type: "boolean", description: "Go back to the previous version", hidden: true },
142
190
  // Internal daemon child marker
143
191
  "_daemon-child": { type: "boolean", description: "Internal: daemon child process marker", hidden: true },
192
+ // Internal: the detached process that checks for a release and installs it.
193
+ "_update-child": { type: "boolean", description: "Internal: background updater marker", hidden: true },
194
+ // Internal: prints IPC_VERSION, so an updater can compare a downloaded binary with a running daemon.
195
+ "_ipc-version": { type: "boolean", description: "Internal: print the IPC protocol version", hidden: true },
144
196
  // Misc
145
197
  version: { type: "boolean", description: "Print version" },
146
198
  // Help
@@ -214,6 +266,11 @@ function printHelpMessage() {
214
266
  console.log(" pinggy device login --foreground # Same, with the agent in this terminal");
215
267
  console.log(" pinggy device status # Show this device and its agent");
216
268
  console.log(" pinggy device stop # Stop the background agent");
269
+ console.log("\nUpdates:");
270
+ console.log(" pinggy update --check # Print the latest version");
271
+ console.log(" pinggy update # Update to the latest version now");
272
+ console.log(" pinggy update --rollback # Go back to the previous version");
273
+ console.log(" PINGGY_AUTO_UPDATE=false # Turn off automatic updates");
217
274
  console.log("\nDaemon Lifecycle (also: pinggy d <command>):");
218
275
  console.log(" pinggy daemon start # Start the background daemon");
219
276
  console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
@@ -283,9 +340,153 @@ function parseCliArgs(options, overrideArgs) {
283
340
  };
284
341
  }
285
342
 
343
+ // src/update/backgroundUpdate.ts
344
+ import { spawn } from "child_process";
345
+ import fs from "fs";
346
+ import os2 from "os";
347
+
348
+ // src/update/updateMessages.ts
349
+ function daemonRestartLine(version, host) {
350
+ const firstSentence = `pinggy ${version} needs a daemon restart.`;
351
+ if (host === DaemonHost.APP) return `${firstSentence} Update the Pinggy app, then run "pinggy update".`;
352
+ return `${firstSentence} Run "pinggy daemon stop", then "pinggy update". This stops all running tunnels.`;
353
+ }
354
+
355
+ // src/update/backgroundUpdate.ts
356
+ var AUTO_UPDATE_ENV = "PINGGY_AUTO_UPDATE";
357
+ var OFF_VALUES = /* @__PURE__ */ new Set(["false", "0"]);
358
+ var ON_VALUES = /* @__PURE__ */ new Set(["true", "1"]);
359
+ var SUDO_UID_ENV = "SUDO_UID";
360
+ var CONTAINER_MARKER_FILES = ["/.dockerenv", "/run/.containerenv"];
361
+ var NPX_SEGMENT = "_npx";
362
+ var UPDATE_SUBCOMMAND = "update";
363
+ var UPDATE_CHILD_FLAG = "--_update-child";
364
+ var SECONDS_PER_DAY = 24 * 60 * 60;
365
+ var CHECK_INTERVAL_SECONDS = SECONDS_PER_DAY;
366
+ var ATTEMPT_INTERVAL_SECONDS = 60 * 60;
367
+ var COULD_NOT_UPDATE_AFTER_SECONDS = 7 * SECONDS_PER_DAY;
368
+ var COULD_NOT_CHECK_AFTER_SECONDS = 30 * SECONDS_PER_DAY;
369
+ function isDue(lastEpochSeconds, intervalSeconds, now) {
370
+ return lastEpochSeconds === void 0 || lastEpochSeconds > now || now - lastEpochSeconds > intervalSeconds;
371
+ }
372
+ function isAutoUpdateOff(variables) {
373
+ const value = variables[AUTO_UPDATE_ENV]?.toLowerCase();
374
+ if (value === void 0) return false;
375
+ if (!OFF_VALUES.has(value) && !ON_VALUES.has(value)) {
376
+ logger.debug(`Unknown ${AUTO_UPDATE_ENV} value leaves auto-update on`, { value });
377
+ }
378
+ return OFF_VALUES.has(value);
379
+ }
380
+ function isExplicitOrPrintOnly({ rawArgs, values, hasAnyArgs }) {
381
+ return rawArgs[0] === UPDATE_SUBCOMMAND || !hasAnyArgs || Boolean(values.help) || Boolean(values.version);
382
+ }
383
+ function isExcludedProcess(environment) {
384
+ return Boolean(environment.variables[SUDO_UID_ENV]) || CONTAINER_MARKER_FILES.some(environment.fileExists) || parseVersion(environment.runningVersion) === null || hasPathSegment(environment.scriptRealPath, NPX_SEGMENT);
385
+ }
386
+ function updatedNotice(state, running) {
387
+ if (state.updatedToVersion !== running || !state.updatedFromVersion) return null;
388
+ return {
389
+ line: `Updated pinggy ${state.updatedFromVersion} to ${running}.`,
390
+ patch: { updatedFromVersion: void 0, updatedToVersion: void 0 }
391
+ };
392
+ }
393
+ function deferredNotice(state, environment) {
394
+ const version = state.deferredVersion;
395
+ if (!version || state.lastNoticeVersion === version) return null;
396
+ const daemon = environment.liveDaemon();
397
+ if (!daemon) return null;
398
+ return { line: daemonRestartLine(version, daemon.host), patch: { lastNoticeVersion: version } };
399
+ }
400
+ function availableLine(kind, latest, platform3) {
401
+ if (kind === InstallKind.Npm) return `pinggy ${latest} is available. Run: ${NPM_INSTALL_COMMAND}`;
402
+ if (kind === InstallKind.WindowsReadOnly || kind === InstallKind.UnixLoose) {
403
+ return `pinggy ${latest} is available. Run: ${installCommandFor(platform3)}`;
404
+ }
405
+ return null;
406
+ }
407
+ function newVersionNotice(state, kind, environment) {
408
+ const latest = state.latestVersion;
409
+ if (!latest || !isNewerVersion(latest, environment.runningVersion) || state.lastNoticeVersion === latest) return null;
410
+ const patch = { lastNoticeVersion: latest };
411
+ const available = availableLine(kind(), latest, environment.platform);
412
+ if (available) return { line: available, patch };
413
+ const seenLongAgo = state.latestSeenEpochSeconds !== void 0 && environment.nowEpochSeconds() - state.latestSeenEpochSeconds > COULD_NOT_UPDATE_AFTER_SECONDS;
414
+ if (canReplaceItself(kind()) && seenLongAgo && latest !== state.rolledBackFromVersion) {
415
+ return { line: `pinggy could not update itself to ${latest}. Run: pinggy update`, patch };
416
+ }
417
+ return null;
418
+ }
419
+ function couldNotCheckNotice(state, kind, environment) {
420
+ const now = environment.nowEpochSeconds();
421
+ const lastCheck = state.lastCheckEpochSeconds;
422
+ if (lastCheck === void 0 || now - lastCheck <= COULD_NOT_CHECK_AFTER_SECONDS) return null;
423
+ if (!isDue(state.lastCheckFailureNoticeEpochSeconds, COULD_NOT_CHECK_AFTER_SECONDS, now)) return null;
424
+ if (kind() === InstallKind.DevCheckout) return null;
425
+ return { line: "pinggy could not check for updates. Run: pinggy update", patch: { lastCheckFailureNoticeEpochSeconds: now } };
426
+ }
427
+ function pendingNotice(state, kind, environment) {
428
+ return updatedNotice(state, environment.runningVersion) ?? deferredNotice(state, environment) ?? newVersionNotice(state, kind, environment) ?? couldNotCheckNotice(state, kind, environment);
429
+ }
430
+ function printPendingNotice(state, kind, environment) {
431
+ const notice = pendingNotice(state, kind, environment);
432
+ if (notice && environment.writeState(notice.patch)) environment.print(notice.line);
433
+ }
434
+ function runGates(command, environment) {
435
+ if (isExplicitOrPrintOnly(command) || !environment.stdoutIsTerminal) return;
436
+ if (isAutoUpdateOff(environment.variables) || isExcludedProcess(environment)) return;
437
+ let detectedKind;
438
+ const kind = () => detectedKind ?? (detectedKind = environment.detectKind());
439
+ const state = environment.readState();
440
+ printPendingNotice(state, kind, environment);
441
+ const now = environment.nowEpochSeconds();
442
+ if (!isDue(state.lastCheckEpochSeconds, CHECK_INTERVAL_SECONDS, now)) return;
443
+ if (!isDue(state.lastAttemptEpochSeconds, ATTEMPT_INTERVAL_SECONDS, now)) return;
444
+ if (kind() === InstallKind.DevCheckout || environment.isLockHeld()) return;
445
+ if (environment.writeState({ lastAttemptEpochSeconds: now })) environment.spawnUpdater();
446
+ }
447
+ function spawnUpdater(spawnProcess = spawn) {
448
+ const child = spawnProcess(process.execPath, [process.argv[1], UPDATE_CHILD_FLAG], {
449
+ detached: true,
450
+ stdio: "ignore",
451
+ // On Windows a process holds its working directory open, so inheriting it would block deleting that folder.
452
+ cwd: os2.homedir(),
453
+ env: environmentWithoutDeviceToken(),
454
+ ...os2.platform() === "win32" ? { windowsHide: true } : {}
455
+ });
456
+ child.on("error", (error) => logger.debug("Could not start the updater", { error: errorMessage(error) }));
457
+ child.unref();
458
+ }
459
+ function realEnvironment() {
460
+ const probe = createInstallProbe();
461
+ return {
462
+ variables: process.env,
463
+ stdoutIsTerminal: process.stdout.isTTY === true,
464
+ runningVersion: getVersion(),
465
+ platform: probe.platform,
466
+ scriptRealPath: probe.scriptRealPath,
467
+ nowEpochSeconds,
468
+ fileExists: (filePath) => fs.existsSync(filePath),
469
+ detectKind: () => backgroundInstallKind(detectInstallKind(probe), probe.execPath, probe.homeRealPath),
470
+ readState: readUpdateState,
471
+ writeState: writeUpdateState,
472
+ isLockHeld: isUpdateLockHeld,
473
+ liveDaemon: getDaemonInfo,
474
+ print: (line) => printer_default.print(line),
475
+ spawnUpdater: () => spawnUpdater()
476
+ };
477
+ }
478
+ function startBackgroundUpdate(command, createEnvironment = realEnvironment) {
479
+ try {
480
+ runGates(command, createEnvironment());
481
+ } catch (error) {
482
+ logger.debug("Background update gate failed", { error: errorMessage(error) });
483
+ }
484
+ }
485
+
286
486
  // src/main.ts
287
487
  import { fileURLToPath } from "url";
288
488
  import { argv } from "process";
489
+ import { platform as platform2 } from "os";
289
490
  import { realpathSync } from "fs";
290
491
 
291
492
  // src/cli/defaults.ts
@@ -458,7 +659,7 @@ function isValidIpV6Cidr(input) {
458
659
 
459
660
  // src/cli/buildConfig.ts
460
661
  import { TunnelType } from "@pinggy/pinggy";
461
- import fs from "fs";
662
+ import fs2 from "fs";
462
663
  import path from "path";
463
664
  import { isIP as isIP2 } from "net";
464
665
  var domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
@@ -829,10 +1030,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
829
1030
  }
830
1031
  function storeJson(config, saveconf) {
831
1032
  if (saveconf) {
832
- const path7 = saveconf;
1033
+ const path5 = saveconf;
833
1034
  try {
834
- fs.writeFileSync(path7, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
835
- logger.info(`Configuration saved to ${path7}`);
1035
+ fs2.writeFileSync(path5, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
1036
+ logger.info(`Configuration saved to ${path5}`);
836
1037
  } catch (err) {
837
1038
  const msg = err instanceof Error ? err.message : String(err);
838
1039
  logger.error("Error loading configuration:", msg);
@@ -844,7 +1045,7 @@ function loadJsonConfig(config) {
844
1045
  if (typeof configpath === "string" && configpath.trim().length > 0) {
845
1046
  const filepath = path.resolve(configpath);
846
1047
  try {
847
- const data = fs.readFileSync(filepath, { encoding: "utf-8" });
1048
+ const data = fs2.readFileSync(filepath, { encoding: "utf-8" });
848
1049
  const json = JSON.parse(data);
849
1050
  return json;
850
1051
  } catch (err) {
@@ -1039,13 +1240,14 @@ async function initTunnelClient() {
1039
1240
  const client = new TunnelClient();
1040
1241
  printer_default.startSpinner("Initializing...");
1041
1242
  try {
1042
- await client.ensureDaemon();
1243
+ await client.ensureDaemon({ holdVersionNotice: true });
1043
1244
  } catch (err) {
1044
1245
  const msg = err instanceof Error ? err.message : String(err);
1045
1246
  printer_default.stopSpinnerFail(`Failed to start daemon: ${msg}`);
1046
1247
  process.exit(1);
1047
1248
  }
1048
1249
  printer_default.stopSpinnerSuccess("Initialized");
1250
+ client.printHeldVersionNotice();
1049
1251
  return client;
1050
1252
  }
1051
1253
  function printRemoteUrls(urls) {
@@ -1157,7 +1359,7 @@ async function connectTui(opts) {
1157
1359
  const exitMessage = opts.exitMessage || "Stopping tunnel...";
1158
1360
  if (!noTui && process.stdin.isTTY) {
1159
1361
  try {
1160
- const { TunnelTui } = await import("./TunnelTui-K7KESRTQ.js");
1362
+ const { TunnelTui } = await import("./TunnelTui-6H4NPUNF.js");
1161
1363
  const tui = new TunnelTui({
1162
1364
  urls,
1163
1365
  greet,
@@ -1380,7 +1582,7 @@ async function startBackgroundTunnels(configs, values, positionals) {
1380
1582
  client.close();
1381
1583
  }
1382
1584
  async function startAutoStartTunnels() {
1383
- const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-DXC6WMYO.js");
1585
+ const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-JJUWT2YO.js");
1384
1586
  const configs = getAutoStartConfigs2();
1385
1587
  if (configs.length === 0) {
1386
1588
  printer_default.warn("No configs marked for auto-start. Use: pinggy config auto <name>");
@@ -1503,335 +1705,6 @@ async function initRemoteManagement(values, blocking) {
1503
1705
  // src/cli/subcommand/handlers/daemonCommandsHandler.ts
1504
1706
  import pico6 from "picocolors";
1505
1707
 
1506
- // src/daemon/lifecycle/serviceInstaller.ts
1507
- import os2 from "os";
1508
- import fs2 from "fs";
1509
- import path2 from "path";
1510
- import { execSync, execFileSync } from "child_process";
1511
- var SERVICE_LABEL = "io.pinggy.agent";
1512
- var SYSTEMD_SERVICE_NAME = "pinggy";
1513
- var SERVICE_ANY_LOCATION_ENV = "PINGGY_SERVICE_ANY_LOCATION";
1514
- function installerBinaryPath(platform2, home, env) {
1515
- if (platform2 === "win32") {
1516
- const localAppData = env.LOCALAPPDATA || path2.win32.join(home, "AppData", "Local");
1517
- return path2.win32.join(localAppData, "Pinggy", "bin", "pinggy.exe");
1518
- }
1519
- return path2.posix.join(home, ".pinggy", "bin", "pinggy");
1520
- }
1521
- function realPath(p) {
1522
- try {
1523
- return fs2.realpathSync(p);
1524
- } catch {
1525
- return p;
1526
- }
1527
- }
1528
- function isInstallerBinary(ctx) {
1529
- const actual = realPath(ctx.execPath);
1530
- const expected = realPath(installerBinaryPath(ctx.platform, ctx.home, ctx.env));
1531
- if (ctx.platform === "win32") return actual.toLowerCase() === expected.toLowerCase();
1532
- return actual === expected;
1533
- }
1534
- function installerFix(platform2) {
1535
- const installCommand = platform2 === "win32" ? "irm https://pinggy.io/install.ps1 | iex" : "curl -fsSL https://pinggy.io/install.sh | sh";
1536
- return [
1537
- "pinggy can only run as a service when it is installed with the Pinggy installer.",
1538
- "Install it, then run this command again:",
1539
- ` ${installCommand}`,
1540
- " pinggy daemon service-install"
1541
- ].join("\n");
1542
- }
1543
- function serviceInstallRefusal(ctx) {
1544
- if (!ctx.isPkg) return `The npm version of pinggy cannot run as a service.
1545
- ${installerFix(ctx.platform)}`;
1546
- if (ctx.env[SERVICE_ANY_LOCATION_ENV] === "1" || isInstallerBinary(ctx)) return null;
1547
- return installerFix(ctx.platform);
1548
- }
1549
- function printInstalled() {
1550
- printer_default.success("pinggy now starts automatically when this computer starts.");
1551
- }
1552
- function printUninstalled() {
1553
- printer_default.success("pinggy no longer starts automatically when this computer starts.");
1554
- }
1555
- function printNotInstalled() {
1556
- printer_default.print("pinggy is not set to start automatically.");
1557
- }
1558
- var QUIET = { stdio: ["ignore", "ignore", "pipe"] };
1559
- function toolError(err) {
1560
- const stderr = err.stderr?.toString().trim();
1561
- return stderr ? stderr.replace(/^ERROR:\s*/i, "") : errorMessage(err);
1562
- }
1563
- function getSystemdServicePath() {
1564
- const dir = path2.join(os2.homedir(), ".config", "systemd", "user");
1565
- return path2.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
1566
- }
1567
- function generateSystemdUnit(program) {
1568
- const execStart = `${program} --_daemon-child`;
1569
- return `[Unit]
1570
- Description=Pinggy Tunnel Daemon
1571
- After=network-online.target
1572
- Wants=network-online.target
1573
-
1574
- [Service]
1575
- Type=simple
1576
- ExecStart=${execStart}
1577
- Restart=on-failure
1578
- RestartSec=5
1579
-
1580
- [Install]
1581
- WantedBy=default.target
1582
- `;
1583
- }
1584
- function installSystemd(program) {
1585
- const servicePath = getSystemdServicePath();
1586
- const dir = path2.dirname(servicePath);
1587
- fs2.mkdirSync(dir, { recursive: true });
1588
- fs2.writeFileSync(servicePath, generateSystemdUnit(program), "utf-8");
1589
- execSync("systemctl --user daemon-reload", QUIET);
1590
- execSync(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`, QUIET);
1591
- execSync(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`, QUIET);
1592
- logger.info("systemd user service installed", { servicePath });
1593
- printInstalled();
1594
- printer_default.print(`To start it before anyone signs in, run: loginctl enable-linger ${os2.userInfo().username}`);
1595
- }
1596
- function uninstallSystemd() {
1597
- const servicePath = getSystemdServicePath();
1598
- try {
1599
- execSync(`systemctl --user stop ${SYSTEMD_SERVICE_NAME} 2>/dev/null || true`);
1600
- execSync(`systemctl --user disable ${SYSTEMD_SERVICE_NAME} 2>/dev/null || true`);
1601
- } catch {
1602
- }
1603
- if (fs2.existsSync(servicePath)) {
1604
- fs2.unlinkSync(servicePath);
1605
- execSync("systemctl --user daemon-reload", QUIET);
1606
- logger.info("systemd user service removed", { servicePath });
1607
- printUninstalled();
1608
- } else {
1609
- printNotInstalled();
1610
- }
1611
- }
1612
- function getLaunchdPlistPath() {
1613
- return path2.join(os2.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
1614
- }
1615
- function generateLaunchdPlist(program) {
1616
- const allArgs = [program, "--_daemon-child"];
1617
- const programArgs = allArgs.map((p) => ` <string>${p}</string>`).join("\n");
1618
- return `<?xml version="1.0" encoding="UTF-8"?>
1619
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
1620
- "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1621
- <plist version="1.0">
1622
- <dict>
1623
- <key>Label</key>
1624
- <string>${SERVICE_LABEL}</string>
1625
- <key>ProgramArguments</key>
1626
- <array>
1627
- ${programArgs}
1628
- </array>
1629
- <key>RunAtLoad</key>
1630
- <true/>
1631
- <key>KeepAlive</key>
1632
- <false/>
1633
- </dict>
1634
- </plist>
1635
- `;
1636
- }
1637
- function installLaunchd(program) {
1638
- const plistPath = getLaunchdPlistPath();
1639
- const dir = path2.dirname(plistPath);
1640
- fs2.mkdirSync(dir, { recursive: true });
1641
- fs2.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
1642
- const uid = process.getuid?.() ?? 501;
1643
- try {
1644
- execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
1645
- } catch {
1646
- }
1647
- loadLaunchdPlist(uid, plistPath);
1648
- logger.info("launchd agent installed", { plistPath });
1649
- printInstalled();
1650
- }
1651
- function loadLaunchdPlist(uid, plistPath) {
1652
- try {
1653
- execSync(`launchctl bootstrap gui/${uid} ${plistPath}`);
1654
- } catch {
1655
- try {
1656
- execSync(`launchctl load -w ${plistPath}`);
1657
- } catch {
1658
- }
1659
- }
1660
- }
1661
- function uninstallLaunchd() {
1662
- const plistPath = getLaunchdPlistPath();
1663
- const uid = process.getuid?.() ?? 501;
1664
- try {
1665
- execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
1666
- } catch {
1667
- try {
1668
- execSync(`launchctl unload ${plistPath} 2>/dev/null || true`);
1669
- } catch {
1670
- }
1671
- }
1672
- if (fs2.existsSync(plistPath)) {
1673
- fs2.unlinkSync(plistPath);
1674
- logger.info("launchd agent removed", { plistPath });
1675
- printUninstalled();
1676
- } else {
1677
- printNotInstalled();
1678
- }
1679
- }
1680
- var WINDOWS_TASK_NAME = "PinggyDaemon";
1681
- function escapeXml(value) {
1682
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1683
- }
1684
- function getWindowsUserId() {
1685
- const user = process.env.USERNAME || os2.userInfo().username;
1686
- const domain = process.env.USERDOMAIN;
1687
- return domain ? `${domain}\\${user}` : user;
1688
- }
1689
- function generateTaskXml(program, userId) {
1690
- const user = escapeXml(userId);
1691
- return `<?xml version="1.0" encoding="UTF-16"?>
1692
- <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
1693
- <Triggers>
1694
- <LogonTrigger>
1695
- <Enabled>true</Enabled>
1696
- <UserId>${user}</UserId>
1697
- </LogonTrigger>
1698
- </Triggers>
1699
- <Principals>
1700
- <Principal id="Author">
1701
- <UserId>${user}</UserId>
1702
- <LogonType>InteractiveToken</LogonType>
1703
- <RunLevel>LeastPrivilege</RunLevel>
1704
- </Principal>
1705
- </Principals>
1706
- <Settings>
1707
- <Hidden>true</Hidden>
1708
- <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
1709
- <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
1710
- <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
1711
- <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
1712
- <RestartOnFailure>
1713
- <Interval>PT1M</Interval>
1714
- <Count>3</Count>
1715
- </RestartOnFailure>
1716
- </Settings>
1717
- <Actions>
1718
- <Exec>
1719
- <Command>${escapeXml(program)}</Command>
1720
- <Arguments>daemon start</Arguments>
1721
- </Exec>
1722
- </Actions>
1723
- </Task>`;
1724
- }
1725
- function createWindowsTask(program) {
1726
- const xml = generateTaskXml(program, getWindowsUserId());
1727
- const tmpPath = path2.join(os2.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
1728
- fs2.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
1729
- try {
1730
- execFileSync("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
1731
- } finally {
1732
- try {
1733
- fs2.unlinkSync(tmpPath);
1734
- } catch {
1735
- }
1736
- }
1737
- }
1738
- function windowsTaskExists() {
1739
- try {
1740
- execFileSync("schtasks", ["/Query", "/TN", WINDOWS_TASK_NAME], QUIET);
1741
- return true;
1742
- } catch {
1743
- return false;
1744
- }
1745
- }
1746
- function isElevated() {
1747
- try {
1748
- return /S-1-16-(12288|16384)\b/.test(execFileSync("whoami", ["/groups"], { encoding: "utf-8" }));
1749
- } catch {
1750
- return false;
1751
- }
1752
- }
1753
- function windowsTaskError(action, undo, err) {
1754
- if (windowsTaskExists() && !isElevated()) {
1755
- return `Could not ${action}. It was set up from an Administrator terminal. Run this command from an Administrator terminal to ${undo}.`;
1756
- }
1757
- return `Could not ${action}: ${toolError(err)}`;
1758
- }
1759
- function installWindows(program) {
1760
- try {
1761
- createWindowsTask(program);
1762
- execFileSync("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], QUIET);
1763
- } catch (err) {
1764
- printer_default.error(windowsTaskError("set pinggy to start automatically", "change it", err));
1765
- process.exit(1);
1766
- }
1767
- logger.info("Scheduled task installed", { task: WINDOWS_TASK_NAME });
1768
- printInstalled();
1769
- }
1770
- async function uninstallWindows() {
1771
- if (!windowsTaskExists()) {
1772
- printNotInstalled();
1773
- return;
1774
- }
1775
- try {
1776
- execFileSync("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], QUIET);
1777
- } catch (err) {
1778
- printer_default.error(windowsTaskError("stop pinggy from starting automatically", "turn it off", err));
1779
- process.exit(1);
1780
- }
1781
- logger.info("Scheduled task removed", { task: WINDOWS_TASK_NAME });
1782
- if (isDaemonRunning()) {
1783
- const result = await stopDaemon();
1784
- if (!result.ok) console.log(`Could not stop the daemon: ${result.error}`);
1785
- }
1786
- printUninstalled();
1787
- }
1788
- function installService() {
1789
- const platform2 = os2.platform();
1790
- const program = process.execPath;
1791
- const refusal = serviceInstallRefusal({
1792
- platform: platform2,
1793
- isPkg: "pkg" in process,
1794
- execPath: program,
1795
- home: os2.homedir(),
1796
- env: process.env
1797
- });
1798
- if (refusal) {
1799
- console.error(refusal);
1800
- process.exit(1);
1801
- }
1802
- switch (platform2) {
1803
- case "linux":
1804
- installSystemd(program);
1805
- break;
1806
- case "darwin":
1807
- installLaunchd(program);
1808
- break;
1809
- case "win32":
1810
- installWindows(program);
1811
- break;
1812
- default:
1813
- console.error(`Unsupported platform: ${platform2}`);
1814
- process.exit(1);
1815
- }
1816
- }
1817
- async function uninstallService() {
1818
- const platform2 = os2.platform();
1819
- switch (platform2) {
1820
- case "linux":
1821
- uninstallSystemd();
1822
- break;
1823
- case "darwin":
1824
- uninstallLaunchd();
1825
- break;
1826
- case "win32":
1827
- await uninstallWindows();
1828
- break;
1829
- default:
1830
- console.error(`Unsupported platform: ${platform2}`);
1831
- process.exit(1);
1832
- }
1833
- }
1834
-
1835
1708
  // src/utils/helpMessages.ts
1836
1709
  function printDaemonHelp() {
1837
1710
  console.log("\nUsage: pinggy daemon <command>");
@@ -1900,6 +1773,13 @@ function printDeviceHelp() {
1900
1773
  console.log(" DEVICE_AGENT_TOKEN connect only: the device token, when --token is not given. With no");
1901
1774
  console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
1902
1775
  }
1776
+ function printUpdateHelp() {
1777
+ console.log("\nUsage: pinggy update [--check | --rollback]\n");
1778
+ console.log("Commands:");
1779
+ console.log(" pinggy update Update to the latest version now");
1780
+ console.log(" pinggy update --check Print the latest version and change nothing");
1781
+ console.log(" pinggy update --rollback Go back to the previous version\n");
1782
+ }
1903
1783
 
1904
1784
  // src/devices/backgroundAgent.ts
1905
1785
  import pico5 from "picocolors";
@@ -2001,7 +1881,7 @@ var WelcomeSchema = z.object({
2001
1881
  // No default either. Without it the agent runs no expiry timer, and the dashboard's sweep
2002
1882
  // still ends an idle shell, only later. A shell has no cap on its running time.
2003
1883
  terminal_idle_timeout_seconds: z.number().optional(),
2004
- // Optional: without it the agent keeps T2's brake and never skips output (slice T8).
1884
+ // Optional: without it the agent keeps the window brake and never skips output.
2005
1885
  terminal_resync: z.boolean().optional(),
2006
1886
  // Optional: a dashboard older than these sends neither, and the agent prints only the device id.
2007
1887
  email: z.string().optional(),
@@ -2747,9 +2627,9 @@ var MAX_CWD_CHARACTERS = 1024;
2747
2627
  var MAX_COMMAND_CHARACTERS = 64;
2748
2628
  var PROCESS_READ_TIMEOUT_MILLIS = 2e3;
2749
2629
  var HOME_PREFIX = "~";
2750
- function processTableReader(platform2 = process.platform) {
2751
- if (platform2 === "linux") return readFromProc;
2752
- if (platform2 === "darwin") return readFromPsAndLsof;
2630
+ function processTableReader(platform3 = process.platform) {
2631
+ if (platform3 === "linux") return readFromProc;
2632
+ if (platform3 === "darwin") return readFromPsAndLsof;
2753
2633
  return null;
2754
2634
  }
2755
2635
  function programName(rawName) {
@@ -2953,7 +2833,7 @@ var ScreenMirror = class _ScreenMirror {
2953
2833
  }
2954
2834
  /**
2955
2835
  * Fed and not yet parsed. xterm queues writes without limit, so a shell that skips its output
2956
- * (slice T8) pauses on this, and on nothing else.
2836
+ * pauses on this, and on nothing else.
2957
2837
  */
2958
2838
  get backlogBytes() {
2959
2839
  return this.unparsedBytes;
@@ -3029,9 +2909,9 @@ var TerminalHandler = class _TerminalHandler {
3029
2909
  this.dependencies = dependencies;
3030
2910
  this.enabled = true;
3031
2911
  this.suspended = false;
3032
- /** `terminal_resync` in `welcome` (slice T8). Off, every shell keeps T2's brake. */
2912
+ /** `terminal_resync` in `welcome`. Off, every shell keeps the window brake. */
3033
2913
  this.resyncEnabled = false;
3034
- /** Paused by `suspend` under T2's brake, so `resumeAll` resumes them if `welcome` turned skip mode on. */
2914
+ /** Paused by `suspend` without skip mode, so `resumeAll` resumes them if `welcome` turned skip mode on. */
3035
2915
  this.pausedBySuspend = /* @__PURE__ */ new Set();
3036
2916
  this.expiryTimer = null;
3037
2917
  this.contextTimer = null;
@@ -3126,9 +3006,9 @@ var TerminalHandler = class _TerminalHandler {
3126
3006
  this.dependencies.registry.killAll();
3127
3007
  }
3128
3008
  /**
3129
- * The socket dropped and the agent will redial. Under T2's brake every shell stops being read and
3009
+ * The socket dropped and the agent will redial. Without skip mode every shell stops being read and
3130
3010
  * keeps running: whatever it prints waits in the kernel, and the shell blocks once that buffer is
3131
- * full. In skip mode (slice T8) a shell is read on, and its output is skipped.
3011
+ * full. In skip mode a shell is read on, and its output is skipped.
3132
3012
  */
3133
3013
  suspend() {
3134
3014
  if (this.suspended) return;
@@ -3148,7 +3028,7 @@ var TerminalHandler = class _TerminalHandler {
3148
3028
  /**
3149
3029
  * `welcome` arrived. Every shell the dashboard did not close is read again, except one whose
3150
3030
  * window is still full. That one resumes on the `ack` that reopens it. A shell in skip mode was
3151
- * never paused, and resyncs instead (slice T8).
3031
+ * never paused, and resyncs instead.
3152
3032
  */
3153
3033
  resumeAll() {
3154
3034
  if (!this.suspended) return;
@@ -3309,7 +3189,7 @@ var TerminalHandler = class _TerminalHandler {
3309
3189
  }
3310
3190
  /**
3311
3191
  * The shell exited on its own. A shell that skipped its last output sends its last screen first, at
3312
- * once, so the tabs see how it ended (slice T8). Then `exit` and `close`. With nothing to resync this
3192
+ * once, so the tabs see how it ended. Then `exit` and `close`. With nothing to resync this
3313
3193
  * runs to the end without yielding, as before.
3314
3194
  */
3315
3195
  async finishExit(terminalId, stream, exitCode, signal) {
@@ -3341,7 +3221,7 @@ var TerminalHandler = class _TerminalHandler {
3341
3221
  * exactly the bundles up to its `after_seq`. Fed when the pty is read, a bundle still being cut
3342
3222
  * would be in the screen and drawn a second time when it is sent.
3343
3223
  *
3344
- * In skip mode (slice T8) `sendOrSkip` decides instead, and never pauses the pty.
3224
+ * In skip mode `sendOrSkip` decides instead, and never pauses the pty.
3345
3225
  */
3346
3226
  sendData(terminalId, chunk) {
3347
3227
  const stream = this.streams.get(terminalId);
@@ -3370,7 +3250,7 @@ var TerminalHandler = class _TerminalHandler {
3370
3250
  return this.resyncEnabled && stream.mirror !== null;
3371
3251
  }
3372
3252
  /**
3373
- * Skip mode (slice T8). A resync being serialised holds the bundle. A skipping stream, a socket that is
3253
+ * Skip mode. A resync being serialised holds the bundle. A skipping stream, a socket that is
3374
3254
  * down, or a closed window skips it. Otherwise it goes out as `data`.
3375
3255
  */
3376
3256
  sendOrSkip(terminalId, stream, chunk) {
@@ -3416,7 +3296,7 @@ var TerminalHandler = class _TerminalHandler {
3416
3296
  this.brakeIfMirrorBehind(terminalId, stream);
3417
3297
  this.reportActivityWhileSkipping(terminalId, stream);
3418
3298
  }
3419
- /** As T2's send, minus the pause: with the window closed, the next bundle is skipped instead. */
3299
+ /** As the send without skip mode, minus the pause: with the window closed, the next bundle is skipped instead. */
3420
3300
  transmit(terminalId, stream, chunk) {
3421
3301
  stream.sentSeq += 1;
3422
3302
  stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
@@ -3504,7 +3384,7 @@ var TerminalHandler = class _TerminalHandler {
3504
3384
  return stream.resyncInFlight;
3505
3385
  }
3506
3386
  /**
3507
- * The latest screen to every tab (slice T8). `after_seq` and `after_bytes` are read before the mirror
3387
+ * The latest screen to every tab. `after_seq` and `after_bytes` are read before the mirror
3508
3388
  * is asked, as for a snapshot, and skipped bytes took neither: the screen holds the output up to
3509
3389
  * `after_seq` plus everything skipped. Serialised under the window size, so a resync never puts more in
3510
3390
  * flight than the window allows. Bundles held meanwhile go out after the parts, from `after_seq + 1`.
@@ -3664,7 +3544,7 @@ var TerminalHandler = class _TerminalHandler {
3664
3544
  this.dependencies.send(event(CHANNEL_TERMINAL, OP_CLOSE, { terminal_id: terminalId, reason }));
3665
3545
  }
3666
3546
  /**
3667
- * A tab attached and asked for the screen it missed (slice T6). Answered in parts, each 1 frame,
3547
+ * A tab attached and asked for the screen it missed. Answered in parts, each 1 frame,
3668
3548
  * which the dashboard routes to that tab alone.
3669
3549
  *
3670
3550
  * `after_seq` and `after_bytes` are read in the same tick as the request, before the mirror is
@@ -3816,123 +3696,8 @@ var TerminalRegistry = class {
3816
3696
 
3817
3697
  // src/devices/terminal/ptySession.ts
3818
3698
  import { execFile as execFile2 } from "child_process";
3819
- import fs6 from "fs";
3820
- import os7 from "os";
3821
-
3822
- // src/devices/terminal/nodePtyRuntime.ts
3823
3699
  import fs5 from "fs";
3824
- import path3 from "path";
3825
- import { createRequire as createRequire2 } from "module";
3826
- var require3 = createRequire2(import.meta.url);
3827
- var PACKAGE_NAME = "node-pty";
3828
- var NATIVE_FILE = "pty.node";
3829
- var SPAWN_HELPER_FILE = "spawn-helper";
3830
- var EXECUTABLE_MODE = 493;
3831
- var EXECUTE_BITS = 73;
3832
- var RUNTIME_DIR_NAME = "runtime";
3833
- var ASAR_ARCHIVE_SUFFIX = ".asar";
3834
- var NATIVE_DIRECTORIES = [
3835
- path3.join("build", "Release"),
3836
- path3.join("prebuilds", `${process.platform}-${process.arch}`)
3837
- ];
3838
- function isPackagedBinary() {
3839
- return Boolean(process.pkg);
3840
- }
3841
- function isInsideAsarArchive(packageRoot) {
3842
- if (!process.versions.electron) return false;
3843
- return packageRoot.split(path3.sep).some((segment) => segment.endsWith(ASAR_ARCHIVE_SUFFIX));
3844
- }
3845
- function resolveNodePtyRoot() {
3846
- const resolvedRoot = path3.dirname(require3.resolve(`${PACKAGE_NAME}/package.json`));
3847
- if (!isPackagedBinary() && !isInsideAsarArchive(resolvedRoot)) return resolvedRoot;
3848
- return unpackNodePty(resolvedRoot);
3849
- }
3850
- function requireNodePty(packageRoot) {
3851
- return require3(packageRoot);
3852
- }
3853
- function spawnHelperPaths(packageRoot) {
3854
- if (process.platform === "win32") return [];
3855
- return NATIVE_DIRECTORIES.map((directory) => path3.join(packageRoot, directory, SPAWN_HELPER_FILE));
3856
- }
3857
- function hasExecutableSpawnHelper(packageRoot) {
3858
- const helpers = spawnHelperPaths(packageRoot);
3859
- if (helpers.length === 0) return true;
3860
- return helpers.some((helper) => {
3861
- try {
3862
- const stat = fs5.statSync(helper);
3863
- return stat.isFile() && (stat.mode & EXECUTE_BITS) !== 0;
3864
- } catch {
3865
- return false;
3866
- }
3867
- });
3868
- }
3869
- function makeSpawnHelperExecutable(packageRoot) {
3870
- for (const helper of spawnHelperPaths(packageRoot)) {
3871
- try {
3872
- const stat = fs5.statSync(helper);
3873
- if ((stat.mode & EXECUTE_BITS) === 0) {
3874
- fs5.chmodSync(helper, EXECUTABLE_MODE);
3875
- }
3876
- } catch {
3877
- }
3878
- }
3879
- }
3880
- function unpackNodePty(snapshotRoot) {
3881
- const unpackedRoot = unpackedRootPath(snapshotRoot);
3882
- if (isLoadable(unpackedRoot)) return unpackedRoot;
3883
- const stagingRoot = `${unpackedRoot}.${process.pid}`;
3884
- fs5.rmSync(stagingRoot, { recursive: true, force: true });
3885
- try {
3886
- copyRuntimeFiles(snapshotRoot, stagingRoot);
3887
- makeSpawnHelperExecutable(stagingRoot);
3888
- fs5.renameSync(stagingRoot, unpackedRoot);
3889
- } catch (error) {
3890
- fs5.rmSync(stagingRoot, { recursive: true, force: true });
3891
- if (!isLoadable(unpackedRoot)) throw error;
3892
- }
3893
- return unpackedRoot;
3894
- }
3895
- function unpackedRootPath(snapshotRoot) {
3896
- const version = readPackageVersion(snapshotRoot);
3897
- const directoryName = `${PACKAGE_NAME}-${version}-${process.platform}-${process.arch}`;
3898
- return path3.join(getPinggyConfigDir(), RUNTIME_DIR_NAME, directoryName);
3899
- }
3900
- function readPackageVersion(packageRoot) {
3901
- const manifest = JSON.parse(fs5.readFileSync(path3.join(packageRoot, "package.json"), "utf8"));
3902
- return String(manifest.version);
3903
- }
3904
- function isLoadable(packageRoot) {
3905
- if (!fs5.existsSync(path3.join(packageRoot, "package.json"))) return false;
3906
- return NATIVE_DIRECTORIES.some((directory) => fs5.existsSync(path3.join(packageRoot, directory, NATIVE_FILE)));
3907
- }
3908
- function copyRuntimeFiles(sourceRoot, targetRoot) {
3909
- fs5.mkdirSync(targetRoot, { recursive: true });
3910
- copyFile(path3.join(sourceRoot, "package.json"), path3.join(targetRoot, "package.json"));
3911
- copyDirectory(path3.join(sourceRoot, "lib"), path3.join(targetRoot, "lib"));
3912
- for (const directory of NATIVE_DIRECTORIES) {
3913
- const source = path3.join(sourceRoot, directory);
3914
- if (fs5.existsSync(source)) {
3915
- copyDirectory(source, path3.join(targetRoot, directory));
3916
- }
3917
- }
3918
- }
3919
- function copyDirectory(sourceDirectory, targetDirectory) {
3920
- fs5.mkdirSync(targetDirectory, { recursive: true });
3921
- for (const entry of fs5.readdirSync(sourceDirectory, { withFileTypes: true })) {
3922
- const source = path3.join(sourceDirectory, entry.name);
3923
- const target = path3.join(targetDirectory, entry.name);
3924
- if (entry.isDirectory()) {
3925
- copyDirectory(source, target);
3926
- continue;
3927
- }
3928
- copyFile(source, target);
3929
- }
3930
- }
3931
- function copyFile(source, target) {
3932
- fs5.writeFileSync(target, fs5.readFileSync(source));
3933
- }
3934
-
3935
- // src/devices/terminal/ptySession.ts
3700
+ import os7 from "os";
3936
3701
  var loadedPty;
3937
3702
  var TERM_NAME = "xterm-256color";
3938
3703
  function foregroundProcessGroup(shellPid) {
@@ -3980,7 +3745,7 @@ function ensureSpawnHelperExecutable(packageRoot) {
3980
3745
  function resolveCwd(requested) {
3981
3746
  if (requested) {
3982
3747
  try {
3983
- if (fs6.statSync(requested).isDirectory()) return requested;
3748
+ if (fs5.statSync(requested).isDirectory()) return requested;
3984
3749
  } catch {
3985
3750
  }
3986
3751
  }
@@ -4030,14 +3795,14 @@ function spawnPty(request2) {
4030
3795
  }
4031
3796
 
4032
3797
  // src/devices/terminal/shellAllowlist.ts
4033
- import fs7 from "fs";
3798
+ import fs6 from "fs";
4034
3799
  var FALLBACK_UNIX_SHELLS = ["/bin/bash", "/bin/zsh", "/bin/sh", "/usr/bin/bash", "/usr/bin/zsh"];
4035
3800
  var WINDOWS_SHELLS = ["powershell.exe", "cmd.exe"];
4036
3801
  var ETC_SHELLS_PATH = "/etc/shells";
4037
3802
  function readShellEnvironment() {
4038
3803
  let etcShells = null;
4039
3804
  try {
4040
- etcShells = fs7.readFileSync(ETC_SHELLS_PATH, "utf8");
3805
+ etcShells = fs6.readFileSync(ETC_SHELLS_PATH, "utf8");
4041
3806
  } catch {
4042
3807
  etcShells = null;
4043
3808
  }
@@ -4045,9 +3810,9 @@ function readShellEnvironment() {
4045
3810
  platform: process.platform,
4046
3811
  loginShell: process.env.SHELL,
4047
3812
  etcShells,
4048
- exists: (path7) => {
3813
+ exists: (path5) => {
4049
3814
  try {
4050
- return fs7.statSync(path7).isFile();
3815
+ return fs6.statSync(path5).isFile();
4051
3816
  } catch {
4052
3817
  return false;
4053
3818
  }
@@ -4080,13 +3845,13 @@ function resolveShell(requested, environment) {
4080
3845
  }
4081
3846
 
4082
3847
  // src/devices/foregroundAgent.ts
4083
- import fs8 from "fs";
3848
+ import fs7 from "fs";
4084
3849
  var RECORD_CHECK_INTERVAL_MILLIS = 1e3;
4085
3850
  var STOP_WAIT_MILLIS = 1e4;
4086
3851
  var STOP_POLL_INTERVAL_MILLIS = 200;
4087
3852
  function readRecordFile(filePath) {
4088
3853
  try {
4089
- const record = JSON.parse(fs8.readFileSync(filePath, "utf-8"));
3854
+ const record = JSON.parse(fs7.readFileSync(filePath, "utf-8"));
4090
3855
  return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
4091
3856
  } catch {
4092
3857
  return null;
@@ -4094,7 +3859,7 @@ function readRecordFile(filePath) {
4094
3859
  }
4095
3860
  function deleteRecordFile(filePath) {
4096
3861
  try {
4097
- fs8.unlinkSync(filePath);
3862
+ fs7.unlinkSync(filePath);
4098
3863
  } catch (err) {
4099
3864
  logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
4100
3865
  }
@@ -4120,7 +3885,7 @@ function recordForegroundAgent(onRecordDeleted) {
4120
3885
  const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
4121
3886
  try {
4122
3887
  ensurePinggyConfigDir();
4123
- fs8.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
3888
+ fs7.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
4124
3889
  } catch (err) {
4125
3890
  logger.warn(
4126
3891
  "Could not write device-agent.json. pinggy device remove cannot stop this agent.",
@@ -4129,7 +3894,7 @@ function recordForegroundAgent(onRecordDeleted) {
4129
3894
  return () => void 0;
4130
3895
  }
4131
3896
  const timer = setInterval(() => {
4132
- if (!fs8.existsSync(filePath)) {
3897
+ if (!fs7.existsSync(filePath)) {
4133
3898
  clearInterval(timer);
4134
3899
  onRecordDeleted();
4135
3900
  }
@@ -4628,8 +4393,8 @@ var DeviceLoginApiError = class extends Error {
4628
4393
  var UNREADABLE_ANSWER = "invalid_answer";
4629
4394
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
4630
4395
  const baseUrl = buildDashboardHttpUrl(manage);
4631
- async function post(path7, body, schema) {
4632
- const response2 = await fetchImpl(`${baseUrl}/${path7}`, {
4396
+ async function post(path5, body, schema) {
4397
+ const response2 = await fetchImpl(`${baseUrl}/${path5}`, {
4633
4398
  method: "POST",
4634
4399
  headers: { "Content-Type": "application/json", Accept: "application/json" },
4635
4400
  body: JSON.stringify(body)
@@ -5473,11 +5238,11 @@ async function handleAttach(args) {
5473
5238
  }
5474
5239
 
5475
5240
  // src/cli/subcommand/handlers/logsCommand.ts
5476
- import fs10 from "fs";
5241
+ import fs9 from "fs";
5477
5242
 
5478
5243
  // src/daemon/logPaths.ts
5479
- import fs9 from "fs";
5480
- import path4 from "path";
5244
+ import fs8 from "fs";
5245
+ import path2 from "path";
5481
5246
  var TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
5482
5247
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5483
5248
  function parseTunnelLogFilename(filename) {
@@ -5497,8 +5262,8 @@ function parseTunnelLogFilename(filename) {
5497
5262
  }
5498
5263
  function listTunnelLogFiles() {
5499
5264
  const logDir = getTunnelLogDir();
5500
- if (!fs9.existsSync(logDir)) return [];
5501
- return fs9.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
5265
+ if (!fs8.existsSync(logDir)) return [];
5266
+ return fs8.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
5502
5267
  }
5503
5268
  function newestLogFile(q) {
5504
5269
  const logDir = getTunnelLogDir();
@@ -5509,8 +5274,8 @@ function newestLogFile(q) {
5509
5274
  const nameMatch = parsed.name !== void 0 && parsed.name === q;
5510
5275
  const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
5511
5276
  if (nameMatch || idMatch) {
5512
- const filePath = path4.join(logDir, file);
5513
- matches.push({ ...parsed, path: filePath, mtime: fs9.statSync(filePath).mtimeMs });
5277
+ const filePath = path2.join(logDir, file);
5278
+ matches.push({ ...parsed, path: filePath, mtime: fs8.statSync(filePath).mtimeMs });
5514
5279
  }
5515
5280
  }
5516
5281
  if (matches.length === 0) return null;
@@ -5586,7 +5351,7 @@ async function handleLogs(args, follow) {
5586
5351
  return;
5587
5352
  }
5588
5353
  client.close();
5589
- if (!filePath || !fs10.existsSync(filePath)) {
5354
+ if (!filePath || !fs9.existsSync(filePath)) {
5590
5355
  printer_default.error(`Log file not found: ${filePath}`);
5591
5356
  process.exit(1);
5592
5357
  }
@@ -5597,18 +5362,18 @@ async function handleLogs(args, follow) {
5597
5362
  }
5598
5363
  }
5599
5364
  function printTail(filePath, lines) {
5600
- const content = fs10.readFileSync(filePath, "utf-8");
5365
+ const content = fs9.readFileSync(filePath, "utf-8");
5601
5366
  const allLines = content.split("\n");
5602
5367
  const tail = allLines.slice(-lines).join("\n");
5603
5368
  process.stdout.write(tail);
5604
5369
  if (!tail.endsWith("\n")) process.stdout.write("\n");
5605
5370
  }
5606
5371
  async function followFile(filePath) {
5607
- if (fs10.existsSync(filePath)) printTail(filePath, 20);
5608
- let fileSize = fs10.existsSync(filePath) ? fs10.statSync(filePath).size : 0;
5372
+ if (fs9.existsSync(filePath)) printTail(filePath, 20);
5373
+ let fileSize = fs9.existsSync(filePath) ? fs9.statSync(filePath).size : 0;
5609
5374
  let watcher = null;
5610
5375
  const openStream = () => {
5611
- const stream = fs10.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
5376
+ const stream = fs9.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
5612
5377
  stream.on("data", (chunk) => {
5613
5378
  process.stdout.write(chunk);
5614
5379
  fileSize += Buffer.byteLength(chunk, "utf-8");
@@ -5616,9 +5381,9 @@ async function followFile(filePath) {
5616
5381
  stream.on("error", () => {
5617
5382
  });
5618
5383
  };
5619
- watcher = fs10.watch(filePath, { persistent: true }, (event2) => {
5384
+ watcher = fs9.watch(filePath, { persistent: true }, (event2) => {
5620
5385
  if (event2 === "change") {
5621
- const stat = fs10.existsSync(filePath) ? fs10.statSync(filePath) : null;
5386
+ const stat = fs9.existsSync(filePath) ? fs9.statSync(filePath) : null;
5622
5387
  if (!stat || stat.size < fileSize) {
5623
5388
  fileSize = 0;
5624
5389
  }
@@ -6006,6 +5771,173 @@ async function handleDeviceStatus(background) {
6006
5771
  await printBackgroundStatus(background);
6007
5772
  }
6008
5773
 
5774
+ // src/cli/subcommand/handlers/updateCommand.ts
5775
+ var EXIT_OK2 = 0;
5776
+ var EXIT_FAILURE = 1;
5777
+ var CHECK_TIMEOUT_MILLIS = 1e4;
5778
+ var CHECK_FLAG = "--check";
5779
+ var ROLLBACK_FLAG = "--rollback";
5780
+ var KNOWN_FLAGS = /* @__PURE__ */ new Set([CHECK_FLAG, ROLLBACK_FLAG]);
5781
+ var HELP_FLAGS = /* @__PURE__ */ new Set(["--help", "-h"]);
5782
+ var SUDO_UID_ENV2 = "SUDO_UID";
5783
+ function createContext() {
5784
+ return { probe: createInstallProbe(), runningVersion: getVersion() };
5785
+ }
5786
+ function targetFor(kind, context) {
5787
+ return context.target !== void 0 ? context.target : createUpdateTarget(kind, context.probe);
5788
+ }
5789
+ function printAvailable(latest, running, command) {
5790
+ printer_default.print(`pinggy ${latest} is available. You run ${running}.`);
5791
+ printer_default.print(`Run: ${command}`);
5792
+ }
5793
+ function installCommand(kind, probe) {
5794
+ return kind === InstallKind.Npm ? NPM_INSTALL_COMMAND : installCommandFor(probe.platform);
5795
+ }
5796
+ async function lookUpRelease(installed) {
5797
+ try {
5798
+ const tag = await resolveLatestTag({ timeoutMillis: CHECK_TIMEOUT_MILLIS });
5799
+ const latest = versionFromTag(tag);
5800
+ const newer = isNewerVersion(latest, installed);
5801
+ if (newer && !await isReleaseComplete(tag, { timeoutMillis: CHECK_TIMEOUT_MILLIS })) {
5802
+ printer_default.error(`Release ${tag} is not ready. Try again later.`);
5803
+ return null;
5804
+ }
5805
+ return { tag, latest, newer };
5806
+ } catch {
5807
+ printer_default.error("Could not reach GitHub to check for updates.");
5808
+ return null;
5809
+ }
5810
+ }
5811
+ async function runCheck(kind, context) {
5812
+ const running = context.runningVersion;
5813
+ const release = await lookUpRelease(running);
5814
+ if (!release) return EXIT_FAILURE;
5815
+ recordLatestVersion(release.latest);
5816
+ if (release.newer) printAvailable(release.latest, running, installCommand(kind, context.probe));
5817
+ else printer_default.print(`pinggy ${running} is up to date.`);
5818
+ return EXIT_OK2;
5819
+ }
5820
+ async function underUpdateLock(action) {
5821
+ if (!await acquireUpdateLock()) {
5822
+ printer_default.error("Another pinggy update is running.");
5823
+ return EXIT_FAILURE;
5824
+ }
5825
+ try {
5826
+ return await action();
5827
+ } catch (error) {
5828
+ if (!(error instanceof UpdateError)) throw error;
5829
+ printer_default.error(error.message);
5830
+ return EXIT_FAILURE;
5831
+ } finally {
5832
+ releaseUpdateLock();
5833
+ }
5834
+ }
5835
+ async function installRelease(release, target, context) {
5836
+ const { tag, latest } = release;
5837
+ const runningVersion = context.runningVersion;
5838
+ const assetName = assetNameFor(context.probe.platform, context.architecture ?? process.arch);
5839
+ return underUpdateLock(async () => {
5840
+ let daemonRestart;
5841
+ try {
5842
+ await downloadRelease(target, tag, assetName, runningVersion, context.download);
5843
+ daemonRestart = await daemonRestartLineFor(target.downloadPath, latest, context);
5844
+ await target.install({ newVersion: latest, runningVersion });
5845
+ } finally {
5846
+ removeQuietly(target.downloadPath);
5847
+ }
5848
+ writeUpdateState({
5849
+ rolledBackFromVersion: void 0,
5850
+ failedVersion: void 0,
5851
+ failedAttempts: void 0,
5852
+ deferredVersion: void 0,
5853
+ deferredIpcVersion: void 0
5854
+ });
5855
+ printer_default.print(`Updated pinggy ${runningVersion} to ${latest}.`);
5856
+ if (daemonRestart) printer_default.print(daemonRestart);
5857
+ return EXIT_OK2;
5858
+ });
5859
+ }
5860
+ async function daemonRestartLineFor(binaryPath, version, context) {
5861
+ const daemon = getDaemonInfo();
5862
+ if (!daemon) return null;
5863
+ const ipcVersion = await readBinaryIpcVersion(binaryPath, context.runBinary ?? runPinggyBinary).catch(() => null);
5864
+ return ipcVersion !== null && ipcVersion !== daemonIpcVersion(daemon) ? daemonRestartLine(version, daemon.host) : null;
5865
+ }
5866
+ function isRollbackCopy(kind, context) {
5867
+ return kind === InstallKind.WindowsWritable && windowsInstallPaths(context.probe.execPath).runningFromBackup;
5868
+ }
5869
+ async function runUpdate(kind, context) {
5870
+ if (isRollbackCopy(kind, context)) {
5871
+ const { liveName } = windowsInstallPaths(context.probe.execPath);
5872
+ printer_default.error(`This is the rollback copy of ${liveName}. It runs only: update ${ROLLBACK_FLAG}`);
5873
+ return EXIT_FAILURE;
5874
+ }
5875
+ const target = targetFor(kind, context);
5876
+ const running = context.runningVersion;
5877
+ const release = await lookUpRelease(target ? target.installedVersion(running) : running);
5878
+ if (!release) return EXIT_FAILURE;
5879
+ recordLatestVersion(release.latest);
5880
+ if (!release.newer) {
5881
+ printer_default.print(`pinggy ${running} is up to date.`);
5882
+ return EXIT_OK2;
5883
+ }
5884
+ if (!target) {
5885
+ printAvailable(release.latest, running, installCommand(kind, context.probe));
5886
+ return EXIT_OK2;
5887
+ }
5888
+ return installRelease(release, target, context);
5889
+ }
5890
+ async function runRollback(kind, context) {
5891
+ const target = targetFor(kind, context);
5892
+ if (!target) {
5893
+ printer_default.error(rollbackRefusal(kind));
5894
+ return EXIT_FAILURE;
5895
+ }
5896
+ return underUpdateLock(async () => {
5897
+ const { from, to } = await target.rollback(context.runningVersion);
5898
+ writeUpdateState({ updatedFromVersion: void 0, updatedToVersion: void 0 });
5899
+ printer_default.print(`Rolled back pinggy ${from} to ${to}.`);
5900
+ const daemonRestart = await daemonRestartLineFor(target.rollbackBinaryPath(to), to, context);
5901
+ if (daemonRestart) printer_default.print(daemonRestart);
5902
+ return EXIT_OK2;
5903
+ });
5904
+ }
5905
+ function rollbackRefusal(kind) {
5906
+ if (kind === InstallKind.WindowsReadOnly || kind === InstallKind.UnixLoose) return "This copy of pinggy cannot update itself.";
5907
+ return "Rollback is not available for this install.";
5908
+ }
5909
+ async function runUpdateCommand(rest, context = createContext()) {
5910
+ if (rest.some((argument) => HELP_FLAGS.has(argument))) {
5911
+ printUpdateHelp();
5912
+ return EXIT_OK2;
5913
+ }
5914
+ const check = rest.includes(CHECK_FLAG);
5915
+ const rollback = rest.includes(ROLLBACK_FLAG);
5916
+ if (rest.some((argument) => !KNOWN_FLAGS.has(argument)) || check && rollback) {
5917
+ printUpdateHelp();
5918
+ return EXIT_FAILURE;
5919
+ }
5920
+ const kind = detectInstallKind(context.probe);
5921
+ if (kind === InstallKind.DevCheckout) {
5922
+ printer_default.print("This is not a packaged build. Run from your checkout, or install a release.");
5923
+ return EXIT_OK2;
5924
+ }
5925
+ if (parseVersion(context.runningVersion) === null) {
5926
+ printer_default.error("Could not read the running version.");
5927
+ return EXIT_FAILURE;
5928
+ }
5929
+ if (check) return runCheck(kind, context);
5930
+ if (process.env[SUDO_UID_ENV2]) {
5931
+ printer_default.error("pinggy update does not run under sudo. Run it without sudo.");
5932
+ return EXIT_FAILURE;
5933
+ }
5934
+ return rollback ? runRollback(kind, context) : runUpdate(kind, context);
5935
+ }
5936
+ async function handleUpdate(rest) {
5937
+ const exitCode = await runUpdateCommand(rest);
5938
+ if (exitCode !== EXIT_OK2) process.exit(exitCode);
5939
+ }
5940
+
6009
5941
  // src/cli/subcommand/subcommands.ts
6010
5942
  var SUBCOMMAND_SET = new Set(SUBCOMMANDS);
6011
5943
  function isSubcommand(rawArgs) {
@@ -6052,6 +5984,9 @@ async function handleSubcommand(rawArgs) {
6052
5984
  case Subcommand.Devices:
6053
5985
  refuseDevicesSpelling(rest);
6054
5986
  return;
5987
+ case Subcommand.Update:
5988
+ await handleUpdate(rest);
5989
+ return;
6055
5990
  }
6056
5991
  }
6057
5992
  function handleConfig(args) {
@@ -6274,12 +6209,12 @@ async function initRemoteManagementBackground(values) {
6274
6209
  }
6275
6210
 
6276
6211
  // src/daemon/lifecycle/daemonChild.ts
6277
- import fs14 from "fs";
6212
+ import fs13 from "fs";
6278
6213
 
6279
6214
  // src/daemon/ipc/ipcServer.ts
6280
6215
  import http from "http";
6281
- import fs12 from "fs";
6282
- import path6 from "path";
6216
+ import fs11 from "fs";
6217
+ import path4 from "path";
6283
6218
  import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
6284
6219
 
6285
6220
  // src/daemon/ws/wsProtocol.ts
@@ -6306,17 +6241,17 @@ function parseClientMessage(raw) {
6306
6241
  }
6307
6242
 
6308
6243
  // src/daemon/lifecycle/stateStore.ts
6309
- import fs11 from "fs";
6310
- import path5 from "path";
6244
+ import fs10 from "fs";
6245
+ import path3 from "path";
6311
6246
  var STATE_FILENAME = "daemon-state.json";
6312
6247
  function getStatePath() {
6313
- return path5.join(getPinggyConfigDir(), STATE_FILENAME);
6248
+ return path3.join(getPinggyConfigDir(), STATE_FILENAME);
6314
6249
  }
6315
6250
  function loadDaemonState() {
6316
6251
  const statePath = getStatePath();
6317
6252
  try {
6318
- if (!fs11.existsSync(statePath)) return null;
6319
- const raw = fs11.readFileSync(statePath, "utf-8");
6253
+ if (!fs10.existsSync(statePath)) return null;
6254
+ const raw = fs10.readFileSync(statePath, "utf-8");
6320
6255
  const state = JSON.parse(raw);
6321
6256
  if (!Array.isArray(state.tunnels)) return null;
6322
6257
  return state;
@@ -6330,8 +6265,8 @@ function persistDaemonState(state) {
6330
6265
  const tmpPath = statePath + ".tmp";
6331
6266
  try {
6332
6267
  state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
6333
- fs11.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
6334
- fs11.renameSync(tmpPath, statePath);
6268
+ fs10.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
6269
+ fs10.renameSync(tmpPath, statePath);
6335
6270
  } catch (err) {
6336
6271
  logger.error("Failed to persist daemon state", { error: errorMessage(err) });
6337
6272
  }
@@ -6339,8 +6274,8 @@ function persistDaemonState(state) {
6339
6274
  function clearDaemonState() {
6340
6275
  const statePath = getStatePath();
6341
6276
  try {
6342
- if (fs11.existsSync(statePath)) {
6343
- fs11.unlinkSync(statePath);
6277
+ if (fs10.existsSync(statePath)) {
6278
+ fs10.unlinkSync(statePath);
6344
6279
  }
6345
6280
  } catch {
6346
6281
  }
@@ -6510,8 +6445,8 @@ var IPCServer = class {
6510
6445
  if (n) activeNames.add(n);
6511
6446
  }
6512
6447
  for (const file of files) {
6513
- const filePath = path6.join(logDir, file);
6514
- const stat = fs12.statSync(filePath);
6448
+ const filePath = path4.join(logDir, file);
6449
+ const stat = fs11.statSync(filePath);
6515
6450
  const parsed = parseTunnelLogFilename(file);
6516
6451
  if (!parsed) continue;
6517
6452
  const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
@@ -7157,11 +7092,11 @@ function machineDeviceAgentHostDependencies(port, record) {
7157
7092
  }
7158
7093
 
7159
7094
  // src/daemon/lifecycle/daemonLock.ts
7160
- import fs13 from "fs";
7095
+ import fs12 from "fs";
7161
7096
  var UNREADABLE_LOCK_GRACE_MILLIS = 1e4;
7162
7097
  function readLock(lockPath) {
7163
7098
  try {
7164
- const record = JSON.parse(fs13.readFileSync(lockPath, "utf-8"));
7099
+ const record = JSON.parse(fs12.readFileSync(lockPath, "utf-8"));
7165
7100
  return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
7166
7101
  } catch {
7167
7102
  return null;
@@ -7169,7 +7104,7 @@ function readLock(lockPath) {
7169
7104
  }
7170
7105
  function isUnreadableLockOld(lockPath) {
7171
7106
  try {
7172
- return Date.now() - fs13.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
7107
+ return Date.now() - fs12.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
7173
7108
  } catch {
7174
7109
  return true;
7175
7110
  }
@@ -7180,7 +7115,7 @@ function isStale(lockPath, holder) {
7180
7115
  }
7181
7116
  function createLock(lockPath, record) {
7182
7117
  try {
7183
- fs13.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
7118
+ fs12.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
7184
7119
  return true;
7185
7120
  } catch (err) {
7186
7121
  if (err.code === "EEXIST") return false;
@@ -7196,13 +7131,13 @@ function acquireDaemonLock() {
7196
7131
  if (holder?.pid === process.pid) return true;
7197
7132
  if (!isStale(lockPath, holder)) return false;
7198
7133
  logger.info("Stale daemon.lock found, replacing it", { stalePid: holder?.pid });
7199
- fs13.rmSync(lockPath, { force: true });
7134
+ fs12.rmSync(lockPath, { force: true });
7200
7135
  return createLock(lockPath, record);
7201
7136
  }
7202
7137
  function releaseDaemonLock() {
7203
7138
  const lockPath = getDaemonLockPath();
7204
7139
  if (readLock(lockPath)?.pid === process.pid) {
7205
- fs13.rmSync(lockPath, { force: true });
7140
+ fs12.rmSync(lockPath, { force: true });
7206
7141
  }
7207
7142
  }
7208
7143
 
@@ -7220,14 +7155,14 @@ function writeDaemonInfo(info) {
7220
7155
  ensurePinggyConfigDir();
7221
7156
  const infoPath = getDaemonInfoPath();
7222
7157
  const tmpPath = infoPath + ".tmp";
7223
- fs14.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
7224
- fs14.renameSync(tmpPath, infoPath);
7158
+ fs13.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
7159
+ fs13.renameSync(tmpPath, infoPath);
7225
7160
  }
7226
7161
  function removeDaemonInfo() {
7227
7162
  try {
7228
7163
  const infoPath = getDaemonInfoPath();
7229
- const info = JSON.parse(fs14.readFileSync(infoPath, "utf-8"));
7230
- if (info.pid === process.pid) fs14.unlinkSync(infoPath);
7164
+ const info = JSON.parse(fs13.readFileSync(infoPath, "utf-8"));
7165
+ if (info.pid === process.pid) fs13.unlinkSync(infoPath);
7231
7166
  } catch {
7232
7167
  }
7233
7168
  }
@@ -7456,7 +7391,8 @@ async function runDaemonChild(opts = {}) {
7456
7391
  port,
7457
7392
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
7458
7393
  host: daemonHost,
7459
- ipcVersion: IPC_VERSION
7394
+ ipcVersion: IPC_VERSION,
7395
+ cliVersion: getVersion()
7460
7396
  };
7461
7397
  writeDaemonInfo(info);
7462
7398
  logger.info("Daemon info written", info);
@@ -7502,10 +7438,21 @@ async function main() {
7502
7438
  const { values, positionals, hasAnyArgs } = parseCliArgs(cliOptions);
7503
7439
  configureLogger(values);
7504
7440
  if (values["_daemon-child"]) {
7505
- const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-HZ27YJKQ.js");
7441
+ const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-Q6WGYKYX.js");
7506
7442
  await runDaemonChild2();
7507
7443
  return;
7508
7444
  }
7445
+ if (values["_ipc-version"]) {
7446
+ printer_default.print(String(IPC_VERSION));
7447
+ return;
7448
+ }
7449
+ if (values["_update-child"]) {
7450
+ const { runUpdateChild } = await import("./updateChild-Z3SIRYO5.js");
7451
+ await runUpdateChild();
7452
+ process.exit(0);
7453
+ }
7454
+ if (isPackagedBinary() && platform2() === "win32") removeStaleUpdateFiles();
7455
+ startBackgroundUpdate({ rawArgs, values, hasAnyArgs });
7509
7456
  if (isSubcommand(rawArgs)) {
7510
7457
  await handleSubcommand(rawArgs);
7511
7458
  return;