pinggy 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ARCHITECTURE.md CHANGED
@@ -16,7 +16,7 @@ The `pinggy` binary has three execution modes, dispatched in `src/main.ts`:
16
16
 
17
17
  The CLI never opens an SDK tunnel itself. Every tunnel is created inside the daemon. CLI processes talk to the daemon over HTTP + WebSocket on `127.0.0.1`.
18
18
 
19
- `pinggy device` is the exception. In the foreground it runs the device agent inside the CLI process and talks to the dashboard directly. With `-b` (slice 17) the daemon runs the same agent instead, so it outlives the terminal. It reads the daemon's tunnel list, and since slice 10 it stops, restarts and starts tunnels when the dashboard asks. See section 17.
19
+ `pinggy device` is the exception. By default the daemon runs the device agent (slice 17), so it outlives the terminal. With `--foreground` it runs inside the CLI process and talks to the dashboard directly. It reads the daemon's tunnel list, and since slice 10 it stops, restarts and starts tunnels when the dashboard asks. See section 17.
20
20
 
21
21
  ![1779362797675](image/ARCHITECTURE/1779362797675.png)
22
22
 
@@ -39,7 +39,9 @@ Logs live under `getPinggyLogDir()`:
39
39
  ```
40
40
  <configDir>/
41
41
  ├── daemon.json Daemon discovery: {pid, port, startedAt}
42
- ├── daemon-state.json Active tunnels and the background device agent, for crash recovery
42
+ ├── daemon.lock Held by the running daemon: {pid, started_at}
43
+ ├── daemon-config.json Persisted settings: log level, and the background device agent to start
44
+ ├── daemon-state.json Active tunnels, for crash recovery
43
45
  ├── device.json Device agent identity + token, mode 0600
44
46
  └── tunnels/
45
47
  └── <name>_<configId>.json Saved tunnel configs (from `pinggy config save`)
@@ -54,7 +56,7 @@ Helpers live in `src/utils/configDir.ts`: `getDaemonInfoPath`, `getDaemonLogPath
54
56
 
55
57
  ## 3. Daemon discovery and spawn
56
58
 
57
- 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, or a dead PID all collapse to the same result: return `null`, and let `ensureDaemonRunning()` spawn a fresh child.
59
+ 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.
58
60
 
59
61
  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.
60
62
 
@@ -92,7 +94,9 @@ The spawn path is deliberately one-way. The CLI fires off a detached child with
92
94
 
93
95
  Implementation: `src/daemon/daemonManager.ts`.
94
96
 
95
- The race between two CLIs invoked at the same moment is bounded but not eliminated: both may observe no `daemon.json`, both may spawn a child. Whichever child's atomic write lands last wins the file; the other daemon is reachable via its port but unreachable through discovery, and dies when its IPC server is closed or its parent CLI exits. In practice this is rare enough that we accept it; tightening it would require a file lock and adds more complexity than it removes.
97
+ 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.
98
+
99
+ 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.
96
100
 
97
101
  ## 4. Daemon child startup sequence
98
102
 
@@ -103,6 +107,7 @@ The race between two CLIs invoked at the same moment is bounded but not eliminat
103
107
  ```
104
108
  1. ensurePinggyConfigDir(), ensurePinggyLogDir()
105
109
  2. Configure winston logger → file: daemon.log, stdout: false
110
+ 2a. acquireDaemonLock(): another live daemon holds daemon.lock → exit 0
106
111
  3. Create TunnelManager singleton
107
112
  4. Create IPCServer (HTTP + WS, port not yet bound)
108
113
  5. Create SessionTracker, wire onSessionDisconnect
@@ -111,6 +116,7 @@ The race between two CLIs invoked at the same moment is bounded but not eliminat
111
116
  8. Write daemon.json atomically (write to .tmp, rename)
112
117
  9. restoreCrashedTunnels() — replay detached tunnels from daemon-state.json
113
118
  10. Start auto-start tunnels (getAutoStartConfigs())
119
+ 10a. startSavedDeviceAgent(): the background device agent saved in daemon-config.json
114
120
  11. Log "Daemon ready"
115
121
 
116
122
 
@@ -257,18 +263,19 @@ Key invariants:
257
263
  ```ts
258
264
  interface DaemonState {
259
265
  tunnels: DaemonStateTunnel[]; // {tunnelId, configId, name, origin, config, mode, startedAt}
260
- deviceAgent?: { startedAt: string; startedBy: TunnelOrigin }; // slice 17, absent when none runs
261
266
  lastUpdated: string;
262
267
  }
263
268
  ```
264
269
 
265
270
  Two lifecycle paths:
266
271
 
267
- - **Clean shutdown** (`/shutdown` or signal): `clearDaemonState()` deletes the file. Next daemon start sees nothing to recover. The device agent host closes first, so no later write brings the file back.
268
- - **Crash** (SIGKILL, OOM, panic): the file remains. Next daemon start calls `restoreCrashedTunnels()`, which restarts each `mode === "detached"` tunnel using the persisted config and stable `tunnelId` (so log files stay continuous). Foreground tunnels are not restored: there is no CLI to attach. Then, after the auto-start tunnels, `restoreCrashedDeviceAgent()` starts the device agent again when `deviceAgent` is set. Its token and server come from `device.json`. An older daemon reading the file ignores the field.
272
+ - **Clean shutdown** (`/shutdown` or signal): `clearDaemonState()` deletes the file. Next daemon start sees nothing to recover.
273
+ - **Crash** (SIGKILL, OOM, panic): the file remains. Next daemon start calls `restoreCrashedTunnels()`, which restarts each `mode === "detached"` tunnel using the persisted config and stable `tunnelId` (so log files stay continuous). Foreground tunnels are not restored: there is no CLI to attach.
269
274
 
270
275
  Auto-start tunnels are independent of crash recovery. They come from saved configs marked `autoStart: true` (`getAutoStartConfigs()`), not from the state file.
271
276
 
277
+ The background device agent is not in this file either. `deviceAgent` (`{startedAt, startedBy}`) in `daemon-config.json` survives a clean shutdown, so every daemon start runs the agent: after a crash, a `pinggy daemon stop`, or a reboot with `pinggy daemon service-install`. See section 17.
278
+
272
279
  ## 9. Tunnel lifecycle end-to-end
273
280
 
274
281
  Foreground start (`pinggy start <name>`):
@@ -346,7 +353,7 @@ src/
346
353
  │ ├── buildAndStartTunnel.ts Legacy single-tunnel path
347
354
  │ ├── buildConfig.ts CLI flags + positionals → FinalConfig
348
355
  │ ├── configStore.ts Persisted saved-config CRUD
349
- │ ├── daemonCommands.ts `pinggy daemon start|stop|status|install-service|...`
356
+ │ ├── daemonCommands.ts `pinggy daemon start|stop|status|service-install|...`
350
357
  │ ├── attachCommand.ts `pinggy attach`
351
358
  │ ├── psCommand.ts `pinggy ps`
352
359
  │ ├── stopCommand.ts `pinggy stop`
@@ -466,63 +473,70 @@ Same code path as user-typed subcommands: the daemon does not know or care that
466
473
 
467
474
  ## 16. Service installation
468
475
 
469
- `pinggy daemon install-service` writes a platform-specific service file and enables it:
476
+ `pinggy daemon service-install` writes a platform-specific service file and enables it. `pinggy daemon service-uninstall` stops the daemon and removes it. Code: `src/daemon/lifecycle/serviceInstaller.ts`.
470
477
 
471
- - Linux: systemd user unit at `~/.config/systemd/user/pinggy.service`. `Type=simple`, runs `<binary> --_daemon-child` directly (no fork). `systemctl --user enable --now`.
478
+ - Linux: systemd user unit at `~/.config/systemd/user/pinggy.service`. `Type=simple`, runs `<binary> --_daemon-child` directly (no fork). `systemctl --user enable`, then `start`.
472
479
  - macOS: launchd `LaunchAgent` at `~/Library/LaunchAgents/io.pinggy.agent.plist`. `launchctl load`.
473
- - Windows: Task Scheduler entry.
480
+ - 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.
474
481
 
475
- The installer resolves the binary via `resolveBinary()` in `src/daemon/serviceInstaller.ts`. Prefers `process.execPath` when running as a pkg binary, falls back to `which pinggy`, then to `node <script>`.
482
+ 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.
476
483
 
477
484
  A system service gives restart-on-failure and start-at-login. The plain daemon mode does not.
478
485
 
479
486
  ## 17. Device agent (`pinggy device`)
480
487
 
481
- 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. In the foreground it runs in the CLI process. With `-b` the daemon runs it (slice 17, Background mode below). Code lives in `src/devices/`, entered from `src/cli/subcommand/handlers/deviceCommand.ts`.
488
+ 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 (slice 17, Background mode below). With `--foreground` it runs in the CLI process. Code lives in `src/devices/`, entered from `src/cli/subcommand/handlers/deviceCommand.ts`.
482
489
 
483
- **Email sign-in (slice 12).** `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. Since slice 13 the email also carries an Approve link: the CLI prints the `match_code` its page shows, 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; `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.
490
+ **Email sign-in (slice 12).** `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. Since slice 13 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.
484
491
 
