pinggy 0.6.7 → 0.6.9

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/ARCHITECTURE.md CHANGED
@@ -39,8 +39,8 @@ Logs live under `getPinggyLogDir()`:
39
39
 
40
40
  ```
41
41
  <configDir>/
42
- ├── daemon.json Daemon discovery: {pid, port, startedAt}
43
- ├── daemon.lock Held by the running daemon: {pid, started_at}
42
+ ├── daemon.json Daemon discovery: {pid, port, startedAt, bootId, ...}
43
+ ├── daemon.lock Held by the running daemon: {pid, started_at, boot_id}
44
44
  ├── daemon-config.json Persisted settings: log level, and the background device agent to start
45
45
  ├── daemon-state.json Active tunnels, for crash recovery
46
46
  ├── device.json Device agent identity + token, mode 0600
@@ -52,6 +52,8 @@ Logs live under `getPinggyLogDir()`:
52
52
  <logDir>/
53
53
  ├── daemon.log Daemon process log (rolled)
54
54
  ├── update.log The last background update, overwritten each run
55
+ ├── libpinggy/
56
+ │ └── libpinggy.log libpinggy's lines for every tunnel (rolled at daemon start)
55
57
  └── tunnels/
56
58
  └── <origin>__<name>__<tunnelId>.log Per-tunnel logs (rolled 10MB×3)
57
59
  ```
@@ -60,7 +62,9 @@ Helpers live in `src/utils/configDir.ts`: `getDaemonInfoPath`, `getDaemonLogPath
60
62
 
61
63
  ## 3. Daemon discovery and spawn
62
64
 
63
- Every CLI invocation that touches a tunnel asks one question first: is there a live daemon to talk to? `getDaemonInfo()` answers it by reading `daemon.json` and validating the recorded PID with `process.kill(pid, 0)`. Signal 0 never delivers anything; it just throws when the target process is gone, which is exactly the liveness probe we need. A missing file, malformed JSON, a dead PID, or a `startedAt` before the last boot all collapse to the same result: return `null`. After a reboot, another process can have the old daemon's PID, so the boot check runs first. Only commands that start a tunnel (`pinggy start`, legacy `pinggy -l 3000`) then call `ensureDaemonRunning()` to spawn a fresh child. `ps`, `stop`, `restart`, `attach`, `logs` and `log` call `TunnelClient.connectIfRunning()` instead, which never spawns: a new daemon would start every auto-start tunnel. With no daemon, `ps` prints "No active tunnels. The daemon is not running.", `stop` prints "Nothing to stop.", and `restart` and `attach` name the `pinggy start` command when a saved config matches. `logs` and `log path` read the log files directly (`src/daemon/logPaths.ts`), and `log level` reads or writes `daemon-config.json`, which the next daemon starts with.
65
+ Every CLI invocation that touches a tunnel asks one question first: is there a live daemon to talk to? `getDaemonInfo()` answers it by reading `daemon.json` and validating the recorded PID with `process.kill(pid, 0)`. Signal 0 never delivers anything; it just throws when the target process is gone, which is exactly the liveness probe we need. A missing file, malformed JSON, a dead PID, or a file from an earlier boot all collapse to the same result: return `null`. After a reboot, another process can have the old daemon's PID, so the boot check runs first. Only commands that start a tunnel (`pinggy start`, legacy `pinggy -l 3000`) then call `ensureDaemonRunning()` to spawn a fresh child. `ps`, `stop`, `restart`, `attach`, `logs` and `log` call `TunnelClient.connectIfRunning()` instead, which never spawns: a new daemon would start every auto-start tunnel. With no daemon, `ps` prints "No active tunnels. The daemon is not running.", `stop` prints "Nothing to stop.", and `restart` and `attach` name the `pinggy start` command when a saved config matches. `logs` and `log path` read the log files directly (`src/daemon/logPaths.ts`), and `log level` reads or writes `daemon-config.json`, which the next daemon starts with.
66
+
67
+ **The boot check** (`startedInEarlierBoot()`, `src/daemon/lifecycle/bootId.ts`) serves `daemon.json`, `daemon.lock` and `device-agent.json`. Each writer saves the OS boot ID: `/proc/sys/kernel/random/boot_id` on Linux, `/usr/sbin/sysctl -n kern.bootsessionuuid` on macOS. Each process reads it once. A record whose boot ID differs from this boot's comes from an earlier boot. A clock step leaves the ID alone. A record with no boot ID, written by an older version or on Windows, which gives none here, falls back to time: `startedAt` more than 60s before `Date.now() - os.uptime()`. `os.uptime()` ignores clock changes and `Date.now()` does not, so a forward clock step moves that boot time later. After a step bigger than the time from boot to the daemon's start plus 60s, the fallback takes a running daemon for one from an earlier boot. The CLI then deletes its `daemon.json`, every command reports no daemon while it runs, and the next spawn takes over `daemon.lock` and runs a 2nd daemon. The fallback ends once every record carries a boot ID and Windows reads one.
64
68
 
65
69
  The spawn path is deliberately one-way. The CLI fires off a detached child with the `--_daemon-child` flag and then polls `daemon.json` until the child writes it. The poll budget is 8 seconds at 200ms intervals; a timeout almost always means the SDK failed to load inside the child, in which case the stderr captured from the spawned process is surfaced in the thrown error. Atomic writes of `daemon.json` (write to `.tmp`, then `fs.renameSync`) keep concurrent readers from ever seeing a half-written file.
66
70
 
@@ -98,7 +102,7 @@ The spawn path is deliberately one-way. The CLI fires off a detached child with
98
102
 
99
103
  Implementation: `src/daemon/daemonManager.ts`.
100
104
 
101
- The `daemon.json` check only stops the CLI from spawning a child. 2 CLIs started at the same moment can both find no `daemon.json` and both spawn one, and systemd and launchd run `--_daemon-child` with no check at all. So the daemon itself takes `daemon.lock` (`src/daemon/lifecycle/daemonLock.ts`) before it opens its IPC port. The file is created with the `wx` flag, so only 1 process creates it. A daemon that finds a live holder exits 0, or throws when the app hosts it in-process. Exit code 0 keeps systemd's `Restart=on-failure` from starting it again. The spawning CLI keeps polling after a child exits 0, and gets the winner's `daemon.json`. A lock is stale when its PID is dead (`process.kill(pid, 0)` throws `ESRCH`), when its `started_at` is before the last boot (the PID may name another process now), or when it is unreadable and older than 10s (a crash between create and write). The next daemon deletes a stale lock and creates its own. 2 daemons that find the same stale lock at the same moment can both take it. `EPERM` counts as alive: the service task runs without admin rights, and gets `EPERM` for a daemon started from an Administrator shell. Treating that as dead started a 2nd daemon on Windows. The daemon deletes `daemon.lock` and `daemon.json` on exit only when they hold its own PID.
105
+ The `daemon.json` check only stops the CLI from spawning a child. 2 CLIs started at the same moment can both find no `daemon.json` and both spawn one, and systemd and launchd run `--_daemon-child` with no check at all. So the daemon itself takes `daemon.lock` (`src/daemon/lifecycle/daemonLock.ts`) before it opens its IPC port. The file is created with the `wx` flag, so only 1 process creates it. A daemon that finds a live holder exits 0, or throws when the app hosts it in-process. Exit code 0 keeps systemd's `Restart=on-failure` from starting it again. The spawning CLI keeps polling after a child exits 0, and gets the winner's `daemon.json`. A lock is stale when its PID is dead (`process.kill(pid, 0)` throws `ESRCH`), when it comes from an earlier boot (the PID may name another process now, see "The boot check" in section 3), or when it is unreadable and older than 10s (a crash between create and write). The next daemon deletes a stale lock and creates its own. 2 daemons that find the same stale lock at the same moment can both take it. `EPERM` counts as alive: the service task runs without admin rights, and gets `EPERM` for a daemon started from an Administrator shell. Treating that as dead started a 2nd daemon on Windows. The daemon deletes `daemon.lock` and `daemon.json` on exit only when they hold its own PID.
102
106
 
103
107
  The CLI keeps its `daemon.json` check. It reads the port from that file anyway, and it skips a process start when a daemon already runs.
104
108
 
@@ -418,7 +422,7 @@ src/
418
422
  - `TunnelStateType` (`src/types.ts`): `idle | starting | running | live | closed | exited`.
419
423
  - `FinalConfig` (`src/types.ts`): the SDK's `TunnelConfigurationV1` plus `conf?` and `saveconf?`. Used by `buildConfig.ts` and threaded through to the daemon.
420
424
  - `TunnelResponseV2` (`src/remote_management/handler.ts`): `{tunnelid, remoteurls, tunnelconfig, status, stats, greetmsg?}`. The canonical wire shape.
421
- - `DaemonInfo` (`src/daemon/daemonChild.ts`): `{pid, port, startedAt}`. The contents of `daemon.json`.
425
+ - `DaemonInfo` (`src/daemon/lifecycle/daemonChild.ts`): `{pid, port, startedAt, host, ipcVersion, cliVersion, bootId}`. The contents of `daemon.json`.
422
426
  - `DaemonStateTunnel` (`src/daemon/stateStore.ts`): `{tunnelId, configId, name, origin, config, mode, startedAt}`. Crash recovery row.
423
427
 
424
428
  ## 12. Singletons and listener maps
@@ -452,15 +456,18 @@ This is how a shared daemon distinguishes tunnels from different clients on disk
452
456
 
453
457
  ## 14. Logging architecture
454
458
 
455
- Three log artifacts:
459
+ Four log artifacts:
456
460
 
457
461
  | Log | Writer | Path | Lifetime |
458
462
  | --------------- | ------------------------------------- | ----------------------------------------------------- | ----------------------------- |
459
463
  | Application log | Electron host via `electron-log` | `<userData>/logs/` | Persistent, rolled |
460
464
  | Daemon log | winston root inside daemon | `<logDir>/daemon.log` | Persistent, rolled |
461
- | Tunnel log | winston `File` transport per tunnel | `<logDir>/tunnels/<origin>__<name>__<tunnelId>.log` | While tunnel runs (10MB × 3) |
465
+ | Tunnel log | winston `File` transport per tunnel, plus the SDK worker's own lines | `<logDir>/tunnels/<origin>__<name>__<tunnelId>.log` | While tunnel runs (10MB × 3) |
466
+ | libpinggy log | libpinggy, for every tunnel | `<logDir>/libpinggy/libpinggy.log` | Persistent, rolled at daemon start |
467
+
468
+ libpinggy has one log file per process, not per tunnel, and whoever sets its path last gets the lines of every tunnel. So `setNativeLogging()` in `src/logger/nativeLog.ts` sets the path once, from the main thread, the first time logging is on, and tunnels are created with `libpinggyLogPath: null`. libpinggy keeps the file open, so it rotates only before that first open. libpinggy has no log level at runtime, only on or off; a release build writes DEBUG and above. `pinggy logs libpinggy` and `pinggy log path libpinggy` reach the file: `logLookup.ts` answers with it when no tunnel or saved config has that name, without asking the daemon.
462
469
 
463
- Toggle: `setTunnelLoggingEnabled(false)` detaches every per-tunnel transport immediately. Tunnels keep running; nothing else changes. Re-enabling does not retroactively re-attach to running tunnels (transports are recreated on next tunnel start).
470
+ Toggle: `POST /config/tunnel-logging` covers all per-tunnel output. Off detaches every per-tunnel transport, turns libpinggy logging off, and tells each running worker to stop writing; tunnels keep running. On turns libpinggy and the running workers back on at once, but does not re-attach the winston transport to running tunnels (it is recreated on the next tunnel start). A daemon starts with the toggle on.
464
471
 
465
472
  CLI logs (the short-lived foreground process) go to stdout by default. The daemon log captures everything inside the long-running process.
466
473
 
@@ -483,7 +490,7 @@ Same code path as user-typed subcommands: the daemon does not know or care that
483
490
  - macOS: launchd `LaunchAgent` at `~/Library/LaunchAgents/io.pinggy.agent.plist`. `launchctl load`.
484
491
  - Windows: Task Scheduler task `PinggyDaemon`, created with `schtasks /Create` and no admin rights. A logon trigger for the current user runs `<binary> daemon start`. `daemon start` spawns `--_daemon-child` detached with `windowsHide`, then exits. The task does not run `--_daemon-child` directly: `pinggy.exe` is a console program, so Task Scheduler opens a console window for it, and closing that window kills the daemon. The `daemon start` window shows for about 1s. The task ends once the daemon is up, so uninstall stops the daemon over IPC. It deletes the task first, so a failed delete leaves the daemon running. With no task, it stops nothing. A task created from an Administrator terminal keeps admin-only permissions, so a normal terminal cannot replace or delete it. When `schtasks` fails, the task exists, and `whoami /groups` shows no High or System integrity SID, pinggy tells the user to run the command from an Administrator terminal. It checks the SID, not the "Access is denied" text, because `schtasks` prints that text in the Windows language.
485
492
 
486
- The service stores the full path of the binary (`process.execPath`). If the user moves or deletes that file, the service fails at login with no message. So `service-install` runs only from the path the install scripts write: `%LOCALAPPDATA%\Pinggy\bin\pinggy.exe` on Windows, `~/.pinggy/bin/pinggy` on Linux and macOS (`installerBinaryPath()`). The scripts update the binary in place, so the stored path stays valid. From any other path, and from an npm install, it prints the install script command and exits 1. The message names no paths. `PINGGY_SERVICE_ANY_LOCATION=1` skips the path check, for development and CI. It does not allow npm installs. `service-uninstall` runs from any path. On Linux and macOS, `service-install` starts the service at once, and the service runs `--_daemon-child`. When a daemon already runs, for example after `pinggy device login`, the service's daemon finds `daemon.lock` held and exits 0, so 1 daemon and 1 device agent stay. On Windows the task runs `daemon start`, which finds the running daemon and exits. Changing the install directory in either script means changing `installerBinaryPath()` in the same commit.
493
+ The service stores the full path of the binary (`process.execPath`). If the user moves or deletes that file, the service fails at login with no message. So `service-install` runs only from the path the install scripts write: `%LOCALAPPDATA%\Pinggy\bin\pinggy.exe` on Windows, `~/.pinggy/bin/pinggy` on Linux and macOS (`installerBinaryPath()`). The scripts update the binary in place, so the stored path stays valid. From any other path it prints the install script command and exits 1. From an npm install it prints `npm uninstall -g pinggy` first, because the install script updates an npm copy with npm. The message names no paths, except when the installed copy exists: then it names that copy and the command to run with it, because a downloaded binary can install itself and then run `service-install` in the same process. `PINGGY_SERVICE_ANY_LOCATION=1` skips the path check, for development and CI. It does not allow npm installs. `service-uninstall` runs from any path. On Linux and macOS, `service-install` starts the service at once, and the service runs `--_daemon-child`. When a daemon already runs, for example after `pinggy device login`, the service's daemon finds `daemon.lock` held and exits 0, so 1 daemon and 1 device agent stay. On Windows the task runs `daemon start`, which finds the running daemon and exits. Changing the install directory in either script means changing `installerBinaryPath()` in the same commit.
487
494
 
488
495
  A system service gives restart-on-failure and start-at-login. The plain daemon mode does not.
489
496
 
@@ -491,13 +498,17 @@ On macOS and Linux an installed binary sits behind the link `~/.pinggy/bin/pingg
491
498
 
