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/dist/index.cjs CHANGED
@@ -3151,6 +3151,8 @@ var init_options = __esm({
3151
3151
  // Background mode (run tunnel in background via daemon)
3152
3152
  b: { type: "boolean", description: "Run tunnel in background via daemon. CLI exits after tunnel starts." },
3153
3153
  all: { type: "boolean", description: "Start all auto-start tunnels" },
3154
+ // `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
3155
+ foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
3154
3156
  // Internal daemon child marker
3155
3157
  "_daemon-child": { type: "boolean", description: "Internal: daemon child process marker", hidden: true },
3156
3158
  // Misc
@@ -3223,6 +3225,11 @@ function printHelpMessage() {
3223
3225
  console.log("\nBackground Mode:");
3224
3226
  console.log(" pinggy -l 3000 --b # Start tunnel in background");
3225
3227
  console.log(" pinggy start my-tunnel --b # Start saved tunnel in background");
3228
+ console.log("\nDevices (more: pinggy device --help):");
3229
+ console.log(" pinggy device login # Sign in by email. The agent runs in the background");
3230
+ console.log(" pinggy device login --foreground # Same, with the agent in this terminal");
3231
+ console.log(" pinggy device status # Show this device and its agent");
3232
+ console.log(" pinggy device stop # Stop the background agent");
3226
3233
  console.log("\nDaemon Lifecycle (also: pinggy d <command>):");
3227
3234
  console.log(" pinggy daemon start # Start the background daemon");
3228
3235
  console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
@@ -7630,14 +7637,17 @@ function printDeviceHelp() {
7630
7637
  console.log("\nUsage: pinggy device <command> [options]\n");
7631
7638
  console.log("Run this machine as a Pinggy device.\n");
7632
7639
  console.log("Commands:");
7633
- console.log(" login Sign this machine in with your email, then stay connected");
7634
- console.log(" connect --token <TOKEN> Enrol, then stay connected until interrupted");
7640
+ console.log(" login Sign this machine in with your email, then run the agent in the");
7641
+ console.log(" background");
7642
+ console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
7643
+ console.log(" background. Without --token: start the enrolled device's agent again");
7635
7644
  console.log(" stop Stop the agent running in the background");
7636
7645
  console.log(" status Show the enrolment, and the agent running in the background");
7637
7646
  console.log(" remove Forget the local credential (does not delete the device)\n");
7647
+ console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.\n");
7638
7648
  console.log("Options:");
7639
- console.log(" -b login and connect: run the agent in the background, in the daemon.");
7640
- console.log(" It stays connected after this terminal closes");
7649
+ console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
7650
+ console.log(" -b login and connect: run the agent in the background. The default");
7641
7651
  console.log(" --token <TOKEN> Device token from the dashboard");
7642
7652
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
7643
7653
  console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname\n");
@@ -7763,10 +7773,11 @@ var init_device_schema = __esm({
7763
7773
  max_terminals_per_device: import_zod3.z.number().optional(),
7764
7774
  // No default on the agent. Without it, terminals stay unavailable rather than unbraked.
7765
7775
  terminal_window_bytes: import_zod3.z.number().optional(),
7766
- // No default either. Without them the agent runs no expiry timers, and the dashboard's sweep
7767
- // still ends an expired shell, only later.
7776
+ // No default either. Without it the agent runs no expiry timer, and the dashboard's sweep
7777
+ // still ends an idle shell, only later. A shell has no cap on its running time.
7768
7778
  terminal_idle_timeout_seconds: import_zod3.z.number().optional(),
7769
- terminal_max_session_seconds: import_zod3.z.number().optional(),
7779
+ // Optional: without it the agent keeps T2's brake and never skips output (slice T8).
7780
+ terminal_resync: import_zod3.z.boolean().optional(),
7770
7781
  // Optional: a dashboard older than these sends neither, and the agent prints only the device id.
7771
7782
  email: import_zod3.z.string().optional(),
7772
7783
  device_url: import_zod3.z.string().optional()
@@ -7790,34 +7801,42 @@ var init_device_schema = __esm({
7790
7801
  });
7791
7802
 
7792
7803
  // src/devices/deviceAgentReporter.ts
7804
+ function printDeviceUrl(print, label, url) {
7805
+ print(label);
7806
+ print("");
7807
+ print(` ${import_picocolors6.default.magentaBright(url)}`);
7808
+ print("");
7809
+ }
7793
7810
  function printConnected(welcome) {
7794
7811
  printer_default.success(`Connected as device ${welcome.device_agent_id}`);
7795
7812
  if (welcome.email) {
7796
7813
  printer_default.print(`Signed in as ${welcome.email}`);
7797
7814
  }
7798
7815
  if (welcome.device_url) {
7799
- printer_default.print("Open the device in a browser:");
7800
- printer_default.print(` ${welcome.device_url}`);
7816
+ printDeviceUrl((message) => printer_default.print(message), "Open the device in a browser:", welcome.device_url);
7801
7817
  }
7802
7818
  }
7803
7819
  function formatSeconds(millis) {
7804
7820
  return (millis / 1e3).toFixed(1);
7805
7821
  }
7806
- var printingReporter;
7822
+ var import_picocolors6, printingReporter;
7807
7823
  var init_deviceAgentReporter = __esm({
7808
7824
  "src/devices/deviceAgentReporter.ts"() {
7809
7825
  "use strict";
7810
7826
  init_cjs_shims();
7827
+ import_picocolors6 = __toESM(require("picocolors"), 1);
7811
7828
  init_printer();
7812
7829
  printingReporter = {
7813
- connecting: (server) => printer_default.print(`Connecting to ${server}`),
7830
+ connecting: (server) => printer_default.print(import_picocolors6.default.cyanBright(`Connecting to ${server}...`)),
7814
7831
  connected: printConnected,
7815
7832
  reconnecting: (delayMillis, attempt) => printer_default.warn(
7816
7833
  `Disconnected. Reconnecting in ${formatSeconds(delayMillis)} seconds (attempt ${attempt}).`
7817
7834
  ),
7818
7835
  warn: (message) => printer_default.warn(message),
7819
7836
  failed: (error) => printer_default.error(error.message),
7820
- replacingDevice: (oldDeviceAgentId) => printer_default.print(`This machine was device ${oldDeviceAgentId}. Connecting it with the token from the command.`)
7837
+ replacingDevice: (oldDeviceAgentId) => printer_default.print(import_picocolors6.default.yellow(
7838
+ `This machine was device ${oldDeviceAgentId}. That device stays in the dashboard, offline.`
7839
+ ))
7821
7840
  };
7822
7841
  }
7823
7842
  });
@@ -8372,7 +8391,7 @@ function clampGrid(requested, fallback) {
8372
8391
  if (requested === void 0 || !Number.isFinite(requested)) return fallback;
8373
8392
  return Math.max(MIN_GRID, Math.min(MAX_GRID, Math.trunc(requested)));
8374
8393
  }
8375
- var import_zod4, CHANNEL_TERMINAL, OP_OPEN, OP_OPENED, OP_CLOSE, OP_DATA, OP_ACK, OP_EXIT, OP_RESIZE, OP_SIGNAL, OP_CONTEXT, OP_SNAPSHOT, TERMINAL_SIGNALS, MIN_GRID, MAX_GRID, CLOSE_REASON_USER_CLOSED, CLOSE_REASON_IDLE_TIMEOUT, CLOSE_REASON_MAX_SESSION, ERROR_INVALID_PAYLOAD2, ERROR_TERMINAL_LIMIT_REACHED, ERROR_TERMINAL_DISABLED, ERROR_SHELL_NOT_ALLOWED, ERROR_SPAWN_FAILED, TerminalOpenSchema, TerminalCloseSchema, TerminalResizeSchema, TerminalInputSchema, TerminalSignalSchema, TerminalAckSchema, TerminalSnapshotRequestSchema;
8394
+ var import_zod4, CHANNEL_TERMINAL, OP_OPEN, OP_OPENED, OP_CLOSE, OP_DATA, OP_ACK, OP_EXIT, OP_RESIZE, OP_SIGNAL, OP_CONTEXT, OP_SNAPSHOT, OP_RESYNC, OP_ACTIVITY, TERMINAL_SIGNALS, MIN_GRID, MAX_GRID, CLOSE_REASON_USER_CLOSED, CLOSE_REASON_IDLE_TIMEOUT, ERROR_INVALID_PAYLOAD2, ERROR_TERMINAL_LIMIT_REACHED, ERROR_TERMINAL_DISABLED, ERROR_SHELL_NOT_ALLOWED, ERROR_SPAWN_FAILED, TerminalOpenSchema, TerminalCloseSchema, TerminalResizeSchema, TerminalInputSchema, TerminalSignalSchema, TerminalAckSchema, TerminalSnapshotRequestSchema;
8376
8395
  var init_terminal_schema = __esm({
8377
8396
  "src/devices/terminal/terminal_schema.ts"() {
8378
8397
  "use strict";
@@ -8389,12 +8408,13 @@ var init_terminal_schema = __esm({
8389
8408
  OP_SIGNAL = "signal";
8390
8409
  OP_CONTEXT = "context";
8391
8410
  OP_SNAPSHOT = "snapshot";
8411
+ OP_RESYNC = "resync";
8412
+ OP_ACTIVITY = "activity";
8392
8413
  TERMINAL_SIGNALS = ["INT", "TERM", "QUIT", "HUP"];
8393
8414
  MIN_GRID = 1;
8394
8415
  MAX_GRID = 1e3;
8395
8416
  CLOSE_REASON_USER_CLOSED = "user_closed";
8396
8417
  CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
8397
- CLOSE_REASON_MAX_SESSION = "max_session";
8398
8418
  ERROR_INVALID_PAYLOAD2 = "invalid_payload";
8399
8419
  ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
8400
8420
  ERROR_TERMINAL_DISABLED = "terminal_disabled";
@@ -8775,6 +8795,7 @@ var init_screenMirror = __esm({
8775
8795
  this.terminal = terminal;
8776
8796
  this.serializer = serializer;
8777
8797
  this.disposed = false;
8798
+ this.unparsedBytes = 0;
8778
8799
  }
8779
8800
  /** Null when the headless terminal cannot load. The shell then works as before, without restore. */
8780
8801
  static create(cols, rows) {
@@ -8785,28 +8806,45 @@ var init_screenMirror = __esm({
8785
8806
  terminal.loadAddon(serializer);
8786
8807
  return new _ScreenMirror(terminal, serializer);
8787
8808
  }
8788
- /** Bytes exactly as they were sent. xterm parses them later, in order, and joins split characters. */
8789
- feed(bytes) {
8790
- if (!this.disposed) this.terminal.write(bytes);
8809
+ /**
8810
+ * Bytes exactly as they were sent or skipped. xterm parses them later, in order, and joins split
8811
+ * characters. `onParsed` runs once they are parsed, when {@link backlogBytes} has already dropped by them.
8812
+ */
8813
+ feed(bytes, onParsed) {
8814
+ if (this.disposed) return;
8815
+ const byteCount = bytes.length;
8816
+ this.unparsedBytes += byteCount;
8817
+ this.terminal.write(bytes, () => {
8818
+ this.unparsedBytes -= byteCount;
8819
+ onParsed?.();
8820
+ });
8821
+ }
8822
+ /**
8823
+ * Fed and not yet parsed. xterm queues writes without limit, so a shell that skips its output
8824
+ * (slice T8) pauses on this, and on nothing else.
8825
+ */
8826
+ get backlogBytes() {
8827
+ return this.unparsedBytes;
8791
8828
  }
8792
8829
  resize(cols, rows) {
8793
8830
  if (!this.disposed) this.terminal.resize(cols, rows);
8794
8831
  }
8795
8832
  /**
8796
- * The screen after everything fed before this call, and nothing fed after it. Null when the
8797
- * mirror was disposed first.
8833
+ * The screen after everything fed before this call, and nothing fed after it, serialised under
8834
+ * `maxBytes`. Null when the mirror was disposed first, or when even the screen alone is over
8835
+ * {@link MAX_SNAPSHOT_BYTES}.
8798
8836
  *
8799
8837
  * xterm parses writes in batches, on a timer. An empty write queued now has its callback run
8800
8838
  * after every earlier chunk is parsed and before the next one is, so serialising inside it sees
8801
8839
  * exactly what was fed before this call.
8802
8840
  */
8803
- snapshot() {
8841
+ snapshot(maxBytes = MAX_SNAPSHOT_BYTES) {
8804
8842
  return new Promise((resolve) => {
8805
8843
  if (this.disposed) {
8806
8844
  resolve(null);
8807
8845
  return;
8808
8846
  }
8809
- this.terminal.write("", () => resolve(this.disposed ? null : this.serialise()));
8847
+ this.terminal.write("", () => resolve(this.disposed ? null : this.serialise(maxBytes)));
8810
8848
  });
8811
8849
  }
8812
8850
  dispose() {
@@ -8814,14 +8852,24 @@ var init_screenMirror = __esm({
8814
8852
  this.disposed = true;
8815
8853
  this.terminal.dispose();
8816
8854
  }
8817
- /** Null when even the screen alone is over the cap. The tab then waits out its fallback. */
8818
- serialise() {
8855
+ /**
8856
+ * Fewer lines of scrollback until the text fits `maxBytes`. A screen alone over a cap below
8857
+ * {@link MAX_SNAPSHOT_BYTES} is still sent under that: a resync over its cap beats a tab that never
8858
+ * catches up. Null when even the screen alone is over {@link MAX_SNAPSHOT_BYTES}.
8859
+ */
8860
+ serialise(maxBytes) {
8819
8861
  for (const scrollback of SCROLLBACK_LINES_TO_TRY) {
8820
8862
  const text = this.serializer.serialize({ scrollback });
8821
- if (Buffer.byteLength(text, "utf-8") <= MAX_SNAPSHOT_BYTES) {
8863
+ if (Buffer.byteLength(text, "utf-8") <= maxBytes) {
8822
8864
  return { text, cols: this.terminal.cols, rows: this.terminal.rows };
8823
8865
  }
8824
8866
  }
8867
+ if (maxBytes < MAX_SNAPSHOT_BYTES) {
8868
+ const screenOnly = this.serializer.serialize({ scrollback: 0 });
8869
+ if (Buffer.byteLength(screenOnly, "utf-8") <= MAX_SNAPSHOT_BYTES) {
8870
+ return { text: screenOnly, cols: this.terminal.cols, rows: this.terminal.rows };
8871
+ }
8872
+ }
8825
8873
  return null;
8826
8874
  }
8827
8875
  };
@@ -8848,11 +8896,12 @@ function signalName(signal) {
8848
8896
  }
8849
8897
  return String(signal);
8850
8898
  }
8851
- var import_os6, DEFAULT_COLS, DEFAULT_ROWS, EXPIRY_CHECK_MILLIS, MILLIS_PER_SECOND, TerminalHandler;
8899
+ var import_crypto3, import_os6, DEFAULT_COLS, DEFAULT_ROWS, EXPIRY_CHECK_MILLIS, MILLIS_PER_SECOND, RESYNC_MIN_INTERVAL_MILLIS, MIRROR_HIGH_WATER_BYTES, MIRROR_LOW_WATER_BYTES, ACTIVITY_REPORT_MILLIS, DEFAULT_SKIP_TUNING, TerminalHandler;
8852
8900
  var init_terminalHandler = __esm({
8853
8901
  "src/devices/terminal/terminalHandler.ts"() {
8854
8902
  "use strict";
8855
8903
  init_cjs_shims();
8904
+ import_crypto3 = require("crypto");
8856
8905
  import_os6 = __toESM(require("os"), 1);
8857
8906
  init_logger();
8858
8907
  init_envelope();
@@ -8865,16 +8914,31 @@ var init_terminalHandler = __esm({
8865
8914
  DEFAULT_ROWS = 24;
8866
8915
  EXPIRY_CHECK_MILLIS = 5e3;
8867
8916
  MILLIS_PER_SECOND = 1e3;
8868
- TerminalHandler = class {
8917
+ RESYNC_MIN_INTERVAL_MILLIS = 1e3;
8918
+ MIRROR_HIGH_WATER_BYTES = 1024 * 1024;
8919
+ MIRROR_LOW_WATER_BYTES = 256 * 1024;
8920
+ ACTIVITY_REPORT_MILLIS = 6e4;
8921
+ DEFAULT_SKIP_TUNING = {
8922
+ resyncMinIntervalMillis: RESYNC_MIN_INTERVAL_MILLIS,
8923
+ mirrorHighWaterBytes: MIRROR_HIGH_WATER_BYTES,
8924
+ mirrorLowWaterBytes: MIRROR_LOW_WATER_BYTES,
8925
+ activityReportMillis: ACTIVITY_REPORT_MILLIS
8926
+ };
8927
+ TerminalHandler = class _TerminalHandler {
8869
8928
  constructor(dependencies) {
8870
8929
  this.dependencies = dependencies;
8871
8930
  this.enabled = true;
8872
8931
  this.suspended = false;
8932
+ /** `terminal_resync` in `welcome` (slice T8). Off, every shell keeps T2's brake. */
8933
+ this.resyncEnabled = false;
8934
+ /** Paused by `suspend` under T2's brake, so `resumeAll` resumes them if `welcome` turned skip mode on. */
8935
+ this.pausedBySuspend = /* @__PURE__ */ new Set();
8873
8936
  this.expiryTimer = null;
8874
8937
  this.contextTimer = null;
8875
8938
  this.contextPollInFlight = false;
8876
8939
  this.contextTracker = new ShellContextTracker();
8877
8940
  this.streams = /* @__PURE__ */ new Map();
8941
+ this.tuning = { ...DEFAULT_SKIP_TUNING, ...dependencies.skipTuning };
8878
8942
  }
8879
8943
  /**
8880
8944
  * From welcome. An older dashboard sends no terminal fields, and `terminal_enabled` and the
@@ -8884,7 +8948,7 @@ var init_terminalHandler = __esm({
8884
8948
  * the field, and nobody notices until a node falls over, so an agent without one refuses to open
8885
8949
  * a terminal at all.
8886
8950
  */
8887
- configure(terminalEnabled, maxTerminalsPerDevice, terminalWindowBytes, maxFrameBytes, idleTimeoutSeconds, maxSessionSeconds) {
8951
+ configure(terminalEnabled, maxTerminalsPerDevice, terminalWindowBytes, maxFrameBytes, idleTimeoutSeconds, terminalResync) {
8888
8952
  if (terminalEnabled !== void 0) this.enabled = terminalEnabled;
8889
8953
  if (maxTerminalsPerDevice !== void 0) this.dependencies.registry.setMaxTerminals(maxTerminalsPerDevice);
8890
8954
  this.windowBytes = terminalWindowBytes;
@@ -8893,21 +8957,33 @@ var init_terminalHandler = __esm({
8893
8957
  logger.info("Terminals unavailable: welcome carried no terminal_window_bytes");
8894
8958
  }
8895
8959
  this.idleTimeoutMillis = positiveMillis(idleTimeoutSeconds);
8896
- this.maxSessionMillis = positiveMillis(maxSessionSeconds);
8960
+ this.setSkipMode(terminalResync === true);
8897
8961
  this.startExpiryTimer();
8898
8962
  }
8899
8963
  /**
8900
- * Ends every shell past its idle timeout or its max-session cap. Runs on a timer; public so a test
8901
- * decides when. The cap goes first: a shell both idle and too old is closed for the rule typing
8902
- * cannot reset.
8964
+ * `welcome` turned skip mode on or off. Off, a skipping shell stops skipping without a resync, since
8965
+ * this dashboard cannot route one, and its tabs miss what was skipped. `resumeAll` then sets the reads.
8903
8966
  */
8967
+ setSkipMode(enabled) {
8968
+ if (enabled === this.resyncEnabled) return;
8969
+ this.resyncEnabled = enabled;
8970
+ for (const stream of this.streams.values()) {
8971
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
8972
+ stream.resyncTimer = null;
8973
+ stream.skipping = false;
8974
+ stream.skippedBytes = 0;
8975
+ stream.resyncOverflowed = false;
8976
+ stream.resyncHeldBundles.splice(0);
8977
+ stream.resyncHeldBytes = 0;
8978
+ stream.mirrorPaused = false;
8979
+ }
8980
+ }
8981
+ /** Ends every shell past its idle timeout. Runs on a timer; public so a test decides when. */
8904
8982
  expireShells() {
8905
8983
  if (this.suspended) return;
8906
8984
  const nowMillis = this.nowMillis();
8907
8985
  for (const [terminalId, stream] of [...this.streams.entries()]) {
8908
- if (this.maxSessionMillis !== void 0 && nowMillis - stream.openedAtMillis >= this.maxSessionMillis) {
8909
- this.expire(terminalId, CLOSE_REASON_MAX_SESSION);
8910
- } else if (this.idleTimeoutMillis !== void 0 && nowMillis - stream.lastActivityMillis >= this.idleTimeoutMillis) {
8986
+ if (this.idleTimeoutMillis !== void 0 && nowMillis - stream.lastActivityMillis >= this.idleTimeoutMillis) {
8911
8987
  this.expire(terminalId, CLOSE_REASON_IDLE_TIMEOUT);
8912
8988
  }
8913
8989
  }
@@ -8941,22 +9017,28 @@ var init_terminalHandler = __esm({
8941
9017
  this.contextTracker.clear();
8942
9018
  this.suspended = false;
8943
9019
  for (const stream of this.streams.values()) {
9020
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
8944
9021
  stream.splitter.dispose();
8945
9022
  stream.mirror?.dispose();
8946
9023
  }
8947
9024
  this.streams.clear();
9025
+ this.pausedBySuspend.clear();
8948
9026
  this.dependencies.registry.killAll();
8949
9027
  }
8950
9028
  /**
8951
- * The socket dropped and the agent will redial. Every shell stops being read and keeps running.
8952
- * Whatever it prints waits in the kernel, and the shell blocks once that buffer is full.
9029
+ * The socket dropped and the agent will redial. Under T2's brake every shell stops being read and
9030
+ * keeps running: whatever it prints waits in the kernel, and the shell blocks once that buffer is
9031
+ * full. In skip mode (slice T8) a shell is read on, and its output is skipped.
8953
9032
  */
8954
9033
  suspend() {
8955
9034
  if (this.suspended) return;
8956
9035
  this.suspended = true;
8957
9036
  for (const [terminalId, session] of this.dependencies.registry.entries()) {
9037
+ const stream = this.streams.get(terminalId);
9038
+ if (stream && this.skipsOutput(stream)) continue;
8958
9039
  try {
8959
9040
  session.pause();
9041
+ this.pausedBySuspend.add(terminalId);
8960
9042
  } catch (err) {
8961
9043
  logger.warn("Terminal pause failed", { terminal_id: terminalId, error: errorName2(err) });
8962
9044
  }
@@ -8965,13 +9047,18 @@ var init_terminalHandler = __esm({
8965
9047
  }
8966
9048
  /**
8967
9049
  * `welcome` arrived. Every shell the dashboard did not close is read again, except one whose
8968
- * window is still full. That one resumes on the `ack` that reopens it.
9050
+ * window is still full. That one resumes on the `ack` that reopens it. A shell in skip mode was
9051
+ * never paused, and resyncs instead (slice T8).
8969
9052
  */
8970
9053
  resumeAll() {
8971
9054
  if (!this.suspended) return;
8972
9055
  this.suspended = false;
8973
9056
  for (const [terminalId, session] of this.dependencies.registry.entries()) {
8974
9057
  const stream = this.streams.get(terminalId);
9058
+ if (stream && this.skipsOutput(stream)) {
9059
+ this.resumeSkipping(terminalId, stream, session);
9060
+ continue;
9061
+ }
8975
9062
  if (stream) {
8976
9063
  for (const chunk of stream.heldBundles.splice(0)) {
8977
9064
  this.sendData(terminalId, chunk);
@@ -8984,6 +9071,7 @@ var init_terminalHandler = __esm({
8984
9071
  logger.warn("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
8985
9072
  }
8986
9073
  }
9074
+ this.pausedBySuspend.clear();
8987
9075
  for (const context of this.contextTracker.current()) {
8988
9076
  if (this.streams.has(context.terminal_id)) {
8989
9077
  this.dependencies.send(event(CHANNEL_TERMINAL, OP_CONTEXT, context));
@@ -9086,7 +9174,6 @@ var init_terminalHandler = __esm({
9086
9174
  this.dependencies.send(response(envelope, OP_OPENED, opened));
9087
9175
  }
9088
9176
  startStream(terminalId, session, windowBytes, bundleBytes) {
9089
- const openedAtMillis = this.nowMillis();
9090
9177
  const stream = {
9091
9178
  session,
9092
9179
  window: new FlowWindow(windowBytes),
@@ -9095,8 +9182,17 @@ var init_terminalHandler = __esm({
9095
9182
  paused: false,
9096
9183
  sentSeq: 0,
9097
9184
  heldBundles: [],
9098
- openedAtMillis,
9099
- lastActivityMillis: openedAtMillis
9185
+ lastActivityMillis: this.nowMillis(),
9186
+ skipping: false,
9187
+ skippedBytes: 0,
9188
+ lastResyncAtMillis: 0,
9189
+ resyncTimer: null,
9190
+ resyncInFlight: null,
9191
+ resyncHeldBundles: [],
9192
+ resyncHeldBytes: 0,
9193
+ resyncOverflowed: false,
9194
+ mirrorPaused: false,
9195
+ lastActivityReportMillis: 0
9100
9196
  };
9101
9197
  this.streams.set(terminalId, stream);
9102
9198
  this.startContextTimer();
@@ -9108,17 +9204,29 @@ var init_terminalHandler = __esm({
9108
9204
  if (this.dependencies.registry.remove(terminalId) === void 0) return;
9109
9205
  stream.splitter.flush();
9110
9206
  stream.splitter.dispose();
9111
- this.forgetStream(terminalId);
9112
- logger.info("Terminal shell exited", { terminal_id: terminalId, exit_code: exitCode, signal });
9113
- const exit = signal ? { terminal_id: terminalId, exit_code: null, signal: signalName(signal) } : { terminal_id: terminalId, exit_code: exitCode, signal: null };
9114
- this.dependencies.send(event(CHANNEL_TERMINAL, OP_EXIT, exit));
9115
- this.dependencies.send(event(
9116
- CHANNEL_TERMINAL,
9117
- OP_CLOSE,
9118
- { terminal_id: terminalId, reason: CLOSE_REASON_USER_CLOSED }
9119
- ));
9207
+ void this.finishExit(terminalId, stream, exitCode, signal);
9120
9208
  });
9121
9209
  }
9210
+ /**
9211
+ * The shell exited on its own. A shell that skipped its last output sends its last screen first, at
9212
+ * once, so the tabs see how it ended (slice T8). Then `exit` and `close`. With nothing to resync this
9213
+ * runs to the end without yielding, as before.
9214
+ */
9215
+ async finishExit(terminalId, stream, exitCode, signal) {
9216
+ if (this.skipsOutput(stream)) {
9217
+ if (stream.resyncInFlight) await stream.resyncInFlight;
9218
+ if (stream.skipping && !this.suspended) await this.resync(terminalId, stream);
9219
+ }
9220
+ this.forgetStream(terminalId);
9221
+ logger.info("Terminal shell exited", { terminal_id: terminalId, exit_code: exitCode, signal });
9222
+ const exit = signal ? { terminal_id: terminalId, exit_code: null, signal: signalName(signal) } : { terminal_id: terminalId, exit_code: exitCode, signal: null };
9223
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_EXIT, exit));
9224
+ this.dependencies.send(event(
9225
+ CHANNEL_TERMINAL,
9226
+ OP_CLOSE,
9227
+ { terminal_id: terminalId, reason: CLOSE_REASON_USER_CLOSED }
9228
+ ));
9229
+ }
9122
9230
  /**
9123
9231
  * 1 bundle leaves, and the window narrows by what it carried.
9124
9232
  *
@@ -9132,10 +9240,16 @@ var init_terminalHandler = __esm({
9132
9240
  * The mirror is fed here, in the same tick as the seq, and nowhere else. A snapshot then holds
9133
9241
  * exactly the bundles up to its `after_seq`. Fed when the pty is read, a bundle still being cut
9134
9242
  * would be in the screen and drawn a second time when it is sent.
9243
+ *
9244
+ * In skip mode (slice T8) `sendOrSkip` decides instead, and never pauses the pty.
9135
9245
  */
9136
9246
  sendData(terminalId, chunk) {
9137
9247
  const stream = this.streams.get(terminalId);
9138
9248
  if (!stream) return;
9249
+ if (this.skipsOutput(stream)) {
9250
+ this.sendOrSkip(terminalId, stream, chunk);
9251
+ return;
9252
+ }
9139
9253
  if (this.suspended) {
9140
9254
  stream.heldBundles.push(chunk);
9141
9255
  return;
@@ -9151,12 +9265,215 @@ var init_terminalHandler = __esm({
9151
9265
  logger.debug("Terminal window full, reads paused", { terminal_id: terminalId });
9152
9266
  }
9153
9267
  }
9268
+ /** Skip mode applies: `welcome` asked for it, and the shell has a screen to resync with. */
9269
+ skipsOutput(stream) {
9270
+ return this.resyncEnabled && stream.mirror !== null;
9271
+ }
9272
+ /**
9273
+ * Skip mode (slice T8). A resync being serialised holds the bundle. A skipping stream, a socket that is
9274
+ * down, or a closed window skips it. Otherwise it goes out as `data`.
9275
+ */
9276
+ sendOrSkip(terminalId, stream, chunk) {
9277
+ if (stream.resyncInFlight) {
9278
+ this.holdDuringResync(terminalId, stream, chunk);
9279
+ } else if (stream.skipping || this.suspended || !stream.window.isOpen()) {
9280
+ this.skip(terminalId, stream, chunk);
9281
+ } else {
9282
+ this.transmit(terminalId, stream, chunk);
9283
+ }
9284
+ }
9285
+ /**
9286
+ * A bundle cut while a resync is serialised is not in its screen, so it waits and goes out after the
9287
+ * parts. Past the window size the held bundles are skipped instead, and the stream stays skipping.
9288
+ */
9289
+ holdDuringResync(terminalId, stream, chunk) {
9290
+ if (!stream.resyncOverflowed && stream.resyncHeldBytes + chunk.length <= (this.windowBytes ?? 0)) {
9291
+ stream.resyncHeldBundles.push(chunk);
9292
+ stream.resyncHeldBytes += chunk.length;
9293
+ return;
9294
+ }
9295
+ if (!stream.resyncOverflowed) {
9296
+ stream.resyncOverflowed = true;
9297
+ this.skipHeldDuringResync(terminalId, stream);
9298
+ }
9299
+ this.skip(terminalId, stream, chunk);
9300
+ }
9301
+ skipHeldDuringResync(terminalId, stream) {
9302
+ const held = stream.resyncHeldBundles.splice(0);
9303
+ stream.resyncHeldBytes = 0;
9304
+ for (const chunk of held) {
9305
+ this.skip(terminalId, stream, chunk);
9306
+ }
9307
+ }
9308
+ /** Into the screen, not onto the wire. It takes no seq, and the window never counts it. */
9309
+ skip(terminalId, stream, chunk) {
9310
+ stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
9311
+ stream.skippedBytes += chunk.length;
9312
+ if (!stream.skipping) {
9313
+ stream.skipping = true;
9314
+ logger.debug("Terminal output skipped until the tabs catch up", { terminal_id: terminalId });
9315
+ }
9316
+ this.brakeIfMirrorBehind(terminalId, stream);
9317
+ this.reportActivityWhileSkipping(terminalId, stream);
9318
+ }
9319
+ /** As T2's send, minus the pause: with the window closed, the next bundle is skipped instead. */
9320
+ transmit(terminalId, stream, chunk) {
9321
+ stream.sentSeq += 1;
9322
+ stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
9323
+ const data = { terminal_id: terminalId, data: chunk.toString("base64") };
9324
+ this.dependencies.send({ ...event(CHANNEL_TERMINAL, OP_DATA, data), seq: stream.sentSeq });
9325
+ stream.window.recordSent(chunk.length);
9326
+ this.brakeIfMirrorBehind(terminalId, stream);
9327
+ }
9328
+ /** The one pause in skip mode: the mirror's parser fell behind. Local CPU, never the network. */
9329
+ brakeIfMirrorBehind(terminalId, stream) {
9330
+ if (stream.mirrorPaused || !stream.mirror || stream.mirror.backlogBytes <= this.tuning.mirrorHighWaterBytes) return;
9331
+ stream.mirrorPaused = true;
9332
+ stream.session.pause();
9333
+ logger.debug("Terminal reads paused until the screen catches up", { terminal_id: terminalId });
9334
+ }
9335
+ mirrorParsed(terminalId, stream) {
9336
+ if (!stream.mirrorPaused || !stream.mirror || stream.mirror.backlogBytes > this.tuning.mirrorLowWaterBytes) return;
9337
+ stream.mirrorPaused = false;
9338
+ if (this.streams.get(terminalId) !== stream) return;
9339
+ try {
9340
+ stream.session.resume();
9341
+ } catch (err) {
9342
+ logger.debug("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
9343
+ }
9344
+ }
9345
+ /**
9346
+ * Skipped output never reaches the dashboard, so its sweep would see an idle shell. At most every
9347
+ * `ACTIVITY_REPORT_MILLIS` it hears that this one is busy.
9348
+ */
9349
+ reportActivityWhileSkipping(terminalId, stream) {
9350
+ if (this.suspended) return;
9351
+ const nowMillis = this.nowMillis();
9352
+ if (nowMillis - stream.lastActivityReportMillis < this.tuning.activityReportMillis) return;
9353
+ stream.lastActivityReportMillis = nowMillis;
9354
+ const activity = { terminal_id: terminalId, skipped_bytes: stream.skippedBytes };
9355
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_ACTIVITY, activity));
9356
+ }
9357
+ /**
9358
+ * Skip mode after `welcome`. A shell that skipped, or had bytes in flight, resyncs at once: frames in
9359
+ * flight died with the old socket, and the tab's ack of the resync's `after_bytes` stands in for theirs.
9360
+ */
9361
+ resumeSkipping(terminalId, stream, session) {
9362
+ stream.paused = false;
9363
+ for (const chunk of stream.heldBundles.splice(0)) {
9364
+ this.skip(terminalId, stream, chunk);
9365
+ }
9366
+ if (this.pausedBySuspend.has(terminalId) && !stream.mirrorPaused) {
9367
+ try {
9368
+ session.resume();
9369
+ } catch (err) {
9370
+ logger.warn("Terminal resume failed", { terminal_id: terminalId, error: errorName2(err) });
9371
+ }
9372
+ }
9373
+ if (stream.skipping || stream.window.sent > stream.window.acked) {
9374
+ void this.resync(terminalId, stream);
9375
+ }
9376
+ }
9377
+ /** Every sent byte is acked: the tabs have drawn everything they were sent. */
9378
+ static isDrained(stream) {
9379
+ return stream.window.acked >= stream.window.sent;
9380
+ }
9381
+ /**
9382
+ * A skipping stream resyncs once its window has drained, and no sooner than the interval after the
9383
+ * last resync. Not drained yet, it waits for the next `ack`.
9384
+ */
9385
+ scheduleResync(terminalId, stream) {
9386
+ if (!stream.skipping || stream.resyncInFlight || stream.resyncTimer || this.suspended || !_TerminalHandler.isDrained(stream)) return;
9387
+ const waitMillis = stream.lastResyncAtMillis + this.tuning.resyncMinIntervalMillis - this.nowMillis();
9388
+ if (waitMillis <= 0) {
9389
+ void this.resync(terminalId, stream);
9390
+ return;
9391
+ }
9392
+ stream.resyncTimer = setTimeout(() => {
9393
+ stream.resyncTimer = null;
9394
+ if (this.streams.get(terminalId) === stream) this.scheduleResync(terminalId, stream);
9395
+ }, waitMillis);
9396
+ stream.resyncTimer.unref();
9397
+ }
9398
+ /** Starts a resync, or returns the one already being serialised. */
9399
+ resync(terminalId, stream) {
9400
+ if (stream.resyncInFlight) return stream.resyncInFlight;
9401
+ if (stream.resyncTimer) clearTimeout(stream.resyncTimer);
9402
+ stream.resyncTimer = null;
9403
+ stream.resyncInFlight = this.serialiseAndSendResync(terminalId, stream);
9404
+ return stream.resyncInFlight;
9405
+ }
9406
+ /**
9407
+ * The latest screen to every tab (slice T8). `after_seq` and `after_bytes` are read before the mirror
9408
+ * is asked, as for a snapshot, and skipped bytes took neither: the screen holds the output up to
9409
+ * `after_seq` plus everything skipped. Serialised under the window size, so a resync never puts more in
9410
+ * flight than the window allows. Bundles held meanwhile go out after the parts, from `after_seq + 1`.
9411
+ */
9412
+ async serialiseAndSendResync(terminalId, stream) {
9413
+ stream.lastResyncAtMillis = this.nowMillis();
9414
+ stream.resyncOverflowed = false;
9415
+ const afterSeq = stream.sentSeq;
9416
+ const afterBytes = stream.window.sent;
9417
+ const skippedBytes = stream.skippedBytes;
9418
+ stream.skippedBytes = 0;
9419
+ const screen = stream.mirror ? await stream.mirror.snapshot(this.windowBytes) : null;
9420
+ stream.resyncInFlight = null;
9421
+ if (this.streams.get(terminalId) !== stream) return;
9422
+ if (this.suspended) {
9423
+ stream.skippedBytes += skippedBytes;
9424
+ this.skipHeldDuringResync(terminalId, stream);
9425
+ stream.resyncOverflowed = false;
9426
+ return;
9427
+ }
9428
+ if (screen && this.bundleBytes !== void 0) {
9429
+ const resyncId = (0, import_crypto3.randomUUID)();
9430
+ const parts = splitIntoParts(Buffer.from(screen.text, "utf-8"), this.bundleBytes);
9431
+ parts.forEach((part, index) => {
9432
+ const payload = {
9433
+ terminal_id: terminalId,
9434
+ resync_id: resyncId,
9435
+ part: index,
9436
+ last: index === parts.length - 1,
9437
+ after_seq: afterSeq,
9438
+ after_bytes: afterBytes,
9439
+ skipped_bytes: skippedBytes,
9440
+ cols: screen.cols,
9441
+ rows: screen.rows,
9442
+ data: part.toString("base64")
9443
+ };
9444
+ this.dependencies.send(event(CHANNEL_TERMINAL, OP_RESYNC, payload));
9445
+ });
9446
+ logger.debug("Terminal resynced", {
9447
+ terminal_id: terminalId,
9448
+ parts: parts.length,
9449
+ after_seq: afterSeq,
9450
+ skipped_bytes: skippedBytes
9451
+ });
9452
+ } else {
9453
+ logger.warn("Terminal resync dropped: the screen is too large to send", { terminal_id: terminalId });
9454
+ }
9455
+ if (stream.resyncOverflowed) {
9456
+ stream.resyncOverflowed = false;
9457
+ this.scheduleResync(terminalId, stream);
9458
+ return;
9459
+ }
9460
+ stream.skipping = false;
9461
+ const held = stream.resyncHeldBundles.splice(0);
9462
+ stream.resyncHeldBytes = 0;
9463
+ for (const chunk of held) {
9464
+ this.sendOrSkip(terminalId, stream, chunk);
9465
+ }
9466
+ }
9154
9467
  acknowledge(envelope) {
9155
9468
  const parsed = TerminalAckSchema.safeParse(envelope.payload);
9156
9469
  if (!parsed.success) return;
9157
9470
  const stream = this.streams.get(parsed.data.terminal_id);
9158
9471
  if (!stream) return;
9159
9472
  stream.window.recordAck(parsed.data.ack_bytes);
9473
+ if (this.skipsOutput(stream)) {
9474
+ this.scheduleResync(parsed.data.terminal_id, stream);
9475
+ return;
9476
+ }
9160
9477
  if (stream.paused && stream.window.isOpen()) {
9161
9478
  stream.paused = false;
9162
9479
  if (this.suspended) return;
@@ -9284,7 +9601,9 @@ var init_terminalHandler = __esm({
9284
9601
  }
9285
9602
  /** A shell is gone. The context poll stops with the last one, so an idle agent spawns nothing. */
9286
9603
  forgetStream(terminalId) {
9287
- this.streams.get(terminalId)?.mirror?.dispose();
9604
+ const stream = this.streams.get(terminalId);
9605
+ if (stream?.resyncTimer) clearTimeout(stream.resyncTimer);
9606
+ stream?.mirror?.dispose();
9288
9607
  this.streams.delete(terminalId);
9289
9608
  this.contextTracker.forget(terminalId);
9290
9609
  if (this.streams.size === 0) this.stopContextTimer();
@@ -9301,7 +9620,7 @@ var init_terminalHandler = __esm({
9301
9620
  }
9302
9621
  }
9303
9622
  startExpiryTimer() {
9304
- if (this.expiryTimer || this.idleTimeoutMillis === void 0 && this.maxSessionMillis === void 0) {
9623
+ if (this.expiryTimer || this.idleTimeoutMillis === void 0) {
9305
9624
  return;
9306
9625
  }
9307
9626
  this.expiryTimer = setInterval(() => this.expireShells(), EXPIRY_CHECK_MILLIS);
@@ -9674,7 +9993,7 @@ var init_shellAllowlist = __esm({
9674
9993
  // src/devices/deviceAgent.ts
9675
9994
  function buildCapabilities(terminalSupported, screenRestoreSupported = false) {
9676
9995
  if (!terminalSupported) return BASE_CAPABILITIES;
9677
- return screenRestoreSupported ? [...BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT] : [...BASE_CAPABILITIES, CAPABILITY_TERMINAL];
9996
+ return screenRestoreSupported ? [...BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC] : [...BASE_CAPABILITIES, CAPABILITY_TERMINAL];
9678
9997
  }
9679
9998
  function buildDeviceAgentWsUrl(manage) {
9680
9999
  let baseUrl = (manage || DEFAULT_SERVER).trim();
@@ -9729,9 +10048,7 @@ function startDeviceAgent(token, manage, options = {}) {
9729
10048
  const server = manage || DEFAULT_SERVER;
9730
10049
  const reporter = options.reporter ?? printingReporter;
9731
10050
  const stored = readDeviceIdentity();
9732
- if (stored?.device_agent_id && stored.token !== token) {
9733
- reporter.replacingDevice(stored.device_agent_id);
9734
- }
10051
+ const usesStoredToken = stored?.token === token;
9735
10052
  const connection = { send: null, close: null };
9736
10053
  const context = {
9737
10054
  wsUrl: buildDeviceAgentWsUrl(manage),
@@ -9751,7 +10068,9 @@ function startDeviceAgent(token, manage, options = {}) {
9751
10068
  reporter,
9752
10069
  writeIdentity: options.writeIdentity ?? writeDeviceIdentity,
9753
10070
  options,
9754
- state: { stopRequested: false, cancelPendingSleep: null, error: null, welcomed: false }
10071
+ state: { stopRequested: false, cancelPendingSleep: null, error: null, welcomed: false },
10072
+ usesStoredToken,
10073
+ replacedDeviceAgentId: usesStoredToken ? null : stored?.device_agent_id ?? null
9755
10074
  };
9756
10075
  const done = runLoop(context);
9757
10076
  return {
@@ -9908,7 +10227,7 @@ function connectOnce(context) {
9908
10227
  welcome.terminal_window_bytes,
9909
10228
  welcome.max_frame_bytes,
9910
10229
  welcome.terminal_idle_timeout_seconds,
9911
- welcome.terminal_max_session_seconds
10230
+ welcome.terminal_resync
9912
10231
  );
9913
10232
  terminalHandler.resumeAll();
9914
10233
  startHeartbeat(welcome.heartbeat_interval_seconds);
@@ -9948,10 +10267,10 @@ function connectOnce(context) {
9948
10267
  if (res.statusCode === 401) {
9949
10268
  finish(fail(context, {
9950
10269
  code: AGENT_ERROR_UNAUTHORIZED,
9951
- message: "Unauthorized. This device token is not valid. Re-enrol this machine with: pinggy device login"
10270
+ message: context.usesStoredToken ? UNAUTHORIZED_STORED_TOKEN_MESSAGE : UNAUTHORIZED_NEW_TOKEN_MESSAGE
9952
10271
  }));
9953
10272
  } else {
9954
- reporter.warn(`Unexpected HTTP ${res.statusCode}.`);
10273
+ reporter.warn(`The dashboard answered HTTP ${res.statusCode}.`);
9955
10274
  finish("retry");
9956
10275
  }
9957
10276
  ws.close();
@@ -9962,7 +10281,7 @@ function connectOnce(context) {
9962
10281
  });
9963
10282
  ws.on("error", (err) => {
9964
10283
  logger.warn("Device agent socket error", { error: err.message });
9965
- if (!state.stopRequested) {
10284
+ if (!state.stopRequested && !settled) {
9966
10285
  reporter.warn(err.message);
9967
10286
  }
9968
10287
  finish("retry");
@@ -9996,6 +10315,10 @@ function handleFrame(envelope, context, onWelcome) {
9996
10315
  identity.enrolled_at = identity.enrolled_at ?? (/* @__PURE__ */ new Date()).toISOString();
9997
10316
  context.writeIdentity(identity);
9998
10317
  context.state.welcomed = true;
10318
+ if (context.replacedDeviceAgentId) {
10319
+ reporter.replacingDevice(context.replacedDeviceAgentId);
10320
+ context.replacedDeviceAgentId = null;
10321
+ }
9999
10322
  reporter.connected(welcome.data);
10000
10323
  onWelcome(welcome.data);
10001
10324
  return "retry";
@@ -10025,7 +10348,7 @@ function describeDisconnect(reason) {
10025
10348
  message: DISCONNECT_MESSAGES[reason] ?? `Disconnected by the dashboard: ${reason}. Re-enrol this device to continue.`
10026
10349
  };
10027
10350
  }
10028
- var import_ws3, import_os8, CLOSE_CODE_REVOKED, CLOSE_CODE_NORMAL, CLOSE_TIMEOUT_MILLIS, TOKEN_HEADER, DEFAULT_SERVER, ERROR_ALREADY_CONNECTED, AGENT_ERROR_UNAUTHORIZED, AGENT_ERROR_HANDSHAKE_REFUSED, AGENT_ERROR_DISCONNECTED, AGENT_ERROR_NOT_CONNECTED, HANDSHAKE_TIMEOUT_MILLIS, PONG_GRACE_INTERVALS, BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, DISCONNECT_REASON_SHUTDOWN, DISCONNECT_MESSAGES;
10351
+ var import_ws3, import_os8, CLOSE_CODE_REVOKED, CLOSE_CODE_NORMAL, CLOSE_TIMEOUT_MILLIS, TOKEN_HEADER, DEFAULT_SERVER, ERROR_ALREADY_CONNECTED, AGENT_ERROR_UNAUTHORIZED, AGENT_ERROR_HANDSHAKE_REFUSED, AGENT_ERROR_DISCONNECTED, AGENT_ERROR_NOT_CONNECTED, UNAUTHORIZED_STORED_TOKEN_MESSAGE, UNAUTHORIZED_NEW_TOKEN_MESSAGE, HANDSHAKE_TIMEOUT_MILLIS, PONG_GRACE_INTERVALS, BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC, DISCONNECT_REASON_SHUTDOWN, DISCONNECT_MESSAGES;
10029
10352
  var init_deviceAgent = __esm({
10030
10353
  "src/devices/deviceAgent.ts"() {
10031
10354
  "use strict";
@@ -10061,11 +10384,14 @@ var init_deviceAgent = __esm({
10061
10384
  AGENT_ERROR_HANDSHAKE_REFUSED = "handshake_refused";
10062
10385
  AGENT_ERROR_DISCONNECTED = "disconnected";
10063
10386
  AGENT_ERROR_NOT_CONNECTED = "not_connected";
10387
+ 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";
10388
+ UNAUTHORIZED_NEW_TOKEN_MESSAGE = "The dashboard refused this device token. Check the token, or copy the install command from the dashboard again.";
10064
10389
  HANDSHAKE_TIMEOUT_MILLIS = 3e4;
10065
10390
  PONG_GRACE_INTERVALS = 2;
10066
10391
  BASE_CAPABILITIES = ["tunnel", "stats", "tunnel_control", "tunnel_update", "saved_config_update"];
10067
10392
  CAPABILITY_TERMINAL = "terminal";
10068
10393
  CAPABILITY_TERMINAL_SNAPSHOT = "terminal_snapshot";
10394
+ CAPABILITY_TERMINAL_RESYNC = "terminal_resync";
10069
10395
  DISCONNECT_REASON_SHUTDOWN = "shutdown";
10070
10396
  DISCONNECT_MESSAGES = {
10071
10397
  revoked: "Credential revoked. Copy the new install command from the dashboard and run it to reconnect.",
@@ -10201,13 +10527,13 @@ function createTerminalPrompter(input, output) {
10201
10527
  async ask(question, signal) {
10202
10528
  const readline = (0, import_promises.createInterface)({ input, output, terminal: true });
10203
10529
  try {
10204
- return await readline.question(question, signal ? { signal } : {});
10530
+ return await readline.question(marked(question), signal ? { signal } : {});
10205
10531
  } finally {
10206
10532
  readline.close();
10207
10533
  }
10208
10534
  },
10209
10535
  async askHidden(question, signal) {
10210
- output.write(question);
10536
+ output.write(marked(question));
10211
10537
  const readline = (0, import_promises.createInterface)({ input, output: discardingOutput(), terminal: true });
10212
10538
  try {
10213
10539
  const answer = await readline.question("", signal ? { signal } : {});
@@ -10222,6 +10548,9 @@ function createTerminalPrompter(input, output) {
10222
10548
  function isInteractiveTerminal() {
10223
10549
  return process.stdin.isTTY === true;
10224
10550
  }
10551
+ function marked(question) {
10552
+ return `${QUESTION_MARKER} ${question}`;
10553
+ }
10225
10554
  function discardingOutput() {
10226
10555
  return new import_stream.Writable({
10227
10556
  write(_chunk, _encoding, callback) {
@@ -10229,13 +10558,15 @@ function discardingOutput() {
10229
10558
  }
10230
10559
  });
10231
10560
  }
10232
- var import_promises, import_stream, terminalPrompter;
10561
+ var import_picocolors7, import_promises, import_stream, QUESTION_MARKER, terminalPrompter;
10233
10562
  var init_prompts = __esm({
10234
10563
  "src/devices/login/prompts.ts"() {
10235
10564
  "use strict";
10236
10565
  init_cjs_shims();
10566
+ import_picocolors7 = __toESM(require("picocolors"), 1);
10237
10567
  import_promises = require("readline/promises");
10238
10568
  import_stream = require("stream");
10569
+ QUESTION_MARKER = import_picocolors7.default.cyan(import_picocolors7.default.bold("\u2192"));
10239
10570
  terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
10240
10571
  }
10241
10572
  });
@@ -10262,6 +10593,20 @@ function machineDeviceLoginDependencies() {
10262
10593
  };
10263
10594
  }
10264
10595
  async function runDeviceLogin(options, dependencies = machineDeviceLoginDependencies()) {
10596
+ try {
10597
+ return await signInAndRunAgent(options, dependencies);
10598
+ } catch (err) {
10599
+ if (!isCtrlCAtPrompt(err)) {
10600
+ throw err;
10601
+ }
10602
+ dependencies.print(import_picocolors8.default.yellow("Sign-in cancelled."));
10603
+ return EXIT_FAILED;
10604
+ }
10605
+ }
10606
+ function isCtrlCAtPrompt(err) {
10607
+ return err instanceof Error && err.name === ABORT_ERROR_NAME;
10608
+ }
10609
+ async function signInAndRunAgent(options, dependencies) {
10265
10610
  if (!dependencies.isInteractive()) {
10266
10611
  dependencies.printError(NO_TERMINAL_MESSAGE);
10267
10612
  return EXIT_FAILED;
@@ -10273,7 +10618,7 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
10273
10618
  `This machine is already enrolled as ${stored.device_agent_id ?? "a device"} on ${stored.server}. Add it again as a new device? [y/N] `
10274
10619
  );
10275
10620
  if (!YES_ANSWER.test(answer.trim())) {
10276
- return await dependencies.runAgent(stored.token, manage) ?? EXIT_OK;
10621
+ return await dependencies.runAgent(stored.token, manage, false) ?? EXIT_OK;
10277
10622
  }
10278
10623
  }
10279
10624
  const email = (await dependencies.prompter.ask("Email: ")).trim();
@@ -10292,13 +10637,12 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
10292
10637
  ...options.name ? { name: options.name } : {}
10293
10638
  });
10294
10639
  linkMinutes = Math.round(started.expires_in_seconds / SECONDS_PER_MINUTE);
10295
- dependencies.print(`We sent a 6-digit code to ${email}. It works for ${linkMinutes} minutes.`);
10296
- if (started.match_code) {
10297
- dependencies.print("Type it below, or click Approve sign-in in the email.");
10298
- 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.`);
10299
- }
10640
+ printCodeSent(email, started.match_code, dependencies);
10300
10641
  approved = await waitForApproval(api, started.device_code, started.poll_interval_seconds, dependencies);
10301
10642
  } catch (err) {
10643
+ if (isCtrlCAtPrompt(err)) {
10644
+ throw err;
10645
+ }
10302
10646
  dependencies.printError(messageOf(err, manage));
10303
10647
  return EXIT_FAILED;
10304
10648
  }
@@ -10312,9 +10656,19 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
10312
10656
  server: manage || DEFAULT_SERVER2,
10313
10657
  enrolled_at: null
10314
10658
  });
10315
- dependencies.print(`Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
10659
+ dependencies.print(`${RESULT_MARKER} Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
10316
10660
  await printDeviceLink(approved, linkMinutes, dependencies);
10317
- return await dependencies.runAgent(approved.token, manage) ?? EXIT_OK;
10661
+ return await dependencies.runAgent(approved.token, manage, true) ?? EXIT_OK;
10662
+ }
10663
+ function printCodeSent(email, matchCode, dependencies) {
10664
+ dependencies.print("");
10665
+ if (matchCode) {
10666
+ dependencies.print(`Device Code: ${import_picocolors8.default.bold(import_picocolors8.default.yellow(matchCode))}`);
10667
+ dependencies.print("");
10668
+ }
10669
+ dependencies.print(`We have sent a 6-digit code to ${email}.`);
10670
+ dependencies.print(matchCode ? "Enter the code below or click the approve button in the email." : "Enter the code below.");
10671
+ dependencies.print("");
10318
10672
  }
10319
10673
  async function waitForApproval(api, deviceCode, pollIntervalSeconds, dependencies) {
10320
10674
  const controller = new AbortController();
@@ -10362,7 +10716,7 @@ async function typeTheCode(api, deviceCode, signal, prompt, dependencies) {
10362
10716
  }
10363
10717
  }
10364
10718
  if (answer.status === LoginStatus.Pending) {
10365
- dependencies.print("Approved from the email link. Waiting for the dashboard to finish.");
10719
+ dependencies.print(import_picocolors8.default.cyanBright("Approved from the email link. Waiting for the dashboard to finish..."));
10366
10720
  return waitUntilAborted(signal);
10367
10721
  }
10368
10722
  if (answer.status !== LoginStatus.Approved) {
@@ -10406,16 +10760,17 @@ async function pollUntilApproved(api, deviceCode, intervalMillis, signal, depend
10406
10760
  }
10407
10761
  async function printDeviceLink(approved, linkMinutes, dependencies) {
10408
10762
  let link;
10763
+ let label;
10409
10764
  if (approved.open_url) {
10410
10765
  link = approved.open_url;
10411
- dependencies.print(`Open the device in a browser. This link signs you in once, within ${linkMinutes} minutes:`);
10766
+ label = `Open the device in a browser. This link signs you in once, within ${linkMinutes} minutes:`;
10412
10767
  } else if (approved.device_url) {
10413
10768
  link = approved.device_url;
10414
- dependencies.print("Open the device in a browser:");
10769
+ label = "Open the device in a browser:";
10415
10770
  } else {
10416
10771
  return;
10417
10772
  }
10418
- dependencies.print(` ${link}`);
10773
+ printDeviceUrl((message) => dependencies.print(message), label, link);
10419
10774
  try {
10420
10775
  dependencies.print(await dependencies.renderQr(link));
10421
10776
  } catch {
@@ -10457,16 +10812,18 @@ function sleepUnlessAborted(millis, signal) {
10457
10812
  signal.addEventListener("abort", onAbort, { once: true });
10458
10813
  });
10459
10814
  }
10460
- var import_os9, EXIT_OK, EXIT_FAILED, DEFAULT_SERVER2, YES_ANSWER, SECONDS_PER_MINUTE, MILLIS_PER_SECOND2, FIRST_SERVER_ERROR_STATUS, NO_TERMINAL_MESSAGE;
10815
+ var import_os9, import_picocolors8, EXIT_OK, EXIT_FAILED, DEFAULT_SERVER2, YES_ANSWER, RESULT_MARKER, SECONDS_PER_MINUTE, MILLIS_PER_SECOND2, FIRST_SERVER_ERROR_STATUS, NO_TERMINAL_MESSAGE, ABORT_ERROR_NAME;
10461
10816
  var init_deviceLogin = __esm({
10462
10817
  "src/devices/login/deviceLogin.ts"() {
10463
10818
  "use strict";
10464
10819
  init_cjs_shims();
10465
10820
  import_os9 = __toESM(require("os"), 1);
10821
+ import_picocolors8 = __toESM(require("picocolors"), 1);
10466
10822
  init_printer();
10467
10823
  init_util();
10468
10824
  init_qrCodeGenerator();
10469
10825
  init_deviceAgent();
10826
+ init_deviceAgentReporter();
10470
10827
  init_deviceIdentity();
10471
10828
  init_loginApi();
10472
10829
  init_login_schema();
@@ -10475,10 +10832,12 @@ var init_deviceLogin = __esm({
10475
10832
  EXIT_FAILED = 1;
10476
10833
  DEFAULT_SERVER2 = "dashboard.pinggy.io";
10477
10834
  YES_ANSWER = /^y(es)?$/i;
10835
+ RESULT_MARKER = import_picocolors8.default.green(import_picocolors8.default.bold("\u2192"));
10478
10836
  SECONDS_PER_MINUTE = 60;
10479
10837
  MILLIS_PER_SECOND2 = 1e3;
10480
10838
  FIRST_SERVER_ERROR_STATUS = 500;
10481
10839
  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>";
10840
+ ABORT_ERROR_NAME = "AbortError";
10482
10841
  }
10483
10842
  });
10484
10843
 
@@ -10527,7 +10886,7 @@ async function readBackgroundAgent(dependencies) {
10527
10886
  return null;
10528
10887
  }
10529
10888
  }
10530
- async function startAgentInBackground(target, dependencies) {
10889
+ async function startAgentInBackground(target, dependencies, options = {}) {
10531
10890
  if (differsFromStored(target, dependencies.readIdentity())) {
10532
10891
  const verified = await dependencies.verify(target.token, target.manage);
10533
10892
  if (verified.error || !verified.welcomed) {
@@ -10535,7 +10894,6 @@ async function startAgentInBackground(target, dependencies) {
10535
10894
  return EXIT_FAILED;
10536
10895
  }
10537
10896
  }
10538
- dependencies.print("Starting the device agent in the background.");
10539
10897
  let daemon;
10540
10898
  try {
10541
10899
  daemon = await dependencies.ensureDaemon();
@@ -10554,12 +10912,14 @@ async function startAgentInBackground(target, dependencies) {
10554
10912
  dependencies.printError(daemonFailureMessage(err, daemon));
10555
10913
  return EXIT_FAILED;
10556
10914
  }
10557
- return waitUntilConnected(client, daemon, dependencies);
10915
+ printManageCommands(dependencies);
10916
+ dependencies.print(import_picocolors9.default.cyanBright("Starting the device agent in the background..."));
10917
+ return waitUntilConnected(client, daemon, options, dependencies);
10558
10918
  }
10559
10919
  async function stopAgentInBackground(dependencies) {
10560
10920
  const reading = await readBackgroundAgent(dependencies);
10561
10921
  if (!reading || !isAgentRunning(reading.status)) {
10562
- dependencies.print("No device agent is running in the background.");
10922
+ dependencies.print(import_picocolors9.default.yellow("No device agent is running in the background."));
10563
10923
  return EXIT_OK;
10564
10924
  }
10565
10925
  if (!await stopReadAgent(reading, dependencies)) {
@@ -10633,7 +10993,16 @@ function daemonFailureMessage(err, daemon) {
10633
10993
  }
10634
10994
  return `Could not reach the daemon: ${errorMessage(err)}`;
10635
10995
  }
10636
- async function waitUntilConnected(client, daemon, dependencies) {
10996
+ function printManageCommands(dependencies) {
10997
+ const commandWidth = Math.max(...MANAGE_COMMANDS.map(([command]) => command.length));
10998
+ dependencies.print("");
10999
+ dependencies.print("Manage this device:");
11000
+ for (const [command, purpose] of MANAGE_COMMANDS) {
11001
+ dependencies.print(` ${import_picocolors9.default.cyan(command.padEnd(commandWidth))} ${purpose}`);
11002
+ }
11003
+ dependencies.print("");
11004
+ }
11005
+ async function waitUntilConnected(client, daemon, options, dependencies) {
10637
11006
  const deadline = dependencies.now() + CONNECT_WAIT_MILLIS;
10638
11007
  for (; ; ) {
10639
11008
  let status;
@@ -10644,7 +11013,7 @@ async function waitUntilConnected(client, daemon, dependencies) {
10644
11013
  return EXIT_FAILED;
10645
11014
  }
10646
11015
  if (status.state === DeviceAgentState.Connected) {
10647
- printRunning(status, daemon, dependencies);
11016
+ printRunning(status, daemon, options, dependencies);
10648
11017
  return EXIT_OK;
10649
11018
  }
10650
11019
  if (status.state === DeviceAgentState.Stopped) {
@@ -10658,26 +11027,25 @@ async function waitUntilConnected(client, daemon, dependencies) {
10658
11027
  await dependencies.sleep(POLL_INTERVAL_MILLIS);
10659
11028
  }
10660
11029
  }
10661
- function printRunning(status, daemon, dependencies) {
11030
+ function printRunning(status, daemon, options, dependencies) {
10662
11031
  dependencies.printSuccess(`Running in the background as device ${status.deviceAgentId}`);
10663
- if (status.email) {
11032
+ if (status.email && !options.signInShown) {
10664
11033
  dependencies.print(`Signed in as ${status.email}`);
10665
11034
  }
10666
- if (status.deviceUrl) {
10667
- dependencies.print("Open the device in a browser:");
10668
- dependencies.print(` ${status.deviceUrl}`);
11035
+ if (status.deviceUrl && !options.signInShown) {
11036
+ printDeviceUrl((message) => dependencies.print(message), "Open the device in a browser:", status.deviceUrl);
10669
11037
  }
10670
11038
  if (daemon.host === DaemonHost.APP) {
10671
- dependencies.print("It runs inside the Pinggy app, and stops when the app quits.");
11039
+ dependencies.print(import_picocolors9.default.gray("It runs inside the Pinggy app, and stops when the app quits."));
10672
11040
  }
10673
- dependencies.print(`Logs: ${dependencies.daemonLogPath()}`);
10674
- dependencies.print("Stop it with: pinggy device stop");
11041
+ dependencies.print(import_picocolors9.default.gray(`Logs: ${dependencies.daemonLogPath()}`));
10675
11042
  }
10676
- var POLL_INTERVAL_MILLIS, CONNECT_WAIT_MILLIS, verifyingReporter;
11043
+ var import_picocolors9, POLL_INTERVAL_MILLIS, CONNECT_WAIT_MILLIS, MANAGE_COMMANDS, verifyingReporter;
10677
11044
  var init_backgroundAgent = __esm({
10678
11045
  "src/devices/backgroundAgent.ts"() {
10679
11046
  "use strict";
10680
11047
  init_cjs_shims();
11048
+ import_picocolors9 = __toESM(require("picocolors"), 1);
10681
11049
  init_logger();
10682
11050
  init_printer();
10683
11051
  init_configDir();
@@ -10692,6 +11060,12 @@ var init_backgroundAgent = __esm({
10692
11060
  init_deviceLogin();
10693
11061
  POLL_INTERVAL_MILLIS = 500;
10694
11062
  CONNECT_WAIT_MILLIS = 15e3;
11063
+ MANAGE_COMMANDS = [
11064
+ ["pinggy device status", "Show this device, and whether its agent runs"],
11065
+ ["pinggy device stop", "Stop the agent. The device shows offline"],
11066
+ ["pinggy device connect", "Start the agent again, after a stop or a reboot"],
11067
+ ["pinggy device remove", "Forget this machine's credential"]
11068
+ ];
10695
11069
  verifyingReporter = {
10696
11070
  connecting: () => void 0,
10697
11071
  connected: () => void 0,
@@ -10740,17 +11114,17 @@ async function handleDaemonStart() {
10740
11114
  printer_default.error(ipcMismatchMessage(info));
10741
11115
  process.exit(1);
10742
11116
  }
10743
- printer_default.print(import_picocolors6.default.yellow(`Daemon already running (PID ${info.pid}, port ${info.port}). Use: pinggy daemon status for details.`));
11117
+ printer_default.print(import_picocolors10.default.yellow(`Daemon already running (PID ${info.pid}, port ${info.port}). Use: pinggy daemon status for details.`));
10744
11118
  return;
10745
11119
  }
10746
11120
  const autoConfigs = getAutoStartConfigs();
10747
11121
  if (autoConfigs.length > 0) {
10748
- printer_default.print(import_picocolors6.default.cyanBright(`Starting daemon with ${autoConfigs.length} auto-start tunnel(s):`));
11122
+ printer_default.print(import_picocolors10.default.cyanBright(`Starting daemon with ${autoConfigs.length} auto-start tunnel(s):`));
10749
11123
  for (const c of autoConfigs) {
10750
- printer_default.print(` ${import_picocolors6.default.bold(c.name)} (${c.configId.slice(0, 8)})`);
11124
+ printer_default.print(` ${import_picocolors10.default.bold(c.name)} (${c.configId.slice(0, 8)})`);
10751
11125
  }
10752
11126
  } else {
10753
- printer_default.print(import_picocolors6.default.cyanBright("Starting daemon..."));
11127
+ printer_default.print(import_picocolors10.default.cyanBright("Starting daemon..."));
10754
11128
  }
10755
11129
  try {
10756
11130
  const info2 = await startDaemon();
@@ -10762,7 +11136,7 @@ async function handleDaemonStart() {
10762
11136
  }
10763
11137
  async function handleDaemonStop() {
10764
11138
  if (!isDaemonRunning()) {
10765
- printer_default.print(import_picocolors6.default.yellow("No daemon is running."));
11139
+ printer_default.print(import_picocolors10.default.yellow("No daemon is running."));
10766
11140
  return;
10767
11141
  }
10768
11142
  const agent = await readBackgroundAgent(machineBackgroundAgentDependencies());
@@ -10773,7 +11147,7 @@ async function handleDaemonStop() {
10773
11147
  printer_default.print("The background device agent stopped too. The device shows offline in the dashboard.");
10774
11148
  }
10775
11149
  } else if (result.reason === DaemonHost.APP) {
10776
- printer_default.print(import_picocolors6.default.yellow("The Pinggy daemon is running inside the Pinggy desktop app. Please quit the Pinggy app to stop it."));
11150
+ printer_default.print(import_picocolors10.default.yellow("The Pinggy daemon is running inside the Pinggy desktop app. Please quit the Pinggy app to stop it."));
10777
11151
  } else {
10778
11152
  printer_default.error(result.error);
10779
11153
  }
@@ -10781,7 +11155,7 @@ async function handleDaemonStop() {
10781
11155
  async function handleDaemonStatus() {
10782
11156
  const info = getDaemonInfo();
10783
11157
  if (!info) {
10784
- printer_default.print(import_picocolors6.default.yellow("No daemon is running. Start with: pinggy daemon start"));
11158
+ printer_default.print(import_picocolors10.default.yellow("No daemon is running. Start with: pinggy daemon start"));
10785
11159
  return;
10786
11160
  }
10787
11161
  const uptimeSec = Math.floor((Date.now() - new Date(info.startedAt).getTime()) / 1e3);
@@ -10789,7 +11163,7 @@ async function handleDaemonStatus() {
10789
11163
  const m = Math.floor(uptimeSec % 3600 / 60);
10790
11164
  const s = uptimeSec % 60;
10791
11165
  const uptimeStr = h > 0 ? `${h}h ${m}m ${s}s` : m > 0 ? `${m}m ${s}s` : `${s}s`;
10792
- printer_default.print(import_picocolors6.default.cyanBright("Daemon Status"));
11166
+ printer_default.print(import_picocolors10.default.cyanBright("Daemon Status"));
10793
11167
  printer_default.print(` PID: ${info.pid}`);
10794
11168
  printer_default.print(` Port: ${info.port}`);
10795
11169
  printer_default.print(` Started: ${info.startedAt}`);
@@ -10797,20 +11171,20 @@ async function handleDaemonStatus() {
10797
11171
  printer_default.print(` Host: ${info.host === DaemonHost.APP ? "Pinggy app (in-process)" : "standalone (CLI)"}`);
10798
11172
  printer_default.print(` IPC: v${daemonIpcVersion(info)}`);
10799
11173
  if (!isIpcCompatible(info)) {
10800
- printer_default.print(import_picocolors6.default.yellow(` Warning: ${ipcMismatchMessage(info)}`));
11174
+ printer_default.print(import_picocolors10.default.yellow(` Warning: ${ipcMismatchMessage(info)}`));
10801
11175
  }
10802
11176
  const agent = await readBackgroundAgent(machineBackgroundAgentDependencies());
10803
11177
  if (agent) {
10804
11178
  printer_default.print(` Device: ${describeAgentForDaemonStatus(agent.status)}`);
10805
11179
  }
10806
11180
  }
10807
- var import_picocolors6;
11181
+ var import_picocolors10;
10808
11182
  var init_daemonCommandsHandler = __esm({
10809
11183
  "src/cli/subcommand/handlers/daemonCommandsHandler.ts"() {
10810
11184
  "use strict";
10811
11185
  init_cjs_shims();
10812
11186
  init_printer();
10813
- import_picocolors6 = __toESM(require("picocolors"), 1);
11187
+ import_picocolors10 = __toESM(require("picocolors"), 1);
10814
11188
  init_configStore();
10815
11189
  init_daemonManager();
10816
11190
  init_ipcRoutes();
@@ -10841,17 +11215,17 @@ async function handlePs() {
10841
11215
  return;
10842
11216
  }
10843
11217
  const header = `${pad("ID", 14)} ${pad("NAME", 16)} ${pad("STATUS", 10)} ${pad("LOCAL", 20)} URL`;
10844
- printer_default.print(import_picocolors7.default.gray(header));
10845
- printer_default.print(import_picocolors7.default.gray("\u2500".repeat(90)));
11218
+ printer_default.print(import_picocolors11.default.gray(header));
11219
+ printer_default.print(import_picocolors11.default.gray("\u2500".repeat(90)));
10846
11220
  for (const t of tunnels) {
10847
11221
  const id = t.tunnelid.slice(0, 12);
10848
11222
  const name = t.tunnelconfig?.name || "-";
10849
11223
  const status = t.status.state;
10850
11224
  const local = getLocalAddress(t.tunnelconfig);
10851
11225
  const url = t.remoteurls?.[0] || "-";
10852
- const statusColor = status === "running" ? import_picocolors7.default.green : status === "starting" ? import_picocolors7.default.yellow : import_picocolors7.default.red;
11226
+ const statusColor = status === "running" ? import_picocolors11.default.green : status === "starting" ? import_picocolors11.default.yellow : import_picocolors11.default.red;
10853
11227
  printer_default.print(
10854
- `${import_picocolors7.default.cyan(pad(id, 14))} ${pad(name, 16)} ${statusColor(pad(status, 10))} ${pad(local, 20)} ${import_picocolors7.default.magentaBright(url)}`
11228
+ `${import_picocolors11.default.cyan(pad(id, 14))} ${pad(name, 16)} ${statusColor(pad(status, 10))} ${pad(local, 20)} ${import_picocolors11.default.magentaBright(url)}`
10855
11229
  );
10856
11230
  }
10857
11231
  } catch (err) {
@@ -10863,7 +11237,7 @@ async function handlePs() {
10863
11237
  function pad(str, len) {
10864
11238
  return str.length >= len ? str.slice(0, len) : str + " ".repeat(len - str.length);
10865
11239
  }
10866
- var import_picocolors7;
11240
+ var import_picocolors11;
10867
11241
  var init_psCommand = __esm({
10868
11242
  "src/cli/subcommand/handlers/psCommand.ts"() {
10869
11243
  "use strict";
@@ -10872,7 +11246,7 @@ var init_psCommand = __esm({
10872
11246
  init_types();
10873
11247
  init_printer();
10874
11248
  init_util();
10875
- import_picocolors7 = __toESM(require("picocolors"), 1);
11249
+ import_picocolors11 = __toESM(require("picocolors"), 1);
10876
11250
  }
10877
11251
  });
10878
11252
 
@@ -10973,14 +11347,14 @@ async function handleAttach(args) {
10973
11347
  }
10974
11348
  const tunnelId = match.tunnelid;
10975
11349
  const name = match.tunnelconfig?.name || tunnelId.slice(0, 12);
10976
- printer_default.print(import_picocolors8.default.cyanBright(`Attaching to tunnel "${name}"...`));
11350
+ printer_default.print(import_picocolors12.default.cyanBright(`Attaching to tunnel "${name}"...`));
10977
11351
  const attachMode = match.mode ?? "detached";
10978
11352
  await client.attach(tunnelId, attachMode);
10979
11353
  const urls = match.remoteurls || [];
10980
11354
  if (urls.length > 0) {
10981
11355
  printer_default.print("");
10982
11356
  for (const url of urls) {
10983
- printer_default.print(" " + import_picocolors8.default.magentaBright(url));
11357
+ printer_default.print(" " + import_picocolors12.default.magentaBright(url));
10984
11358
  }
10985
11359
  printer_default.print("");
10986
11360
  }
@@ -10999,12 +11373,12 @@ async function handleAttach(args) {
10999
11373
  client.close();
11000
11374
  }
11001
11375
  }
11002
- var import_picocolors8;
11376
+ var import_picocolors12;
11003
11377
  var init_attachCommand = __esm({
11004
11378
  "src/cli/subcommand/handlers/attachCommand.ts"() {
11005
11379
  "use strict";
11006
11380
  init_cjs_shims();
11007
- import_picocolors8 = __toESM(require("picocolors"), 1);
11381
+ import_picocolors12 = __toESM(require("picocolors"), 1);
11008
11382
  init_printer();
11009
11383
  init_tunnelClient();
11010
11384
  init_types();
@@ -11288,7 +11662,11 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
11288
11662
  const flagArgs = args.slice(1);
11289
11663
  const { values } = parseCliArgs(cliOptions, flagArgs);
11290
11664
  configureLogger(values);
11291
- const inBackground = Boolean(values.b);
11665
+ if (values.b && values.foreground) {
11666
+ printer_default.error("-b and --foreground contradict each other. The agent runs in the background unless --foreground is given.");
11667
+ process.exit(1);
11668
+ }
11669
+ const inBackground = !values.foreground;
11292
11670
  switch (verb) {
11293
11671
  case DeviceVerb.Login:
11294
11672
  exitUnlessOk(await handleDeviceLogin(values.manage, values.name, inBackground, background));
@@ -11349,7 +11727,7 @@ async function handleDeviceLogin(manage, name, inBackground, background) {
11349
11727
  }
11350
11728
  return runDeviceLogin({ manage, name }, {
11351
11729
  ...machineDeviceLoginDependencies(),
11352
- runAgent: (token, agentManage) => startAgentInBackground({ token, manage: agentManage }, background)
11730
+ runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
11353
11731
  });
11354
11732
  }
11355
11733
  async function handleDeviceConnect(flagToken, environmentToken, manage, inBackground, background) {
@@ -11368,13 +11746,13 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
11368
11746
  async function handleDeviceStatus(background) {
11369
11747
  const identity = background.readIdentity();
11370
11748
  if (!identity) {
11371
- printer_default.print("This machine is not enrolled. Run: pinggy device login");
11749
+ printer_default.print(import_picocolors13.default.yellow("This machine is not enrolled. Run: pinggy device login"));
11372
11750
  return;
11373
11751
  }
11374
- printer_default.print(` Device id ${identity.device_agent_id ?? import_picocolors9.default.gray("not yet assigned")}`);
11752
+ printer_default.print(` Device id ${identity.device_agent_id ?? import_picocolors13.default.gray("not yet assigned")}`);
11375
11753
  printer_default.print(` Server ${identity.server}`);
11376
11754
  printer_default.print(` Token ${maskToken(identity.token)}`);
11377
- printer_default.print(` Enrolled ${identity.enrolled_at ?? import_picocolors9.default.gray("never")}`);
11755
+ printer_default.print(` Enrolled ${identity.enrolled_at ?? import_picocolors13.default.gray("never")}`);
11378
11756
  await printBackgroundStatus(background);
11379
11757
  }
11380
11758
  async function handleDeviceRemove(background) {
@@ -11383,18 +11761,18 @@ async function handleDeviceRemove(background) {
11383
11761
  }
11384
11762
  if (clearDeviceIdentity()) {
11385
11763
  printer_default.success("Local device credential removed.");
11386
- printer_default.print(import_picocolors9.default.gray("The device still exists in the dashboard. Delete it there to revoke it."));
11764
+ printer_default.print(import_picocolors13.default.gray("The device still exists in the dashboard. Delete it there to revoke it."));
11387
11765
  } else {
11388
- printer_default.print("This machine is not enrolled.");
11766
+ printer_default.print(import_picocolors13.default.yellow("This machine is not enrolled."));
11389
11767
  }
11390
11768
  return EXIT_OK;
11391
11769
  }
11392
- var import_picocolors9, DeviceVerb, DEVICE_AGENT_TOKEN_VARIABLE;
11770
+ var import_picocolors13, DeviceVerb, DEVICE_AGENT_TOKEN_VARIABLE;
11393
11771
  var init_deviceCommand = __esm({
11394
11772
  "src/cli/subcommand/handlers/deviceCommand.ts"() {
11395
11773
  "use strict";
11396
11774
  init_cjs_shims();
11397
- import_picocolors9 = __toESM(require("picocolors"), 1);
11775
+ import_picocolors13 = __toESM(require("picocolors"), 1);
11398
11776
  init_options();
11399
11777
  init_parseArgs();
11400
11778
  init_logger();
@@ -13866,7 +14244,7 @@ var init_tunnelClient = __esm({
13866
14244
  this.assertClient();
13867
14245
  await this.ipc.restartTunnel(tunnelId);
13868
14246
  }
13869
- // Device agent (`pinggy device connect -b`). The daemon reads the token and the server from
14247
+ // Device agent (`pinggy device connect`). The daemon reads the token and the server from
13870
14248
  // device.json, so none of these takes either.
13871
14249
  async getDeviceAgentStatus() {
13872
14250
  this.assertClient();