485
- **Install scripts (slice 14).** `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 run `pinggy device login` by full path. `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 3 things this repo owns: the release asset names, the `Pinggy CLI version: <x.y.z>` line, and the `device login --manage` flag. 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`. Lint with `shellcheck -s sh` and `PSScriptAnalyzer`. The step order is in `install-script-plan.md` under the backend's `docs/pinggy-devices/`.
492
+ **Install scripts (slice 14).** `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 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. The service actually starts pinggy after the user signs in, not at boot. 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`. The step order is in `install-script-plan.md` under the backend's `docs/pinggy-devices/`.
486
493
 
487
- **The token command (slice 16).** 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` 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.
494
+ **The token command (slice 16).** 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.
488
495
 
489
496
  The design lives in the `pinggy_backend` repo under `docs/pinggy-devices/`: `cli.md` is the CLI contract, `api-websocket.md` the wire format, `slices/` the delivery order. This section records what the CLI implements today.
490
497
 
491
- **In the foreground it runs in the CLI process.** The agent owns no tunnel. Since slice 09 it reads the daemon: `getDaemonInfo()` for `daemon.json`, then `IPCClient.listTunnels()` for `GET /tunnels`, every 5 s, and `listSavedConfigs()` for the saved configs. Listing never starts a daemon, and it refuses a daemon whose `ipcVersion` differs, as `ensureDaemonRunning()` does. Since slice 10 it also acts on the daemon when the dashboard asks (see Device tunnel actions below); only a start of a config may call `ensureDaemonRunning()`. `TunnelManager` and `TunnelClient` stay off this path. Killing the agent leaves running tunnels alone.
498
+ **With `--foreground` it runs in the CLI process.** The agent owns no tunnel. Since slice 09 it reads the daemon: `getDaemonInfo()` for `daemon.json`, then `IPCClient.listTunnels()` for `GET /tunnels`, every 5 s, and `listSavedConfigs()` for the saved configs. Listing never starts a daemon, and it refuses a daemon whose `ipcVersion` differs, as `ensureDaemonRunning()` does. Since slice 10 it also acts on the daemon when the dashboard asks (see Device tunnel actions below); only a start of a config may call `ensureDaemonRunning()`. `TunnelManager` and `TunnelClient` stay off this path. Killing the agent leaves running tunnels alone.
492
499
 
493
500
  **It does not reuse `src/remote_management/`.** Remote management is a dashboard-driven tunnel controller keyed by an API key. A device is the machine itself, keyed by its own token, and the 2 sockets speak different protocols. The duplication is deliberate: the backend `constraints.md` lists the remote-management files as do-not-touch, and that loop keeps its fixed 5000 ms retry with no cap and no watchdog.
494
501
 
495
502
  ### Background mode (slice 17)
496
503
 
497
- `pinggy device connect -b` and `pinggy device login -b` hand the agent to the daemon, as `pinggy start -b` hands it a tunnel, and exit once the device connects. `-b` is the existing `cliOptions.b`. Whoever hosts the daemon hosts the agent: the CLI's detached child, `pinggy daemon install-service`, or the Pinggy app, whose in-process daemon runs the same `runDaemonChild()`. The app reaches it through `TunnelClient.getDeviceAgentStatus()`, `startDeviceAgent()` and `stopDeviceAgent()`.
504
+ `pinggy device connect` and `pinggy device login` hand the agent to the daemon, as `pinggy start -b` hands it a tunnel, and exit once the device connects. This is the default. `--foreground` (`cliOptions.foreground`, hidden) keeps the agent in the CLI process. `-b` (`cliOptions.b`) still parses and changes nothing. `-b` with `--foreground` exits 1 before anything runs. Whoever hosts the daemon hosts the agent: the CLI's detached child, `pinggy daemon service-install`, or the Pinggy app, whose in-process daemon runs the same `runDaemonChild()`. The app reaches it through `TunnelClient.getDeviceAgentStatus()`, `startDeviceAgent()` and `stopDeviceAgent()`.
498
505
 
499
506
  **The token never goes over IPC.** `device.json` is the hand-off: the CLI writes it, the daemon reads it. The 3 `/device` routes (section 5) read no request field. A target that differs from `device.json` (another token, or another server) is checked first in the CLI with `startDeviceAgent(..., { verifyOnly: true })`: 1 attempt, ended at `welcome`, which writes `device.json` as the foreground agent does. A token the dashboard refuses never reaches the file or the daemon.
500
507
 
501
- `connect -b`, in `src/devices/backgroundAgent.ts`:
508
+ `connect`, in `src/devices/backgroundAgent.ts`:
502
509
 
503
510
  1. `takeEnvironmentToken()` and `resolveConnectTarget()`, as in the foreground.
504
511
  2. A target that differs from `device.json`: the verify above. A refusal prints it and exits 1.
505
512
  3. `ensureDaemonRunning()`.
506
513
  4. `POST /device/start`. An older daemon answers 404, and the CLI says to stop it, or to update the Pinggy app when the app hosts it (`olderDaemonMessage()`).