492
499
  ## 17. Device agent (`pinggy device`)
493
500
 
494
- The one long-lived surface that is not a tunnel. `pinggy device connect` enrols the machine with the Pinggy dashboard and holds 1 WebSocket open so the dashboard can show it as online. By default the daemon runs it (see Background mode below). With `--foreground` it runs in the CLI process. Code lives in `src/devices/`, entered from `src/cli/subcommand/handlers/deviceCommand.ts`.
501
+ The one long-lived surface that is not a tunnel. `pinggy device connect` enrols the machine with the Pinggy dashboard and holds 1 WebSocket open so the dashboard can show it as online. By default the daemon runs it (see Background mode below). With `--foreground` it runs in the CLI process. Code lives in `src/devices/`, entered from `src/cli/subcommand/handlers/deviceCommand.ts`. `pinggy device start` is the same verb as `connect`: `handleDevice()` sends both to `handleDeviceConnect()`, so everything below about `connect` holds for `start`.
495
502
 
496
503
  **Email sign-in.** `pinggy device login` gets the device token without the dashboard: it asks for an email, `POST /backend/api/v1/device-agent/login/start` emails a 6-digit code, and the code prompt races a `poll` every few seconds under 1 `AbortController`. A right code (and the TOTP, with MFA on) answers the token once. The email also carries an Approve link: the CLI prints the `match_code` its page shows as `Device Code: <code>`, then `We have sent a 6-digit code to <email>.` and `Enter the code below or click the approve button in the email.` A poll collects a link's approval, and a typed code answered `pending` stops the prompt so the poll can. The CLI writes `device.json`, prints the device's browser link and its QR code (`createQrCodes`, shared with the TUI): a one-time sign-in link after a typed code, the plain device page after the emailed link. Then it runs the same agent. Code in `src/devices/login/`: `deviceLogin.ts` (the command; every dependency injected, so `src/_tests_/deviceLogin.test.ts` runs it with no dashboard or terminal), `loginApi.ts` (`fetch`, `buildDashboardHttpUrl`, the public client token), `login_schema.ts` (zod), `prompts.ts` (`readline/promises`, 1 interface per question, closed on answer or abort; every question starts with a cyan `→`, and the sign-in result with a green one, through `picocolors`; `askHidden` reads the authenticator code without showing it, since the code still works after it is typed and the open link asks for one). A stdin that is not a TTY stops at once and points at `connect --token`. The token is never printed.
497
504
 
