pinggy 0.6.3 → 0.6.4

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
 
@@ -478,35 +478,36 @@ A system service gives restart-on-failure and start-at-login. The plain daemon m
478
478
 
479
479
  ## 17. Device agent (`pinggy device`)
480
480
 
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`.
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. 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
482
 
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.
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 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
484
 
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/`.
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 -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. `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`. Lint with `shellcheck -s sh` and `PSScriptAnalyzer`. The step order is in `install-script-plan.md` under the backend's `docs/pinggy-devices/`.
486
486
 
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.
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 -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
488
 
489
489
  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
490
 
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.
491
+ **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
492
 
493
493
  **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
494
 
495
495
  ### Background mode (slice 17)
496
496
 
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()`.
497
+ `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 install-service`, or the Pinggy app, whose in-process daemon runs the same `runDaemonChild()`. The app reaches it through `TunnelClient.getDeviceAgentStatus()`, `startDeviceAgent()` and `stopDeviceAgent()`.
498
498
 
499
499
  **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
500
 
501
- `connect -b`, in `src/devices/backgroundAgent.ts`:
501
+ `connect`, in `src/devices/backgroundAgent.ts`:
502
502
 
503
503
  1. `takeEnvironmentToken()` and `resolveConnectTarget()`, as in the foreground.
504
504
  2. A target that differs from `device.json`: the verify above. A refusal prints it and exits 1.
505
505
  3. `ensureDaemonRunning()`.
506
506
  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.
507
+ 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.
508
+ 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.
508
509
 
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`.
510
+ `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`.
510
511
 
511
512
  **`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.
512
513
 
@@ -514,11 +515,11 @@ The daemon's run differs from the foreground one in 3 dependencies, passed throu
514
515
 
515
516
  - **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
517
  - **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.
518
+ - **`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
519
 
519
520
  | Event | The background agent |
520
521
  | --- | --- |
521
- | The CLI that ran `connect -b` exits, or its terminal closes | Keeps running. The daemon is detached |
522
+ | The CLI that ran `connect` exits, or its terminal closes | Keeps running. The daemon is detached |
522
523
  | Daemon crash | Restored at the next daemon start (section 8) |
523
524
  | `pinggy daemon stop`, or the Pinggy app quits | Stops. The socket closes with 1000 and every shell ends |
524
525
  | Reboot | Stops, as a `-b` tunnel does |
@@ -537,7 +538,7 @@ The daemon's run differs from the foreground one in 3 dependencies, passed throu
537
538
  | `src/devices/deviceIdentity.ts` | `device.json` read, write, clear, and token masking |
538
539
  | `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
540
  | `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 |
541
+ | `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
542
  | `src/daemon/deviceAgentHost.ts` | `DeviceAgentHost`: the daemon's 1 run, behind the `/device` routes. `writeIdentityWhileOwned()` |
542
543
  | `src/devices/collectors/systemInfo.ts` | `collectSystemInfo()`: the `device/info` payload |
543
544
  | `src/devices/collectors/metrics.ts` | `collectMetrics()`: the `device/metrics` payload, with `cpu_percent` from 2 samples |
@@ -553,7 +554,7 @@ The daemon's run differs from the foreground one in 3 dependencies, passed throu
553
554
  | `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
555
  | `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
556
  | `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 |
557
+ | `src/cli/subcommand/handlers/deviceCommand.ts` | The `login`, `connect`, `stop`, `status`, `remove` verbs, and `--foreground`. `refuseDevicesSpelling()` for the old spelling |
557
558
  | `src/utils/helpMessages.ts` | `printDeviceHelp()` |
558
559
 
559
560
  `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 +642,7 @@ Every call goes through an `IPCClient` with origin `device`. With no daemon, a s
641
642
 
642
643
  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
644
 
644
- ### Terminal (slices T1, T1b, T2 and T3: open, close, shells that outlive the socket, output, input)
645
+ ### Terminal (slices T1, T1b, T2, T3, T6 and T8: open, close, shells that outlive the socket, output, input, screen)
645
646
 
646
647
  `ch: "terminal"` frames go to the run's `TerminalHandler`, never to `handleFrame()`. Output flows up as `data`, and keystrokes flow down as `data`.
647
648
 
@@ -670,26 +671,36 @@ The dashboard answers an unreadable payload with `invalid_payload` on the `devic
670
671
  ├───────────────────────────────────────────────────────▶│ a tab attached and asks for its screen (T6)
671
672
  │ terminal/snapshot event {part, last, after_seq, data} │
672
673
  │◀───────────────────────────────────────────────────────┤ the screen, to that tab only
674
+ │ terminal/resync event {resync_id, part, after_seq, data}
675
+ │◀───────────────────────────────────────────────────────┤ the latest screen after a skip, to every tab (T8)
676
+ │ terminal/activity event {terminal_id, skipped_bytes} │
677
+ │◀───────────────────────────────────────────────────────┤ still busy while skipping, not forwarded (T8)
673
678
  ```
674
679
 
675
680
  - **`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
681
  - **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
682
  - **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()`.
683
+ - **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
684
  - **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
685
  - **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
686
  - **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.
687
+ - **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
688
  - **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
689
  - **`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
690
  - **`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.
691
+ - **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
692
  - **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
693
  - **`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.
694
+ - **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
695
  - **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
696
  - **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
697
  - **`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.
698
+ - **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.
699
+ - **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.
700
+ - **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.
701
+ - **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.
702
+ - **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.
703
+ - **`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
704
  - **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
705
  - `welcome.terminal_enabled` and `welcome.max_terminals_per_device` are optional, so an older dashboard leaves the defaults (enabled, 3).
695
706
 