507
- 5. `GET /device` every 500 ms for up to 15 s. `connected` prints the device, the email, the device link and the log path. `stopped` prints `lastError` and exits 1. Still connecting leaves it to the daemon and exits 0.
514
+ 5. Print the commands that manage the device once the CLI exits: `pinggy device status`, `stop`, `connect` and `remove` (`MANAGE_COMMANDS`). Then print that the agent starts. A refusal in steps 3 or 4 prints only the refusal.
515
+ 6. `GET /device` every 500 ms for up to 15 s. `connected` prints the device, the email, the device link and the log path. `stopped` prints `lastError` and exits 1. Still connecting leaves it to the daemon and exits 0.
516
+
517
+ `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` adds a `Background` line from `GET /device`. `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`.
508
518
 
509
- `login -b` signs in as the foreground does, then runs steps 3 to 5 in place of `runAgent`. `device stop` calls `POST /device/stop`. `device status` adds a `Background` line from `GET /device`. `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`.
519
+ **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.
510
520
 
511
- **`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 records the run in `daemon-state.json` through `trackDeviceAgentStart()` and `trackDeviceAgentStop()`; `close()` on shutdown records nothing.
521
+ **`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.
522
+
523
+ **Start with the daemon.** After the auto-start tunnels, `startSavedDeviceAgent()` in `runDaemonChild()` starts the saved agent with its `startedBy`. This runs on every daemon start, the way auto-start tunnels do, so the Pinggy app's in-process daemon starts it too. It skips the start while `device-agent.json` names a live foreground agent: 2 agents on 1 credential refuse each other with `already_connected`. The record stays for the next start. With no `device.json`, the start fails with `DEVICE_NOT_ENROLLED` and the record is deleted. Only `pinggy device remove` deletes the record from the CLI, before it deletes `device.json`. `pinggy device status` prints `Autostart on` while the record exists. A `--foreground` agent never writes it.
512
524
 
513
525
  The daemon's run differs from the foreground one in 3 dependencies, passed through `DeviceAgentOptions`:
514
526
 
515
527
  - **Reporter.** The loop prints nothing itself. It calls a `DeviceAgentReporter` (`src/devices/deviceAgentReporter.ts`). The foreground's `printingReporter` prints the same lines as before. The daemon's logs to `daemon.log` and keeps the latest state for `GET /device`, without the email.
516
528
  - **Its own port.** `selfTunnelListSource(port)` and `selfTunnelActionDependencies(port)` reach the daemon that runs the agent, never `daemon.json` and never `ensureDaemonRunning()`. From inside a daemon, that call would spawn a 2nd daemon, or host a 2nd one in the app's process, whenever `daemon.json` goes missing.
517
- - **`writeIdentityWhileOwned()`.** The daemon's run rewrites `device.json` on `welcome` only while the file holds its own token. `connect -b` with a new token writes the new credential, then asks the daemon to switch; an old run that reconnects in between must not write the old one back.
529
+ - **`writeIdentityWhileOwned()`.** The daemon's run rewrites `device.json` on `welcome` only while the file holds its own token. A background `connect` with a new token writes the new credential, then asks the daemon to switch; an old run that reconnects in between must not write the old one back.
518
530
 
519
531
  | Event | The background agent |
520
532
  | --- | --- |
521
- | The CLI that ran `connect -b` exits, or its terminal closes | Keeps running. The daemon is detached |
522
- | Daemon crash | Restored at the next daemon start (section 8) |
523
- | `pinggy daemon stop`, or the Pinggy app quits | Stops. The socket closes with 1000 and every shell ends |
524
- | Reboot | Stops, as a `-b` tunnel does |
525
- | A terminal outcome | Stops, with `lastError`, and is removed from `daemon-state.json` |
533
+ | The CLI that ran `connect` exits, or its terminal closes | Keeps running. The daemon is detached |
534
+ | Daemon crash | Starts again with the next daemon |
535
+ | `pinggy daemon stop`, or the Pinggy app quits | Stops. The socket closes with 1000 and every shell ends. Starts again with the next daemon |
536
+ | Reboot | Starts again when the daemon starts, at sign-in with `pinggy daemon service-install` |
537
+ | `pinggy device stop` | Stops. Starts again with the next daemon |
538
+ | `pinggy device remove` | Stops, and the daemon never starts it again |
539
+ | A terminal outcome | Stops, with `lastError`, and stays stopped until the next `connect` or `login` |
526
540
 
527
541
  **Inside the Pinggy app** `node-pty` resolves inside `app.asar`, where `spawn-helper` is not on real disk, and a spawn without its helper kills the process. `resolveNodePtyRoot()` copies the package out of an `.asar` archive the way it does out of a `pkg` snapshot, and `loadNodePty()` offers a terminal only when `hasExecutableSpawnHelper()` holds.
528
542
 
@@ -537,7 +551,7 @@ The daemon's run differs from the foreground one in 3 dependencies, passed throu
537
551
  | `src/devices/deviceIdentity.ts` | `device.json` read, write, clear, and token masking |
538
552
  | `src/devices/deviceAgent.ts` | URL build, connect loop, frame dispatch, heartbeat and metrics timers. `startDeviceAgent()` returns a run with `stop()` and `done`; `runDeviceAgent()` is the foreground entry with the SIGINT handler |
539
553
  | `src/devices/deviceAgentReporter.ts` | `DeviceAgentReporter`, the run's events. `printingReporter`: the foreground's terminal output. `printConnected()` |
540
- | `src/devices/backgroundAgent.ts` | The CLI's half of `-b`: verify a new target, start the daemon's agent, wait for `connected`. `device stop`, the `status` line, the stop before `remove`, the foreground refusal |
554
+ | `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 |
541
555
  | `src/daemon/deviceAgentHost.ts` | `DeviceAgentHost`: the daemon's 1 run, behind the `/device` routes. `writeIdentityWhileOwned()` |
542
556
  | `src/devices/collectors/systemInfo.ts` | `collectSystemInfo()`: the `device/info` payload |
543
557
  | `src/devices/collectors/metrics.ts` | `collectMetrics()`: the `device/metrics` payload, with `cpu_percent` from 2 samples |
@@ -553,7 +567,7 @@ The daemon's run differs from the foreground one in 3 dependencies, passed throu
553
567
  | `src/devices/terminal/ptySession.ts` | Lazy `node-pty` load, `isTerminalSupported()` (false unless `spawn-helper` can be exec'd), `spawnPty()`, the `spawn-helper` execute-bit repair, `signalForeground()` to the tty's foreground process group |
554
568
  | `src/devices/terminal/nodePtyRuntime.ts` | `resolveNodePtyRoot()`: where `node-pty` loads from. Unpacks it onto real disk inside a `pkg` binary or an Electron `.asar` archive. `hasExecutableSpawnHelper()` |
555
569
  | `src/devices/terminal/shellAllowlist.ts` | `resolveShell()`: exact match against `/etc/shells`, or `powershell.exe` and `cmd.exe` on Windows |
556
- | `src/cli/subcommand/handlers/deviceCommand.ts` | The `login`, `connect`, `stop`, `status`, `remove` verbs, and `-b`. `refuseDevicesSpelling()` for the old spelling |
570
+ | `src/cli/subcommand/handlers/deviceCommand.ts` | The `login`, `connect`, `stop`, `status`, `remove` verbs, and `--foreground`. `refuseDevicesSpelling()` for the old spelling |
557
571
  | `src/utils/helpMessages.ts` | `printDeviceHelp()` |
558
572
 
559
573
  `Subcommand.Device` in `src/cli/configStore.ts` puts `device` in `SUBCOMMANDS` and `RESERVED_NAMES`, so no new saved tunnel config can be named `device`. `Subcommand.Devices` keeps the old spelling in both. `pinggy devices` prints `"pinggy devices" is now "pinggy device". Run: pinggy device <verb>` and exits 1. It names the verb only when it is 1 of the 5, else `--help`, and never repeats the other arguments, which can hold a token. Without it, `devices` would fall to legacy tunnel mode, where `--token` is the tunnel token, and a device token would reach the tunnel server.
@@ -641,7 +655,7 @@ Every call goes through an `IPCClient` with origin `device`. With no daemon, a s
641
655
 
642
656
  The dashboard answers an unreadable payload with `invalid_payload` on the `device` channel. The agent ignores every non-`system` frame, so that answer is logged at debug and changes nothing.
643
657
 
644
- ### Terminal (slices T1, T1b, T2 and T3: open, close, shells that outlive the socket, output, input)
658
+ ### Terminal (slices T1, T1b, T2, T3, T6 and T8: open, close, shells that outlive the socket, output, input, screen)
645
659
 
646
660
  `ch: "terminal"` frames go to the run's `TerminalHandler`, never to `handleFrame()`. Output flows up as `data`, and keystrokes flow down as `data`.
647
661
 
@@ -670,26 +684,36 @@ The dashboard answers an unreadable payload with `invalid_payload` on the `devic
670
684
  ├───────────────────────────────────────────────────────▶│ a tab attached and asks for its screen (T6)