498
- **Install scripts.** `scripts/install/install.sh` (macOS, Linux, POSIX `sh`) and `scripts/install/install.ps1` (Windows PowerShell 5.1 and 7) install or update the binary, put `pinggy` on PATH with no sudo, then ask "Connect this device to Pinggy? [Y/n]". Enter or `y` runs `pinggy device login -b` by full path. `-b` is the default, and the scripts pass it so an older binary the user kept also runs the agent in its daemon. An answer starting with `n` prints the login command and exits 0, so the CLI is installed with no device. With no terminal, the scripts ask nothing and print the command. `install.sh` writes `~/.pinggy/bin/pinggy` and links `~/.local/bin/pinggy` to it, adding 1 marked block to the shell's rc file when `~/.local/bin` is not on PATH. `install.ps1` writes `%LOCALAPPDATA%\Pinggy\bin\pinggy.exe` and adds that directory to the user PATH. Both read the version to install from `https://pinggy.io/cli/version.json`, never from GitHub's `/releases/latest`. The website builds that file from `data/cli_releases.yaml`, and the release PR changes that list and both scripts in 1 commit, so the script and the binary come from 1 release. When pinggy.io does not answer, or the file has no `x.y.z` in its `version` field, the scripts exit 1 with a message that names the URL and `PINGGY_VERSION`. `PINGGY_VERSION` skips the request. The binary still downloads from the GitHub release. `install.sh` reads the field with `sed`, so the key stays `version` with a quoted value. Both read 3 things this repo owns: the release asset names, the `Pinggy CLI version: <x.y.z>` line, and the `--manage` and `-b` flags of `device login` and `connect`. A change to any of them changes both scripts in the same commit. `.github/workflows/website-cli-download-links-pr.yml` copies both, read at the release tag, to the website's `static/`, so pinggy.io serves `/install.sh` and `/install.ps1`. After `device login` or `connect` exits 0, both scripts ask "Start pinggy automatically when this computer starts? [Y/n]" and run `pinggy daemon service-install`. The question says "starts" for users. On macOS and Windows the service starts pinggy after the user signs in, not at boot. On Linux it starts at boot, because `service-install` turns on lingering. They skip the question when the service exists and runs the installed binary: `install.sh` looks for that binary's path in the launchd plist or the systemd unit file, `install.ps1` compares the command of the `PinggyDaemon` task (`Get-ScheduledTask`) with it. A service that runs any other binary gets the question, and `service-install` replaces it. `install.sh` also skips it on Linux with no systemd user manager. With no terminal, they print the `service-install` command. They remove `DEVICE_AGENT_TOKEN` before the question. Renaming the task, the plist or the unit file changes both scripts in the same commit. Lint with `shellcheck -s sh` and `PSScriptAnalyzer`.
505
+ **Install scripts.** `scripts/install/install.sh` (macOS, Linux, POSIX `sh`) and `scripts/install/install.ps1` (Windows PowerShell 5.1 and 7) install or update the binary, put `pinggy` on PATH with no sudo, then ask "Connect this device to Pinggy? [Y/n]". Enter or `y` runs `pinggy device login -b` by full path. `-b` is the default, and the scripts pass it so an older binary the user kept also runs the agent in its daemon. An answer starting with `n` prints the login command and exits 0, so the CLI is installed with no device. With no terminal, the scripts ask nothing and print the command. `install.sh` writes `~/.pinggy/bin/pinggy` and links `~/.local/bin/pinggy` to it, adding 1 marked block to the shell's rc file when `~/.local/bin` is not on PATH. `install.ps1` writes `%LOCALAPPDATA%\Pinggy\bin\pinggy.exe` and adds that directory to the user PATH. Both read the version to install from `https://pinggy.io/cli/version.json`, never from GitHub's `/releases/latest`. The website builds that file from `data/cli_releases.yaml`, and the release PR changes that list and both scripts in 1 commit, so the script and the binary come from 1 release. When pinggy.io does not answer, or the file has no `x.y.z` in its `version` field, the scripts exit 1 with a message that names the URL and `PINGGY_VERSION`. `PINGGY_VERSION` skips the request. The binary still downloads from the GitHub release. `install.sh` reads the field with `sed`, so the key stays `version` with a quoted value. Both read 3 things this repo owns: the release asset names, the `Pinggy CLI version: <x.y.z>` line, and the `--manage` and `-b` flags of `device login` and `connect`. A change to any of them changes both scripts in the same commit. `.github/workflows/website-cli-download-links-pr.yml` copies both, read at the release tag, to the website's `static/`, so pinggy.io serves `/install.sh` and `/install.ps1`. After `device login` or `connect` exits 0, both scripts ask "Start pinggy automatically when this computer starts? [Y/n]" and run `pinggy daemon service-install`. The question says "starts" for users. On macOS and Windows the service starts pinggy after the user signs in, not at boot. On Linux it starts at boot, because `service-install` turns on lingering. They skip the question when the service exists and runs the installed binary: `install.sh` looks for that binary's path in the launchd plist or the systemd unit file, `install.ps1` compares the command of the `PinggyDaemon` task (`Get-ScheduledTask`) with it. A service that runs any other binary gets the question, and `service-install` replaces it. `install.sh` also skips it on Linux with no systemd user manager. With no terminal, they print the `service-install` command. They remove `DEVICE_AGENT_TOKEN` before the question. Renaming the task, the plist or the unit file changes both scripts in the same commit. Before each request the user waits on, both scripts print what it does: `Checking the latest version of Pinggy...` before `version.json`, and `Checking the latest version of pinggy on npm...` before `npm view`. Each request has a stall check and no limit on its total time. curl gets `--speed-limit 1 --speed-time 60`: it gives up when less than 1 byte per second arrives for 60 s. wget gets `--read-timeout=60 --tries=2`. The OS still ends a connection attempt with no answer, and curl a stalled TLS handshake after 5 min. Windows PowerShell 5.1 has no stall check, so `install.ps1` gives the version request `-TimeoutSec 60` and the binary download no limit. `install.sh` prints `Downloading pinggy <version> for <os>-<cpu>` and runs the download in the background. With a terminal on stderr, it rewrites 1 line each second, ` 23.4 MB of 61.5 MB (38%)`. The total comes from the `Content-Length` of the 2xx response in the file curl writes with `-D`, since GitHub's redirect sends `Content-Length: 0` first. curl's own `--progress-bar` drew an unknown-size animation during that redirect, and drew 79 columns under `curl | sh`, which gives curl no terminal width. curl's errors go to a file and print after the line ends. wget shows the size with no total. `install.ps1` downloads with no progress line. After the install, before the sign-in, both scripts offer a daemon restart. They read `pid`, `host` and `cliVersion` from `daemon.json`. When the pid runs `--_daemon-child`, `host` is not `app`, and `cliVersion` differs from what the copy they sign in with prints, they ask "Restart it with <version>? [Y/n]". Yes restarts the daemon the way `serviceRestartInstruction()` names: `launchctl kickstart -k gui/<uid>/io.pinggy.agent` when launchd's process is the daemon, `systemctl --user restart pinggy` when systemd's is. Otherwise, and always on Windows, they run `pinggy daemon stop`, wait up to 10 s for the pid to end, and run `pinggy daemon start`. The restart runs without `DEVICE_AGENT_TOKEN`, because a daemon copies the environment of the command that starts it. Then they read `daemon.json` again and print `The pinggy daemon now runs <version>.` or the restart command. No, or no terminal, restarts nothing and prints the restart command. Tunnels started with `-b` or from the dashboard stop with the old daemon, because a clean stop deletes `daemon-state.json`. Auto-start tunnels and the device agent start again. `PINGGY_INSTALL_ONLY=1` skips the question. Lint with `shellcheck -s sh` and `PSScriptAnalyzer`.
506
+
507
+ **Which copy the scripts update.** Both scripts update the copy that the `pinggy` command runs in that terminal: `command -v pinggy` with every link resolved in `install.sh` (a `readlink` loop and `cd -P`, since macOS before 13 has no `realpath`), and the first `Get-Command pinggy` in `install.ps1`. No copy, or the scripts' own binary, gets the binary flow above. An npm copy is a real path under `<prefix>/lib/node_modules/pinggy/`, or on Windows a launcher folder that holds `node_modules\pinggy\package.json` and no junction there. The scripts update it with `npm install -g --prefix <prefix> pinggy@<version>`, with the version from `npm view pinggy version`, because npm publishes in a separate job. `--prefix` updates that copy even when the `npm` on PATH uses another global folder. The npm flow writes no binary and no PATH, signs in with npm's copy by full path (`pinggy.cmd` on Windows, since an execution policy can block `pinggy.ps1`), and skips the login service question with no message, because `service-install` refuses the npm version. A broken npm copy, one that prints no `Pinggy CLI version:` line, gets "Reinstall it with npm? [Y/n]". On macOS and Linux, a folder the user cannot write stops the script with the `sudo npm install -g --prefix` command. On Windows, when the update fails while `%APPDATA%\pinggy\daemon.json` names a live process, `install.ps1` asks "pinggy is running. Stop it and all its tunnels, then retry? [Y/n]". With no terminal that answer is no. A program file the scripts did not install, such as a binary downloaded by hand, gets "Install the latest pinggy, <version>, to ~/.pinggy/bin/pinggy? [Y/n]". No signs in with that file and skips the login service question. A script file, one that starts with `#!` (`npm link`, pnpm, yarn, bun), stops the script with exit 1 and names the command's path. bun's Windows launcher is a `pinggy.exe` beside a `pinggy.bunx`, and counts as a script. `PINGGY_BINARY_URL` skips the check and installs that file.
508
+
509
+ **A downloaded binary installs itself.** `offerSelfInstall()` in `src/install/selfInstall.ts` runs in `main.ts` before the background update. A packaged binary that is not the installed copy (`UnixLayout` or `UnixPlainFile`, or on Windows any file in `%LOCALAPPDATA%\Pinggy\bin`) asks 1 question when stdin and stdout are terminals. With nothing installed, or when `pinggy` runs a copy it cannot remove (`npm link`, pnpm, yarn, bun, another binary): "Install this pinggy, X, to ~/.pinggy/bin/pinggy? [Y/n]". With the scripts' binary installed, whatever its version: "pinggy X is installed in ~/.pinggy/bin/pinggy. Replace it with this pinggy, Y? [Y/n]". When `pinggy` runs an npm copy, whatever its version: "pinggy X is installed with npm. Remove it, and install this pinggy, Y, to ~/.pinggy/bin/pinggy? [Y/n]". The versions are printed and never compared, so an older file can replace a newer install, and the same version asks again. `src/install/pinggyOnPath.ts` finds the copy with the scripts' npm rules and never counts the current folder. No question for `--version`, `--help` or `pinggy update`, under sudo, in a container, while `update.lock` is held, when `update.json` cannot be written, or for a file and version the user said `n` to (`declinedInstallPath`, `declinedInstallVersion`). Yes copies the install script the binary carries in `pkg.assets` to a private temp folder and runs it with `PINGGY_BINARY_URL` naming this file and `PINGGY_INSTALL_ONLY=1`, which ends the script after the install, with no sign-in and no PATH warning. So the files match the scripts' layout exactly. `install.ps1` runs through `iex`, so an execution policy that blocks script files does not block it. For an npm copy the binary installs first, then runs `npm uninstall -g --prefix <prefix> pinggy`, and prints the `sudo` command for a folder it cannot write. It prints the PATH warning itself, then runs the user's command in the same process. A daemon that command starts runs from the installed copy (`startDaemonFromInstalledBinary()`). The installed binary's version comes from its link target, with no process. A plain file's or the Windows binary's `--version` output is kept in `update.json` with the file's size and modified time. Ctrl+D answers nothing, and a failed install counts as `n`. A double-clicked `pinggy.exe` ends with "Press Enter to close.", and the Windows updater moves a remembered `n` to the new version when it replaces that file in place. In the scripts' own case 7, after `n`, sign-in runs the user's binary, which can ask its own question once.
499
510
 
