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.
@@ -13,7 +13,7 @@ import {
13
13
  startDaemon,
14
14
  startRemoteManagement,
15
15
  stopDaemon
16
- } from "./chunk-GESMZQHI.js";
16
+ } from "./chunk-CIOYQU7F.js";
17
17
  import {
18
18
  readDaemonConfig
19
19
  } from "./chunk-PD7HXVQ3.js";
@@ -129,6 +129,8 @@ var cliOptions = {
129
129
  // Background mode (run tunnel in background via daemon)
130
130
  b: { type: "boolean", description: "Run tunnel in background via daemon. CLI exits after tunnel starts." },
131
131
  all: { type: "boolean", description: "Start all auto-start tunnels" },
132
+ // `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
133
+ foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
132
134
  // Internal daemon child marker
133
135
  "_daemon-child": { type: "boolean", description: "Internal: daemon child process marker", hidden: true },
134
136
  // Misc
@@ -199,6 +201,11 @@ function printHelpMessage() {
199
201
  console.log("\nBackground Mode:");
200
202
  console.log(" pinggy -l 3000 --b # Start tunnel in background");
201
203
  console.log(" pinggy start my-tunnel --b # Start saved tunnel in background");
204
+ console.log("\nDevices (more: pinggy device --help):");
205
+ console.log(" pinggy device login # Sign in by email. The agent runs in the background");
206
+ console.log(" pinggy device login --foreground # Same, with the agent in this terminal");
207
+ console.log(" pinggy device status # Show this device and its agent");
208
+ console.log(" pinggy device stop # Stop the background agent");
202
209
  console.log("\nDaemon Lifecycle (also: pinggy d <command>):");
203
210
  console.log(" pinggy daemon start # Start the background daemon");
204
211
  console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
@@ -1484,7 +1491,7 @@ async function initRemoteManagement(values, blocking) {
1484
1491
  }
1485
1492
 
1486
1493
  // src/cli/subcommand/handlers/daemonCommandsHandler.ts
1487
- import pico2 from "picocolors";
1494
+ import pico6 from "picocolors";
1488
1495
 
1489
1496
  // src/daemon/lifecycle/serviceInstaller.ts
1490
1497
  import os2 from "os";
@@ -1775,14 +1782,17 @@ function printDeviceHelp() {
1775
1782
  console.log("\nUsage: pinggy device <command> [options]\n");
1776
1783
  console.log("Run this machine as a Pinggy device.\n");
1777
1784
  console.log("Commands:");
1778
- console.log(" login Sign this machine in with your email, then stay connected");
1779
- console.log(" connect --token <TOKEN> Enrol, then stay connected until interrupted");
1785
+ console.log(" login Sign this machine in with your email, then run the agent in the");
1786
+ console.log(" background");
1787
+ console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
1788
+ console.log(" background. Without --token: start the enrolled device's agent again");
1780
1789
  console.log(" stop Stop the agent running in the background");
1781
1790
  console.log(" status Show the enrolment, and the agent running in the background");
1782
1791
  console.log(" remove Forget the local credential (does not delete the device)\n");
1792
+ console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.\n");
1783
1793
  console.log("Options:");
1784
- console.log(" -b login and connect: run the agent in the background, in the daemon.");
1785
- console.log(" It stays connected after this terminal closes");
1794
+ console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
1795
+ console.log(" -b login and connect: run the agent in the background. The default");
1786
1796
  console.log(" --token <TOKEN> Device token from the dashboard");
1787
1797
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
1788
1798
  console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname\n");
@@ -1791,6 +1801,9 @@ function printDeviceHelp() {
1791
1801
  console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
1792
1802
  }
1793
1803
 
1804
+ // src/devices/backgroundAgent.ts
1805
+ import pico5 from "picocolors";
1806
+
1794
1807
  // src/devices/deviceIdentity.ts
1795
1808
  import fs3 from "fs";
1796
1809
  var SECRET_FILE_MODE = 384;
@@ -1885,10 +1898,11 @@ var WelcomeSchema = z.object({
1885
1898
  max_terminals_per_device: z.number().optional(),
1886
1899
  // No default on the agent. Without it, terminals stay unavailable rather than unbraked.
1887
1900
  terminal_window_bytes: z.number().optional(),
1888
- // No default either. Without them the agent runs no expiry timers, and the dashboard's sweep
1889
- // still ends an expired shell, only later.
1901
+ // No default either. Without it the agent runs no expiry timer, and the dashboard's sweep
1902
+ // still ends an idle shell, only later. A shell has no cap on its running time.
1890
1903
  terminal_idle_timeout_seconds: z.number().optional(),
1891
- terminal_max_session_seconds: z.number().optional(),
1904
+ // Optional: without it the agent keeps T2's brake and never skips output (slice T8).
1905
+ terminal_resync: z.boolean().optional(),
1892
1906
  // Optional: a dashboard older than these sends neither, and the agent prints only the device id.
1893
1907
  email: z.string().optional(),
1894
1908
  device_url: z.string().optional()
@@ -1910,28 +1924,36 @@ var TunnelActionSchema = z.object({
1910
1924
  });
1911
1925
 
1912
1926
  // src/devices/deviceAgentReporter.ts
1927
+ import pico2 from "picocolors";
1928
+ function printDeviceUrl(print, label, url) {
1929
+ print(label);
1930
+ print("");
1931
+ print(` ${pico2.magentaBright(url)}`);
1932
+ print("");
1933
+ }
1913
1934
  function printConnected(welcome) {
1914
1935
  printer_default.success(`Connected as device ${welcome.device_agent_id}`);
1915
1936
  if (welcome.email) {
1916
1937
  printer_default.print(`Signed in as ${welcome.email}`);
1917
1938
  }
1918
1939
  if (welcome.device_url) {
1919
- printer_default.print("Open the device in a browser:");
1920
- printer_default.print(` ${welcome.device_url}`);
1940
+ printDeviceUrl((message) => printer_default.print(message), "Open the device in a browser:", welcome.device_url);
1921
1941
  }
1922
1942
  }
1923
1943
  function formatSeconds(millis) {
1924
1944
  return (millis / 1e3).toFixed(1);
1925
1945
  }
1926
1946
  var printingReporter = {
1927
- connecting: (server) => printer_default.print(`Connecting to ${server}`),
1947
+ connecting: (server) => printer_default.print(pico2.cyanBright(`Connecting to ${server}...`)),
1928
1948
  connected: printConnected,
1929
1949
  reconnecting: (delayMillis, attempt) => printer_default.warn(
1930
1950
  `Disconnected. Reconnecting in ${formatSeconds(delayMillis)} seconds (attempt ${attempt}).`
1931
1951
  ),
1932
1952
  warn: (message) => printer_default.warn(message),
1933
1953
  failed: (error) => printer_default.error(error.message),
1934
- replacingDevice: (oldDeviceAgentId) => printer_default.print(`This machine was device ${oldDeviceAgentId}. Connecting it with the token from the command.`)
1954
+ replacingDevice: (oldDeviceAgentId) => printer_default.print(pico2.yellow(
1955
+ `This machine was device ${oldDeviceAgentId}. That device stays in the dashboard, offline.`
1956
+ ))
1935
1957
  };
1936
1958
 
1937
1959
  // src/devices/collectors/systemInfo.ts
@@ -2441,12 +2463,13 @@ var OP_RESIZE = "resize";
2441
2463
  var OP_SIGNAL = "signal";
2442
2464
  var OP_CONTEXT = "context";
2443
2465
  var OP_SNAPSHOT = "snapshot";
2466
+ var OP_RESYNC = "resync";
2467
+ var OP_ACTIVITY = "activity";
2444
2468
  var TERMINAL_SIGNALS = ["INT", "TERM", "QUIT", "HUP"];
2445
2469
  var MIN_GRID = 1;
2446
2470
  var MAX_GRID = 1e3;
2447
2471
  var CLOSE_REASON_USER_CLOSED = "user_closed";
2448
2472
  var CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
2449
- var CLOSE_REASON_MAX_SESSION = "max_session";
2450
2473
  var ERROR_INVALID_PAYLOAD2 = "invalid_payload";
2451
2474
  var ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
2452
2475
  var ERROR_TERMINAL_DISABLED = "terminal_disabled";
@@ -2491,6 +2514,7 @@ function clampGrid(requested, fallback) {
2491
2514
  }
2492
2515
 
2493
2516
  // src/devices/terminal/terminalHandler.ts
2517
+ import { randomUUID as randomUUID2 } from "crypto";
2494
2518
  import os6 from "os";
2495
2519
 
2496
2520
  // src/devices/terminal/flowWindow.ts
@@ -2803,6 +2827,7 @@ var ScreenMirror = class _ScreenMirror {
2803
2827
  this.terminal = terminal;
2804
2828
  this.serializer = serializer;
2805
2829
  this.disposed = false;
2830
+ this.unparsedBytes = 0;
2806
2831
  }
2807
2832
  /** Null when the headless terminal cannot load. The shell then works as before, without restore. */
2808
2833
  static create(cols, rows) {
@@ -2813,28 +2838,45 @@ var ScreenMirror = class _ScreenMirror {
2813
2838
  terminal.loadAddon(serializer);
2814
2839
  return new _ScreenMirror(terminal, serializer);
2815
2840
  }
2816
- /** Bytes exactly as they were sent. xterm parses them later, in order, and joins split characters. */
2817
- feed(bytes) {
2818
- if (!this.disposed) this.terminal.write(bytes);
2841
+ /**
2842
+ * Bytes exactly as they were sent or skipped. xterm parses them later, in order, and joins split
2843
+ * characters. `onParsed` runs once they are parsed, when {@link backlogBytes} has already dropped by them.
2844
+ */
2845
+ feed(bytes, onParsed) {
2846
+ if (this.disposed) return;
2847
+ const byteCount = bytes.length;
2848
+ this.unparsedBytes += byteCount;
2849
+ this.terminal.write(bytes, () => {
2850
+ this.unparsedBytes -= byteCount;
2851
+ onParsed?.();
2852
+ });
2853
+ }
2854
+ /**
2855
+ * Fed and not yet parsed. xterm queues writes without limit, so a shell that skips its output
2856
+ * (slice T8) pauses on this, and on nothing else.
2857
+ */
2858
+ get backlogBytes() {
2859
+ return this.unparsedBytes;
2819
2860
  }
2820
2861
  resize(cols, rows) {
2821
2862
  if (!this.disposed) this.terminal.resize(cols, rows);
2822
2863
  }
2823
2864
  /**
2824
- * The screen after everything fed before this call, and nothing fed after it. Null when the
2825
- * mirror was disposed first.
2865
+ * The screen after everything fed before this call, and nothing fed after it, serialised under
2866
+ * `maxBytes`. Null when the mirror was disposed first, or when even the screen alone is over
2867
+ * {@link MAX_SNAPSHOT_BYTES}.
2826
2868
  *
2827
2869
  * xterm parses writes in batches, on a timer. An empty write queued now has its callback run
2828
2870
  * after every earlier chunk is parsed and before the next one is, so serialising inside it sees
2829
2871
  * exactly what was fed before this call.
2830
2872
  */
2831
- snapshot() {
2873
+ snapshot(maxBytes = MAX_SNAPSHOT_BYTES) {
2832
2874
  return new Promise((resolve) => {
2833
2875
  if (this.disposed) {
2834
2876
  resolve(null);
2835
2877
  return;
2836
2878
  }
2837
- this.terminal.write("", () => resolve(this.disposed ? null : this.serialise()));
2879
+ this.terminal.write("", () => resolve(this.disposed ? null : this.serialise(maxBytes)));
2838
2880
  });
2839
2881
  }
2840
2882
  dispose() {
@@ -2842,14 +2884,24 @@ var ScreenMirror = class _ScreenMirror {
2842
2884
  this.disposed = true;
2843
2885
  this.terminal.dispose();
2844
2886
  }
2845
- /** Null when even the screen alone is over the cap. The tab then waits out its fallback. */
2846
- serialise() {
2887
+ /**
2888
+ * Fewer lines of scrollback until the text fits `maxBytes`. A screen alone over a cap below
2889
+ * {@link MAX_SNAPSHOT_BYTES} is still sent under that: a resync over its cap beats a tab that never
2890
+ * catches up. Null when even the screen alone is over {@link MAX_SNAPSHOT_BYTES}.
2891
+ */
2892
+ serialise(maxBytes) {
2847
2893
  for (const scrollback of SCROLLBACK_LINES_TO_TRY) {
2848
2894
  const text = this.serializer.serialize({ scrollback });
2849
- if (Buffer.byteLength(text, "utf-8") <= MAX_SNAPSHOT_BYTES) {
2895
+ if (Buffer.byteLength(text, "utf-8") <= maxBytes) {
2850
2896
  return { text, cols: this.terminal.cols, rows: this.terminal.rows };
2851
2897
  }
2852
2898
  }
2899
+ if (maxBytes < MAX_SNAPSHOT_BYTES) {
2900
+ const screenOnly = this.serializer.serialize({ scrollback: 0 });
2901
+ if (Buffer.byteLength(screenOnly, "utf-8") <= MAX_SNAPSHOT_BYTES) {
2902
+ return { text: screenOnly, cols: this.terminal.cols, rows: this.terminal.rows };
2903
+ }
2904
+ }
2853
2905
  return null;
2854
2906
  }
2855
2907
  };
@@ -2862,16 +2914,31 @@ var DEFAULT_COLS = 80;
2862
2914
  var DEFAULT_ROWS = 24;
2863
2915
  var EXPIRY_CHECK_MILLIS = 5e3;
2864
2916
  var MILLIS_PER_SECOND = 1e3;
2865
- var TerminalHandler = class {
2917
+ var RESYNC_MIN_INTERVAL_MILLIS = 1e3;
2918
+ var MIRROR_HIGH_WATER_BYTES = 1024 * 1024;
2919
+ var MIRROR_LOW_WATER_BYTES = 256 * 1024;
2920
+ var ACTIVITY_REPORT_MILLIS = 6e4;
2921
+ var DEFAULT_SKIP_TUNING = {
2922
+ resyncMinIntervalMillis: RESYNC_MIN_INTERVAL_MILLIS,
2923
+ mirrorHighWaterBytes: MIRROR_HIGH_WATER_BYTES,
2924
+ mirrorLowWaterBytes: MIRROR_LOW_WATER_BYTES,
2925
+ activityReportMillis: ACTIVITY_REPORT_MILLIS
2926
+ };
2927
+ var TerminalHandler = class _TerminalHandler {
2866
2928
  constructor(dependencies) {
2867
2929
  this.dependencies = dependencies;
2868
2930
  this.enabled = true;
2869
2931
  this.suspended = false;
2932
+ /** `terminal_resync` in `welcome` (slice T8). Off, every shell keeps T2's brake. */
2933
+ this.resyncEnabled = false;
2934
+ /** Paused by `suspend` under T2's brake, so `resumeAll` resumes them if `welcome` turned skip mode on. */
2935
+ this.pausedBySuspend = /* @__PURE__ */ new Set();
2870
2936
  this.expiryTimer = null;
2871
2937
  this.contextTimer = null;
2872
2938
  this.contextPollInFlight = false;
2873
2939
  this.contextTracker = new ShellContextTracker();
2874
2940
  this.streams = /* @__PURE__ */ new Map();
2941
+ this.tuning = { ...DEFAULT_SKIP_TUNING, ...dependencies.skipTuning };
2875
2942
  }
2876
2943
  /**
2877
2944
  * From welcome. An older dashboard sends no terminal fields, and `terminal_enabled` and the
@@ -2881,7 +2948,7 @@ var TerminalHandler = class {
2881
2948
  * the field, and nobody notices until a node falls over, so an agent without one refuses to open
2882
2949
  * a terminal at all.
2883
2950
  */
2884
- configure(terminalEnabled, maxTerminalsPerDevice, terminalWindowBytes, maxFrameBytes, idleTimeoutSeconds, maxSessionSeconds) {
2951
+ configure(terminalEnabled, maxTerminalsPerDevice, terminalWindowBytes, maxFrameBytes, idleTimeoutSeconds, terminalResync) {
2885
2952
  if (terminalEnabled !== void 0) this.enabled = terminalEnabled;
2886
2953
  if (maxTerminalsPerDevice !== void 0) this.dependencies.registry.setMaxTerminals(maxTerminalsPerDevice);
2887
2954
  this.windowBytes = terminalWindowBytes;
@@ -2890,21 +2957,33 @@ var TerminalHandler = class {
2890
2957
  logger.info("Terminals unavailable: welcome carried no terminal_window_bytes");
2891
2958
  }
2892
2959
  this.idleTimeoutMillis = positiveMillis(idleTimeoutSeconds);
2893
- this.maxSessionMillis = positiveMillis(maxSessionSeconds);
2960
+ this.setSkipMode(terminalResync === true);
2894
2961
  this.startExpiryTimer();
2895
2962
  }
2896
2963
  /**
2897
- * Ends every shell past its idle timeout or its max-session cap. Runs on a timer; public so a test
2898
- * decides when. The cap goes first: a shell both idle and too old is closed for the rule typing
2899
- * cannot reset.
2964
+ * `welcome` turned skip mode on or off. Off, a skipping shell stops skipping without a resync, since
2965
+ * this dashboard cannot route one, and its tabs miss what was skipped. `resumeAll` then sets the reads.
2900
2966
  */
2967
+ setSkipMode(enabled) {
2968
+ if (enabled === this.resyncEnabled) return;
2969
+ this.resyncEnabled = enabled;
2970
+ for (const stream of this.streams.values()) {
2971
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
2972
+ stream.resyncTimer = null;
2973
+ stream.skipping = false;
2974
+ stream.skippedBytes = 0;
2975
+ stream.resyncOverflowed = false;
2976
+ stream.resyncHeldBundles.splice(0);
2977
+ stream.resyncHeldBytes = 0;
2978
+ stream.mirrorPaused = false;
2979
+ }
2980
+ }
2981
+ /** Ends every shell past its idle timeout. Runs on a timer; public so a test decides when. */
2901
2982
  expireShells() {
2902
2983
  if (this.suspended) return;
2903
2984
  const nowMillis = this.nowMillis();
2904
2985
  for (const [terminalId, stream] of [...this.streams.entries()]) {
2905
- if (this.maxSessionMillis !== void 0 && nowMillis - stream.openedAtMillis >= this.maxSessionMillis) {
2906
- this.expire(terminalId, CLOSE_REASON_MAX_SESSION);
2907
- } else if (this.idleTimeoutMillis !== void 0 && nowMillis - stream.lastActivityMillis >= this.idleTimeoutMillis) {
2986
+ if (this.idleTimeoutMillis !== void 0 && nowMillis - stream.lastActivityMillis >= this.idleTimeoutMillis) {
2908
2987
  this.expire(terminalId, CLOSE_REASON_IDLE_TIMEOUT);
2909
2988
  }
2910
2989
  }
@@ -2938,22 +3017,28 @@ var TerminalHandler = class {
2938
3017
  this.contextTracker.clear();
2939
3018
  this.suspended = false;
2940
3019
  for (const stream of this.streams.values()) {
3020
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
2941
3021
  stream.splitter.dispose();
2942
3022
  stream.mirror?.dispose();
2943
3023
  }
2944
3024
  this.streams.clear();
3025
+ this.pausedBySuspend.clear();
2945
3026
  this.dependencies.registry.killAll();
2946
3027
  }
2947
3028
  /**
2948
- * The socket dropped and the agent will redial. Every shell stops being read and keeps running.
2949
- * Whatever it prints waits in the kernel, and the shell blocks once that buffer is full.
3029
+ * The socket dropped and the agent will redial. Under T2's brake every shell stops being read and
3030
+ * keeps running: whatever it prints waits in the kernel, and the shell blocks once that buffer is
3031
+ * full. In skip mode (slice T8) a shell is read on, and its output is skipped.
2950
3032
  */
2951
3033
  suspend() {
2952
3034
  if (this.suspended) return;
2953
3035
  this.suspended = true;
2954
3036
  for (const [terminalId, session] of this.dependencies.registry.entries()) {
3037
+ const stream = this.streams.get(terminalId);
3038
+ if (stream && this.skipsOutput(stream)) continue;
2955
3039
  try {
2956
3040
  session.pause();
3041
+ this.pausedBySuspend.add(terminalId);
2957
3042
  } catch (err) {
2958
3043
  logger.warn("Terminal pause failed", { terminal_id: terminalId, error: errorName2(err) });
2959
3044
  }
@@ -2962,13 +3047,18 @@ var TerminalHandler = class {
2962
3047
  }
2963
3048
  /**
2964
3049
  * `welcome` arrived. Every shell the dashboard did not close is read again, except one whose
2965
- * window is still full. That one resumes on the `ack` that reopens it.
3050
+ * window is still full. That one resumes on the `ack` that reopens it. A shell in skip mode was
3051
+ * never paused, and resyncs instead (slice T8).
2966
3052
  */
2967
3053
  resumeAll() {
2968
3054
  if (!this.suspended) return;
2969
3055
  this.suspended = false;
2970
3056
  for (const [terminalId, session] of this.dependencies.registry.entries()) {
2971
3057
  const stream = this.streams.get(terminalId);
3058
+ if (stream && this.skipsOutput(stream)) {
3059
+ this.resumeSkipping(terminalId, stream, session);
3060
+ continue;
3061
+ }
2972
3062
  if (stream) {
2973
3063
  for (const chunk of stream.heldBundles.splice(0)) {
2974
3064
  this.sendData(terminalId, chunk);
@@ -2981,6 +3071,7 @@ var TerminalHandler = class {
2981
3071
  logger.warn("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
2982
3072
  }
2983
3073
  }
3074
+ this.pausedBySuspend.clear();
2984
3075
  for (const context of this.contextTracker.current()) {
2985
3076
  if (this.streams.has(context.terminal_id)) {
2986
3077
  this.dependencies.send(event(CHANNEL_TERMINAL, OP_CONTEXT, context));
@@ -3083,7 +3174,6 @@ var TerminalHandler = class {
3083
3174
  this.dependencies.send(response(envelope, OP_OPENED, opened));
3084
3175
  }
3085
3176
  startStream(terminalId, session, windowBytes, bundleBytes) {
3086
- const openedAtMillis = this.nowMillis();
3087
3177
  const stream = {
3088
3178
  session,
3089
3179
  window: new FlowWindow(windowBytes),
@@ -3092,8 +3182,17 @@ var TerminalHandler = class {
3092
3182
  paused: false,
3093
3183
  sentSeq: 0,
3094
3184
  heldBundles: [],
3095
- openedAtMillis,
3096
- lastActivityMillis: openedAtMillis
3185
+ lastActivityMillis: this.nowMillis(),
3186
+ skipping: false,
3187
+ skippedBytes: 0,
3188
+ lastResyncAtMillis: 0,
3189
+ resyncTimer: null,
3190
+ resyncInFlight: null,
3191
+ resyncHeldBundles: [],
3192
+ resyncHeldBytes: 0,
3193
+ resyncOverflowed: false,
3194
+ mirrorPaused: false,
3195
+ lastActivityReportMillis: 0
3097
3196
  };
3098
3197
  this.streams.set(terminalId, stream);
3099
3198
  this.startContextTimer();
@@ -3105,17 +3204,29 @@ var TerminalHandler = class {
3105
3204
  if (this.dependencies.registry.remove(terminalId) === void 0) return;
3106
3205
  stream.splitter.flush();
3107
3206
  stream.splitter.dispose();
3108
- this.forgetStream(terminalId);
3109
- logger.info("Terminal shell exited", { terminal_id: terminalId, exit_code: exitCode, signal });
3110
- const exit = signal ? { terminal_id: terminalId, exit_code: null, signal: signalName(signal) } : { terminal_id: terminalId, exit_code: exitCode, signal: null };
3111
- this.dependencies.send(event(CHANNEL_TERMINAL, OP_EXIT, exit));
3112
- this.dependencies.send(event(
3113
- CHANNEL_TERMINAL,
3114
- OP_CLOSE,
3115
- { terminal_id: terminalId, reason: CLOSE_REASON_USER_CLOSED }
3116
- ));
3207
+ void this.finishExit(terminalId, stream, exitCode, signal);
3117
3208
  });
3118
3209
  }
3210
+ /**
3211
+ * The shell exited on its own. A shell that skipped its last output sends its last screen first, at
3212
+ * once, so the tabs see how it ended (slice T8). Then `exit` and `close`. With nothing to resync this
3213
+ * runs to the end without yielding, as before.
3214
+ */
3215
+ async finishExit(terminalId, stream, exitCode, signal) {
3216
+ if (this.skipsOutput(stream)) {
3217
+ if (stream.resyncInFlight) await stream.resyncInFlight;
3218
+ if (stream.skipping && !this.suspended) await this.resync(terminalId, stream);
3219
+ }
3220
+ this.forgetStream(terminalId);
3221
+ logger.info("Terminal shell exited", { terminal_id: terminalId, exit_code: exitCode, signal });
3222
+ const exit = signal ? { terminal_id: terminalId, exit_code: null, signal: signalName(signal) } : { terminal_id: terminalId, exit_code: exitCode, signal: null };
3223
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_EXIT, exit));
3224
+ this.dependencies.send(event(
3225
+ CHANNEL_TERMINAL,
3226
+ OP_CLOSE,
3227
+ { terminal_id: terminalId, reason: CLOSE_REASON_USER_CLOSED }
3228
+ ));
3229
+ }
3119
3230
  /**
3120
3231
  * 1 bundle leaves, and the window narrows by what it carried.
3121
3232
  *
@@ -3129,10 +3240,16 @@ var TerminalHandler = class {
3129
3240
  * The mirror is fed here, in the same tick as the seq, and nowhere else. A snapshot then holds
3130
3241
  * exactly the bundles up to its `after_seq`. Fed when the pty is read, a bundle still being cut
3131
3242
  * would be in the screen and drawn a second time when it is sent.
3243
+ *
3244
+ * In skip mode (slice T8) `sendOrSkip` decides instead, and never pauses the pty.
3132
3245
  */
3133
3246
  sendData(terminalId, chunk) {
3134
3247
  const stream = this.streams.get(terminalId);
3135
3248
  if (!stream) return;
3249
+ if (this.skipsOutput(stream)) {
3250
+ this.sendOrSkip(terminalId, stream, chunk);
3251
+ return;
3252
+ }
3136
3253
  if (this.suspended) {
3137
3254
  stream.heldBundles.push(chunk);
3138
3255
  return;
@@ -3148,12 +3265,215 @@ var TerminalHandler = class {
3148
3265
  logger.debug("Terminal window full, reads paused", { terminal_id: terminalId });
3149
3266
  }
3150
3267
  }
3268
+ /** Skip mode applies: `welcome` asked for it, and the shell has a screen to resync with. */
3269
+ skipsOutput(stream) {
3270
+ return this.resyncEnabled && stream.mirror !== null;
3271
+ }
3272
+ /**
3273
+ * Skip mode (slice T8). A resync being serialised holds the bundle. A skipping stream, a socket that is
3274
+ * down, or a closed window skips it. Otherwise it goes out as `data`.
3275
+ */
3276
+ sendOrSkip(terminalId, stream, chunk) {
3277
+ if (stream.resyncInFlight) {
3278
+ this.holdDuringResync(terminalId, stream, chunk);
3279
+ } else if (stream.skipping || this.suspended || !stream.window.isOpen()) {
3280
+ this.skip(terminalId, stream, chunk);
3281
+ } else {
3282
+ this.transmit(terminalId, stream, chunk);
3283
+ }
3284
+ }
3285
+ /**
3286
+ * A bundle cut while a resync is serialised is not in its screen, so it waits and goes out after the
3287
+ * parts. Past the window size the held bundles are skipped instead, and the stream stays skipping.
3288
+ */
3289
+ holdDuringResync(terminalId, stream, chunk) {
3290
+ if (!stream.resyncOverflowed && stream.resyncHeldBytes + chunk.length <= (this.windowBytes ?? 0)) {
3291
+ stream.resyncHeldBundles.push(chunk);
3292
+ stream.resyncHeldBytes += chunk.length;
3293
+ return;
3294
+ }
3295
+ if (!stream.resyncOverflowed) {
3296
+ stream.resyncOverflowed = true;
3297
+ this.skipHeldDuringResync(terminalId, stream);
3298
+ }
3299
+ this.skip(terminalId, stream, chunk);
3300
+ }
3301
+ skipHeldDuringResync(terminalId, stream) {
3302
+ const held = stream.resyncHeldBundles.splice(0);
3303
+ stream.resyncHeldBytes = 0;
3304
+ for (const chunk of held) {
3305
+ this.skip(terminalId, stream, chunk);
3306
+ }
3307
+ }
3308
+ /** Into the screen, not onto the wire. It takes no seq, and the window never counts it. */
3309
+ skip(terminalId, stream, chunk) {
3310
+ stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
3311
+ stream.skippedBytes += chunk.length;
3312
+ if (!stream.skipping) {
3313
+ stream.skipping = true;
3314
+ logger.debug("Terminal output skipped until the tabs catch up", { terminal_id: terminalId });
3315
+ }
3316
+ this.brakeIfMirrorBehind(terminalId, stream);
3317
+ this.reportActivityWhileSkipping(terminalId, stream);
3318
+ }
3319
+ /** As T2's send, minus the pause: with the window closed, the next bundle is skipped instead. */
3320
+ transmit(terminalId, stream, chunk) {
3321
+ stream.sentSeq += 1;
3322
+ stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
3323
+ const data = { terminal_id: terminalId, data: chunk.toString("base64") };
3324
+ this.dependencies.send({ ...event(CHANNEL_TERMINAL, OP_DATA, data), seq: stream.sentSeq });
3325
+ stream.window.recordSent(chunk.length);
3326
+ this.brakeIfMirrorBehind(terminalId, stream);
3327
+ }
3328
+ /** The one pause in skip mode: the mirror's parser fell behind. Local CPU, never the network. */
3329
+ brakeIfMirrorBehind(terminalId, stream) {
3330
+ if (stream.mirrorPaused || !stream.mirror || stream.mirror.backlogBytes <= this.tuning.mirrorHighWaterBytes) return;
3331
+ stream.mirrorPaused = true;
3332
+ stream.session.pause();
3333
+ logger.debug("Terminal reads paused until the screen catches up", { terminal_id: terminalId });
3334
+ }
3335
+ mirrorParsed(terminalId, stream) {
3336
+ if (!stream.mirrorPaused || !stream.mirror || stream.mirror.backlogBytes > this.tuning.mirrorLowWaterBytes) return;
3337
+ stream.mirrorPaused = false;
3338
+ if (this.streams.get(terminalId) !== stream) return;
3339
+ try {
3340
+ stream.session.resume();
3341
+ } catch (err) {
3342
+ logger.debug("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
3343
+ }
3344
+ }
3345
+ /**
3346
+ * Skipped output never reaches the dashboard, so its sweep would see an idle shell. At most every
3347
+ * `ACTIVITY_REPORT_MILLIS` it hears that this one is busy.
3348
+ */
3349
+ reportActivityWhileSkipping(terminalId, stream) {
3350
+ if (this.suspended) return;
3351
+ const nowMillis = this.nowMillis();
3352
+ if (nowMillis - stream.lastActivityReportMillis < this.tuning.activityReportMillis) return;
3353
+ stream.lastActivityReportMillis = nowMillis;
3354
+ const activity = { terminal_id: terminalId, skipped_bytes: stream.skippedBytes };
3355
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_ACTIVITY, activity));
3356
+ }
3357
+ /**
3358
+ * Skip mode after `welcome`. A shell that skipped, or had bytes in flight, resyncs at once: frames in
3359
+ * flight died with the old socket, and the tab's ack of the resync's `after_bytes` stands in for theirs.
3360
+ */
3361
+ resumeSkipping(terminalId, stream, session) {
3362
+ stream.paused = false;
3363
+ for (const chunk of stream.heldBundles.splice(0)) {
3364
+ this.skip(terminalId, stream, chunk);
3365
+ }
3366
+ if (this.pausedBySuspend.has(terminalId) && !stream.mirrorPaused) {
3367
+ try {
3368
+ session.resume();
3369
+ } catch (err) {
3370
+ logger.warn("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
3371
+ }
3372
+ }
3373
+ if (stream.skipping || stream.window.sent > stream.window.acked) {
3374
+ void this.resync(terminalId, stream);
3375
+ }
3376
+ }
3377
+ /** Every sent byte is acked: the tabs have drawn everything they were sent. */
3378
+ static isDrained(stream) {
3379
+ return stream.window.acked >= stream.window.sent;
3380
+ }
3381
+ /**
3382
+ * A skipping stream resyncs once its window has drained, and no sooner than the interval after the
3383
+ * last resync. Not drained yet, it waits for the next `ack`.
3384
+ */
3385
+ scheduleResync(terminalId, stream) {
3386
+ if (!stream.skipping || stream.resyncInFlight || stream.resyncTimer || this.suspended || !_TerminalHandler.isDrained(stream)) return;
3387
+ const waitMillis = stream.lastResyncAtMillis + this.tuning.resyncMinIntervalMillis - this.nowMillis();
3388
+ if (waitMillis <= 0) {
3389
+ void this.resync(terminalId, stream);
3390
+ return;
3391
+ }
3392
+ stream.resyncTimer = setTimeout(() => {
3393
+ stream.resyncTimer = null;
3394
+ if (this.streams.get(terminalId) === stream) this.scheduleResync(terminalId, stream);
3395
+ }, waitMillis);
3396
+ stream.resyncTimer.unref();
3397
+ }
3398
+ /** Starts a resync, or returns the one already being serialised. */
3399
+ resync(terminalId, stream) {
3400
+ if (stream.resyncInFlight) return stream.resyncInFlight;
3401
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
3402
+ stream.resyncTimer = null;
3403
+ stream.resyncInFlight = this.serialiseAndSendResync(terminalId, stream);
3404
+ return stream.resyncInFlight;
3405
+ }
3406
+ /**
3407
+ * The latest screen to every tab (slice T8). `after_seq` and `after_bytes` are read before the mirror
3408
+ * is asked, as for a snapshot, and skipped bytes took neither: the screen holds the output up to
3409
+ * `after_seq` plus everything skipped. Serialised under the window size, so a resync never puts more in
3410
+ * flight than the window allows. Bundles held meanwhile go out after the parts, from `after_seq + 1`.
3411
+ */
3412
+ async serialiseAndSendResync(terminalId, stream) {
3413
+ stream.lastResyncAtMillis = this.nowMillis();
3414
+ stream.resyncOverflowed = false;
3415
+ const afterSeq = stream.sentSeq;
3416
+ const afterBytes = stream.window.sent;
3417
+ const skippedBytes = stream.skippedBytes;
3418
+ stream.skippedBytes = 0;
3419
+ const screen = stream.mirror ? await stream.mirror.snapshot(this.windowBytes) : null;
3420
+ stream.resyncInFlight = null;
3421
+ if (this.streams.get(terminalId) !== stream) return;
3422
+ if (this.suspended) {
3423
+ stream.skippedBytes += skippedBytes;
3424
+ this.skipHeldDuringResync(terminalId, stream);
3425
+ stream.resyncOverflowed = false;
3426
+ return;
3427
+ }
3428
+ if (screen && this.bundleBytes !== void 0) {
3429
+ const resyncId = randomUUID2();
3430
+ const parts = splitIntoParts(Buffer.from(screen.text, "utf-8"), this.bundleBytes);
3431
+ parts.forEach((part, index) => {
3432
+ const payload = {
3433
+ terminal_id: terminalId,
3434
+ resync_id: resyncId,
3435
+ part: index,
3436
+ last: index === parts.length - 1,
3437
+ after_seq: afterSeq,
3438
+ after_bytes: afterBytes,
3439
+ skipped_bytes: skippedBytes,
3440
+ cols: screen.cols,
3441
+ rows: screen.rows,
3442
+ data: part.toString("base64")
3443
+ };
3444
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_RESYNC, payload));
3445
+ });
3446
+ logger.debug("Terminal resynced", {
3447
+ terminal_id: terminalId,
3448
+ parts: parts.length,
3449
+ after_seq: afterSeq,
3450
+ skipped_bytes: skippedBytes
3451
+ });
3452
+ } else {
3453
+ logger.warn("Terminal resync dropped: the screen is too large to send", { terminal_id: terminalId });
3454
+ }
3455
+ if (stream.resyncOverflowed) {
3456
+ stream.resyncOverflowed = false;
3457
+ this.scheduleResync(terminalId, stream);
3458
+ return;
3459
+ }
3460
+ stream.skipping = false;
3461
+ const held = stream.resyncHeldBundles.splice(0);
3462
+ stream.resyncHeldBytes = 0;
3463
+ for (const chunk of held) {
3464
+ this.sendOrSkip(terminalId, stream, chunk);
3465
+ }
3466
+ }
3151
3467
  acknowledge(envelope) {
3152
3468
  const parsed = TerminalAckSchema.safeParse(envelope.payload);
3153
3469
  if (!parsed.success) return;
3154
3470
  const stream = this.streams.get(parsed.data.terminal_id);
3155
3471
  if (!stream) return;
3156
3472
  stream.window.recordAck(parsed.data.ack_bytes);
3473
+ if (this.skipsOutput(stream)) {
3474
+ this.scheduleResync(parsed.data.terminal_id, stream);
3475
+ return;
3476
+ }
3157
3477
  if (stream.paused && stream.window.isOpen()) {
3158
3478
  stream.paused = false;
3159
3479
  if (this.suspended) return;
@@ -3281,7 +3601,9 @@ var TerminalHandler = class {
3281
3601
  }
3282
3602
  /** A shell is gone. The context poll stops with the last one, so an idle agent spawns nothing. */
3283
3603
  forgetStream(terminalId) {
3284
- this.streams.get(terminalId)?.mirror?.dispose();
3604
+ const stream = this.streams.get(terminalId);
3605
+ if (stream?.resyncTimer) clearTimeout(stream.resyncTimer);
3606
+ stream?.mirror?.dispose();
3285
3607
  this.streams.delete(terminalId);
3286
3608
  this.contextTracker.forget(terminalId);
3287
3609
  if (this.streams.size === 0) this.stopContextTimer();
@@ -3298,7 +3620,7 @@ var TerminalHandler = class {
3298
3620
  }
3299
3621
  }
3300
3622
  startExpiryTimer() {
3301
- if (this.expiryTimer || this.idleTimeoutMillis === void 0 && this.maxSessionMillis === void 0) {
3623
+ if (this.expiryTimer || this.idleTimeoutMillis === void 0) {
3302
3624
  return;
3303
3625
  }
3304
3626
  this.expiryTimer = setInterval(() => this.expireShells(), EXPIRY_CHECK_MILLIS);
@@ -3668,14 +3990,17 @@ var AGENT_ERROR_UNAUTHORIZED = "unauthorized";
3668
3990
  var AGENT_ERROR_HANDSHAKE_REFUSED = "handshake_refused";
3669
3991
  var AGENT_ERROR_DISCONNECTED = "disconnected";
3670
3992
  var AGENT_ERROR_NOT_CONNECTED = "not_connected";
3993
+ var UNAUTHORIZED_STORED_TOKEN_MESSAGE = "The dashboard refused this machine's device token. The device was deleted, or its token was rotated. Sign this machine in again: pinggy device login";
3994
+ var UNAUTHORIZED_NEW_TOKEN_MESSAGE = "The dashboard refused this device token. Check the token, or copy the install command from the dashboard again.";
3671
3995
  var HANDSHAKE_TIMEOUT_MILLIS = 3e4;
3672
3996
  var PONG_GRACE_INTERVALS = 2;
3673
3997
  var BASE_CAPABILITIES = ["tunnel", "stats", "tunnel_control", "tunnel_update", "saved_config_update"];
3674
3998
  var CAPABILITY_TERMINAL = "terminal";
3675
3999
  var CAPABILITY_TERMINAL_SNAPSHOT = "terminal_snapshot";
4000
+ var CAPABILITY_TERMINAL_RESYNC = "terminal_resync";
3676
4001
  function buildCapabilities(terminalSupported, screenRestoreSupported = false) {
3677
4002
  if (!terminalSupported) return BASE_CAPABILITIES;
3678
- return screenRestoreSupported ? [...BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT] : [...BASE_CAPABILITIES, CAPABILITY_TERMINAL];
4003
+ return screenRestoreSupported ? [...BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC] : [...BASE_CAPABILITIES, CAPABILITY_TERMINAL];
3679
4004
  }
3680
4005
  function buildDeviceAgentWsUrl(manage) {
3681
4006
  let baseUrl = (manage || DEFAULT_SERVER).trim();
@@ -3730,9 +4055,7 @@ function startDeviceAgent(token, manage, options = {}) {
3730
4055
  const server = manage || DEFAULT_SERVER;
3731
4056
  const reporter = options.reporter ?? printingReporter;
3732
4057
  const stored = readDeviceIdentity();
3733
- if (stored?.device_agent_id && stored.token !== token) {
3734
- reporter.replacingDevice(stored.device_agent_id);
3735
- }
4058
+ const usesStoredToken = stored?.token === token;
3736
4059
  const connection = { send: null, close: null };
3737
4060
  const context = {
3738
4061
  wsUrl: buildDeviceAgentWsUrl(manage),
@@ -3752,7 +4075,9 @@ function startDeviceAgent(token, manage, options = {}) {
3752
4075
  reporter,
3753
4076
  writeIdentity: options.writeIdentity ?? writeDeviceIdentity,
3754
4077
  options,
3755
- state: { stopRequested: false, cancelPendingSleep: null, error: null, welcomed: false }
4078
+ state: { stopRequested: false, cancelPendingSleep: null, error: null, welcomed: false },
4079
+ usesStoredToken,
4080
+ replacedDeviceAgentId: usesStoredToken ? null : stored?.device_agent_id ?? null
3756
4081
  };
3757
4082
  const done = runLoop(context);
3758
4083
  return {
@@ -3909,7 +4234,7 @@ function connectOnce(context) {
3909
4234
  welcome.terminal_window_bytes,
3910
4235
  welcome.max_frame_bytes,
3911
4236
  welcome.terminal_idle_timeout_seconds,
3912
- welcome.terminal_max_session_seconds
4237
+ welcome.terminal_resync
3913
4238
  );
3914
4239
  terminalHandler.resumeAll();
3915
4240
  startHeartbeat(welcome.heartbeat_interval_seconds);
@@ -3949,10 +4274,10 @@ function connectOnce(context) {
3949
4274
  if (res.statusCode === 401) {
3950
4275
  finish(fail(context, {
3951
4276
  code: AGENT_ERROR_UNAUTHORIZED,
3952
- message: "Unauthorized. This device token is not valid. Re-enrol this machine with: pinggy device login"
4277
+ message: context.usesStoredToken ? UNAUTHORIZED_STORED_TOKEN_MESSAGE : UNAUTHORIZED_NEW_TOKEN_MESSAGE
3953
4278
  }));
3954
4279
  } else {
3955
- reporter.warn(`Unexpected HTTP ${res.statusCode}.`);
4280
+ reporter.warn(`The dashboard answered HTTP ${res.statusCode}.`);
3956
4281
  finish("retry");
3957
4282
  }
3958
4283
  ws.close();
@@ -3963,7 +4288,7 @@ function connectOnce(context) {
3963
4288
  });
3964
4289
  ws.on("error", (err) => {
3965
4290
  logger.warn("Device agent socket error", { error: err.message });
3966
- if (!state.stopRequested) {
4291
+ if (!state.stopRequested && !settled) {
3967
4292
  reporter.warn(err.message);
3968
4293
  }
3969
4294
  finish("retry");
@@ -3997,6 +4322,10 @@ function handleFrame(envelope, context, onWelcome) {
3997
4322
  identity.enrolled_at = identity.enrolled_at ?? (/* @__PURE__ */ new Date()).toISOString();
3998
4323
  context.writeIdentity(identity);
3999
4324
  context.state.welcomed = true;
4325
+ if (context.replacedDeviceAgentId) {
4326
+ reporter.replacingDevice(context.replacedDeviceAgentId);
4327
+ context.replacedDeviceAgentId = null;
4328
+ }
4000
4329
  reporter.connected(welcome.data);
4001
4330
  onWelcome(welcome.data);
4002
4331
  return "retry";
@@ -4035,6 +4364,7 @@ function describeDisconnect(reason) {
4035
4364
 
4036
4365
  // src/devices/login/deviceLogin.ts
4037
4366
  import os9 from "os";
4367
+ import pico4 from "picocolors";
4038
4368
 
4039
4369
  // src/devices/login/login_schema.ts
4040
4370
  import { z as z3 } from "zod";
@@ -4142,20 +4472,22 @@ async function readJson(response2) {
4142
4472
  }
4143
4473
 
4144
4474
  // src/devices/login/prompts.ts
4475
+ import pico3 from "picocolors";
4145
4476
  import { createInterface } from "readline/promises";
4146
4477
  import { Writable } from "stream";
4478
+ var QUESTION_MARKER = pico3.cyan(pico3.bold("\u2192"));
4147
4479
  function createTerminalPrompter(input, output) {
4148
4480
  return {
4149
4481
  async ask(question, signal) {
4150
4482
  const readline = createInterface({ input, output, terminal: true });
4151
4483
  try {
4152
- return await readline.question(question, signal ? { signal } : {});
4484
+ return await readline.question(marked(question), signal ? { signal } : {});
4153
4485
  } finally {
4154
4486
  readline.close();
4155
4487
  }
4156
4488
  },
4157
4489
  async askHidden(question, signal) {
4158
- output.write(question);
4490
+ output.write(marked(question));
4159
4491
  const readline = createInterface({ input, output: discardingOutput(), terminal: true });
4160
4492
  try {
4161
4493
  const answer = await readline.question("", signal ? { signal } : {});
@@ -4171,6 +4503,9 @@ var terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
4171
4503
  function isInteractiveTerminal() {
4172
4504
  return process.stdin.isTTY === true;
4173
4505
  }
4506
+ function marked(question) {
4507
+ return `${QUESTION_MARKER} ${question}`;
4508
+ }
4174
4509
  function discardingOutput() {
4175
4510
  return new Writable({
4176
4511
  write(_chunk, _encoding, callback) {
@@ -4184,10 +4519,12 @@ var EXIT_OK = 0;
4184
4519
  var EXIT_FAILED = 1;
4185
4520
  var DEFAULT_SERVER2 = "dashboard.pinggy.io";
4186
4521
  var YES_ANSWER = /^y(es)?$/i;
4522
+ var RESULT_MARKER = pico4.green(pico4.bold("\u2192"));
4187
4523
  var SECONDS_PER_MINUTE = 60;
4188
4524
  var MILLIS_PER_SECOND2 = 1e3;
4189
4525
  var FIRST_SERVER_ERROR_STATUS = 500;
4190
4526
  var NO_TERMINAL_MESSAGE = "pinggy device login needs a terminal to type the email and the code. On a machine without one, add the device in the dashboard and run: pinggy device connect --token <TOKEN>";
4527
+ var ABORT_ERROR_NAME = "AbortError";
4191
4528
  function machineDeviceLoginDependencies() {
4192
4529
  return {
4193
4530
  createApi: (manage) => createDeviceLoginApi(manage),
@@ -4209,6 +4546,20 @@ function machineDeviceLoginDependencies() {
4209
4546
  };
4210
4547
  }
4211
4548
  async function runDeviceLogin(options, dependencies = machineDeviceLoginDependencies()) {
4549
+ try {
4550
+ return await signInAndRunAgent(options, dependencies);
4551
+ } catch (err) {
4552
+ if (!isCtrlCAtPrompt(err)) {
4553
+ throw err;
4554
+ }
4555
+ dependencies.print(pico4.yellow("Sign-in cancelled."));
4556
+ return EXIT_FAILED;
4557
+ }
4558
+ }
4559
+ function isCtrlCAtPrompt(err) {
4560
+ return err instanceof Error && err.name === ABORT_ERROR_NAME;
4561
+ }
4562
+ async function signInAndRunAgent(options, dependencies) {
4212
4563
  if (!dependencies.isInteractive()) {
4213
4564
  dependencies.printError(NO_TERMINAL_MESSAGE);
4214
4565
  return EXIT_FAILED;
@@ -4220,7 +4571,7 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
4220
4571
  `This machine is already enrolled as ${stored.device_agent_id ?? "a device"} on ${stored.server}. Add it again as a new device? [y/N] `
4221
4572
  );
4222
4573
  if (!YES_ANSWER.test(answer.trim())) {
4223
- return await dependencies.runAgent(stored.token, manage) ?? EXIT_OK;
4574
+ return await dependencies.runAgent(stored.token, manage, false) ?? EXIT_OK;
4224
4575
  }
4225
4576
  }
4226
4577
  const email = (await dependencies.prompter.ask("Email: ")).trim();
@@ -4239,13 +4590,12 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
4239
4590
  ...options.name ? { name: options.name } : {}
4240
4591
  });
4241
4592
  linkMinutes = Math.round(started.expires_in_seconds / SECONDS_PER_MINUTE);
4242
- dependencies.print(`We sent a 6-digit code to ${email}. It works for ${linkMinutes} minutes.`);
4243
- if (started.match_code) {
4244
- dependencies.print("Type it below, or click Approve sign-in in the email.");
4245
- dependencies.print(`If you use the email: approve only if the page shows ${started.match_code}. A different code is someone else's sign-in.`);
4246
- }
4593
+ printCodeSent(email, started.match_code, dependencies);
4247
4594
  approved = await waitForApproval(api, started.device_code, started.poll_interval_seconds, dependencies);
4248
4595
  } catch (err) {
4596
+ if (isCtrlCAtPrompt(err)) {
4597
+ throw err;
4598
+ }
4249
4599
  dependencies.printError(messageOf(err, manage));
4250
4600
  return EXIT_FAILED;
4251
4601
  }
@@ -4259,9 +4609,19 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
4259
4609
  server: manage || DEFAULT_SERVER2,
4260
4610
  enrolled_at: null
4261
4611
  });
4262
- dependencies.print(`Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
4612
+ dependencies.print(`${RESULT_MARKER} Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
4263
4613
  await printDeviceLink(approved, linkMinutes, dependencies);
4264
- return await dependencies.runAgent(approved.token, manage) ?? EXIT_OK;
4614
+ return await dependencies.runAgent(approved.token, manage, true) ?? EXIT_OK;
4615
+ }
4616
+ function printCodeSent(email, matchCode, dependencies) {
4617
+ dependencies.print("");
4618
+ if (matchCode) {
4619
+ dependencies.print(`Device Code: ${pico4.bold(pico4.yellow(matchCode))}`);
4620
+ dependencies.print("");
4621
+ }
4622
+ dependencies.print(`We have sent a 6-digit code to ${email}.`);
4623
+ dependencies.print(matchCode ? "Enter the code below or click the approve button in the email." : "Enter the code below.");
4624
+ dependencies.print("");
4265
4625
  }
4266
4626
  async function waitForApproval(api, deviceCode, pollIntervalSeconds, dependencies) {
4267
4627
  const controller = new AbortController();
@@ -4309,7 +4669,7 @@ async function typeTheCode(api, deviceCode, signal, prompt, dependencies) {
4309
4669
  }
4310
4670
  }
4311
4671
  if (answer.status === LoginStatus.Pending) {
4312
- dependencies.print("Approved from the email link. Waiting for the dashboard to finish.");
4672
+ dependencies.print(pico4.cyanBright("Approved from the email link. Waiting for the dashboard to finish..."));
4313
4673
  return waitUntilAborted(signal);
4314
4674
  }
4315
4675
  if (answer.status !== LoginStatus.Approved) {
@@ -4353,16 +4713,17 @@ async function pollUntilApproved(api, deviceCode, intervalMillis, signal, depend
4353
4713
  }
4354
4714
  async function printDeviceLink(approved, linkMinutes, dependencies) {
4355
4715
  let link;
4716
+ let label;
4356
4717
  if (approved.open_url) {
4357
4718
  link = approved.open_url;
4358
- dependencies.print(`Open the device in a browser. This link signs you in once, within ${linkMinutes} minutes:`);
4719
+ label = `Open the device in a browser. This link signs you in once, within ${linkMinutes} minutes:`;
4359
4720
  } else if (approved.device_url) {
4360
4721
  link = approved.device_url;
4361
- dependencies.print("Open the device in a browser:");
4722
+ label = "Open the device in a browser:";
4362
4723
  } else {
4363
4724
  return;
4364
4725
  }
4365
- dependencies.print(` ${link}`);
4726
+ printDeviceUrl((message) => dependencies.print(message), label, link);
4366
4727
  try {
4367
4728
  dependencies.print(await dependencies.renderQr(link));
4368
4729
  } catch {
@@ -4408,6 +4769,12 @@ function sleepUnlessAborted(millis, signal) {
4408
4769
  // src/devices/backgroundAgent.ts
4409
4770
  var POLL_INTERVAL_MILLIS = 500;
4410
4771
  var CONNECT_WAIT_MILLIS = 15e3;
4772
+ var MANAGE_COMMANDS = [
4773
+ ["pinggy device status", "Show this device, and whether its agent runs"],
4774
+ ["pinggy device stop", "Stop the agent. The device shows offline"],
4775
+ ["pinggy device connect", "Start the agent again, after a stop or a reboot"],
4776
+ ["pinggy device remove", "Forget this machine's credential"]
4777
+ ];
4411
4778
  var verifyingReporter = {
4412
4779
  connecting: () => void 0,
4413
4780
  connected: () => void 0,
@@ -4461,7 +4828,7 @@ async function readBackgroundAgent(dependencies) {
4461
4828
  return null;
4462
4829
  }
4463
4830
  }
4464
- async function startAgentInBackground(target, dependencies) {
4831
+ async function startAgentInBackground(target, dependencies, options = {}) {
4465
4832
  if (differsFromStored(target, dependencies.readIdentity())) {
4466
4833
  const verified = await dependencies.verify(target.token, target.manage);
4467
4834
  if (verified.error || !verified.welcomed) {
@@ -4469,7 +4836,6 @@ async function startAgentInBackground(target, dependencies) {
4469
4836
  return EXIT_FAILED;
4470
4837
  }
4471
4838
  }
4472
- dependencies.print("Starting the device agent in the background.");
4473
4839
  let daemon;
4474
4840
  try {
4475
4841
  daemon = await dependencies.ensureDaemon();
@@ -4488,12 +4854,14 @@ async function startAgentInBackground(target, dependencies) {
4488
4854
  dependencies.printError(daemonFailureMessage(err, daemon));
4489
4855
  return EXIT_FAILED;
4490
4856
  }
4491
- return waitUntilConnected(client, daemon, dependencies);
4857
+ printManageCommands(dependencies);
4858
+ dependencies.print(pico5.cyanBright("Starting the device agent in the background..."));
4859
+ return waitUntilConnected(client, daemon, options, dependencies);
4492
4860
  }
4493
4861
  async function stopAgentInBackground(dependencies) {
4494
4862
  const reading = await readBackgroundAgent(dependencies);
4495
4863
  if (!reading || !isAgentRunning(reading.status)) {
4496
- dependencies.print("No device agent is running in the background.");
4864
+ dependencies.print(pico5.yellow("No device agent is running in the background."));
4497
4865
  return EXIT_OK;
4498
4866
  }
4499
4867
  if (!await stopReadAgent(reading, dependencies)) {
@@ -4567,7 +4935,16 @@ function daemonFailureMessage(err, daemon) {
4567
4935
  }
4568
4936
  return `Could not reach the daemon: ${errorMessage(err)}`;
4569
4937
  }
4570
- async function waitUntilConnected(client, daemon, dependencies) {
4938
+ function printManageCommands(dependencies) {
4939
+ const commandWidth = Math.max(...MANAGE_COMMANDS.map(([command]) => command.length));
4940
+ dependencies.print("");
4941
+ dependencies.print("Manage this device:");
4942
+ for (const [command, purpose] of MANAGE_COMMANDS) {
4943
+ dependencies.print(` ${pico5.cyan(command.padEnd(commandWidth))} ${purpose}`);
4944
+ }
4945
+ dependencies.print("");
4946
+ }
4947
+ async function waitUntilConnected(client, daemon, options, dependencies) {
4571
4948
  const deadline = dependencies.now() + CONNECT_WAIT_MILLIS;
4572
4949
  for (; ; ) {
4573
4950
  let status;
@@ -4578,7 +4955,7 @@ async function waitUntilConnected(client, daemon, dependencies) {
4578
4955
  return EXIT_FAILED;
4579
4956
  }
4580
4957
  if (status.state === DeviceAgentState.Connected) {
4581
- printRunning(status, daemon, dependencies);
4958
+ printRunning(status, daemon, options, dependencies);
4582
4959
  return EXIT_OK;
4583
4960
  }
4584
4961
  if (status.state === DeviceAgentState.Stopped) {
@@ -4592,20 +4969,18 @@ async function waitUntilConnected(client, daemon, dependencies) {
4592
4969
  await dependencies.sleep(POLL_INTERVAL_MILLIS);
4593
4970
  }
4594
4971
  }
4595
- function printRunning(status, daemon, dependencies) {
4972
+ function printRunning(status, daemon, options, dependencies) {
4596
4973
  dependencies.printSuccess(`Running in the background as device ${status.deviceAgentId}`);
4597
- if (status.email) {
4974
+ if (status.email && !options.signInShown) {
4598
4975
  dependencies.print(`Signed in as ${status.email}`);
4599
4976
  }
4600
- if (status.deviceUrl) {
4601
- dependencies.print("Open the device in a browser:");
4602
- dependencies.print(` ${status.deviceUrl}`);
4977
+ if (status.deviceUrl && !options.signInShown) {
4978
+ printDeviceUrl((message) => dependencies.print(message), "Open the device in a browser:", status.deviceUrl);
4603
4979
  }
4604
4980
  if (daemon.host === DaemonHost.APP) {
4605
- dependencies.print("It runs inside the Pinggy app, and stops when the app quits.");
4981
+ dependencies.print(pico5.gray("It runs inside the Pinggy app, and stops when the app quits."));
4606
4982
  }
4607
- dependencies.print(`Logs: ${dependencies.daemonLogPath()}`);
4608
- dependencies.print("Stop it with: pinggy device stop");
4983
+ dependencies.print(pico5.gray(`Logs: ${dependencies.daemonLogPath()}`));
4609
4984
  }
4610
4985
 
4611
4986
  // src/cli/subcommand/handlers/daemonCommandsHandler.ts
@@ -4644,17 +5019,17 @@ async function handleDaemonStart() {
4644
5019
  printer_default.error(ipcMismatchMessage(info));
4645
5020
  process.exit(1);
4646
5021
  }
4647
- printer_default.print(pico2.yellow(`Daemon already running (PID ${info.pid}, port ${info.port}). Use: pinggy daemon status for details.`));
5022
+ printer_default.print(pico6.yellow(`Daemon already running (PID ${info.pid}, port ${info.port}). Use: pinggy daemon status for details.`));
4648
5023
  return;
4649
5024
  }
4650
5025
  const autoConfigs = getAutoStartConfigs();
4651
5026
  if (autoConfigs.length > 0) {
4652
- printer_default.print(pico2.cyanBright(`Starting daemon with ${autoConfigs.length} auto-start tunnel(s):`));
5027
+ printer_default.print(pico6.cyanBright(`Starting daemon with ${autoConfigs.length} auto-start tunnel(s):`));
4653
5028
  for (const c of autoConfigs) {
4654
- printer_default.print(` ${pico2.bold(c.name)} (${c.configId.slice(0, 8)})`);
5029
+ printer_default.print(` ${pico6.bold(c.name)} (${c.configId.slice(0, 8)})`);
4655
5030
  }
4656
5031
  } else {
4657
- printer_default.print(pico2.cyanBright("Starting daemon..."));
5032
+ printer_default.print(pico6.cyanBright("Starting daemon..."));
4658
5033
  }
4659
5034
  try {
4660
5035
  const info2 = await startDaemon();
@@ -4666,7 +5041,7 @@ async function handleDaemonStart() {
4666
5041
  }
4667
5042
  async function handleDaemonStop() {
4668
5043
  if (!isDaemonRunning()) {
4669
- printer_default.print(pico2.yellow("No daemon is running."));
5044
+ printer_default.print(pico6.yellow("No daemon is running."));
4670
5045
  return;
4671
5046
  }
4672
5047
  const agent = await readBackgroundAgent(machineBackgroundAgentDependencies());
@@ -4677,7 +5052,7 @@ async function handleDaemonStop() {
4677
5052
  printer_default.print("The background device agent stopped too. The device shows offline in the dashboard.");
4678
5053
  }
4679
5054
  } else if (result.reason === DaemonHost.APP) {
4680
- printer_default.print(pico2.yellow("The Pinggy daemon is running inside the Pinggy desktop app. Please quit the Pinggy app to stop it."));
5055
+ printer_default.print(pico6.yellow("The Pinggy daemon is running inside the Pinggy desktop app. Please quit the Pinggy app to stop it."));
4681
5056
  } else {
4682
5057
  printer_default.error(result.error);
4683
5058
  }
@@ -4685,7 +5060,7 @@ async function handleDaemonStop() {
4685
5060
  async function handleDaemonStatus() {
4686
5061
  const info = getDaemonInfo();
4687
5062
  if (!info) {
4688
- printer_default.print(pico2.yellow("No daemon is running. Start with: pinggy daemon start"));
5063
+ printer_default.print(pico6.yellow("No daemon is running. Start with: pinggy daemon start"));
4689
5064
  return;
4690
5065
  }
4691
5066
  const uptimeSec = Math.floor((Date.now() - new Date(info.startedAt).getTime()) / 1e3);
@@ -4693,7 +5068,7 @@ async function handleDaemonStatus() {
4693
5068
  const m = Math.floor(uptimeSec % 3600 / 60);
4694
5069
  const s = uptimeSec % 60;
4695
5070
  const uptimeStr = h > 0 ? `${h}h ${m}m ${s}s` : m > 0 ? `${m}m ${s}s` : `${s}s`;
4696
- printer_default.print(pico2.cyanBright("Daemon Status"));
5071
+ printer_default.print(pico6.cyanBright("Daemon Status"));
4697
5072
  printer_default.print(` PID: ${info.pid}`);
4698
5073
  printer_default.print(` Port: ${info.port}`);
4699
5074
  printer_default.print(` Started: ${info.startedAt}`);
@@ -4701,7 +5076,7 @@ async function handleDaemonStatus() {
4701
5076
  printer_default.print(` Host: ${info.host === DaemonHost.APP ? "Pinggy app (in-process)" : "standalone (CLI)"}`);
4702
5077
  printer_default.print(` IPC: v${daemonIpcVersion(info)}`);
4703
5078
  if (!isIpcCompatible(info)) {
4704
- printer_default.print(pico2.yellow(` Warning: ${ipcMismatchMessage(info)}`));
5079
+ printer_default.print(pico6.yellow(` Warning: ${ipcMismatchMessage(info)}`));
4705
5080
  }
4706
5081
  const agent = await readBackgroundAgent(machineBackgroundAgentDependencies());
4707
5082
  if (agent) {
@@ -4710,7 +5085,7 @@ async function handleDaemonStatus() {
4710
5085
  }
4711
5086
 
4712
5087
  // src/cli/subcommand/handlers/psCommand.ts
4713
- import pico3 from "picocolors";
5088
+ import pico7 from "picocolors";
4714
5089
  async function handlePs() {
4715
5090
  const client = new TunnelClient();
4716
5091
  try {
@@ -4730,17 +5105,17 @@ async function handlePs() {
4730
5105
  return;
4731
5106
  }
4732
5107
  const header = `${pad("ID", 14)} ${pad("NAME", 16)} ${pad("STATUS", 10)} ${pad("LOCAL", 20)} URL`;
4733
- printer_default.print(pico3.gray(header));
4734
- printer_default.print(pico3.gray("\u2500".repeat(90)));
5108
+ printer_default.print(pico7.gray(header));
5109
+ printer_default.print(pico7.gray("\u2500".repeat(90)));
4735
5110
  for (const t of tunnels) {
4736
5111
  const id = t.tunnelid.slice(0, 12);
4737
5112
  const name = t.tunnelconfig?.name || "-";
4738
5113
  const status = t.status.state;
4739
5114
  const local = getLocalAddress(t.tunnelconfig);
4740
5115
  const url = t.remoteurls?.[0] || "-";
4741
- const statusColor = status === "running" ? pico3.green : status === "starting" ? pico3.yellow : pico3.red;
5116
+ const statusColor = status === "running" ? pico7.green : status === "starting" ? pico7.yellow : pico7.red;
4742
5117
  printer_default.print(
4743
- `${pico3.cyan(pad(id, 14))} ${pad(name, 16)} ${statusColor(pad(status, 10))} ${pad(local, 20)} ${pico3.magentaBright(url)}`
5118
+ `${pico7.cyan(pad(id, 14))} ${pad(name, 16)} ${statusColor(pad(status, 10))} ${pad(local, 20)} ${pico7.magentaBright(url)}`
4744
5119
  );
4745
5120
  }
4746
5121
  } catch (err) {
@@ -4812,7 +5187,7 @@ function resolveTargets(tunnels, args) {
4812
5187
  }
4813
5188
 
4814
5189
  // src/cli/subcommand/handlers/attachCommand.ts
4815
- import pico4 from "picocolors";
5190
+ import pico8 from "picocolors";
4816
5191
  async function handleAttach(args) {
4817
5192
  if (args.length === 0) {
4818
5193
  printer_default.error("Usage: pinggy attach <name|id>");
@@ -4840,14 +5215,14 @@ async function handleAttach(args) {
4840
5215
  }
4841
5216
  const tunnelId = match.tunnelid;
4842
5217
  const name = match.tunnelconfig?.name || tunnelId.slice(0, 12);
4843
- printer_default.print(pico4.cyanBright(`Attaching to tunnel "${name}"...`));
5218
+ printer_default.print(pico8.cyanBright(`Attaching to tunnel "${name}"...`));
4844
5219
  const attachMode = match.mode ?? "detached";
4845
5220
  await client.attach(tunnelId, attachMode);
4846
5221
  const urls = match.remoteurls || [];
4847
5222
  if (urls.length > 0) {
4848
5223
  printer_default.print("");
4849
5224
  for (const url of urls) {
4850
- printer_default.print(" " + pico4.magentaBright(url));
5225
+ printer_default.print(" " + pico8.magentaBright(url));
4851
5226
  }
4852
5227
  printer_default.print("");
4853
5228
  }
@@ -5083,7 +5458,7 @@ async function handleRestart(args) {
5083
5458
  }
5084
5459
 
5085
5460
  // src/cli/subcommand/handlers/deviceCommand.ts
5086
- import pico5 from "picocolors";
5461
+ import pico9 from "picocolors";
5087
5462
  var DeviceVerb = {
5088
5463
  Login: "login",
5089
5464
  Connect: "connect",
@@ -5119,7 +5494,11 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
5119
5494
  const flagArgs = args.slice(1);
5120
5495
  const { values } = parseCliArgs(cliOptions, flagArgs);
5121
5496
  configureLogger(values);
5122
- const inBackground = Boolean(values.b);
5497
+ if (values.b && values.foreground) {
5498
+ printer_default.error("-b and --foreground contradict each other. The agent runs in the background unless --foreground is given.");
5499
+ process.exit(1);
5500
+ }
5501
+ const inBackground = !values.foreground;
5123
5502
  switch (verb) {
5124
5503
  case DeviceVerb.Login:
5125
5504
  exitUnlessOk(await handleDeviceLogin(values.manage, values.name, inBackground, background));
@@ -5180,7 +5559,7 @@ async function handleDeviceLogin(manage, name, inBackground, background) {
5180
5559
  }
5181
5560
  return runDeviceLogin({ manage, name }, {
5182
5561
  ...machineDeviceLoginDependencies(),
5183
- runAgent: (token, agentManage) => startAgentInBackground({ token, manage: agentManage }, background)
5562
+ runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
5184
5563
  });
5185
5564
  }
5186
5565
  async function handleDeviceConnect(flagToken, environmentToken, manage, inBackground, background) {
@@ -5199,13 +5578,13 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
5199
5578
  async function handleDeviceStatus(background) {
5200
5579
  const identity = background.readIdentity();
5201
5580
  if (!identity) {
5202
- printer_default.print("This machine is not enrolled. Run: pinggy device login");
5581
+ printer_default.print(pico9.yellow("This machine is not enrolled. Run: pinggy device login"));
5203
5582
  return;
5204
5583
  }
5205
- printer_default.print(` Device id ${identity.device_agent_id ?? pico5.gray("not yet assigned")}`);
5584
+ printer_default.print(` Device id ${identity.device_agent_id ?? pico9.gray("not yet assigned")}`);
5206
5585
  printer_default.print(` Server ${identity.server}`);
5207
5586
  printer_default.print(` Token ${maskToken(identity.token)}`);
5208
- printer_default.print(` Enrolled ${identity.enrolled_at ?? pico5.gray("never")}`);
5587
+ printer_default.print(` Enrolled ${identity.enrolled_at ?? pico9.gray("never")}`);
5209
5588
  await printBackgroundStatus(background);
5210
5589
  }
5211
5590
  async function handleDeviceRemove(background) {
@@ -5214,9 +5593,9 @@ async function handleDeviceRemove(background) {
5214
5593
  }
5215
5594
  if (clearDeviceIdentity()) {
5216
5595
  printer_default.success("Local device credential removed.");
5217
- printer_default.print(pico5.gray("The device still exists in the dashboard. Delete it there to revoke it."));
5596
+ printer_default.print(pico9.gray("The device still exists in the dashboard. Delete it there to revoke it."));
5218
5597
  } else {
5219
- printer_default.print("This machine is not enrolled.");
5598
+ printer_default.print(pico9.yellow("This machine is not enrolled."));
5220
5599
  }
5221
5600
  return EXIT_OK;
5222
5601
  }
@@ -6711,7 +7090,7 @@ async function main() {
6711
7090
  const { values, positionals, hasAnyArgs } = parseCliArgs(cliOptions);
6712
7091
  configureLogger(values);
6713
7092
  if (values["_daemon-child"]) {
6714
- const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-E73NFWKE.js");
7093
+ const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-WHS676G4.js");
6715
7094
  await runDaemonChild2();
6716
7095
  return;
6717
7096
  }