671
685
  │ terminal/snapshot event {part, last, after_seq, data} │
672
686
  │◀───────────────────────────────────────────────────────┤ the screen, to that tab only
687
+ │ terminal/resync event {resync_id, part, after_seq, data}
688
+ │◀───────────────────────────────────────────────────────┤ the latest screen after a skip, to every tab (T8)
689
+ │ terminal/activity event {terminal_id, skipped_bytes} │
690
+ │◀───────────────────────────────────────────────────────┤ still busy while skipping, not forwarded (T8)
673
691
  ```
674
692
 
675
693
  - **`terminal` is advertised only when `node-pty` loads.** `buildCapabilities(isTerminalSupported())`. The capability is what un-greys the Terminal button, so an agent must never advertise a shell it cannot spawn.
676
694
  - **The dashboard validates neither shell nor cwd.** `resolveShell()` is the only check. A requested shell must equal an `/etc/shells` line exactly and exist; no request picks `$SHELL` when it is allowed. A missing cwd falls back to home rather than refusing.
677
695
  - **A refusal answers on `opened`** with `{terminal_id, error: {code, message}}`: `invalid_payload`, `terminal_disabled`, `terminal_limit_reached`, `shell_not_allowed`, or `spawn_failed`.
678
- - **A shell outlives the socket that opened it** (slice T1b). `runDeviceAgent()` builds 1 `TerminalHandler` for the whole run. When `connectOnce()` settles, `suspend()` pauses every pty (stops reading its master, so the shell blocks once the kernel buffer fills) and kills none. The next `hello` lists them in `terminals`. The dashboard answers `close` with `device_gone` for any it forgot, possibly before `welcome`, and `welcome` calls `resumeAll()`.
696
+ - **A shell outlives the socket that opened it** (slice T1b). `runDeviceAgent()` builds 1 `TerminalHandler` for the whole run. When `connectOnce()` settles, `suspend()` pauses every pty (stops reading its master, so the shell blocks once the kernel buffer fills) and kills none. In skip mode (T8, below) it pauses none. The next `hello` lists them in `terminals`. The dashboard answers `close` with `device_gone` for any it forgot, possibly before `welcome`, and `welcome` calls `resumeAll()`.
679
697
  - **Only the agent stopping kills shells.** When the loop ends (interrupted, revoked, refused), `closeAll()` kills them. Killing the agent process reaps them too, through `SIGHUP` when the pty master closes.
680
698
  - **A shell that exits while the socket is down sends nothing.** Its `close` has no socket to go to, and the next `hello` simply omits it. The dashboard records that as `device_gone`.
681
699
  - **Output is read as raw bytes and sent as base64.** `spawnPty()` passes `encoding: null`, so a read that ends mid-character is not decoded into a replacement character. `FrameSplitter` sends a bundle at the raw cap from `rawBundleBytes(max_frame_bytes)` or after `BUNDLE_MILLIS`, whichever comes first. A frame above `max_frame_bytes` would close the socket, and every other terminal on it.
682
- - **A full window stops the reads, not the sends.** `FlowWindow` counts raw bytes sent minus the browser's cumulative `ack_bytes`, clamped to what was sent. When it reaches the window, the handler pauses the pty and the shell blocks in the kernel. The next `ack` that reopens it resumes reads. Nothing is buffered on the agent.
700
+ - **Under T2's brake, a full window stops the reads, not the sends.** `FlowWindow` counts raw bytes sent minus the browser's cumulative `ack_bytes`, clamped to what was sent. When it reaches the window, the handler pauses the pty and the shell blocks in the kernel. The next `ack` that reopens it resumes reads. Nothing is buffered on the agent.
683
701
  - **Ctrl-C is input, not a signal.** It arrives as `data` byte `0x03`, and the pty's line discipline turns it into SIGINT for the foreground process group.
684
702
  - **`signal` goes to the foreground process group**, never the shell's pid. `signalForeground()` reads the tty's `tpgid` with `ps` and calls `process.kill(-tpgid)`, falling back to the shell's own group. `node-pty`'s `kill(signal)` signals the pid only, and bash ignores SIGINT while `sleep` holds the terminal. The allowlist is `TERMINAL_SIGNALS`, enforced by the zod schema, so `KILL` and anything else never reach `kill`. Ignored on Windows.
685
703
  - **`resize` touches the pty only on an actual change.** Every call is a `TIOCSWINSZ` and a SIGWINCH, and a full-screen program redraws on each.
686
- - **2 things pause a pty, and neither lifts the other's.** A suspended handler (socket down) and a full window. `resumeAll()` skips a shell whose window is still full, and an `ack` does not resume a shell while the handler is suspended.
704
+ - **Under T2's brake, 2 things pause a pty, and neither lifts the other's.** A suspended handler (socket down) and a full window. `resumeAll()` skips a shell whose window is still full, and an `ack` does not resume a shell while the handler is suspended.
687
705
  - **The window has no default.** `welcome.terminal_window_bytes` is the only place the number lives. Without it the handler answers every `open` with `terminal_disabled`.
688
706
  - **`seq` counts per terminal from 1**, on every `data` frame, for the life of the shell rather than the socket. The dashboard closes a terminal with `sequence_gap` on a hole.
689
- - **A bundle cut while the socket is down is held**, not sent into no socket. It takes no `seq` and does not count against the window until `resumeAll()` sends it first. It is at most what was already read when `suspend()` paused the pty.
707
+ - **Under T2's brake, a bundle cut while the socket is down is held**, not sent into no socket. It takes no `seq` and does not count against the window until `resumeAll()` sends it first. It is at most what was already read when `suspend()` paused the pty.
690
708
  - **The window still assumes 1 viewer.** T1b's multi-viewer rules for T2 (slowest viewer's ack, 10 s `too_slow` detach) are not built. Its replay for a late attach is T6's screen, below, not a buffer of bytes.
691
709
  - **Every shell keeps its screen** (slice T6). `ScreenMirror` is a headless xterm (`@xterm/headless`, 1000 lines of scrollback) fed each bundle in `sendData`, in the same tick as its `seq`, never when the pty is read: a bundle still being cut would otherwise be in the screen and drawn twice. `snapshot` notes `after_seq` and `after_bytes`, then serialises inside the callback of an empty write queued on the mirror, which xterm runs before it parses anything fed later. The text goes out in parts of the raw bundle size. Parts take no `seq` and never count against the window. Over 1 MB it is serialised again with 200 lines, then with the screen alone, and past that it is not sent. The serialize addon needs `allowProposedApi`.
692
710
  - **`terminal_snapshot` is advertised only beside `terminal`**, and only when both xterm packages load. The mirror is memory only, disposed with its shell, never logged and never written to disk.
711
+ - **Output never waits** (slice T8). With `welcome.terminal_resync` and a mirror, `sendOrSkip` replaces T2's brake. A bundle cut while the window is closed, the socket is down, or the stream is already skipping is skipped: fed to the mirror, given no `seq`, not sent, not counted against the window. Once every sent byte is acked, and no sooner than `RESYNC_MIN_INTERVAL_MILLIS` (1 s) after the last, the latest screen goes to every tab as `resync` parts, then live `data`. `after_seq` and `after_bytes` are read before the mirror is asked, as for a snapshot. The screen is serialised under the window size, and a screen alone over it still goes, up to 1 MB. The dashboard treats each part as a `seq` barrier.
712
+ - **After `welcome`, a resync at once** for every stream that skipped or had bytes in flight, since frames in flight died with the old socket. A shell that exits while skipping sends 1 last resync, then `exit` and `close`. A T6 snapshot never ends skip mode: it reaches 1 tab.
713
+ - **A bundle cut while a resync is serialised waits** in `resyncHeldBundles`, unfed, and goes out after the parts. Past the window size the held bundles and every later one are skipped, and another resync follows.
714
+ - **The only pause in skip mode is the mirror's.** `ScreenMirror.feed` counts bytes fed and not yet parsed through xterm's write callback. The pty pauses above `MIRROR_HIGH_WATER_BYTES` (1 MB) and resumes under `MIRROR_LOW_WATER_BYTES` (256 KB). That is local CPU, never the network: a loud shell runs at the parse rate, about 22.5 MB/s measured on 2026-11-03.
715
+ - **A skipping shell sends `activity`** with its `skipped_bytes`, at most every `ACTIVITY_REPORT_MILLIS` (60 s), so the dashboard's sweep does not close it as idle. The agent's own idle timer counts every pty read already.
716
+ - **`terminal_resync` is advertised beside `terminal_snapshot`**, on the same condition. A `welcome` without the flag ends skip mode on every shell with no resync, and the shells go back to T2's brake.
693
717
  - **No log line carries a payload.** Ids, pids, and codes only, and an error's class name rather than its message. Input is what a person typed, so it is never logged at any level.
694
718
  - `welcome.terminal_enabled` and `welcome.max_terminals_per_device` are optional, so an older dashboard leaves the defaults (enabled, 3).
695
719
 
@@ -697,7 +721,7 @@ The dashboard answers an unreadable payload with `invalid_payload` on the `devic
697
721
 