500
- **The token command.** The dashboard shows `curl -fsSL https://pinggy.io/install.sh | DEVICE_AGENT_TOKEN=<token> sh`, and `$env:DEVICE_AGENT_TOKEN='<token>'; irm https://pinggy.io/install.ps1 | iex` on Windows. With the variable set, both scripts update an older binary without asking, then run `pinggy device connect -b` by full path, with `--manage` when `PINGGY_MANAGE` is set. The token reaches the CLI in its environment, never on a command line, where `ps` would show it. `install.sh` gives `connect` `/dev/null` as stdin, since it reads no key. `install.ps1` removes the variable in a `finally`, because `iex` runs in the user's own window. `handleDevice()` reads `DEVICE_AGENT_TOKEN` and deletes it from `process.env` before any verb runs, so no shell, daemon or other child inherits it (`takeEnvironmentToken()` in `deviceCommand.ts`). `connect` then picks the token from `--token`, else the variable, else `device.json`, and the server from `--manage`, else `dashboard.pinggy.io` for a token from the variable, else the server in `device.json` (`resolveConnectTarget()`). An empty variable counts as unset.
511
+ **The token command.** The dashboard shows `curl -fsSL https://pinggy.io/install.sh | DEVICE_AGENT_TOKEN=<token> sh`, and `$env:DEVICE_AGENT_TOKEN='<token>'; irm https://pinggy.io/install.ps1 | iex` on Windows. With the variable set, both scripts still ask every update question, then run `pinggy device connect -b` by full path, with `--manage` when `PINGGY_MANAGE` is set. The token reaches the CLI in its environment, never on a command line, where `ps` would show it. `install.sh` gives `connect` `/dev/null` as stdin, since it reads no key. `install.ps1` removes the variable in a `finally`, because `iex` runs in the user's own window. `handleDevice()` reads `DEVICE_AGENT_TOKEN` and deletes it from `process.env` before any verb runs, so no shell, daemon or other child inherits it (`takeEnvironmentToken()` in `deviceCommand.ts`). `connect` then picks the token from `--token`, else the variable, else `device.json`, and the server from `--manage`, else `dashboard.pinggy.io` for a token from the variable, else the server in `device.json` (`resolveConnectTarget()`). An empty variable counts as unset. A pinggy older than 0.6.2 ignores the variable, so a user who keeps one at the update question gets no connection.
501
512
 
502
513
  The design lives in the `pinggy_backend` repo under `docs/pinggy-devices/`: `cli.md` is the CLI contract. The wire format is `src/devices/envelope.ts` and the zod schemas under `src/devices/`. This section records what the CLI implements today.
503
514
 