@@ -697,7 +708,7 @@ The dashboard answers an unreadable payload with `invalid_payload` on the `devic
697
708
 
698
709
  **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
710
 
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.
711
+ `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
712
 
702
713
  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
714
 
@@ -709,7 +720,7 @@ Measured on `macos-arm64` and `macos-x64`. `linux-x64`, `linux-arm64` and `win-x
709
720
 
710
721
  | Signal | Outcome |
711
722
  | --- | --- |
712
- | HTTP 401 on the upgrade | terminal |
723
+ | 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
724
  | Close code 4001 | terminal |
714
725
  | `welcome` with an error other than `already_connected` | terminal |
715
726
  | `system/disconnect` with any reason but `shutdown` | terminal |
@@ -717,6 +728,8 @@ Measured on `macos-arm64` and `macos-x64`. `linux-x64`, `linux-arm64` and `win-x
717
728
  | `system/disconnect` with `shutdown` | retry. The node is draining, the credential is fine |
718
729
  | Any other close code, socket error, or unreadable `welcome` | retry |
719
730
 
731
+ 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.
732
+
720
733
  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
734
 
722
735
  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,7 +743,7 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
730
743
  "server": "dashboard.pinggy.io", "enrolled_at": "2026-09-05T09:22:10Z"}
731
744
  ```
732
745
 
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.
746
+ `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
747
 
735
748
  **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
749
 
@@ -744,8 +757,9 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
744
757
  | --- | --- | --- |
745
758
  | `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
759
  | `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` |
760
+ | `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` |
761
+ | `device connect -b --foreground` | `-b and --foreground contradict each other`, exit 1. Nothing runs | `handleDevice`, before the verb switch |
762
+ | `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` |
749
763
  | `device stop` with no background agent | "No device agent is running in the background.", exit 0. Never starts a daemon | `stopAgentInBackground()` |
750
764
  | `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
765
  | `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,14 +775,14 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
761
775
 
762
776
  ### The agent and the daemon
763
777
 
764
- In the foreground the agent shares no state with the daemon or with tunnels, which is what makes the composition table boring.
778
+ With `--foreground` the agent shares no state with the daemon or with tunnels, which is what makes the composition table boring.
765
779
 
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`.
780
+ - `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
781
  - `pinggy daemon stop` stops tunnels and the daemon. A foreground agent is a separate process and keeps going.
768
782
  - Ctrl+C on the agent touches no tunnel. There is no `SessionTracker` entry, no grace timer, and no origin tag.
769
783
  - 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
784
 
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.
785
+ 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-state.json` records it. It still has no `SessionTracker` entry and no origin tag of its own.
772
786
 
773
787
  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()`).
774
788
 
@@ -824,7 +838,7 @@ No em-dashes. Short phrases. Present tense. See `CLAUDE.md` § "English Style" b
824
838
  - `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
839
  - 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
840
  - 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.
841
+ - 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
842
  - Do not generalise `src/remote_management/` to serve the device agent. Those files are on the backend `constraints.md` do-not-touch list.
829
843
  - `device.json` holds a live credential. Any code that writes it goes through `writeDeviceIdentity()`, which keeps the 0600 mode on rewrites.
830
844
 
package/CLAUDE.md CHANGED
@@ -69,13 +69,13 @@ Single daemon per user. State lives under `~/.config/pinggy/` on Linux/macOS or
69
69
 
70
70
  `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
71
 
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.
72
+ 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
73
 
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.
74
+ `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
75
 
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`.
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` and `--foreground`.
77
77
 
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.
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 -b`. `-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.
79
79
 
80
80
  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
81
 
@@ -91,12 +91,14 @@ Section 17 of `ARCHITECTURE.md` has the protocol, the retry and terminal outcome
91
91
  | `pinggy ps` | Table of running tunnels (ID, name, status, local, URL) |
92
92
  | `pinggy attach <name\|id>` | Re-attach TUI to a running tunnel |
93
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 |
94
+ | `pinggy device login \| connect [--foreground] \| stop \| status \| remove` | 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; forget the credential |
95
95
 
96
96
  ## Build System
97
97
 
98
98
  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
99
 
100
+ 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.
101
+
100
102
  ## Testing
101
103
 
102
104
  **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
@@ -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. `pinggy device connect` starts it again.
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. `--foreground` is refused while the daemon runs an agent. Stop it first with `pinggy device stop`.
321
+ - `pinggy device remove` stops the daemon's agent, then deletes the credential file. It does not stop a `--foreground` agent, which rewrites the file the next time it connects. Stop that one first with Ctrl+C.
314
322
 
315
323
 
316
324
  ## Usage
@@ -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
@@ -1601,7 +1601,7 @@ async function ensureDaemonRunning() {
1601
1601
  return existing;
1602
1602
  }
1603
1603
  if (process.versions.electron) {
1604
- const { runDaemonChild } = await import("./daemonChild-E73NFWKE.js");
1604
+ const { runDaemonChild } = await import("./daemonChild-WHS676G4.js");
1605
1605
  const handle = await runDaemonChild({
1606
1606
  installSignalHandlers: false,
1607
1607
  exitOnFailure: false,
@@ -2216,7 +2216,7 @@ var TunnelClient = class _TunnelClient {
2216
2216
  this.assertClient();
2217
2217
  await this.ipc.restartTunnel(tunnelId);
2218
2218
  }
2219
- // Device agent (`pinggy device connect -b`). The daemon reads the token and the server from
2219
+ // Device agent (`pinggy device connect`). The daemon reads the token and the server from
2220
2220
  // device.json, so none of these takes either.
2221
2221
  async getDeviceAgentStatus() {
2222
2222
  this.assertClient();