698
722
  **A packaged binary loads `node-pty` from real disk, not from the snapshot.** `node-pty` does not exec the shell directly. It execs `spawn-helper`, at a path it derives from wherever its own module sits. Inside a `pkg` binary that path is `/snapshot/...`, which only exists in the `fs` module pkg patches, so the kernel cannot exec it and `posix_spawn` fails with `ENOENT`. The throw is fatal inside the addon, so no caller gets to answer for it.
699
723
 
700
- `resolveNodePtyRoot()` copies the package out of the snapshot on first use and returns that path, so every path `node-pty` derives afterwards is a real one. It copies `package.json`, `lib/`, and this platform's native directory only: 41 files and 404 KB, against 62 MB for the whole package, most of which is other architectures' prebuilds. The copy lands in `~/.config/pinggy/runtime/node-pty-<version>-<platform>-<arch>`, staged under a sibling name and renamed into place, so 2 agents starting at once cannot load a half-written copy. An unpackaged run resolves through `require` as normal and copies nothing.
724
+ `resolveNodePtyRoot()` copies the package out of the snapshot on first use and returns that path, so every path `node-pty` derives afterwards is a real one. It copies `package.json`, `lib/`, and this platform's native directory only: 41 files and 404 KB. The snapshot carries the native directories of all 4 prebuilt platforms, about 5 MB. The `pkg.ignore` list in `package.json` keeps the package's `.pdb` debug symbols and C++ source, 56 MB, out of the binary. A glob added there must not remove anything else from the 3 copied paths. The copy lands in `~/.config/pinggy/runtime/node-pty-<version>-<platform>-<arch>`, staged under a sibling name and renamed into place, so 2 agents starting at once cannot load a half-written copy. An unpackaged run resolves through `require` as normal and copies nothing.
701
725
 
702
726
  Not `pkg`'s own cache. `pkg` already unpacks the addon to `~/.cache/pkg/<hash>/` at mode 644, but the hash is undocumented and `node-pty` never looks there.
703
727
 
@@ -709,7 +733,7 @@ Measured on `macos-arm64` and `macos-x64`. `linux-x64`, `linux-arm64` and `win-x
709
733
 
710
734
  | Signal | Outcome |
711
735
  | --- | --- |
712
- | HTTP 401 on the upgrade | terminal |
736
+ | HTTP 401 on the upgrade | terminal. For the token in `device.json`, the message says the device was deleted or its token rotated, and to run `pinggy device login`. For a token from `--token` or `DEVICE_AGENT_TOKEN`, it says to check the token, since `device.json` is untouched |
713
737
  | Close code 4001 | terminal |
714
738
  | `welcome` with an error other than `already_connected` | terminal |
715
739
  | `system/disconnect` with any reason but `shutdown` | terminal |
@@ -717,6 +741,8 @@ Measured on `macos-arm64` and `macos-x64`. `linux-x64`, `linux-arm64` and `win-x
717
741
  | `system/disconnect` with `shutdown` | retry. The node is draining, the credential is fine |
718
742
  | Any other close code, socket error, or unreadable `welcome` | retry |
719
743
 
744
+ The socket error that `ws` raises for its own close of an attempt that already settled, such as the close after a 401 or a 502, is logged and not reported as a warning.
745
+
720
746
  Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap, drawn as `random(0, ceiling)`, reset to 1 s only after a connection holds 60 s. The schedule lives in `src/devices/reconnect.ts` as pure functions over an injected clock, so it is testable without a socket; `deviceAgent.ts` owns the timers.
721
747
 
722
748
  2 timers catch a socket that died without saying so, since a dropped link sends nothing and leaves `readyState` at `OPEN`. A handshake timer gives the dashboard 30 s to answer `hello` with `welcome`. After `welcome` a pong watchdog pings every heartbeat interval and drops the socket after 2 unanswered. Both call `terminate()` rather than `close()`, because a polite close waits for a close frame from the peer that has already stopped answering. `ws` auto-answers inbound pings on its own, so the agent sends its own and does not handle theirs.