@@ -522,7 +533,7 @@ The design lives in the `pinggy_backend` repo under `docs/pinggy-devices/`: `cli
522
533
 
523
534
  `login` signs in as the foreground does, then runs steps 3 to 6 in place of `runAgent`. After a new sign-in, `runAgent` gets `signInShown`, and step 6 leaves out the email and the device link, which the sign-in already printed. `device stop` calls `POST /device/stop`. `device status` prints a `State` line first (`describeDeviceState()`). It reads `GET /device` once, and `device-agent.json`: `running` plus the daemon agent's connection state, `running, with --foreground in another terminal`, `stopped` when no agent runs or no daemon runs, or `unknown` when `daemon.json` names a daemon that `GET /device` cannot read (another IPC version, an older daemon, no answer). It adds a `Background` line from the same reading. `device remove` stops a running background agent before it deletes `device.json`. A `--foreground` `connect` or `login` refuses while `GET /device` reports a run: 2 agents on 1 credential refuse each other with `already_connected`.
524
535
 
525
- **The foreground record** (`src/devices/foregroundAgent.ts`). The daemon cannot see an agent started with `--foreground`, so `runDeviceAgent()` writes `device-agent.json` (`{pid, started_at}`) beside `device.json` while it runs, and deletes it on exit if it still names its own PID. The agent checks once a second that the file exists. `device remove` (`src/devices/removeDevice.ts`) first prints the device id, the background agent's state and the foreground record's PID, and asks "Remove this device from this machine? [y/N]". Only `y` or `yes` goes on. `-f`, the existing `cliOptions.force`, skips the question. With no TTY and no `-f`, it exits 1 and changes nothing. Then it deletes the file, waits up to 10 s for the PID to exit, and deletes `device.json`. An agent still running after that fails the remove with exit 1 and leaves `device.json` in place. No signal goes to the PID: a record left by a crash can name an unrelated process. `readForegroundAgent()` deletes a record whose PID is dead or whose `started_at` is before the last boot. `connect` and `login` refuse while a live record names another process, both in the default background start and with `--foreground`. The background start writes no record: the daemon's `GET /device` already reports it. `device status` adds a `Foreground` line.
536
+ **The foreground record** (`src/devices/foregroundAgent.ts`). The daemon cannot see an agent started with `--foreground`, so `runDeviceAgent()` writes `device-agent.json` (`{pid, started_at, boot_id}`) beside `device.json` while it runs, and deletes it on exit if it still names its own PID. The agent checks once a second that the file exists. `device remove` (`src/devices/removeDevice.ts`) first prints the device id, the background agent's state and the foreground record's PID, and asks "Remove this device from this machine? [y/N]". Only `y` or `yes` goes on. `-f`, the existing `cliOptions.force`, skips the question. With no TTY and no `-f`, it exits 1 and changes nothing. Then it deletes the file, waits up to 10 s for the PID to exit, and deletes `device.json`. An agent still running after that fails the remove with exit 1 and leaves `device.json` in place. No signal goes to the PID: a record left by a crash can name an unrelated process. `readForegroundAgent()` deletes a record whose PID is dead or that comes from an earlier boot (section 3, "The boot check"). `connect` and `login` refuse while a live record names another process, both in the default background start and with `--foreground`. The background start writes no record: the daemon's `GET /device` already reports it. `device status` adds a `Foreground` line.
526
537
 
527
538
  **`DeviceAgentHost`** (`src/daemon/deviceAgentHost.ts`) holds at most 1 run, built in `runDaemonChild()` once the IPC port is known. `start(origin)` reads `device.json`: none answers `DEVICE_NOT_ENROLLED`, a run on the same token and server is left alone, and a run on another is stopped before the new one starts. Start and stop run 1 at a time through 1 promise chain. A run that ends on its own (401, revoked, deleted, replaced) keeps why in `lastError`. The host saves the run in `daemon-config.json` through `saveDeviceAgent()`, and forgets it through `forgetDeviceAgent()` on a terminal outcome. A stop keeps it saved: `device stop` ends the current run only. `close()` on shutdown records nothing, so the run stays saved.
528
539
 
@@ -560,7 +571,7 @@ The daemon's run differs from the foreground one in 3 dependencies, passed throu
560
571
  | `src/devices/backgroundAgent.ts` | The CLI's half of the background agent: verify a new target, print the manage commands, start the daemon's agent, wait for `connected`. `device stop`, the `status` line, the stop before `remove`, the foreground refusal |
561
572
  | `src/daemon/deviceAgentHost.ts` | `DeviceAgentHost`: the daemon's 1 run, behind the `/device` routes. `writeIdentityWhileOwned()` |
562
573
  | `src/devices/collectors/systemInfo.ts` | `collectSystemInfo()`: the `device/info` payload |
563
- | `src/devices/collectors/metrics.ts` | `collectMetrics()`: the `device/metrics` payload, with `cpu_percent` from 2 samples |
574
+ | `src/devices/collectors/metrics.ts` | `createMetricsCollector()`: the `device/metrics` payload for 1 connection, with `cpu_percent` since the previous report |
564
575
  | `src/devices/tunnels/tunnelList.ts` | `collectTunnelList()`: the `device/tunnels` payload, built from named fields of `GET /tunnels` and the saved configs. `startTunnelReporting()`: send at once, poll every 5 s, send only on change. `selfTunnelListSource(port)` for the daemon's own run |
565
576
  | `src/devices/tunnels/tunnelActions.ts` | `handleTunnelAction()`: `tunnel/start`, `stop` and `restart` against the daemon, with the `device` origin, answered on the request's id and op. `selfTunnelActionDependencies(port)` for the daemon's own run |
566
577
  | `src/devices/terminal/terminal_schema.ts` | Terminal ops, zod schemas for `open`, `close`, `ack`, `resize` and the `snapshot` request, `TerminalData`, `TerminalExit`, `TerminalHeld`, `TerminalContext`, `TerminalSnapshotPart`, refusal codes, grid clamp |
@@ -655,7 +666,7 @@ No daemon, or a dead pid in `daemon.json`, sends `daemon_running: false` with th
655
666
  A restart, and an update of a running tunnel, keep the tunnel in `GET /tunnels` as `starting` until the new instance replaces the old one, so the `pollNow()` after the answer finds it. A failed rebuild leaves it `exited`, with the reason in `errormsg`. A 2nd restart or update during the rebuild answers `TUNNEL_WITH_ID_OR_CONFIG_ID_ALREADY_RUNNING`, which the agent turns into `tunnel_action_failed`.
656
667
 
657
668
  Every call goes through an `IPCClient` with origin `device`. With no daemon, a stop, restart or dashboard update answers `tunnel_not_found`. The daemon's `TUNNEL_WITH_ID_OR_CONFIG_ID_NOT_FOUND` becomes `tunnel_not_found`; any other refusal, and any throw, becomes `tunnel_action_failed` with the message cleaned and cut to 256. The dashboard config holds a token: no log line carries a config or a payload, only the op, the ids and the outcome code. After each action the agent calls `pollNow()` on the tunnel reporting, so the changed list reaches the page at once instead of on the next 5 s poll; a `pollNow()` during a read in flight reads again when it ends.
658
- - `cpu_percent` samples `os.cpus()` twice, 200 ms apart, and differences the idle and total ticks. 1 reading is cumulative since boot and gives a flat, wrong number.
669
+ - `cpu_percent` differences the idle and total ticks of `os.cpus()` between 2 readings. 1 reading is cumulative since boot and gives a flat, wrong number. Each report reads the ticks once and measures from the ticks the previous report ended on, so the window is the whole stats interval. The first report of a connection samples twice, 200 ms apart, and so does a report whose saved ticks did not move forward (`ticksMovedForward()`). Windows charges CPU time in clock ticks of about 15.6 ms: 200 ms on a 2-core VM holds about 25 ticks, and a lightly loaded VM often has 0 busy ticks among them, so a 200 ms window alone reads 0.0% there. Each connection gets a new collector, so the saved ticks never span time offline.
659
670
  - `load_avg_1m`, `load_avg_5m`, `load_avg_15m` are `[0, 0, 0]` on Windows and are sent anyway, so the payload shape never varies by platform.
660
671
  - `memory_used_bytes` is `totalmem - freemem`. On macOS that counts file cache as used.
661
672
 
@@ -789,7 +800,8 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
789
800
  | Command | Behaviour | Where it is decided |
790
801
  | --- | --- | --- |
791
802
  | `device connect start my-tunnel` | Runs the agent. `start` and `my-tunnel` land in `positionals` and are ignored | `deviceCommand.ts`, `parseCliArgs` with `allowPositionals: true` |
792
- | `device start`, `device daemon stop` | `Unknown command "<verb>"`, `process.exit(1)` | The `default` arm of the verb switch |
803
+ | `device start my-tunnel` | Runs the agent, as `device connect` does. `my-tunnel` lands in `positionals` and is ignored, so no tunnel starts | `deviceCommand.ts`, `parseCliArgs` with `allowPositionals: true` |
804
+ | `device daemon stop` | `Unknown command "<verb>"`, `process.exit(1)` | The `default` arm of the verb switch |
793
805
  | `device connect -l 3000 -b --all --remote-management KEY` | Runs the agent in the daemon, the default, and ignores the other 3. Only `values.token`, `values.manage`, `values.b` and `values.foreground` are read. No tunnel and no remote management | `handleDevice` reads 4 fields off `values` |
794
806
  | `device connect -b --foreground` | `-b and --foreground contradict each other`, exit 1. Nothing runs | `handleDevice`, before the verb switch |
795
807
  | `device connect --foreground`, `device login --foreground` while the daemon runs an agent | Refused, exit 1: "This machine already runs as device <id> in the background. Stop it first: pinggy device stop" | `foregroundRefusal()` in `backgroundAgent.ts` |
@@ -926,7 +938,7 @@ No em-dashes. Short phrases. Present tense. See `CLAUDE.md` § "English Style" b
926
938
  │ next pinggy command
927
939
  ▼
928
940
  getDaemonInfo() returns null (PID dead, or ──▶ unlinks daemon.json
929
- started before the last boot)
941
+ written in an earlier boot)
930
942
  │
931
943
  ▼
932
944
  startDaemon() spawns new child
package/CLAUDE.md CHANGED
@@ -45,18 +45,18 @@ CLI code calls `TunnelClient` (`src/daemon/tunnelClient.ts`), the public facade
45
45
 
46
46
  ### Daemon discovery and lifecycle
47
47
 
48
- `getDaemonInfo()` in `src/daemon/daemonManager.ts` reads `daemon.json`, validates the PID with `process.kill(pid, 0)`, deletes the file if stale (dead PID, or `startedAt` before the last boot), and returns `null` if no live daemon is found. `startDaemon()` spawns a detached daemon child and polls `daemon.json` for up to 8s.
48
+ `getDaemonInfo()` in `src/daemon/lifecycle/daemonManager.ts` reads `daemon.json`, validates the PID with `process.kill(pid, 0)`, deletes the file if stale (dead PID, or written in an earlier boot), and returns `null` if no live daemon is found. `startedInEarlierBoot()` in `src/daemon/lifecycle/bootId.ts` decides "earlier boot" for `daemon.json`, `daemon.lock` and `device-agent.json`: it compares the OS boot ID each record saves with this boot's. A record with no boot ID, from an older version or on Windows, falls back to comparing its start time with `Date.now() - os.uptime()`. A forward clock step moves that boot time later, so never decide "earlier boot" from the clock where a boot ID exists: the CLI would delete a running daemon's `daemon.json` (ARCHITECTURE.md section 3). `startDaemon()` spawns a detached daemon child and polls `daemon.json` for up to 8s.
49
49
 
50
50
  Single daemon per user. State lives under `~/.config/pinggy/` on Linux/macOS or `%APPDATA%/pinggy/` on Windows (helper: `src/utils/configDir.ts`):
51
51
 
52
- - `daemon.json`: `{pid, port, startedAt, host, ipcVersion, cliVersion}`. `cliVersion` is the version the daemon started with, and never follows the installed binary. `ipcVersion` is `IPC_VERSION` from `src/daemon/ipc/ipcRoutes.ts`. `ensureDaemonRunning()` refuses a live daemon whose version differs and tells the user to run `pinggy daemon stop`. Bump `IPC_VERSION` on any incompatible IPC or WebSocket change. After an update the CLI is newer than the daemon, often for weeks, so a new IPC route or WebSocket frame needs a capability check or an `IPC_VERSION` bump.
53
- - `daemon.lock`: `{pid, started_at}` of the running daemon (`src/daemon/lifecycle/daemonLock.ts`). Each daemon takes it before it opens its IPC port, and a daemon that finds a live holder exits 0. systemd and launchd run `--_daemon-child` directly, and 2 CLIs can spawn at once, so the CLI's `daemon.json` check alone does not keep 1 daemon.
52
+ - `daemon.json`: `{pid, port, startedAt, host, ipcVersion, cliVersion, bootId}`. `cliVersion` is the version the daemon started with, and never follows the installed binary. `ipcVersion` is `IPC_VERSION` from `src/daemon/ipc/ipcRoutes.ts`. `ensureDaemonRunning()` refuses a live daemon whose version differs and tells the user to run `pinggy daemon stop`. Bump `IPC_VERSION` on any incompatible IPC or WebSocket change. After an update the CLI is newer than the daemon, often for weeks, so a new IPC route or WebSocket frame needs a capability check or an `IPC_VERSION` bump.
53
+ - `daemon.lock`: `{pid, started_at, boot_id}` of the running daemon (`src/daemon/lifecycle/daemonLock.ts`). Each daemon takes it before it opens its IPC port, and a daemon that finds a live holder exits 0. systemd and launchd run `--_daemon-child` directly, and 2 CLIs can spawn at once, so the CLI's `daemon.json` check alone does not keep 1 daemon.
54
54
  - `daemon-state.json`: detached tunnel configs, for crash recovery (`src/daemon/lifecycle/stateStore.ts`). Deleted on clean shutdown; replayed on next start.
55
55
  - `daemon-config.json`: settings that survive a clean shutdown (`src/daemon/lifecycle/daemonConfig.ts`): the log level, and `deviceAgent`, set while the background device agent should run. Every daemon start runs that agent. `pinggy device remove` deletes it. `pinggy device stop` keeps it, so the agent starts again with the next daemon.
56
56
  - `daemon.log`: SDK + daemon logs. CLI logs stay separate.
57
57
  - `tunnels/<name>_<configId>.json`: saved tunnel configs from `pinggy config save`.
58
58
  - `device.json`: device agent id and token from `pinggy device connect` (`src/devices/deviceIdentity.ts`). Written 0600, unlike the tunnel configs beside it.
59
- - `device-agent.json`: `{pid, started_at}` of a device agent started with `--foreground`, while it runs (`src/devices/foregroundAgent.ts`). `pinggy device remove` deletes it, and the agent stops within 1 s. No credential.
59
+ - `device-agent.json`: `{pid, started_at, boot_id}` of a device agent started with `--foreground`, while it runs (`src/devices/foregroundAgent.ts`). `pinggy device remove` deletes it, and the agent stops within 1 s. No credential.
60
60
 
61
61
  ### Foreground vs detached tunnels
62
62
 
@@ -75,11 +75,11 @@ Single daemon per user. State lives under `~/.config/pinggy/` on Linux/macOS or
75
75
 
76
76
  It owns no tunnel. It reads the daemon's `GET /tunnels` through `IPCClient` and the saved configs, to send `device/tunnels` (`src/devices/tunnels/tunnelList.ts`), and listing never starts a daemon. It stops, restarts and starts tunnels when the dashboard asks (`src/devices/tunnels/tunnelActions.ts`), through `IPCClient` with the `device` origin; only a start of a config may call `ensureDaemonRunning()`. It also applies an updated dashboard config to the tunnel running it, through the daemon's `update-config-v2`, and it rewrites a saved config's file when the dashboard edits it (`upsertConfig()`, no daemon). `pinggy device login` signs the machine in by email over plain HTTPS (`src/devices/login/`), writes `device.json`, then runs the same agent; the sign-in can also be approved from the email's link, and the poll collects it. No `TunnelManager`. It also does not reuse `src/remote_management/`, which is a tunnel controller keyed by an API key rather than the machine keyed by a device token. Frames use a versioned envelope (`src/devices/envelope.ts`) validated with zod (`src/devices/device_schema.ts`); an unknown `ch` or `op` is ignored, never fatal.
77
77
 
78
- `pinggy device connect` and `login` run the agent in the daemon, as `pinggy start -b` runs a tunnel there, so it outlives the terminal. `--foreground` runs it in the CLI process instead, until Ctrl+C. `-b` still parses and changes nothing; `-b` with `--foreground` exits 1. `--foreground` sits hidden in `cliOptions`, because `main.ts` parses the whole command line with it, strict, before it dispatches. Whoever hosts the daemon, the CLI's child or the Pinggy app, hosts the agent (`src/daemon/deviceAgentHost.ts`, `src/devices/backgroundAgent.ts`). `GET /device`, `POST /device/start` and `POST /device/stop` reach it, and `TunnelClient` exposes them for the app. No IPC route takes or returns a token or a server: the daemon reads both from `device.json`, and a new token is checked in the CLI with 1 handshake before the daemon sees it. Once the daemon starts the agent, the CLI prints the commands that manage it (`status`, `stop`, `connect`, `remove`). `pinggy device stop` stops it. A `--foreground` `connect` or `login` refuses while it runs. The loop prints nothing itself: it calls a `DeviceAgentReporter`, and the foreground's prints the same lines as before.
78
+ `pinggy device connect` and `login` run the agent in the daemon, as `pinggy start -b` runs a tunnel there, so it outlives the terminal. `pinggy device start` is the same verb as `connect`. `--foreground` runs it in the CLI process instead, until Ctrl+C. `-b` still parses and changes nothing; `-b` with `--foreground` exits 1. `--foreground` sits hidden in `cliOptions`, because `main.ts` parses the whole command line with it, strict, before it dispatches. Whoever hosts the daemon, the CLI's child or the Pinggy app, hosts the agent (`src/daemon/deviceAgentHost.ts`, `src/devices/backgroundAgent.ts`). `GET /device`, `POST /device/start` and `POST /device/stop` reach it, and `TunnelClient` exposes them for the app. No IPC route takes or returns a token or a server: the daemon reads both from `device.json`, and a new token is checked in the CLI with 1 handshake before the daemon sees it. Once the daemon starts the agent, the CLI prints the commands that manage it (`status`, `stop`, `start`, `connect`, `remove`). `pinggy device stop` stops it. A `--foreground` `connect` or `login` refuses while it runs. The loop prints nothing itself: it calls a `DeviceAgentReporter`, and the foreground's prints the same lines as before.
79
79
 
80
80
  1 invocation runs 1 subcommand: `isSubcommand()` reads `rawArgs[0]` only, so `pinggy device connect start my-tunnel` runs the agent and drops the rest, and tunnel flags on a `device` line parse and are ignored, except `-b` and `--foreground`.
81
81
 
82
- `scripts/install/install.sh` installs into `~/.pinggy/versions/<version>/` and points the link `~/.pinggy/bin/pinggy` at it. `install.sh` and `install.ps1` install or update the binary, put it on PATH, then ask "Connect this device to Pinggy? [Y/n]" and run `pinggy device login -b` unless the answer starts with `n`. `-b` is the default, and the scripts pass it so an older binary the user kept also runs the agent in its daemon. pinggy.io serves copies that `website-cli-download-links-pr.yml` writes at each release tag. The scripts read the version to install from `https://pinggy.io/cli/version.json`, which the website builds from the `data/cli_releases.yaml` that the same PR updates, and they exit 1 when it does not answer. They download the binary from the GitHub release. The updater in `src/update/` still reads GitHub's `/releases/latest`. Copies of the scripts stay in use, so that URL and its `version` field never change. Renaming a release asset, changing the `Pinggy CLI version:` line, or changing `device login`'s `--manage` or `-b` flag means changing both scripts in the same commit. `DEVICE_AGENT_TOKEN` on either script updates without asking and runs `pinggy device connect -b` instead, with the token in the environment, never on a command line. `handleDevice()` deletes the variable from `process.env` before any verb runs, so no shell or daemon the agent starts inherits it. Renaming the variable or `connect`'s `--manage` or `-b` flag also changes both scripts in the same commit. `pinggy daemon service-install` runs only from the path the scripts install to (`installerBinaryPath()` in `src/daemon/lifecycle/serviceInstaller.ts`), so changing either script's install directory changes that function in the same commit. Once the device connects, both scripts offer `pinggy daemon service-install` unless the service exists. They look for the task name, plist or unit file that `serviceInstaller.ts` writes, and the installed binary's path in it, so renaming any of them changes both scripts in the same commit.
82
+ `scripts/install/install.sh` installs into `~/.pinggy/versions/<version>/` and points the link `~/.pinggy/bin/pinggy` at it. `install.sh` and `install.ps1` install or update the binary, put it on PATH, then ask "Connect this device to Pinggy? [Y/n]" and run `pinggy device login -b` unless the answer starts with `n`. `-b` is the default, and the scripts pass it so an older binary the user kept also runs the agent in its daemon. pinggy.io serves copies that `website-cli-download-links-pr.yml` writes at each release tag. The scripts read the version to install from `https://pinggy.io/cli/version.json`, which the website builds from the `data/cli_releases.yaml` that the same PR updates, and they exit 1 when it does not answer. They download the binary from the GitHub release. The updater in `src/update/` still reads GitHub's `/releases/latest`. Copies of the scripts stay in use, so that URL and its `version` field never change. Renaming a release asset, changing the `Pinggy CLI version:` line, or changing `device login`'s `--manage` or `-b` flag means changing both scripts in the same commit. `DEVICE_AGENT_TOKEN` on either script still gets every update question, then runs `pinggy device connect -b` instead, with the token in the environment, never on a command line. `handleDevice()` deletes the variable from `process.env` before any verb runs, so no shell or daemon the agent starts inherits it. Renaming the variable or `connect`'s `--manage` or `-b` flag also changes both scripts in the same commit. Both scripts update the copy the `pinggy` command runs: an npm copy with `npm install -g --prefix`, the binary otherwise. A copy from `npm link`, pnpm, yarn or bun stops them, and a binary they did not install gets a question first (ARCHITECTURE.md, "Which copy the scripts update"). They tell an npm copy by the `lib/node_modules/pinggy/` path that npm writes. A packaged binary run from anywhere else offers to install itself by running the script it carries, with `PINGGY_BINARY_URL` and `PINGGY_INSTALL_ONLY=1` (`src/install/selfInstall.ts`). It finds the copy `pinggy` runs in `src/install/pinggyOnPath.ts`, so a change to how either script tells an npm copy changes that file in the same commit. `pinggy daemon service-install` runs only from the path the scripts install to (`installerBinaryPath()` in `src/daemon/lifecycle/serviceInstaller.ts`), so changing either script's install directory changes that function in the same commit. Once the device connects, both scripts offer `pinggy daemon service-install` unless the service exists. They look for the task name, plist or unit file that `serviceInstaller.ts` writes, and the installed binary's path in it, so renaming any of them changes both scripts in the same commit. Before the sign-in, both scripts offer to restart a daemon that runs another version (ARCHITECTURE.md section 17, "Install scripts."). They read `pid`, `host` and `cliVersion` from `daemon.json`, look for `--_daemon-child` in the daemon's command line, and `install.sh` restarts through the launchd label or the systemd unit as `serviceRestartInstruction()` does. Renaming any of those fields, the flag, the label or the unit changes both scripts in the same commit.
83
83
 