@@ -730,11 +756,11 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
730
756
  "server": "dashboard.pinggy.io", "enrolled_at": "2026-09-05T09:22:10Z"}
731
757
  ```
732
758
 
733
- `getDeviceConfigPath()` puts it beside `tunnels/`, not inside it: a device is not a tunnel config. `device_agent_id` is minted by the dashboard and read from `welcome`; the agent never invents one. A token from `--token` or `DEVICE_AGENT_TOKEN` always beats the stored value. When it differs from the stored token, `identityForRun()` starts a new identity, with no old `device_agent_id` and no old `enrolled_at`, and the run reports "This machine was device <old id>. Connecting it with the token from the command." The old device stays in the dashboard, offline.
759
+ `getDeviceConfigPath()` puts it beside `tunnels/`, not inside it: a device is not a tunnel config. `device_agent_id` is minted by the dashboard and read from `welcome`; the agent never invents one. A token from `--token` or `DEVICE_AGENT_TOKEN` always beats the stored value. When it differs from the stored token, `identityForRun()` starts a new identity, with no old `device_agent_id` and no old `enrolled_at`. At the 1st `welcome`, and not before, the run reports "This machine was device <old id>. That device stays in the dashboard, offline." A token the dashboard refuses replaces nothing, so it reports nothing.
734
760
 
735
761
  **Written 0600, then chmodded again on every rewrite**, because `writeFileSync` applies `mode` only when it creates the file. This diverges from `configStore.ts`, which writes tunnel tokens at 0644 under a normal umask. Do not copy that pattern into anything new.
736
762
 
737
- `pinggy device remove` deletes this file and nothing else, after it stops a background agent. Revoking the device server-side is a dashboard action, because a machine that has lost its credential cannot authenticate the delete.
763
+ `pinggy device remove` deletes this file and `device-agent.json`, after it stops a background agent and a `--foreground` agent in another terminal. Revoking the device server-side is a dashboard action, because a machine that has lost its credential cannot authenticate the delete.
738
764
 
739
765
  ### Composition with other subcommands
740
766
 
@@ -744,8 +770,10 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
744
770
  | --- | --- | --- |
745
771
  | `device connect start my-tunnel` | Runs the agent. `start` and `my-tunnel` land in `positionals` and are ignored | `deviceCommand.ts`, `parseCliArgs` with `allowPositionals: true` |
746
772
  | `device start`, `device daemon stop` | `Unknown command "<verb>"`, `process.exit(1)` | The `default` arm of the verb switch |
747
- | `device connect -l 3000 -b --all --remote-management KEY` | Runs the agent in the daemon, for `-b`, and ignores the other 3. Only `values.token`, `values.manage` and `values.b` are read. No tunnel and no remote management | `handleDevice` reads 3 fields off `values` |
748
- | `device connect`, `device login` 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` |
773
+ | `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` |
774
+ | `device connect -b --foreground` | `-b and --foreground contradict each other`, exit 1. Nothing runs | `handleDevice`, before the verb switch |
775
+ | `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` |
776
+ | `device connect`, `device login`, with or without `--foreground`, while another terminal runs a `--foreground` agent | Refused, exit 1: "This machine already runs as a device in another terminal (PID <pid>). Press Ctrl+C in that terminal first." | `foregroundAgentRefusal()` in `foregroundAgent.ts` |
749
777
  | `device stop` with no background agent | "No device agent is running in the background.", exit 0. Never starts a daemon | `stopAgentInBackground()` |
750
778
  | `device connect --typo` | `Fatal Error: Unknown option '--typo'`, exit 1, before dispatch | `main()` parses the full argv with `parseArgs` in strict mode, then calls `isSubcommand` |
751
779
  | `device connect --help` | Ignores `--help` and connects. Only `device` and `device --help` reach `printDeviceHelp()` | The verb switch tests `--help` in its `default` arm only |
@@ -761,16 +789,16 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
761
789
 
762
790
  ### The agent and the daemon
763
791
 
764
- In the foreground the agent shares no state with the daemon or with tunnels, which is what makes the composition table boring.
792
+ With `--foreground` the agent shares no state with the daemon or with tunnels, which is what makes the composition table boring.
765
793
 
766
- - `pinggy device connect` never calls `ensureDaemon()`, so it neither finds nor spawns one. A device agent on a machine with no daemon writes no `daemon.json`.
794
+ - `pinggy device connect --foreground` never calls `ensureDaemon()`, so it neither finds nor spawns one. A device agent on a machine with no daemon writes no `daemon.json`.
767
795
  - `pinggy daemon stop` stops tunnels and the daemon. A foreground agent is a separate process and keeps going.
768
796
  - Ctrl+C on the agent touches no tunnel. There is no `SessionTracker` entry, no grace timer, and no origin tag.
769
797
  - The agent logs through `CLIPrinter` and the CLI logger, not the daemon log. Nothing about it reaches `daemon.log` or the per-tunnel logs.
770
798
 
771
- With `-b` the daemon owns the agent: `ensureDaemonRunning()` may start a daemon, `pinggy daemon stop` stops the agent too and says so, the agent logs to `daemon.log`, and `daemon-state.json` records it. It still has no `SessionTracker` entry and no origin tag of its own.
799
+ Without `--foreground` the daemon owns the agent: `ensureDaemonRunning()` may start a daemon, `pinggy daemon stop` stops the agent too and says so, the agent logs to `daemon.log`, and `daemon-config.json` saves it, so the next daemon start runs it again. It still has no `SessionTracker` entry and no origin tag of its own.
772
800
 
773
- 1 identity per config dir, last write wins: a run keeps what `device.json` holds while the token matches, sets the server, and rewrites the file on every `welcome`. So `device remove` during a live foreground session deletes a file the agent restores on its next reconnect, and 2 agents sharing 1 credential lose the race by design: the dashboard refuses the second with `already_connected`, and it retries on the backoff until the first socket drops. The daemon's run rewrites the file only while it holds its own token (`writeIdentityWhileOwned()`).
801
+ 1 identity per config dir, last write wins: a run keeps what `device.json` holds while the token matches, sets the server, and rewrites the file on every `welcome`. `device remove` stops a foreground agent through its record first, so the file stays deleted. 2 agents sharing 1 credential lose the race by design: the dashboard refuses the second with `already_connected`, and it retries on the backoff until the first socket drops. The daemon's run rewrites the file only while it holds its own token (`writeIdentityWhileOwned()`).
774
802
 
775
803
  ### Not built yet
776
804
 
@@ -824,7 +852,7 @@ No em-dashes. Short phrases. Present tense. See `CLAUDE.md` § "English Style" b
824
852
  - `daemon.json` writes are atomic (write tmp, rename). Direct partial reads should not happen, but `getDaemonInfo()` still tolerates malformed JSON by returning `null` and triggering a respawn.
825
853
  - The IPC server only listens on `127.0.0.1`. Do not change to `0.0.0.0` without adding authentication. The current design assumes loopback isolation.
826
854
  - Every tunnel reconnects without limit. `_createTunnelWithProcessedConfig()` in `TunnelManager.ts` sets `maxReconnectAttempts` to 0 and ignores the value the caller sends. Create, restart and update all pass through it, so the rule covers the CLI, the app, autostart, crash recovery and remote management. libpinggy counts reconnects over the whole tunnel lifetime and does not reset the count after a successful reconnect. Any limit, including the libpinggy default of 20 for an omitted value, stops a long-running tunnel permanently.
827
- - Do not route the foreground `pinggy device` through the daemon. With `-b` the daemon runs the agent, and no IPC route takes or returns a token or a server: the daemon reads both from `device.json`. Any local user can reach the IPC port.
855
+ - Do not route `pinggy device --foreground` through the daemon. Without it the daemon runs the agent, and no IPC route takes or returns a token or a server: the daemon reads both from `device.json`. Any local user can reach the IPC port.
828
856
  - Do not generalise `src/remote_management/` to serve the device agent. Those files are on the backend `constraints.md` do-not-touch list.
829
857
  - `device.json` holds a live credential. Any code that writes it goes through `writeDeviceIdentity()`, which keeps the 0600 mode on rewrites.
830
858
 
@@ -877,7 +905,8 @@ No em-dashes. Short phrases. Present tense. See `CLAUDE.md` § "English Style" b
877
905
  └──────────────────────────────────┘
878
906
  │ next pinggy command
879
907
  ▼
880
- getDaemonInfo() returns null (PID dead) ──▶ unlinks daemon.json
908
+ getDaemonInfo() returns null (PID dead, or ──▶ unlinks daemon.json
909
+ started before the last boot)
881
910
  │
882
911
  ▼
883
912
  startDaemon() spawns new child
package/CLAUDE.md CHANGED
@@ -44,15 +44,18 @@ CLI code calls `TunnelClient` (`src/daemon/tunnelClient.ts`), the public facade
44
44
 
45
45
  ### Daemon discovery and lifecycle
46
46
 
47
- `getDaemonInfo()` in `src/daemon/daemonManager.ts` reads `daemon.json`, validates the PID with `process.kill(pid, 0)`, deletes the file if stale, and returns `null` if no live daemon is found. `startDaemon()` spawns a detached daemon child and polls `daemon.json` for up to 8s.
47
+ `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
48
 
49
49
  Single daemon per user. State lives under `~/.config/pinggy/` on Linux/macOS or `%APPDATA%/pinggy/` on Windows (helper: `src/utils/configDir.ts`):
50
50
 
51
51
  - `daemon.json`: `{pid, port, startedAt, host, ipcVersion}`. `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.
52
- - `daemon-state.json`: detached tunnel configs, and the background device agent (`deviceAgent`), for crash recovery (`src/daemon/stateStore.ts`). Deleted on clean shutdown; replayed on next start.
52
+ - `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.
53
+ - `daemon-state.json`: detached tunnel configs, for crash recovery (`src/daemon/lifecycle/stateStore.ts`). Deleted on clean shutdown; replayed on next start.
54
+ - `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.
53
55
  - `daemon.log`: SDK + daemon logs. CLI logs stay separate.
54
56
  - `tunnels/<name>_<configId>.json`: saved tunnel configs from `pinggy config save`.
55
57
  - `device.json`: device agent id and token from `pinggy device connect` (`src/devices/deviceIdentity.ts`). Written 0600, unlike the tunnel configs beside it.
58
+ - `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.
56
59
 
57
60
  ### Foreground vs detached tunnels
58
61
 
@@ -69,13 +72,13 @@ Single daemon per user. State lives under `~/.config/pinggy/` on Linux/macOS or
69
72
 
70
73
  `pinggy devices`, the old spelling, stays a subcommand that prints the new one and exits 1 (`refuseDevicesSpelling()`). Do not remove `Subcommand.Devices`: without it `devices` falls to legacy tunnel mode, where `--token` is the tunnel token, so `pinggy devices connect --token pga_...` would send the device token to the tunnel server.
71
74
 
72
- It runs in the CLI process and owns no tunnel. Since slice 09 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. Since slice 10 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()`. Since slice 10b 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). Since slice 12 `pinggy device login` signs the machine in by email over plain HTTPS (`src/devices/login/`), writes `device.json`, then runs the same agent; since slice 13 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.
75
+ It owns no tunnel. Since slice 09 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. Since slice 10 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()`. Since slice 10b 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). Since slice 12 `pinggy device login` signs the machine in by email over plain HTTPS (`src/devices/login/`), writes `device.json`, then runs the same agent; since slice 13 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.
73
76
 
74
- Since slice 17, `pinggy device connect -b` and `login -b` run the agent in the daemon, as `pinggy start -b` runs a tunnel there, so it outlives the terminal; 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. `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.
77
+ `pinggy device connect` and `login` run the agent in the daemon, as `pinggy start -b` runs a tunnel there, so it outlives the terminal (slice 17). `--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.
75
78
 
76
- 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`.
79
+ 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`.
77
80
 
78
- Since slice 14, `scripts/install/install.sh` and `install.ps1` install or update the binary, put it on PATH, and run `pinggy device login`. pinggy.io serves copies that `website-cli-download-links-pr.yml` writes at each release tag. Renaming a release asset, changing the `Pinggy CLI version:` line, or changing `device login`'s `--manage` flag means changing both scripts in the same commit. Since slice 16, `DEVICE_AGENT_TOKEN` on either script updates without asking and runs `pinggy device connect` 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` flag also changes both scripts in the same commit.
81
+ Since slice 14, `scripts/install/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. 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. Since slice 16, `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.
79
82
 
80
83
  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` and `api-websocket.md` there before changing anything in `src/devices/`.
81
84
 
@@ -90,13 +93,15 @@ Section 17 of `ARCHITECTURE.md` has the protocol, the retry and terminal outcome
90
93
  | `pinggy stop <name\|id>` | Stop running tunnel(s) by name or ID prefix |
91
94
  | `pinggy ps` | Table of running tunnels (ID, name, status, local, URL) |
92
95
  | `pinggy attach <name\|id>` | Re-attach TUI to a running tunnel |
93
- | `pinggy daemon start \| stop \| status \| install-service \| uninstall-service` (alias `d`) | Daemon lifecycle and system-service installation |
94
- | `pinggy device login \| connect [-b] \| stop \| status \| remove` | Sign this machine in by email, or enrol it with a token, as a Pinggy device; `-b` runs the agent in the daemon, and `stop` stops it there; show the enrolment and the background agent; forget the credential |
96
+ | `pinggy daemon start \| stop \| status \| service-install \| service-uninstall` (alias `d`) | Daemon lifecycle and system-service installation |
97
+ | `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 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) |
95
98
 
96
99
  ## Build System
97
100
 
98
101
  tsup bundles to `dist/` (CJS + ESM). tsc type-checks only (`npm run build:tsc`). pkg builds standalone platform binaries (`out/pinggy-<platform>`). ts-jest with the ESM preset for unit tests (`jest.config.cjs`).
99
102
 
103
+ pkg packs every file in a dependency's `files` list and every package in its `dependencies`, whether the code loads it or not. The `pkg.ignore` list in `package.json` keeps out what the binary never loads: node-pty's `.pdb` debug symbols and C++ source, the SDK's unlinked `libcrypto.dylib` and `libssl.dylib` copies, the SDK's install-time `node-gyp` and `@mapbox/node-pre-gyp`, and zod's `src/` and `v3/`. A new glob must not match node-pty's `package.json`, `lib/`, or any file under `prebuilds/` other than a `.pdb`: `resolveNodePtyRoot()` copies those out of the snapshot at runtime. The `**` in these globs does not match a folder whose name starts with a dot, so a checkout under such a path (`~/.work/cli-js`) ignores nothing and builds the full-size binary. `"compress": "Brotli"` compresses the snapshot: on macOS arm64 the binary drops from 83 MB to 59 MB, and each run starts about 80ms later.
104
+
100
105
  ## Testing