84
84
  Section 17 of `ARCHITECTURE.md` has the protocol, the retry and terminal outcome table, the `device.json` rules, and the full composition table. The design docs are in the `pinggy_backend` repo under `docs/pinggy-devices/`; read `cli.md` there before changing anything in `src/devices/`.
85
85
 
@@ -96,7 +96,7 @@ Section 17 of `ARCHITECTURE.md` has the protocol, the retry and terminal outcome
96
96
  | `pinggy attach <name\|id>` | Re-attach TUI to a running tunnel |
97
97
  | `pinggy daemon start \| stop \| status \| service-install \| service-uninstall` (alias `d`) | Daemon lifecycle and system-service installation |
98
98
  | `pinggy update [--check \| --rollback]` | Update to the latest release now, print the latest version and change nothing, or go back to the previous version. A background check starts on its own; `PINGGY_AUTO_UPDATE=false` turns it off |
99
- | `pinggy device login \| connect [--foreground] \| stop \| status \| remove [-f]` | Sign this machine in by email, or enrol it with a token, as a Pinggy device; the agent runs in the daemon, or in this terminal with `--foreground`, and `stop` stops the daemon's; show whether the agent runs, the enrolment and the background agent; show the device and its connection, ask, then stop every agent and forget the credential (`-f` skips the question) |
99
+ | `pinggy device login \| connect \| start [--foreground] \| stop \| status \| remove [-f]` | Sign this machine in by email, or enrol it with a token, as a Pinggy device (`start` is the same as `connect`); the agent runs in the daemon, or in this terminal with `--foreground`, and `stop` stops the daemon's; show whether the agent runs, the enrolment and the background agent; show the device and its connection, ask, then stop every agent and forget the credential (`-f` skips the question) |
100
100
 