101
106
 
102
107
  **Unit tests** live in `src/_tests_/`. Use `@jest/globals` imports (no global `jest`). `TunnelManager` is a singleton, so reset it between tests with `TunnelManager.instance = undefined`, and call `jest.clearAllMocks()` in `beforeEach`.
package/README.md CHANGED
@@ -233,14 +233,21 @@ Enrol this machine as a Pinggy device. The agent opens 1 WebSocket to the dashbo
233
233
 
234
234
  Devices and remote management are separate features. Remote management drives tunnels from the dashboard with an API key. A device is the machine itself, enrolled with its own token. The device agent owns no tunnels, and stopping it leaves every running tunnel alone.
235
235
 
236
- The agent runs in the foreground CLI process, not the daemon. It needs no daemon and starts none.
236
+ The agent runs in the background, in the daemon, so it stays connected after the terminal closes. Once the daemon starts it, the CLI prints the commands that manage it: `pinggy device status`, `stop`, `connect` and `remove`. Add `--foreground` to keep the agent in this terminal until Ctrl+C. `-b` still works and changes nothing.
237
+
238
+ ### Sign in with your email
239
+ ```bash
240
+ pinggy device login
241
+ ```
242
+
243
+ The CLI asks for your email and prints a Device Code. The dashboard emails a 6-digit code and an approve button. Type the code, or click the button. The approve page shows the same Device Code: approve only if it matches. The install script runs this command.
237
244
 
238
245
  ### Connect a device
239
246
  ```bash
240
247
  pinggy device connect --token <TOKEN>
241
248
  ```
242
249
 
243
- Add the device in the dashboard first, then pass the token it gives you. The command stays in the foreground and reconnects on its own until you interrupt it.
250
+ Add the device in the dashboard first, then pass the token it gives you. The CLI exits once the device connects, and the daemon reconnects it on its own until `pinggy device stop`.
244
251
 
245
252
  The token is written to disk on the first successful connect, so later runs need no flag:
246
253
  ```bash
@@ -268,7 +275,7 @@ Prints the device id, server, masked token, and enrolment time from the local fi
268
275
  pinggy device remove
269
276
  ```
270
277
 
271
- Deletes the local credential only. The device still exists in the dashboard. Delete it there to revoke it, because a machine that has lost its credential cannot authenticate the delete.
278
+ Prints the device id and whether the device is connected now, in the background or with `--foreground` in another terminal, then asks "Remove this device from this machine? [y/N]". Only `y` removes it: the command stops the device agent, then deletes the local credential. With no terminal, it refuses unless you add `-f`, which removes without asking. The device still exists in the dashboard. Delete it there to revoke it, because a machine that has lost its credential cannot authenticate the delete.
272
279
 
273
280
  ### Reconnect and stop conditions
274
281
 
@@ -294,7 +301,8 @@ It enrols, learns its device id and heartbeat interval from the dashboard, and s
294
301
 
295
302
  | Command | What happens |
296
303
  |---------|--------------|
297
- | `pinggy device connect -l 3000 -b --all --remote-management <KEY>` | Runs the agent. Those flags parse and are ignored. No tunnel, no remote management, no daemon. Only `--token` and `--manage` are read |
304
+ | `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 |
305
+ | `pinggy device connect -b --foreground` | Error, exit 1. The 2 flags contradict each other. Nothing runs |
298
306
  | `pinggy device start`, `pinggy device daemon stop` | Error, exit 1. The verb after `device` is `login`, `connect`, `stop`, `status`, or `remove` |
299
307
  | `pinggy start device`, `pinggy stop device` | `device` reads as a tunnel name. No new config can be called `device`, so nothing matches |
300
308
  | `pinggy config save device ...` | Rejected. `device` is a reserved name |
@@ -304,13 +312,13 @@ It enrols, learns its device id and heartbeat interval from the dashboard, and s
304
312
 
305
313
  `pinggy device` and `pinggy device --help` print the command list. After a verb, `--help` is ignored, so `pinggy device connect --help` tries to connect.
306
314
 
307
- ### Devices, tunnels, and the daemon do not interfere
315
+ ### Devices, tunnels, and the daemon
308
316
 
309
- - The agent is its own process. `pinggy daemon stop` leaves it running, and Ctrl+C on the agent leaves every tunnel running.
310
- - `pinggy device connect` never starts the daemon. Run tunnels and the agent side by side in 2 terminals.
317
+ - 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.
318
+ - 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.
311
319
  - 1 enrolment per machine. The newest successful connect overwrites `device.json`, and a `--token` on the command line beats the stored one.
312
- - Running the agent twice on 1 machine does not work. The dashboard refuses the second connection because the device is already connected, and that copy keeps retrying until the first one drops.
313
- - `pinggy device remove` deletes the credential file but does not stop a running agent, which rewrites the file the next time it connects. Stop the agent first.
320
+ - 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`.
321
+ - `pinggy device remove` stops a running agent, in the background or with `--foreground` in another terminal, before it deletes the credential file.
314
322
 
315
323
 
316
324
  ## Usage
@@ -490,7 +498,7 @@ Config dir varies by OS:
490
498
  - Linux/macOS: `~/.config/pinggy/`
491
499
  - Windows: `%APPDATA%\pinggy\`
492
500
 
493
- It holds `daemon.json` (discovery), `daemon-config.json` (persisted settings), `daemon-state.json` (crash recovery), `tunnels/` (saved configs), and `device.json` (the Pinggy Devices credential, written `0600`).
501
+ It holds `daemon.json` (discovery), `daemon-config.json` (persisted settings), `daemon-state.json` (crash recovery), `tunnels/` (saved configs), `device.json` (the Pinggy Devices credential, written `0600`), and `device-agent.json` (the PID of a device agent running in a terminal).
494
502
 
495
503
  Log dir varies by OS:
496
504
  - Linux: `~/.local/state/pinggy-cli/logs/` (honors `$XDG_STATE_HOME`)
@@ -510,7 +518,8 @@ Optionally combine with other flags (auth, IP whitelist) as needed.
510
518
  - **Foreground tunnel**: Ctrl+C closes the TUI. The daemon arms a 5-second grace timer and stops the tunnel if no other CLI re-attaches.
511
519
  - **Detached tunnel** (`-b`): the CLI already exited. Stop it with `pinggy stop <name|id>`.
512
520
  - **Everything at once**: `pinggy daemon stop` stops every tunnel and shuts the daemon down cleanly. `daemon-state.json` is cleared, so nothing replays on next start.
513
- - **Device agent** (`pinggy device connect`): Ctrl+C ends the agent. It runs outside the daemon, so no tunnel is affected.
521
+ - **Device agent** (`pinggy device connect`): the CLI already exited. Stop the agent with `pinggy device stop`. No tunnel is affected.
522
+ - **Device agent in the foreground** (`pinggy device connect --foreground`): Ctrl+C ends the agent. It runs outside the daemon, so no tunnel is affected.
514
523
 
515
524
 
516
525
  ## Versioning