101
101
  ### Auto-update
102
102
 
package/README.md CHANGED
@@ -254,6 +254,8 @@ The token is written to disk on the first successful connect, so later runs need
254
254
  pinggy device connect
255
255
  ```
256
256
 
257
+ `pinggy device start` is the same command. It takes the same flags.
258
+
257
259
  Point the agent at a different dashboard with `--manage`:
258
260
  ```bash
259
261
  pinggy device connect --token <TOKEN> --manage dashboard.pinggy.io
@@ -275,7 +277,7 @@ The first line is the device's state:
275
277
  | `running, connected` | The agent runs in the daemon and the dashboard shows the device online |
276
278
  | `running, connecting` or `running, reconnecting` | The agent runs in the daemon and is dialling the dashboard |
277
279
  | `running, with --foreground in another terminal` | Another terminal runs `pinggy device connect --foreground` |
278
- | `stopped` | No agent runs. `pinggy device connect` starts it |
280
+ | `stopped` | No agent runs. `pinggy device start` or `pinggy device connect` starts it |
279
281
  | `unknown` | A daemon runs but does not answer, for example after an update. `pinggy daemon stop` fixes it, and stops all running tunnels |
280
282
 
281
283
  Then it prints the device id, server, masked token, and enrolment time from the local file. It asks the running daemon about its agent and never starts one. It contacts no server.
@@ -313,7 +315,8 @@ It enrols, learns its device id and heartbeat interval from the dashboard, and s
313
315
  |---------|--------------|
314
316
  | `pinggy device connect -l 3000 -b --all --remote-management <KEY>` | Runs the agent in the daemon. Those flags parse and are ignored. No tunnel, no remote management. Only `--token`, `--manage`, `-b` and `--foreground` are read |
315
317
  | `pinggy device connect -b --foreground` | Error, exit 1. The 2 flags contradict each other. Nothing runs |
316
- | `pinggy device start`, `pinggy device daemon stop` | Error, exit 1. The verb after `device` is `login`, `connect`, `stop`, `status`, or `remove` |
318
+ | `pinggy device start my-tunnel` | Runs the agent, as `connect` does, and ignores `my-tunnel`. To start that tunnel, run `pinggy start my-tunnel` |
319
+ | `pinggy device daemon stop` | Error, exit 1. The verb after `device` is `login`, `connect`, `start`, `stop`, `status`, or `remove` |
317
320
  | `pinggy start device`, `pinggy stop device` | `device` reads as a tunnel name. No new config can be called `device`, so nothing matches |
318
321
  | `pinggy config save device ...` | Rejected. `device` is a reserved name |
319
322
  | `pinggy -l 3000 device` | An ordinary tunnel. `device` is not a valid domain, so it warns `Unknown extended option` and is ignored |
@@ -324,7 +327,7 @@ It enrols, learns its device id and heartbeat interval from the dashboard, and s
324
327
 
325
328
  ### Devices, tunnels, and the daemon
326
329
 
327
- - By default the daemon runs the agent. `pinggy device connect` and `login` start a daemon when none runs. `pinggy daemon stop` stops the agent with every tunnel, and so does a reboot. Every daemon start runs it again, until `pinggy device remove`. `pinggy device stop` stops it until the daemon starts again. With `pinggy daemon service-install`, the daemon starts at sign-in, so the device comes back online after a reboot. `pinggy device connect` starts it again after a stop.
330
+ - By default the daemon runs the agent. `pinggy device connect` and `login` start a daemon when none runs. `pinggy daemon stop` stops the agent with every tunnel, and so does a reboot. Every daemon start runs it again, until `pinggy device remove`. `pinggy device stop` stops it until the daemon starts again. With `pinggy daemon service-install`, the daemon starts at sign-in, so the device comes back online after a reboot. `pinggy device start` or `pinggy device connect` starts it again after a stop.
328
331
  - With `--foreground` the agent is its own process. It never starts the daemon, `pinggy daemon stop` leaves it running, and Ctrl+C on it leaves every tunnel running.
329
332
  - 1 enrolment per machine. The newest successful connect overwrites `device.json`, and a `--token` on the command line beats the stored one.
330
333
  - 1 agent per machine. `connect` and `login` refuse while another terminal runs a `--foreground` agent. `--foreground` is refused while the daemon runs an agent. Stop that one first with `pinggy device stop`.
@@ -474,7 +477,7 @@ pinggy -p 3000 --logfile ~/.pinggy/pinggy.log --loglevel INFO --v
474
477
  If you pass `--v`, `--vv`, or `--vvv` without a log level, the default is INFO. If a logfile path is provided, the log directory is created if it does not exist.
475
478
 
476
479
  ### Daemon and per-tunnel log files
477
- The daemon writes its own log file and a separate log per tunnel under the platform log directory (see [State and file locations](#state-and-file-locations)).
480
+ The daemon writes its own log file and a separate log per tunnel under the platform log directory (see [State and file locations](#state-and-file-locations)). The native tunnel library logs to `libpinggy/libpinggy.log` in the same directory: one file for all tunnels.
478
481
 
479
482
  #### Tail the daemon log
480
483
  ```bash
@@ -488,10 +491,18 @@ pinggy logs my-tunnel # last 100 lines of that tunnel's log
488
491
  pinggy logs my-tunnel -f # follow new lines (survives log rotation)
489
492
  ```
490
493
 
494
+ #### Tail the native library log
495
+ ```bash
496
+ pinggy logs libpinggy # last 100 lines of libpinggy.log
497
+ pinggy logs libpinggy -f # follow new lines
498
+ ```
499
+ The file holds the library's lines for every tunnel. A tunnel or saved config named `libpinggy` keeps the name for its own log.
500
+
491
501
  #### Print the log file path
492
502
  ```bash
493
503
  pinggy log path # daemon log path
494
504
  pinggy log path my-tunnel # path to a specific tunnel's log
505
+ pinggy log path libpinggy # path to the native library's log
495
506
  ```
496
507
 
497
508
  #### Get or set the daemon log level
@@ -2,11 +2,11 @@ import {
2
2
  TunnelAlreadyRunningError,
3
3
  TunnelManager,
4
4
  TunnelRebuildInProgressError
5
- } from "./chunk-3WMTTJHI.js";
5
+ } from "./chunk-5HBGVJSW.js";
6
6
  import "./chunk-UB26QJ4T.js";
7
7
  import "./chunk-HTIWY3O5.js";
8
- import "./chunk-LWCVB42S.js";
9
- import "./chunk-MAK5R4WQ.js";
8
+ import "./chunk-DGAH7UVX.js";
9
+ import "./chunk-WFHMERT3.js";
10
10
  export {
11
11
  TunnelAlreadyRunningError,
12
12
  TunnelManager,
@@ -3,13 +3,13 @@ import {
3
3
  } from "./chunk-XZ64ZAGO.js";
4
4
  import {
5
5
  TunnelManager
6
- } from "./chunk-3WMTTJHI.js";
6
+ } from "./chunk-5HBGVJSW.js";
7
7
  import "./chunk-UB26QJ4T.js";
8
8
  import "./chunk-HTIWY3O5.js";
9
9
  import {
10
10
  logger
11
- } from "./chunk-LWCVB42S.js";
12
- import "./chunk-MAK5R4WQ.js";
11
+ } from "./chunk-DGAH7UVX.js";
12
+ import "./chunk-WFHMERT3.js";
13
13
 
14
14
  // src/tui/blessed/TunnelTui.ts
15
15
  import blessed3 from "blessed";
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  logger
3
- } from "./chunk-LWCVB42S.js";
3
+ } from "./chunk-DGAH7UVX.js";
4
4
  import {
5
5
  ensureTunnelConfigDir,
6
6
  getTunnelConfigDir
7
- } from "./chunk-MAK5R4WQ.js";
7
+ } from "./chunk-WFHMERT3.js";
8
8
 
9
9
  // src/cli/configStore.ts
10
10
  import fs from "fs";
@@ -9,10 +9,12 @@ import {
9
9
  import {
10
10
  getLogLevel,
11
11
  logger
12
- } from "./chunk-LWCVB42S.js";
12
+ } from "./chunk-DGAH7UVX.js";
13
13
  import {
14
+ ensureLibpinggyLogDir,
15
+ getLibpinggyLogPath,
14
16
  getTunnelLogPath
15
- } from "./chunk-MAK5R4WQ.js";
17
+ } from "./chunk-WFHMERT3.js";
16
18
 
17
19
  // src/tunnel_manager/TunnelManager.ts
18
20
  import { TunnelInstance, LogLevel as SdkLogLevel } from "@pinggy/pinggy";
@@ -71,6 +73,9 @@ function detachAllTunnelLoggers() {
71
73
  }
72
74
  }
73
75
 
76
+ // src/logger/nativeLog.ts
77
+ import { Pinggy } from "@pinggy/pinggy";
78
+
74
79
  // src/logger/rotateLog.ts
75
80
  import fs2 from "fs";
76
81
  var DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
@@ -99,6 +104,34 @@ function maybeRotate(file, maxBytes = DEFAULT_MAX_BYTES, maxArchives = DEFAULT_M
99
104
  }
100
105
  }
101
106
 
107
+ // src/logger/nativeLog.ts
108
+ var pathSet = false;
109
+ var warned = false;
110
+ function sdkAddon() {
111
+ return Pinggy.addon;
112
+ }
113
+ function setNativeLogging(enabled, addon = sdkAddon()) {
114
+ if (!addon) {
115
+ if (!warned) {
116
+ warned = true;
117
+ logger.warn("libpinggy logging unavailable: the SDK does not expose its native addon");
118
+ }
119
+ return;
120
+ }
121
+ try {
122
+ if (enabled && !pathSet) {
123
+ ensureLibpinggyLogDir();
124
+ const logPath = getLibpinggyLogPath();
125
+ maybeRotate(logPath);
126
+ addon.setLogPath(logPath);
127
+ pathSet = true;
128
+ }
129
+ addon.setLogEnable(enabled);
130
+ } catch (err) {
131
+ logger.error("Failed to configure libpinggy logging", { error: err instanceof Error ? err.message : String(err) });
132
+ }
133
+ }
134
+
102
135
  // src/tunnel_manager/TunnelManager.ts
103
136
  import path2 from "path";
104
137
  import { Worker } from "worker_threads";
@@ -198,14 +231,16 @@ var TunnelManager = class _TunnelManager {
198
231
  const tunnelLogPath = getTunnelLogPath(params.tunnelid, params.origin, tunnelLogName);
199
232
  maybeRotate(tunnelLogPath);
200
233
  attachTunnelLogger(params.tunnelid, params.origin, tunnelLogName);
234
+ const loggingEnabled = isTunnelLoggingEnabled();
235
+ setNativeLogging(loggingEnabled);
201
236
  let instance;
202
237
  try {
203
238
  logger.debug("Creating tunnel instance with processed config", tunnelConfig);
204
239
  instance = await TunnelInstance.create(tunnelConfig, {
205
- enabled: true,
240
+ enabled: loggingEnabled,
206
241
  logLevel: mapToSdkLogLevel(getLogLevel()),
207
242
  logFilePath: tunnelLogPath,
208
- libpinggyLogPath: tunnelLogPath
243
+ libpinggyLogPath: null
209
244
  });
210
245
  } catch (e) {
211
246
  logger.error("Error creating tunnel instance:", e);
@@ -398,17 +433,17 @@ var TunnelManager = class _TunnelManager {
398
433
  }
399
434
  }
400
435
  /**
401
- * Re-apply the given log level to every live tunnel's worker JS logger.
402
- * Native libpinggy level is fixed at worker init and cannot be re-pathed
403
- * or re-levelled at runtime without restarting the tunnel.
436
+ * Re-apply the given log level, and the tunnel-logging switch, to every live tunnel's worker
437
+ * JS logger. libpinggy has no log level at runtime, only on or off (see nativeLog.ts).
404
438
  */
405
439
  applyLogLevelToActiveTunnels(level) {
406
440
  const sdkLevel = mapToSdkLogLevel(level);
441
+ const loggingEnabled = isTunnelLoggingEnabled();
407
442
  for (const tunnel of this.tunnelsByTunnelId.values()) {
408
443
  if (tunnel.isStopped) continue;
409
444
  if (tunnel.lastError?.isFatal) continue;
410
445
  const logPath = getTunnelLogPath(tunnel.tunnelid, tunnel.origin, tunnel.tunnelName || tunnel.tunnelConfig?.name);
411
- tunnel.instance.setDebugLogging(true, sdkLevel, logPath).catch((err) => {
446
+ tunnel.instance.setDebugLogging(loggingEnabled, sdkLevel, logPath).catch((err) => {
412
447
  logger.error("Failed to apply log level to tunnel", { tunnelId: tunnel.tunnelid, error: err?.message ?? err });
413
448
  });
414
449
  }
@@ -1637,6 +1672,7 @@ export {
1637
1672
  setTunnelLoggingEnabled,
1638
1673
  isTunnelLoggingEnabled,
1639
1674
  detachAllTunnelLoggers,
1675
+ setNativeLogging,
1640
1676
  TunnelAlreadyRunningError,
1641
1677
  TunnelRebuildInProgressError,
1642
1678
  TunnelManager
@@ -14,9 +14,9 @@ function setLogLevel(level) {
14
14
  if (_sdkLogFilePath) {
15
15
  enableLoggingByLogLevelInSdk(level, _sdkLogFilePath);
16
16
  }
17
- import("./daemonConfig-VWK4TXVS.js").then(({ writeDaemonConfig }) => writeDaemonConfig({ logLevel: level })).catch(() => {
17
+ import("./daemonConfig-R34QH73H.js").then(({ writeDaemonConfig }) => writeDaemonConfig({ logLevel: level })).catch(() => {
18
18
  });
19
- import("./TunnelManager-JRVEADS4.js").then(({ TunnelManager }) => TunnelManager.getInstance().applyLogLevelToActiveTunnels(level)).catch(() => {
19
+ import("./TunnelManager-CDQGC6ZU.js").then(({ TunnelManager }) => TunnelManager.getInstance().applyLogLevelToActiveTunnels(level)).catch(() => {
20
20
  });
21
21
  }
22
22
  var _logger = null;
@@ -2,21 +2,22 @@ import {
2
2
  InstallKind,
3
3
  getDaemonInfo,
4
4
  isProcessAlive,
5
+ moveDeclinedInstallToVersion,
5
6
  readServiceEntryText,
6
7
  readUpdateState,
7
8
  unixLayoutPaths,
8
9
  writeUpdateState
9
- } from "./chunk-3KCXR33Y.js";
10
+ } from "./chunk-OQVFQ5VG.js";
10
11
  import {
11
12
  errorMessage
12
13
  } from "./chunk-HTIWY3O5.js";
13
14
  import {
14
15
  logger
15
- } from "./chunk-LWCVB42S.js";
16
+ } from "./chunk-DGAH7UVX.js";
16
17
  import {
17
18
  ensurePinggyConfigDir,
18
19
  getUpdateLockPath
19
- } from "./chunk-MAK5R4WQ.js";
20
+ } from "./chunk-WFHMERT3.js";
20
21
 
21
22
  // src/update/latestRelease.ts
22
23
  import http from "http";
@@ -803,11 +804,14 @@ function windowsUpdateTarget(execPath, runBinary) {
803
804
  rollbackBinaryPath: () => windowsInstallPaths(execPath).livePath,
804
805
  installedVersion: (runningVersion) => runningVersion,
805
806
  prepareDownload: () => void 0,
806
- install: ({ newVersion, runningVersion }) => swapWindowsBinary(
807
- { execPath, downloadPath: windowsDownloadPath(execPath), newVersion, runningVersion },
808
- realWindowsFileOperations,
809
- runBinary
810
- ),
807
+ install: async ({ newVersion, runningVersion }) => {
808
+ await swapWindowsBinary(
809
+ { execPath, downloadPath: windowsDownloadPath(execPath), newVersion, runningVersion },
810
+ realWindowsFileOperations,
811
+ runBinary
812
+ );
813
+ moveDeclinedInstallToVersion(execPath, newVersion);
814
+ },
811
815
  rollback: async (runningVersion) => {
812
816
  const result = await rollbackWindowsBinary(
813
817
  { execPath, runningVersion, latestVersion: readUpdateState().latestVersion },
@@ -866,7 +870,9 @@ export {
866
870
  isNewerVersion,
867
871
  UpdateError,
868
872
  environmentWithoutDeviceToken,
873
+ pinggyBinaryRunOptions,
869
874
  runPinggyBinary,
875
+ readBinaryVersion,
870
876
  readBinaryIpcVersion,
871
877
  assetNameFor,
872
878
  removeQuietly,
@@ -876,6 +882,7 @@ export {
876
882
  isUpdateLockHeld,
877
883
  isUpdateLockOurs,
878
884
  releaseUpdateLock,
885
+ readLinkVersion,
879
886
  removeStaleUnixFiles,
880
887
  createUpdateTarget,
881
888
  downloadRelease